Compare commits

...

371 Commits

Author SHA1 Message Date
Tom Finegan
82ac5fcdc8 Remove RELEASE.TXT.
It's stale and redundant.

Change-Id: I91c3a1e0f0c717c8f1b3ae30d648127cb2f3590c
2015-12-09 08:12:34 -08:00
Tom Finegan
852e1733a8 webm2pes: Split super frames and packetize large frames.
- PES depacketizers don't want anything but simple encoded frames.
- Large in this case means frame size + size of PES header
  is > UINT16_MAX.

Change-Id: Ifb76caaa97a0dcf3600228a0cbc4d4f2533027a7
2015-12-07 20:14:53 -08:00
Tom Finegan
faf85c227d webm2pes: Refactor header/optional header writing.
- Move class declarations to webm2pes.h.
- Add some visual demarcation between the method definitions for each
  class in webm2pes.cc.
- Reorganize the output code to make further development simpler.
- Also, clang format noise.

Change-Id: Id6d156e1f255cefe30a62784a3eadde6b93ae614
2015-12-03 14:42:37 -08:00
Tom Finegan
7c19266548 Add Webm2Pes.
Add tool for converting WebM VPx streams to Packetized Elementary
Streams.

Change-Id: I599de053df5423a803a3ea450876c52c3e400034
2015-12-02 11:42:24 -08:00
Tom Finegan
01fdee435c mkvmuxer: Disallow AddTrack() after Tracks element is output.
BUG=https://code.google.com/p/webm/issues/detail?id=1083

Change-Id: I6a603337ba5fea1333f3f1c2595f9b87b148c427
2015-10-21 09:07:00 -07:00
James Zern
1ad314e297 mkvparser: EBMLHeader::Parse: remove dead init
Change-Id: Ie06b44c3b7fd948d11aa86ae521a196ea668312b
2015-10-13 16:10:55 -07:00
James Zern
476366249e mkvparser: fix type warnings
Change-Id: Ia77a9a4e694986ece4c2e0f86f2857f320432f48
2015-09-11 18:56:09 -07:00
James Zern
267f71c76e mkvparser: SafeArrayAlloc fix type warning
num_bytes has been validated so it's safe to cast to size_t for use with
new

Change-Id: If1a6c5521dd6fbcb7e30f434b81daa3b26bd0386
2015-09-11 18:56:09 -07:00
James Zern
f1a99d5f25 mkvparser: s/LONG_LONG_MAX/LLONG_MAX/ for compatibility
Change-Id: If3b80bfd08f02ec9cba0be223ff95991564f6fd7
2015-09-11 18:56:09 -07:00
James Zern
bff1aa512d mkvparser: add msvc compatibility for isnan/isinf
fixes build errors related to these functions on visual studio prior to
2013

Change-Id: I8272f9065195e5447055aad7d0f899afa0294ea9
2015-09-11 18:55:03 -07:00
Vignesh Venkatasubramanian
a58c32339e mkvmuxer: Add codec id constant for VP10.
This was added in the libvpx's snapshot here:
https://chromium-review.googlesource.com/#/c/293861

Change-Id: I58b9635c62535ecdb0dff14dc294466262590861
2015-09-10 12:10:01 -07:00
Tom Finegan
714f3c4e4f mkvparser: validate results in EBMLHeader::Parse.
Return an error when DocType, DocTypeReadVersion, DocTypeVersion
EBMLMaxIDLength or EBMLMaxSizeLength are invalid or cannot be
handled by mkvparser.

Update samples to respect the return value from EBMLHeader::Parse.

BUG=https://code.google.com/p/webm/issues/detail?id=1057

Change-Id: I9337f13c1d5fa366b1101e48fe6bc46eb5b2ee97
2015-09-05 08:06:45 -07:00
Tom Finegan
cec98d4110 mkvparser: Correct the ReadID implementation.
Return real, known MKV IDs when reading them. Previously
IDs were treated as EBML integer values. This was both
wrong and confusing. Wrong because this results in values
that are not part of the Matroska spec, and confusing
because the code was littered with magic numbers
representing the invented IDs.

Currently uses mkvmuxer::MkvId; A TODO in the code addresses this.
Additional IDs have been added that were not previously in the enum:
mkvparser parses many elements that we do not write in the muxer.

Change-Id: I5db2b4d70d786d5239d2e2a0cbff4e7f8d844aa6
2015-09-04 09:55:59 -07:00
Tom Finegan
eb36ae4840 Merge changes I029a268e,Ia272b150,I5c4d1bbc,Ia47a2478,I3a2e2226
* changes:
  mkvparser: Cluster::Parse clean up.
  mkvparser: Disallow EBML IDs equal to 0.
  mkvparser: Cluster::Load clean up.
  mkvparser: Segment::Load asserts to error checks.
  mkvparser: Segment::PreloadCluster asserts to error checks.
2015-08-31 22:48:36 +00:00
Tom Finegan
229f49347d Merge "mkvparser: Segment::AppendCluster asserts to error checks." 2015-08-31 22:10:13 +00:00
Tom Finegan
287faf95f6 Merge "mkvparser: Segment::DoLoadClusterUnknownSize asserts to error checks." 2015-08-31 22:09:51 +00:00
Tom Finegan
1a87b59032 Merge "mkvparser: Segment assert clean up." 2015-08-31 22:09:37 +00:00
Tom Finegan
d26ec6909d mkvparser: Cluster::Parse clean up.
- Remove "// weird"'s.
- Remove commented out asserts.
- Asserts to error checks.
- Use ReadID to read IDs.

Change-Id: I029a268e4fa45931e3c6a72e41448f0b8fb2d0c3
2015-08-31 14:32:53 -07:00
Tom Finegan
f2029be5f4 mkvparser: Disallow EBML IDs equal to 0.
Change-Id: Ia272b1505dc62fdadf06348365a6aef058b081d8
2015-08-31 14:23:38 -07:00
Tom Finegan
19f5694277 mkvparser: Cluster::Load clean up.
- Remove "// weird"'s.
- Remove needless extra scoping.
- Asserts to error checks.

Change-Id: I5c4d1bbc59d9debe95e1e35e63ff0679335048ff
2015-08-31 13:59:35 -07:00
Tom Finegan
27a07c1fd1 mkvparser: Segment::Load asserts to error checks.
Change-Id: Ia47a24786789d6f94a786f76e313318e013f4f40
2015-08-31 13:38:35 -07:00
Tom Finegan
d0313dd7ce mkvparser: Segment::PreloadCluster asserts to error checks.
Change-Id: I3a2e2226f30ee047f96f5136c52e4cb9081d42c8
2015-08-31 13:36:15 -07:00
Tom Finegan
b108695b9b mkvparser: Segment::AppendCluster asserts to error checks.
Change-Id: Id6bb378b22a7c6397e3d950c2fdd84396279e881
2015-08-31 12:40:24 -07:00
Tom Finegan
4630f80f79 mkvparser: Segment::DoLoadClusterUnknownSize asserts to error checks.
Change-Id: I4597416261efb9202d2307e1ac4abfeb38e7c515
2015-08-31 12:38:20 -07:00
Tom Finegan
841a9b5fd9 mkvparser: Segment assert clean up.
- Remove asserts from ~Segment, CreateInstance, and DoLoadCluster.
- Adds new return constant (E_PARSE_FAILED == -1); most places in
  mkvparser that return -1 are the result of an internal inconsistency
  and/or misusing the API. In those cases E_FILE_FORMAT_INVALID is not
  appropriate as a return value because it's misleading to libwebm users.

Change-Id: I0d46e831b3475d69432b8745066de3329419fa11
2015-08-31 12:38:09 -07:00
Tom Finegan
8c4ca2ea04 Merge "mkvparser: Make mkvparser namespace usage uniform." 2015-08-28 21:55:13 +00:00
Tom Finegan
49ae6f0dd9 Merge "mkvparser: Fix include order." 2015-08-28 21:54:04 +00:00
Tom Finegan
0735bb5bdc mkvparser: Make mkvparser namespace usage uniform.
Instead of being weird and defining the first few functions
in mkvparser by explicitly prepending the namespace, open the
namespace immediately and define all functions within it.

Change-Id: I9a44a0fda8b04f89c8f874a2a6edc78f1b8e5bcc
2015-08-28 14:26:46 -07:00
Tom Finegan
93b24c4195 mkvparser: Fix include order.
Change-Id: Ia03ce824c78c19f5ab62c736069ea0972b8c93ea
2015-08-28 11:06:03 -07:00
James Zern
a57d6602b4 sample_muxer: fix Segment memory leak on error
use an auto_ptr<mkvparser::Segment> for compatibility which should be
harmless as there is no attempt to transfer ownership; sample.cpp
operates similarly.

Change-Id: I2cb6982aa64c62ff2ec7cbbd646770cb4e782509
2015-08-27 21:09:16 -07:00
Tom Finegan
1c5bd949d0 mkvparser: Cues, change asserts to error checks.
Change-Id: I116845b792aa5bb9a35341097cbd393300539f79
2015-08-26 12:51:05 -07:00
Tom Finegan
7f77201dca Merge "mkvparser: Add ReadID." 2015-08-26 19:49:11 +00:00
James Zern
795fd568b6 mkvparser: set kMaxAllocSize explicitly
removes the need for the unrelated INT32_MAX and fixes the build
(stdint.h was missing)

Change-Id: Idf3315097982aec6fb28030bd2327ba6cff14668
2015-08-25 20:29:50 -07:00
Tom Finegan
23bb18b76d mkvparser: Add ReadID.
Enforce ID rules in one place instead of every time
an ID is read.

Change-Id: I6e39a2e2dbafa2d5926dea790dd563cc3a48f67e
2015-08-25 13:37:35 -07:00
Tom Finegan
7b57e37fde mkvparser: add SafeArrayAlloc.
A new wrapper that makes array allocations safer by
limiting allocated size.

BUG=23430787

Change-Id: I901ee61dc2b601e8c0b5bf13f7499b5d2479ba7a
2015-08-25 13:06:27 -07:00
Tom Finegan
83a1f68944 mkvparser: Remove buf_t typedef.
- It is useless.
- It masks errors; buf_t was unsigned char*, but const buf_t was
  not seen by the compiler as const unsigned char*, which allowed
  passing a const pointer as a mutable argument to
  IMkvReader::Read at every site where buf_t was in use.

Change-Id: I293015e11c69d992e76c88ac02052a5a9a2b2c9c
2015-08-25 10:47:17 -07:00
James Zern
507471457e Merge changes Ia1265a63,I799d54df,Icfc582e4,I3425f608
* changes:
  Block::Parse: replace pos asserts w/checks
  Cluster::ParseBlockGroup: replace pos asserts w/checks
  Tags::*::Parse: replace pos asserts w/checks
  Chapters::*::Parse: replace pos asserts w/checks
2015-08-25 06:28:43 +00:00
James Zern
b18110541a Merge changes Ie4318152,I1e65f30f
* changes:
  Block::Parse: use int64 to aggregate laced frame sizes
  UnserializeFloat: check result for Inf/NaN
2015-08-25 06:25:04 +00:00
James Zern
06b4337ed8 Block::Parse: replace pos asserts w/checks
replace the common patterns assert(pos <= stop) / assert(pos == stop)
with error checks

BUG=23431751

Change-Id: Ia1265a639086c790a2ed542f34c2f438c153b036
2015-08-24 19:59:08 -07:00
James Zern
b366a98053 Cluster::ParseBlockGroup: replace pos asserts w/checks
replace the common patterns assert(pos <= stop) / assert(pos == stop)
with error checks
+ harmonize error return -1 -> E_FILE_FORMAT_INVALID

BUG=23431751

Change-Id: I799d54df62d93388b52ac325b836ab28e0860992
2015-08-24 19:59:04 -07:00
James Zern
2857b2350c Tags::*::Parse: replace pos asserts w/checks
replace the common patterns assert(pos <= stop) / assert(pos == stop)
with error checks
+ harmonize error return -1 -> E_FILE_FORMAT_INVALID

BUG=23431751

Change-Id: Icfc582e414a7d02ae0675ef14c047922c4a12036
2015-08-24 19:59:00 -07:00
James Zern
f1b2cfa03e Chapters::*::Parse: replace pos asserts w/checks
replace the common patterns assert(pos <= stop) / assert(pos == stop)
with error checks

BUG=23431751

Change-Id: I3425f6083456b5ab4f40497e3a192569b494dfa9
2015-08-24 19:56:07 -07:00
Tom Finegan
ca8062959a Merge "mkvparser: Cues::PreloadCuePoint now returns bool." 2015-08-25 02:22:05 +00:00
James Zern
6b4b297220 Block::Parse: use int64 to aggregate laced frame sizes
this is compared against a final total which is also int64

BUG=23488728

Change-Id: Ie4318152f9f9ae049a35d0b2724ccad129316981
2015-08-24 17:00:34 -07:00
James Zern
c0d2c9852b UnserializeFloat: check result for Inf/NaN
fail in either case

BUG=23488728

Change-Id: I1e65f30ff1cf857a5d1eb4bdedc3f842423cf15f
2015-08-24 16:49:22 -07:00
Tom Finegan
1a6dc4f210 mkvparser: Cues::PreloadCuePoint now returns bool.
Check allocations and fail appropriately.

Change-Id: Ie16d258a47e46b5e15c5c6275ea83ebead8b0f49
2015-08-24 16:20:13 -07:00
Tom Finegan
275ac22cae mkvparser: Cluster::Create clean up.
- Asserts to error condition check and return.
- Use nothrow new.

Change-Id: Iff9da5806e6f3240e7ea9f9e90ccdf729848a778
2015-08-24 16:19:10 -07:00
James Zern
064f2eed62 Segment::PreloadCluster(): return a bool status
BUG=23430793

Change-Id: I10aab67e94961868be806ee7ee9df550a5187e5a
2015-08-22 11:02:55 -07:00
James Zern
3778408b2a Segment::AppendCluster(): return a bool status
BUG=23430793

Change-Id: I6072234bfe211153ad143ccf7a3c6bbfa8cd166e
2015-08-22 11:01:47 -07:00
James Zern
e86d046c07 mkvparser: check Cluster::Create() return
BUG=23430793

Change-Id: Ie932dd2ee82d41368616999ab75ba3b213008642
2015-08-22 10:47:03 -07:00
James Zern
f9885b5882 mkvparser: check allocations
some unchecked new's are left in a few void functions, they'll be
addressed in a separate commit

BUG=23430793

Change-Id: I4953e70f4e7b0401a293c6b87c02445960e9ff9e
2015-08-22 10:47:03 -07:00
James Zern
21ee398281 mkvparser: Segment::Load fail w/missing info/tracks
convert asserts to error returns

BUG=23430793

Change-Id: Ifbfb5a2e7cd41344acc9c8d7afdf183b28dc2cd2
2015-08-22 10:47:03 -07:00
James Zern
08fb6546e8 Merge changes I264e68b2,Ife6190a4,Ibf37245f,I06efadb5,I88b5dfec, ...
* changes:
  mkvparser/Cluster: convert asserts to failure returns
  mkvparser/Tracks: convert asserts to failure returns
  mkvparser/Track: convert asserts to failure returns
  mkvparser/ContentEncoding: convert asserts to failure returns
  mkvparser/Cues: convert asserts to failure returns
  mkvparser/SeekHead: convert asserts to failure returns
  mkvparser/Segment: convert asserts to failure returns
2015-08-22 05:52:07 +00:00
James Zern
c8960955db mkvparser/Cluster: convert asserts to failure returns
Change-Id: I264e68b24eeb0f719a9d60b4cb0454e38110dd39
2015-08-21 22:49:57 -07:00
James Zern
680b4bfd3d mkvparser/Tracks: convert asserts to failure returns
BUG=23431751

Change-Id: Ife6190a4bcd4ab949165f17fd0b6c26a058a661b
2015-08-21 22:49:57 -07:00
James Zern
5889e6c18b mkvparser/Track: convert asserts to failure returns
Change-Id: Ibf37245f74e019c788b3f4121082956aa209430a
2015-08-21 22:49:57 -07:00
James Zern
5135c4cd74 mkvparser/ContentEncoding: convert asserts to failure returns
Change-Id: I06efadb5242135b095ad4cdefceef0e1c42c79b9
2015-08-21 22:49:57 -07:00
James Zern
b0e4f32011 mkvparser/Cues: convert asserts to failure returns
Change-Id: I88b5dfecfd03fec7f5808959ec6f640bff838d7a
2015-08-21 22:45:02 -07:00
James Zern
13ccc7f089 mkvparser/UnserializeInt: fix sign flip
with -funsigned-char the sign will be flipped, e.g., -128 -> 128, use an
explicit signed char.

additionally drop the misguided range check; this is meant as a data
size limit not one for the big-endian encoded ints

Change-Id: Ia10ef811d16acd09cbcd3d95856d9c460c9b7f16
2015-08-21 22:35:20 -07:00
James Zern
db3f9bbd79 mkvparser/SeekHead: convert asserts to failure returns
Change-Id: Ic2c83e4eb246fd4c1fc63fe16298f0dc78801912
2015-08-21 19:47:34 -07:00
James Zern
8de3654fdb mkvparser/Segment: convert asserts to failure returns
Change-Id: I7ccfd5be5e7438561edacb06bc8e6256aa6e0369
2015-08-21 19:46:15 -07:00
James Zern
fa2aa7da2d SeekHead::Parse(): fix assertion failure
replace assertions with failure returns

BUG=23430787
BUG=23431751

Change-Id: I22f000388cf040d064ba898c5de3658b56a3dfea
2015-08-21 18:12:08 -07:00
James Zern
d9bdadeff8 sample{,_muxer}: check SegmentInfo::GetInfo() return
prevents a segfault when parsing a corrupt file

BUG=23430793

Change-Id: I909fd456555ed0d5d871e12258b4887f36f90867
2015-08-21 16:58:04 -07:00
James Zern
07a9cf7127 Merge "mkvparser: Remove some asserts." 2015-08-21 21:28:13 +00:00
Tom Finegan
c56ee29254 mkvparser: Remove some asserts.
Remove asserts in sections recently updated to do error checking, and
replace some additional nearby asserts with error checks.

Change-Id: Ia8b60824736a7a821bbca3f2bfef5de4bb584c2d
2015-08-21 13:06:09 -07:00
Tom Finegan
d9013243ff Merge "mkvparser: Remove some asserts from SegmentInfo::Parse." 2015-08-21 19:57:35 +00:00
Rob Gaunt
7f7d898a27 Fix case sensitivity issue in iosbuild.sh.
Change-Id: I82b851b442cfe46ead78d115bbd7e22927ea6334
2015-08-21 12:27:30 -07:00
Tom Finegan
42fe2cd755 mkvparser: Remove some asserts from SegmentInfo::Parse.
Just return errors.

Change-Id: Ic3510db9c298e12cbe2a40fe09344a1c8e1e4ca8
2015-08-21 12:10:38 -07:00
Tom Finegan
8bccd9c306 Merge "mkvparser: avoid rollover in UnserializeInt()." 2015-08-21 18:47:16 +00:00
Tom Finegan
7a2fa0daf3 mkvparser: avoid rollover in UnserializeInt().
- Not strictly rollover-- avoid exceeding max 64 EBML (2^26 - 2).
- Tidy up the function.

BUG=23321923

Change-Id: I172c75064c189ed0fcf224145d016fca421f60c6
2015-08-21 11:24:30 -07:00
Tom Finegan
44f5ce64b1 mkvparser: Disallow durations in seconds greater than LONG_LONG_MAX.
libwebm cannot handle a duration in seconds greater than LONG_LONG_MAX
because it stores the values in long long variables.

BUG=23321923

Change-Id: Idb73f04a73e35829ae34386ea6c388fd355dd102
2015-08-21 10:54:27 -07:00
Tom Finegan
b521e3030e Merge "mkvparser: Segment::ParseHeaders() avoid rollover and bad int sizes." 2015-08-20 16:59:29 +00:00
Tom Finegan
7680e2a76b mkvparser: Check for errors in Match().
Confirm asserted conditions are as expected in all build
configurations, and avoid rolling over pos in obvious places.

BUG=23225325

Change-Id: I8af3192283788fd4a4b5b8ba4ad94abeab7feff2
2015-08-19 21:46:32 -07:00
Tom Finegan
39a315f8c1 mkvparser: Segment::ParseHeaders() avoid rollover and bad int sizes.
BUG=23226908

Change-Id: I177fc75684daa3c0282b63ec270d095251a70881
2015-08-19 21:23:21 -07:00
Tom Finegan
f250aceeaa mkvparser: Handle invalid lengths and rollover in ParseElementHeader().
BUG=23224239

Change-Id: I597054dc552b54f99a6716fb8f1b0f2480f2a29b
2015-08-19 12:34:54 -07:00
Tom Finegan
cd96a76985 mkvparser: Avoid rollover/truncation in UnserializeString().
Change-Id: I355d00b59ec1b7645ae5b4010e292215b5da3a17
2015-08-17 15:35:44 -07:00
Tom Finegan
8e8b3dbc6a Merge "mkvparser: Add error checking in Block::Parse." 2015-08-14 18:11:24 +00:00
James Zern
82b7e5f487 sample: correct mbstowcs() error check
mbstowcs() can return (size_t)-1 if it encounters an invalid string

BUG=23200382

Change-Id: Ibf67145be3989e16cd24c06850c7a5aa581a0ada
2015-08-14 10:57:48 -07:00
James Zern
04d7809375 sample: check allocation return
BUG=23200382

Change-Id: Ic64f76000d181f169af9aed2f7891f6ed3d28681
2015-08-14 10:57:01 -07:00
Tom Finegan
986b64b8c0 mkvparser: Add error checking in Block::Parse.
Instead of relying solely on asserts, which compile away to
nothing in downstream projects using libwebm for parsing webm
input streams, actually check for the conditions being asserted,
and return errors when appropriate.

Change-Id: Id8b6352e8dda69782129dcea8f67203fd9c4f572
2015-08-14 10:45:46 -07:00
James Zern
2dec09426a mkvparser: normalize UnserializeInt signature
long size -> long long; fixes a conversion warning under visual studio

Change-Id: I216151236f4ad7e1b8af4d8b7d19e3b36083fd14
2015-08-04 19:01:06 -07:00
Francisco Facioni
b6de61a5c0 Adds support for simple tags
Change-Id: I285e4b73df0a7112bbde7ef13eddf8fdccf59178
2015-07-22 17:07:25 -03:00
Tom Finegan
75a6d2da8b sample_muxer: Don't write huge files.
sample_muxer was using the buffer size instead of the frame payload size
when passing frames to the muxer.

BUG=https://code.google.com/p/webm/issues/detail?id=1032

Change-Id: I25578934e8822553e3482ded80eaf22651be85cc
2015-07-01 14:26:55 -07:00
James Zern
cec1f8521f mkvmuxer: remove unused timecode_scale variable
unused in WriteFramesAll() / WriteFramesLessThan() since:
d6d04ac mkvmuxer: use generic Cluster::AddFrame

Change-Id: I2089dc24b6a942f342b278b46271c6144cf8351e
2015-06-17 16:23:30 -07:00
James Zern
8a61b4033e Merge "mkvparser: Tiny whitespace fix." 2015-06-10 19:10:17 +00:00
Vignesh Venkatasubramanian
7affc5c3f8 clang-format re-run
Re-run clang-format to pick up some missed changes over the past
few CLs. Also update the .clang-format file to break after ternary
operator.

Change-Id: Ia4ba4e58362c2dbe36aeb33894f0411af33ef17d
2015-06-04 16:48:48 -07:00
Vignesh Venkatasubramanian
d6d04acdcc mkvmuxer: use generic Cluster::AddFrame
Replace specific Cluster::AddFrame* calls with a call to generic
Cluster::AddFrame().

Change-Id: If082490d2c29003b466034fc318f5e58791408a6
2015-06-04 16:33:36 -07:00
Vignesh Venkatasubramanian
4928b0bd5f Merge "mkvmuxer: Write Block key frames correctly." 2015-06-04 23:32:33 +00:00
Vignesh Venkatasubramanian
c2e4a46244 Merge "sample_muxer: Use AddGenericFrame to add frames." 2015-06-04 23:17:14 +00:00
Tom Finegan
e97f296855 mkvparser: Tiny whitespace fix.
Change-Id: I0f17eee0ce161c950f6d504ba1b509bd7b0e6343
2015-06-04 09:55:58 -07:00
Frank Galligan
d66ba4470a Merge "Add support to parse DisplayUnit." 2015-06-03 00:25:32 +00:00
Frank Galligan
deb41c2ea1 Add support to parse DisplayUnit.
BUG=https://code.google.com/p/webm/issues/detail?id=1009

Change-Id: I209ee6caf5bc10dfc1761e650821cc2338a4b13c
2015-06-02 16:17:13 -07:00
Leonel Togniolli
42e5660e73 Fix issues on EBML lacing block parsing
Fix EBML lacing block parsing when attempting to parse the last frame
on single-frame videos and assertion when frame_count is lower
than actual data in the file.

Change-Id: I223e30be54970ef75126c6c4ee3401cbeb92e02f
2015-06-02 15:51:48 -07:00
Leonel Togniolli
fe1e9bba6e Fix block parsing to not allow frame_size = 0
Fixed block parsing to account to cases that would
allow frame_size = 0, only to be rejected later on
Block::GetFrame assert(f.len > 0);

Change-Id: Idb93388b37e1963ec6115ac49f15e4951bc2c724
2015-06-02 15:51:48 -07:00
Leonel Togniolli
2cb6a28b09 Change assertions to checks when parsing TrackPositions
Malformed files woudl cause the parser to assert.

Instead now it stops parsing and skips the segment.

Change-Id: I256b3b72e43f969693ae16547ca98da07d665e21
2015-06-02 15:51:40 -07:00
Leonel Togniolli
d04580fda5 Fixes issues on Block Group parsing
Changed assertions to "invalid file format" errors files that
had Block Groups without Block IDs or had invalid sizes or
durations

Change-Id: I1383a63bfb76ee46aaa0aff089780383ce65fc31
2015-06-02 10:39:09 -07:00
Vignesh Venkatasubramanian
c3550fdacf mkvmuxer: Write Block key frames correctly.
Per matroska Block Structure [1], for keyframes the flag should not be
set (unlike SimpleBlocks). For Blocks, keyframes is inferred by the
absence of ReferenceBlock element.

This CL fixes Issue #933 [2].

[1] http://www.matroska.org/technical/specs/index.html#block_structure
[2] https://code.google.com/p/webm/issues/detail?id=933

Change-Id: Ia3f811c3fe17fb4dededda2f6834cf7cf2d2e022
2015-06-01 11:04:12 -07:00
Vignesh Venkatasubramanian
5dd0e40dbd Merge "mkvmuxer: Set is_key to true for metadata blocks." 2015-06-01 17:51:40 +00:00
Vignesh Venkatasubramanian
8e96863b56 mkvmuxer: Set is_key to true for metadata blocks.
Per matroska semantics, all metadata blocks should be considered
key frames. Set it to true in AddMetadata functions.

Change-Id: Ibc26845dc6cc72ccbf90ae8d4dcc27c948e8a375
2015-06-01 10:49:19 -07:00
Vignesh Venkatasubramanian
a9e4819e9f sample_muxer: Use AddGenericFrame to add frames.
Use Segment::AddGenericFrame to add frames to the output file. The
other AddFrame* functions will soon be deprecated and this will be
the preferred way of adding frames.

Change-Id: I3ed862543a1e0199617dc613a1760ff5f233ce7d
2015-06-01 10:32:07 -07:00
Leonel Togniolli
5a3be734f3 Change assertions to checks when load CuePoints
Malformed files would cause the parser to assert.

Instead now it stops parsing and skips the segment.

Change-Id: I07e3baf5c9eb6feb115e155f226d8abc2c37698e
2015-05-25 01:27:38 +01:00
James Zern
f99f3b20fb mkvmuxerutil::EbmlDateElementSize: remove value param
this is unused as the size of dates is fixed:
Date - signed 8 octets integer in nanoseconds with 0 indicating the
precise beginning of the millennium (at 2001-01-01T00:00:00,000000000
UTC)

Change-Id: I7d44c92a6b746e92e4041238b110115b56e38a93
2015-05-23 10:33:12 -07:00
James Zern
ff572b5399 Frame::IsValid: fix track_number check
previously IsValidTrackNumber() expected a track_number > 0
this also fixes a warning:
'comparison of unsigned expression < 0 is always false'

Change-Id: I839863986ff776aae59e38ee7e4a1a710081303a
2015-05-23 10:32:56 -07:00
Vignesh Venkatasubramanian
b6311dc16f mkvmuxer: Refactor to remove a lot of duplicate code
Refactor muxer to remove a lot of duplicate code. This CL strives
to not change the API as much as possible. Although, there is one
minor public API change (constructor of the Cluster class). Other
than that, all the functions should work exactly the same way as
before.

Following up on this CL, we are going to make AddGenericFrame the
preferred way of adding frames to a segment and deprecate (and
eventually remove) all the other specific AddFrame* functions.

Change-Id: Ie410f1a64a981e1545ade53ce476bbe8b3610c4f
2015-05-20 10:24:26 -07:00
Vignesh Venkatasubramanian
256cd02327 Merge "mkvmuxer: DiscardPadding should be signed integer." 2015-05-14 13:42:50 +00:00
Vignesh Venkatasubramanian
16c8e78265 mkvmuxer: s/frame/data in all AddFrame* functions.
Rename variable "frame" to "data" in all the AddFrame* functions.
This is in prepararation for a follow-up CL.

Change-Id: Ifd0d96cfbeca85c12be23d854bc87e085436984d
2015-05-12 15:31:07 -07:00
Vignesh Venkatasubramanian
c5e511c00a mkvmuxer: DiscardPadding should be signed integer.
Discard Padding getter and setter should take and return a signed
integer respectively.

Change-Id: Ieb6b9cd8c9830c2335ffdbcd608c727a3d135bb8
2015-05-12 14:56:12 -07:00
Tom Finegan
4baaa2c9a3 Add framework build script: iosbuild.sh
Builds WebM.framework.

Change-Id: I6f71defa18a7cbb21e290dbbb819a85353912e53
2015-05-06 10:33:48 -07:00
James Zern
3d06eb1e2c PATENTS: fix a typo: constitutes -> constitute
Change-Id: Iec2d5fea1b89fc97f981f5cd0a545b83110bd8c2
2015-04-30 15:40:13 -07:00
Tom Finegan
d3849c2f7b mkvparser: Dead code removal.
Change-Id: Ic4cf359ecc80641b97f40c20639ce9c32b34077d
2015-04-14 23:36:29 -07:00
Leonel Togniolli
f439e523b8 Change assertions to checks when preloading Cues
If a malformed webm file contains invalid information on the Cues
the segment, the parser would assert.

Instead, now it ignores the Cues and skips the segment.

Change-Id: I9270f6a0935ce9e9a3765a5f324ae542c1ade1c7
2015-04-14 01:25:25 +01:00
Leonel Togniolli
d3a44cd549 Fix track transversal when listing Cues on sample
It could skip tracks or crash if track numbers were non-sequential or tracks were missing.

Change-Id: I485bd4c14c73500775f2944b4486f9a5e154a5e8
2015-04-11 00:24:30 +01:00
Leonel Togniolli
c6255af02a Tweak .gitignore so git status is clean after checkout and build:
- added missing underscore to sample_muxer
- added cmake and make related files

Change-Id: Id9a6f12be83d28c95941098b57b61a7a11510f1b
2015-04-09 00:38:17 +01:00
James Zern
b5229c7bc8 Makefile.unix: s/samplemuxer/sample_muxer/
this matches the target name used in CMakeLists.txt and the writing app
stored in the output file

Change-Id: I161675c6bff8ebfa041331a329589441d3874514
2015-03-18 15:33:06 -07:00
Sasi Inguva
e3616a6614 Add support to parse stereo mode, display width and display height in mkvparser
Change-Id: I7ff99275b70e96b84601c32836f1b79f95fcf0d4
2015-03-12 00:25:58 -07:00
Vignesh Venkatasubramanian
a4b68f825e parser: Fix bug in Chapters::Atom::Parse()
Reading the UID is considered to be failed only if status is < 0
and not the value read.

Change-Id: I88fee3aa5b8c323d099930a6823406c012b70f81
2015-03-03 12:08:28 -08:00
Tom Finegan
bab0a002c5 cmake: Set library and project name the proper way on Windows.
Revert previous hack and use target properties to correct project
and library names.

Change-Id: Ib35da1cedcedf86f3f020d879cd39199fd236572
2015-03-02 12:43:56 -08:00
Tom Finegan
feeb9b13ff Set library name to match Windows expectations.
Back to libwebm.lib from webm.lib.

Change-Id: I6ced362c987a7b5d3d56365a1ed53de7bf9f849b
2015-02-25 15:37:05 -08:00
Vignesh Venkatasubramanian
b9a549b467 Fix CMakefile to generate libwebm.a
The existing CMakeLists.txt ends up generating a static library
with name "liblibwebm.a" rather than "libwebm.a". This patch fixes
it.

Change-Id: I4dabac5158530714a38045b8af29e75ade0a939e
2015-02-25 14:04:04 -08:00
Tom Finegan
b386aa5c6b Add CMakeLists.txt and msvc_runtime.cmake.
- These files facilitate project/makefile generation.
- Remove old Visual Studio projects.
- Rename Makefile to Makefile.unix.

Change-Id: If786edd75d44c462538526c286eccc5cbf15d828
2015-02-13 16:07:01 -08:00
Vignesh Venkatasubramanian
b0f8a81df9 parser: Fix memory leak in Chapter parsing
Fix a memory leak in parsing Chapters element.

Change-Id: I95324299014174d3f0926d96022eeb747b07d1a7
2015-02-06 15:17:28 -08:00
Vignesh Venkatasubramanian
f06e152abd mkvmuxer: Fix MoveCuesBeforeClustersHelper recursive call.
The third parameter of the MoveCuesBeforeClustersHelper recursive function
should always be the size of the cues element without the master element's size
(i.e.) it should be the sum of size of all Cue Points. This way, the changes in
the Length of the master element itself will be computed correctly.

Change-Id: I05ff1606fb74168f80ffed81fd3c0de3f237c579
2015-02-02 18:34:18 -08:00
Lajos Molnar
27bb7476dd allow subtitle tracks with ContentEncodings
This is allowed by matroska spec

Change-Id: I1842b6e7c6bab4ba0f86938bbe6b110be0c5435f
2015-01-13 12:56:25 -08:00
James Zern
623d182613 DoLoadCluster: tolerate empty clusters
previously only empty clusters of known size were accepted; with
clusters of unknown size the cluster has been successfully parsed and a
working copy of the file position updated, so parsing can continue.
clusters of this type are discarded as clusters of known size currently
are.

Change-Id: I3ef848768519ab7f1887a11629c50af72249cead
2014-10-01 12:53:14 -07:00
Lou Quillio
1156da8d29 Update PATENTS to reflect s/VP8/WebM/g
Sync with http://www.webmproject.org/license/additional/

modified:   PATENTS.TXT

Change-Id: I3e1b3a570b26ada0e6e0d344f1783ef0e3cd5fa1
2014-08-11 14:30:54 -07:00
Tom Finegan
0d4cb404ea mkvmuxerutil: Use rand() in MSVC builds.
Instead of rand_s(), which can make things unpleasant for downstream
projects.

Change-Id: Ie172867c28aaa43223dc5fb694eb4a4fd26515d6
2014-07-18 11:37:06 -07:00
Vignesh Venkatasubramanian
e12fff0ebb mkvmuxer: Overload WriteEbmlHeader for backward compatibility
WriteEbmlHeader function was updated on
a321704b4c. It is a public function that
is exposed outside of the library. Overload it with an old signature
to maintain compatibility. The overloaded function writes the
doc_type_version as 2 by default (thereby retaining the old behavior).

Change-Id: If887a1bfa3e81e7e639c986a922aa5155faab2cf
2014-07-09 11:24:09 -07:00
James Zern
a321704b4c mkvmuxer: write correct DocTypeVersion
Change-Id: I9a463394dec5e69ae8a7b5a1378f19d390e441e4
2: default
4: if CodecDelay/SeekPreRoll/DiscardPadding are present
2014-06-24 16:17:29 -07:00
James Zern
574045edd4 mkvmuxer: fix DiscardPadding
DiscardPadding is a signed int.
this change fixes 2 things:
- allows negative values for discard padding
- fixes cases where an unsigned value would be written such that on read
  the sign would be flipped

Change-Id: I9418da7a22c09768e02d5b61da8d01c2bccb5dee
2014-06-18 12:50:25 -07:00
Sergey Ulanov
8be63972fd Include crop elements when calculating size of Video element
Change acf788 added Crop* elements support, but they were not
added when calculating size of Video element.

Change-Id: I64495cc35406a28b86b40d915dbc291f45aa1263
2014-06-06 00:40:50 -07:00
James Zern
8f2d1b3cde mkvparser: fix DiscardPadding extraction
the element length was being read twice; the second attempt would
consume a portion of the discard padding field often failing due to
limitations in GetUIntLength.

Change-Id: Ibbe3f082e2d05460734a0e1f7d23f3c665e3f24b
2014-05-30 14:44:28 -07:00
Vignesh Venkatasubramanian
1c36c24694 mkvmuxer: fix style guide violations
fix a few style guide violations in mkvmuxer.cpp

Change-Id: If800a5d6851f8ba4b904341fd054e1c2091e281e
2014-05-29 08:30:30 -07:00
Vignesh Venkatasubramanian
568504e64e Merge "UUIDs can have their high bit set" 2014-05-23 09:01:20 -07:00
Sergey Ulanov
acf788bedd Add support for CropLeft, CropRight, CropTop and CropBottom elements.
Change-Id: Ic5993a3e04b3eefccc3016fbe6b49d1e4a5fc05d
2014-05-21 19:46:36 -07:00
Vignesh Venkatasubramanian
418188b03e Merge "muxer: codec_id is a mandatory element" 2014-05-18 12:48:29 -07:00
Vignesh Venkatasubramanian
07688c92d7 mkvmuxer: Reject frames if invalid track number is passed.
Reject frames if an invalid track number is passed. Also change sample_muxer
to reject files which have Block elements with invalid track numbers.

Fixes Issue #659: https://code.google.com/p/webm/issues/detail?id=659

Change-Id: Ie6cf39a409b68bb4d2261f308409ee0c36d5dd8e
2014-05-18 12:45:49 -07:00
Vignesh Venkatasubramanian
2a63e473d8 muxer: codec_id is a mandatory element
codec_id element for a Track is mandatory and it does not have a default.
Rejecting the file if that happens.

Change-Id: I4fb0dfcd4c09eeabf22634db7fdf6ca818c93917
2014-05-16 11:42:05 -07:00
Vignesh Venkatasubramanian
d13c017744 UUIDs can have their high bit set
mkvparser::UnserializeUInt() assumes that unsigned values never have
their high bit set. This is too limiting for UUIDs. In addition, the
Chapters::Atom::Parse() method would truncate a "negative" 64-bit UUID
value to 32 bits and return the truncated value as a status code.
This value then might or might not be treated as an error by the caller
depending on whether the truncated value was itself negative.

Change-Id: I15624ac62d0b02691a1405ee6a5f7eb441b3bc48
2014-05-16 11:25:22 -07:00
James Zern
249629d46c make Mkv(Reader|Writer)(FILE*) explicit
Change-Id: I2c6e0df3049903f8ea53babeacffaa87f6c222b0
2014-05-02 11:47:44 -07:00
Vignesh Venkatasubramanian
7f3cda494a mkvparser: fix a bunch of windows warnings
fix a bunch of windows warnings in parser.

Change-Id: Ia9a03879540595306d8fa2b90ceb9b3b5b0d93a6
2014-05-01 13:50:19 -07:00
Vignesh Venkatasubramanian
5c0617852f Merge "clang-format on mkvparser.[ch]pp" 2014-05-01 11:50:03 -07:00
Vignesh Venkatasubramanian
4df111e60a clang-format on mkvparser.[ch]pp
Conformance of mkvparser.[ch]pp to Google C++ style guide.

Change-Id: I459adac3da1496b432b71b3580b4dbd63037df2b
2014-04-29 11:30:00 -07:00
Vignesh Venkatasubramanian
7b2450131c clang-format re-run.
Re-running clang-format to take into account the recent change in it.
(https://gerrit.chromium.org/gerrit/#/c/69926/ )

Change-Id: Ie11afcaaf07a1967f65fd765f1a7c7112c85875a
2014-04-29 11:27:31 -07:00
Vignesh Venkatasubramanian
c6767b94fd Change AlignTrailingComments to false in .clang-format
AlignTrailingComments set to true seems to be causing some unwanted
alignments. Turning it off.

Change-Id: I5fd99db90b00c76cc7891f2cd1c80ec69ae97697
2014-04-29 00:38:14 -07:00
Vignesh Venkatasubramanian
9097a0691b Merge "muxer: Reject file if TrackType is never specified" 2014-04-29 00:18:55 -07:00
Vignesh Venkatasubramanian
eddf9744cb Merge "clang-format on mkvmuxertypes.hpp and webmids.hpp" 2014-04-28 10:40:43 -07:00
Vignesh Venkatasubramanian
def325c010 muxer: Reject file if TrackType is never specified
According to matroska specification, TrackType is a mandatory element without a
default value [1]. But we have been producing invalid matroska files when
TrackType is never specified because we write 0 by default.

This patch will reject writing a track without specifying the TrackType value.
Specifically, this path will be triggered when Segment::AddTrack() is called
but there is no subsequent call to Track::set_type().

[1] http://www.matroska.org/technical/specs/index.html#TrackType

Fixes issue #769: https://code.google.com/p/webm/issues/detail?id=769

Change-Id: I4d75d169fd96c7e1fad278561f0e7a3e1135989c
2014-04-26 03:14:05 -07:00
Vignesh Venkatasubramanian
41f869cb0c Merge "clang-format on webvttparser.(cc|h)" 2014-04-25 22:19:26 -07:00
Vignesh Venkatasubramanian
fd0be37ba4 clang-format on webvttparser.(cc|h)
Conformance of webvttparser.(cc|h) to Google C++ style guide.

Change-Id: I19610c5795c0bd2446c07a6c2abde58c3286b2ea
2014-04-25 22:18:40 -07:00
Vignesh Venkatasubramanian
207d8a193a Merge "clang-format on mkvmuxerutil.[ch]pp" 2014-04-25 22:09:48 -07:00
Vignesh Venkatasubramanian
02429eb11b Merge "clang-format on mkvwriter.[ch]pp" 2014-04-25 22:09:17 -07:00
Vignesh Venkatasubramanian
0cf7b1b7d3 Merge "clang-format on mkvreader.[ch]pp" 2014-04-25 22:09:02 -07:00
Vignesh Venkatasubramanian
2e80fedf8c Merge "clang-format on sample.cpp" 2014-04-25 22:08:38 -07:00
Vignesh Venkatasubramanian
3402e12d1a Merge "clang-format on sample_muxer.cpp" 2014-04-25 22:08:27 -07:00
Vignesh Venkatasubramanian
1a685db45b Merge "clang-format on sample_muxer_metadata.(cc|h)" 2014-04-25 22:07:59 -07:00
Vignesh Venkatasubramanian
6634c7f87a Merge "clang-format on vttreader.cc" 2014-04-25 22:07:46 -07:00
Vignesh Venkatasubramanian
7566004462 Merge "clang-format on vttdemux.cc" 2014-04-25 22:06:42 -07:00
Vignesh Venkatasubramanian
9915b8408e clang-format on mkvreader.[ch]pp
Conformance of mkvreader.[ch]pp to Google C++ style guide.

Change-Id: I9928a1a7daf9afaa30355b17b3eeeb2966626031
2014-04-15 12:05:58 -07:00
Vignesh Venkatasubramanian
743725477c clang-format on mkvmuxertypes.hpp and webmids.hpp
Conformance of mkvmuxertypes.hpp and webmids.hpp to Google C++ style guide.

Change-Id: Ib5e524f75f04ae6f6f5f24600d70b8448d01964c
2014-04-15 11:39:44 -07:00
Vignesh Venkatasubramanian
0d5a98cee5 clang-format on sample_muxer.cpp
Conformance of sample_muxer.cpp to Google C++ style guide.

Change-Id: I8d7ef884fbaac8ebbf12fc3e3215532ced5ac29b
2014-04-15 11:36:43 -07:00
Vignesh Venkatasubramanian
e3485c9b9f clang-format on vttdemux.cc
Conformance of vttdemux.cc to Google C++ style guide.

Change-Id: Id8838ddec286f935c8a3c1b78d9d9027b467165f
2014-04-15 11:31:20 -07:00
Vignesh Venkatasubramanian
46cc823994 clang-format on dumpvtt.cc
Conformance of dumpvtt.cc to Google C++ style guide.

Change-Id: I5fa11e79e95e61c1a1d923ba76ac7ae343c9c8e4
2014-04-14 12:15:04 -07:00
Vignesh Venkatasubramanian
5218bd291c clang-format on vttreader.cc
Conformance of vttreader.cc to Google C++ style guide.

Change-Id: Id5d2baf0977bca9ab938831cf6e6204acd4ed647
2014-04-14 12:11:27 -07:00
Vignesh Venkatasubramanian
1a0130d069 clang-format on sample_muxer_metadata.(cc|h)
Conformance of sample_muxer_metadata.(cc|h) to Google C++ style guide.

Change-Id: I500a8cdbc443981ecae6ac2a7d8de7cab1c72e28
2014-04-14 12:09:20 -07:00
Vignesh Venkatasubramanian
867f1894da clang-format on sample.cpp
Conformance of sample.cpp to Google C++ style guide.

Change-Id: Icb6bfce6af5df04775a086e080e6fa742c6d68f9
2014-04-14 12:05:21 -07:00
Vignesh Venkatasubramanian
4c7bec5743 clang-format on mkvwriter.[ch]pp
Conformance of mkvwriter.[ch]pp to Google C++ style guide.

Change-Id: I997545b366277b7f1235b9fa7cc30a4969098553
2014-04-14 10:30:33 -07:00
Vignesh Venkatasubramanian
9ead078aaf clang-format on mkvmuxerutil.[ch]pp
Conformance of mkvmuxerutil.[ch]pp to Google C++ style guide.

Change-Id: Ib66b73adb2682cd5560f6f363fc04d75ab3815c6
2014-04-14 10:28:59 -07:00
Vignesh Venkatasubramanian
fb6b6e6444 clang-format on mkvmuxer.[ch]pp
Conformance of mkvmuxer.[ch]pp to Google C++ style guide.

Change-Id: I9bcd14710adbad4f32aa1a6be2ea7e40fb715e91
2014-04-11 11:41:01 -07:00
Vignesh Venkatasubramanian
ce775929a6 Update .clang-format to allow short functions in one line
Update .clang-format so that it allows short functions and constructors in a
single line if it fits.

Change-Id: I60788089fc7a4e2f4c4df6947368ebc0f3fa8c49
2014-04-11 11:24:46 -07:00
Tom Finegan
0a24fe44ae Merge "Add support for DateUTC and DefaultDuration in MKV Muxer." 2014-04-10 16:13:21 -07:00
Vignesh Venkatasubramanian
11d5b66eb4 Merge "Add .clang-format" 2014-04-09 11:55:47 -07:00
Vignesh Venkatasubramanian
a1a3b14538 Add .clang-format
Add .clang-format file so that it can be used to maintain
the same style throughout the library.

Change-Id: I22bd21055f565a886b5a880856810f4b35b22cce
2014-04-09 11:50:54 -07:00
Sergey Ulanov
0fcec38045 Add support for DateUTC and DefaultDuration in MKV Muxer.
BUG=crbug.com/321825

Change-Id: I5ff8c5b9fd4e6be23ef2bc91a7a4ba021db6441f
2014-04-08 21:48:00 -07:00
Vignesh Venkatasubramanian
a7118d8ec5 Fixing a warning in mkvmuxerutil.cpp
Changing a constant from int32 to uint64 to fix a warning in
mkmuxerutil.cpp

Change-Id: Ifd9f76ea4be848eff4d98a797d2d4dcd22f11478
2014-04-08 16:15:28 -07:00
Vignesh Venkatasubramanian
abe9c2d0d1 Adding support for user file ownership in MkvReader
Adding a constructor to MkvReader that will enable user application
ownership of the file.

Change-Id: I10f8f71715392df3d4b78c7c11076e19c30e1af6
2014-04-04 13:49:52 -07:00
Vignesh Venkatasubramanian
630a0e3c33 mkvmuxerutil: Getting rid of strict-aliasing warning
Replacing a reinterpret_cast from float& to uint32& with a union to get rid of
"dereferencing type-punned pointer will break strict-aliasing rules" warning.
This warning is produced on passing -O3 in gcc.

Change-Id: Ie942597f418e3659e3ff29a909c43dd99266c04d
2014-03-17 12:19:21 -07:00
Vignesh Venkatasubramanian
e369bed319 Support user ownership of files in MkvWriter
Overloading MkvWriter's constructor so that it can wrap a user owned
FILE pointer. Doing this so that applications which handle the file opening
and closing by themselves don't have to have their own implementation of the
IMkvWriter interface.

Change-Id: I69c57f3e6927ea13b616c425e3b5f179d2e69215
2014-03-12 12:48:17 -07:00
Tom Finegan
a9d94ef2c5 Merge "vttdemux: Add VS2013 project." 2014-03-10 11:49:55 -07:00
Tom Finegan
3b66306126 vttdemux: Add VS2013 project.
And add it to the libwebm VS2013 solution.

Change-Id: I9957b47b291722bc0e5eb435795252cf780f968b
2014-03-10 11:46:53 -07:00
Tom Finegan
acb7a2c8bc Add VS2010 DLL build configurations for vttdemux.
- Link to libwebm instead of building sources.
- Add missing dependency on libwebm.

Change-Id: I8f977f767f6104d07f716c7c5ebecda249c202f2
2014-03-07 16:53:47 -08:00
Tom Finegan
99f40649a7 Merge "mkvmuxer: Silence MSVC warning that suggests making code non-portable." 2014-03-06 16:40:59 -08:00
Matthew Heaney
c6634bca44 Merge "vttdemux: created win32 project" 2014-03-06 14:36:03 -08:00
Matthew Heaney
17cf7cc519 vttdemux: created win32 project
Change-Id: I2a1ce12bc374f7493c50021cbe4fc4a4716a6829
2014-03-06 14:31:02 -08:00
Tom Finegan
7f79df14a8 Add Visual Studio 2013 projects.
Basically identical to the 2010 projects, but with platform
toolset set to VS 2013, and output files/paths updated to
avoid collisions with VS 2010 output.

Change-Id: I02b827288319db22eeb0beeed71261dc0673d6ef
2014-03-04 16:53:39 -08:00
Tom Finegan
23cdb09fd2 mkvmuxer: Silence MSVC warning that suggests making code non-portable.
Change-Id: I19bfa107bf01b1e10ac5a43040d409f4d620f4a7
2014-03-04 16:50:34 -08:00
Tom Finegan
8ae2137637 mkvparser: Silence MSVC warning that suggests making code non-portable.
Change-Id: Ia8b4cd39711105a5b3462b512160f9250e8a5966
2014-02-25 09:36:32 -08:00
Tom Finegan
7952ce8f78 Merge "mkvparser: Fix unused variable warnings when NDEBUG is defined." 2014-02-05 20:56:22 -08:00
Tom Finegan
d58f55542f mkvparser: Fix unused variable warnings when NDEBUG is defined.
Change-Id: I98b1121768e5650c2184acbf35636a15e9241148
2014-02-05 20:44:29 -08:00
Tom Finegan
a0c85b1e46 mkvparser/sample: Fix incorrect printf format specifiers.
Change-Id: I8b61f429f7bb1da7b3def612f6413895f8cb945d
2014-02-05 18:51:17 -08:00
Tom Finegan
4600f5b4a2 Merge "Fix mingw build." 2014-01-24 11:13:56 -08:00
Tom Finegan
a142b15ada Fix mingw build.
Change-Id: Iec913e0cf5849bec459e98df59b0e0bd8e02965b
2014-01-23 22:31:42 -08:00
Tom Finegan
4a3f5c9f99 Merge "mkvparser: Add basic cues walking to sample." 2014-01-23 22:29:12 -08:00
Tom Finegan
84f2156ca1 Merge "mkvmuxer: Add DiscardPadding support." 2014-01-23 15:34:12 -08:00
Tom Finegan
5440f20071 mkvparser: Add basic cues walking to sample.
Change-Id: Ia90e760f04083fa60b44f4d372e118474fc59fee
2014-01-23 15:31:18 -08:00
Tom Finegan
5c14a3f035 mkvparser/mkvreader/sample: CRLF -> LF
Change-Id: Id4a5bea411d104289548b276d0e996352cc816b1
2014-01-23 10:57:06 -08:00
Tom Finegan
71a097fb12 mkvparser sample: clang-formatify
Exception asterisk placement, which was left as before to match the rest of
libwebm.

Change-Id: I3947acc936cca68df72a5bcd8dec17ed40658ba6
2014-01-23 10:52:46 -08:00
Tom Finegan
cd6f7bff4b mkvmuxer: Add DiscardPadding support.
Also a bit of refactoring to remove some duplicate code.

Change-Id: Ia3d17461ae5f6275534e06c31f348bdfc4bba169
2014-01-22 23:26:26 -08:00
Tom Finegan
327e8ab617 Minor clean up: msvc warnings/include order/comment text.
Change-Id: I2b54abcb9f535715d8713930942447c0b0f5f862
2014-01-22 14:03:40 -08:00
Tom Finegan
796c90798a Merge "sample_muxer: Silence MSVC warning." 2014-01-16 13:01:54 -08:00
Sergey Ulanov
0f7815b036 Add license header in sample_muxer_metadata.cc.
This is required by the checklicenses.py script in chromium.

Change-Id: Ice6155b1332adcbda74532e558438083212e1511
2014-01-16 11:31:13 -08:00
Tom Finegan
ccb7fa9c73 sample_muxer: Silence MSVC warning.
Disable C4996; A warning that encourages users to make their code
require the "secure" variant of functions like tmpnam(). Doing so
just happens to make the resulting code require the MSVC runtime.

Change-Id: I0329ce3aa93da060110d24a4bc7f48a7f9c87227
2014-01-15 15:00:59 -08:00
Tom Finegan
4ec1e5cae5 Merge "mkvmuxer: Fix warnings." 2014-01-15 14:36:06 -08:00
Tom Finegan
849093f84f mkvmuxer: CRLF->LF webmids.h.
Match the other muxer sources. Also fix declaration order
of elements in the track grouping.

Change-Id: I06fdb98eb42815af96e80e33379ef73d41b470b3
2014-01-15 12:37:15 -08:00
Tom Finegan
32e1556e68 mkvmuxer: Fix warnings.
Remove useless spam from build output.

Change-Id: Iae200d32cda1fc11cd471772725345d0979e97bc
2014-01-15 12:14:27 -08:00
Tom Finegan
5efd6e3c1d mkvmuxer: Add support for VP9 and Opus tracks.
Also make codec ID constants really constant.

Change-Id: I951d25e83ce507afb1ca475e2d5dbfe6402f3d61
2014-01-10 15:03:47 -08:00
Tom Finegan
a6c71c1407 mkvmuxer: Add support for writing CodecDelay and SeekPreRoll elements.
Change-Id: Iad8c671b76c4b97abad58946df7f3c0ebe6cb01b
2014-01-10 11:32:56 -08:00
Tom Finegan
81c1d8415c mkvparser: Add support for CodecDelay, DiscardPadding, and SeekPreRoll elements.
Change-Id: Ic9e6ebcc2ba533f8cc1ab933d0bf55782ccab932
2014-01-08 17:33:03 -08:00
Vignesh Venkatasubramanian
d2f7478148 Initializing last_block_duration_ to zero.
Adding a missing initialization.

Change-Id: Id4223765968745a46653139b2a9f1537102c3618
2013-10-30 11:13:38 -07:00
Vignesh Venkatasubramanian
fd0a65af98 Merge "Fixing a bug in Chapter::Clear" 2013-10-25 11:13:05 -07:00
Vignesh Venkatasubramanian
872cc57de4 Adding set_uid to Chapter Class
Adding set_uid function to the Chapter class. It can be used to
achieve deterministic output from the muxer. For example, for files
with only one segment, track number or track id can be used for
chapter uid.

Change-Id: I2e94c6150e32cb9019a6623af7919acc099aa20d
2013-10-25 09:33:28 -07:00
Vignesh Venkatasubramanian
ddfea3431f Fixing a bug in Chapter::Clear
Replacing a typo'd < with > in Chapter::Clear of mkvmuxer.

Change-Id: I8784d19dbca5a8a62c92ed14e2efa61d96c5375f
2013-10-25 09:12:11 -07:00
Vignesh Venkatasubramanian
4134f6e04e Adding AddLastFrame to Segment
Adding AddLastFrame function to the Segment muxer so that the duration
of the Segment can be accurately calculated given the last Block's duration.
We now provide an AddLastFrame function which will take duration of that block
as a parameter. When this function is used to add the last frame, the duration
of it is taken into account when computing the Segment's duration.

Change-Id: I3e1456299fefa1a4dd6d845c47292951d1ce3ad0
2013-10-25 08:28:23 -07:00
Tom Finegan
25025a5471 Add dependency checks to Makefile.
Avoid unfortunate things like breaking the library because the make file
was not previously checking dependencies.

Change-Id: Iab20c3cfa0d1475dfb5c54127646b351df1c4c50
2013-08-19 19:32:37 -07:00
Tom Finegan
f72dc7b052 Ignore dependency files and build products.
Change-Id: I4e9da395b8e06a696e77389d0bc863b8837eceee
2013-08-19 11:02:23 -07:00
Tom Finegan
c5892de23b Fix mkvmuxer::Track::set_uid().
Modifying const variables doesn't work.

Change-Id: Ie1aa9ce1779002973ec93f808ba5e86c569b9df4
2013-08-19 11:01:49 -07:00
Tom Finegan
15a708e416 Add set_uid() to mkvmuxer::Track.
Allow users of libwebm's MKV muxer to control the Track UID. This,
for example, allows creation of tests that rely on checksum comparisons
to verify output from the library.

Change-Id: I8b052e6dd5af734d76122b2a1b6b16382ffba214
2013-08-16 10:58:17 -07:00
Vignesh Venkatasubramanian
8206558561 Handling chunking_ being set to true on repositioning cues.
CopyAndMoveCuesBeforeClusters should return false (fail gracefully)
if chunking_ is set to true.

Change-Id: Idf4d573e3f15b59c25ee0774a7875e5dfda9c02e
2013-06-27 11:30:17 -07:00
Vignesh Venkatasubramanian
d782edd68e Update Segment size if Cues size changes on repositioning
Files created with Segment::CopyAndMoveCuesBeforeClusters can't be parsed by
libwebm because the Segment size was not updated to account for the change
in Cue size. Fixing that.

Change-Id: I993f63e5c279f131cd39c54bee40163da00b8cbd
2013-06-24 11:55:53 -07:00
Vignesh Venkatasubramanian
4ac7b755f4 Repositing Cues before Clusters
A whole new approach to repositioning Cues before Clusters. This
patchset adds a new function CopyAndMoveCuesBeforeClusters to the
Segment class. This function should be called after
Segment::Finalize() to obtain a copy of the same output file with
Cues positioned before the Clusters.

Removing everything else that was added to accomplish the same in
the previous few commits.

Also, adding std:: qualifier to one of the variables in
sample_muxer_metadata which was missed accidentally in the previous
commit.

Change-Id: I2810d06a6251325add2f5e54d32d1da6e2fe143f
2013-06-14 13:01:48 -07:00
Vignesh Venkatasubramanian
09dd90fcc7 Fully qualifiying usage of std::string
Replacing "using std::string" with fully qualified namespace on
each occurance of string in sample_muxer_metadata.cc and
webvttparser.cc.

Also fixing a formatting nit in mkvwriteeofreader.cpp

Change-Id: Icf713f9e489fbdc9af14e83d0cb7ba2e89e65ab4
2013-06-12 11:23:35 -07:00
Vignesh Venkatasubramanian
54ca052b1c Changing IMkvReadableWriter to IMkvWriteEOFReader
Changing the IMkvReadableWriter interface to IMkvWriteEOFReader.
Also changing the default implementation.

Change-Id: Id37ffd7ef0af2ff7a392fb4fb0b1b134664ab20f
2013-06-11 15:11:18 -07:00
Vignesh Venkatasubramanian
74e5f0fa1d Adding mkvreadablewriter
Adding mkvreadablewriter files which was missed from previous commit.

Change-Id: I84363ca897ebe758a42538c179ad60c2adfe9247
2013-06-03 14:26:20 -07:00
Vignesh Venkatasubramanian
9b42d039ad Support for placing Cues before Clusters
Adding support for placing Cues element before the Cluster element. We
recompute the new offsets using a recursive algorithm and update the Cues and
Seek Heads with the updates offsets.

Change-Id: I038f1a403b1defa853b9026bd3e48f4ad1006866
2013-06-03 10:27:27 -07:00
Vignesh Venkatasubramanian
3f7681d11e Merge "Fixing mistyped element name in mkvmuxerutil" 2013-05-20 17:11:11 -07:00
Vignesh Venkatasubramanian
7a64466954 Fixing mistyped element name in mkvmuxerutil
Replacing correct element name in mkvmuxerutil that was mistyped
in a previous commit.

Change-Id: Ic34f544aeeb124f0950c3f45e7b638d4616f8b86
2013-05-20 16:46:33 -07:00
Vignesh Venkatasubramanian
05912e8a96 Merge "Elements and functions to support BlockAdditional" 2013-05-07 14:17:43 -07:00
Patrik2 Carlsson
a9f43fe8e7 mkvparser: Get frame default duration
Track::GetDefaultDuration is implemented as an alternative
to VideoTrack::GetFrameRate which seems to be deprecated.

Change-Id: I2c7a6d56a232125b8632d87eab75b9600c5451e1
2013-05-02 16:04:34 +02:00
Vignesh Venkatasubramanian
5af56bb9ee Elements and functions to support BlockAdditional
Adding elements and functions to support muxing of BlockAdditional element.
This is required for supporting muxing of streams with Alpha Channel (where the
Alpha data goes into BlockAdditional). Detailed design doc of Alpha Channel can
be found here: http://goo.gl/wCP1y

Change-Id: Idac144d9588de16685734850585ab7115ddd08a4
2013-04-24 16:16:14 -07:00
Frank Galligan
64cee42b85 libwebm: Remove STL dependency from Android build.
Change-Id: Id2f378f2fa8350aae97394bd8b21918cff4d179a
2013-04-15 10:24:34 -07:00
Frank Galligan
d5cb6c7fa4 libwebm: Fix random number generation on Android.
Change-Id: I593561128aaeb5806f8f015e2de3b4c9aa4411fc
2013-04-15 09:27:34 -07:00
Frank Galligan
252bd24950 libwebm: Update Android build
- Change to libwebm.
- Add muxer support.
- Remove sample app.

Change-Id: I39c31ecbff573f86214e85b3ac08e0dcdfe22ae2
2013-04-15 09:13:07 -07:00
Michael Szal
9cb9ee4efa Removed IsOpen because it should not have been there.
Change-Id: I4d5149de362e50a8f15ebfd382e39218ca2ca560
2013-03-29 11:44:28 -07:00
Patrik Carlsson
3af8d02ca1 mkvparser: support seek for generic tracks (subtitles)
To support seek in generic tracks with subtitles the audio track
implementation of seek is made generic and inherited by audio track.

Change-Id: Ic88d2e859d077a1054b2af7d7680cfddfba8a589
2013-02-28 15:47:04 +01:00
Patrik Carlsson
0d5b3fc5ae mkvparser: add support for compression elements
ContentCompression elements are now parsed.

Change-Id: I9a67ae444ed929e49c7ea223a16c13c9d16a4c13
2013-02-28 15:46:58 +01:00
Patrik Carlsson
3980cf4159 mkvparser: read track language information
Track::GetLanguageAsUTF8 is implemented to allow the user to
choose between available audio and subtitle tracks.

Change-Id: I5ec9b1c1c00182da759681ba486cbace46e9b63f
2013-02-27 15:40:33 +01:00
Matthew Heaney
1274be1184 libwebm: fixed compilation error
Change-Id: I2dfa93f3a2470e016ca905caee33c3dceb789b57
2013-01-31 14:13:33 -08:00
Matthew Heaney
43178b4c9a libwebm: fixed rand() on windows
Change-Id: Ie17445072f10f91bdaabfba74a1be58764d78b94
2013-01-24 17:29:23 -08:00
Matthew Heaney
8376a8e9d7 mkvparser: liberalize parsing of bad elements
Normally, if a sub-element of a cluster reports a size
that lies beyond the end of its enclosing cluster, we
would treat this as a malformed stream and immediately
terminate the parse.

However, if the sub-element is not a simple block or block
group, we would ignore the (sub)element anyway, so there
doesn't appear to be any harm in just concontinuing to
ignore the (sub)element, and treating this case as if
we had reached the end-of-cluster in the normal way.

Change-Id: I16c0a44f7458823ed579612d917b09ee08a8d90a
2013-01-10 19:24:21 -08:00
David Schalig
2b09f9b53a mkvparser: ignore 0-size elements in TrackEntry
ParseTrackEntry handled MKVs with 0-sized EBML elements
as malformed. Relaxing this and allow empty elements to allow
parsing such MKV content.

Change-Id: I7e430e9b2d177df7fe1e656546f63ee8673e784e
2012-12-11 17:08:22 +09:00
Matthew Heaney
28222b4927 Add support for WebVTT cue identifier line
Modified the mkvmuxer to write the ChapterStringUID
sub-element of the Chapter Atom element.

Modified the mkvparser to read the ChapterStringUID
sub-element of the chapter atom.

Modified the vttdemux app to write the Cue Identifier
line of the WebVTT cue.

Change-Id: I06fe386f44897ada3fe10cbf89096df104dcf779
2012-11-13 12:44:06 -08:00
Matthew Heaney
0fcf5e5a40 Merge "vttdemux: add support for WebVTT chapters" 2012-11-13 09:38:29 -08:00
Matthew Heaney
c26db03d5a vttdemux: add support for WebVTT chapters
Change-Id: If5e12ff7057ce4217907ef91d493e1bcd8a72656
2012-11-12 11:52:15 -08:00
Frank Galligan
baefebcf1c libwebm: Fix BlockNumber on CuePoint
- libwebm was writing the BlockNumber of the next Block instead
  of the Block that was just written.

Change-Id: I344800fcea919a82d7f0a04a54cf510be3851ec6
2012-11-12 08:35:39 -08:00
Matthew Heaney
386928d8b8 mkvparser: add missing definitions
Change-Id: I043a6d974bdf146a8726d090722159943eb20752
2012-11-08 18:12:30 -08:00
Matthew Heaney
50ee255b8c mkvparser: add support for MKV chapters
Change-Id: I2404b6886ed592fe505ee973bf05c769a9d134b1
2012-11-02 14:42:40 -07:00
Matthew Heaney
ad54bfb572 sample_muxer: added support for WebVTT chapters
Change-Id: Ic5ab8097c0981ef300eadc4a3c151f63b2aad81d
2012-11-02 14:20:43 -07:00
Matthew Heaney
c99838a5fe Merge "mkvmuxer: add support for WebVTT chapters" 2012-10-31 18:03:59 -07:00
Matthew Heaney
2c5836837e mkvmuxer: add support for WebVTT chapters
Change-Id: I469ce3bd79a9b50b82e00ac8c63fc3d1db220887
2012-10-30 17:07:38 -07:00
Frank Galligan
50afbea946 muxer: Add support to force Cluster placement.
Change-Id: I7d4653561ca760885ba6926825ba6b80cdbea8ab
2012-10-29 09:24:41 -07:00
Matthew Heaney
25ee621061 mkvmuxer: add MakeUID utility function
Change-Id: I3fb57438767ddcc8f9e17c050d494f48ff203e58
2012-10-22 16:50:48 -07:00
Matthew Heaney
ac238c0c5c webvttparser: check intermediate values while parsing int
Change-Id: I145529097246f75c27ff2d29cf091416ba1c437d
2012-10-16 11:32:42 -07:00
Matthew Heaney
4a5141344e vttdemux: initial revision
vttdemux is a tool for demuxing a webm file containing
WebVTT metadata tracks, extracting the embedded metadata
from each track and storing it as a standalone WebVTT file.

Change-Id: I8897b3dc502c49c92f5b79925939baa5a9490aaa
2012-10-12 11:00:24 -07:00
Matthew Heaney
2fc496a0d6 mkvparser: create generic track objects
Formerly, it was only possible to create instances of
the Track subclasses, VideoTrack and AudioTrack.  However,
we now populate WebM files with WebVTT metadata blocks,
so we must allow for a third kind of track object.

We now enable instances of type Track to be created,
by providing a new factory function, Track::Create, and
making all Track methods non-pure and with a generic
implementation.

Change-Id: I7d4c965eb566b9fc2f5ceefe1d43723cf8c1e5f0
2012-10-10 16:51:21 -07:00
Matthew Heaney
cb8899a920 sample_muxer: clean-up to conform to style guide
Change-Id: I77a4657d71359777a8f55f40346014f90051e02d
2012-10-08 12:52:55 -07:00
Matthew Heaney
49078292b4 webvttparser: added LineReader class
Previously the Parser class had an internal function to parse
the character stream into separate lines.  This functionality
was separated out into its own class, LineReader, in order
to make this functionality available to clients too.

Change-Id: Ic5a1b0b73d7a253cf21cb6b4804b4941fd69c8ab
2012-10-02 18:14:51 -07:00
Matthew Heaney
4f494f6dd4 mkvparser: implemented BlockGroup::GetDuration method
Change-Id: Ib0106df3823c29e45a8fe59669c0fa65dd13a123
2012-09-28 14:55:24 -07:00
Matthew Heaney
7ef225de9f sample_muxer: added WebVTT support
Change-Id: If72d31ca4828adf39e4637003979a314e5dda98e
2012-09-28 10:38:19 -07:00
Frank Galligan
8f0c3333d1 Merge "mkvparser: Version 1.0.0.26 mkvmuxer: Version 0.2.0.0" 2012-09-27 10:06:58 -07:00
Frank Galligan
bf664baf05 mkvparser: Version 1.0.0.26 mkvmuxer: Version 0.2.0.0
Change-Id: I6875b1c10adea41c45762d82b7dd2f9551f5b7ca
2012-09-27 09:56:24 -07:00
James Zern
232bae0d50 Merge "Added a rule to the Makefile to build libwebm as a shared library." 2012-09-26 13:37:17 -07:00
Michael Szal
69c9348f07 Added a rule to the Makefile to build libwebm as a shared
library.

I'm building two different object files now: the ones for
libwebm.a are compiled normally (*_a.o), and the ones for
libwebm.so are compiled with -fPIC and linked with -shared
(*_so.o).

Change-Id: I76471ab225a006c7e169bc0d69df9a0731ff6681
2012-09-26 13:15:10 -07:00
Matthew Heaney
711af0c505 mkvmuxer: add operations for muxing metadata
Change-Id: Ia17166ee9133b4841f7d206aa7d5ec81f800e994
2012-09-24 12:13:45 -07:00
Matthew Heaney
38173f9d49 add operation to add generic track
Change-Id: I34e4ab14c0a5b022b77b98d9403125550024e730
2012-09-21 16:37:30 -07:00
Frank Galligan
21a2bd14c7 Make AddCuePoint function public.
Change-Id: I08df2b604185d6ae1d63eb360e68e84efa2cebfa
2012-09-21 16:21:03 -07:00
Frank Galligan
9ec562f72d Add Track number to AddCuePoint function.
Change-Id: I67fd8db3d436f8931f5d50deeb1f1d41cfdc0836
2012-09-21 15:42:57 -07:00
Frank Galligan
e6e2b6b387 Merge "Fix set_writing_app." 2012-09-21 14:08:43 -07:00
Frank Galligan
a2ca300513 Merge "mkvmuxer: default track_num to 0 in AddTrack" 2012-09-21 14:08:08 -07:00
Frank Galligan
6cf00207c0 Fix set_writing_app.
Change-Id: Idbb0522b10184072802be710088f0ec0bf008277
2012-09-21 12:20:43 -07:00
Frank Galligan
4df02ce68b libwebm: Add support for setting muxing app.
Change-Id: I78f4d08142aeeaacf5f9c175bab6a4993b917b1b
2012-09-21 12:17:03 -07:00
Matthew Heaney
4ffb162798 mkvmuxer: default track_num to 0 in AddTrack
Change-Id: I484cb56df7be7677a821db262c75cf8bdf1d30af
2012-09-21 11:55:47 -07:00
Matthew Heaney
76d9cf9cf4 mkvmuxer: handle large gaps in frame timestamps
Change-Id: If223a03cc37f2f373893c914e417475f62949717
2012-09-20 14:58:45 -07:00
Frank Galligan
20f64ff979 Merge "Fix incremental parsing in CreateInstance" 2012-09-14 11:18:27 -07:00
Frank Galligan
537da82f37 Fix incremental parsing in CreateInstance
- Segment::CreateInstance was treating the available data as EOF
  and returning errors.
- Added a check for potential underflow if the segment was not the
  first element after the EBML header.

Change-Id: I481bf0eea71eeb3def3bf54ec251be0b2ae13536
2012-09-14 11:05:18 -07:00
Matthew Heaney
db20aaa2b1 mkvmuxer: refactored code that creates a new cluster
Change-Id: I5db03b0e1ea23f45820dd47b7be9e4b0422f3e6a
2012-09-14 10:17:09 -07:00
Matthew Heaney
c9e284b9e7 refactor code to make a new cluster
Change-Id: Ifa7938134494e3524d6479bd026aea6d1b309d52
2012-09-13 10:15:59 -07:00
Matthew Heaney
07ac1947f0 Change return type of Segment::WriteFramesAll()
Change-Id: I7fb45f1779c384bcc1cdea507f1f2f51c28dd827
2012-09-12 10:29:40 -07:00
Matthew Heaney
0edf087bbb Refactor Cluster::AddFrame member function
Change-Id: Ibff460918243647eb76785508bb50490bc1d8561
2012-09-11 14:58:56 -07:00
Matthew Heaney
c425e965aa add operation to write metadata block
Change-Id: I08f6c7f71dbc9b0d9ce15c08cf288f4918b2c22a
2012-09-05 15:44:45 -07:00
Matthew Heaney
ed6282b2d6 webvttparser more closely conforms to style rules
A few adjustments we made such that the webvttparser
now conforms more closely to the Google C++ style guide.

Change-Id: Iefb2242678ceea6ab5b9daa3a046980deb6cd91c
2012-08-30 15:24:20 -07:00
Matthew Heaney
282a67599c added dumpvtt app
Change-Id: I9eba00412bbd05641dafd1a6cfc4656bda8bb8c2
2012-08-23 14:00:57 -07:00
Matthew Heaney
adebb53754 added webvtt parser
Change-Id: Icef6d484e8fe6e2c63dc69ab02b6ab37ffcabbd8
2012-08-16 16:39:07 -07:00
Frank Galligan
a320f5be63 Add CTR encryption.
- Added ContentEncAESSettings, AESSettingsCipherMode,
  AESSettingsCipherInitData elements to the parser and muxer.
- Changed ParseContentEncodingsEntry, ParseContentEncodingEntry,
  and ParseEncryptionEntry to use PasreElementHeader.
- Added ParseContentEncAESSettingsEntry function.
- PS6 removed AESSettingsCipherInitData.
- PS9 Addressed comments, Fixed some LINT issues, and converted
  mkvwriter.h/.cpp to Unix line endings.
- PS10 Addressed comments.

Change-Id: I9d96a0c194f74a6c9bf0001aa0286196e410f07e
2012-07-27 09:34:31 -07:00
Frank Galligan
c4d2b27b7a Add support for DLL configurations.
- Added "Release DLL" which uses /MTd and "Debug DLL" which
  uses /MDd.

Change-Id: Ibdaf58995e5ee94c34d52ece64e2f8f01524e9cd
2012-07-25 08:41:01 -07:00
Frank Galligan
13a90600ea Muxer fix for chunking file names on Linux.
Change-Id: Ica2dbfc7af64a83fc8f08d35196eabf1dd69f2f0
2012-07-12 08:01:55 -07:00
matthewjheaney
478b524df3 version 1.0.0.25
Change-Id: I438d43572f450bb6e151d4a1ede077ff22252d1f
2012-05-30 15:42:33 -04:00
Tom Finegan
010a457bc9 Add Visual Studio 2010 projects and solution.
Change-Id: I6387f1e6d68b05b8f605f155784c1025f85c1a5b
2012-05-30 14:18:23 -04:00
Tom Finegan
47a09523b2 Ignore visual studio 2010 temporary files.
Change-Id: I18d214b5ba032ff71af2fa67e72a92715636513c
2012-05-30 14:18:22 -04:00
Tom Finegan
84bf4a41dc Move build output outside the repository directory.
Change vs2008 output and intermediate directories to:
1. Avoid build output collisions when using vs2008 and vs2010 on the
   same system (makes no difference until subsequent commit adding
   vs2010 support).
2. Keep the tree clean.

Change-Id: Ie819e57421b7df90244eebffc0f5e608bc135930
2012-05-30 14:18:22 -04:00
Tom Finegan
177df33d25 Move the muxer sample source file and project.
They now reside in the same place as the parser sample.

Change-Id: Idb4471ea81a3d91eeeaf1b36053187203de9a21f
2012-05-30 14:18:08 -04:00
Tom Finegan
4fff53441d Remove visual studio 2005 projects and solution.
Change-Id: I1d4d8cffeb8997eee415246753ea3c29c1af45ec
2012-05-30 11:36:31 -04:00
Tom Finegan
ca13a5bae0 Rename sample_muxer.vcproj to sample_muxer_2008.vcproj.
Also update the solution file path to the project.

Change-Id: I7e83b99893bcde5429e6de03772c61369b29d332
2012-05-29 10:55:00 -04:00
Tom Finegan
cb69e608b4 Enable auto CRLF for visual studio project and solution files.
Change-Id: I23ca85442173eec7a144c001080ca8a3b41609f3
2012-05-29 10:45:59 -04:00
Tom Finegan
f6b0408aba Use LF as EoL in visual studio solutions and projects.
Makes files easier to read in gitweb, and prevents conflict with
upcoming .gitattributes change.

Change-Id: I185e496d8df8efb4987bfb848a582f7d0da81fb8
2012-05-29 10:43:40 -04:00
matthewjheaney
9a561ab4dd libwebm: handle negative time for a block
Change-Id: Iafa0254fb1554621b42635cb99d40b2c0177468f
2012-05-11 11:53:23 -04:00
Frank Galligan
0568dd63a6 Memory Leak Fix in Muxer.
- Track language_ and name_ member variables were not properly
  deleted.
- http://code.google.com/p/webm/issues/detail?id=416

Change-Id: Id0da669c347270cd355ad0b5e1e45ebf6415e367
2012-04-17 15:28:28 -04:00
Frank Galligan
56488f73ef Merge "sample_muxer: Fixed bug with outputting audio cues." 2012-03-16 08:06:54 -07:00
Frank Galligan
f270ddaeb8 sample_muxer: Fixed bug with outputting audio cues.
- For muxed content with default settings the cues was getting
  output on the audio track when it should be on the video track
  by default.
- Added check to command line parameter parsing to make sure
  there are enough parameters.
- If Cues are set to output on one type of track the other type
  is now disabled.

Change-Id: I96ef1978dc3f442f34364f6dee6cfb01571c7289
2012-03-16 09:26:28 -04:00
matthewjheaney
041a5c5811 Parse headers outside of constructor
In several cases, the parser would parse a header
(say, a track header, or the segment info header)
in the constructor for the type.  The parser had
assumed (incorrectly) that the file was well-formed,
but this turned out to be an incorrect assumption.

The parse errors triggered some assertion failures,
but this is not acceptable in a production system.

The parser solved that problem by separating the
construction of the header object from the parsing
of the file.  There is now a separate parse method
to be called after construction of the object,
which returns a status whether the parse was
successful.

This change fixes the bugs from the following
tracker issues:

http://code.google.com/p/webm/issues/detail?id=399
http://code.google.com/p/webm/issues/detail?id=400

Change-Id: Idb09154ae7008429d8613ce3b3e8294f5a12de86
2012-03-13 14:40:17 -04:00
matthewjheaney
6fa7c7611c Block parsing is now robust
Previously, parsing of a Block element was done inside its
constructor.  Parsing errors were handled via assertion checks,
but this only works in practice if there are no actual errors
in the file.

We did come across a file, however, that used EMBL-style lacing,
but the lacing was done incorrectly and so the parse asserted.
This isn't acceptable for a production system, and more a graceful
handling of parse errors was needed.

The code was restructured such that the Block object's ctor does
only trivial initialization of member variables.  A separate Parse
method was added, that is called after the object is constructed.
If the parse succeeds all is well, otherwise the object is destroyed
and the error is reported to the caller.

This commit fixes bug tracker issue #398, described here:

http://code.google.com/p/webm/issues/detail?id=398

Change-Id: Ib95ca95d0eec08cf670b308c461e42ed8345e890
2012-02-28 14:03:21 -05:00
matthewjheaney
71d296e44c Merge "mkvparser: overflow in biased count of laced frames" 2012-02-23 18:07:34 -08:00
matthewjheaney
72052ed8b1 mkvparser: overflow in biased count of laced frames
Change-Id: I946b233d559186fc8a24d0769607075333598191
2012-02-23 13:33:46 -05:00
Frank Galligan
a88d62b682 Fix muxer output with no Cues.
- Fixed a bug with the muxer where it would generate a entry in
  the SeekHead for a Cues element with OutputCues set to false.
- Fixed a bug with the muxer where it would generate an empty
  Cues element with OutputCues set to false.
- Issue:http://code.google.com/p/webm/issues/detail?id=383

Change-Id: I99cc404a7e8ad61759dbb57ab769625dd724240c
2012-02-16 16:34:59 -05:00
Frank Galligan
28d54555a7 Fix for audio and video track size calculation.
- There was a bug where the calculation for the audio and video
track size where the code would calculate the size of the track
elements minus the size of the audio or video elements. If the
coded size of the track elements was one byte smaller than with
the audio or video elements then the muxer would return an
error.
- Fixed another issue that the track's virtual Size function was
calling the Track's PayloadSize function where it should have
been calling the virtual PayloadSize function.

Change-Id: Ie6d66d6d720334180a11e06926a3bd8c7788a1f1
2012-01-25 13:23:40 -05:00
Frank Galligan
359b3654ad Merge "Fix bug with calculating master element sizes." 2012-01-25 10:01:39 -08:00
Frank Galligan
000944c4e4 Fix bug with calculating master element sizes.
There was a potential bug with calculating the size of a master
element. The size was being calculated with a straight unsigned
integer when it should have been calculated with a coded
integer.

Change-Id: I68422ecdb7818af51ded2953a8914fcdc8858f7a
2012-01-25 10:28:26 -05:00
Tom Finegan
8da8206fa0 mkvmuxer: Use WriteID for all element IDs.
Fixes reliability issue with IMkvWriter::ElementStartNotify: the
cluster and segment IDs were being written with SerializeInt instead
of WriteID.

Also:
- Remove completed TODO.
- Fix method declaration order in MkvWriter.

Change-Id: Ie37e141169af6e0ca7d931cc39f001722e7b9078
2012-01-23 16:42:03 -05:00
Tom Finegan
7a9a72f984 mkvmuxer: Disallow non-monotonically increasing timestamps.
Segment::AddFrame will now return false (fail) when a non-monotonically
increasing timestamp value is passed to the method.

Change-Id: Icfac093e6bddf18e3ef252df79e35c33dbe1e134
2012-01-20 15:59:38 -05:00
Tom Finegan
d2327e2b65 sample_muxer: Cosmetics.
- Fix return values; use EXIT_FAILURE and EXIT_SUCCESS
  instead of -1 and 0.
- Use C++ versions of C library includes.

Change-Id: Ib3a36e799d6a91b7fea0f328480e977ef21ca260
2012-01-19 20:21:36 -05:00
Tom Finegan
1e37a264f1 mkvmuxer: Add element start notification.
Just before the first byte of an element identifier is written
the muxer calls IMkvWriter::ElementStartNotify to report the
position of the element in the WebM stream.

Change-Id: Iac40090587bd9496b05f41203aace00902f5606e
2012-01-19 20:21:35 -05:00
Tom Finegan
01d5924817 mkvmuxer: Cosmetics.
- Use c++ versions of C library includes.
- Make Segment::~Segment non-virtual.

Change-Id: I868c1f3769b5a87362efe99383cca880586b57f3
2012-01-19 20:21:35 -05:00
Tom Finegan
a20f4255c7 mkvmuxer: Return errors instead of using assert.
NDEBUG is defined in our release build, which allowed for misuse of
the library by users that would result in dereferencing NULL
MkvWriter pointers in various places throughout the muxer code.

Change-Id: I6ab51453ef26786ca988310c051bb49db16ecbc5
2012-01-19 20:21:30 -05:00
Tom Finegan
69df730519 mkvmuxer: Add Init method to Cluster and Segment.
Remove asserts on the MkvWriter pointer in each constructor,
and assign the pointer in each Init method. Update Segment::Init
usage site in sample_muxer.

Change-Id: Id940f76b50dc15603742e76afc04cdffe0ec4990
2012-01-19 20:21:25 -05:00
Tom Finegan
f7aa8ab33d Merge "Add output of elements to separate files." 2012-01-18 13:54:56 -08:00
Frank Galligan
73ad7bd83c Add output of elements to separate files.
Support outputting header, clusters, and cues to separate files.

Change-Id: Ia89bf59ddbddc094c3daf944123fd01630ae9193
2012-01-18 16:02:43 -05:00
matthewjheaney
4c682199b0 mkvparser: cache SeekEntry start and size
Change-Id: I54a0ac4035f7174f51ae2145dedb1c3ed5ad7ec8
2011-12-08 16:07:15 -05:00
matthewjheaney
9303667611 parse void elements in seek head
Change-Id: Ifc8841909f6aa877108abebb5b5623c2344d0e35
2011-11-17 19:08:48 -05:00
Frank Galligan
4affedd0a7 Add support for encryption elements.
Added support for the ContentEncoding element to be added to a
Track element for muxing. Currently only one ContentEncoding may
be added. The ContentEncoding must be encryption of the whole
frame with AES.
Added support for parsing the ConentEncoding elements. Currently
the parser does not parse any ContentCompression elements.

Change-Id: Ie199116a1bcc18a0c2b5eea3dba6622887c108c8
2011-11-04 14:09:56 -04:00
Frank Galligan
23808a7ba4 Switch AddFrame parameter to const.
Change-Id: I4ae4ac3a57f91eb19a7bb1b1d1c63fe64128efe2
2011-10-27 13:21:04 -04:00
Frank Galligan
32227e70c1 Fix for writing audio to first cluster.
If the muxer had audio frames that were earlier in time than the
first video frame then the first cluster would not be initialized
in time to write out the first audio frames.

Change-Id: I6a2ca25a25c326a4215c307bdae666db9107e9b5
2011-09-13 11:41:15 -04:00
Frank Galligan
2d3461b4b3 Add support for setting track numbers.
When adding tracks to the muxer the application can set the
track number.

Change-Id: Id4dbbfec5cd541b1354c03361a40a3d2d7f921b9
2011-08-15 15:29:20 -04:00
Frank Galligan
a09f15f00e Better support for audio only webm files.
Changed max_cluster_duration to 30 seconds so default command line
will not crash on audio only WebM files. Added support to the sample
muxer to output cues on the audio track. Created a muxer helper
function to clean up the code a little.

Change-Id: I2871836b64cef7defd10aa51a209b4abd9046832
2011-08-14 10:49:50 -04:00
Tom Finegan
6d99850e7c Build muxer and parser into a single library.
Makefile:
- Add a new target that makes a single libwebm.a instead of building
separate muxer and parser libraries.
- Update sample targets accordingly.

Visual Studio:
- Use a single project for muxing and parsing, and build a single library
name libwebm.lib.
- Update code generation settings (DLL -> static runtimes).
- Use C7 debug information format (instead of PDB)
- Disable minimal rebuild (C7 use causes warning otherwise).

Change-Id: Ie221d4ee02c93f98f2521757c08b75ecbf75f54f
2011-08-11 17:19:45 -04:00
matthewjheaney
1ae4335c1c libwebm: liberalize handling of reference blocks
Change-Id: I3df0235e005c57507eb974ad3754b4c800a99825
2011-08-09 16:03:50 -04:00
Frank Galligan
52f0a92192 Added const to some pointers.
Updated some long assignment statements to indent 4 per the
coding guide. Added explicit calls to Close on the reader and
writer objects.

Change-Id: I149326c3a07543d7eb9323c702cf13852c5bc3c2
2011-07-18 14:28:12 -04:00
Frank Galligan
6ebe4a39df Merge "Add support for muxing to libwebm." 2011-07-18 08:09:34 -07:00
Frank Galligan
a3dd40877d Add support for muxing to libwebm.
Squashed commit of the following:

9f73b86 Updated code to Google C++ style guide.
8580901 Added support for linux.
fd0b59c Fixed segment size issue.
d51d5ef Added more Track and Video options.
0fc73fd Fixed issue where cue point was being written out on wrong
        track.
fcfdd07 Updated sample_muxer to read in a webm and output a webm file.
        Added some options to sample_muxer. Fixed writing out unknown
        size.
285c558 Added support for muxer guideline "Audio that matches video key
        frame should be in the same cluster." Added support for
        block_number in cue points. Added support for setting max
        cluster size.
f956dec Add support for setting the max duration for all clusters.
92ca53e Add support for Cues element.
d6b4cba Added typedefs for unsigned long long, long long, and unsigned
        char. Reformated some code.
1b1f8b2 Added support for SeekHead element. Added WriteVoidElement
        function.
8faa187 Add support for CodecPrivate. Add support for updating
        SegmentInfo duration. Add support for updating Segment size.
        Added new sample that swicthes the tracks.
1dd3555 Refactored some code. Check to see if track is a video track if
        starting a new cluster on a key-frame.
1bc8374 Refacotrs code so Cluster is in charge of wirting out its own
        data.
836cd74 Added basic cluster and simple_block support for writing frames.
cc48cc2 Add simple support for Audio tracks.
4efd614 Added support for using the encoded ID value for the elements.
fb8b5a6 Initial commit of libwebm muxer.

Removed switch_sample project. Fixed initialization order warnings on
Linux. Reformatted code to follow Google C++ style guide. Fixed Makefile.
Removed tester.cpp.

Change-Id: I4857042f804edb834be52787a7d5ccdd578b7275
2011-07-15 17:30:27 -04:00
James Zern
1623fb983b mkvparser: silence initializer list warnings
Ensure initializer lists match declaration order, from gcc -Wreorder.

Change-Id: I9ba245ab9c28d89978cdfe3865edcb54da2e949c
2011-07-14 10:30:47 -07:00
Frank Galligan
18ac83d501 Add default mkvreader object to mkvparser namespace. Add mkvreader
object to linux and mac libmkvparser.a.

Change-Id: Ibb94e8dee9a3a897bcda925916c5713cb45d35fe
2011-06-06 13:08:08 -04:00
Joel Dice
5942099a85 fix warnings when building with gcc -Wall -Wextra
This commit addresses three types of warnings:

 * constructor initialization order inconsistencies
 * statements with no effect
 * possible use of uninitialized fields

Change-Id: I572ccdc6813d8cfeff3e9e06d7acf6a8ab5ac7b1
2011-05-09 16:34:40 -04:00
matthewjheaney
9ecedef185 libwebm: include <cstddef>
Change-Id: Ieba2507dd82b34558ffef4febb6f80225009cc30
2011-05-03 15:48:13 -04:00
matthewjheaney
6f68021678 libwebm: re-implemented Block::EOS()
Change-Id: I91c6746d3e06e2f74dc899dbeec5c5270e150d08
2011-04-07 19:36:15 -07:00
matthewjheaney
3395c36a8e libwebm: added UnserializeInt function
Change-Id: I2298e547cd38d3aea04c0c993a67e5e291b8fea8
2011-04-05 20:55:26 -07:00
matthewjheaney
ffe5a8e548 libwebm: added GetLacing selector function for Block
Change-Id: I77bff875919f7a57a8c838beb05bc9a992cadacd
2011-04-05 20:55:25 -07:00
matthewjheaney
a9c65fbbc0 libwebm: added BlockEntry::GetKind op
Change-Id: I7d7daac0d3b8be1b8839f96503250170f675e34d
2011-04-05 20:55:24 -07:00
matthewjheaney
31a9d5470e libwebm: don't alloc block object in block group
Change-Id: I55ff9451591da86b89ed58c22eb9778317b89364
2011-04-05 20:55:23 -07:00
matthewjheaney
2b84a12da8 libwebm: removed old Cluster::Load
Change-Id: I02448e6c9d5850368282353dba40a549753c26bc
2011-04-05 20:55:22 -07:00
matthewjheaney
bd833a82e4 libwebm: removed old LoadBlockEntries
Change-Id: I340f444f719fa9c5d9da986f1527522d8a5f9812
2011-04-05 20:55:21 -07:00
matthewjheaney
7b07758854 libwebm: refactor BlockEntry class
Change-Id: I68d799d5b928de0ff7be293731ab73750c7cbb86
2011-04-05 20:55:20 -07:00
matthewjheaney
00ed87aad6 libwebm: Block::GetIndex returns type long
Change-Id: I7b233a18b5054398ae22696148ede17817ea608a
2011-04-05 20:55:11 -07:00
matthewjheaney
06f08663be libwebm: Block::GetTimeCode allows NULL param
Change-Id: Ia62820637f1819d1904d2e6e7b20bd3c39053bb5
2011-04-05 20:54:14 -07:00
matthewjheaney
35ded77a23 libwebm: change version to 1.0.0.21
Change-Id: Ic8ef4e8f02a3dc5b07939f0b09903d31dc4a403f
2011-03-28 13:04:26 -04:00
matthewjheaney
1f33611caa libwebm: bad assert in Cluster::GetEntry
Change-Id: I5bcee1f496260416b438a1c2632dd24e8b26eee4
2011-03-22 14:18:14 -04:00
matthewjheaney
70f9644a8d libwebm: restored Cluster::GetLast
Change-Id: I73564fb508e23004392b5aaab1f1ad7cdedc8bb1
2011-03-19 10:34:12 -04:00
matthewjheaney
f2bd78ef6b libwebm: changed semantics of LoadCuePoint retval
Change-Id: Iabbc82b24bde27c06b44b9f9f45e64215b9164c5
2011-03-19 09:54:41 -04:00
matthewjheaney
2083c72300 libwebm: removed LoadBlockEntries
Change-Id: I1d65c07d91de568573f48e9fddf83b4c5672871d
2011-03-18 21:43:06 -04:00
matthewjheaney
f5ec272e54 libwebm: removed Cluster::Load (non-incremental)
Change-Id: I1f2ad153e0c643d04fa1fe1ec85410bbef1954ef
2011-03-18 11:18:46 -04:00
matthewjheaney
b324e52139 libwebm: handle truncated segment
Change-Id: Iddd15a207bce4a2c26f72e5e35f736c1b3f700d7
2011-03-16 15:08:06 -04:00
matthewjheaney
4137f9c999 libwebm: v1.0.0.20
Change-Id: I8a93517762c0edecd59a38e2f4fc99566c7b2de5
2011-03-15 14:27:53 -04:00
matthewjheaney
ba4096f120 libwebm: fixed bug in LoadBlockEntries
Change-Id: I4a0870030803bcbb5502800ae5627f716d417440
2011-03-10 15:12:16 -05:00
matthewjheaney
365a39b5ec libwebm: set version to v1.0.0.19
Change-Id: I5e88dce1c52bc18bdab2063111830b5fbd0faafe
2011-03-09 11:04:21 -05:00
matthewjheaney
601f7903a3 libwebm: block group must parse ref times too
Change-Id: Iadf7674dfaf311e04f2eea35fc396e2eaab18163
2011-03-08 21:51:13 -05:00
matthewjheaney
16b2cdaf57 libwebm: changed to version v1.0.0.18
Change-Id: I9f0f0c25fca48cfe18fd16c332bf21265bfef204
2011-03-08 13:13:07 -05:00
matthewjheaney
ca1e6b7323 libwebm: defend against truncated stream
Change-Id: I3fb983f9601ac133752fbbdb8bb8b179b18d14fb
2011-03-08 12:25:26 -05:00
matthewjheaney
c226b79e61 libwebm: safer way to handle truncated cluster
Change-Id: Ifa9df95fedee14846835c16942a80735e7f3c0ed
2011-03-07 23:44:47 -05:00
matthewjheaney
dc8bdb3389 libwebm: handle EOF in ParseNext
Change-Id: I1d93fca0c6ad259e76b79bdba8bb0debdd96bd94
2011-03-07 22:40:00 -05:00
matthewjheaney
31b2d8689c libwebm: parse unkown cluster size
Change-Id: I74f7f552185aafaa4466556644e95c3a25063a08
2011-03-07 21:11:57 -05:00
matthewjheaney
227d62aadf libwebm: changed type from size_t to long
Change-Id: I5a684628119877a2f89116b760a1c7e41716748d
2011-03-02 19:05:28 -05:00
matthewjheaney
85beb00fe3 libwebm: changed idx from size_t to long
Change-Id: I7ea9637ab3c55d7535fe9f2fe11fe88f4d47e474
2011-03-02 18:21:21 -05:00
matthewjheaney
eb4bd69098 libwebm: do not lazy-load cue points
Change-Id: I07646f1942d1f473f051ff8ab0aa07b2f4381d4c
2011-02-26 16:59:42 -05:00
matthewjheaney
cf36dc2848 libwebm: added Cues::GetCount
Change-Id: I5b2bca8fd7229318783d9b97c50a4e20ce2ba640
2011-02-26 11:50:23 -05:00
matthewjheaney
b0465e167e libwebm: audio track channel count defaults to 1
Change-Id: Id12bec611bd34f299235a278738f3b55cf5a36c5
2011-02-23 13:15:37 -05:00
matthewjheaney
a1aa16692a libwebm: added support for incremental cluster parsing
Change-Id: Idb1bd292a01b7c9971967760ad016691ac628c29
2011-02-22 11:51:23 -05:00
matthewjheaney
f971a94349 changed version to 1.0.0.17
Change-Id: I213e1279a25d8b7830e635434723b4770d31662c
2011-02-14 15:31:38 -05:00
matthewjheaney
5ac9764a95 libwebm: liberalized parsing of next cluster
Change-Id: I166ecfb5a76d475b77c3e418c4ae91195ff58d32
2011-02-13 19:00:31 -05:00
matthewjheaney
d82f86a40a libwebm: handle underflow from IMkvReader::Read
Change-Id: I8bb0ed53b7bfdde6c0ed24665591f95d7cf43083
2011-02-10 20:42:52 -05:00
matthewjheaney
a1736157be libwebm: handle unknown cluster size in Segment::Load too
Change-Id: I7ed5feb7fe29cd413c8de35274138605725c5b38
2011-02-10 14:41:54 -05:00
matthewjheaney
2c835bcc28 libwebm: handle (as error) cluster with unknown size
Change-Id: I8342d50d0482d77cb895ae659568016eb48ed2be
2011-02-10 13:32:40 -05:00
matthewjheaney
d931a6ecc6 libwebm: set version to 1.0.0.16
Change-Id: Id8f9d8a5d1aa50545c403eb9da04f62347b4604f
2011-02-01 18:49:47 -08:00
matthewjheaney
7a8b013f16 libwebm: handle unknown file length
Change-Id: I6ad22ce302e40a4ec882b4f9ac59d5ca7f6489d7
2011-02-01 16:29:02 -08:00
matthewjheaney
a977a2b536 libwebm: changed version to 1.0.0.15
Change-Id: I70c6b22d75defcb11fecbbcd8763659cca7f77e0
2011-01-28 16:56:27 -05:00
matthewjheaney
5e72a2dfc2 libwebm: changed signature of CuePoint::GetTime
Change-Id: Ia80da8af5607c7067e848bafd453842cfe8cfcca
2011-01-28 00:52:13 -05:00
43 changed files with 19530 additions and 8431 deletions

53
.clang-format Normal file
View File

@@ -0,0 +1,53 @@
---
Language: Cpp
# BasedOnStyle: Google
AccessModifierOffset: -1
ConstructorInitializerIndentWidth: 4
AlignEscapedNewlinesLeft: true
AlignTrailingComments: false
AllowAllParametersOfDeclarationOnNextLine: true
AllowShortIfStatementsOnASingleLine: false
AllowShortLoopsOnASingleLine: false
AllowShortFunctionsOnASingleLine: true
AlwaysBreakTemplateDeclarations: true
AlwaysBreakBeforeMultilineStrings: true
BreakBeforeBinaryOperators: false
BreakBeforeTernaryOperators: false
BreakConstructorInitializersBeforeComma: false
BinPackParameters: true
ColumnLimit: 80
ConstructorInitializerAllOnOneLineOrOnePerLine: true
DerivePointerBinding: true
ExperimentalAutoDetectBinPacking: false
IndentCaseLabels: true
MaxEmptyLinesToKeep: 1
KeepEmptyLinesAtTheStartOfBlocks: false
NamespaceIndentation: None
ObjCSpaceAfterProperty: false
ObjCSpaceBeforeProtocolList: false
PenaltyBreakBeforeFirstCallParameter: 1
PenaltyBreakComment: 300
PenaltyBreakString: 1000
PenaltyBreakFirstLessLess: 120
PenaltyExcessCharacter: 1000000
PenaltyReturnTypeOnItsOwnLine: 200
PointerBindsToType: true
SpacesBeforeTrailingComments: 2
Cpp11BracedListStyle: true
Standard: Auto
IndentWidth: 2
TabWidth: 8
UseTab: Never
BreakBeforeBraces: Attach
IndentFunctionDeclarationAfterType: true
SpacesInParentheses: false
SpacesInAngles: false
SpaceInEmptyParentheses: false
SpacesInCStyleCastParentheses: false
SpacesInContainerLiterals: true
SpaceBeforeAssignmentOperators: true
ContinuationIndentWidth: 4
CommentPragmas: '^ IWYU pragma:'
SpaceBeforeParens: ControlStatements
...

4
.gitattributes vendored Normal file
View File

@@ -0,0 +1,4 @@
*.sln eol=crlf
*.vcproj eol=crlf
*.vsprops eol=crlf
*.vcxproj eol=crlf

14
.gitignore vendored
View File

@@ -2,6 +2,7 @@
*.MKV
core
*.a
*.d
*.so*
*.o
*~
@@ -12,4 +13,15 @@ core
*.exe
*.webm
Debug
Release
Release
*.sdf
*.opensdf
ipch
dumpvtt
sample
sample_muxer
vttdemux
Makefile
CMakeFiles
CMakeCache.txt
*.cmake

View File

@@ -1,13 +1,10 @@
LOCAL_PATH:= $(call my-dir)
include $(CLEAR_VARS)
LOCAL_MODULE:= libmkvparser
LOCAL_MODULE:= libwebm
LOCAL_SRC_FILES:= mkvparser.cpp \
mkvreader.cpp
mkvreader.cpp \
mkvmuxer.cpp \
mkvmuxerutil.cpp \
mkvwriter.cpp
include $(BUILD_STATIC_LIBRARY)
include $(CLEAR_VARS)
LOCAL_MODULE:= mkvparser
LOCAL_SRC_FILES:= sample.cpp
LOCAL_STATIC_LIBRARIES:= libmkvparser
include $(BUILD_EXECUTABLE)

64
CMakeLists.txt Normal file
View File

@@ -0,0 +1,64 @@
## Copyright (c) 2015 The WebM project authors. All Rights Reserved.
##
## Use of this source code is governed by a BSD-style license
## that can be found in the LICENSE file in the root of the source
## tree. An additional intellectual property rights grant can be found
## in the file PATENTS. All contributing project authors may
## be found in the AUTHORS file in the root of the source tree.
cmake_minimum_required(VERSION 2.8)
project(LIBWEBM)
include("${CMAKE_CURRENT_SOURCE_DIR}/build/msvc_runtime.cmake")
set(LIBWEBM_SRC_DIR "${CMAKE_CURRENT_SOURCE_DIR}")
# Libwebm section.
add_library(webm STATIC
"${LIBWEBM_SRC_DIR}/mkvmuxer.cpp"
"${LIBWEBM_SRC_DIR}/mkvmuxer.hpp"
"${LIBWEBM_SRC_DIR}/mkvmuxertypes.hpp"
"${LIBWEBM_SRC_DIR}/mkvmuxerutil.cpp"
"${LIBWEBM_SRC_DIR}/mkvmuxerutil.hpp"
"${LIBWEBM_SRC_DIR}/mkvparser.cpp"
"${LIBWEBM_SRC_DIR}/mkvparser.hpp"
"${LIBWEBM_SRC_DIR}/mkvreader.cpp"
"${LIBWEBM_SRC_DIR}/mkvreader.hpp"
"${LIBWEBM_SRC_DIR}/mkvwriter.cpp"
"${LIBWEBM_SRC_DIR}/mkvwriter.hpp"
"${LIBWEBM_SRC_DIR}/webmids.hpp")
if(WIN32)
# Use libwebm and libwebm.lib for project and library name on Windows (instead
# webm and webm.lib).
set_target_properties(webm PROPERTIES PROJECT_LABEL libwebm)
set_target_properties(webm PROPERTIES PREFIX lib)
endif(WIN32)
include_directories("${LIBWEBM_SRC_DIR}")
# Sample section.
add_executable(sample
"${LIBWEBM_SRC_DIR}/sample.cpp")
target_link_libraries(sample LINK_PUBLIC webm)
# Sample muxer section.
add_executable(sample_muxer
"${LIBWEBM_SRC_DIR}/sample_muxer.cpp"
"${LIBWEBM_SRC_DIR}/sample_muxer_metadata.cc"
"${LIBWEBM_SRC_DIR}/sample_muxer_metadata.h"
"${LIBWEBM_SRC_DIR}/vttreader.cc"
"${LIBWEBM_SRC_DIR}/vttreader.h"
"${LIBWEBM_SRC_DIR}/webvttparser.cc"
"${LIBWEBM_SRC_DIR}/webvttparser.h")
target_link_libraries(sample_muxer LINK_PUBLIC webm)
# Vttdemux section.
add_executable(vttdemux
"${LIBWEBM_SRC_DIR}/vttdemux.cc"
"${LIBWEBM_SRC_DIR}/webvttparser.cc"
"${LIBWEBM_SRC_DIR}/webvttparser.h")
target_link_libraries(vttdemux LINK_PUBLIC webm)
# webm2pes section.
add_executable(webm2pes
"${LIBWEBM_SRC_DIR}/webm2pes.cc"
"${LIBWEBM_SRC_DIR}/webm2pes.h")
target_link_libraries(webm2pes LINK_PUBLIC webm)

View File

@@ -1,20 +0,0 @@
LIB = libmkvparser.a
OBJECTS = mkvparser.o mkvreader.o sample.o
EXE = sample
CFLAGS = -W -Wall -g
$(EXE): $(OBJECTS)
$(AR) rcs $(LIB) mkvparser.o
$(CXX) $(OBJECTS) -L./ -lmkvparser -o $(EXE)
mkvparser.o: mkvparser.cpp
$(CXX) -c $(CFLAGS) mkvparser.cpp -o mkvparser.o
mkvreader.o: mkvreader.cpp
$(CXX) -c $(CFLAGS) mkvreader.cpp -o mkvreader.o
sample.o: sample.cpp
$(CXX) -c $(CFLAGS) sample.cpp -o sample.o
clean:
rm -rf $(OBJECTS) $(LIB) $(EXE) Makefile.bak

53
Makefile.unix Normal file
View File

@@ -0,0 +1,53 @@
CXX := g++
CXXFLAGS := -W -Wall -g -MMD -MP
LIBWEBMA := libwebm.a
LIBWEBMSO := libwebm.so
WEBMOBJS := mkvparser.o mkvreader.o mkvmuxer.o mkvmuxerutil.o mkvwriter.o
OBJSA := $(WEBMOBJS:.o=_a.o)
OBJSSO := $(WEBMOBJS:.o=_so.o)
OBJECTS1 := sample.o
OBJECTS2 := sample_muxer.o vttreader.o webvttparser.o sample_muxer_metadata.o
OBJECTS3 := dumpvtt.o vttreader.o webvttparser.o
OBJECTS4 := vttdemux.o webvttparser.o
INCLUDES := -I.
DEPS := $(WEBMOBJS:.o=.d) $(OBJECTS1:.o=.d) $(OBJECTS2:.o=.d)
DEPS += $(OBJECTS3:.o=.d) $(OBJECTS4:.o=.d)
EXES := sample_muxer sample dumpvtt vttdemux
all: $(EXES)
sample: sample.o $(LIBWEBMA)
$(CXX) $^ -o $@
sample_muxer: $(OBJECTS2) $(LIBWEBMA)
$(CXX) $^ -o $@
dumpvtt: $(OBJECTS3)
$(CXX) $^ -o $@
shared: $(LIBWEBMSO)
vttdemux: $(OBJECTS4) $(LIBWEBMA)
$(CXX) $^ -o $@
libwebm.a: $(OBJSA)
$(AR) rcs $@ $^
libwebm.so: $(OBJSSO)
$(CXX) $(CXXFLAGS) -shared $(OBJSSO) -o $(LIBWEBMSO)
%.o: %.cpp
$(CXX) -c $(CXXFLAGS) $(INCLUDES) $< -o $@
%_a.o: %.cpp
$(CXX) -c $(CXXFLAGS) $(INCLUDES) $< -o $@
%_so.o: %.cpp
$(CXX) -c $(CXXFLAGS) -fPIC $(INCLUDES) $< -o $@
clean:
$(RM) -f $(OBJECTS1) $(OBJECTS2) $(OBJECTS3) $(OBJECTS4) $(OBJSA) $(OBJSSO) $(LIBWEBMA) $(LIBWEBMSO) $(EXES) $(DEPS) Makefile.bak
ifneq ($(MAKECMDGOALS), clean)
-include $(DEPS)
endif

View File

@@ -1,22 +1,23 @@
Additional IP Rights Grant (Patents)
------------------------------------
"This implementation" means the copyrightable works distributed by
Google as part of the WebM Project.
"These implementations" means the copyrightable works that implement the WebM
codecs distributed by Google as part of the WebM Project.
Google hereby grants to you a perpetual, worldwide, non-exclusive,
no-charge, royalty-free, irrevocable (except as stated in this section)
patent license to make, have made, use, offer to sell, sell, import,
transfer, and otherwise run, modify and propagate the contents of this
implementation of VP8, where such license applies only to those patent
claims, both currently owned by Google and acquired in the future,
licensable by Google that are necessarily infringed by this
implementation of VP8. This grant does not include claims that would be
infringed only as a consequence of further modification of this
implementation. If you or your agent or exclusive licensee institute or
order or agree to the institution of patent litigation against any
entity (including a cross-claim or counterclaim in a lawsuit) alleging
that this implementation of VP8 or any code incorporated within this
implementation of VP8 constitutes direct or contributory patent
infringement, or inducement of patent infringement, then any patent
rights granted to you under this License for this implementation of VP8
shall terminate as of the date such litigation is filed.
Google hereby grants to you a perpetual, worldwide, non-exclusive, no-charge,
royalty-free, irrevocable (except as stated in this section) patent license to
make, have made, use, offer to sell, sell, import, transfer, and otherwise
run, modify and propagate the contents of these implementations of WebM, where
such license applies only to those patent claims, both currently owned by
Google and acquired in the future, licensable by Google that are necessarily
infringed by these implementations of WebM. This grant does not include claims
that would be infringed only as a consequence of further modification of these
implementations. If you or your agent or exclusive licensee institute or order
or agree to the institution of patent litigation or any other patent
enforcement activity against any entity (including a cross-claim or
counterclaim in a lawsuit) alleging that any of these implementations of WebM
or any code incorporated within any of these implementations of WebM
constitute direct or contributory patent infringement, or inducement of
patent infringement, then any patent rights granted to you under this License
for these implementations of WebM shall terminate as of the date such
litigation is filed.

57
README.libwebm Normal file
View File

@@ -0,0 +1,57 @@
Building Libwebm
To build libwebm you must first create project files. To do this run cmake
and pass it the path to your libwebm repo.
Makefile.unix can be used as a fallback on systems that cmake does not
support.
CMake Basics
To generate project/make files for the default toolchain on your system simply
run cmake with the path to the libwebm repo:
$ cmake path/to/libwebm
On Windows the above command will produce Visual Studio project files for the
newest Visual Studio detected on the system. On Mac OS X and Linux systems, the
above command will produce a makefile.
To control what types of projects are generated the -G parameter is added to
the cmake command line. This argument must be followed by the name of a
generator. Running cmake with the --help argument will list the available
generators for your system.
On Mac OS X you would run the following command to generate Xcode projects:
$ cmake path/to/libwebm -G Xcode
On a Windows box you would run the following command to generate Visual Studio
2013 projects:
$ cmake path/to/libwebm -G "Visual Studio 12"
To generate 64-bit Windows Visual Studio 2013 projects:
$ cmake path/to/libwebm "Visual Studio 12 Win64"
CMake Makefiles: Debugging and Optimization
Unlike Visual Studio and Xcode projects, the build configuration for make builds
is controlled when you run cmake. The following examples demonstrate various
build configurations.
Omitting the build type produces makefiles that use build flags containing
neither optimization nor debug flags:
$ cmake path/to/libwebm
A makefile using release (optimized) flags is produced like this:
$ cmake path/to/libwebm -DCMAKE_BUILD_TYPE=release
A release build with debug info can be produced as well:
$ cmake path/to/libwebm -DCMAKE_BUILD_TYPE=relwithdebinfo
And your standard debug build will be produced using:
$ cmake path/to/libwebm -DCMAKE_BUILD_TYPE=debug

View File

@@ -1,34 +0,0 @@
1.0.0.5
* Handled case when no duration
* Handled empty clusters
* Handled empty clusters when seeking
* Implemented check lacing bits
1.0.0.4
* Made Cues member variables mutables
* Defined against badly-formatted cue points
* Segment::GetCluster returns CuePoint too
* Separated cue-based searches
1.0.0.3
* Added Block::GetOffset() to get a frame's offset in a block
* Changed cluster count type from size_t to long
* Parsed SeekHead to find cues
* Allowed seeking beyond end of cluster cache
* Added not to attempt to reparse cues element
* Restructured Segment::LoadCluster
* Marked position of cues without parsing cues element
* Allowed cue points to be loaded incrementally
* Implemented to load lazily cue points as they're searched
* Merged Cues::LoadCuePoint into Cues::Find
* Lazy init cues
* Loaded cue point during find
1.0.0.2
* added support for Cues element
* seeking was improved
1.0.0.1
* fixed item 141
* added item 142
* added this file, RELEASE.TXT, to repository

24
build/msvc_runtime.cmake Normal file
View File

@@ -0,0 +1,24 @@
## Copyright (c) 2015 The WebM project authors. All Rights Reserved.
##
## Use of this source code is governed by a BSD-style license
## that can be found in the LICENSE file in the root of the source
## tree. An additional intellectual property rights grant can be found
## in the file PATENTS. All contributing project authors may
## be found in the AUTHORS file in the root of the source tree.
cmake_minimum_required(VERSION 2.8)
if(WIN32)
# CMake defaults to producing code linked to the DLL MSVC runtime. In libwebm
# static is typically desired. Force static code generation unless the user
# running CMake set MSVC_RUNTIME to dll.
if(NOT "${MSVC_RUNTIME}" STREQUAL "dll")
foreach(flag_var
CMAKE_CXX_FLAGS CMAKE_CXX_FLAGS_DEBUG CMAKE_CXX_FLAGS_RELEASE
CMAKE_CXX_FLAGS_MINSIZEREL CMAKE_CXX_FLAGS_RELWITHDEBINFO)
if(${flag_var} MATCHES "/MD")
string(REGEX REPLACE "/MD" "/MT" ${flag_var} "${${flag_var}}")
endif(${flag_var} MATCHES "/MD")
endforeach(flag_var)
endif(NOT "${MSVC_RUNTIME}" STREQUAL "dll")
endif(WIN32)

62
common/common.sh Normal file
View File

@@ -0,0 +1,62 @@
#!/bin/sh
##
## Copyright (c) 2015 The WebM project authors. All Rights Reserved.
##
## Use of this source code is governed by a BSD-style license
## that can be found in the LICENSE file in the root of the source
## tree. An additional intellectual property rights grant can be found
## in the file PATENTS. All contributing project authors may
## be found in the AUTHORS file in the root of the source tree.
##
set -e
devnull='> /dev/null 2>&1'
readonly ORIG_PWD="$(pwd)"
elog() {
echo "${0##*/} failed because: $@" 1>&2
}
vlog() {
if [ "${VERBOSE}" = "yes" ]; then
echo "$@"
fi
}
# Terminates script when name of current directory does not match $1.
check_dir() {
current_dir="$(pwd)"
required_dir="$1"
if [ "${current_dir##*/}" != "${required_dir}" ]; then
elog "This script must be run from the ${required_dir} directory."
exit 1
fi
}
# Terminates the script when $1 is not in $PATH. Any arguments required for
# the tool being tested to return a successful exit code can be passed as
# additional arguments.
check_tool() {
tool="$1"
shift
tool_args="$@"
if ! eval "${tool}" ${tool_args} > /dev/null 2>&1; then
elog "${tool} must be in your path."
exit 1
fi
}
# Echoes git describe output for the directory specified by $1 to stdout.
git_describe() {
git_dir="$1"
check_git
echo $(git -C "${git_dir}" describe)
}
# Echoes current git revision for the directory specifed by $1 to stdout.
git_revision() {
git_dir="$1"
check_git
echo $(git -C "${git_dir}" rev-parse HEAD)
}

91
dumpvtt.cc Normal file
View File

@@ -0,0 +1,91 @@
// Copyright (c) 2012 The WebM project authors. All Rights Reserved.
//
// Use of this source code is governed by a BSD-style license
// that can be found in the LICENSE file in the root of the source
// tree. An additional intellectual property rights grant can be found
// in the file PATENTS. All contributing project authors may
// be found in the AUTHORS file in the root of the source tree.
#include <cstdio>
#include <cstdlib>
#include "./vttreader.h"
#include "./webvttparser.h"
int main(int argc, const char* argv[]) {
if (argc != 2) {
fprintf(stdout, "usage: dumpvtt <vtt file>\n");
return EXIT_SUCCESS;
}
libwebvtt::VttReader reader;
const char* const filename = argv[1];
if (int e = reader.Open(filename)) {
(void)e;
fprintf(stderr, "open failed\n");
return EXIT_FAILURE;
}
libwebvtt::Parser parser(&reader);
if (int e = parser.Init()) {
(void)e;
fprintf(stderr, "parser init failed\n");
return EXIT_FAILURE;
}
for (libwebvtt::Cue cue;;) {
const int e = parser.Parse(&cue);
if (e < 0) { // error
fprintf(stderr, "error parsing cue\n");
return EXIT_FAILURE;
}
if (e > 0) // EOF
return EXIT_SUCCESS;
fprintf(stdout, "cue identifier: \"%s\"\n", cue.identifier.c_str());
const libwebvtt::Time& st = cue.start_time;
fprintf(stdout, "cue start time: \"HH=%i MM=%i SS=%i SSS=%i\"\n", st.hours,
st.minutes, st.seconds, st.milliseconds);
const libwebvtt::Time& sp = cue.stop_time;
fprintf(stdout, "cue stop time: \"HH=%i MM=%i SS=%i SSS=%i\"\n", sp.hours,
sp.minutes, sp.seconds, sp.milliseconds);
{
typedef libwebvtt::Cue::settings_t::const_iterator iter_t;
iter_t i = cue.settings.begin();
const iter_t j = cue.settings.end();
if (i == j) {
fprintf(stdout, "cue setting: <no settings present>\n");
} else {
while (i != j) {
const libwebvtt::Setting& setting = *i++;
fprintf(stdout, "cue setting: name=%s value=%s\n",
setting.name.c_str(), setting.value.c_str());
}
}
}
{
typedef libwebvtt::Cue::payload_t::const_iterator iter_t;
iter_t i = cue.payload.begin();
const iter_t j = cue.payload.end();
int idx = 1;
while (i != j) {
const std::string& payload = *i++;
const char* const payload_str = payload.c_str();
fprintf(stdout, "cue payload[%i]: \"%s\"\n", idx, payload_str);
++idx;
}
}
fprintf(stdout, "\n");
fflush(stdout);
}
}

193
iosbuild.sh Executable file
View File

@@ -0,0 +1,193 @@
#!/bin/sh
##
## Copyright (c) 2015 The WebM project authors. All Rights Reserved.
##
## Use of this source code is governed by a BSD-style license
## that can be found in the LICENSE file in the root of the source
## tree. An additional intellectual property rights grant can be found
## in the file PATENTS. All contributing project authors may
## be found in the AUTHORS file in the root of the source tree.
##
## This script generates 'WebM.framework'. An iOS app can mux/demux WebM
## container files by including 'WebM.framework'.
##
## Run ./iosbuild.sh to generate 'WebM.framework'. By default the framework
## bundle will be created in a directory called framework. Use --out-dir to
## change the output directory.
##
## This script is based on iosbuild.sh from the libwebp project.
. $(dirname $0)/common/common.sh
# Trap function. Cleans up build output.
cleanup() {
local readonly res=$?
cd "${ORIG_PWD}"
for dir in ${LIBDIRS}; do
if [ -d "${dir}" ]; then
rm -rf "${dir}"
fi
done
if [ $res -ne 0 ]; then
elog "build exited with error ($res)"
fi
}
trap cleanup EXIT
check_dir libwebm
iosbuild_usage() {
cat << EOF
Usage: ${0##*/} [arguments]
--help: Display this message and exit.
--out-dir: Override output directory (default is ${OUTDIR}).
--show-build-output: Show output from each library build.
--verbose: Output information about the environment and each stage of the
build.
EOF
}
# Extract the latest SDK version from the final field of the form: iphoneosX.Y
readonly SDK=$(xcodebuild -showsdks \
| grep iphoneos | sort | tail -n 1 | awk '{print substr($NF, 9)}'
)
# Extract Xcode version.
readonly XCODE=$(xcodebuild -version | grep Xcode | cut -d " " -f2)
if [ -z "${XCODE}" ]; then
echo "Xcode not available"
exit 1
fi
# Add iPhoneOS-V6 to the list of platforms below if you need armv6 support.
# Note that iPhoneOS-V6 support is not available with the iOS6 SDK.
readonly INCLUDES="mkvmuxer.hpp
mkvmuxertypes.hpp
mkvmuxerutil.hpp
mkvparser.hpp
mkvreader.hpp
mkvwriter.hpp
webmids.hpp"
readonly PLATFORMS="iPhoneSimulator
iPhoneSimulator64
iPhoneOS-V7
iPhoneOS-V7s
iPhoneOS-V7-arm64"
readonly TARGETDIR="WebM.framework"
readonly DEVELOPER="$(xcode-select --print-path)"
readonly PLATFORMSROOT="${DEVELOPER}/Platforms"
readonly LIPO="$(xcrun -sdk iphoneos${SDK} -find lipo)"
LIBLIST=""
OPT_FLAGS="-DNDEBUG -O3"
readonly SDK_MAJOR_VERSION="$(echo ${SDK} | awk -F '.' '{ print $1 }')"
if [ -z "${SDK_MAJOR_VERSION}" ]; then
elog "iOS SDK not available"
exit 1
elif [ "${SDK_MAJOR_VERSION}" -lt "6" ]; then
elog "You need iOS SDK version 6 or above"
exit 1
else
vlog "iOS SDK Version ${SDK}"
fi
# Parse the command line.
while [ -n "$1" ]; do
case "$1" in
--help)
iosbuild_usage
exit
;;
--out-dir)
OUTDIR="$2"
shift
;;
--enable-debug)
OPT_FLAGS="-g"
;;
--show-build-output)
devnull=
;;
--verbose)
VERBOSE=yes
;;
*)
iosbuild_usage
exit 1
;;
esac
shift
done
readonly OPT_FLAGS="${OPT_FLAGS}"
readonly OUTDIR="${OUTDIR:-framework}"
if [ "${VERBOSE}" = "yes" ]; then
cat << EOF
OUTDIR=${OUTDIR}
INCLUDES=${INCLUDES}
PLATFORMS=${PLATFORMS}
TARGETDIR=${TARGETDIR}
DEVELOPER=${DEVELOPER}
LIPO=${LIPO}
OPT_FLAGS=${OPT_FLAGS}
ORIG_PWD=${ORIG_PWD}
EOF
fi
rm -rf "${OUTDIR}/${TARGETDIR}"
mkdir -p "${OUTDIR}/${TARGETDIR}/Headers/"
for PLATFORM in ${PLATFORMS}; do
ARCH2=""
if [ "${PLATFORM}" = "iPhoneOS-V7-arm64" ]; then
PLATFORM="iPhoneOS"
ARCH="aarch64"
ARCH2="arm64"
elif [ "${PLATFORM}" = "iPhoneOS-V7s" ]; then
PLATFORM="iPhoneOS"
ARCH="armv7s"
elif [ "${PLATFORM}" = "iPhoneOS-V7" ]; then
PLATFORM="iPhoneOS"
ARCH="armv7"
elif [ "${PLATFORM}" = "iPhoneOS-V6" ]; then
PLATFORM="iPhoneOS"
ARCH="armv6"
elif [ "${PLATFORM}" = "iPhoneSimulator64" ]; then
PLATFORM="iPhoneSimulator"
ARCH="x86_64"
else
ARCH="i386"
fi
LIBDIR="${OUTDIR}/${PLATFORM}-${SDK}-${ARCH}"
LIBDIRS="${LIBDIRS} ${LIBDIR}"
LIBFILE="${LIBDIR}/libwebm.a"
eval mkdir -p "${LIBDIR}" ${devnull}
DEVROOT="${DEVELOPER}/Toolchains/XcodeDefault.xctoolchain"
SDKROOT="${PLATFORMSROOT}/"
SDKROOT="${SDKROOT}${PLATFORM}.platform/Developer/SDKs/${PLATFORM}${SDK}.sdk/"
CXXFLAGS="-arch ${ARCH2:-${ARCH}} -isysroot ${SDKROOT} ${OPT_FLAGS}
-miphoneos-version-min=6.0"
# Build using the legacy makefile (instead of generating via cmake).
eval make -f Makefile.unix libwebm.a CXXFLAGS=\"${CXXFLAGS}\" ${devnull}
# copy lib and add it to LIBLIST.
eval cp libwebm.a "${LIBFILE}" ${devnull}
LIBLIST="${LIBLIST} ${LIBFILE}"
# clean build so we can go again.
eval make -f Makefile.unix clean ${devnull}
done
for include_file in ${INCLUDES}; do
eval cp -p ${include_file} "${OUTDIR}/${TARGETDIR}/Headers/" ${devnull}
done
eval ${LIPO} -create ${LIBLIST} -output "${OUTDIR}/${TARGETDIR}/WebM" ${devnull}
echo "Succesfully built ${TARGETDIR} in ${OUTDIR}."

3281
mkvmuxer.cpp Normal file

File diff suppressed because it is too large Load Diff

1495
mkvmuxer.hpp Normal file

File diff suppressed because it is too large Load Diff

30
mkvmuxertypes.hpp Normal file
View File

@@ -0,0 +1,30 @@
// Copyright (c) 2012 The WebM project authors. All Rights Reserved.
//
// Use of this source code is governed by a BSD-style license
// that can be found in the LICENSE file in the root of the source
// tree. An additional intellectual property rights grant can be found
// in the file PATENTS. All contributing project authors may
// be found in the AUTHORS file in the root of the source tree.
#ifndef MKVMUXERTYPES_HPP
#define MKVMUXERTYPES_HPP
// Copied from Chromium basictypes.h
// A macro to disallow the copy constructor and operator= functions
// This should be used in the private: declarations for a class
#define LIBWEBM_DISALLOW_COPY_AND_ASSIGN(TypeName) \
TypeName(const TypeName&); \
void operator=(const TypeName&)
namespace mkvmuxer {
typedef unsigned char uint8;
typedef short int16;
typedef int int32;
typedef unsigned int uint32;
typedef long long int64;
typedef unsigned long long uint64;
} // end namespace mkvmuxer
#endif // MKVMUXERTYPES_HPP

629
mkvmuxerutil.cpp Normal file
View File

@@ -0,0 +1,629 @@
// Copyright (c) 2012 The WebM project authors. All Rights Reserved.
//
// Use of this source code is governed by a BSD-style license
// that can be found in the LICENSE file in the root of the source
// tree. An additional intellectual property rights grant can be found
// in the file PATENTS. All contributing project authors may
// be found in the AUTHORS file in the root of the source tree.
#include "mkvmuxerutil.hpp"
#ifdef __ANDROID__
#include <fcntl.h>
#endif
#include <cassert>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <ctime>
#include <new>
#include "mkvwriter.hpp"
#include "webmids.hpp"
#ifdef _MSC_VER
// Disable MSVC warnings that suggest making code non-portable.
#pragma warning(disable : 4996)
#endif
namespace mkvmuxer {
namespace {
// Date elements are always 8 octets in size.
const int kDateElementSize = 8;
uint64 WriteBlock(IMkvWriter* writer, const Frame* const frame, int64 timecode,
uint64 timecode_scale) {
uint64 block_additional_elem_size = 0;
uint64 block_addid_elem_size = 0;
uint64 block_more_payload_size = 0;
uint64 block_more_elem_size = 0;
uint64 block_additions_payload_size = 0;
uint64 block_additions_elem_size = 0;
if (frame->additional()) {
block_additional_elem_size = EbmlElementSize(
kMkvBlockAdditional, frame->additional(), frame->additional_length());
block_addid_elem_size = EbmlElementSize(kMkvBlockAddID, frame->add_id());
block_more_payload_size =
block_addid_elem_size + block_additional_elem_size;
block_more_elem_size =
EbmlMasterElementSize(kMkvBlockMore, block_more_payload_size) +
block_more_payload_size;
block_additions_payload_size = block_more_elem_size;
block_additions_elem_size =
EbmlMasterElementSize(kMkvBlockAdditions,
block_additions_payload_size) +
block_additions_payload_size;
}
uint64 discard_padding_elem_size = 0;
if (frame->discard_padding() != 0) {
discard_padding_elem_size =
EbmlElementSize(kMkvDiscardPadding, frame->discard_padding());
}
const uint64 reference_block_timestamp =
frame->reference_block_timestamp() / timecode_scale;
uint64 reference_block_elem_size = 0;
if (!frame->is_key()) {
reference_block_elem_size =
EbmlElementSize(kMkvReferenceBlock, reference_block_timestamp);
}
const uint64 duration = frame->duration() / timecode_scale;
uint64 block_duration_elem_size = 0;
if (duration > 0)
block_duration_elem_size = EbmlElementSize(kMkvBlockDuration, duration);
const uint64 block_payload_size = 4 + frame->length();
const uint64 block_elem_size =
EbmlMasterElementSize(kMkvBlock, block_payload_size) + block_payload_size;
const uint64 block_group_payload_size =
block_elem_size + block_additions_elem_size + block_duration_elem_size +
discard_padding_elem_size + reference_block_elem_size;
if (!WriteEbmlMasterElement(writer, kMkvBlockGroup,
block_group_payload_size)) {
return 0;
}
if (!WriteEbmlMasterElement(writer, kMkvBlock, block_payload_size))
return 0;
if (WriteUInt(writer, frame->track_number()))
return 0;
if (SerializeInt(writer, timecode, 2))
return 0;
// For a Block, flags is always 0.
if (SerializeInt(writer, 0, 1))
return 0;
if (writer->Write(frame->frame(), static_cast<uint32>(frame->length())))
return 0;
if (frame->additional()) {
if (!WriteEbmlMasterElement(writer, kMkvBlockAdditions,
block_additions_payload_size)) {
return 0;
}
if (!WriteEbmlMasterElement(writer, kMkvBlockMore, block_more_payload_size))
return 0;
if (!WriteEbmlElement(writer, kMkvBlockAddID, frame->add_id()))
return 0;
if (!WriteEbmlElement(writer, kMkvBlockAdditional, frame->additional(),
frame->additional_length())) {
return 0;
}
}
if (frame->discard_padding() != 0 &&
!WriteEbmlElement(writer, kMkvDiscardPadding, frame->discard_padding())) {
return false;
}
if (!frame->is_key() &&
!WriteEbmlElement(writer, kMkvReferenceBlock,
reference_block_timestamp)) {
return false;
}
if (duration > 0 && !WriteEbmlElement(writer, kMkvBlockDuration, duration)) {
return false;
}
return EbmlMasterElementSize(kMkvBlockGroup, block_group_payload_size) +
block_group_payload_size;
}
uint64 WriteSimpleBlock(IMkvWriter* writer, const Frame* const frame,
int64 timecode) {
if (WriteID(writer, kMkvSimpleBlock))
return 0;
const int32 size = static_cast<int32>(frame->length()) + 4;
if (WriteUInt(writer, size))
return 0;
if (WriteUInt(writer, static_cast<uint64>(frame->track_number())))
return 0;
if (SerializeInt(writer, timecode, 2))
return 0;
uint64 flags = 0;
if (frame->is_key())
flags |= 0x80;
if (SerializeInt(writer, flags, 1))
return 0;
if (writer->Write(frame->frame(), static_cast<uint32>(frame->length())))
return 0;
return GetUIntSize(kMkvSimpleBlock) + GetCodedUIntSize(size) + 4 +
frame->length();
}
} // namespace
int32 GetCodedUIntSize(uint64 value) {
if (value < 0x000000000000007FULL)
return 1;
else if (value < 0x0000000000003FFFULL)
return 2;
else if (value < 0x00000000001FFFFFULL)
return 3;
else if (value < 0x000000000FFFFFFFULL)
return 4;
else if (value < 0x00000007FFFFFFFFULL)
return 5;
else if (value < 0x000003FFFFFFFFFFULL)
return 6;
else if (value < 0x0001FFFFFFFFFFFFULL)
return 7;
return 8;
}
int32 GetUIntSize(uint64 value) {
if (value < 0x0000000000000100ULL)
return 1;
else if (value < 0x0000000000010000ULL)
return 2;
else if (value < 0x0000000001000000ULL)
return 3;
else if (value < 0x0000000100000000ULL)
return 4;
else if (value < 0x0000010000000000ULL)
return 5;
else if (value < 0x0001000000000000ULL)
return 6;
else if (value < 0x0100000000000000ULL)
return 7;
return 8;
}
int32 GetIntSize(int64 value) {
// Doubling the requested value ensures positive values with their high bit
// set are written with 0-padding to avoid flipping the signedness.
const uint64 v = (value < 0) ? value ^ -1LL : value;
return GetUIntSize(2 * v);
}
uint64 EbmlMasterElementSize(uint64 type, uint64 value) {
// Size of EBML ID
int32 ebml_size = GetUIntSize(type);
// Datasize
ebml_size += GetCodedUIntSize(value);
return ebml_size;
}
uint64 EbmlElementSize(uint64 type, int64 value) {
// Size of EBML ID
int32 ebml_size = GetUIntSize(type);
// Datasize
ebml_size += GetIntSize(value);
// Size of Datasize
ebml_size++;
return ebml_size;
}
uint64 EbmlElementSize(uint64 type, uint64 value) {
// Size of EBML ID
int32 ebml_size = GetUIntSize(type);
// Datasize
ebml_size += GetUIntSize(value);
// Size of Datasize
ebml_size++;
return ebml_size;
}
uint64 EbmlElementSize(uint64 type, float /* value */) {
// Size of EBML ID
uint64 ebml_size = GetUIntSize(type);
// Datasize
ebml_size += sizeof(float);
// Size of Datasize
ebml_size++;
return ebml_size;
}
uint64 EbmlElementSize(uint64 type, const char* value) {
if (!value)
return 0;
// Size of EBML ID
uint64 ebml_size = GetUIntSize(type);
// Datasize
ebml_size += strlen(value);
// Size of Datasize
ebml_size++;
return ebml_size;
}
uint64 EbmlElementSize(uint64 type, const uint8* value, uint64 size) {
if (!value)
return 0;
// Size of EBML ID
uint64 ebml_size = GetUIntSize(type);
// Datasize
ebml_size += size;
// Size of Datasize
ebml_size += GetCodedUIntSize(size);
return ebml_size;
}
uint64 EbmlDateElementSize(uint64 type) {
// Size of EBML ID
uint64 ebml_size = GetUIntSize(type);
// Datasize
ebml_size += kDateElementSize;
// Size of Datasize
ebml_size++;
return ebml_size;
}
int32 SerializeInt(IMkvWriter* writer, int64 value, int32 size) {
if (!writer || size < 1 || size > 8)
return -1;
for (int32 i = 1; i <= size; ++i) {
const int32 byte_count = size - i;
const int32 bit_count = byte_count * 8;
const int64 bb = value >> bit_count;
const uint8 b = static_cast<uint8>(bb);
const int32 status = writer->Write(&b, 1);
if (status < 0)
return status;
}
return 0;
}
int32 SerializeFloat(IMkvWriter* writer, float f) {
if (!writer)
return -1;
assert(sizeof(uint32) == sizeof(float));
// This union is merely used to avoid a reinterpret_cast from float& to
// uint32& which will result in violation of strict aliasing.
union U32 {
uint32 u32;
float f;
} value;
value.f = f;
for (int32 i = 1; i <= 4; ++i) {
const int32 byte_count = 4 - i;
const int32 bit_count = byte_count * 8;
const uint8 byte = static_cast<uint8>(value.u32 >> bit_count);
const int32 status = writer->Write(&byte, 1);
if (status < 0)
return status;
}
return 0;
}
int32 WriteUInt(IMkvWriter* writer, uint64 value) {
if (!writer)
return -1;
int32 size = GetCodedUIntSize(value);
return WriteUIntSize(writer, value, size);
}
int32 WriteUIntSize(IMkvWriter* writer, uint64 value, int32 size) {
if (!writer || size < 0 || size > 8)
return -1;
if (size > 0) {
const uint64 bit = 1LL << (size * 7);
if (value > (bit - 2))
return -1;
value |= bit;
} else {
size = 1;
int64 bit;
for (;;) {
bit = 1LL << (size * 7);
const uint64 max = bit - 2;
if (value <= max)
break;
++size;
}
if (size > 8)
return false;
value |= bit;
}
return SerializeInt(writer, value, size);
}
int32 WriteID(IMkvWriter* writer, uint64 type) {
if (!writer)
return -1;
writer->ElementStartNotify(type, writer->Position());
const int32 size = GetUIntSize(type);
return SerializeInt(writer, type, size);
}
bool WriteEbmlMasterElement(IMkvWriter* writer, uint64 type, uint64 size) {
if (!writer)
return false;
if (WriteID(writer, type))
return false;
if (WriteUInt(writer, size))
return false;
return true;
}
bool WriteEbmlElement(IMkvWriter* writer, uint64 type, uint64 value) {
if (!writer)
return false;
if (WriteID(writer, type))
return false;
const uint64 size = GetUIntSize(value);
if (WriteUInt(writer, size))
return false;
if (SerializeInt(writer, value, static_cast<int32>(size)))
return false;
return true;
}
bool WriteEbmlElement(IMkvWriter* writer, uint64 type, int64 value) {
if (!writer)
return false;
if (WriteID(writer, type))
return 0;
const uint64 size = GetIntSize(value);
if (WriteUInt(writer, size))
return false;
if (SerializeInt(writer, value, static_cast<int32>(size)))
return false;
return true;
}
bool WriteEbmlElement(IMkvWriter* writer, uint64 type, float value) {
if (!writer)
return false;
if (WriteID(writer, type))
return false;
if (WriteUInt(writer, 4))
return false;
if (SerializeFloat(writer, value))
return false;
return true;
}
bool WriteEbmlElement(IMkvWriter* writer, uint64 type, const char* value) {
if (!writer || !value)
return false;
if (WriteID(writer, type))
return false;
const uint64 length = strlen(value);
if (WriteUInt(writer, length))
return false;
if (writer->Write(value, static_cast<const uint32>(length)))
return false;
return true;
}
bool WriteEbmlElement(IMkvWriter* writer, uint64 type, const uint8* value,
uint64 size) {
if (!writer || !value || size < 1)
return false;
if (WriteID(writer, type))
return false;
if (WriteUInt(writer, size))
return false;
if (writer->Write(value, static_cast<uint32>(size)))
return false;
return true;
}
bool WriteEbmlDateElement(IMkvWriter* writer, uint64 type, int64 value) {
if (!writer)
return false;
if (WriteID(writer, type))
return false;
if (WriteUInt(writer, kDateElementSize))
return false;
if (SerializeInt(writer, value, kDateElementSize))
return false;
return true;
}
uint64 WriteFrame(IMkvWriter* writer, const Frame* const frame,
Cluster* cluster) {
if (!writer || !frame || !frame->IsValid() || !cluster ||
!cluster->timecode_scale())
return 0;
// Technically the timecode for a block can be less than the
// timecode for the cluster itself (remember that block timecode
// is a signed, 16-bit integer). However, as a simplification we
// only permit non-negative cluster-relative timecodes for blocks.
const int64 relative_timecode = cluster->GetRelativeTimecode(
frame->timestamp() / cluster->timecode_scale());
if (relative_timecode < 0 || relative_timecode > kMaxBlockTimecode)
return 0;
return frame->CanBeSimpleBlock() ?
WriteSimpleBlock(writer, frame, relative_timecode) :
WriteBlock(writer, frame, relative_timecode,
cluster->timecode_scale());
}
uint64 WriteVoidElement(IMkvWriter* writer, uint64 size) {
if (!writer)
return false;
// Subtract one for the void ID and the coded size.
uint64 void_entry_size = size - 1 - GetCodedUIntSize(size - 1);
uint64 void_size =
EbmlMasterElementSize(kMkvVoid, void_entry_size) + void_entry_size;
if (void_size != size)
return 0;
const int64 payload_position = writer->Position();
if (payload_position < 0)
return 0;
if (WriteID(writer, kMkvVoid))
return 0;
if (WriteUInt(writer, void_entry_size))
return 0;
const uint8 value = 0;
for (int32 i = 0; i < static_cast<int32>(void_entry_size); ++i) {
if (writer->Write(&value, 1))
return 0;
}
const int64 stop_position = writer->Position();
if (stop_position < 0 ||
stop_position - payload_position != static_cast<int64>(void_size))
return 0;
return void_size;
}
void GetVersion(int32* major, int32* minor, int32* build, int32* revision) {
*major = 0;
*minor = 2;
*build = 1;
*revision = 0;
}
} // namespace mkvmuxer
mkvmuxer::uint64 mkvmuxer::MakeUID(unsigned int* seed) {
uint64 uid = 0;
#ifdef __MINGW32__
srand(*seed);
#endif
for (int i = 0; i < 7; ++i) { // avoid problems with 8-byte values
uid <<= 8;
// TODO(fgalligan): Move random number generation to platform specific code.
#ifdef _MSC_VER
(void)seed;
const int32 nn = rand();
#elif __ANDROID__
int32 temp_num = 1;
int fd = open("/dev/urandom", O_RDONLY);
if (fd != -1) {
read(fd, &temp_num, sizeof(int32));
close(fd);
}
const int32 nn = temp_num;
#elif defined __MINGW32__
const int32 nn = rand();
#else
const int32 nn = rand_r(seed);
#endif
const int32 n = 0xFF & (nn >> 4); // throw away low-order bits
uid |= n;
}
return uid;
}

83
mkvmuxerutil.hpp Normal file
View File

@@ -0,0 +1,83 @@
// Copyright (c) 2012 The WebM project authors. All Rights Reserved.
//
// Use of this source code is governed by a BSD-style license
// that can be found in the LICENSE file in the root of the source
// tree. An additional intellectual property rights grant can be found
// in the file PATENTS. All contributing project authors may
// be found in the AUTHORS file in the root of the source tree.
#ifndef MKVMUXERUTIL_HPP
#define MKVMUXERUTIL_HPP
#include "mkvmuxer.hpp"
#include "mkvmuxertypes.hpp"
namespace mkvmuxer {
class IMkvWriter;
const uint64 kEbmlUnknownValue = 0x01FFFFFFFFFFFFFFULL;
const int64 kMaxBlockTimecode = 0x07FFFLL;
// Writes out |value| in Big Endian order. Returns 0 on success.
int32 SerializeInt(IMkvWriter* writer, int64 value, int32 size);
// Returns the size in bytes of the element.
int32 GetUIntSize(uint64 value);
int32 GetIntSize(int64 value);
int32 GetCodedUIntSize(uint64 value);
uint64 EbmlMasterElementSize(uint64 type, uint64 value);
uint64 EbmlElementSize(uint64 type, int64 value);
uint64 EbmlElementSize(uint64 type, uint64 value);
uint64 EbmlElementSize(uint64 type, float value);
uint64 EbmlElementSize(uint64 type, const char* value);
uint64 EbmlElementSize(uint64 type, const uint8* value, uint64 size);
uint64 EbmlDateElementSize(uint64 type);
// Creates an EBML coded number from |value| and writes it out. The size of
// the coded number is determined by the value of |value|. |value| must not
// be in a coded form. Returns 0 on success.
int32 WriteUInt(IMkvWriter* writer, uint64 value);
// Creates an EBML coded number from |value| and writes it out. The size of
// the coded number is determined by the value of |size|. |value| must not
// be in a coded form. Returns 0 on success.
int32 WriteUIntSize(IMkvWriter* writer, uint64 value, int32 size);
// Output an Mkv master element. Returns true if the element was written.
bool WriteEbmlMasterElement(IMkvWriter* writer, uint64 value, uint64 size);
// Outputs an Mkv ID, calls |IMkvWriter::ElementStartNotify|, and passes the
// ID to |SerializeInt|. Returns 0 on success.
int32 WriteID(IMkvWriter* writer, uint64 type);
// Output an Mkv non-master element. Returns true if the element was written.
bool WriteEbmlElement(IMkvWriter* writer, uint64 type, uint64 value);
bool WriteEbmlElement(IMkvWriter* writer, uint64 type, int64 value);
bool WriteEbmlElement(IMkvWriter* writer, uint64 type, float value);
bool WriteEbmlElement(IMkvWriter* writer, uint64 type, const char* value);
bool WriteEbmlElement(IMkvWriter* writer, uint64 type, const uint8* value,
uint64 size);
bool WriteEbmlDateElement(IMkvWriter* writer, uint64 type, int64 value);
// Output a Mkv Frame. It decides the correct element to write (Block vs
// SimpleBlock) based on the parameters of the Frame.
uint64 WriteFrame(IMkvWriter* writer, const Frame* const frame,
Cluster* cluster);
// Output a void element. |size| must be the entire size in bytes that will be
// void. The function will calculate the size of the void header and subtract
// it from |size|.
uint64 WriteVoidElement(IMkvWriter* writer, uint64 size);
// Returns the version number of the muxer in |major|, |minor|, |build|,
// and |revision|.
void GetVersion(int32* major, int32* minor, int32* build, int32* revision);
// Returns a random number to be used for UID, using |seed| to seed
// the random-number generator (see POSIX rand_r() for semantics).
uint64 MakeUID(unsigned int* seed);
} // end namespace mkvmuxer
#endif // MKVMUXERUTIL_HPP

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@@ -1,34 +0,0 @@

Microsoft Visual Studio Solution File, Format Version 9.00
# Visual Studio 2005
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "mkvparser_2005", "mkvparser_2005.vcproj", "{F9128EC6-C008-41AD-B38F-0E70D549D9F4}"
ProjectSection(WebsiteProperties) = preProject
Debug.AspNetCompiler.Debug = "True"
Release.AspNetCompiler.Debug = "False"
EndProjectSection
EndProject
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "sample_2005", "sample_2005.vcproj", "{0CB5681F-6065-490C-98C8-05531732ED7E}"
ProjectSection(WebsiteProperties) = preProject
Debug.AspNetCompiler.Debug = "True"
Release.AspNetCompiler.Debug = "False"
EndProjectSection
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Win32 = Debug|Win32
Release|Win32 = Release|Win32
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{F9128EC6-C008-41AD-B38F-0E70D549D9F4}.Debug|Win32.ActiveCfg = Debug|Win32
{F9128EC6-C008-41AD-B38F-0E70D549D9F4}.Debug|Win32.Build.0 = Debug|Win32
{F9128EC6-C008-41AD-B38F-0E70D549D9F4}.Release|Win32.ActiveCfg = Release|Win32
{F9128EC6-C008-41AD-B38F-0E70D549D9F4}.Release|Win32.Build.0 = Release|Win32
{0CB5681F-6065-490C-98C8-05531732ED7E}.Debug|Win32.ActiveCfg = Debug|Win32
{0CB5681F-6065-490C-98C8-05531732ED7E}.Debug|Win32.Build.0 = Debug|Win32
{0CB5681F-6065-490C-98C8-05531732ED7E}.Release|Win32.ActiveCfg = Release|Win32
{0CB5681F-6065-490C-98C8-05531732ED7E}.Release|Win32.Build.0 = Release|Win32
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
EndGlobal

View File

@@ -1,176 +0,0 @@
<?xml version="1.0" encoding="Windows-1252"?>
<VisualStudioProject
ProjectType="Visual C++"
Version="8.00"
Name="mkvparser"
ProjectGUID="{F9128EC6-C008-41AD-B38F-0E70D549D9F4}"
RootNamespace="mkvparser"
Keyword="Win32Proj"
>
<Platforms>
<Platform
Name="Win32"
/>
</Platforms>
<ToolFiles>
</ToolFiles>
<Configurations>
<Configuration
Name="Debug|Win32"
OutputDirectory="$(SolutionDir)$(ConfigurationName)"
IntermediateDirectory="$(ConfigurationName)"
ConfigurationType="4"
UseOfMFC="0"
CharacterSet="1"
>
<Tool
Name="VCPreBuildEventTool"
/>
<Tool
Name="VCCustomBuildTool"
/>
<Tool
Name="VCXMLDataGeneratorTool"
/>
<Tool
Name="VCWebServiceProxyGeneratorTool"
/>
<Tool
Name="VCMIDLTool"
/>
<Tool
Name="VCCLCompilerTool"
Optimization="0"
PreprocessorDefinitions="WIN32;_DEBUG;_LIB"
MinimalRebuild="true"
BasicRuntimeChecks="3"
RuntimeLibrary="3"
UsePrecompiledHeader="0"
WarningLevel="3"
Detect64BitPortabilityProblems="true"
DebugInformationFormat="4"
/>
<Tool
Name="VCManagedResourceCompilerTool"
/>
<Tool
Name="VCResourceCompilerTool"
/>
<Tool
Name="VCPreLinkEventTool"
/>
<Tool
Name="VCLibrarianTool"
/>
<Tool
Name="VCALinkTool"
/>
<Tool
Name="VCXDCMakeTool"
/>
<Tool
Name="VCBscMakeTool"
/>
<Tool
Name="VCFxCopTool"
/>
<Tool
Name="VCPostBuildEventTool"
/>
</Configuration>
<Configuration
Name="Release|Win32"
OutputDirectory="$(SolutionDir)$(ConfigurationName)"
IntermediateDirectory="$(ConfigurationName)"
ConfigurationType="4"
CharacterSet="1"
WholeProgramOptimization="1"
>
<Tool
Name="VCPreBuildEventTool"
/>
<Tool
Name="VCCustomBuildTool"
/>
<Tool
Name="VCXMLDataGeneratorTool"
/>
<Tool
Name="VCWebServiceProxyGeneratorTool"
/>
<Tool
Name="VCMIDLTool"
/>
<Tool
Name="VCCLCompilerTool"
PreprocessorDefinitions="WIN32;NDEBUG;_LIB"
RuntimeLibrary="2"
UsePrecompiledHeader="2"
WarningLevel="3"
Detect64BitPortabilityProblems="true"
DebugInformationFormat="3"
/>
<Tool
Name="VCManagedResourceCompilerTool"
/>
<Tool
Name="VCResourceCompilerTool"
/>
<Tool
Name="VCPreLinkEventTool"
/>
<Tool
Name="VCLibrarianTool"
/>
<Tool
Name="VCALinkTool"
/>
<Tool
Name="VCXDCMakeTool"
/>
<Tool
Name="VCBscMakeTool"
/>
<Tool
Name="VCFxCopTool"
/>
<Tool
Name="VCPostBuildEventTool"
/>
</Configuration>
</Configurations>
<References>
</References>
<Files>
<Filter
Name="Source Files"
Filter="cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx"
UniqueIdentifier="{4FC737F1-C7A5-4376-A066-2A32D752A2FF}"
>
<File
RelativePath=".\mkvparser.cpp"
>
</File>
<File
RelativePath=".\mkvreader.cpp"
>
</File>
</Filter>
<Filter
Name="Header Files"
Filter="h;hpp;hxx;hm;inl;inc;xsd"
UniqueIdentifier="{93995380-89BD-4b04-88EB-625FBE52EBFB}"
>
<File
RelativePath=".\mkvparser.hpp"
>
</File>
<File
RelativePath=".\mkvreader.hpp"
>
</File>
</Filter>
</Files>
<Globals>
</Globals>
</VisualStudioProject>

View File

@@ -1,29 +0,0 @@

Microsoft Visual Studio Solution File, Format Version 10.00
# Visual Studio 2008
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "mkvparser", "mkvparser_2008.vcproj", "{F9128EC6-C008-41AD-B38F-0E70D549D9F4}"
EndProject
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "sample", "sample_2008.vcproj", "{0CB5681F-6065-490C-98C8-05531732ED7E}"
ProjectSection(ProjectDependencies) = postProject
{F9128EC6-C008-41AD-B38F-0E70D549D9F4} = {F9128EC6-C008-41AD-B38F-0E70D549D9F4}
EndProjectSection
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Win32 = Debug|Win32
Release|Win32 = Release|Win32
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{F9128EC6-C008-41AD-B38F-0E70D549D9F4}.Debug|Win32.ActiveCfg = Debug|Win32
{F9128EC6-C008-41AD-B38F-0E70D549D9F4}.Debug|Win32.Build.0 = Debug|Win32
{F9128EC6-C008-41AD-B38F-0E70D549D9F4}.Release|Win32.ActiveCfg = Release|Win32
{F9128EC6-C008-41AD-B38F-0E70D549D9F4}.Release|Win32.Build.0 = Release|Win32
{0CB5681F-6065-490C-98C8-05531732ED7E}.Debug|Win32.ActiveCfg = Debug|Win32
{0CB5681F-6065-490C-98C8-05531732ED7E}.Debug|Win32.Build.0 = Debug|Win32
{0CB5681F-6065-490C-98C8-05531732ED7E}.Release|Win32.ActiveCfg = Release|Win32
{0CB5681F-6065-490C-98C8-05531732ED7E}.Release|Win32.Build.0 = Release|Win32
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
EndGlobal

View File

@@ -1,178 +0,0 @@
<?xml version="1.0" encoding="Windows-1252"?>
<VisualStudioProject
ProjectType="Visual C++"
Version="9.00"
Name="mkvparser"
ProjectGUID="{F9128EC6-C008-41AD-B38F-0E70D549D9F4}"
RootNamespace="mkvparser"
Keyword="Win32Proj"
TargetFrameworkVersion="131072"
>
<Platforms>
<Platform
Name="Win32"
/>
</Platforms>
<ToolFiles>
</ToolFiles>
<Configurations>
<Configuration
Name="Debug|Win32"
OutputDirectory="$(SolutionDir)$(ConfigurationName)"
IntermediateDirectory="$(ConfigurationName)"
ConfigurationType="4"
UseOfMFC="0"
CharacterSet="1"
>
<Tool
Name="VCPreBuildEventTool"
/>
<Tool
Name="VCCustomBuildTool"
/>
<Tool
Name="VCXMLDataGeneratorTool"
/>
<Tool
Name="VCWebServiceProxyGeneratorTool"
/>
<Tool
Name="VCMIDLTool"
/>
<Tool
Name="VCCLCompilerTool"
Optimization="0"
PreprocessorDefinitions="WIN32;_DEBUG;_LIB"
MinimalRebuild="false"
BasicRuntimeChecks="3"
RuntimeLibrary="1"
UsePrecompiledHeader="0"
WarningLevel="4"
Detect64BitPortabilityProblems="false"
DebugInformationFormat="1"
/>
<Tool
Name="VCManagedResourceCompilerTool"
/>
<Tool
Name="VCResourceCompilerTool"
/>
<Tool
Name="VCPreLinkEventTool"
/>
<Tool
Name="VCLibrarianTool"
/>
<Tool
Name="VCALinkTool"
/>
<Tool
Name="VCXDCMakeTool"
/>
<Tool
Name="VCBscMakeTool"
/>
<Tool
Name="VCFxCopTool"
/>
<Tool
Name="VCPostBuildEventTool"
/>
</Configuration>
<Configuration
Name="Release|Win32"
OutputDirectory="$(SolutionDir)$(ConfigurationName)"
IntermediateDirectory="$(ConfigurationName)"
ConfigurationType="4"
UseOfMFC="1"
CharacterSet="1"
WholeProgramOptimization="1"
>
<Tool
Name="VCPreBuildEventTool"
/>
<Tool
Name="VCCustomBuildTool"
/>
<Tool
Name="VCXMLDataGeneratorTool"
/>
<Tool
Name="VCWebServiceProxyGeneratorTool"
/>
<Tool
Name="VCMIDLTool"
/>
<Tool
Name="VCCLCompilerTool"
PreprocessorDefinitions="WIN32;NDEBUG;_LIB"
RuntimeLibrary="2"
UsePrecompiledHeader="0"
WarningLevel="3"
Detect64BitPortabilityProblems="false"
DebugInformationFormat="3"
/>
<Tool
Name="VCManagedResourceCompilerTool"
/>
<Tool
Name="VCResourceCompilerTool"
/>
<Tool
Name="VCPreLinkEventTool"
/>
<Tool
Name="VCLibrarianTool"
/>
<Tool
Name="VCALinkTool"
/>
<Tool
Name="VCXDCMakeTool"
/>
<Tool
Name="VCBscMakeTool"
/>
<Tool
Name="VCFxCopTool"
/>
<Tool
Name="VCPostBuildEventTool"
/>
</Configuration>
</Configurations>
<References>
</References>
<Files>
<Filter
Name="Source Files"
Filter="cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx"
UniqueIdentifier="{4FC737F1-C7A5-4376-A066-2A32D752A2FF}"
>
<File
RelativePath=".\mkvparser.cpp"
>
</File>
<File
RelativePath=".\mkvreader.cpp"
>
</File>
</Filter>
<Filter
Name="Header Files"
Filter="h;hpp;hxx;hm;inl;inc;xsd"
UniqueIdentifier="{93995380-89BD-4b04-88EB-625FBE52EBFB}"
>
<File
RelativePath=".\mkvparser.hpp"
>
</File>
<File
RelativePath=".\mkvreader.hpp"
>
</File>
</Filter>
</Files>
<Globals>
</Globals>
</VisualStudioProject>

View File

@@ -1,123 +1,132 @@
// Copyright (c) 2010 The WebM project authors. All Rights Reserved.
//
// Use of this source code is governed by a BSD-style license
// that can be found in the LICENSE file in the root of the source
// tree. An additional intellectual property rights grant can be found
// in the file PATENTS. All contributing project authors may
// be found in the AUTHORS file in the root of the source tree.
#include "mkvreader.hpp"
#include <cassert>
MkvReader::MkvReader() :
m_file(NULL)
{
}
MkvReader::~MkvReader()
{
Close();
}
int MkvReader::Open(const char* fileName)
{
if (fileName == NULL)
return -1;
if (m_file)
return -1;
#ifdef WIN32
const errno_t e = fopen_s(&m_file, fileName, "rb");
if (e)
return -1; //error
#else
m_file = fopen(fileName, "rb");
if (m_file == NULL)
return -1;
#endif
#ifdef WIN32
int status = _fseeki64(m_file, 0L, SEEK_END);
if (status)
return -1; //error
m_length = _ftelli64(m_file);
#else
fseek(m_file, 0L, SEEK_END);
m_length = ftell(m_file);
#endif
assert(m_length >= 0);
#ifdef WIN32
status = _fseeki64(m_file, 0L, SEEK_SET);
if (status)
return -1; //error
#else
fseek(m_file, 0L, SEEK_SET);
#endif
return 0;
}
void MkvReader::Close()
{
if (m_file != NULL)
{
fclose(m_file);
m_file = NULL;
}
}
int MkvReader::Length(long long* total, long long* available)
{
if (m_file == NULL)
return -1;
if (total)
*total = m_length;
if (available)
*available = m_length;
return 0;
}
int MkvReader::Read(long long offset, long len, unsigned char* buffer)
{
if (m_file == NULL)
return -1;
if (offset < 0)
return -1;
if (len < 0)
return -1;
if (len == 0)
return 0;
if (offset >= m_length)
return -1;
#ifdef WIN32
const int status = _fseeki64(m_file, offset, SEEK_SET);
if (status)
return -1; //error
#else
fseek(m_file, offset, SEEK_SET);
#endif
const size_t size = fread(buffer, 1, len, m_file);
if (size < size_t(len))
return -1; //error
return 0; //success
}
// Copyright (c) 2010 The WebM project authors. All Rights Reserved.
//
// Use of this source code is governed by a BSD-style license
// that can be found in the LICENSE file in the root of the source
// tree. An additional intellectual property rights grant can be found
// in the file PATENTS. All contributing project authors may
// be found in the AUTHORS file in the root of the source tree.
#include "mkvreader.hpp"
#include <cassert>
namespace mkvparser {
MkvReader::MkvReader() : m_file(NULL), reader_owns_file_(true) {}
MkvReader::MkvReader(FILE* fp) : m_file(fp), reader_owns_file_(false) {
GetFileSize();
}
MkvReader::~MkvReader() {
if (reader_owns_file_)
Close();
m_file = NULL;
}
int MkvReader::Open(const char* fileName) {
if (fileName == NULL)
return -1;
if (m_file)
return -1;
#ifdef _MSC_VER
const errno_t e = fopen_s(&m_file, fileName, "rb");
if (e)
return -1; // error
#else
m_file = fopen(fileName, "rb");
if (m_file == NULL)
return -1;
#endif
return !GetFileSize();
}
bool MkvReader::GetFileSize() {
if (m_file == NULL)
return false;
#ifdef _MSC_VER
int status = _fseeki64(m_file, 0L, SEEK_END);
if (status)
return false; // error
m_length = _ftelli64(m_file);
#else
fseek(m_file, 0L, SEEK_END);
m_length = ftell(m_file);
#endif
assert(m_length >= 0);
if (m_length < 0)
return false;
#ifdef _MSC_VER
status = _fseeki64(m_file, 0L, SEEK_SET);
if (status)
return false; // error
#else
fseek(m_file, 0L, SEEK_SET);
#endif
return true;
}
void MkvReader::Close() {
if (m_file != NULL) {
fclose(m_file);
m_file = NULL;
}
}
int MkvReader::Length(long long* total, long long* available) {
if (m_file == NULL)
return -1;
if (total)
*total = m_length;
if (available)
*available = m_length;
return 0;
}
int MkvReader::Read(long long offset, long len, unsigned char* buffer) {
if (m_file == NULL)
return -1;
if (offset < 0)
return -1;
if (len < 0)
return -1;
if (len == 0)
return 0;
if (offset >= m_length)
return -1;
#ifdef _MSC_VER
const int status = _fseeki64(m_file, offset, SEEK_SET);
if (status)
return -1; // error
#else
fseek(m_file, offset, SEEK_SET);
#endif
const size_t size = fread(buffer, 1, len, m_file);
if (size < size_t(len))
return -1; // error
return 0; // success
}
} // end namespace mkvparser

View File

@@ -1,34 +1,45 @@
// Copyright (c) 2010 The WebM project authors. All Rights Reserved.
//
// Use of this source code is governed by a BSD-style license
// that can be found in the LICENSE file in the root of the source
// tree. An additional intellectual property rights grant can be found
// in the file PATENTS. All contributing project authors may
// be found in the AUTHORS file in the root of the source tree.
#ifndef MKVREADER_HPP
#define MKVREADER_HPP
#include "mkvparser.hpp"
#include <cstdio>
class MkvReader : public mkvparser::IMkvReader
{
MkvReader(const MkvReader&);
MkvReader& operator=(const MkvReader&);
public:
MkvReader();
virtual ~MkvReader();
int Open(const char*);
void Close();
bool IsOpen() const;
virtual int Read(long long position, long length, unsigned char* buffer);
virtual int Length(long long* total, long long* available);
private:
long long m_length;
FILE* m_file;
};
#endif //MKVREADER_HPP
// Copyright (c) 2010 The WebM project authors. All Rights Reserved.
//
// Use of this source code is governed by a BSD-style license
// that can be found in the LICENSE file in the root of the source
// tree. An additional intellectual property rights grant can be found
// in the file PATENTS. All contributing project authors may
// be found in the AUTHORS file in the root of the source tree.
#ifndef MKVREADER_HPP
#define MKVREADER_HPP
#include "mkvparser.hpp"
#include <cstdio>
namespace mkvparser {
class MkvReader : public IMkvReader {
public:
MkvReader();
explicit MkvReader(FILE* fp);
virtual ~MkvReader();
int Open(const char*);
void Close();
virtual int Read(long long position, long length, unsigned char* buffer);
virtual int Length(long long* total, long long* available);
private:
MkvReader(const MkvReader&);
MkvReader& operator=(const MkvReader&);
// Determines the size of the file. This is called either by the constructor
// or by the Open function depending on file ownership. Returns true on
// success.
bool GetFileSize();
long long m_length;
FILE* m_file;
bool reader_owns_file_;
};
} // end namespace mkvparser
#endif // MKVREADER_HPP

90
mkvwriter.cpp Normal file
View File

@@ -0,0 +1,90 @@
// Copyright (c) 2012 The WebM project authors. All Rights Reserved.
//
// Use of this source code is governed by a BSD-style license
// that can be found in the LICENSE file in the root of the source
// tree. An additional intellectual property rights grant can be found
// in the file PATENTS. All contributing project authors may
// be found in the AUTHORS file in the root of the source tree.
#include "mkvwriter.hpp"
#ifdef _MSC_VER
#include <share.h> // for _SH_DENYWR
#endif
#include <new>
namespace mkvmuxer {
MkvWriter::MkvWriter() : file_(NULL), writer_owns_file_(true) {}
MkvWriter::MkvWriter(FILE* fp) : file_(fp), writer_owns_file_(false) {}
MkvWriter::~MkvWriter() { Close(); }
int32 MkvWriter::Write(const void* buffer, uint32 length) {
if (!file_)
return -1;
if (length == 0)
return 0;
if (buffer == NULL)
return -1;
const size_t bytes_written = fwrite(buffer, 1, length, file_);
return (bytes_written == length) ? 0 : -1;
}
bool MkvWriter::Open(const char* filename) {
if (filename == NULL)
return false;
if (file_)
return false;
#ifdef _MSC_VER
file_ = _fsopen(filename, "wb", _SH_DENYWR);
#else
file_ = fopen(filename, "wb");
#endif
if (file_ == NULL)
return false;
return true;
}
void MkvWriter::Close() {
if (file_ && writer_owns_file_) {
fclose(file_);
}
file_ = NULL;
}
int64 MkvWriter::Position() const {
if (!file_)
return 0;
#ifdef _MSC_VER
return _ftelli64(file_);
#else
return ftell(file_);
#endif
}
int32 MkvWriter::Position(int64 position) {
if (!file_)
return -1;
#ifdef _MSC_VER
return _fseeki64(file_, position, SEEK_SET);
#else
return fseek(file_, position, SEEK_SET);
#endif
}
bool MkvWriter::Seekable() const { return true; }
void MkvWriter::ElementStartNotify(uint64, int64) {}
} // namespace mkvmuxer

51
mkvwriter.hpp Normal file
View File

@@ -0,0 +1,51 @@
// Copyright (c) 2012 The WebM project authors. All Rights Reserved.
//
// Use of this source code is governed by a BSD-style license
// that can be found in the LICENSE file in the root of the source
// tree. An additional intellectual property rights grant can be found
// in the file PATENTS. All contributing project authors may
// be found in the AUTHORS file in the root of the source tree.
#ifndef MKVWRITER_HPP
#define MKVWRITER_HPP
#include <stdio.h>
#include "mkvmuxer.hpp"
#include "mkvmuxertypes.hpp"
namespace mkvmuxer {
// Default implementation of the IMkvWriter interface on Windows.
class MkvWriter : public IMkvWriter {
public:
MkvWriter();
explicit MkvWriter(FILE* fp);
virtual ~MkvWriter();
// IMkvWriter interface
virtual int64 Position() const;
virtual int32 Position(int64 position);
virtual bool Seekable() const;
virtual int32 Write(const void* buffer, uint32 length);
virtual void ElementStartNotify(uint64 element_id, int64 position);
// Creates and opens a file for writing. |filename| is the name of the file
// to open. This function will overwrite the contents of |filename|. Returns
// true on success.
bool Open(const char* filename);
// Closes an opened file.
void Close();
private:
// File handle to output file.
FILE* file_;
bool writer_owns_file_;
LIBWEBM_DISALLOW_COPY_AND_ASSIGN(MkvWriter);
};
} // end namespace mkvmuxer
#endif // MKVWRITER_HPP

View File

@@ -1,283 +1,366 @@
// Copyright (c) 2010 The WebM project authors. All Rights Reserved.
//
// Use of this source code is governed by a BSD-style license
// that can be found in the LICENSE file in the root of the source
// tree. An additional intellectual property rights grant can be found
// in the file PATENTS. All contributing project authors may
// be found in the AUTHORS file in the root of the source tree.
//
// This sample application demonstrates how to use the matroska parser
// library, which allows clients to handle a matroska format file.
#include "mkvreader.hpp"
#include "mkvparser.hpp"
static const wchar_t* utf8towcs(const char* str)
{
if (str == NULL)
return NULL;
//TODO: this probably requires that the locale be
//configured somehow:
const size_t size = mbstowcs(NULL, str, 0);
if (size == 0)
return NULL;
wchar_t* const val = new wchar_t[size+1];
mbstowcs(val, str, size);
val[size] = L'\0';
return val;
}
int main(int argc, char* argv[])
{
if (argc == 1)
{
printf("\t\t\tMkv Parser Sample Application\n");
printf("\t\t\tUsage: \n");
printf("\t\t\t ./sample [input file] \n");
printf("\t\t\t ./sample sample.mkv \n");
return -1;
}
using namespace mkvparser;
MkvReader reader;
if (reader.Open(argv[1]))
{
printf("\n Filename is invalid or error while opening.\n");
return -1;
}
int maj, min, build, rev;
GetVersion(maj, min, build, rev);
printf("\t\t libmkv verison: %d.%d.%d.%d\n", maj, min, build, rev);
long long pos = 0;
EBMLHeader ebmlHeader;
ebmlHeader.Parse(&reader, pos);
printf("\t\t\t EBML Header\n");
printf("\t\tEBML Version\t\t: %lld\n", ebmlHeader.m_version);
printf("\t\tEBML MaxIDLength\t: %lld\n", ebmlHeader.m_maxIdLength);
printf("\t\tEBML MaxSizeLength\t: %lld\n", ebmlHeader.m_maxSizeLength);
printf("\t\tDoc Type\t\t: %s\n", ebmlHeader.m_docType);
printf("\t\tPos\t\t\t: %lld\n", pos);
mkvparser::Segment* pSegment;
long long ret = mkvparser::Segment::CreateInstance(&reader, pos, pSegment);
if (ret)
{
printf("\n Segment::CreateInstance() failed.");
return -1;
}
ret = pSegment->Load();
if (ret < 0)
{
printf("\n Segment::Load() failed.");
return -1;
}
const SegmentInfo* const pSegmentInfo = pSegment->GetInfo();
const long long timeCodeScale = pSegmentInfo->GetTimeCodeScale();
const long long duration_ns = pSegmentInfo->GetDuration();
const char* const pTitle_ = pSegmentInfo->GetTitleAsUTF8();
const wchar_t* const pTitle = utf8towcs(pTitle_);
const char* const pMuxingApp_ = pSegmentInfo->GetMuxingAppAsUTF8();
const wchar_t* const pMuxingApp = utf8towcs(pMuxingApp_);
const char* const pWritingApp_ = pSegmentInfo->GetWritingAppAsUTF8();
const wchar_t* const pWritingApp = utf8towcs(pWritingApp_);
printf("\n");
printf("\t\t\t Segment Info\n");
printf("\t\tTimeCodeScale\t\t: %lld \n", timeCodeScale);
printf("\t\tDuration\t\t: %lld\n", duration_ns);
const double duration_sec = double(duration_ns) / 1000000000;
printf("\t\tDuration(secs)\t\t: %7.3lf\n", duration_sec);
if (pTitle == NULL)
printf("\t\tTrack Name\t\t: NULL\n");
else
{
printf("\t\tTrack Name\t\t: %ls\n", pTitle);
delete [] pTitle;
}
if (pMuxingApp == NULL)
printf("\t\tMuxing App\t\t: NULL\n");
else
{
printf("\t\tMuxing App\t\t: %ls\n", pMuxingApp);
delete [] pMuxingApp;
}
if (pWritingApp == NULL)
printf("\t\tWriting App\t\t: NULL\n");
else
{
printf("\t\tWriting App\t\t: %ls\n", pWritingApp);
delete [] pWritingApp;
}
// pos of segment payload
printf("\t\tPosition(Segment)\t: %lld\n", pSegment->m_start);
// size of segment payload
printf("\t\tSize(Segment)\t\t: %lld\n", pSegment->m_size);
const mkvparser::Tracks* pTracks = pSegment->GetTracks();
unsigned long i = 0;
const unsigned long j = pTracks->GetTracksCount();
enum { VIDEO_TRACK = 1, AUDIO_TRACK = 2 };
printf("\n\t\t\t Track Info\n");
while (i != j)
{
const Track* const pTrack = pTracks->GetTrackByIndex(i++);
if (pTrack == NULL)
continue;
const long long trackType = pTrack->GetType();
const long long trackNumber = pTrack->GetNumber();
const unsigned long long trackUid = pTrack->GetUid();
const wchar_t* const pTrackName = utf8towcs(pTrack->GetNameAsUTF8());
printf("\t\tTrack Type\t\t: %lld\n", trackType);
printf("\t\tTrack Number\t\t: %lld\n", trackNumber);
printf("\t\tTrack Uid\t\t: %lld\n", trackUid);
if (pTrackName == NULL)
printf("\t\tTrack Name\t\t: NULL\n");
else
{
printf("\t\tTrack Name\t\t: %ls \n", pTrackName);
delete [] pTrackName;
}
const char* const pCodecId = pTrack->GetCodecId();
if (pCodecId == NULL)
printf("\t\tCodec Id\t\t: NULL\n");
else
printf("\t\tCodec Id\t\t: %s\n", pCodecId);
const char* const pCodecName_ = pTrack->GetCodecNameAsUTF8();
const wchar_t* const pCodecName = utf8towcs(pCodecName_);
if (pCodecName == NULL)
printf("\t\tCodec Name\t\t: NULL\n");
else
{
printf("\t\tCodec Name\t\t: %ls\n", pCodecName);
delete [] pCodecName;
}
if (trackType == VIDEO_TRACK)
{
const VideoTrack* const pVideoTrack =
static_cast<const VideoTrack*>(pTrack);
const long long width = pVideoTrack->GetWidth();
printf("\t\tVideo Width\t\t: %lld\n", width);
const long long height = pVideoTrack->GetHeight();
printf("\t\tVideo Height\t\t: %lld\n", height);
const double rate = pVideoTrack->GetFrameRate();
printf("\t\tVideo Rate\t\t: %f\n",rate);
}
if (trackType == AUDIO_TRACK)
{
const AudioTrack* const pAudioTrack =
static_cast<const AudioTrack*>(pTrack);
const long long channels = pAudioTrack->GetChannels();
printf("\t\tAudio Channels\t\t: %lld\n", channels);
const long long bitDepth = pAudioTrack->GetBitDepth();
printf("\t\tAudio BitDepth\t\t: %lld\n", bitDepth);
const double sampleRate = pAudioTrack->GetSamplingRate();
printf("\t\tAddio Sample Rate\t: %.3f\n", sampleRate);
}
}
printf("\n\n\t\t\t Cluster Info\n");
const unsigned long clusterCount = pSegment->GetCount();
printf("\t\tCluster Count\t: %ld\n\n", clusterCount);
if (clusterCount == 0)
{
printf("\t\tSegment has no clusters.\n");
delete pSegment;
return -1;
}
const mkvparser::Cluster* pCluster = pSegment->GetFirst();
while ((pCluster != NULL) && !pCluster->EOS())
{
const long long timeCode = pCluster->GetTimeCode();
printf("\t\tCluster Time Code\t: %lld\n", timeCode);
const long long time_ns = pCluster->GetTime();
printf("\t\tCluster Time (ns)\t: %lld\n", time_ns);
const BlockEntry* pBlockEntry = pCluster->GetFirst();
while ((pBlockEntry != NULL) && !pBlockEntry->EOS())
{
const Block* const pBlock = pBlockEntry->GetBlock();
const long long trackNum = pBlock->GetTrackNumber();
const unsigned long tn = static_cast<unsigned long>(trackNum);
const Track* const pTrack = pTracks->GetTrackByNumber(tn);
const long long trackType = pTrack->GetType();
const int frameCount = pBlock->GetFrameCount();
const long long time_ns = pBlock->GetTime(pCluster);
printf("\t\t\tBlock\t\t:%s,%s,%15lld\n",
(trackType == VIDEO_TRACK) ? "V" : "A",
pBlock->IsKey() ? "I" : "P",
time_ns);
for (int i = 0; i < frameCount; ++i)
{
const Block::Frame& theFrame = pBlock->GetFrame(i);
const long size = theFrame.len;
const long long offset = theFrame.pos;
printf("\t\t\t %15ld,%15llx\n", size, offset);
}
pBlockEntry = pCluster->GetNext(pBlockEntry);
}
pCluster = pSegment->GetNext(pCluster);
}
delete pSegment;
return 0;
}
// Copyright (c) 2010 The WebM project authors. All Rights Reserved.
//
// Use of this source code is governed by a BSD-style license
// that can be found in the LICENSE file in the root of the source
// tree. An additional intellectual property rights grant can be found
// in the file PATENTS. All contributing project authors may
// be found in the AUTHORS file in the root of the source tree.
//
// This sample application demonstrates how to use the Matroska parser
// library, which allows clients to handle a Matroska format file.
#include <memory>
#include "mkvreader.hpp"
#include "mkvparser.hpp"
#ifdef _MSC_VER
// Disable MSVC warnings that suggest making code non-portable.
#pragma warning(disable : 4996)
#endif
static const wchar_t* utf8towcs(const char* str) {
if (str == NULL)
return NULL;
// TODO: this probably requires that the locale be
// configured somehow:
const size_t size = mbstowcs(NULL, str, 0);
if (size == 0 || size == static_cast<size_t>(-1))
return NULL;
wchar_t* const val = new (std::nothrow) wchar_t[size + 1];
if (val == NULL)
return NULL;
mbstowcs(val, str, size);
val[size] = L'\0';
return val;
}
bool InputHasCues(const mkvparser::Segment* const segment) {
const mkvparser::Cues* const cues = segment->GetCues();
if (cues == NULL)
return false;
while (!cues->DoneParsing())
cues->LoadCuePoint();
const mkvparser::CuePoint* const cue_point = cues->GetFirst();
if (cue_point == NULL)
return false;
return true;
}
int main(int argc, char* argv[]) {
if (argc == 1) {
printf("\t\t\tMkv Parser Sample Application\n");
printf("\t\t\tUsage: \n");
printf("\t\t\t ./sample [input file] \n");
printf("\t\t\t ./sample sample.mkv \n");
return -1;
}
using namespace mkvparser;
MkvReader reader;
if (reader.Open(argv[1])) {
printf("\n Filename is invalid or error while opening.\n");
return -1;
}
int maj, min, build, rev;
GetVersion(maj, min, build, rev);
printf("\t\t libmkv verison: %d.%d.%d.%d\n", maj, min, build, rev);
long long pos = 0;
EBMLHeader ebmlHeader;
long long ret = ebmlHeader.Parse(&reader, pos);
if (ret < 0) {
printf("\n EBMLHeader::Parse() failed.");
return -1;
}
printf("\t\t\t EBML Header\n");
printf("\t\tEBML Version\t\t: %lld\n", ebmlHeader.m_version);
printf("\t\tEBML MaxIDLength\t: %lld\n", ebmlHeader.m_maxIdLength);
printf("\t\tEBML MaxSizeLength\t: %lld\n", ebmlHeader.m_maxSizeLength);
printf("\t\tDoc Type\t\t: %s\n", ebmlHeader.m_docType);
printf("\t\tPos\t\t\t: %lld\n", pos);
typedef mkvparser::Segment seg_t;
seg_t* pSegment_;
ret = seg_t::CreateInstance(&reader, pos, pSegment_);
if (ret) {
printf("\n Segment::CreateInstance() failed.");
return -1;
}
const std::auto_ptr<seg_t> pSegment(pSegment_);
ret = pSegment->Load();
if (ret < 0) {
printf("\n Segment::Load() failed.");
return -1;
}
const SegmentInfo* const pSegmentInfo = pSegment->GetInfo();
if (pSegmentInfo == NULL) {
printf("\n Segment::GetInfo() failed.");
return -1;
}
const long long timeCodeScale = pSegmentInfo->GetTimeCodeScale();
const long long duration_ns = pSegmentInfo->GetDuration();
const char* const pTitle_ = pSegmentInfo->GetTitleAsUTF8();
const wchar_t* const pTitle = utf8towcs(pTitle_);
const char* const pMuxingApp_ = pSegmentInfo->GetMuxingAppAsUTF8();
const wchar_t* const pMuxingApp = utf8towcs(pMuxingApp_);
const char* const pWritingApp_ = pSegmentInfo->GetWritingAppAsUTF8();
const wchar_t* const pWritingApp = utf8towcs(pWritingApp_);
printf("\n");
printf("\t\t\t Segment Info\n");
printf("\t\tTimeCodeScale\t\t: %lld \n", timeCodeScale);
printf("\t\tDuration\t\t: %lld\n", duration_ns);
const double duration_sec = double(duration_ns) / 1000000000;
printf("\t\tDuration(secs)\t\t: %7.3lf\n", duration_sec);
if (pTitle == NULL)
printf("\t\tTrack Name\t\t: NULL\n");
else {
printf("\t\tTrack Name\t\t: %ls\n", pTitle);
delete[] pTitle;
}
if (pMuxingApp == NULL)
printf("\t\tMuxing App\t\t: NULL\n");
else {
printf("\t\tMuxing App\t\t: %ls\n", pMuxingApp);
delete[] pMuxingApp;
}
if (pWritingApp == NULL)
printf("\t\tWriting App\t\t: NULL\n");
else {
printf("\t\tWriting App\t\t: %ls\n", pWritingApp);
delete[] pWritingApp;
}
// pos of segment payload
printf("\t\tPosition(Segment)\t: %lld\n", pSegment->m_start);
// size of segment payload
printf("\t\tSize(Segment)\t\t: %lld\n", pSegment->m_size);
const mkvparser::Tracks* pTracks = pSegment->GetTracks();
unsigned long track_num = 0;
const unsigned long num_tracks = pTracks->GetTracksCount();
printf("\n\t\t\t Track Info\n");
while (track_num != num_tracks) {
const Track* const pTrack = pTracks->GetTrackByIndex(track_num++);
if (pTrack == NULL)
continue;
const long trackType = pTrack->GetType();
const long trackNumber = pTrack->GetNumber();
const unsigned long long trackUid = pTrack->GetUid();
const wchar_t* const pTrackName = utf8towcs(pTrack->GetNameAsUTF8());
printf("\t\tTrack Type\t\t: %ld\n", trackType);
printf("\t\tTrack Number\t\t: %ld\n", trackNumber);
printf("\t\tTrack Uid\t\t: %lld\n", trackUid);
if (pTrackName == NULL)
printf("\t\tTrack Name\t\t: NULL\n");
else {
printf("\t\tTrack Name\t\t: %ls \n", pTrackName);
delete[] pTrackName;
}
const char* const pCodecId = pTrack->GetCodecId();
if (pCodecId == NULL)
printf("\t\tCodec Id\t\t: NULL\n");
else
printf("\t\tCodec Id\t\t: %s\n", pCodecId);
const char* const pCodecName_ = pTrack->GetCodecNameAsUTF8();
const wchar_t* const pCodecName = utf8towcs(pCodecName_);
if (pCodecName == NULL)
printf("\t\tCodec Name\t\t: NULL\n");
else {
printf("\t\tCodec Name\t\t: %ls\n", pCodecName);
delete[] pCodecName;
}
if (trackType == mkvparser::Track::kVideo) {
const VideoTrack* const pVideoTrack =
static_cast<const VideoTrack*>(pTrack);
const long long width = pVideoTrack->GetWidth();
printf("\t\tVideo Width\t\t: %lld\n", width);
const long long height = pVideoTrack->GetHeight();
printf("\t\tVideo Height\t\t: %lld\n", height);
const double rate = pVideoTrack->GetFrameRate();
printf("\t\tVideo Rate\t\t: %f\n", rate);
}
if (trackType == mkvparser::Track::kAudio) {
const AudioTrack* const pAudioTrack =
static_cast<const AudioTrack*>(pTrack);
const long long channels = pAudioTrack->GetChannels();
printf("\t\tAudio Channels\t\t: %lld\n", channels);
const long long bitDepth = pAudioTrack->GetBitDepth();
printf("\t\tAudio BitDepth\t\t: %lld\n", bitDepth);
const double sampleRate = pAudioTrack->GetSamplingRate();
printf("\t\tAddio Sample Rate\t: %.3f\n", sampleRate);
const long long codecDelay = pAudioTrack->GetCodecDelay();
printf("\t\tAudio Codec Delay\t\t: %lld\n", codecDelay);
const long long seekPreRoll = pAudioTrack->GetSeekPreRoll();
printf("\t\tAudio Seek Pre Roll\t\t: %lld\n", seekPreRoll);
}
}
printf("\n\n\t\t\t Cluster Info\n");
const unsigned long clusterCount = pSegment->GetCount();
printf("\t\tCluster Count\t: %ld\n\n", clusterCount);
if (clusterCount == 0) {
printf("\t\tSegment has no clusters.\n");
return -1;
}
const mkvparser::Cluster* pCluster = pSegment->GetFirst();
while ((pCluster != NULL) && !pCluster->EOS()) {
const long long timeCode = pCluster->GetTimeCode();
printf("\t\tCluster Time Code\t: %lld\n", timeCode);
const long long time_ns = pCluster->GetTime();
printf("\t\tCluster Time (ns)\t: %lld\n", time_ns);
const BlockEntry* pBlockEntry;
long status = pCluster->GetFirst(pBlockEntry);
if (status < 0) // error
{
printf("\t\tError parsing first block of cluster\n");
fflush(stdout);
return -1;
}
while ((pBlockEntry != NULL) && !pBlockEntry->EOS()) {
const Block* const pBlock = pBlockEntry->GetBlock();
const long long trackNum = pBlock->GetTrackNumber();
const unsigned long tn = static_cast<unsigned long>(trackNum);
const Track* const pTrack = pTracks->GetTrackByNumber(tn);
if (pTrack == NULL)
printf("\t\t\tBlock\t\t:UNKNOWN TRACK TYPE\n");
else {
const long long trackType = pTrack->GetType();
const int frameCount = pBlock->GetFrameCount();
const long long time_ns = pBlock->GetTime(pCluster);
const long long discard_padding = pBlock->GetDiscardPadding();
printf("\t\t\tBlock\t\t:%s,%s,%15lld,%lld\n",
(trackType == mkvparser::Track::kVideo) ? "V" : "A",
pBlock->IsKey() ? "I" : "P", time_ns, discard_padding);
for (int i = 0; i < frameCount; ++i) {
const Block::Frame& theFrame = pBlock->GetFrame(i);
const long size = theFrame.len;
const long long offset = theFrame.pos;
printf("\t\t\t %15ld,%15llx\n", size, offset);
}
}
status = pCluster->GetNext(pBlockEntry, pBlockEntry);
if (status < 0) {
printf("\t\t\tError parsing next block of cluster\n");
fflush(stdout);
return -1;
}
}
pCluster = pSegment->GetNext(pCluster);
}
if (InputHasCues(pSegment.get())) {
// Walk them.
const mkvparser::Cues* const cues = pSegment->GetCues();
const mkvparser::CuePoint* cue = cues->GetFirst();
int cue_point_num = 1;
printf("\t\tCues\n");
do {
for (track_num = 0; track_num < num_tracks; ++track_num) {
const mkvparser::Track* const track =
pTracks->GetTrackByIndex(track_num);
const mkvparser::CuePoint::TrackPosition* const track_pos =
cue->Find(track);
if (track_pos != NULL) {
const char track_type =
(track->GetType() == mkvparser::Track::kVideo) ? 'V' : 'A';
printf(
"\t\t\tCue Point %4d Track %3lu(%c) Time %14lld "
"Block %4lld Pos %8llx\n",
cue_point_num, track->GetNumber(), track_type,
cue->GetTime(pSegment.get()), track_pos->m_block,
track_pos->m_pos);
}
}
cue = cues->GetNext(cue);
++cue_point_num;
} while (cue != NULL);
}
const mkvparser::Tags* const tags = pSegment->GetTags();
if (tags && tags->GetTagCount() > 0) {
printf("\t\tTags\n");
for (int i = 0; i < tags->GetTagCount(); ++i) {
const mkvparser::Tags::Tag* const tag = tags->GetTag(i);
printf("\t\t\tTag\n");
for (int j = 0; j < tag->GetSimpleTagCount(); j++) {
const mkvparser::Tags::SimpleTag* const simple_tag =
tag->GetSimpleTag(j);
printf("\t\t\t\tSimple Tag \"%s\" Value \"%s\"\n",
simple_tag->GetTagName(), simple_tag->GetTagString());
}
}
}
fflush(stdout);
return 0;
}

View File

@@ -1,193 +0,0 @@
<?xml version="1.0" encoding="Windows-1252"?>
<VisualStudioProject
ProjectType="Visual C++"
Version="8.00"
Name="sample"
ProjectGUID="{0CB5681F-6065-490C-98C8-05531732ED7E}"
RootNamespace="sample"
Keyword="Win32Proj"
>
<Platforms>
<Platform
Name="Win32"
/>
</Platforms>
<ToolFiles>
</ToolFiles>
<Configurations>
<Configuration
Name="Debug|Win32"
OutputDirectory="$(SolutionDir)$(ConfigurationName)"
IntermediateDirectory="$(ConfigurationName)"
ConfigurationType="1"
CharacterSet="1"
>
<Tool
Name="VCPreBuildEventTool"
/>
<Tool
Name="VCCustomBuildTool"
/>
<Tool
Name="VCXMLDataGeneratorTool"
/>
<Tool
Name="VCWebServiceProxyGeneratorTool"
/>
<Tool
Name="VCMIDLTool"
/>
<Tool
Name="VCCLCompilerTool"
Optimization="0"
AdditionalIncludeDirectories="..\"
PreprocessorDefinitions="WIN32;_DEBUG;_CONSOLE"
MinimalRebuild="true"
BasicRuntimeChecks="3"
RuntimeLibrary="3"
UsePrecompiledHeader="0"
WarningLevel="3"
Detect64BitPortabilityProblems="true"
DebugInformationFormat="4"
/>
<Tool
Name="VCManagedResourceCompilerTool"
/>
<Tool
Name="VCResourceCompilerTool"
/>
<Tool
Name="VCPreLinkEventTool"
/>
<Tool
Name="VCLinkerTool"
AdditionalDependencies=".\Debug\mkvparser.lib"
LinkIncremental="2"
GenerateDebugInformation="true"
SubSystem="1"
TargetMachine="1"
/>
<Tool
Name="VCALinkTool"
/>
<Tool
Name="VCManifestTool"
/>
<Tool
Name="VCXDCMakeTool"
/>
<Tool
Name="VCBscMakeTool"
/>
<Tool
Name="VCFxCopTool"
/>
<Tool
Name="VCAppVerifierTool"
/>
<Tool
Name="VCWebDeploymentTool"
/>
<Tool
Name="VCPostBuildEventTool"
/>
</Configuration>
<Configuration
Name="Release|Win32"
OutputDirectory="$(SolutionDir)$(ConfigurationName)"
IntermediateDirectory="$(ConfigurationName)"
ConfigurationType="1"
CharacterSet="1"
WholeProgramOptimization="1"
>
<Tool
Name="VCPreBuildEventTool"
/>
<Tool
Name="VCCustomBuildTool"
/>
<Tool
Name="VCXMLDataGeneratorTool"
/>
<Tool
Name="VCWebServiceProxyGeneratorTool"
/>
<Tool
Name="VCMIDLTool"
/>
<Tool
Name="VCCLCompilerTool"
PreprocessorDefinitions="WIN32;NDEBUG;_CONSOLE"
RuntimeLibrary="2"
UsePrecompiledHeader="0"
WarningLevel="3"
Detect64BitPortabilityProblems="true"
DebugInformationFormat="3"
/>
<Tool
Name="VCManagedResourceCompilerTool"
/>
<Tool
Name="VCResourceCompilerTool"
/>
<Tool
Name="VCPreLinkEventTool"
/>
<Tool
Name="VCLinkerTool"
LinkIncremental="1"
GenerateDebugInformation="true"
SubSystem="1"
OptimizeReferences="2"
EnableCOMDATFolding="2"
TargetMachine="1"
/>
<Tool
Name="VCALinkTool"
/>
<Tool
Name="VCManifestTool"
/>
<Tool
Name="VCXDCMakeTool"
/>
<Tool
Name="VCBscMakeTool"
/>
<Tool
Name="VCFxCopTool"
/>
<Tool
Name="VCAppVerifierTool"
/>
<Tool
Name="VCWebDeploymentTool"
/>
<Tool
Name="VCPostBuildEventTool"
/>
</Configuration>
</Configurations>
<References>
</References>
<Files>
<Filter
Name="Source Files"
Filter="cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx"
UniqueIdentifier="{4FC737F1-C7A5-4376-A066-2A32D752A2FF}"
>
<File
RelativePath=".\sample.cpp"
>
</File>
</Filter>
<Filter
Name="Header Files"
Filter="h;hpp;hxx;hm;inl;inc;xsd"
UniqueIdentifier="{93995380-89BD-4b04-88EB-625FBE52EBFB}"
>
</Filter>
</Files>
<Globals>
</Globals>
</VisualStudioProject>

View File

@@ -1,193 +0,0 @@
<?xml version="1.0" encoding="Windows-1252"?>
<VisualStudioProject
ProjectType="Visual C++"
Version="9.00"
Name="sample"
ProjectGUID="{0CB5681F-6065-490C-98C8-05531732ED7E}"
RootNamespace="sample"
Keyword="Win32Proj"
TargetFrameworkVersion="131072"
>
<Platforms>
<Platform
Name="Win32"
/>
</Platforms>
<ToolFiles>
</ToolFiles>
<Configurations>
<Configuration
Name="Debug|Win32"
OutputDirectory="$(SolutionDir)$(ConfigurationName)"
IntermediateDirectory="$(ConfigurationName)"
ConfigurationType="1"
CharacterSet="1"
>
<Tool
Name="VCPreBuildEventTool"
/>
<Tool
Name="VCCustomBuildTool"
/>
<Tool
Name="VCXMLDataGeneratorTool"
/>
<Tool
Name="VCWebServiceProxyGeneratorTool"
/>
<Tool
Name="VCMIDLTool"
/>
<Tool
Name="VCCLCompilerTool"
Optimization="0"
AdditionalIncludeDirectories="..\"
PreprocessorDefinitions="WIN32;_DEBUG;_CONSOLE"
MinimalRebuild="false"
BasicRuntimeChecks="3"
RuntimeLibrary="1"
UsePrecompiledHeader="0"
WarningLevel="4"
Detect64BitPortabilityProblems="false"
DebugInformationFormat="1"
/>
<Tool
Name="VCManagedResourceCompilerTool"
/>
<Tool
Name="VCResourceCompilerTool"
/>
<Tool
Name="VCPreLinkEventTool"
/>
<Tool
Name="VCLinkerTool"
AdditionalDependencies=".\Debug\mkvparser.lib"
LinkIncremental="2"
GenerateDebugInformation="true"
SubSystem="1"
RandomizedBaseAddress="1"
DataExecutionPrevention="0"
TargetMachine="1"
/>
<Tool
Name="VCALinkTool"
/>
<Tool
Name="VCManifestTool"
/>
<Tool
Name="VCXDCMakeTool"
/>
<Tool
Name="VCBscMakeTool"
/>
<Tool
Name="VCFxCopTool"
/>
<Tool
Name="VCAppVerifierTool"
/>
<Tool
Name="VCPostBuildEventTool"
/>
</Configuration>
<Configuration
Name="Release|Win32"
OutputDirectory="$(SolutionDir)$(ConfigurationName)"
IntermediateDirectory="$(ConfigurationName)"
ConfigurationType="1"
CharacterSet="1"
WholeProgramOptimization="1"
>
<Tool
Name="VCPreBuildEventTool"
/>
<Tool
Name="VCCustomBuildTool"
/>
<Tool
Name="VCXMLDataGeneratorTool"
/>
<Tool
Name="VCWebServiceProxyGeneratorTool"
/>
<Tool
Name="VCMIDLTool"
/>
<Tool
Name="VCCLCompilerTool"
PreprocessorDefinitions="WIN32;NDEBUG;_CONSOLE"
RuntimeLibrary="2"
UsePrecompiledHeader="0"
WarningLevel="3"
Detect64BitPortabilityProblems="false"
DebugInformationFormat="3"
/>
<Tool
Name="VCManagedResourceCompilerTool"
/>
<Tool
Name="VCResourceCompilerTool"
/>
<Tool
Name="VCPreLinkEventTool"
/>
<Tool
Name="VCLinkerTool"
AdditionalDependencies=".\Release\mkvparser.lib"
LinkIncremental="1"
GenerateDebugInformation="true"
SubSystem="1"
OptimizeReferences="2"
EnableCOMDATFolding="2"
RandomizedBaseAddress="1"
DataExecutionPrevention="0"
TargetMachine="1"
/>
<Tool
Name="VCALinkTool"
/>
<Tool
Name="VCManifestTool"
/>
<Tool
Name="VCXDCMakeTool"
/>
<Tool
Name="VCBscMakeTool"
/>
<Tool
Name="VCFxCopTool"
/>
<Tool
Name="VCAppVerifierTool"
/>
<Tool
Name="VCPostBuildEventTool"
/>
</Configuration>
</Configurations>
<References>
</References>
<Files>
<Filter
Name="Source Files"
Filter="cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx"
UniqueIdentifier="{4FC737F1-C7A5-4376-A066-2A32D752A2FF}"
>
<File
RelativePath=".\sample.cpp"
>
</File>
</Filter>
<Filter
Name="Header Files"
Filter="h;hpp;hxx;hm;inl;inc;xsd"
UniqueIdentifier="{93995380-89BD-4b04-88EB-625FBE52EBFB}"
>
</Filter>
</Files>
<Globals>
</Globals>
</VisualStudioProject>

583
sample_muxer.cpp Normal file
View File

@@ -0,0 +1,583 @@
// Copyright (c) 2011 The WebM project authors. All Rights Reserved.
//
// Use of this source code is governed by a BSD-style license
// that can be found in the LICENSE file in the root of the source
// tree. An additional intellectual property rights grant can be found
// in the file PATENTS. All contributing project authors may
// be found in the AUTHORS file in the root of the source tree.
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <memory>
#include <list>
#include <string>
// libwebm parser includes
#include "mkvreader.hpp"
#include "mkvparser.hpp"
// libwebm muxer includes
#include "mkvmuxer.hpp"
#include "mkvwriter.hpp"
#include "mkvmuxerutil.hpp"
#include "sample_muxer_metadata.h"
using mkvmuxer::int64;
using mkvmuxer::uint64;
#ifdef _MSC_VER
// Disable MSVC warnings that suggest making code non-portable.
#pragma warning(disable : 4996)
#endif
namespace {
void Usage() {
printf("Usage: sample_muxer -i input -o output [options]\n");
printf("\n");
printf("Main options:\n");
printf(" -h | -? show help\n");
printf(" -video <int> >0 outputs video\n");
printf(" -audio <int> >0 outputs audio\n");
printf(" -live <int> >0 puts the muxer into live mode\n");
printf(" 0 puts the muxer into file mode\n");
printf(" -output_cues <int> >0 outputs cues element\n");
printf(" -cues_on_video_track <int> >0 outputs cues on video track\n");
printf(" -cues_on_audio_track <int> >0 outputs cues on audio track\n");
printf(" -max_cluster_duration <double> in seconds\n");
printf(" -max_cluster_size <int> in bytes\n");
printf(" -switch_tracks <int> >0 switches tracks in output\n");
printf(" -audio_track_number <int> >0 Changes the audio track number\n");
printf(" -video_track_number <int> >0 Changes the video track number\n");
printf(" -chunking <string> Chunk output\n");
printf(" -copy_tags <int> >0 Copies the tags\n");
printf("\n");
printf("Video options:\n");
printf(" -display_width <int> Display width in pixels\n");
printf(" -display_height <int> Display height in pixels\n");
printf(" -stereo_mode <int> 3D video mode\n");
printf("\n");
printf("Cues options:\n");
printf(" -output_cues_block_number <int> >0 outputs cue block number\n");
printf(" -cues_before_clusters <int> >0 puts Cues before Clusters\n");
printf("\n");
printf("Metadata options:\n");
printf(" -webvtt-subtitles <vttfile> ");
printf("add WebVTT subtitles as metadata track\n");
printf(" -webvtt-captions <vttfile> ");
printf("add WebVTT captions as metadata track\n");
printf(" -webvtt-descriptions <vttfile> ");
printf("add WebVTT descriptions as metadata track\n");
printf(" -webvtt-metadata <vttfile> ");
printf("add WebVTT subtitles as metadata track\n");
printf(" -webvtt-chapters <vttfile> ");
printf("add WebVTT chapters as MKV chapters element\n");
}
struct MetadataFile {
const char* name;
SampleMuxerMetadata::Kind kind;
};
typedef std::list<MetadataFile> metadata_files_t;
// Cache the WebVTT filenames specified as command-line args.
bool LoadMetadataFiles(const metadata_files_t& files,
SampleMuxerMetadata* metadata) {
typedef metadata_files_t::const_iterator iter_t;
iter_t i = files.begin();
const iter_t j = files.end();
while (i != j) {
const metadata_files_t::value_type& v = *i++;
if (!metadata->Load(v.name, v.kind))
return false;
}
return true;
}
int ParseArgWebVTT(char* argv[], int* argv_index, int argc_check,
metadata_files_t* metadata_files) {
int& i = *argv_index;
enum { kCount = 5 };
struct Arg {
const char* name;
SampleMuxerMetadata::Kind kind;
};
const Arg args[kCount] = {
{"-webvtt-subtitles", SampleMuxerMetadata::kSubtitles},
{"-webvtt-captions", SampleMuxerMetadata::kCaptions},
{"-webvtt-descriptions", SampleMuxerMetadata::kDescriptions},
{"-webvtt-metadata", SampleMuxerMetadata::kMetadata},
{"-webvtt-chapters", SampleMuxerMetadata::kChapters}};
for (int idx = 0; idx < kCount; ++idx) {
const Arg& arg = args[idx];
if (strcmp(arg.name, argv[i]) != 0) // no match
continue;
++i; // consume arg name here
if (i > argc_check) {
printf("missing value for %s\n", arg.name);
return -1; // error
}
MetadataFile f;
f.name = argv[i]; // arg value is consumed via caller's loop idx
f.kind = arg.kind;
metadata_files->push_back(f);
return 1; // successfully parsed WebVTT arg
}
return 0; // not a WebVTT arg
}
} // end namespace
int main(int argc, char* argv[]) {
char* input = NULL;
char* output = NULL;
// Segment variables
bool output_video = true;
bool output_audio = true;
bool live_mode = false;
bool output_cues = true;
bool cues_before_clusters = false;
bool cues_on_video_track = true;
bool cues_on_audio_track = false;
uint64 max_cluster_duration = 0;
uint64 max_cluster_size = 0;
bool switch_tracks = false;
int audio_track_number = 0; // 0 tells muxer to decide.
int video_track_number = 0; // 0 tells muxer to decide.
bool chunking = false;
bool copy_tags = false;
const char* chunk_name = NULL;
bool output_cues_block_number = true;
uint64 display_width = 0;
uint64 display_height = 0;
uint64 stereo_mode = 0;
metadata_files_t metadata_files;
const int argc_check = argc - 1;
for (int i = 1; i < argc; ++i) {
char* end;
if (!strcmp("-h", argv[i]) || !strcmp("-?", argv[i])) {
Usage();
return EXIT_SUCCESS;
} else if (!strcmp("-i", argv[i]) && i < argc_check) {
input = argv[++i];
} else if (!strcmp("-o", argv[i]) && i < argc_check) {
output = argv[++i];
} else if (!strcmp("-video", argv[i]) && i < argc_check) {
output_video = strtol(argv[++i], &end, 10) == 0 ? false : true;
} else if (!strcmp("-audio", argv[i]) && i < argc_check) {
output_audio = strtol(argv[++i], &end, 10) == 0 ? false : true;
} else if (!strcmp("-live", argv[i]) && i < argc_check) {
live_mode = strtol(argv[++i], &end, 10) == 0 ? false : true;
} else if (!strcmp("-output_cues", argv[i]) && i < argc_check) {
output_cues = strtol(argv[++i], &end, 10) == 0 ? false : true;
} else if (!strcmp("-cues_before_clusters", argv[i]) && i < argc_check) {
cues_before_clusters = strtol(argv[++i], &end, 10) == 0 ? false : true;
} else if (!strcmp("-cues_on_video_track", argv[i]) && i < argc_check) {
cues_on_video_track = strtol(argv[++i], &end, 10) == 0 ? false : true;
if (cues_on_video_track)
cues_on_audio_track = false;
} else if (!strcmp("-cues_on_audio_track", argv[i]) && i < argc_check) {
cues_on_audio_track = strtol(argv[++i], &end, 10) == 0 ? false : true;
if (cues_on_audio_track)
cues_on_video_track = false;
} else if (!strcmp("-max_cluster_duration", argv[i]) && i < argc_check) {
const double seconds = strtod(argv[++i], &end);
max_cluster_duration = static_cast<uint64>(seconds * 1000000000.0);
} else if (!strcmp("-max_cluster_size", argv[i]) && i < argc_check) {
max_cluster_size = strtol(argv[++i], &end, 10);
} else if (!strcmp("-switch_tracks", argv[i]) && i < argc_check) {
switch_tracks = strtol(argv[++i], &end, 10) == 0 ? false : true;
} else if (!strcmp("-audio_track_number", argv[i]) && i < argc_check) {
audio_track_number = strtol(argv[++i], &end, 10);
} else if (!strcmp("-video_track_number", argv[i]) && i < argc_check) {
video_track_number = strtol(argv[++i], &end, 10);
} else if (!strcmp("-chunking", argv[i]) && i < argc_check) {
chunking = true;
chunk_name = argv[++i];
} else if (!strcmp("-copy_tags", argv[i]) && i < argc_check) {
copy_tags = strtol(argv[++i], &end, 10) == 0 ? false : true;
} else if (!strcmp("-display_width", argv[i]) && i < argc_check) {
display_width = strtol(argv[++i], &end, 10);
} else if (!strcmp("-display_height", argv[i]) && i < argc_check) {
display_height = strtol(argv[++i], &end, 10);
} else if (!strcmp("-stereo_mode", argv[i]) && i < argc_check) {
stereo_mode = strtol(argv[++i], &end, 10);
} else if (!strcmp("-output_cues_block_number", argv[i]) &&
i < argc_check) {
output_cues_block_number =
strtol(argv[++i], &end, 10) == 0 ? false : true;
} else if (int e = ParseArgWebVTT(argv, &i, argc_check, &metadata_files)) {
if (e < 0)
return EXIT_FAILURE;
}
}
if (input == NULL || output == NULL) {
Usage();
return EXIT_FAILURE;
}
// Get parser header info
mkvparser::MkvReader reader;
if (reader.Open(input)) {
printf("\n Filename is invalid or error while opening.\n");
return EXIT_FAILURE;
}
long long pos = 0;
mkvparser::EBMLHeader ebml_header;
long long ret = ebml_header.Parse(&reader, pos);
if (ret) {
printf("\n EBMLHeader::Parse() failed.");
return EXIT_FAILURE;
}
mkvparser::Segment* parser_segment_;
ret = mkvparser::Segment::CreateInstance(&reader, pos, parser_segment_);
if (ret) {
printf("\n Segment::CreateInstance() failed.");
return EXIT_FAILURE;
}
const std::auto_ptr<mkvparser::Segment> parser_segment(parser_segment_);
ret = parser_segment->Load();
if (ret < 0) {
printf("\n Segment::Load() failed.");
return EXIT_FAILURE;
}
const mkvparser::SegmentInfo* const segment_info = parser_segment->GetInfo();
if (segment_info == NULL) {
printf("\n Segment::GetInfo() failed.");
return EXIT_FAILURE;
}
const long long timeCodeScale = segment_info->GetTimeCodeScale();
// Set muxer header info
mkvmuxer::MkvWriter writer;
char* temp_file = tmpnam(NULL);
if (!writer.Open(cues_before_clusters ? temp_file : output)) {
printf("\n Filename is invalid or error while opening.\n");
return EXIT_FAILURE;
}
// Set Segment element attributes
mkvmuxer::Segment muxer_segment;
if (!muxer_segment.Init(&writer)) {
printf("\n Could not initialize muxer segment!\n");
return EXIT_FAILURE;
}
if (live_mode)
muxer_segment.set_mode(mkvmuxer::Segment::kLive);
else
muxer_segment.set_mode(mkvmuxer::Segment::kFile);
if (chunking)
muxer_segment.SetChunking(true, chunk_name);
if (max_cluster_duration > 0)
muxer_segment.set_max_cluster_duration(max_cluster_duration);
if (max_cluster_size > 0)
muxer_segment.set_max_cluster_size(max_cluster_size);
muxer_segment.OutputCues(output_cues);
// Set SegmentInfo element attributes
mkvmuxer::SegmentInfo* const info = muxer_segment.GetSegmentInfo();
info->set_timecode_scale(timeCodeScale);
info->set_writing_app("sample_muxer");
const mkvparser::Tags* const tags = parser_segment->GetTags();
if (copy_tags && tags) {
for (int i = 0; i < tags->GetTagCount(); i++) {
const mkvparser::Tags::Tag* const tag = tags->GetTag(i);
mkvmuxer::Tag* muxer_tag = muxer_segment.AddTag();
for (int j = 0; j < tag->GetSimpleTagCount(); j++) {
const mkvparser::Tags::SimpleTag* const simple_tag =
tag->GetSimpleTag(j);
muxer_tag->add_simple_tag(simple_tag->GetTagName(),
simple_tag->GetTagString());
}
}
}
// Set Tracks element attributes
const mkvparser::Tracks* const parser_tracks = parser_segment->GetTracks();
unsigned long i = 0;
uint64 vid_track = 0; // no track added
uint64 aud_track = 0; // no track added
using mkvparser::Track;
while (i != parser_tracks->GetTracksCount()) {
int track_num = i++;
if (switch_tracks)
track_num = i % parser_tracks->GetTracksCount();
const mkvparser::Track* const parser_track =
parser_tracks->GetTrackByIndex(track_num);
if (parser_track == NULL)
continue;
// TODO(fgalligan): Add support for language to parser.
const char* const track_name = parser_track->GetNameAsUTF8();
const long long track_type = parser_track->GetType();
if (track_type == Track::kVideo && output_video) {
// Get the video track from the parser
const mkvparser::VideoTrack* const pVideoTrack =
static_cast<const mkvparser::VideoTrack*>(parser_track);
const long long width = pVideoTrack->GetWidth();
const long long height = pVideoTrack->GetHeight();
// Add the video track to the muxer
vid_track = muxer_segment.AddVideoTrack(static_cast<int>(width),
static_cast<int>(height),
video_track_number);
if (!vid_track) {
printf("\n Could not add video track.\n");
return EXIT_FAILURE;
}
mkvmuxer::VideoTrack* const video = static_cast<mkvmuxer::VideoTrack*>(
muxer_segment.GetTrackByNumber(vid_track));
if (!video) {
printf("\n Could not get video track.\n");
return EXIT_FAILURE;
}
if (track_name)
video->set_name(track_name);
video->set_codec_id(pVideoTrack->GetCodecId());
if (display_width > 0)
video->set_display_width(display_width);
if (display_height > 0)
video->set_display_height(display_height);
if (stereo_mode > 0)
video->SetStereoMode(stereo_mode);
const double rate = pVideoTrack->GetFrameRate();
if (rate > 0.0) {
video->set_frame_rate(rate);
}
} else if (track_type == Track::kAudio && output_audio) {
// Get the audio track from the parser
const mkvparser::AudioTrack* const pAudioTrack =
static_cast<const mkvparser::AudioTrack*>(parser_track);
const long long channels = pAudioTrack->GetChannels();
const double sample_rate = pAudioTrack->GetSamplingRate();
// Add the audio track to the muxer
aud_track = muxer_segment.AddAudioTrack(static_cast<int>(sample_rate),
static_cast<int>(channels),
audio_track_number);
if (!aud_track) {
printf("\n Could not add audio track.\n");
return EXIT_FAILURE;
}
mkvmuxer::AudioTrack* const audio = static_cast<mkvmuxer::AudioTrack*>(
muxer_segment.GetTrackByNumber(aud_track));
if (!audio) {
printf("\n Could not get audio track.\n");
return EXIT_FAILURE;
}
if (track_name)
audio->set_name(track_name);
audio->set_codec_id(pAudioTrack->GetCodecId());
size_t private_size;
const unsigned char* const private_data =
pAudioTrack->GetCodecPrivate(private_size);
if (private_size > 0) {
if (!audio->SetCodecPrivate(private_data, private_size)) {
printf("\n Could not add audio private data.\n");
return EXIT_FAILURE;
}
}
const long long bit_depth = pAudioTrack->GetBitDepth();
if (bit_depth > 0)
audio->set_bit_depth(bit_depth);
if (pAudioTrack->GetCodecDelay())
audio->set_codec_delay(pAudioTrack->GetCodecDelay());
if (pAudioTrack->GetSeekPreRoll())
audio->set_seek_pre_roll(pAudioTrack->GetSeekPreRoll());
}
}
// We have created all the video and audio tracks. If any WebVTT
// files were specified as command-line args, then parse them and
// add a track to the output file corresponding to each metadata
// input file.
SampleMuxerMetadata metadata;
if (!metadata.Init(&muxer_segment)) {
printf("\n Could not initialize metadata cache.\n");
return EXIT_FAILURE;
}
if (!LoadMetadataFiles(metadata_files, &metadata))
return EXIT_FAILURE;
if (!metadata.AddChapters())
return EXIT_FAILURE;
// Set Cues element attributes
mkvmuxer::Cues* const cues = muxer_segment.GetCues();
cues->set_output_block_number(output_cues_block_number);
if (cues_on_video_track && vid_track)
muxer_segment.CuesTrack(vid_track);
if (cues_on_audio_track && aud_track)
muxer_segment.CuesTrack(aud_track);
// Write clusters
unsigned char* data = NULL;
int data_len = 0;
const mkvparser::Cluster* cluster = parser_segment->GetFirst();
while ((cluster != NULL) && !cluster->EOS()) {
const mkvparser::BlockEntry* block_entry;
long status = cluster->GetFirst(block_entry);
if (status) {
printf("\n Could not get first block of cluster.\n");
return EXIT_FAILURE;
}
while ((block_entry != NULL) && !block_entry->EOS()) {
const mkvparser::Block* const block = block_entry->GetBlock();
const long long trackNum = block->GetTrackNumber();
const mkvparser::Track* const parser_track =
parser_tracks->GetTrackByNumber(static_cast<unsigned long>(trackNum));
// When |parser_track| is NULL, it means that the track number in the
// Block is invalid (i.e.) the was no TrackEntry corresponding to the
// track number. So we reject the file.
if (!parser_track) {
return EXIT_FAILURE;
}
const long long track_type = parser_track->GetType();
const long long time_ns = block->GetTime(cluster);
// Flush any metadata frames to the output file, before we write
// the current block.
if (!metadata.Write(time_ns))
return EXIT_FAILURE;
if ((track_type == Track::kAudio && output_audio) ||
(track_type == Track::kVideo && output_video)) {
const int frame_count = block->GetFrameCount();
for (int i = 0; i < frame_count; ++i) {
const mkvparser::Block::Frame& frame = block->GetFrame(i);
if (frame.len > data_len) {
delete[] data;
data = new unsigned char[frame.len];
if (!data)
return EXIT_FAILURE;
data_len = frame.len;
}
if (frame.Read(&reader, data))
return EXIT_FAILURE;
mkvmuxer::Frame muxer_frame;
if (!muxer_frame.Init(data, frame.len))
return EXIT_FAILURE;
muxer_frame.set_track_number(track_type == Track::kAudio ? aud_track :
vid_track);
if (block->GetDiscardPadding())
muxer_frame.set_discard_padding(block->GetDiscardPadding());
muxer_frame.set_timestamp(time_ns);
muxer_frame.set_is_key(block->IsKey());
if (!muxer_segment.AddGenericFrame(&muxer_frame)) {
printf("\n Could not add frame.\n");
return EXIT_FAILURE;
}
}
}
status = cluster->GetNext(block_entry, block_entry);
if (status) {
printf("\n Could not get next block of cluster.\n");
return EXIT_FAILURE;
}
}
cluster = parser_segment->GetNext(cluster);
}
// We have exhausted all video and audio frames in the input file.
// Flush any remaining metadata frames to the output file.
if (!metadata.Write(-1))
return EXIT_FAILURE;
if (!muxer_segment.Finalize()) {
printf("Finalization of segment failed.\n");
return EXIT_FAILURE;
}
reader.Close();
writer.Close();
if (cues_before_clusters) {
if (reader.Open(temp_file)) {
printf("\n Filename is invalid or error while opening.\n");
return EXIT_FAILURE;
}
if (!writer.Open(output)) {
printf("\n Filename is invalid or error while opening.\n");
return EXIT_FAILURE;
}
if (!muxer_segment.CopyAndMoveCuesBeforeClusters(&reader, &writer)) {
printf("\n Unable to copy and move cues before clusters.\n");
return EXIT_FAILURE;
}
reader.Close();
writer.Close();
remove(temp_file);
}
delete[] data;
return EXIT_SUCCESS;
}

387
sample_muxer_metadata.cc Normal file
View File

@@ -0,0 +1,387 @@
// Copyright (c) 2012 The WebM project authors. All Rights Reserved.
//
// Use of this source code is governed by a BSD-style license
// that can be found in the LICENSE file in the root of the source
// tree. An additional intellectual property rights grant can be found
// in the file PATENTS. All contributing project authors may
// be found in the AUTHORS file in the root of the source tree.
//
// This sample application demonstrates how to use the matroska parser
// library, which allows clients to handle a matroska format file.
#include "sample_muxer_metadata.h"
#include <string>
#include "vttreader.h"
SampleMuxerMetadata::SampleMuxerMetadata() : segment_(NULL) {}
bool SampleMuxerMetadata::Init(mkvmuxer::Segment* segment) {
if (segment == NULL || segment_ != NULL)
return false;
segment_ = segment;
return true;
}
bool SampleMuxerMetadata::Load(const char* file, Kind kind) {
if (kind == kChapters)
return LoadChapters(file);
mkvmuxer::uint64 track_num;
if (!AddTrack(kind, &track_num)) {
printf("Unable to add track for WebVTT file \"%s\"\n", file);
return false;
}
return Parse(file, kind, track_num);
}
bool SampleMuxerMetadata::AddChapters() {
typedef cue_list_t::const_iterator iter_t;
iter_t i = chapter_cues_.begin();
const iter_t j = chapter_cues_.end();
while (i != j) {
const cue_t& chapter = *i++;
if (!AddChapter(chapter))
return false;
}
return true;
}
bool SampleMuxerMetadata::Write(mkvmuxer::int64 time_ns) {
typedef cues_set_t::iterator iter_t;
iter_t i = cues_set_.begin();
const iter_t j = cues_set_.end();
while (i != j) {
const cues_set_t::value_type& v = *i;
if (time_ns >= 0 && v > time_ns)
return true; // nothing else to do just yet
if (!v.Write(segment_)) {
printf("\nCould not add metadata.\n");
return false; // error
}
cues_set_.erase(i++);
}
return true;
}
bool SampleMuxerMetadata::LoadChapters(const char* file) {
if (!chapter_cues_.empty()) {
printf("Support for more than one chapters file is not yet implemented\n");
return false;
}
cue_list_t cues;
if (!ParseChapters(file, &cues))
return false;
// TODO(matthewjheaney): support more than one chapters file
chapter_cues_.swap(cues);
return true;
}
bool SampleMuxerMetadata::ParseChapters(const char* file,
cue_list_t* cues_ptr) {
cue_list_t& cues = *cues_ptr;
cues.clear();
libwebvtt::VttReader r;
int e = r.Open(file);
if (e) {
printf("Unable to open WebVTT file: \"%s\"\n", file);
return false;
}
libwebvtt::Parser p(&r);
e = p.Init();
if (e < 0) { // error
printf("Error parsing WebVTT file: \"%s\"\n", file);
return false;
}
libwebvtt::Time t;
t.hours = -1;
for (;;) {
cue_t c;
e = p.Parse(&c);
if (e < 0) { // error
printf("Error parsing WebVTT file: \"%s\"\n", file);
return false;
}
if (e > 0) // EOF
return true;
if (c.start_time < t) {
printf("bad WebVTT cue timestamp (out-of-order)\n");
return false;
}
if (c.stop_time < c.start_time) {
printf("bad WebVTT cue timestamp (stop < start)\n");
return false;
}
t = c.start_time;
cues.push_back(c);
}
}
bool SampleMuxerMetadata::AddChapter(const cue_t& cue) {
// TODO(matthewjheaney): support language and country
mkvmuxer::Chapter* const chapter = segment_->AddChapter();
if (chapter == NULL) {
printf("Unable to add chapter\n");
return false;
}
if (cue.identifier.empty()) {
chapter->set_id(NULL);
} else {
const char* const id = cue.identifier.c_str();
if (!chapter->set_id(id)) {
printf("Unable to set chapter id\n");
return false;
}
}
typedef libwebvtt::presentation_t time_ms_t;
const time_ms_t start_time_ms = cue.start_time.presentation();
const time_ms_t stop_time_ms = cue.stop_time.presentation();
enum { kNsPerMs = 1000000 };
const mkvmuxer::uint64 start_time_ns = start_time_ms * kNsPerMs;
const mkvmuxer::uint64 stop_time_ns = stop_time_ms * kNsPerMs;
chapter->set_time(*segment_, start_time_ns, stop_time_ns);
typedef libwebvtt::Cue::payload_t::const_iterator iter_t;
iter_t i = cue.payload.begin();
const iter_t j = cue.payload.end();
std::string title;
for (;;) {
title += *i++;
if (i == j)
break;
enum { kLF = '\x0A' };
title += kLF;
}
if (!chapter->add_string(title.c_str(), NULL, NULL)) {
printf("Unable to set chapter title\n");
return false;
}
return true;
}
bool SampleMuxerMetadata::AddTrack(Kind kind, mkvmuxer::uint64* track_num) {
*track_num = 0;
// Track number value 0 means "let muxer choose track number"
mkvmuxer::Track* const track = segment_->AddTrack(0);
if (track == NULL) // error
return false;
// Return the track number value chosen by the muxer
*track_num = track->number();
int type;
const char* codec_id;
switch (kind) {
case kSubtitles:
type = 0x11;
codec_id = "D_WEBVTT/SUBTITLES";
break;
case kCaptions:
type = 0x11;
codec_id = "D_WEBVTT/CAPTIONS";
break;
case kDescriptions:
type = 0x21;
codec_id = "D_WEBVTT/DESCRIPTIONS";
break;
case kMetadata:
type = 0x21;
codec_id = "D_WEBVTT/METADATA";
break;
default:
return false;
}
track->set_type(type);
track->set_codec_id(codec_id);
// TODO(matthewjheaney): set name and language
return true;
}
bool SampleMuxerMetadata::Parse(const char* file, Kind /* kind */,
mkvmuxer::uint64 track_num) {
libwebvtt::VttReader r;
int e = r.Open(file);
if (e) {
printf("Unable to open WebVTT file: \"%s\"\n", file);
return false;
}
libwebvtt::Parser p(&r);
e = p.Init();
if (e < 0) { // error
printf("Error parsing WebVTT file: \"%s\"\n", file);
return false;
}
SortableCue cue;
cue.track_num = track_num;
libwebvtt::Time t;
t.hours = -1;
for (;;) {
cue_t& c = cue.cue;
e = p.Parse(&c);
if (e < 0) { // error
printf("Error parsing WebVTT file: \"%s\"\n", file);
return false;
}
if (e > 0) // EOF
return true;
if (c.start_time >= t) {
t = c.start_time;
} else {
printf("bad WebVTT cue timestamp (out-of-order)\n");
return false;
}
if (c.stop_time < c.start_time) {
printf("bad WebVTT cue timestamp (stop < start)\n");
return false;
}
cues_set_.insert(cue);
}
}
void SampleMuxerMetadata::MakeFrame(const cue_t& c, std::string* pf) {
pf->clear();
WriteCueIdentifier(c.identifier, pf);
WriteCueSettings(c.settings, pf);
WriteCuePayload(c.payload, pf);
}
void SampleMuxerMetadata::WriteCueIdentifier(const std::string& identifier,
std::string* pf) {
pf->append(identifier);
pf->push_back('\x0A'); // LF
}
void SampleMuxerMetadata::WriteCueSettings(const cue_t::settings_t& settings,
std::string* pf) {
if (settings.empty()) {
pf->push_back('\x0A'); // LF
return;
}
typedef cue_t::settings_t::const_iterator iter_t;
iter_t i = settings.begin();
const iter_t j = settings.end();
for (;;) {
const libwebvtt::Setting& setting = *i++;
pf->append(setting.name);
pf->push_back(':');
pf->append(setting.value);
if (i == j)
break;
pf->push_back(' '); // separate settings with whitespace
}
pf->push_back('\x0A'); // LF
}
void SampleMuxerMetadata::WriteCuePayload(const cue_t::payload_t& payload,
std::string* pf) {
typedef cue_t::payload_t::const_iterator iter_t;
iter_t i = payload.begin();
const iter_t j = payload.end();
while (i != j) {
const std::string& line = *i++;
pf->append(line);
pf->push_back('\x0A'); // LF
}
}
bool SampleMuxerMetadata::SortableCue::Write(mkvmuxer::Segment* segment) const {
// Cue start time expressed in milliseconds
const mkvmuxer::int64 start_ms = cue.start_time.presentation();
// Cue start time expressed in nanoseconds (MKV time)
const mkvmuxer::int64 start_ns = start_ms * 1000000;
// Cue stop time expressed in milliseconds
const mkvmuxer::int64 stop_ms = cue.stop_time.presentation();
// Cue stop time expressed in nanonseconds
const mkvmuxer::int64 stop_ns = stop_ms * 1000000;
// Metadata blocks always specify the block duration.
const mkvmuxer::int64 duration_ns = stop_ns - start_ns;
std::string frame;
MakeFrame(cue, &frame);
typedef const mkvmuxer::uint8* data_t;
const data_t buf = reinterpret_cast<data_t>(frame.data());
const mkvmuxer::uint64 len = frame.length();
mkvmuxer::Frame muxer_frame;
if (!muxer_frame.Init(buf, len))
return 0;
muxer_frame.set_track_number(track_num);
muxer_frame.set_timestamp(start_ns);
muxer_frame.set_duration(duration_ns);
muxer_frame.set_is_key(true); // All metadata frames are keyframes.
return segment->AddGenericFrame(&muxer_frame);
}

128
sample_muxer_metadata.h Normal file
View File

@@ -0,0 +1,128 @@
// Copyright (c) 2012 The WebM project authors. All Rights Reserved.
//
// Use of this source code is governed by a BSD-style license
// that can be found in the LICENSE file in the root of the source
// tree. An additional intellectual property rights grant can be found
// in the file PATENTS. All contributing project authors may
// be found in the AUTHORS file in the root of the source tree.
#ifndef SAMPLE_MUXER_METADATA_H_ // NOLINT
#define SAMPLE_MUXER_METADATA_H_
#include <list>
#include <set>
#include "mkvmuxer.hpp"
#include "webvttparser.h"
class SampleMuxerMetadata {
public:
enum Kind { kSubtitles, kCaptions, kDescriptions, kMetadata, kChapters };
SampleMuxerMetadata();
// Bind this metadata object to the muxer instance. Returns false
// if segment equals NULL, or Init has already been called.
bool Init(mkvmuxer::Segment* segment);
// Parse the WebVTT file |filename| having the indicated |kind|, and
// create a corresponding track (or chapters element) in the
// segment. Returns false on error.
bool Load(const char* filename, Kind kind);
bool AddChapters();
// Write any WebVTT cues whose time is less or equal to |time_ns| as
// a metadata block in its corresponding track. If |time_ns| is
// negative, write all remaining cues. Returns false on error.
bool Write(mkvmuxer::int64 time_ns);
private:
typedef libwebvtt::Cue cue_t;
// Used to sort cues as they are loaded.
struct SortableCue {
bool operator>(mkvmuxer::int64 time_ns) const {
// Cue start time expressed in milliseconds
const mkvmuxer::int64 start_ms = cue.start_time.presentation();
// Cue start time expressed in nanoseconds (MKV time)
const mkvmuxer::int64 start_ns = start_ms * 1000000;
return (start_ns > time_ns);
}
bool operator<(const SortableCue& rhs) const {
if (cue.start_time < rhs.cue.start_time)
return true;
if (cue.start_time > rhs.cue.start_time)
return false;
return (track_num < rhs.track_num);
}
// Write this cue as a metablock to |segment|. Returns false on
// error.
bool Write(mkvmuxer::Segment* segment) const;
mkvmuxer::uint64 track_num;
cue_t cue;
};
typedef std::multiset<SortableCue> cues_set_t;
typedef std::list<cue_t> cue_list_t;
// Parse the WebVTT cues in the named |file|, returning false on
// error. We handle chapters as a special case, because they are
// stored in their own, dedicated level-1 element.
bool LoadChapters(const char* file);
// Parse the WebVTT chapters in |file| to populate |cues|. Returns
// false on error.
static bool ParseChapters(const char* file, cue_list_t* cues);
// Adds WebVTT cue |chapter| to the chapters element of the output
// file's segment element. Returns false on error.
bool AddChapter(const cue_t& chapter);
// Add a metadata track to the segment having the indicated |kind|,
// returning the |track_num| that has been chosen for this track.
// Returns false on error.
bool AddTrack(Kind kind, mkvmuxer::uint64* track_num);
// Parse the WebVTT |file| having the indicated |kind| and
// |track_num|, adding each parsed cue to cues set. Returns false
// on error.
bool Parse(const char* file, Kind kind, mkvmuxer::uint64 track_num);
// Converts a WebVTT cue to a Matroska metadata block.
static void MakeFrame(const cue_t& cue, std::string* frame);
// Populate the cue identifier part of the metadata block.
static void WriteCueIdentifier(const std::string& identifier,
std::string* frame);
// Populate the cue settings part of the metadata block.
static void WriteCueSettings(const cue_t::settings_t& settings,
std::string* frame);
// Populate the payload part of the metadata block.
static void WriteCuePayload(const cue_t::payload_t& payload,
std::string* frame);
mkvmuxer::Segment* segment_;
// Set of cues ordered by time and then by track number.
cues_set_t cues_set_;
// The cues that will be used to populate the Chapters level-1
// element of the output file.
cue_list_t chapter_cues_;
// Disable copy ctor and copy assign.
SampleMuxerMetadata(const SampleMuxerMetadata&);
SampleMuxerMetadata& operator=(const SampleMuxerMetadata&);
};
#endif // SAMPLE_MUXER_METADATA_H_ // NOLINT

999
vttdemux.cc Normal file
View File

@@ -0,0 +1,999 @@
// Copyright (c) 2012 The WebM project authors. All Rights Reserved.
//
// Use of this source code is governed by a BSD-style license
// that can be found in the LICENSE file in the root of the source
// tree. An additional intellectual property rights grant can be found
// in the file PATENTS. All contributing project authors may
// be found in the AUTHORS file in the root of the source tree.
#include <cstdio>
#include <cstring>
#include <map>
#include <memory>
#include <string>
#include "./mkvparser.hpp"
#include "./mkvreader.hpp"
#include "./webvttparser.h"
#ifdef _MSC_VER
// Disable MSVC warnings that suggest making code non-portable.
#pragma warning(disable : 4996)
#endif
using std::string;
namespace vttdemux {
typedef long long mkvtime_t; // NOLINT
typedef long long mkvpos_t; // NOLINT
typedef std::auto_ptr<mkvparser::Segment> segment_ptr_t;
// WebVTT metadata tracks have a type (encoded in the CodecID for the track).
// We use |type| to synthesize a filename for the out-of-band WebVTT |file|.
struct MetadataInfo {
enum Type { kSubtitles, kCaptions, kDescriptions, kMetadata, kChapters } type;
FILE* file;
};
// We use a map, indexed by track number, to collect information about
// each track in the input file.
typedef std::map<long, MetadataInfo> metadata_map_t; // NOLINT
// The distinguished key value we use to store the chapters
// information in the metadata map.
enum { kChaptersKey = 0 };
// The data from the original WebVTT Cue is stored as a WebM block.
// The FrameParser is used to parse the lines of text out from the
// block, in order to reconstruct the original WebVTT Cue.
class FrameParser : public libwebvtt::LineReader {
public:
// Bind the FrameParser instance to a WebM block.
explicit FrameParser(const mkvparser::BlockGroup* block_group);
virtual ~FrameParser();
// The Webm block (group) to which this instance is bound. We
// treat the payload of the block as a stream of characters.
const mkvparser::BlockGroup* const block_group_;
protected:
// Read the next character from the character stream (the payload
// of the WebM block). We increment the stream pointer |pos_| as
// each character from the stream is consumed.
virtual int GetChar(char* c);
// End-of-line handling requires that we put a character back into
// the stream. Here we need only decrement the stream pointer |pos_|
// to unconsume the character.
virtual void UngetChar(char c);
// The current position in the character stream (the payload of the block).
mkvpos_t pos_;
// The position of the end of the character stream. When the current
// position |pos_| equals the end position |pos_end_|, the entire
// stream (block payload) has been consumed and end-of-stream is indicated.
mkvpos_t pos_end_;
private:
// Disable copy ctor and copy assign
FrameParser(const FrameParser&);
FrameParser& operator=(const FrameParser&);
};
// The data from the original WebVTT Cue is stored as an MKV Chapters
// Atom element (the cue payload is stored as a Display sub-element).
// The ChapterAtomParser is used to parse the lines of text out from
// the String sub-element of the Display element (though it would be
// admittedly odd if there were more than one line).
class ChapterAtomParser : public libwebvtt::LineReader {
public:
explicit ChapterAtomParser(const mkvparser::Chapters::Display* display);
virtual ~ChapterAtomParser();
const mkvparser::Chapters::Display* const display_;
protected:
// Read the next character from the character stream (the title
// member of the atom's display). We increment the stream pointer
// |str_| as each character from the stream is consumed.
virtual int GetChar(char* c);
// End-of-line handling requires that we put a character back into
// the stream. Here we need only decrement the stream pointer |str_|
// to unconsume the character.
virtual void UngetChar(char c);
// The current position in the character stream (the title of the
// atom's display).
const char* str_;
// The position of the end of the character stream. When the current
// position |str_| equals the end position |str_end_|, the entire
// stream (title of the display) has been consumed and end-of-stream
// is indicated.
const char* str_end_;
private:
ChapterAtomParser(const ChapterAtomParser&);
ChapterAtomParser& operator=(const ChapterAtomParser&);
};
// Parse the EBML header of the WebM input file, to determine whether we
// actually have a WebM file. Returns false if this is not a WebM file.
bool ParseHeader(mkvparser::IMkvReader* reader, mkvpos_t* pos);
// Parse the Segment of the input file and load all of its clusters.
// Returns false if there was an error parsing the file.
bool ParseSegment(mkvparser::IMkvReader* reader, mkvpos_t pos,
segment_ptr_t* segment);
// If |segment| has a Chapters element (in which case, there will be a
// corresponding entry in |metadata_map|), convert the MKV chapters to
// WebVTT chapter cues and write them to the output file. Returns
// false on error.
bool WriteChaptersFile(const metadata_map_t& metadata_map,
const mkvparser::Segment* segment);
// Convert an MKV Chapters Atom to a WebVTT cue and write it to the
// output |file|. Returns false on error.
bool WriteChaptersCue(FILE* file, const mkvparser::Chapters* chapters,
const mkvparser::Chapters::Atom* atom,
const mkvparser::Chapters::Display* display);
// Write the Cue Identifier line of the WebVTT cue, if it's present.
// Returns false on error.
bool WriteChaptersCueIdentifier(FILE* file,
const mkvparser::Chapters::Atom* atom);
// Use the timecodes from the chapters |atom| to write just the
// timings line of the WebVTT cue. Returns false on error.
bool WriteChaptersCueTimings(FILE* file, const mkvparser::Chapters* chapters,
const mkvparser::Chapters::Atom* atom);
// Parse the String sub-element of the |display| and write the payload
// of the WebVTT cue. Returns false on error.
bool WriteChaptersCuePayload(FILE* file,
const mkvparser::Chapters::Display* display);
// Iterate over the tracks of the input file (and any chapters
// element) and cache information about each metadata track.
void BuildMap(const mkvparser::Segment* segment, metadata_map_t* metadata_map);
// For each track listed in the cache, synthesize its output filename
// and open a file handle that designates the out-of-band file.
// Returns false if we were unable to open an output file for a track.
bool OpenFiles(metadata_map_t* metadata_map, const char* filename);
// Close the file handle for each track in the cache.
void CloseFiles(metadata_map_t* metadata_map);
// Iterate over the clusters of the input file, and write a WebVTT cue
// for each metadata block. Returns false if processing of a cluster
// failed.
bool WriteFiles(const metadata_map_t& m, mkvparser::Segment* s);
// Write the WebVTT header for each track in the cache. We do this
// immediately before writing the actual WebVTT cues. Returns false
// if the write failed.
bool InitializeFiles(const metadata_map_t& metadata_map);
// Iterate over the blocks of the |cluster|, writing a WebVTT cue to
// its associated output file for each block of metadata. Returns
// false if processing a block failed, or there was a parse error.
bool ProcessCluster(const metadata_map_t& metadata_map,
const mkvparser::Cluster* cluster);
// Look up this track number in the cache, and if found (meaning this
// is a metadata track), write a WebVTT cue to the associated output
// file. Returns false if writing the WebVTT cue failed.
bool ProcessBlockEntry(const metadata_map_t& metadata_map,
const mkvparser::BlockEntry* block_entry);
// Parse the lines of text from the |block_group| to reconstruct the
// original WebVTT cue, and write it to the associated output |file|.
// Returns false if there was an error writing to the output file.
bool WriteCue(FILE* file, const mkvparser::BlockGroup* block_group);
// Consume a line of text from the character stream, and if the line
// is not empty write the cue identifier to the associated output
// file. Returns false if there was an error writing to the file.
bool WriteCueIdentifier(FILE* f, FrameParser* parser);
// Consume a line of text from the character stream (which holds any
// cue settings) and write the cue timings line for this cue to the
// associated output file. Returns false if there was an error
// writing to the file.
bool WriteCueTimings(FILE* f, FrameParser* parser);
// Write the timestamp (representating either the start time or stop
// time of the cue) to the output file. Returns false if there was an
// error writing to the file.
bool WriteCueTime(FILE* f, mkvtime_t time_ns);
// Consume the remaining lines of text from the character stream
// (these lines are the actual payload of the WebVTT cue), and write
// them to the associated output file. Returns false if there was an
// error writing to the file.
bool WriteCuePayload(FILE* f, FrameParser* parser);
} // namespace vttdemux
int main(int argc, const char* argv[]) {
if (argc != 2) {
printf("usage: vttdemux <webmfile>\n");
return EXIT_SUCCESS;
}
const char* const filename = argv[1];
mkvparser::MkvReader reader;
int e = reader.Open(filename);
if (e) { // error
printf("unable to open file\n");
return EXIT_FAILURE;
}
vttdemux::mkvpos_t pos;
if (!vttdemux::ParseHeader(&reader, &pos))
return EXIT_FAILURE;
vttdemux::segment_ptr_t segment_ptr;
if (!vttdemux::ParseSegment(&reader, pos, &segment_ptr))
return EXIT_FAILURE;
vttdemux::metadata_map_t metadata_map;
BuildMap(segment_ptr.get(), &metadata_map);
if (metadata_map.empty()) {
printf("no WebVTT metadata found\n");
return EXIT_FAILURE;
}
if (!OpenFiles(&metadata_map, filename)) {
CloseFiles(&metadata_map); // nothing to flush, so not strictly necessary
return EXIT_FAILURE;
}
if (!WriteFiles(metadata_map, segment_ptr.get())) {
CloseFiles(&metadata_map); // might as well flush what we do have
return EXIT_FAILURE;
}
CloseFiles(&metadata_map);
return EXIT_SUCCESS;
}
namespace vttdemux {
FrameParser::FrameParser(const mkvparser::BlockGroup* block_group)
: block_group_(block_group) {
const mkvparser::Block* const block = block_group->GetBlock();
const mkvparser::Block::Frame& f = block->GetFrame(0);
// The beginning and end of the character stream corresponds to the
// position of this block's frame within the WebM input file.
pos_ = f.pos;
pos_end_ = f.pos + f.len;
}
FrameParser::~FrameParser() {}
int FrameParser::GetChar(char* c) {
if (pos_ >= pos_end_) // end-of-stream
return 1; // per the semantics of libwebvtt::Reader::GetChar
const mkvparser::Cluster* const cluster = block_group_->GetCluster();
const mkvparser::Segment* const segment = cluster->m_pSegment;
mkvparser::IMkvReader* const reader = segment->m_pReader;
unsigned char* const buf = reinterpret_cast<unsigned char*>(c);
const int result = reader->Read(pos_, 1, buf);
if (result < 0) // error
return -1;
++pos_; // consume this character in the stream
return 0;
}
void FrameParser::UngetChar(char /* c */) {
// All we need to do here is decrement the position in the stream.
// The next time GetChar is called the same character will be
// re-read from the input file.
--pos_;
}
ChapterAtomParser::ChapterAtomParser(
const mkvparser::Chapters::Display* display)
: display_(display) {
str_ = display->GetString();
const size_t len = strlen(str_);
str_end_ = str_ + len;
}
ChapterAtomParser::~ChapterAtomParser() {}
int ChapterAtomParser::GetChar(char* c) {
if (str_ >= str_end_) // end-of-stream
return 1; // per the semantics of libwebvtt::Reader::GetChar
*c = *str_++; // consume this character in the stream
return 0;
}
void ChapterAtomParser::UngetChar(char /* c */) {
// All we need to do here is decrement the position in the stream.
// The next time GetChar is called the same character will be
// re-read from the input file.
--str_;
}
} // namespace vttdemux
bool vttdemux::ParseHeader(mkvparser::IMkvReader* reader, mkvpos_t* pos) {
mkvparser::EBMLHeader h;
const mkvpos_t status = h.Parse(reader, *pos);
if (status) {
printf("error parsing EBML header\n");
return false;
}
if (h.m_docType == NULL || strcmp(h.m_docType, "webm") != 0) {
printf("bad doctype\n");
return false;
}
return true; // success
}
bool vttdemux::ParseSegment(mkvparser::IMkvReader* reader, mkvpos_t pos,
segment_ptr_t* segment_ptr) {
// We first create the segment object.
mkvparser::Segment* p;
const mkvpos_t create = mkvparser::Segment::CreateInstance(reader, pos, p);
if (create) {
printf("error parsing segment element\n");
return false;
}
segment_ptr->reset(p);
// Now parse all of the segment's sub-elements, in toto.
const long status = p->Load(); // NOLINT
if (status < 0) {
printf("error loading segment\n");
return false;
}
return true;
}
void vttdemux::BuildMap(const mkvparser::Segment* segment,
metadata_map_t* map_ptr) {
metadata_map_t& m = *map_ptr;
m.clear();
if (segment->GetChapters()) {
MetadataInfo info;
info.file = NULL;
info.type = MetadataInfo::kChapters;
m[kChaptersKey] = info;
}
const mkvparser::Tracks* const tt = segment->GetTracks();
if (tt == NULL)
return;
const long tc = tt->GetTracksCount(); // NOLINT
if (tc <= 0)
return;
// Iterate over the tracks in the intput file. We determine whether
// a track holds metadata by inspecting its CodecID.
for (long idx = 0; idx < tc; ++idx) { // NOLINT
const mkvparser::Track* const t = tt->GetTrackByIndex(idx);
if (t == NULL) // weird
continue;
const long tn = t->GetNumber(); // NOLINT
if (tn <= 0) // weird
continue;
const char* const codec_id = t->GetCodecId();
if (codec_id == NULL) // weird
continue;
MetadataInfo info;
info.file = NULL;
if (strcmp(codec_id, "D_WEBVTT/SUBTITLES") == 0) {
info.type = MetadataInfo::kSubtitles;
} else if (strcmp(codec_id, "D_WEBVTT/CAPTIONS") == 0) {
info.type = MetadataInfo::kCaptions;
} else if (strcmp(codec_id, "D_WEBVTT/DESCRIPTIONS") == 0) {
info.type = MetadataInfo::kDescriptions;
} else if (strcmp(codec_id, "D_WEBVTT/METADATA") == 0) {
info.type = MetadataInfo::kMetadata;
} else {
continue;
}
m[tn] = info; // create an entry in the cache for this track
}
}
bool vttdemux::OpenFiles(metadata_map_t* metadata_map, const char* filename) {
if (metadata_map == NULL || metadata_map->empty())
return false;
if (filename == NULL)
return false;
// Find the position of the filename extension. We synthesize the
// output filename from the directory path and basename of the input
// filename.
const char* const ext = strrchr(filename, '.');
if (ext == NULL) // TODO(matthewjheaney): liberalize?
return false;
// Remember whether a track of this type has already been seen (the
// map key) by keeping a count (the map item). We quality the
// output filename with the track number if there is more than one
// track having a given type.
std::map<MetadataInfo::Type, int> exists;
typedef metadata_map_t::iterator iter_t;
metadata_map_t& m = *metadata_map;
const iter_t ii = m.begin();
const iter_t j = m.end();
// Make a first pass over the cache to determine whether there is
// more than one track corresponding to a given metadata type.
iter_t i = ii;
while (i != j) {
const metadata_map_t::value_type& v = *i++;
const MetadataInfo& info = v.second;
const MetadataInfo::Type type = info.type;
++exists[type];
}
// Make a second pass over the cache, synthesizing the filename of
// each output file (from the input file basename, the input track
// metadata type, and its track number if necessary), and then
// opening a WebVTT output file having that filename.
i = ii;
while (i != j) {
metadata_map_t::value_type& v = *i++;
MetadataInfo& info = v.second;
const MetadataInfo::Type type = info.type;
// Start with the basename of the input file.
string name(filename, ext);
// Next append the metadata kind.
switch (type) {
case MetadataInfo::kSubtitles:
name += "_SUBTITLES";
break;
case MetadataInfo::kCaptions:
name += "_CAPTIONS";
break;
case MetadataInfo::kDescriptions:
name += "_DESCRIPTIONS";
break;
case MetadataInfo::kMetadata:
name += "_METADATA";
break;
case MetadataInfo::kChapters:
name += "_CHAPTERS";
break;
default:
return false;
}
// If there is more than one metadata track having a given type
// (the WebVTT-in-WebM spec doesn't preclude this), then qualify
// the output filename with the input track number.
if (exists[type] > 1) {
enum { kLen = 33 };
char str[kLen]; // max 126 tracks, so only 4 chars really needed
#ifndef _MSC_VER
snprintf(str, kLen, "%ld", v.first); // track number
#else
_snprintf_s(str, sizeof(str), kLen, "%ld", v.first); // track number
#endif
name += str;
}
// Finally append the output filename extension.
name += ".vtt";
// We have synthesized the full output filename, so attempt to
// open the WebVTT output file.
info.file = fopen(name.c_str(), "wb");
const bool success = (info.file != NULL);
if (!success) {
printf("unable to open output file %s\n", name.c_str());
return false;
}
}
return true;
}
void vttdemux::CloseFiles(metadata_map_t* metadata_map) {
if (metadata_map == NULL)
return;
metadata_map_t& m = *metadata_map;
typedef metadata_map_t::iterator iter_t;
iter_t i = m.begin();
const iter_t j = m.end();
// Gracefully close each output file, to ensure all output gets
// propertly flushed.
while (i != j) {
metadata_map_t::value_type& v = *i++;
MetadataInfo& info = v.second;
fclose(info.file);
info.file = NULL;
}
}
bool vttdemux::WriteFiles(const metadata_map_t& m, mkvparser::Segment* s) {
// First write the WebVTT header.
InitializeFiles(m);
if (!WriteChaptersFile(m, s))
return false;
// Now iterate over the clusters, writing the WebVTT cue as we parse
// each metadata block.
const mkvparser::Cluster* cluster = s->GetFirst();
while (cluster != NULL && !cluster->EOS()) {
if (!ProcessCluster(m, cluster))
return false;
cluster = s->GetNext(cluster);
}
return true;
}
bool vttdemux::InitializeFiles(const metadata_map_t& m) {
// Write the WebVTT header for each output file in the cache.
typedef metadata_map_t::const_iterator iter_t;
iter_t i = m.begin();
const iter_t j = m.end();
while (i != j) {
const metadata_map_t::value_type& v = *i++;
const MetadataInfo& info = v.second;
FILE* const f = info.file;
if (fputs("WEBVTT\n", f) < 0) {
printf("unable to initialize output file\n");
return false;
}
}
return true;
}
bool vttdemux::WriteChaptersFile(const metadata_map_t& m,
const mkvparser::Segment* s) {
const metadata_map_t::const_iterator info_iter = m.find(kChaptersKey);
if (info_iter == m.end()) // no chapters, so nothing to do
return true;
const mkvparser::Chapters* const chapters = s->GetChapters();
if (chapters == NULL) // weird
return true;
const MetadataInfo& info = info_iter->second;
FILE* const file = info.file;
const int edition_count = chapters->GetEditionCount();
if (edition_count <= 0) // weird
return true; // nothing to do
if (edition_count > 1) {
// TODO(matthewjheaney): figure what to do here
printf("more than one chapter edition detected\n");
return false;
}
const mkvparser::Chapters::Edition* const edition = chapters->GetEdition(0);
const int atom_count = edition->GetAtomCount();
for (int idx = 0; idx < atom_count; ++idx) {
const mkvparser::Chapters::Atom* const atom = edition->GetAtom(idx);
const int display_count = atom->GetDisplayCount();
if (display_count <= 0)
continue;
if (display_count > 1) {
// TODO(matthewjheaney): handle case of multiple languages
printf("more than 1 display in atom detected\n");
return false;
}
const mkvparser::Chapters::Display* const display = atom->GetDisplay(0);
if (const char* language = display->GetLanguage()) {
if (strcmp(language, "eng") != 0) {
// TODO(matthewjheaney): handle case of multiple languages.
// We must create a separate webvtt file for each language.
// This isn't a simple problem (which is why we defer it for
// now), because there's nothing in the header that tells us
// what languages we have as cues. We must parse the displays
// of each atom to determine that.
// One solution is to make two passes over the input data.
// First parse the displays, creating an in-memory cache of
// all the chapter cues, sorted according to their language.
// After we have read all of the chapter atoms from the input
// file, we can then write separate output files for each
// language.
printf("only English-language chapter cues are supported\n");
return false;
}
}
if (!WriteChaptersCue(file, chapters, atom, display))
return false;
}
return true;
}
bool vttdemux::WriteChaptersCue(FILE* f, const mkvparser::Chapters* chapters,
const mkvparser::Chapters::Atom* atom,
const mkvparser::Chapters::Display* display) {
// We start a new cue by writing a cue separator (an empty line)
// into the stream.
if (fputc('\n', f) < 0)
return false;
// A WebVTT Cue comprises 3 things: a cue identifier, followed by
// the cue timings, followed by the payload of the cue. We write
// each part of the cue in sequence.
if (!WriteChaptersCueIdentifier(f, atom))
return false;
if (!WriteChaptersCueTimings(f, chapters, atom))
return false;
if (!WriteChaptersCuePayload(f, display))
return false;
return true;
}
bool vttdemux::WriteChaptersCueIdentifier(
FILE* f, const mkvparser::Chapters::Atom* atom) {
const char* const identifier = atom->GetStringUID();
if (identifier == NULL)
return true; // nothing else to do
if (fprintf(f, "%s\n", identifier) < 0)
return false;
return true;
}
bool vttdemux::WriteChaptersCueTimings(FILE* f,
const mkvparser::Chapters* chapters,
const mkvparser::Chapters::Atom* atom) {
const mkvtime_t start_ns = atom->GetStartTime(chapters);
if (start_ns < 0)
return false;
const mkvtime_t stop_ns = atom->GetStopTime(chapters);
if (stop_ns < 0)
return false;
if (!WriteCueTime(f, start_ns))
return false;
if (fputs(" --> ", f) < 0)
return false;
if (!WriteCueTime(f, stop_ns))
return false;
if (fputc('\n', f) < 0)
return false;
return true;
}
bool vttdemux::WriteChaptersCuePayload(
FILE* f, const mkvparser::Chapters::Display* display) {
// Bind a Chapter parser object to the display, which allows us to
// extract each line of text from the title-part of the display.
ChapterAtomParser parser(display);
int count = 0; // count of lines of payload text written to output file
for (string line;;) {
const int e = parser.GetLine(&line);
if (e < 0) // error (only -- we allow EOS here)
return false;
if (line.empty()) // TODO(matthewjheaney): retain this check?
break;
if (fprintf(f, "%s\n", line.c_str()) < 0)
return false;
++count;
}
if (count <= 0) // WebVTT cue requires non-empty payload
return false;
return true;
}
bool vttdemux::ProcessCluster(const metadata_map_t& m,
const mkvparser::Cluster* c) {
// Visit the blocks in this cluster, writing a WebVTT cue for each
// metadata block.
const mkvparser::BlockEntry* block_entry;
long result = c->GetFirst(block_entry); // NOLINT
if (result < 0) {
printf("bad cluster (unable to get first block)\n");
return false;
}
while (block_entry != NULL && !block_entry->EOS()) {
if (!ProcessBlockEntry(m, block_entry))
return false;
result = c->GetNext(block_entry, block_entry);
if (result < 0) { // error
printf("bad cluster (unable to get next block)\n");
return false;
}
}
return true;
}
bool vttdemux::ProcessBlockEntry(const metadata_map_t& m,
const mkvparser::BlockEntry* block_entry) {
// If the track number for this block is in the cache, then we have
// a metadata block, so write the WebVTT cue to the output file.
const mkvparser::Block* const block = block_entry->GetBlock();
const long long tn = block->GetTrackNumber(); // NOLINT
typedef metadata_map_t::const_iterator iter_t;
const iter_t i = m.find(static_cast<metadata_map_t::key_type>(tn));
if (i == m.end()) // not a metadata track
return true; // nothing else to do
if (block_entry->GetKind() != mkvparser::BlockEntry::kBlockGroup)
return false; // weird
typedef mkvparser::BlockGroup BG;
const BG* const block_group = static_cast<const BG*>(block_entry);
const MetadataInfo& info = i->second;
FILE* const f = info.file;
return WriteCue(f, block_group);
}
bool vttdemux::WriteCue(FILE* f, const mkvparser::BlockGroup* block_group) {
// Bind a FrameParser object to the block, which allows us to
// extract each line of text from the payload of the block.
FrameParser parser(block_group);
// We start a new cue by writing a cue separator (an empty line)
// into the stream.
if (fputc('\n', f) < 0)
return false;
// A WebVTT Cue comprises 3 things: a cue identifier, followed by
// the cue timings, followed by the payload of the cue. We write
// each part of the cue in sequence.
if (!WriteCueIdentifier(f, &parser))
return false;
if (!WriteCueTimings(f, &parser))
return false;
if (!WriteCuePayload(f, &parser))
return false;
return true;
}
bool vttdemux::WriteCueIdentifier(FILE* f, FrameParser* parser) {
string line;
int e = parser->GetLine(&line);
if (e) // error or EOS
return false;
// If the cue identifier line is empty, this means that the original
// WebVTT cue did not have a cue identifier, so we don't bother
// writing an extra line terminator to the output file (though doing
// so would be harmless).
if (!line.empty()) {
if (fputs(line.c_str(), f) < 0)
return false;
if (fputc('\n', f) < 0)
return false;
}
return true;
}
bool vttdemux::WriteCueTimings(FILE* f, FrameParser* parser) {
const mkvparser::BlockGroup* const block_group = parser->block_group_;
const mkvparser::Cluster* const cluster = block_group->GetCluster();
const mkvparser::Block* const block = block_group->GetBlock();
// A WebVTT Cue "timings" line comprises two parts: the start and
// stop time for this cue, followed by the (optional) cue settings,
// such as orientation of the rendered text or its size. Only the
// settings part of the cue timings line is stored in the WebM
// block. We reconstruct the start and stop times of the WebVTT cue
// from the timestamp and duration of the WebM block.
const mkvtime_t start_ns = block->GetTime(cluster);
if (!WriteCueTime(f, start_ns))
return false;
if (fputs(" --> ", f) < 0)
return false;
const mkvtime_t duration_timecode = block_group->GetDurationTimeCode();
if (duration_timecode < 0)
return false;
const mkvparser::Segment* const segment = cluster->m_pSegment;
const mkvparser::SegmentInfo* const info = segment->GetInfo();
if (info == NULL)
return false;
const mkvtime_t timecode_scale = info->GetTimeCodeScale();
if (timecode_scale <= 0)
return false;
const mkvtime_t duration_ns = duration_timecode * timecode_scale;
const mkvtime_t stop_ns = start_ns + duration_ns;
if (!WriteCueTime(f, stop_ns))
return false;
string line;
int e = parser->GetLine(&line);
if (e) // error or EOS
return false;
if (!line.empty()) {
if (fputc(' ', f) < 0)
return false;
if (fputs(line.c_str(), f) < 0)
return false;
}
if (fputc('\n', f) < 0)
return false;
return true;
}
bool vttdemux::WriteCueTime(FILE* f, mkvtime_t time_ns) {
mkvtime_t ms = time_ns / 1000000; // WebVTT time has millisecond resolution
mkvtime_t sec = ms / 1000;
ms -= sec * 1000;
mkvtime_t min = sec / 60;
sec -= 60 * min;
mkvtime_t hr = min / 60;
min -= 60 * hr;
if (hr > 0) {
if (fprintf(f, "%02lld:", hr) < 0)
return false;
}
if (fprintf(f, "%02lld:%02lld.%03lld", min, sec, ms) < 0)
return false;
return true;
}
bool vttdemux::WriteCuePayload(FILE* f, FrameParser* parser) {
int count = 0; // count of lines of payload text written to output file
for (string line;;) {
const int e = parser->GetLine(&line);
if (e < 0) // error (only -- we allow EOS here)
return false;
if (line.empty()) // TODO(matthewjheaney): retain this check?
break;
if (fprintf(f, "%s\n", line.c_str()) < 0)
return false;
++count;
}
if (count <= 0) // WebVTT cue requires non-empty payload
return false;
return true;
}

59
vttreader.cc Normal file
View File

@@ -0,0 +1,59 @@
// Copyright (c) 2012 The WebM project authors. All Rights Reserved.
//
// Use of this source code is governed by a BSD-style license
// that can be found in the LICENSE file in the root of the source
// tree. An additional intellectual property rights grant can be found
// in the file PATENTS. All contributing project authors may
// be found in the AUTHORS file in the root of the source tree.
#include "./vttreader.h" // NOLINT
#ifdef _MSC_VER
// Disable MSVC warnings that suggest making code non-portable.
#pragma warning(disable : 4996)
#endif
namespace libwebvtt {
VttReader::VttReader() : file_(NULL) {}
VttReader::~VttReader() { Close(); }
int VttReader::Open(const char* filename) {
if (filename == NULL || file_ != NULL)
return -1;
file_ = fopen(filename, "rb");
if (file_ == NULL)
return -1;
return 0; // success
}
void VttReader::Close() {
if (file_) {
fclose(file_);
file_ = NULL;
}
}
int VttReader::GetChar(char* c) {
if (c == NULL || file_ == NULL)
return -1;
const int result = fgetc(file_);
if (result != EOF) {
*c = static_cast<char>(result);
return 0; // success
}
if (ferror(file_))
return -1; // error
if (feof(file_))
return 1; // EOF
return -1; // weird
}
} // namespace libwebvtt

44
vttreader.h Normal file
View File

@@ -0,0 +1,44 @@
// Copyright (c) 2012 The WebM project authors. All Rights Reserved.
//
// Use of this source code is governed by a BSD-style license
// that can be found in the LICENSE file in the root of the source
// tree. An additional intellectual property rights grant can be found
// in the file PATENTS. All contributing project authors may
// be found in the AUTHORS file in the root of the source tree.
#ifndef VTTREADER_H_ // NOLINT
#define VTTREADER_H_
#include <cstdio>
#include "./webvttparser.h"
namespace libwebvtt {
class VttReader : public libwebvtt::Reader {
public:
VttReader();
virtual ~VttReader();
// Open the file identified by |filename| in read-only mode, as a
// binary stream of bytes. Returns 0 on success, negative if error.
int Open(const char* filename);
// Closes the file stream. Note that the stream is automatically
// closed when the VttReader object is destroyed.
void Close();
// Reads the next character in the file stream, as per the semantics
// of Reader::GetChar. Returns negative if error, 0 on success, and
// positive if end-of-stream has been reached.
virtual int GetChar(char* c);
private:
FILE* file_;
VttReader(const VttReader&);
VttReader& operator=(const VttReader&);
};
} // namespace libwebvtt
#endif // VTTREADER_H_ // NOLINT

517
webm2pes.cc Normal file
View File

@@ -0,0 +1,517 @@
// Copyright (c) 2015 The WebM project authors. All Rights Reserved.
//
// Use of this source code is governed by a BSD-style license
// that can be found in the LICENSE file in the root of the source
// tree. An additional intellectual property rights grant can be found
// in the file PATENTS. All contributing project authors may
// be found in the AUTHORS file in the root of the source tree.
#include "webm2pes.h"
#include <vector>
namespace {
void Usage(const char* argv[]) {
printf("Usage: %s <WebM file> <output file>", argv[0]);
}
bool WriteUint8(std::uint8_t val, std::FILE* fileptr) {
if (fileptr == nullptr)
return false;
return (std::fputc(val, fileptr) == val);
}
struct Range {
Range(std::size_t off, std::size_t len) : offset(off), length(len) {}
Range() = delete;
Range(const Range&) = default;
Range(Range&&) = default;
~Range() = default;
const std::size_t offset;
const std::size_t length;
};
typedef std::vector<Range> FrameRanges;
// Returns true and stores frame offsets and lengths in |frame_ranges| when
// |frame| has a valid VP9 super frame index.
bool ParseVP9SuperFrameIndex(const std::uint8_t* frame,
std::size_t length,
FrameRanges* frame_ranges) {
if (frame == nullptr || length == 0 || frame_ranges == nullptr)
return false;
bool parse_ok = false;
const std::uint8_t marker = frame[length - 1];
const std::uint32_t kHasSuperFrameIndexMask = 0xe0;
const std::uint32_t kSuperFrameMarker = 0xc0;
if ((marker & kHasSuperFrameIndexMask) == kSuperFrameMarker) {
const std::uint32_t kFrameCountMask = 0x7;
const int num_frames = (marker & kFrameCountMask) + 1;
const int length_field_size = ((marker >> 3) & 0x3) + 1;
const std::size_t index_length = 2 + length_field_size * num_frames;
// Consume the super frame index.
std::size_t frame_offset = index_length;
if (length >= index_length && frame[length - index_length] == marker) {
// Found a valid superframe index.
const std::uint8_t* byte = frame + length - index_length + 1;
for (int i = 0; i < num_frames; ++i) {
std::uint32_t child_frame_length = 0;
for (int j = 0; j < length_field_size; ++j) {
child_frame_length |= (*byte++) << (j * 8);
}
frame_ranges->push_back(Range(frame_offset, child_frame_length));
frame_offset += child_frame_length;
}
if (frame_ranges->size() != num_frames) {
std::fprintf(stderr, "Webm2Pes: superframe index parse failed.\n");
return false;
}
parse_ok = true;
} else {
std::fprintf(stderr, "Webm2Pes: Invalid superframe index.\n");
}
}
return parse_ok;
}
std::int64_t NanosecondsTo90KhzTicks(std::int64_t nanoseconds) {
const double kNanosecondsPerSecond = 1000000000.0;
const double pts_seconds = nanoseconds / kNanosecondsPerSecond;
return pts_seconds * 90000;
}
bool GetPacketPayloadRanges(const libwebm::PesHeader& header,
const FrameRanges& frame_ranges,
FrameRanges* packet_payload_ranges) {
// TODO(tomfinegan): The length field in PES is actually number of bytes that
// follow the length field, and does not include the 6 byte fixed portion of
// the header (4 byte start code + 2 bytes for the length). We can fit in 6
// more bytes if we really want to, and avoid packetization when size is very
// close to UINT16_MAX.
if (packet_payload_ranges == nullptr) {
std::fprintf(stderr, "Webm2Pes: nullptr getting payload ranges.\n");
return false;
}
const std::size_t kMaxPacketPayloadSize = UINT16_MAX - header.size();
for (const Range& frame_range : frame_ranges) {
if (frame_range.length + header.size() > kMaxPacketPayloadSize) {
// make packet ranges until range.length is exhausted
const std::size_t kBytesToPacketize = frame_range.length;
std::size_t packet_payload_length = 0;
for (std::size_t pos = 0; pos < kBytesToPacketize;
pos += packet_payload_length) {
packet_payload_length =
(frame_range.length - pos < kMaxPacketPayloadSize)
? frame_range.length - pos
: kMaxPacketPayloadSize;
packet_payload_ranges->push_back(
Range(frame_range.offset + pos, packet_payload_length));
}
} else {
// copy range into |packet_ranges|
packet_payload_ranges->push_back(
Range(frame_range.offset, frame_range.length));
}
}
return true;
}
} // namespace
namespace libwebm {
//
// PesOptionalHeader methods.
//
void PesOptionalHeader::SetPtsBits(std::int64_t pts_90khz) {
std::uint64_t* pts_bits = &pts.bits;
*pts_bits = 0;
// PTS is broken up and stored in 40 bits as shown:
//
// PES PTS Only flag
// / Marker Marker Marker
// | / / /
// | | | |
// 7654 321 0 765432107654321 0 765432107654321 0
// 0010 PTS 32-30 1 PTS 29-15 1 PTS 14-0 1
const std::uint32_t pts1 = (pts_90khz >> 30) & 0x7;
const std::uint32_t pts2 = (pts_90khz >> 15) & 0x7FFF;
const std::uint32_t pts3 = pts_90khz & 0x7FFF;
std::uint8_t buffer[5] = {0};
// PTS only flag.
buffer[0] |= 1 << 5;
// Top 3 bits of PTS and 1 bit marker.
buffer[0] |= pts1 << 1;
// Marker.
buffer[0] |= 1;
// Next 15 bits of pts and 1 bit marker.
// Top 8 bits of second PTS chunk.
buffer[1] |= (pts2 >> 7) & 0xff;
// bottom 7 bits of second PTS chunk.
buffer[2] |= (pts2 << 1);
// Marker.
buffer[2] |= 1;
// Last 15 bits of pts and 1 bit marker.
// Top 8 bits of second PTS chunk.
buffer[3] |= (pts3 >> 7) & 0xff;
// bottom 7 bits of second PTS chunk.
buffer[4] |= (pts3 << 1);
// Marker.
buffer[4] |= 1;
// Write bits into PesHeaderField.
std::memcpy(reinterpret_cast<std::uint8_t*>(pts_bits), buffer, 5);
}
// Writes fields to |file| and returns true. Returns false when write or
// field value validation fails.
bool PesOptionalHeader::Write(std::FILE* file, bool write_pts) const {
if (file == nullptr) {
std::fprintf(stderr, "Webm2Pes: nullptr in opt header writer.\n");
return false;
}
std::uint8_t header[9] = {0};
std::uint8_t* byte = header;
if (marker.Check() != true || scrambling.Check() != true ||
priority.Check() != true || data_alignment.Check() != true ||
copyright.Check() != true || original.Check() != true ||
has_pts.Check() != true || has_dts.Check() != true ||
pts.Check() != true || stuffing_byte.Check() != true) {
std::fprintf(stderr, "Webm2Pes: Invalid PES Optional Header field.\n");
return false;
}
// TODO(tomfinegan): As noted in above, the PesHeaderFields should be an
// array (or some data structure) that can be iterated over.
// First byte of header, fields: marker, scrambling, priority, alignment,
// copyright, original.
*byte = 0;
*byte |= marker.bits << marker.shift;
*byte |= scrambling.bits << scrambling.shift;
*byte |= priority.bits << priority.shift;
*byte |= data_alignment.bits << data_alignment.shift;
*byte |= copyright.bits << copyright.shift;
*byte |= original.bits << original.shift;
// Second byte of header, fields: has_pts, has_dts, unused fields.
*++byte = 0;
if (write_pts == true) {
*byte |= has_pts.bits << has_pts.shift;
*byte |= has_dts.bits << has_dts.shift;
}
// Third byte of header, fields: remaining size of header.
*++byte = remaining_size.bits; // Field is 8 bits wide.
int num_stuffing_bytes =
(pts.num_bits + 7) / 8 + 1 /* always 1 stuffing byte */;
if (write_pts == true) {
// Set the PTS value and adjust stuffing byte count accordingly.
*++byte = (pts.bits >> 32) & 0xff;
*++byte = (pts.bits >> 24) & 0xff;
*++byte = (pts.bits >> 16) & 0xff;
*++byte = (pts.bits >> 8) & 0xff;
*++byte = pts.bits & 0xff;
num_stuffing_bytes = 1;
}
// Add the stuffing byte(s).
for (int i = 0; i < num_stuffing_bytes; ++i)
*++byte = stuffing_byte.bits;
if (std::fwrite(reinterpret_cast<void*>(header), 1, size_in_bytes(), file) !=
size_in_bytes()) {
std::fprintf(stderr, "Webm2Pes: unable to write PES opt header to file.\n");
return false;
}
return true;
}
//
// BCMVHeader methods.
//
bool BCMVHeader::Write(std::FILE* fileptr) const {
if (fileptr == nullptr) {
std::fprintf(stderr, "Webm2Pes: nullptr for file in BCMV Write.\n");
return false;
}
if (std::fwrite(bcmv, 1, 4, fileptr) != 4) {
std::fprintf(stderr, "Webm2Pes: BCMV write failed.\n");
}
const std::size_t kRemainingBytes = 6;
const uint8_t buffer[kRemainingBytes] = {(length >> 24) & 0xff,
(length >> 16) & 0xff,
(length >> 8) & 0xff,
length & 0xff,
0,
0 /* 2 bytes 0 padding */};
for (std::int8_t i = 0; i < kRemainingBytes; ++i) {
if (WriteUint8(buffer[i], fileptr) != true) {
std::fprintf(stderr, "Webm2Pes: BCMV remainder write failed.\n");
return false;
}
}
return true;
}
//
// PesHeader methods.
//
// Writes out the header to |file|. Calls PesOptionalHeader::Write() to write
// |optional_header| contents. Returns true when successful, false otherwise.
bool PesHeader::Write(std::FILE* file, bool write_pts) const {
if (file == nullptr) {
std::fprintf(stderr, "Webm2Pes: nullptr in header writer.\n");
return false;
}
// Write |start_code|.
if (std::fwrite(reinterpret_cast<const void*>(start_code), 1, 4, file) != 4) {
std::fprintf(stderr, "Webm2Pes: cannot write packet start code.\n");
return false;
}
// Write |packet_length| as big endian.
std::uint8_t byte = (packet_length >> 8) & 0xff;
if (WriteUint8(byte, file) != true) {
std::fprintf(stderr, "Webm2Pes: cannot write packet length (byte 0).\n");
return false;
}
byte = packet_length & 0xff;
if (WriteUint8(byte, file) != true) {
std::fprintf(stderr, "Webm2Pes: cannot write packet length (byte 1).\n");
return false;
}
// Write the (not really) optional header.
if (optional_header.Write(file, write_pts) != true) {
std::fprintf(stderr, "Webm2Pes: PES optional header write failed.");
return false;
}
return true;
}
//
// Webm2Pes methods.
//
bool Webm2Pes::Convert() {
if (input_file_name_.empty() || output_file_name_.empty()) {
std::fprintf(stderr, "Webm2Pes: input and/or output file name(s) empty.\n");
return false;
}
if (webm_reader_.Open(input_file_name_.c_str()) != 0) {
std::fprintf(stderr, "Webm2Pes: Cannot open %s as input.\n",
input_file_name_.c_str());
return false;
}
output_file_ = FilePtr(fopen(output_file_name_.c_str(), "wb"), FILEDeleter());
if (output_file_ == nullptr) {
std::fprintf(stderr, "Webm2Pes: Cannot open %s for output.\n",
output_file_name_.c_str());
return false;
}
using mkvparser::Segment;
Segment* webm_parser = nullptr;
if (Segment::CreateInstance(&webm_reader_, 0 /* pos */,
webm_parser /* Segment*& */) != 0) {
std::fprintf(stderr, "Webm2Pes: Cannot create WebM parser.\n");
return false;
}
webm_parser_.reset(webm_parser);
if (webm_parser_->Load() != 0) {
std::fprintf(stderr, "Webm2Pes: Cannot parse %s.\n",
input_file_name_.c_str());
return false;
}
// Store timecode scale.
timecode_scale_ = webm_parser_->GetInfo()->GetTimeCodeScale();
// Make sure there's a video track.
const mkvparser::Tracks* tracks = webm_parser_->GetTracks();
if (tracks == nullptr) {
std::fprintf(stderr, "Webm2Pes: %s has no tracks.\n",
input_file_name_.c_str());
return false;
}
for (int track_index = 0; track_index < tracks->GetTracksCount();
++track_index) {
const mkvparser::Track* track = tracks->GetTrackByIndex(track_index);
if (track && track->GetType() == mkvparser::Track::kVideo) {
if (std::string(track->GetCodecId()) == std::string("V_VP8"))
codec_ = VP8;
else if (std::string(track->GetCodecId()) == std::string("V_VP9"))
codec_ = VP9;
else {
fprintf(stderr, "Webm2Pes: Codec must be VP8 or VP9.\n");
return false;
}
video_track_num_ = track_index + 1;
break;
}
}
if (video_track_num_ < 1) {
std::fprintf(stderr, "Webm2Pes: No video track found in %s.\n",
input_file_name_.c_str());
return false;
}
// Walk clusters in segment.
const mkvparser::Cluster* cluster = webm_parser_->GetFirst();
while (cluster != nullptr && cluster->EOS() == false) {
const mkvparser::BlockEntry* block_entry = nullptr;
std::int64_t block_status = cluster->GetFirst(block_entry);
if (block_status < 0) {
std::fprintf(stderr, "Webm2Pes: Cannot parse first block in %s.\n",
input_file_name_.c_str());
return false;
}
// Walk blocks in cluster.
while (block_entry != nullptr && block_entry->EOS() == false) {
const mkvparser::Block* block = block_entry->GetBlock();
if (block->GetTrackNumber() == video_track_num_) {
const int frame_count = block->GetFrameCount();
// Walk frames in block.
for (int frame_num = 0; frame_num < frame_count; ++frame_num) {
const mkvparser::Block::Frame& frame = block->GetFrame(frame_num);
// Write frame out as PES packet(s).
const bool pes_status =
WritePesPacket(frame, block->GetTime(cluster));
if (pes_status != true) {
std::fprintf(stderr, "Webm2Pes: WritePesPacket failed.\n");
return false;
}
}
}
block_status = cluster->GetNext(block_entry, block_entry);
if (block_status < 0) {
std::fprintf(stderr, "Webm2Pes: Cannot parse block in %s.\n",
input_file_name_.c_str());
return false;
}
}
cluster = webm_parser_->GetNext(cluster);
}
return true;
}
bool Webm2Pes::WritePesPacket(const mkvparser::Block::Frame& vpx_frame,
double nanosecond_pts) {
// Read the input frame.
std::unique_ptr<uint8_t[]> frame_data(new (std::nothrow)
uint8_t[vpx_frame.len]);
if (frame_data.get() == nullptr) {
std::fprintf(stderr, "Webm2Pes: Out of memory.\n");
return false;
}
if (vpx_frame.Read(&webm_reader_, frame_data.get()) != 0) {
std::fprintf(stderr, "Webm2Pes: Error reading VPx frame!\n");
return false;
}
FrameRanges frame_ranges;
if (codec_ == VP9) {
bool has_superframe_index =
ParseVP9SuperFrameIndex(frame_data.get(), vpx_frame.len, &frame_ranges);
if (has_superframe_index == false) {
frame_ranges.push_back(Range(0, vpx_frame.len));
}
} else {
frame_ranges.push_back(Range(0, vpx_frame.len));
}
PesHeader header;
FrameRanges packet_payload_ranges;
if (GetPacketPayloadRanges(header, frame_ranges, &packet_payload_ranges) !=
true) {
std::fprintf(stderr, "Webm2Pes: Error preparing packet payload ranges!\n");
return false;
}
///
/// TODO: DEBUG/REMOVE
///
printf("-FRAME TOTAL LENGTH %ld--\n", vpx_frame.len);
for (const Range& frame_range : frame_ranges) {
printf("--frame range: off:%lu len:%lu\n", frame_range.offset,
frame_range.length);
}
for (const Range& payload_range : packet_payload_ranges) {
printf("---payload range: off:%lu len:%lu\n", payload_range.offset,
payload_range.length);
}
const std::int64_t khz90_pts = NanosecondsTo90KhzTicks(nanosecond_pts);
header.optional_header.SetPtsBits(khz90_pts);
bool write_pts = true;
for (const Range& packet_payload_range : packet_payload_ranges) {
header.packet_length =
header.optional_header.size_in_bytes() + packet_payload_range.length;
if (header.Write(output_file_.get(), write_pts) != true) {
std::fprintf(stderr, "Webm2Pes: packet header write failed.\n");
return false;
}
write_pts = false;
BCMVHeader bcmv_header(packet_payload_range.length);
if (bcmv_header.Write(output_file_.get()) != true) {
std::fprintf(stderr, "Webm2Pes: BCMV write failed.\n");
return false;
}
// Write the payload.
if (std::fwrite(frame_data.get() + packet_payload_range.offset, 1,
packet_payload_range.length,
output_file_.get()) != packet_payload_range.length) {
std::fprintf(stderr, "Webm2Pes: packet payload write failed.\n");
return false;
}
}
return true;
}
} // namespace libwebm
int main(int argc, const char* argv[]) {
if (argc < 3) {
Usage(argv);
return EXIT_FAILURE;
}
const std::string input_path = argv[1];
const std::string output_path = argv[2];
libwebm::Webm2Pes converter(input_path, output_path);
return converter.Convert() == true ? EXIT_SUCCESS : EXIT_FAILURE;
}

209
webm2pes.h Normal file
View File

@@ -0,0 +1,209 @@
// Copyright (c) 2015 The WebM project authors. All Rights Reserved.
//
// Use of this source code is governed by a BSD-style license
// that can be found in the LICENSE file in the root of the source
// tree. An additional intellectual property rights grant can be found
// in the file PATENTS. All contributing project authors may
// be found in the AUTHORS file in the root of the source tree.
#ifndef LIBWEBM_WEBM2PES_H_
#define LIBWEBM_WEBM2PES_H_
#include <cstdio>
#include <cstdint>
#include <memory>
#include <string>
#include <vector>
#include "mkvparser.hpp"
#include "mkvreader.hpp"
namespace libwebm {
// Stores a value and its size in bits for writing into a PES Optional Header.
// Maximum size is 64 bits. Users may call the Check() method to perform minimal
// validation (size > 0 and <= 64).
struct PesHeaderField {
PesHeaderField(std::uint64_t value,
std::uint32_t size_in_bits,
std::uint8_t byte_index,
std::uint8_t bits_to_shift)
: bits(value),
num_bits(size_in_bits),
index(byte_index),
shift(bits_to_shift) {}
PesHeaderField() = delete;
PesHeaderField(const PesHeaderField&) = default;
PesHeaderField(PesHeaderField&&) = default;
~PesHeaderField() = default;
bool Check() const {
return num_bits > 0 && num_bits <= 64 && shift >= 0 && shift < 64;
}
// Value to be stored in the field.
std::uint64_t bits;
// Number of bits in the value.
const std::uint32_t num_bits;
// Index into the header for the byte in which |bits| will be written.
const std::uint8_t index;
// Number of bits to shift value before or'ing.
const std::uint8_t shift;
};
// Storage for PES Optional Header values. Fields written in order using sizes
// specified.
struct PesOptionalHeader {
// TODO(tomfinegan): The fields could be in an array, which would allow the
// code writing the optional header to iterate over the fields instead of
// having code for dealing with each one.
// 2 bits (marker): 2 ('10')
const PesHeaderField marker = PesHeaderField(2, 2, 0, 6);
// 2 bits (no scrambling): 0x0 ('00')
const PesHeaderField scrambling = PesHeaderField(0, 2, 0, 4);
// 1 bit (priority): 0x0 ('0')
const PesHeaderField priority = PesHeaderField(0, 1, 0, 3);
// TODO(tomfinegan): The BCMV header could be considered a sync word, and this
// field should be 1 when a sync word follows the packet. Clarify.
// 1 bit (data alignment): 0x0 ('0')
const PesHeaderField data_alignment = PesHeaderField(0, 1, 0, 2);
// 1 bit (copyright): 0x0 ('0')
const PesHeaderField copyright = PesHeaderField(0, 1, 0, 1);
// 1 bit (original/copy): 0x0 ('0')
const PesHeaderField original = PesHeaderField(0, 1, 0, 0);
// 1 bit (has_pts): 0x1 ('1')
const PesHeaderField has_pts = PesHeaderField(1, 1, 1, 7);
// 1 bit (has_dts): 0x0 ('0')
const PesHeaderField has_dts = PesHeaderField(0, 1, 1, 6);
// 6 bits (unused fields): 0x0 ('000000')
const PesHeaderField unused = PesHeaderField(0, 6, 1, 0);
// 8 bits (size of remaining data in the Header).
const PesHeaderField remaining_size = PesHeaderField(6, 8, 2, 0);
// PTS: 5 bytes
// 4 bits (flag: PTS present, but no DTS): 0x2 ('0010')
// 36 bits (90khz PTS):
// top 3 bits
// marker ('1')
// middle 15 bits
// marker ('1')
// bottom 15 bits
// marker ('1')
PesHeaderField pts = PesHeaderField(0, 40, 3, 0);
PesHeaderField stuffing_byte = PesHeaderField(0xFF, 8, 8, 0);
// PTS omitted in fragments. Size remains unchanged: More stuffing bytes.
bool fragment = false;
static std::size_t size_in_bytes() { return 9; }
// Writes |pts_90khz| to |pts| per format described at its declaration above.
void SetPtsBits(std::int64_t pts_90khz);
// Writes fields to |file| and returns true. Returns false when write or
// field value validation fails.
bool Write(std::FILE* file, bool write_pts) const;
};
// Describes custom 10 byte header that immediately follows the PES Optional
// Header in each PES packet output by Webm2Pes:
// 4 byte 'B' 'C' 'M' 'V'
// 4 byte big-endian length of frame
// 2 bytes 0 padding
struct BCMVHeader {
explicit BCMVHeader(std::uint32_t frame_length) : length(frame_length) {}
BCMVHeader() = delete;
BCMVHeader(const BCMVHeader&) = delete;
BCMVHeader(BCMVHeader&&) = delete;
~BCMVHeader() = default;
const std::uint8_t bcmv[4] = {'B', 'C', 'M', 'V'};
const std::uint32_t length;
static std::size_t size() { return 10; }
// Write the BCMV Header into the FILE stream.
bool Write(std::FILE* fileptr) const;
};
struct PesHeader {
const std::uint8_t start_code[4] = {
0x00,
0x00,
0x01, // 0x000001 is the PES packet start code prefix.
0xE0}; // 0xE0 is the minimum video stream ID.
std::uint16_t packet_length = 0; // Number of bytes _after_ this field.
PesOptionalHeader optional_header;
std::size_t size() const {
return optional_header.size_in_bytes() + BCMVHeader::size() +
6 /* start_code + packet_length */ + packet_length;
}
// Writes out the header to |file|. Calls PesOptionalHeader::Write() to write
// |optional_header| contents. Returns true when successful, false otherwise.
bool Write(std::FILE* file, bool write_pts) const;
};
// Converts the VP9 track of a WebM file to a Packetized Elementary Stream
// suitable for use in a MPEG2TS.
// https://en.wikipedia.org/wiki/Packetized_elementary_stream
// https://en.wikipedia.org/wiki/MPEG_transport_stream
class Webm2Pes {
public:
enum VideoCodec { VP8, VP9 };
Webm2Pes(const std::string& input_file, const std::string& output_file)
: input_file_name_(input_file), output_file_name_(output_file) {}
Webm2Pes() = delete;
Webm2Pes(const Webm2Pes&) = delete;
Webm2Pes(Webm2Pes&&) = delete;
~Webm2Pes() = default;
// Converts the VPx video stream to a PES and returns true. Returns false
// to report failure.
bool Convert();
private:
// fclose functor for wrapping FILE in std::unique_ptr.
struct FILEDeleter {
int operator()(FILE* f) {
if (f != nullptr)
return fclose(f);
return 0;
}
};
typedef std::unique_ptr<FILE, FILEDeleter> FilePtr;
bool WritePesPacket(const mkvparser::Block::Frame& vpx_frame,
double nanosecond_pts);
const std::string input_file_name_;
const std::string output_file_name_;
std::unique_ptr<mkvparser::Segment> webm_parser_;
mkvparser::MkvReader webm_reader_;
FilePtr output_file_;
// Video track num in the WebM file.
int video_track_num_ = 0;
// Video codec reported by CodecName from Video TrackEntry.
VideoCodec codec_;
// Input timecode scale.
std::int64_t timecode_scale_ = 1000000;
};
} // namespace libwebm
#endif // LIBWEBM_WEBM2PES_H_

155
webmids.hpp Normal file
View File

@@ -0,0 +1,155 @@
// Copyright (c) 2012 The WebM project authors. All Rights Reserved.
//
// Use of this source code is governed by a BSD-style license
// that can be found in the LICENSE file in the root of the source
// tree. An additional intellectual property rights grant can be found
// in the file PATENTS. All contributing project authors may
// be found in the AUTHORS file in the root of the source tree.
#ifndef WEBMIDS_HPP
#define WEBMIDS_HPP
namespace mkvmuxer {
enum MkvId {
kMkvEBML = 0x1A45DFA3,
kMkvEBMLVersion = 0x4286,
kMkvEBMLReadVersion = 0x42F7,
kMkvEBMLMaxIDLength = 0x42F2,
kMkvEBMLMaxSizeLength = 0x42F3,
kMkvDocType = 0x4282,
kMkvDocTypeVersion = 0x4287,
kMkvDocTypeReadVersion = 0x4285,
kMkvVoid = 0xEC,
kMkvSignatureSlot = 0x1B538667,
kMkvSignatureAlgo = 0x7E8A,
kMkvSignatureHash = 0x7E9A,
kMkvSignaturePublicKey = 0x7EA5,
kMkvSignature = 0x7EB5,
kMkvSignatureElements = 0x7E5B,
kMkvSignatureElementList = 0x7E7B,
kMkvSignedElement = 0x6532,
// segment
kMkvSegment = 0x18538067,
// Meta Seek Information
kMkvSeekHead = 0x114D9B74,
kMkvSeek = 0x4DBB,
kMkvSeekID = 0x53AB,
kMkvSeekPosition = 0x53AC,
// Segment Information
kMkvInfo = 0x1549A966,
kMkvTimecodeScale = 0x2AD7B1,
kMkvDuration = 0x4489,
kMkvDateUTC = 0x4461,
kMkvTitle = 0x7BA9,
kMkvMuxingApp = 0x4D80,
kMkvWritingApp = 0x5741,
// Cluster
kMkvCluster = 0x1F43B675,
kMkvTimecode = 0xE7,
kMkvPrevSize = 0xAB,
kMkvBlockGroup = 0xA0,
kMkvBlock = 0xA1,
kMkvBlockDuration = 0x9B,
kMkvReferenceBlock = 0xFB,
kMkvLaceNumber = 0xCC,
kMkvSimpleBlock = 0xA3,
kMkvBlockAdditions = 0x75A1,
kMkvBlockMore = 0xA6,
kMkvBlockAddID = 0xEE,
kMkvBlockAdditional = 0xA5,
kMkvDiscardPadding = 0x75A2,
// Track
kMkvTracks = 0x1654AE6B,
kMkvTrackEntry = 0xAE,
kMkvTrackNumber = 0xD7,
kMkvTrackUID = 0x73C5,
kMkvTrackType = 0x83,
kMkvFlagEnabled = 0xB9,
kMkvFlagDefault = 0x88,
kMkvFlagForced = 0x55AA,
kMkvFlagLacing = 0x9C,
kMkvDefaultDuration = 0x23E383,
kMkvMaxBlockAdditionID = 0x55EE,
kMkvName = 0x536E,
kMkvLanguage = 0x22B59C,
kMkvCodecID = 0x86,
kMkvCodecPrivate = 0x63A2,
kMkvCodecName = 0x258688,
kMkvCodecDelay = 0x56AA,
kMkvSeekPreRoll = 0x56BB,
// video
kMkvVideo = 0xE0,
kMkvFlagInterlaced = 0x9A,
kMkvStereoMode = 0x53B8,
kMkvAlphaMode = 0x53C0,
kMkvPixelWidth = 0xB0,
kMkvPixelHeight = 0xBA,
kMkvPixelCropBottom = 0x54AA,
kMkvPixelCropTop = 0x54BB,
kMkvPixelCropLeft = 0x54CC,
kMkvPixelCropRight = 0x54DD,
kMkvDisplayWidth = 0x54B0,
kMkvDisplayHeight = 0x54BA,
kMkvDisplayUnit = 0x54B2,
kMkvAspectRatioType = 0x54B3,
kMkvFrameRate = 0x2383E3,
// end video
// audio
kMkvAudio = 0xE1,
kMkvSamplingFrequency = 0xB5,
kMkvOutputSamplingFrequency = 0x78B5,
kMkvChannels = 0x9F,
kMkvBitDepth = 0x6264,
// end audio
// ContentEncodings
kMkvContentEncodings = 0x6D80,
kMkvContentEncoding = 0x6240,
kMkvContentEncodingOrder = 0x5031,
kMkvContentEncodingScope = 0x5032,
kMkvContentEncodingType = 0x5033,
kMkvContentCompression = 0x5034,
kMkvContentCompAlgo = 0x4254,
kMkvContentCompSettings = 0x4255,
kMkvContentEncryption = 0x5035,
kMkvContentEncAlgo = 0x47E1,
kMkvContentEncKeyID = 0x47E2,
kMkvContentSignature = 0x47E3,
kMkvContentSigKeyID = 0x47E4,
kMkvContentSigAlgo = 0x47E5,
kMkvContentSigHashAlgo = 0x47E6,
kMkvContentEncAESSettings = 0x47E7,
kMkvAESSettingsCipherMode = 0x47E8,
kMkvAESSettingsCipherInitData = 0x47E9,
// end ContentEncodings
// Cueing Data
kMkvCues = 0x1C53BB6B,
kMkvCuePoint = 0xBB,
kMkvCueTime = 0xB3,
kMkvCueTrackPositions = 0xB7,
kMkvCueTrack = 0xF7,
kMkvCueClusterPosition = 0xF1,
kMkvCueBlockNumber = 0x5378,
// Chapters
kMkvChapters = 0x1043A770,
kMkvEditionEntry = 0x45B9,
kMkvChapterAtom = 0xB6,
kMkvChapterUID = 0x73C4,
kMkvChapterStringUID = 0x5654,
kMkvChapterTimeStart = 0x91,
kMkvChapterTimeEnd = 0x92,
kMkvChapterDisplay = 0x80,
kMkvChapString = 0x85,
kMkvChapLanguage = 0x437C,
kMkvChapCountry = 0x437E,
// Tags
kMkvTags = 0x1254C367,
kMkvTag = 0x7373,
kMkvSimpleTag = 0x67C8,
kMkvTagName = 0x45A3,
kMkvTagString = 0x4487
};
} // end namespace mkvmuxer
#endif // WEBMIDS_HPP

702
webvttparser.cc Normal file
View File

@@ -0,0 +1,702 @@
// Copyright (c) 2012 The WebM project authors. All Rights Reserved.
//
// Use of this source code is governed by a BSD-style license
// that can be found in the LICENSE file in the root of the source
// tree. An additional intellectual property rights grant can be found
// in the file PATENTS. All contributing project authors may
// be found in the AUTHORS file in the root of the source tree.
#include "./webvttparser.h" // NOLINT
#include <climits>
namespace libwebvtt {
// NOLINT'ing this enum because clang-format puts it in a single line which
// makes it look really unreadable.
enum {
kNUL = '\x00',
kSPACE = ' ',
kTAB = '\x09',
kLF = '\x0A',
kCR = '\x0D'
}; // NOLINT
Reader::~Reader() {}
LineReader::~LineReader() {}
int LineReader::GetLine(std::string* line_ptr) {
if (line_ptr == NULL)
return -1;
std::string& ln = *line_ptr;
ln.clear();
// Consume characters from the stream, until we
// reach end-of-line (or end-of-stream).
// The WebVTT spec states that lines may be
// terminated in any of these three ways:
// LF
// CR
// CR LF
// We interrogate each character as we read it from the stream.
// If we detect an end-of-line character, we consume the full
// end-of-line indication, and we're done; otherwise, accumulate
// the character and repeat.
for (;;) {
char c;
const int e = GetChar(&c);
if (e < 0) // error
return e;
if (e > 0) // EOF
return (ln.empty()) ? 1 : 0;
// We have a character, so we must first determine
// whether we have reached end-of-line.
if (c == kLF)
return 0; // handle the easy end-of-line case immediately
if (c == kCR)
break; // handle the hard end-of-line case outside of loop
if (c == '\xFE' || c == '\xFF') // not UTF-8
return -1;
// To defend against pathological or malicious streams, we
// cap the line length at some arbitrarily-large value:
enum { kMaxLineLength = 10000 }; // arbitrary
if (ln.length() >= kMaxLineLength)
return -1;
// We don't have an end-of-line character, so accumulate
// the character in our line buffer.
ln.push_back(c);
}
// We detected a CR. We must interrogate the next character
// in the stream, to determine whether we have a LF (which
// would make it part of this same line).
char c;
const int e = GetChar(&c);
if (e < 0) // error
return e;
if (e > 0) // EOF
return 0;
// If next character in the stream is not a LF, return it
// to the stream (because it's part of the next line).
if (c != kLF)
UngetChar(c);
return 0;
}
Parser::Parser(Reader* r) : reader_(r), unget_(-1) {}
Parser::~Parser() {}
int Parser::Init() {
int e = ParseBOM();
if (e < 0) // error
return e;
if (e > 0) // EOF
return -1;
// Parse "WEBVTT". We read from the stream one character at-a-time, in
// order to defend against non-WebVTT streams (e.g. binary files) that don't
// happen to comprise lines of text demarcated with line terminators.
const char kId[] = "WEBVTT";
for (const char* p = kId; *p; ++p) {
char c;
e = GetChar(&c);
if (e < 0) // error
return e;
if (e > 0) // EOF
return -1;
if (c != *p)
return -1;
}
std::string line;
e = GetLine(&line);
if (e < 0) // error
return e;
if (e > 0) // EOF
return 0; // weird but valid
if (!line.empty()) {
// Parse optional characters that follow "WEBVTT"
const char c = line[0];
if (c != kSPACE && c != kTAB)
return -1;
}
// The WebVTT spec requires that the "WEBVTT" line
// be followed by an empty line (to separate it from
// first cue).
e = GetLine(&line);
if (e < 0) // error
return e;
if (e > 0) // EOF
return 0; // weird but we allow it
if (!line.empty())
return -1;
return 0; // success
}
int Parser::Parse(Cue* cue) {
if (cue == NULL)
return -1;
// Parse first non-blank line
std::string line;
int e;
for (;;) {
e = GetLine(&line);
if (e) // EOF is OK here
return e;
if (!line.empty())
break;
}
// A WebVTT cue comprises an optional cue identifier line followed
// by a (non-optional) timings line. You determine whether you have
// a timings line by scanning for the arrow token, the lexeme of which
// may not appear in the cue identifier line.
const char kArrow[] = "-->";
std::string::size_type arrow_pos = line.find(kArrow);
if (arrow_pos != std::string::npos) {
// We found a timings line, which implies that we don't have a cue
// identifier.
cue->identifier.clear();
} else {
// We did not find a timings line, so we assume that we have a cue
// identifier line, and then try again to find the cue timings on
// the next line.
cue->identifier.swap(line);
e = GetLine(&line);
if (e < 0) // error
return e;
if (e > 0) // EOF
return -1;
arrow_pos = line.find(kArrow);
if (arrow_pos == std::string::npos) // not a timings line
return -1;
}
e = ParseTimingsLine(&line, arrow_pos, &cue->start_time, &cue->stop_time,
&cue->settings);
if (e) // error
return e;
// The cue payload comprises all the non-empty
// lines that follow the timings line.
Cue::payload_t& p = cue->payload;
p.clear();
for (;;) {
e = GetLine(&line);
if (e < 0) // error
return e;
if (line.empty())
break;
p.push_back(line);
}
if (p.empty())
return -1;
return 0; // success
}
int Parser::GetChar(char* c) {
if (unget_ >= 0) {
*c = static_cast<char>(unget_);
unget_ = -1;
return 0;
}
return reader_->GetChar(c);
}
void Parser::UngetChar(char c) { unget_ = static_cast<unsigned char>(c); }
int Parser::ParseBOM() {
// Explanation of UTF-8 BOM:
// http://en.wikipedia.org/wiki/Byte_order_mark
static const char BOM[] = "\xEF\xBB\xBF"; // UTF-8 BOM
for (int i = 0; i < 3; ++i) {
char c;
int e = GetChar(&c);
if (e < 0) // error
return e;
if (e > 0) // EOF
return 1;
if (c != BOM[i]) {
if (i == 0) { // we don't have a BOM
UngetChar(c);
return 0; // success
}
// We started a BOM, so we must finish the BOM.
return -1; // error
}
}
return 0; // success
}
int Parser::ParseTimingsLine(std::string* line_ptr,
std::string::size_type arrow_pos, Time* start_time,
Time* stop_time, Cue::settings_t* settings) {
if (line_ptr == NULL)
return -1;
std::string& line = *line_ptr;
if (arrow_pos == std::string::npos || arrow_pos >= line.length())
return -1;
// Place a NUL character at the start of the arrow token, in
// order to demarcate the start time from remainder of line.
line[arrow_pos] = kNUL;
std::string::size_type idx = 0;
int e = ParseTime(line, &idx, start_time);
if (e) // error
return e;
// Detect any junk that follows the start time,
// but precedes the arrow symbol.
while (char c = line[idx]) {
if (c != kSPACE && c != kTAB)
return -1;
++idx;
}
// Place a NUL character at the end of the line,
// so the scanner has a place to stop, and begin
// the scan just beyond the arrow token.
line.push_back(kNUL);
idx = arrow_pos + 3;
e = ParseTime(line, &idx, stop_time);
if (e) // error
return e;
e = ParseSettings(line, idx, settings);
if (e) // error
return e;
return 0; // success
}
int Parser::ParseTime(const std::string& line, std::string::size_type* idx_ptr,
Time* time) {
if (idx_ptr == NULL)
return -1;
std::string::size_type& idx = *idx_ptr;
if (idx == std::string::npos || idx >= line.length())
return -1;
if (time == NULL)
return -1;
// Consume any whitespace that precedes the timestamp.
while (char c = line[idx]) {
if (c != kSPACE && c != kTAB)
break;
++idx;
}
// WebVTT timestamp syntax comes in three flavors:
// SS[.sss]
// MM:SS[.sss]
// HH:MM:SS[.sss]
// Parse a generic number value. We don't know which component
// of the time we have yet, until we do more parsing.
int val = ParseNumber(line, &idx);
if (val < 0) // error
return val;
Time& t = *time;
// The presence of a colon character indicates that we have
// an [HH:]MM:SS style syntax.
if (line[idx] == ':') {
// We have either HH:MM:SS or MM:SS
// The value we just parsed is either the hours or minutes.
// It must be followed by another number value (that is
// either minutes or seconds).
const int first_val = val;
++idx; // consume colon
// Parse second value
val = ParseNumber(line, &idx);
if (val < 0)
return val;
if (val >= 60) // either MM or SS
return -1;
if (line[idx] == ':') {
// We have HH:MM:SS
t.hours = first_val;
t.minutes = val; // vetted above
++idx; // consume MM:SS colon
// We have parsed the hours and minutes.
// We must now parse the seconds.
val = ParseNumber(line, &idx);
if (val < 0)
return val;
if (val >= 60) // SS part of HH:MM:SS
return -1;
t.seconds = val;
} else {
// We have MM:SS
// The implication here is that the hour value was omitted
// from the timestamp (because it was 0).
if (first_val >= 60) // minutes
return -1;
t.hours = 0;
t.minutes = first_val;
t.seconds = val; // vetted above
}
} else {
// We have SS (only)
// The time is expressed as total number of seconds,
// so the seconds value has no upper bound.
t.seconds = val;
// Convert SS to HH:MM:SS
t.minutes = t.seconds / 60;
t.seconds -= t.minutes * 60;
t.hours = t.minutes / 60;
t.minutes -= t.hours * 60;
}
// We have parsed the hours, minutes, and seconds.
// We must now parse the milliseconds.
char c = line[idx];
// TODO(matthewjheaney): one option here is to slightly relax the
// syntax rules for WebVTT timestamps, to permit the comma character
// to also be used as the seconds/milliseconds separator. This
// would handle streams that use localization conventions for
// countries in Western Europe. For now we obey the rules specified
// in the WebVTT spec (allow "full stop" only).
const bool have_milliseconds = (c == '.');
if (!have_milliseconds) {
t.milliseconds = 0;
} else {
++idx; // consume FULL STOP
val = ParseNumber(line, &idx);
if (val < 0)
return val;
if (val >= 1000)
return -1;
if (val < 10)
t.milliseconds = val * 100;
else if (val < 100)
t.milliseconds = val * 10;
else
t.milliseconds = val;
}
// We have parsed the time proper. We must check for any
// junk that immediately follows the time specifier.
c = line[idx];
if (c != kNUL && c != kSPACE && c != kTAB)
return -1;
return 0; // success
}
int Parser::ParseSettings(const std::string& line, std::string::size_type idx,
Cue::settings_t* settings) {
settings->clear();
if (idx == std::string::npos || idx >= line.length())
return -1;
for (;;) {
// We must parse a line comprising a sequence of 0 or more
// NAME:VALUE pairs, separated by whitespace. The line iself is
// terminated with a NUL char (indicating end-of-line).
for (;;) {
const char c = line[idx];
if (c == kNUL) // end-of-line
return 0; // success
if (c != kSPACE && c != kTAB)
break;
++idx; // consume whitespace
}
// We have consumed the whitespace, and have not yet reached
// end-of-line, so there is something on the line for us to parse.
settings->push_back(Setting());
Setting& s = settings->back();
// Parse the NAME part of the settings pair.
for (;;) {
const char c = line[idx];
if (c == ':') // we have reached end of NAME part
break;
if (c == kNUL || c == kSPACE || c == kTAB)
return -1;
s.name.push_back(c);
++idx;
}
if (s.name.empty())
return -1;
++idx; // consume colon
// Parse the VALUE part of the settings pair.
for (;;) {
const char c = line[idx];
if (c == kNUL || c == kSPACE || c == kTAB)
break;
if (c == ':') // suspicious when part of VALUE
return -1; // TODO(matthewjheaney): verify this behavior
s.value.push_back(c);
++idx;
}
if (s.value.empty())
return -1;
}
}
int Parser::ParseNumber(const std::string& line,
std::string::size_type* idx_ptr) {
if (idx_ptr == NULL)
return -1;
std::string::size_type& idx = *idx_ptr;
if (idx == std::string::npos || idx >= line.length())
return -1;
if (!isdigit(line[idx]))
return -1;
int result = 0;
while (isdigit(line[idx])) {
const char c = line[idx];
const int i = c - '0';
if (result > INT_MAX / 10)
return -1;
result *= 10;
if (result > INT_MAX - i)
return -1;
result += i;
++idx;
}
return result;
}
bool Time::operator==(const Time& rhs) const {
if (hours != rhs.hours)
return false;
if (minutes != rhs.minutes)
return false;
if (seconds != rhs.seconds)
return false;
return (milliseconds == rhs.milliseconds);
}
bool Time::operator<(const Time& rhs) const {
if (hours < rhs.hours)
return true;
if (hours > rhs.hours)
return false;
if (minutes < rhs.minutes)
return true;
if (minutes > rhs.minutes)
return false;
if (seconds < rhs.seconds)
return true;
if (seconds > rhs.seconds)
return false;
return (milliseconds < rhs.milliseconds);
}
bool Time::operator>(const Time& rhs) const { return rhs.operator<(*this); }
bool Time::operator<=(const Time& rhs) const { return !this->operator>(rhs); }
bool Time::operator>=(const Time& rhs) const { return !this->operator<(rhs); }
presentation_t Time::presentation() const {
const presentation_t h = 1000LL * 3600LL * presentation_t(hours);
const presentation_t m = 1000LL * 60LL * presentation_t(minutes);
const presentation_t s = 1000LL * presentation_t(seconds);
const presentation_t result = h + m + s + milliseconds;
return result;
}
Time& Time::presentation(presentation_t d) {
if (d < 0) { // error
hours = 0;
minutes = 0;
seconds = 0;
milliseconds = 0;
return *this;
}
seconds = static_cast<int>(d / 1000);
milliseconds = static_cast<int>(d - 1000 * seconds);
minutes = seconds / 60;
seconds -= 60 * minutes;
hours = minutes / 60;
minutes -= 60 * hours;
return *this;
}
Time& Time::operator+=(presentation_t rhs) {
const presentation_t d = this->presentation();
const presentation_t dd = d + rhs;
this->presentation(dd);
return *this;
}
Time Time::operator+(presentation_t d) const {
Time t(*this);
t += d;
return t;
}
Time& Time::operator-=(presentation_t d) { return this->operator+=(-d); }
presentation_t Time::operator-(const Time& t) const {
const presentation_t rhs = t.presentation();
const presentation_t lhs = this->presentation();
const presentation_t result = lhs - rhs;
return result;
}
} // namespace libwebvtt

158
webvttparser.h Normal file
View File

@@ -0,0 +1,158 @@
// Copyright (c) 2012 The WebM project authors. All Rights Reserved.
//
// Use of this source code is governed by a BSD-style license
// that can be found in the LICENSE file in the root of the source
// tree. An additional intellectual property rights grant can be found
// in the file PATENTS. All contributing project authors may
// be found in the AUTHORS file in the root of the source tree.
#ifndef WEBVTTPARSER_H_ // NOLINT
#define WEBVTTPARSER_H_
#include <list>
#include <string>
namespace libwebvtt {
class Reader {
public:
// Fetch a character from the stream. Return
// negative if error, positive if end-of-stream,
// and 0 if a character is available.
virtual int GetChar(char* c) = 0;
protected:
virtual ~Reader();
};
class LineReader : protected Reader {
public:
// Consume a line of text from the stream, stripping off
// the line terminator characters. Returns negative if error,
// 0 on success, and positive at end-of-stream.
int GetLine(std::string* line);
protected:
virtual ~LineReader();
// Puts a character back into the stream.
virtual void UngetChar(char c) = 0;
};
// As measured in thousandths of a second,
// e.g. a duration of 1 equals 0.001 seconds,
// and a duration of 1000 equals 1 second.
typedef long long presentation_t; // NOLINT
struct Time {
int hours;
int minutes;
int seconds;
int milliseconds;
bool operator==(const Time& rhs) const;
bool operator<(const Time& rhs) const;
bool operator>(const Time& rhs) const;
bool operator<=(const Time& rhs) const;
bool operator>=(const Time& rhs) const;
presentation_t presentation() const;
Time& presentation(presentation_t);
Time& operator+=(presentation_t);
Time operator+(presentation_t) const;
Time& operator-=(presentation_t);
presentation_t operator-(const Time&) const;
};
struct Setting {
std::string name;
std::string value;
};
struct Cue {
std::string identifier;
Time start_time;
Time stop_time;
typedef std::list<Setting> settings_t;
settings_t settings;
typedef std::list<std::string> payload_t;
payload_t payload;
};
class Parser : private LineReader {
public:
explicit Parser(Reader* r);
virtual ~Parser();
// Pre-parse enough of the stream to determine whether
// this is really a WEBVTT file. Returns 0 on success,
// negative if error.
int Init();
// Parse the next WebVTT cue from the stream. Returns 0 if
// an entire cue was parsed, negative if error, and positive
// at end-of-stream.
int Parse(Cue* cue);
private:
// Returns the next character in the stream, using the look-back character
// if present (as per Reader::GetChar).
virtual int GetChar(char* c);
// Puts a character back into the stream (as per LineReader::UngetChar).
virtual void UngetChar(char c);
// Check for presence of a UTF-8 BOM in the stream. Returns
// negative if error, 0 on success, and positive at end-of-stream.
int ParseBOM();
// Parse the distinguished "cue timings" line, which includes the start
// and stop times and settings. Argument |line| contains the complete
// line of text (as returned by ParseLine()), which the function is free
// to modify as it sees fit, to facilitate scanning. Argument |arrow_pos|
// is the offset of the arrow token ("-->"), which indicates that this is
// the timings line. Returns negative if error, 0 on success.
//
static int ParseTimingsLine(std::string* line,
std::string::size_type arrow_pos,
Time* start_time, Time* stop_time,
Cue::settings_t* settings);
// Parse a single time specifier (from the timings line), starting
// at the given offset; lexical scanning stops when a NUL character
// is detected. The function modifies offset |off| by the number of
// characters consumed. Returns negative if error, 0 on success.
//
static int ParseTime(const std::string& line, std::string::size_type* off,
Time* time);
// Parse the cue settings from the timings line, starting at the
// given offset. Returns negative if error, 0 on success.
//
static int ParseSettings(const std::string& line, std::string::size_type off,
Cue::settings_t* settings);
// Parse a non-negative integer from the characters in |line| beginning
// at offset |off|. The function increments |off| by the number
// of characters consumed. Returns the value, or negative if error.
//
static int ParseNumber(const std::string& line, std::string::size_type* off);
Reader* const reader_;
// Provides one character's worth of look-back, to facilitate scanning.
int unget_;
// Disable copy ctor and copy assign for Parser.
Parser(const Parser&);
Parser& operator=(const Parser&);
};
} // namespace libwebvtt
#endif // WEBVTTPARSER_H_ // NOLINT