Welcome to mirror list, hosted at ThFree Co, Russian Federation.

github.com/mpc-hc/mpc-hc.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorXhmikosR <xhmikosr@users.sourceforge.net>2010-04-09 18:12:59 +0400
committerXhmikosR <xhmikosr@users.sourceforge.net>2010-04-09 18:12:59 +0400
commitefbc9d9043ff8ff92716ddd00a5f61412d535593 (patch)
tree8f3e621f756cf1f5b4d64d97964c7e7abd8aaf08 /src/filters/parser
parentdf6b139a6d9027156f614b68687e039e3a5854db (diff)
revert r1783
git-svn-id: https://mpc-hc.svn.sourceforge.net/svnroot/mpc-hc/trunk@1785 10f7b99b-c216-0410-bff0-8a66a9350fd8
Diffstat (limited to 'src/filters/parser')
-rw-r--r--src/filters/parser/AviSplitter/AviFile.cpp1051
-rw-r--r--src/filters/parser/AviSplitter/AviFile.h90
-rw-r--r--src/filters/parser/AviSplitter/AviReportWnd.cpp558
-rw-r--r--src/filters/parser/AviSplitter/AviReportWnd.h45
-rw-r--r--src/filters/parser/AviSplitter/AviSplitter.cpp1296
-rw-r--r--src/filters/parser/AviSplitter/AviSplitter.h62
-rw-r--r--src/filters/parser/AviSplitter/resource.h2
-rw-r--r--src/filters/parser/AviSplitter/stdafx.cpp8
-rw-r--r--src/filters/parser/AviSplitter/stdafx.h8
-rw-r--r--src/filters/parser/BaseSplitter/AsyncReader.cpp276
-rw-r--r--src/filters/parser/BaseSplitter/AsyncReader.h130
-rw-r--r--src/filters/parser/BaseSplitter/BaseSplitter.cpp1722
-rw-r--r--src/filters/parser/BaseSplitter/BaseSplitter.h559
-rw-r--r--src/filters/parser/BaseSplitter/BaseSplitterFile.cpp319
-rw-r--r--src/filters/parser/BaseSplitter/BaseSplitterFile.h67
-rw-r--r--src/filters/parser/BaseSplitter/BaseSplitterFileEx.cpp2894
-rw-r--r--src/filters/parser/BaseSplitter/BaseSplitterFileEx.h699
-rw-r--r--src/filters/parser/BaseSplitter/MultiFiles.cpp251
-rw-r--r--src/filters/parser/BaseSplitter/MultiFiles.h102
-rw-r--r--src/filters/parser/BaseSplitter/stdafx.cpp8
-rw-r--r--src/filters/parser/BaseSplitter/stdafx.h8
-rw-r--r--src/filters/parser/DSMSplitter/DSMSplitter.cpp294
-rw-r--r--src/filters/parser/DSMSplitter/DSMSplitter.h30
-rw-r--r--src/filters/parser/DSMSplitter/DSMSplitterFile.cpp677
-rw-r--r--src/filters/parser/DSMSplitter/DSMSplitterFile.h52
-rw-r--r--src/filters/parser/DSMSplitter/resource.h2
-rw-r--r--src/filters/parser/DSMSplitter/stdafx.cpp8
-rw-r--r--src/filters/parser/DSMSplitter/stdafx.h8
-rw-r--r--src/filters/parser/DiracSplitter/DiracSplitter.cpp127
-rw-r--r--src/filters/parser/DiracSplitter/DiracSplitter.h56
-rw-r--r--src/filters/parser/DiracSplitter/DiracSplitterFile.cpp38
-rw-r--r--src/filters/parser/DiracSplitter/DiracSplitterFile.h26
-rw-r--r--src/filters/parser/DiracSplitter/libdirac/libdirac_byteio/accessunit_byteio.cpp88
-rw-r--r--src/filters/parser/DiracSplitter/libdirac/libdirac_byteio/accessunit_byteio.h243
-rw-r--r--src/filters/parser/DiracSplitter/libdirac/libdirac_byteio/byteio.cpp110
-rw-r--r--src/filters/parser/DiracSplitter/libdirac/libdirac_byteio/byteio.h687
-rw-r--r--src/filters/parser/DiracSplitter/libdirac/libdirac_byteio/codingparams_byteio.cpp34
-rw-r--r--src/filters/parser/DiracSplitter/libdirac/libdirac_byteio/codingparams_byteio.h150
-rw-r--r--src/filters/parser/DiracSplitter/libdirac/libdirac_byteio/component_byteio.cpp16
-rw-r--r--src/filters/parser/DiracSplitter/libdirac/libdirac_byteio/component_byteio.h130
-rw-r--r--src/filters/parser/DiracSplitter/libdirac/libdirac_byteio/dirac_byte_stats.cpp22
-rw-r--r--src/filters/parser/DiracSplitter/libdirac/libdirac_byteio/dirac_byte_stats.h125
-rw-r--r--src/filters/parser/DiracSplitter/libdirac/libdirac_byteio/dirac_byte_stream.cpp54
-rw-r--r--src/filters/parser/DiracSplitter/libdirac/libdirac_byteio/dirac_byte_stream.h194
-rw-r--r--src/filters/parser/DiracSplitter/libdirac/libdirac_byteio/displayparams_byteio.cpp210
-rw-r--r--src/filters/parser/DiracSplitter/libdirac/libdirac_byteio/displayparams_byteio.h284
-rw-r--r--src/filters/parser/DiracSplitter/libdirac/libdirac_byteio/endofsequence_byteio.cpp12
-rw-r--r--src/filters/parser/DiracSplitter/libdirac/libdirac_byteio/endofsequence_byteio.h96
-rw-r--r--src/filters/parser/DiracSplitter/libdirac/libdirac_byteio/mvdata_byteio.cpp154
-rw-r--r--src/filters/parser/DiracSplitter/libdirac/libdirac_byteio/mvdata_byteio.h439
-rw-r--r--src/filters/parser/DiracSplitter/libdirac/libdirac_byteio/mvdataelement_byteio.cpp10
-rw-r--r--src/filters/parser/DiracSplitter/libdirac/libdirac_byteio/mvdataelement_byteio.h132
-rw-r--r--src/filters/parser/DiracSplitter/libdirac/libdirac_byteio/parseparams_byteio.cpp58
-rw-r--r--src/filters/parser/DiracSplitter/libdirac/libdirac_byteio/parseparams_byteio.h114
-rw-r--r--src/filters/parser/DiracSplitter/libdirac/libdirac_byteio/parseunit_byteio.cpp64
-rw-r--r--src/filters/parser/DiracSplitter/libdirac/libdirac_byteio/parseunit_byteio.h395
-rw-r--r--src/filters/parser/DiracSplitter/libdirac/libdirac_byteio/picture_byteio.cpp92
-rw-r--r--src/filters/parser/DiracSplitter/libdirac/libdirac_byteio/picture_byteio.h314
-rw-r--r--src/filters/parser/DiracSplitter/libdirac/libdirac_byteio/subband_byteio.cpp42
-rw-r--r--src/filters/parser/DiracSplitter/libdirac/libdirac_byteio/subband_byteio.h114
-rw-r--r--src/filters/parser/DiracSplitter/libdirac/libdirac_byteio/transform_byteio.cpp50
-rw-r--r--src/filters/parser/DiracSplitter/libdirac/libdirac_byteio/transform_byteio.h172
-rw-r--r--src/filters/parser/DiracSplitter/libdirac/libdirac_common/arith_codec.cpp226
-rw-r--r--src/filters/parser/DiracSplitter/libdirac/libdirac_common/arith_codec.h661
-rw-r--r--src/filters/parser/DiracSplitter/libdirac/libdirac_common/arrays.h885
-rw-r--r--src/filters/parser/DiracSplitter/libdirac/libdirac_common/band_codec.cpp30
-rw-r--r--src/filters/parser/DiracSplitter/libdirac/libdirac_common/band_codec.h324
-rw-r--r--src/filters/parser/DiracSplitter/libdirac/libdirac_common/band_codec_template.h354
-rw-r--r--src/filters/parser/DiracSplitter/libdirac/libdirac_common/band_vlc.cpp16
-rw-r--r--src/filters/parser/DiracSplitter/libdirac/libdirac_common/band_vlc.h156
-rw-r--r--src/filters/parser/DiracSplitter/libdirac/libdirac_common/bit_manager.cpp176
-rw-r--r--src/filters/parser/DiracSplitter/libdirac/libdirac_common/bit_manager.h848
-rw-r--r--src/filters/parser/DiracSplitter/libdirac/libdirac_common/cmd_line.cpp16
-rw-r--r--src/filters/parser/DiracSplitter/libdirac/libdirac_common/cmd_line.h72
-rw-r--r--src/filters/parser/DiracSplitter/libdirac/libdirac_common/common.cpp400
-rw-r--r--src/filters/parser/DiracSplitter/libdirac/libdirac_common/common.h3005
-rw-r--r--src/filters/parser/DiracSplitter/libdirac/libdirac_common/common_types.h263
-rw-r--r--src/filters/parser/DiracSplitter/libdirac/libdirac_common/dirac_assertions.cpp14
-rw-r--r--src/filters/parser/DiracSplitter/libdirac/libdirac_common/dirac_assertions.h4
-rw-r--r--src/filters/parser/DiracSplitter/libdirac/libdirac_common/dirac_exception.cpp16
-rw-r--r--src/filters/parser/DiracSplitter/libdirac/libdirac_common/dirac_exception.h65
-rw-r--r--src/filters/parser/DiracSplitter/libdirac/libdirac_common/dirac_types.h244
-rw-r--r--src/filters/parser/DiracSplitter/libdirac/libdirac_common/mot_comp.cpp764
-rw-r--r--src/filters/parser/DiracSplitter/libdirac/libdirac_common/mot_comp.h468
-rw-r--r--src/filters/parser/DiracSplitter/libdirac/libdirac_common/mot_comp_mmx.cpp432
-rw-r--r--src/filters/parser/DiracSplitter/libdirac/libdirac_common/mot_comp_mmx.h14
-rw-r--r--src/filters/parser/DiracSplitter/libdirac/libdirac_common/motion.cpp624
-rw-r--r--src/filters/parser/DiracSplitter/libdirac/libdirac_common/motion.h661
-rw-r--r--src/filters/parser/DiracSplitter/libdirac/libdirac_common/mv_codec.cpp532
-rw-r--r--src/filters/parser/DiracSplitter/libdirac/libdirac_common/mv_codec.h434
-rw-r--r--src/filters/parser/DiracSplitter/libdirac/libdirac_common/pic_io.cpp305
-rw-r--r--src/filters/parser/DiracSplitter/libdirac/libdirac_common/pic_io.h844
-rw-r--r--src/filters/parser/DiracSplitter/libdirac/libdirac_common/picture.cpp226
-rw-r--r--src/filters/parser/DiracSplitter/libdirac/libdirac_common/picture.h170
-rw-r--r--src/filters/parser/DiracSplitter/libdirac/libdirac_common/picture_buffer.cpp128
-rw-r--r--src/filters/parser/DiracSplitter/libdirac/libdirac_common/picture_buffer.h277
-rw-r--r--src/filters/parser/DiracSplitter/libdirac/libdirac_common/upconvert.cpp70
-rw-r--r--src/filters/parser/DiracSplitter/libdirac/libdirac_common/upconvert.h78
-rw-r--r--src/filters/parser/DiracSplitter/libdirac/libdirac_common/video_format_defaults.cpp40
-rw-r--r--src/filters/parser/DiracSplitter/libdirac/libdirac_common/video_format_defaults.h94
-rw-r--r--src/filters/parser/DiracSplitter/libdirac/libdirac_common/wavelet_utils.cpp1209
-rw-r--r--src/filters/parser/DiracSplitter/libdirac/libdirac_common/wavelet_utils.h1140
-rw-r--r--src/filters/parser/DiracSplitter/libdirac/libdirac_common/wavelet_utils_mmx.cpp1432
-rw-r--r--src/filters/parser/DiracSplitter/libdirac/libdirac_decoder/comp_decompress.cpp88
-rw-r--r--src/filters/parser/DiracSplitter/libdirac/libdirac_decoder/comp_decompress.h144
-rw-r--r--src/filters/parser/DiracSplitter/libdirac/libdirac_decoder/decoder_types.h21
-rw-r--r--src/filters/parser/DiracSplitter/libdirac/libdirac_decoder/dirac_cppparser.cpp116
-rw-r--r--src/filters/parser/DiracSplitter/libdirac/libdirac_decoder/dirac_cppparser.h248
-rw-r--r--src/filters/parser/DiracSplitter/libdirac/libdirac_decoder/dirac_parser.cpp578
-rw-r--r--src/filters/parser/DiracSplitter/libdirac/libdirac_decoder/dirac_parser.h164
-rw-r--r--src/filters/parser/DiracSplitter/libdirac/libdirac_decoder/picture_decompress.cpp300
-rw-r--r--src/filters/parser/DiracSplitter/libdirac/libdirac_decoder/picture_decompress.h200
-rw-r--r--src/filters/parser/DiracSplitter/libdirac/libdirac_decoder/seq_decompress.cpp68
-rw-r--r--src/filters/parser/DiracSplitter/libdirac/libdirac_decoder/seq_decompress.h264
-rw-r--r--src/filters/parser/DiracSplitter/libdirac/libdirac_encoder/comp_compress.cpp76
-rw-r--r--src/filters/parser/DiracSplitter/libdirac/libdirac_encoder/comp_compress.h112
-rw-r--r--src/filters/parser/DiracSplitter/libdirac/libdirac_encoder/dirac_encoder.cpp794
-rw-r--r--src/filters/parser/DiracSplitter/libdirac/libdirac_encoder/dirac_encoder.h627
-rw-r--r--src/filters/parser/DiracSplitter/libdirac/libdirac_encoder/enc_picture.cpp309
-rw-r--r--src/filters/parser/DiracSplitter/libdirac/libdirac_encoder/enc_picture.h77
-rw-r--r--src/filters/parser/DiracSplitter/libdirac/libdirac_encoder/enc_queue.cpp145
-rw-r--r--src/filters/parser/DiracSplitter/libdirac/libdirac_encoder/enc_queue.h328
-rw-r--r--src/filters/parser/DiracSplitter/libdirac/libdirac_encoder/picture_compress.cpp600
-rw-r--r--src/filters/parser/DiracSplitter/libdirac/libdirac_encoder/picture_compress.h286
-rw-r--r--src/filters/parser/DiracSplitter/libdirac/libdirac_encoder/prefilter.cpp847
-rw-r--r--src/filters/parser/DiracSplitter/libdirac/libdirac_encoder/prefilter.h10
-rw-r--r--src/filters/parser/DiracSplitter/libdirac/libdirac_encoder/quality_monitor.cpp146
-rw-r--r--src/filters/parser/DiracSplitter/libdirac/libdirac_encoder/quality_monitor.h108
-rw-r--r--src/filters/parser/DiracSplitter/libdirac/libdirac_encoder/quant_chooser.cpp252
-rw-r--r--src/filters/parser/DiracSplitter/libdirac/libdirac_encoder/quant_chooser.h123
-rw-r--r--src/filters/parser/DiracSplitter/libdirac/libdirac_encoder/rate_control.cpp280
-rw-r--r--src/filters/parser/DiracSplitter/libdirac/libdirac_encoder/rate_control.h243
-rw-r--r--src/filters/parser/DiracSplitter/libdirac/libdirac_encoder/seq_compress.cpp681
-rw-r--r--src/filters/parser/DiracSplitter/libdirac/libdirac_encoder/seq_compress.h570
-rw-r--r--src/filters/parser/DiracSplitter/libdirac/libdirac_motionest/block_match.cpp386
-rw-r--r--src/filters/parser/DiracSplitter/libdirac/libdirac_motionest/block_match.h289
-rw-r--r--src/filters/parser/DiracSplitter/libdirac/libdirac_motionest/downconvert.cpp144
-rw-r--r--src/filters/parser/DiracSplitter/libdirac/libdirac_motionest/downconvert.h77
-rw-r--r--src/filters/parser/DiracSplitter/libdirac/libdirac_motionest/downconvert_mmx.cpp148
-rw-r--r--src/filters/parser/DiracSplitter/libdirac/libdirac_motionest/me_mode_decn.cpp390
-rw-r--r--src/filters/parser/DiracSplitter/libdirac/libdirac_motionest/me_mode_decn.h178
-rw-r--r--src/filters/parser/DiracSplitter/libdirac/libdirac_motionest/me_subpel.cpp62
-rw-r--r--src/filters/parser/DiracSplitter/libdirac/libdirac_motionest/me_subpel.h100
-rw-r--r--src/filters/parser/DiracSplitter/libdirac/libdirac_motionest/me_utils.cpp1723
-rw-r--r--src/filters/parser/DiracSplitter/libdirac/libdirac_motionest/me_utils.h1000
-rw-r--r--src/filters/parser/DiracSplitter/libdirac/libdirac_motionest/me_utils_mmx.cpp1913
-rw-r--r--src/filters/parser/DiracSplitter/libdirac/libdirac_motionest/me_utils_mmx.h44
-rw-r--r--src/filters/parser/DiracSplitter/libdirac/libdirac_motionest/motion_estimate.cpp152
-rw-r--r--src/filters/parser/DiracSplitter/libdirac/libdirac_motionest/motion_estimate.h113
-rw-r--r--src/filters/parser/DiracSplitter/libdirac/libdirac_motionest/pixel_match.cpp208
-rw-r--r--src/filters/parser/DiracSplitter/libdirac/libdirac_motionest/pixel_match.h142
-rw-r--r--src/filters/parser/DiracSplitter/resource.h2
-rw-r--r--src/filters/parser/DiracSplitter/stdafx.cpp8
-rw-r--r--src/filters/parser/DiracSplitter/stdafx.h36
-rw-r--r--src/filters/parser/FLVSplitter/FLVSplitter.cpp1278
-rw-r--r--src/filters/parser/FLVSplitter/FLVSplitter.h110
-rw-r--r--src/filters/parser/FLVSplitter/resource.h2
-rw-r--r--src/filters/parser/FLVSplitter/stdafx.cpp8
-rw-r--r--src/filters/parser/FLVSplitter/stdafx.h8
-rw-r--r--src/filters/parser/MP4Splitter/AP4/Source/Codecs/Ap4AdtsParser.cpp172
-rw-r--r--src/filters/parser/MP4Splitter/AP4/Source/Codecs/Ap4AdtsParser.h24
-rw-r--r--src/filters/parser/MP4Splitter/AP4/Source/Codecs/Ap4AvcParser.cpp266
-rw-r--r--src/filters/parser/MP4Splitter/AP4/Source/Codecs/Ap4AvcParser.h24
-rw-r--r--src/filters/parser/MP4Splitter/AP4/Source/Codecs/Ap4BitStream.cpp216
-rw-r--r--src/filters/parser/MP4Splitter/AP4/Source/Codecs/Ap4BitStream.h177
-rw-r--r--src/filters/parser/MP4Splitter/AP4/Source/Codecs/Ap4Mp4AudioInfo.cpp183
-rw-r--r--src/filters/parser/MP4Splitter/AP4/Source/Codecs/Ap4Mp4AudioInfo.h19
-rw-r--r--src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4.h74
-rw-r--r--src/filters/parser/MP4Splitter/AP4/Source/Core/Ap48bdlAtom.cpp28
-rw-r--r--src/filters/parser/MP4Splitter/AP4/Source/Core/Ap48bdlAtom.h29
-rw-r--r--src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4Array.h93
-rw-r--r--src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4Atom.cpp374
-rw-r--r--src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4Atom.h476
-rw-r--r--src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4AtomFactory.cpp625
-rw-r--r--src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4AtomFactory.h27
-rw-r--r--src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4AtomSampleTable.cpp264
-rw-r--r--src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4AtomSampleTable.h14
-rw-r--r--src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4AvcCAtom.cpp140
-rw-r--r--src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4AvcCAtom.h46
-rw-r--r--src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4ByteStream.cpp312
-rw-r--r--src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4ByteStream.h94
-rw-r--r--src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4ChplAtom.cpp42
-rw-r--r--src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4ChplAtom.h24
-rw-r--r--src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4CmvdAtom.cpp42
-rw-r--r--src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4CmvdAtom.h27
-rw-r--r--src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4Co64Atom.cpp50
-rw-r--r--src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4Co64Atom.h14
-rw-r--r--src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4Command.cpp2
-rw-r--r--src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4Command.h15
-rw-r--r--src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4CommandFactory.cpp31
-rw-r--r--src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4CommandFactory.h6
-rw-r--r--src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4ContainerAtom.cpp75
-rw-r--r--src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4ContainerAtom.h23
-rw-r--r--src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4CttsAtom.cpp56
-rw-r--r--src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4CttsAtom.h18
-rw-r--r--src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4DataBuffer.cpp57
-rw-r--r--src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4DataBuffer.h30
-rw-r--r--src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4DcomAtom.cpp14
-rw-r--r--src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4DcomAtom.h22
-rw-r--r--src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4Debug.cpp2
-rw-r--r--src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4DecoderConfigDescriptor.cpp39
-rw-r--r--src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4DecoderConfigDescriptor.h39
-rw-r--r--src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4DecoderSpecificInfoDescriptor.cpp18
-rw-r--r--src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4DecoderSpecificInfoDescriptor.h9
-rw-r--r--src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4Descriptor.cpp8
-rw-r--r--src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4Descriptor.h38
-rw-r--r--src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4DescriptorFactory.cpp63
-rw-r--r--src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4DescriptorFactory.h6
-rw-r--r--src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4DrefAtom.cpp27
-rw-r--r--src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4DrefAtom.h2
-rw-r--r--src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4ElstAtom.cpp47
-rw-r--r--src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4ElstAtom.h19
-rw-r--r--src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4EsDescriptor.cpp108
-rw-r--r--src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4EsDescriptor.h42
-rw-r--r--src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4EsdsAtom.cpp24
-rw-r--r--src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4EsdsAtom.h11
-rw-r--r--src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4Expandable.cpp42
-rw-r--r--src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4Expandable.h38
-rw-r--r--src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4File.cpp48
-rw-r--r--src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4File.h77
-rw-r--r--src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4FileByteStream.h56
-rw-r--r--src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4FileCopier.cpp7
-rw-r--r--src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4FileCopier.h3
-rw-r--r--src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4FileWriter.cpp74
-rw-r--r--src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4FileWriter.h14
-rw-r--r--src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4FragmentSampleTable.cpp199
-rw-r--r--src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4FragmentSampleTable.h37
-rw-r--r--src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4FrmaAtom.cpp4
-rw-r--r--src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4FrmaAtom.h12
-rw-r--r--src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4FtabAtom.cpp28
-rw-r--r--src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4FtabAtom.h50
-rw-r--r--src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4FtypAtom.cpp26
-rw-r--r--src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4FtypAtom.h24
-rw-r--r--src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4GrpiAtom.cpp22
-rw-r--r--src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4GrpiAtom.h32
-rw-r--r--src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4HdlrAtom.cpp49
-rw-r--r--src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4HdlrAtom.h34
-rw-r--r--src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4HintTrackReader.cpp128
-rw-r--r--src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4HintTrackReader.h21
-rw-r--r--src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4HmhdAtom.cpp18
-rw-r--r--src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4HmhdAtom.h4
-rw-r--r--src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4IkmsAtom.cpp42
-rw-r--r--src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4IkmsAtom.h17
-rw-r--r--src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4Interfaces.h2
-rw-r--r--src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4IodsAtom.cpp22
-rw-r--r--src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4IodsAtom.h11
-rw-r--r--src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4Ipmp.cpp97
-rw-r--r--src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4Ipmp.h83
-rw-r--r--src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4IproAtom.cpp26
-rw-r--r--src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4IproAtom.h2
-rw-r--r--src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4IsfmAtom.cpp24
-rw-r--r--src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4IsfmAtom.h17
-rw-r--r--src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4IsltAtom.cpp7
-rw-r--r--src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4IsltAtom.h10
-rw-r--r--src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4IsmaCryp.cpp244
-rw-r--r--src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4IsmaCryp.h38
-rw-r--r--src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4LinearReader.cpp143
-rw-r--r--src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4LinearReader.h50
-rw-r--r--src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4List.h203
-rw-r--r--src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4Marlin.cpp747
-rw-r--r--src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4Marlin.h61
-rw-r--r--src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4MdhdAtom.cpp71
-rw-r--r--src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4MdhdAtom.h29
-rw-r--r--src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4MehdAtom.cpp27
-rw-r--r--src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4MehdAtom.h16
-rw-r--r--src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4MfhdAtom.cpp10
-rw-r--r--src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4MfhdAtom.h14
-rw-r--r--src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4MfroAtom.cpp18
-rw-r--r--src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4MfroAtom.h13
-rw-r--r--src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4MoovAtom.cpp192
-rw-r--r--src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4MoovAtom.h13
-rw-r--r--src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4Movie.cpp89
-rw-r--r--src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4Movie.h22
-rw-r--r--src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4MovieFragment.cpp88
-rw-r--r--src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4MovieFragment.h19
-rw-r--r--src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4Mpeg2Ts.cpp545
-rw-r--r--src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4Mpeg2Ts.h59
-rw-r--r--src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4MvhdAtom.cpp65
-rw-r--r--src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4MvhdAtom.h24
-rw-r--r--src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4NmhdAtom.cpp8
-rw-r--r--src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4NmhdAtom.h4
-rw-r--r--src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4ObjectDescriptor.cpp204
-rw-r--r--src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4ObjectDescriptor.h102
-rw-r--r--src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4OdafAtom.cpp18
-rw-r--r--src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4OdafAtom.h17
-rw-r--r--src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4OddaAtom.cpp42
-rw-r--r--src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4OddaAtom.h18
-rw-r--r--src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4OdheAtom.cpp21
-rw-r--r--src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4OdheAtom.h19
-rw-r--r--src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4OhdrAtom.cpp59
-rw-r--r--src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4OhdrAtom.h50
-rw-r--r--src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4OmaDcf.cpp716
-rw-r--r--src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4OmaDcf.h62
-rw-r--r--src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4Piff.cpp837
-rw-r--r--src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4Piff.h116
-rw-r--r--src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4Processor.cpp305
-rw-r--r--src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4Processor.h101
-rw-r--r--src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4Protection.cpp890
-rw-r--r--src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4Protection.h106
-rw-r--r--src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4Results.cpp75
-rw-r--r--src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4RtpAtom.cpp17
-rw-r--r--src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4RtpAtom.h10
-rw-r--r--src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4RtpHint.cpp212
-rw-r--r--src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4RtpHint.h140
-rw-r--r--src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4SLConfigDescriptor.cpp2
-rw-r--r--src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4SLConfigDescriptor.h4
-rw-r--r--src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4Sample.cpp12
-rw-r--r--src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4Sample.h100
-rw-r--r--src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4SampleDescription.cpp505
-rw-r--r--src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4SampleDescription.h211
-rw-r--r--src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4SampleEntry.cpp669
-rw-r--r--src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4SampleEntry.h205
-rw-r--r--src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4SampleSource.cpp24
-rw-r--r--src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4SampleSource.h24
-rw-r--r--src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4SampleTable.cpp97
-rw-r--r--src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4SampleTable.h13
-rw-r--r--src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4SchmAtom.cpp88
-rw-r--r--src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4SchmAtom.h23
-rw-r--r--src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4SdpAtom.cpp17
-rw-r--r--src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4SdpAtom.h7
-rw-r--r--src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4SmhdAtom.cpp14
-rw-r--r--src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4SmhdAtom.h4
-rw-r--r--src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4StcoAtom.cpp57
-rw-r--r--src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4StcoAtom.h16
-rw-r--r--src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4String.cpp60
-rw-r--r--src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4String.h30
-rw-r--r--src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4StscAtom.cpp119
-rw-r--r--src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4StscAtom.h25
-rw-r--r--src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4StsdAtom.cpp52
-rw-r--r--src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4StsdAtom.h2
-rw-r--r--src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4StssAtom.cpp42
-rw-r--r--src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4StssAtom.h13
-rw-r--r--src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4StszAtom.cpp79
-rw-r--r--src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4StszAtom.h16
-rw-r--r--src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4SttsAtom.cpp86
-rw-r--r--src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4SttsAtom.h28
-rw-r--r--src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4SyntheticSampleTable.cpp123
-rw-r--r--src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4SyntheticSampleTable.h41
-rw-r--r--src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4TfhdAtom.cpp89
-rw-r--r--src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4TfhdAtom.h66
-rw-r--r--src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4TfraAtom.cpp350
-rw-r--r--src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4TfraAtom.h16
-rw-r--r--src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4TimsAtom.cpp4
-rw-r--r--src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4TimsAtom.h10
-rw-r--r--src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4TkhdAtom.cpp70
-rw-r--r--src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4TkhdAtom.h51
-rw-r--r--src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4Track.cpp199
-rw-r--r--src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4Track.h58
-rw-r--r--src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4TrakAtom.cpp166
-rw-r--r--src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4TrakAtom.h22
-rw-r--r--src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4TrefTypeAtom.cpp24
-rw-r--r--src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4TrefTypeAtom.h18
-rw-r--r--src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4TrexAtom.cpp10
-rw-r--r--src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4TrexAtom.h41
-rw-r--r--src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4TrunAtom.cpp132
-rw-r--r--src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4TrunAtom.h28
-rw-r--r--src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4Types.h29
-rw-r--r--src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4UrlAtom.cpp41
-rw-r--r--src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4UrlAtom.h4
-rw-r--r--src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4Utils.cpp177
-rw-r--r--src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4Utils.h61
-rw-r--r--src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4UuidAtom.cpp82
-rw-r--r--src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4UuidAtom.h21
-rw-r--r--src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4VmhdAtom.cpp16
-rw-r--r--src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4VmhdAtom.h4
-rw-r--r--src/filters/parser/MP4Splitter/AP4/Source/Crypto/Ap4AesBlockCipher.cpp614
-rw-r--r--src/filters/parser/MP4Splitter/AP4/Source/Crypto/Ap4AesBlockCipher.h22
-rw-r--r--src/filters/parser/MP4Splitter/AP4/Source/Crypto/Ap4Hmac.cpp296
-rw-r--r--src/filters/parser/MP4Splitter/AP4/Source/Crypto/Ap4Hmac.h9
-rw-r--r--src/filters/parser/MP4Splitter/AP4/Source/Crypto/Ap4KeyWrap.cpp78
-rw-r--r--src/filters/parser/MP4Splitter/AP4/Source/Crypto/Ap4KeyWrap.h6
-rw-r--r--src/filters/parser/MP4Splitter/AP4/Source/Crypto/Ap4StreamCipher.cpp232
-rw-r--r--src/filters/parser/MP4Splitter/AP4/Source/Crypto/Ap4StreamCipher.h49
-rw-r--r--src/filters/parser/MP4Splitter/AP4/Source/MetaData/Ap4MetaData.cpp1021
-rw-r--r--src/filters/parser/MP4Splitter/AP4/Source/MetaData/Ap4MetaData.h337
-rw-r--r--src/filters/parser/MP4Splitter/Ap4AsyncReaderStream.cpp64
-rw-r--r--src/filters/parser/MP4Splitter/Ap4AsyncReaderStream.h22
-rw-r--r--src/filters/parser/MP4Splitter/MP4Splitter.cpp2806
-rw-r--r--src/filters/parser/MP4Splitter/MP4Splitter.h60
-rw-r--r--src/filters/parser/MP4Splitter/MP4SplitterFile.cpp32
-rw-r--r--src/filters/parser/MP4Splitter/MP4SplitterFile.h10
-rw-r--r--src/filters/parser/MP4Splitter/resource.h2
-rw-r--r--src/filters/parser/MP4Splitter/stdafx.cpp8
-rw-r--r--src/filters/parser/MP4Splitter/stdafx.h8
-rw-r--r--src/filters/parser/MatroskaSplitter/MatroskaFile.cpp1959
-rw-r--r--src/filters/parser/MatroskaSplitter/MatroskaFile.h1013
-rw-r--r--src/filters/parser/MatroskaSplitter/MatroskaSplitter.cpp2296
-rw-r--r--src/filters/parser/MatroskaSplitter/MatroskaSplitter.h116
-rw-r--r--src/filters/parser/MatroskaSplitter/resource.h2
-rw-r--r--src/filters/parser/MatroskaSplitter/stdafx.cpp8
-rw-r--r--src/filters/parser/MatroskaSplitter/stdafx.h8
-rw-r--r--src/filters/parser/MpaSplitter/MpaSplitter.cpp172
-rw-r--r--src/filters/parser/MpaSplitter/MpaSplitter.h28
-rw-r--r--src/filters/parser/MpaSplitter/MpaSplitterFile.cpp598
-rw-r--r--src/filters/parser/MpaSplitter/MpaSplitterFile.h56
-rw-r--r--src/filters/parser/MpaSplitter/resource.h2
-rw-r--r--src/filters/parser/MpaSplitter/stdafx.cpp8
-rw-r--r--src/filters/parser/MpaSplitter/stdafx.h8
-rw-r--r--src/filters/parser/MpegSplitter/MpegSplitter.cpp2790
-rw-r--r--src/filters/parser/MpegSplitter/MpegSplitter.h78
-rw-r--r--src/filters/parser/MpegSplitter/MpegSplitterFile.cpp1400
-rw-r--r--src/filters/parser/MpegSplitter/MpegSplitterFile.h215
-rw-r--r--src/filters/parser/MpegSplitter/resource.h2
-rw-r--r--src/filters/parser/MpegSplitter/stdafx.cpp8
-rw-r--r--src/filters/parser/MpegSplitter/stdafx.h8
-rw-r--r--src/filters/parser/NutSplitter/NutFile.cpp266
-rw-r--r--src/filters/parser/NutSplitter/NutFile.h210
-rw-r--r--src/filters/parser/NutSplitter/NutSplitter.cpp486
-rw-r--r--src/filters/parser/NutSplitter/NutSplitter.h30
-rw-r--r--src/filters/parser/NutSplitter/resource.h2
-rw-r--r--src/filters/parser/NutSplitter/stdafx.cpp8
-rw-r--r--src/filters/parser/NutSplitter/stdafx.h8
-rw-r--r--src/filters/parser/OggSplitter/OggFile.cpp97
-rw-r--r--src/filters/parser/OggSplitter/OggFile.h80
-rw-r--r--src/filters/parser/OggSplitter/OggSplitter.cpp1960
-rw-r--r--src/filters/parser/OggSplitter/OggSplitter.h179
-rw-r--r--src/filters/parser/OggSplitter/resource.h2
-rw-r--r--src/filters/parser/OggSplitter/stdafx.cpp8
-rw-r--r--src/filters/parser/OggSplitter/stdafx.h8
-rw-r--r--src/filters/parser/RealMediaSplitter/RealMediaSplitter.cpp3980
-rw-r--r--src/filters/parser/RealMediaSplitter/RealMediaSplitter.h452
-rw-r--r--src/filters/parser/RealMediaSplitter/resource.h2
-rw-r--r--src/filters/parser/RealMediaSplitter/stdafx.cpp8
-rw-r--r--src/filters/parser/RealMediaSplitter/stdafx.h8
-rw-r--r--src/filters/parser/RoQSplitter/RoQSplitter.cpp1546
-rw-r--r--src/filters/parser/RoQSplitter/RoQSplitter.h122
-rw-r--r--src/filters/parser/RoQSplitter/resource.h2
-rw-r--r--src/filters/parser/RoQSplitter/stdafx.cpp8
-rw-r--r--src/filters/parser/RoQSplitter/stdafx.h8
-rw-r--r--src/filters/parser/SSFSplitter/SSFSplitter.cpp316
-rw-r--r--src/filters/parser/SSFSplitter/SSFSplitter.h34
-rw-r--r--src/filters/parser/SSFSplitter/resource.h2
-rw-r--r--src/filters/parser/SSFSplitter/stdafx.cpp8
-rw-r--r--src/filters/parser/SSFSplitter/stdafx.h8
-rw-r--r--src/filters/parser/StreamDriveThru/StreamDriveThru.cpp534
-rw-r--r--src/filters/parser/StreamDriveThru/StreamDriveThru.h108
-rw-r--r--src/filters/parser/StreamDriveThru/resource.h2
-rw-r--r--src/filters/parser/StreamDriveThru/stdafx.cpp8
-rw-r--r--src/filters/parser/StreamDriveThru/stdafx.h8
439 files changed, 44460 insertions, 51300 deletions
diff --git a/src/filters/parser/AviSplitter/AviFile.cpp b/src/filters/parser/AviSplitter/AviFile.cpp
index 95bf6bea3..7b610a505 100644
--- a/src/filters/parser/AviSplitter/AviFile.cpp
+++ b/src/filters/parser/AviSplitter/AviFile.cpp
@@ -6,618 +6,607 @@
//
CAviFile::CAviFile(IAsyncReader* pAsyncReader, HRESULT& hr)
- : CBaseSplitterFile(pAsyncReader, hr)
+ : CBaseSplitterFile(pAsyncReader, hr)
{
- if(FAILED(hr)) return;
- m_isamv = false;
- hr = Init();
+ if(FAILED(hr)) return;
+ m_isamv = false;
+ hr = Init();
}
-template<typename T>
+template<typename T>
HRESULT CAviFile::Read(T& var, int offset)
{
- memset(&var, 0, sizeof(var));
- HRESULT hr = ByteRead((BYTE*)&var + offset, sizeof(var) - offset);
- return hr;
+ memset(&var, 0, sizeof(var));
+ HRESULT hr = ByteRead((BYTE*)&var + offset, sizeof(var) - offset);
+ return hr;
}
HRESULT CAviFile::Init()
{
- Seek(0);
- DWORD dw[3];
- if(S_OK != Read(dw) || dw[0] != FCC('RIFF') || (dw[2] != FCC('AVI ') && dw[2] != FCC('AVIX') && dw[2] != FCC('AMV ')))
- return E_FAIL;
-
- m_isamv = (dw[2] == FCC('AMV '));
- Seek(0);
- HRESULT hr = Parse(0, GetLength());
- if(m_movis.GetCount() == 0) // FAILED(hr) is allowed as long as there was a movi chunk found
- return E_FAIL;
-
- if(m_avih.dwStreams == 0 && m_strms.GetCount() > 0)
- m_avih.dwStreams = m_strms.GetCount();
-
- if(m_avih.dwStreams != m_strms.GetCount())
- return E_FAIL;
-
- for(int i = 0; i < (int)m_avih.dwStreams; i++)
- {
- strm_t* s = m_strms[i];
- if(s->strh.fccType != FCC('auds')) continue;
- WAVEFORMATEX* wfe = (WAVEFORMATEX*)s->strf.GetData();
- if(wfe->wFormatTag == 0x55 && wfe->nBlockAlign == 1152
- && s->strh.dwScale == 1 && s->strh.dwRate != wfe->nSamplesPerSec)
- {
- // correcting encoder bugs...
- s->strh.dwScale = 1152;
- s->strh.dwRate = wfe->nSamplesPerSec;
- }
- }
-
- if(!m_isamv && (FAILED(BuildIndex())))
- EmptyIndex();
-
- return S_OK;
+ Seek(0);
+ DWORD dw[3];
+ if(S_OK != Read(dw) || dw[0] != FCC('RIFF') || (dw[2] != FCC('AVI ') && dw[2] != FCC('AVIX') && dw[2] != FCC('AMV ')))
+ return E_FAIL;
+
+ m_isamv = (dw[2] == FCC('AMV '));
+ Seek(0);
+ HRESULT hr = Parse(0, GetLength());
+ if(m_movis.GetCount() == 0) // FAILED(hr) is allowed as long as there was a movi chunk found
+ return E_FAIL;
+
+ if(m_avih.dwStreams == 0 && m_strms.GetCount() > 0)
+ m_avih.dwStreams = m_strms.GetCount();
+
+ if(m_avih.dwStreams != m_strms.GetCount())
+ return E_FAIL;
+
+ for(int i = 0; i < (int)m_avih.dwStreams; i++)
+ {
+ strm_t* s = m_strms[i];
+ if(s->strh.fccType != FCC('auds')) continue;
+ WAVEFORMATEX* wfe = (WAVEFORMATEX*)s->strf.GetData();
+ if(wfe->wFormatTag == 0x55 && wfe->nBlockAlign == 1152
+ && s->strh.dwScale == 1 && s->strh.dwRate != wfe->nSamplesPerSec)
+ {
+ // correcting encoder bugs...
+ s->strh.dwScale = 1152;
+ s->strh.dwRate = wfe->nSamplesPerSec;
+ }
+ }
+
+ if (!m_isamv && (FAILED(BuildIndex())))
+ EmptyIndex();
+
+ return S_OK;
}
HRESULT CAviFile::BuildAMVIndex()
{
- strm_t::chunk NewChunk;
- ULONG ulType;
- ULONG ulSize;
-
- memset(&NewChunk, 0, sizeof(strm_t::chunk));
- while((Read(ulType) == S_OK) && (Read(ulSize) == S_OK))
- {
- switch(ulType)
- {
- case FCC('00dc'): // 01bw : JPeg
- NewChunk.size = ulSize;
- NewChunk.filepos = GetPos();
- NewChunk.orgsize = ulSize;
- NewChunk.fKeyFrame = true;
- m_strms[0]->cs.Add(NewChunk);
- break;
- case FCC('01wb') : // 00dc : Audio
- NewChunk.size = ulSize;
- NewChunk.orgsize = ulSize;
- NewChunk.fKeyFrame = true;
- NewChunk.filepos = GetPos();
- m_strms[1]->cs.Add(NewChunk);
- break;
- }
- Seek(GetPos() + ulSize);
- }
-
- TRACE("Video packet : %d Audio packet :%d\n", m_strms[0]->cs.GetCount(), m_strms[1]->cs.GetCount());
- return S_OK;
+ strm_t::chunk NewChunk;
+ ULONG ulType;
+ ULONG ulSize;
+
+ memset (&NewChunk, 0, sizeof(strm_t::chunk));
+ while((Read(ulType) == S_OK) && (Read(ulSize) == S_OK))
+ {
+ switch (ulType)
+ {
+ case FCC('00dc'): // 01bw : JPeg
+ NewChunk.size = ulSize;
+ NewChunk.filepos = GetPos();
+ NewChunk.orgsize = ulSize;
+ NewChunk.fKeyFrame = true;
+ m_strms[0]->cs.Add (NewChunk);
+ break;
+ case FCC('01wb') : // 00dc : Audio
+ NewChunk.size = ulSize;
+ NewChunk.orgsize = ulSize;
+ NewChunk.fKeyFrame = true;
+ NewChunk.filepos = GetPos();
+ m_strms[1]->cs.Add (NewChunk);
+ break;
+ }
+ Seek(GetPos() + ulSize);
+ }
+
+ TRACE ("Video packet : %d Audio packet :%d\n", m_strms[0]->cs.GetCount(), m_strms[1]->cs.GetCount());
+ return S_OK;
}
HRESULT CAviFile::Parse(DWORD parentid, __int64 end)
{
- HRESULT hr = S_OK;
-
- CAutoPtr<strm_t> strm;
-
- while(S_OK == hr && GetPos() < end)
- {
- UINT64 pos = GetPos();
-
- DWORD id = 0, size;
- if(S_OK != Read(id) || id == 0)
- return E_FAIL;
-
- if(id == FCC('RIFF') || id == FCC('LIST'))
- {
- if(S_OK != Read(size) || S_OK != Read(id))
- return E_FAIL;
-
- if(m_isamv) size = end - GetPos() - 8; // No size set in AVM : guess end of file...
- size += (size & 1) + 8;
-
- TRACE(_T("CAviFile::Parse(..): LIST '%c%c%c%c'\n"),
- TCHAR((id >> 0) & 0xff),
- TCHAR((id >> 8) & 0xff),
- TCHAR((id >> 16) & 0xff),
- TCHAR((id >> 24) & 0xff));
-
- if(id == FCC('movi'))
- {
- m_movis.AddTail(pos);
- if(m_isamv) BuildAMVIndex();
- }
- else
- {
- hr = Parse(id, pos + size);
- }
- }
- else
- {
- if(S_OK != Read(size))
- return E_FAIL;
-
- TRACE(_T("CAviFile::Parse(..): '%c%c%c%c'\n"),
- TCHAR((id >> 0) & 0xff),
- TCHAR((id >> 8) & 0xff),
- TCHAR((id >> 16) & 0xff),
- TCHAR((id >> 24) & 0xff));
-
- if(parentid == FCC('INFO') && size > 0)
- {
- switch(id)
- {
- case FCC('IARL'): // Archival Location. Indicates where the subject of the file is archived.
- case FCC('IART'): // Artist. Lists the artist of the original subject of the file; for example, “Michaelangelo.”
- case FCC('ICMS'): // Commissioned. Lists the name of the person or organization that commissioned the subject of the file; for example, “Pope Julian II.”
- case FCC('ICMT'): // Comments. Provides general comments about the file or the subject of the file. If the comment is several sentences long, end each sentence with a period. Do not include new-line characters.
- case FCC('ICOP'): // Copyright. Records the copyright information for the file; for example, “Copyright Encyclopedia International 1991.” If there are multiple copyrights, separate them by a semicolon followed by a space.
- case FCC('ICRD'): // Creation date. Specifies the date the subject of the file was created. List dates in year-month-day format, padding one-digit months and days with a zero on the left; for example, “1553-05-03” for May 3, 1553.
- case FCC('ICRP'): // Cropped. Describes whether an image has been cropped and, if so, how it was cropped; for example, “lower-right corner.”
- case FCC('IDIM'): // Dimensions. Specifies the size of the original subject of the file; for example, “8.5 in h, 11 in w.”
- case FCC('IDPI'): // Dots Per Inch. Stores dots per inch setting of the digitizer used to produce the file, such as “300.”
- case FCC('IENG'): // Engineer. Stores the name of the engineer who worked on the file. If there are multiple engineers, separate the names by a semicolon and a blank; for example, “Smith, John; Adams, Joe.”
- case FCC('IGNR'): // Genre. Describes the original work, such as “landscape,” “portrait,” “still life,” etc.
- case FCC('IKEY'): // Keywords. Provides a list of keywords that refer to the file or subject of the file. Separate multiple keywords with a semicolon and a blank; for example, “Seattle; aerial view; scenery.”
- case FCC('ILGT'): // Lightness. Describes the changes in lightness settings on the digitizer required to produce the file. Note that the format of this information depends on hardware used.
- case FCC('IMED'): // Medium. Describes the original subject of the file, such as “computer image,” “drawing,” “lithograph,” and so on.
- case FCC('INAM'): // Name. Stores the title of the subject of the file, such as “Seattle From Above.”
- case FCC('IPLT'): // Palette Setting. Specifies the number of colors requested when digitizing an image, such as “256.”
- case FCC('IPRD'): // Product. Specifies the name of the title the file was originally intended for, such as “Encyclopedia of Pacific Northwest Geography.”
- case FCC('ISBJ'): // Subject. Describes the contents of the file, such as “Aerial view of Seattle.”
- case FCC('ISFT'): // Software. Identifies the name of the software package used to create the file, such as “Microsoft WaveEdit.”
- case FCC('ISHP'): // Sharpness. Identifies the changes in sharpness for the digitizer required to produce the file (the format depends on the hardware used).
- case FCC('ISRC'): // Source. Identifies the name of the person or organization who supplied the original subject of the file; for example, “Trey Research.”
- case FCC('ISRF'): // Source Form. Identifies the original form of the material that was digitized, such as “slide,” “paper,” “map,” and so on. This is not necessarily the same as IMED.
- case FCC('ITCH'): // Technician. Identifies the technician who digitized the subject file; for example, “Smith, John.”
- {
- CStringA str;
- if(S_OK != ByteRead((BYTE*)str.GetBufferSetLength(size), size)) return E_FAIL;
- m_info[id] = str;
- break;
- }
- }
- }
-
- switch(id)
- {
- case FCC('amvh'):
- case FCC('avih'):
- m_avih.fcc = id;
- m_avih.cb = size;
- if(S_OK != Read(m_avih, 8)) return E_FAIL;
- break;
- case FCC('strh'):
- if(!strm) strm.Attach(DNew strm_t());
- strm->strh.fcc = FCC('strh');
- strm->strh.cb = size;
- if(S_OK != Read(strm->strh, 8)) return E_FAIL;
- if(m_isamv)
- {
- // First alway video, second always audio
- strm->strh.fccType = m_strms.GetCount() == 0 ? FCC('vids') : FCC('amva');
- strm->strh.dwRate = m_avih.dwReserved[0] * 1000; // dwReserved[0] = fps!
- strm->strh.dwScale = 1000;
- }
- break;
- case FCC('strn'):
- if(S_OK != ByteRead((BYTE*)strm->strn.GetBufferSetLength(size), size)) return E_FAIL;
- break;
- case FCC('strf'):
- if(!strm) strm.Attach(DNew strm_t());
- strm->strf.SetCount(size);
- if(S_OK != ByteRead(strm->strf.GetData(), size)) return E_FAIL;
- if(m_isamv)
- {
- if(strm->strh.fccType == FCC('vids'))
- {
- strm->strf.SetCount(sizeof(BITMAPINFOHEADER));
- BITMAPINFOHEADER* pbmi = &((BITMAPINFO*)strm->strf.GetData())->bmiHeader;
- pbmi->biSize = sizeof(BITMAPINFOHEADER);
- pbmi->biHeight = m_avih.dwHeight;
- pbmi->biWidth = m_avih.dwWidth;
- pbmi->biCompression = FCC('AMVV');
- pbmi->biPlanes = 1;
- pbmi->biBitCount = 24;
- pbmi->biSizeImage = pbmi->biHeight * pbmi->biWidth * (pbmi->biBitCount / 8);
- }
- m_strms.Add(strm);
- }
-
- break;
- case FCC('indx'):
- if(!strm) strm.Attach(DNew strm_t());
- ASSERT(strm->indx == NULL);
- AVISUPERINDEX* pSuperIndex;
- if(size < MAXDWORD - 8)
- {
- // Fix buffer overrun vulnerability : http://www.vulnhunt.com/advisories/CAL-20070912-1_Multiple_vendor_produce_handling_AVI_file_vulnerabilities.txt
- TRY
- {
- pSuperIndex = (AVISUPERINDEX*)DNew unsigned char [(size_t)(size + 8)];
- }
- CATCH(CMemoryException, e)
- {
- pSuperIndex = NULL;
- }
- END_CATCH
- if(pSuperIndex)
- {
- strm->indx.Attach(pSuperIndex);
- strm->indx->fcc = FCC('indx');
- strm->indx->cb = size;
- if(S_OK != ByteRead((BYTE*)(AVISUPERINDEX*)strm->indx + 8, size)) return E_FAIL;
- ASSERT(strm->indx->wLongsPerEntry == 4 && strm->indx->bIndexType == AVI_INDEX_OF_INDEXES);
- }
- }
- break;
- case FCC('dmlh'):
- if(S_OK != Read(m_dmlh)) return E_FAIL;
- break;
- case FCC('vprp'):
+ HRESULT hr = S_OK;
+
+ CAutoPtr<strm_t> strm;
+
+ while(S_OK == hr && GetPos() < end)
+ {
+ UINT64 pos = GetPos();
+
+ DWORD id = 0, size;
+ if(S_OK != Read(id) || id == 0)
+ return E_FAIL;
+
+ if(id == FCC('RIFF') || id == FCC('LIST'))
+ {
+ if(S_OK != Read(size) || S_OK != Read(id))
+ return E_FAIL;
+
+ if (m_isamv) size = end - GetPos() - 8; // No size set in AVM : guess end of file...
+ size += (size&1) + 8;
+
+ TRACE(_T("CAviFile::Parse(..): LIST '%c%c%c%c'\n"),
+ TCHAR((id>>0)&0xff),
+ TCHAR((id>>8)&0xff),
+ TCHAR((id>>16)&0xff),
+ TCHAR((id>>24)&0xff));
+
+ if(id == FCC('movi'))
+ {
+ m_movis.AddTail(pos);
+ if (m_isamv) BuildAMVIndex();
+ }
+ else
+ {
+ hr = Parse(id, pos + size);
+ }
+ }
+ else
+ {
+ if(S_OK != Read(size))
+ return E_FAIL;
+
+ TRACE(_T("CAviFile::Parse(..): '%c%c%c%c'\n"),
+ TCHAR((id>>0)&0xff),
+ TCHAR((id>>8)&0xff),
+ TCHAR((id>>16)&0xff),
+ TCHAR((id>>24)&0xff));
+
+ if(parentid == FCC('INFO') && size > 0)
+ {
+ switch(id)
+ {
+ case FCC('IARL'): // Archival Location. Indicates where the subject of the file is archived.
+ case FCC('IART'): // Artist. Lists the artist of the original subject of the file; for example, “Michaelangelo.”
+ case FCC('ICMS'): // Commissioned. Lists the name of the person or organization that commissioned the subject of the file; for example, “Pope Julian II.”
+ case FCC('ICMT'): // Comments. Provides general comments about the file or the subject of the file. If the comment is several sentences long, end each sentence with a period. Do not include new-line characters.
+ case FCC('ICOP'): // Copyright. Records the copyright information for the file; for example, “Copyright Encyclopedia International 1991.” If there are multiple copyrights, separate them by a semicolon followed by a space.
+ case FCC('ICRD'): // Creation date. Specifies the date the subject of the file was created. List dates in year-month-day format, padding one-digit months and days with a zero on the left; for example, “1553-05-03” for May 3, 1553.
+ case FCC('ICRP'): // Cropped. Describes whether an image has been cropped and, if so, how it was cropped; for example, “lower-right corner.”
+ case FCC('IDIM'): // Dimensions. Specifies the size of the original subject of the file; for example, “8.5 in h, 11 in w.”
+ case FCC('IDPI'): // Dots Per Inch. Stores dots per inch setting of the digitizer used to produce the file, such as “300.”
+ case FCC('IENG'): // Engineer. Stores the name of the engineer who worked on the file. If there are multiple engineers, separate the names by a semicolon and a blank; for example, “Smith, John; Adams, Joe.”
+ case FCC('IGNR'): // Genre. Describes the original work, such as “landscape,” “portrait,” “still life,” etc.
+ case FCC('IKEY'): // Keywords. Provides a list of keywords that refer to the file or subject of the file. Separate multiple keywords with a semicolon and a blank; for example, “Seattle; aerial view; scenery.”
+ case FCC('ILGT'): // Lightness. Describes the changes in lightness settings on the digitizer required to produce the file. Note that the format of this information depends on hardware used.
+ case FCC('IMED'): // Medium. Describes the original subject of the file, such as “computer image,” “drawing,” “lithograph,” and so on.
+ case FCC('INAM'): // Name. Stores the title of the subject of the file, such as “Seattle From Above.”
+ case FCC('IPLT'): // Palette Setting. Specifies the number of colors requested when digitizing an image, such as “256.”
+ case FCC('IPRD'): // Product. Specifies the name of the title the file was originally intended for, such as “Encyclopedia of Pacific Northwest Geography.”
+ case FCC('ISBJ'): // Subject. Describes the contents of the file, such as “Aerial view of Seattle.”
+ case FCC('ISFT'): // Software. Identifies the name of the software package used to create the file, such as “Microsoft WaveEdit.”
+ case FCC('ISHP'): // Sharpness. Identifies the changes in sharpness for the digitizer required to produce the file (the format depends on the hardware used).
+ case FCC('ISRC'): // Source. Identifies the name of the person or organization who supplied the original subject of the file; for example, “Trey Research.”
+ case FCC('ISRF'): // Source Form. Identifies the original form of the material that was digitized, such as “slide,” “paper,” “map,” and so on. This is not necessarily the same as IMED.
+ case FCC('ITCH'): // Technician. Identifies the technician who digitized the subject file; for example, “Smith, John.”
+ {
+ CStringA str;
+ if(S_OK != ByteRead((BYTE*)str.GetBufferSetLength(size), size)) return E_FAIL;
+ m_info[id] = str;
+ break;
+ }
+ }
+ }
+
+ switch(id)
+ {
+ case FCC('amvh'):
+ case FCC('avih'):
+ m_avih.fcc = id;
+ m_avih.cb = size;
+ if(S_OK != Read(m_avih, 8)) return E_FAIL;
+ break;
+ case FCC('strh'):
+ if(!strm) strm.Attach(DNew strm_t());
+ strm->strh.fcc = FCC('strh');
+ strm->strh.cb = size;
+ if(S_OK != Read(strm->strh, 8)) return E_FAIL;
+ if (m_isamv)
+ {
+ // First alway video, second always audio
+ strm->strh.fccType = m_strms.GetCount() == 0 ? FCC('vids') : FCC('amva');
+ strm->strh.dwRate = m_avih.dwReserved[0]*1000; // dwReserved[0] = fps!
+ strm->strh.dwScale = 1000;
+ }
+ break;
+ case FCC('strn'):
+ if(S_OK != ByteRead((BYTE*)strm->strn.GetBufferSetLength(size), size)) return E_FAIL;
+ break;
+ case FCC('strf'):
+ if(!strm) strm.Attach(DNew strm_t());
+ strm->strf.SetCount(size);
+ if(S_OK != ByteRead(strm->strf.GetData(), size)) return E_FAIL;
+ if (m_isamv)
+ {
+ if (strm->strh.fccType == FCC('vids'))
+ {
+ strm->strf.SetCount(sizeof(BITMAPINFOHEADER));
+ BITMAPINFOHEADER* pbmi = &((BITMAPINFO*)strm->strf.GetData())->bmiHeader;
+ pbmi->biSize = sizeof(BITMAPINFOHEADER);
+ pbmi->biHeight = m_avih.dwHeight;
+ pbmi->biWidth = m_avih.dwWidth;
+ pbmi->biCompression = FCC('AMVV');
+ pbmi->biPlanes = 1;
+ pbmi->biBitCount = 24;
+ pbmi->biSizeImage = pbmi->biHeight * pbmi->biWidth * (pbmi->biBitCount/8);
+ }
+ m_strms.Add(strm);
+ }
+
+ break;
+ case FCC('indx'):
+ if(!strm) strm.Attach(DNew strm_t());
+ ASSERT(strm->indx == NULL);
+ AVISUPERINDEX* pSuperIndex;
+ if (size < MAXDWORD-8)
+ {
+ // Fix buffer overrun vulnerability : http://www.vulnhunt.com/advisories/CAL-20070912-1_Multiple_vendor_produce_handling_AVI_file_vulnerabilities.txt
+ TRY
+ {
+ pSuperIndex = (AVISUPERINDEX*)DNew unsigned char [(size_t)(size + 8)];
+ }
+ CATCH (CMemoryException, e)
+ {
+ pSuperIndex = NULL;
+ }
+ END_CATCH
+ if (pSuperIndex)
+ {
+ strm->indx.Attach(pSuperIndex);
+ strm->indx->fcc = FCC('indx');
+ strm->indx->cb = size;
+ if(S_OK != ByteRead((BYTE*)(AVISUPERINDEX*)strm->indx + 8, size)) return E_FAIL;
+ ASSERT(strm->indx->wLongsPerEntry == 4 && strm->indx->bIndexType == AVI_INDEX_OF_INDEXES);
+ }
+ }
+ break;
+ case FCC('dmlh'):
+ if(S_OK != Read(m_dmlh)) return E_FAIL;
+ break;
+ case FCC('vprp'):
// if(S_OK != Read(m_vprp)) return E_FAIL;
- break;
- case FCC('idx1'):
- ASSERT(m_idx1 == NULL);
- m_idx1.Attach((AVIOLDINDEX*)DNew BYTE[size + 8]);
- m_idx1->fcc = FCC('idx1');
- m_idx1->cb = size;
- if(S_OK != ByteRead((BYTE*)(AVIOLDINDEX*)m_idx1 + 8, size)) return E_FAIL;
- break;
- default :
- TRACE(_T("CAviFile::Parse(..): unknown tag '%c%c%c%c'\n"),
- TCHAR((id >> 0) & 0xff),
- TCHAR((id >> 8) & 0xff),
- TCHAR((id >> 16) & 0xff),
- TCHAR((id >> 24) & 0xff));
- break;
- }
-
- size += (size & 1) + 8;
- }
-
- Seek(pos + size);
- }
-
- if(strm) m_strms.Add(strm);
-
- return hr;
+ break;
+ case FCC('idx1'):
+ ASSERT(m_idx1 == NULL);
+ m_idx1.Attach((AVIOLDINDEX*)DNew BYTE[size + 8]);
+ m_idx1->fcc = FCC('idx1');
+ m_idx1->cb = size;
+ if(S_OK != ByteRead((BYTE*)(AVIOLDINDEX*)m_idx1 + 8, size)) return E_FAIL;
+ break;
+ default :
+ TRACE(_T("CAviFile::Parse(..): unknown tag '%c%c%c%c'\n"),
+ TCHAR((id>>0)&0xff),
+ TCHAR((id>>8)&0xff),
+ TCHAR((id>>16)&0xff),
+ TCHAR((id>>24)&0xff));
+ break;
+ }
+
+ size += (size&1) + 8;
+ }
+
+ Seek(pos + size);
+ }
+
+ if(strm) m_strms.Add(strm);
+
+ return hr;
}
REFERENCE_TIME CAviFile::GetTotalTime()
{
- REFERENCE_TIME t = 0/*10i64*m_avih.dwMicroSecPerFrame*m_avih.dwTotalFrames*/;
+ REFERENCE_TIME t = 0/*10i64*m_avih.dwMicroSecPerFrame*m_avih.dwTotalFrames*/;
- for(int i = 0; i < (int)m_avih.dwStreams; i++)
- {
- strm_t* s = m_strms[i];
- REFERENCE_TIME t2 = s->GetRefTime(s->cs.GetCount(), s->totalsize);
- t = max(t, t2);
- }
+ for(int i = 0; i < (int)m_avih.dwStreams; i++)
+ {
+ strm_t* s = m_strms[i];
+ REFERENCE_TIME t2 = s->GetRefTime(s->cs.GetCount(), s->totalsize);
+ t = max(t, t2);
+ }
- if(t == 0) t = 10i64 * m_avih.dwMicroSecPerFrame * m_avih.dwTotalFrames;
+ if(t == 0) t = 10i64*m_avih.dwMicroSecPerFrame*m_avih.dwTotalFrames;
- return(t);
+ return(t);
}
HRESULT CAviFile::BuildIndex()
{
- EmptyIndex();
-
- int nSuperIndexes = 0;
-
- for(int i = 0; i < (int)m_avih.dwStreams; i++)
- {
- strm_t* s = m_strms[i];
- if(s->indx && s->indx->nEntriesInUse > 0) nSuperIndexes++;
- }
-
- if(nSuperIndexes == m_avih.dwStreams)
- {
- for(int i = 0; i < (int)m_avih.dwStreams; i++)
- {
- strm_t* s = m_strms[i];
-
- AVISUPERINDEX* idx = (AVISUPERINDEX*)s->indx;
-
- DWORD nEntriesInUse = 0;
-
- for(int j = 0; j < (int)idx->nEntriesInUse; j++)
- {
- Seek(idx->aIndex[j].qwOffset);
-
- AVISTDINDEX stdidx;
- if(S_OK != ByteRead((BYTE*)&stdidx, FIELD_OFFSET(AVISTDINDEX, aIndex)))
- {
- EmptyIndex();
- return E_FAIL;
- }
-
- nEntriesInUse += stdidx.nEntriesInUse;
- }
-
- s->cs.SetCount(nEntriesInUse);
-
- DWORD frame = 0;
- UINT64 size = 0;
-
- for(int j = 0; j < (int)idx->nEntriesInUse; j++)
- {
- Seek(idx->aIndex[j].qwOffset);
-
- CAutoPtr<AVISTDINDEX> p((AVISTDINDEX*)DNew BYTE[idx->aIndex[j].dwSize]);
- if(!p || S_OK != ByteRead((BYTE*)(AVISTDINDEX*)p, idx->aIndex[j].dwSize))
- {
- EmptyIndex();
- return E_FAIL;
- }
-
- for(int k = 0, l = 0; k < (int)p->nEntriesInUse; k++)
- {
- s->cs[frame].size = size;
- s->cs[frame].filepos = p->qwBaseOffset + p->aIndex[k].dwOffset;
- s->cs[frame].fKeyFrame = !(p->aIndex[k].dwSize & AVISTDINDEX_DELTAFRAME)
- || s->strh.fccType == FCC('auds');
- s->cs[frame].fChunkHdr = false;
- s->cs[frame].orgsize = p->aIndex[k].dwSize & AVISTDINDEX_SIZEMASK;
-
- if(m_idx1)
- {
- s->cs[frame].filepos -= 8;
- s->cs[frame].fChunkHdr = true;
- }
-
- frame++;
- size += s->GetChunkSize(p->aIndex[k].dwSize & AVISTDINDEX_SIZEMASK);
- }
- }
-
- s->totalsize = size;
- }
- }
- else if(AVIOLDINDEX* idx = m_idx1)
- {
- int len = idx->cb / sizeof(idx->aIndex[0]);
-
- UINT64 offset = m_movis.GetHead() + 8;
-
- for(int i = 0; i < (int)m_avih.dwStreams; i++)
- {
- strm_t* s = m_strms[i];
-
- int nFrames = 0;
-
- for(int j = 0; j < len; j++)
- {
- if(TRACKNUM(idx->aIndex[j].dwChunkId) == i)
- nFrames++;
- }
-
- s->cs.SetCount(nFrames);
-
- DWORD frame = 0;
- UINT64 size = 0;
-
- for(int j = 0, k = 0; j < len; j++)
- {
- DWORD TrackNumber = TRACKNUM(idx->aIndex[j].dwChunkId);
-
- if(TrackNumber == i)
- {
- if(j == 0 && idx->aIndex[j].dwOffset > offset)
- {
- DWORD id;
- Seek(offset + idx->aIndex[j].dwOffset);
- Read(id);
- if(id != idx->aIndex[j].dwChunkId)
- {
- TRACE(_T("WARNING: CAviFile::Init() detected absolute chunk addressing in \'idx1\'"));
- offset = 0;
- }
- }
-
- s->cs[frame].size = size;
- s->cs[frame].filepos = offset + idx->aIndex[j].dwOffset;
- s->cs[frame].fKeyFrame = !!(idx->aIndex[j].dwFlags & AVIIF_KEYFRAME)
- || s->strh.fccType == FCC('auds') // FIXME: some audio index is without any kf flag
- || frame == 0; // grrr
- s->cs[frame].fChunkHdr = j == len - 1 || idx->aIndex[j].dwOffset != idx->aIndex[j+1].dwOffset;
- s->cs[frame].orgsize = idx->aIndex[j].dwSize;
-
- frame++;
- size += s->GetChunkSize(idx->aIndex[j].dwSize);
- }
- }
-
- s->totalsize = size;
- }
- }
-
- m_idx1.Free();
- for(int i = 0; i < (int)m_avih.dwStreams; i++)
- m_strms[i]->indx.Free();
-
- return S_OK;
+ EmptyIndex();
+
+ int nSuperIndexes = 0;
+
+ for(int i = 0; i < (int)m_avih.dwStreams; i++)
+ {
+ strm_t* s = m_strms[i];
+ if(s->indx && s->indx->nEntriesInUse > 0) nSuperIndexes++;
+ }
+
+ if(nSuperIndexes == m_avih.dwStreams)
+ {
+ for(int i = 0; i < (int)m_avih.dwStreams; i++)
+ {
+ strm_t* s = m_strms[i];
+
+ AVISUPERINDEX* idx = (AVISUPERINDEX*)s->indx;
+
+ DWORD nEntriesInUse = 0;
+
+ for(int j = 0; j < (int)idx->nEntriesInUse; j++)
+ {
+ Seek(idx->aIndex[j].qwOffset);
+
+ AVISTDINDEX stdidx;
+ if(S_OK != ByteRead((BYTE*)&stdidx, FIELD_OFFSET(AVISTDINDEX, aIndex)))
+ {
+ EmptyIndex();
+ return E_FAIL;
+ }
+
+ nEntriesInUse += stdidx.nEntriesInUse;
+ }
+
+ s->cs.SetCount(nEntriesInUse);
+
+ DWORD frame = 0;
+ UINT64 size = 0;
+
+ for(int j = 0; j < (int)idx->nEntriesInUse; j++)
+ {
+ Seek(idx->aIndex[j].qwOffset);
+
+ CAutoPtr<AVISTDINDEX> p((AVISTDINDEX*)DNew BYTE[idx->aIndex[j].dwSize]);
+ if(!p || S_OK != ByteRead((BYTE*)(AVISTDINDEX*)p, idx->aIndex[j].dwSize))
+ {
+ EmptyIndex();
+ return E_FAIL;
+ }
+
+ for(int k = 0, l = 0; k < (int)p->nEntriesInUse; k++)
+ {
+ s->cs[frame].size = size;
+ s->cs[frame].filepos = p->qwBaseOffset + p->aIndex[k].dwOffset;
+ s->cs[frame].fKeyFrame = !(p->aIndex[k].dwSize&AVISTDINDEX_DELTAFRAME)
+ || s->strh.fccType == FCC('auds');
+ s->cs[frame].fChunkHdr = false;
+ s->cs[frame].orgsize = p->aIndex[k].dwSize&AVISTDINDEX_SIZEMASK;
+
+ if(m_idx1)
+ {
+ s->cs[frame].filepos -= 8;
+ s->cs[frame].fChunkHdr = true;
+ }
+
+ frame++;
+ size += s->GetChunkSize(p->aIndex[k].dwSize&AVISTDINDEX_SIZEMASK);
+ }
+ }
+
+ s->totalsize = size;
+ }
+ }
+ else if(AVIOLDINDEX* idx = m_idx1)
+ {
+ int len = idx->cb/sizeof(idx->aIndex[0]);
+
+ UINT64 offset = m_movis.GetHead() + 8;
+
+ for(int i = 0; i < (int)m_avih.dwStreams; i++)
+ {
+ strm_t* s = m_strms[i];
+
+ int nFrames = 0;
+
+ for(int j = 0; j < len; j++)
+ {
+ if(TRACKNUM(idx->aIndex[j].dwChunkId) == i)
+ nFrames++;
+ }
+
+ s->cs.SetCount(nFrames);
+
+ DWORD frame = 0;
+ UINT64 size = 0;
+
+ for(int j = 0, k = 0; j < len; j++)
+ {
+ DWORD TrackNumber = TRACKNUM(idx->aIndex[j].dwChunkId);
+
+ if(TrackNumber == i)
+ {
+ if(j == 0 && idx->aIndex[j].dwOffset > offset)
+ {
+ DWORD id;
+ Seek(offset + idx->aIndex[j].dwOffset);
+ Read(id);
+ if(id != idx->aIndex[j].dwChunkId)
+ {
+ TRACE(_T("WARNING: CAviFile::Init() detected absolute chunk addressing in \'idx1\'"));
+ offset = 0;
+ }
+ }
+
+ s->cs[frame].size = size;
+ s->cs[frame].filepos = offset + idx->aIndex[j].dwOffset;
+ s->cs[frame].fKeyFrame = !!(idx->aIndex[j].dwFlags&AVIIF_KEYFRAME)
+ || s->strh.fccType == FCC('auds') // FIXME: some audio index is without any kf flag
+ || frame == 0; // grrr
+ s->cs[frame].fChunkHdr = j == len-1 || idx->aIndex[j].dwOffset != idx->aIndex[j+1].dwOffset;
+ s->cs[frame].orgsize = idx->aIndex[j].dwSize;
+
+ frame++;
+ size += s->GetChunkSize(idx->aIndex[j].dwSize);
+ }
+ }
+
+ s->totalsize = size;
+ }
+ }
+
+ m_idx1.Free();
+ for(int i = 0; i < (int)m_avih.dwStreams; i++)
+ m_strms[i]->indx.Free();
+
+ return S_OK;
}
void CAviFile::EmptyIndex()
{
- for(int i = 0; i < (int)m_avih.dwStreams; i++)
- {
- strm_t* s = m_strms[i];
- s->cs.RemoveAll();
- s->totalsize = 0;
- }
+ for(int i = 0; i < (int)m_avih.dwStreams; i++)
+ {
+ strm_t* s = m_strms[i];
+ s->cs.RemoveAll();
+ s->totalsize = 0;
+ }
}
bool CAviFile::IsInterleaved(bool fKeepInfo)
{
- if(m_strms.GetCount() < 2)
- return(true);
- /*
- if(m_avih.dwFlags&AVIF_ISINTERLEAVED) // not reliable, nandub can write f*cked up files and still sets it
- return(true);
- */
- for(int i = 0; i < (int)m_avih.dwStreams; i++)
- m_strms[i]->cs2.SetCount(m_strms[i]->cs.GetCount());
-
- DWORD* curchunks = DNew DWORD[m_avih.dwStreams];
- UINT64* cursizes = DNew UINT64[m_avih.dwStreams];
-
- memset(curchunks, 0, sizeof(DWORD)*m_avih.dwStreams);
- memset(cursizes, 0, sizeof(UINT64)*m_avih.dwStreams);
-
- int end = 0;
-
- while(1)
- {
- UINT64 fpmin = _I64_MAX;
-
- DWORD n = -1;
- for(int i = 0; i < (int)m_avih.dwStreams; i++)
- {
- int curchunk = curchunks[i];
- CAtlArray<strm_t::chunk>& cs = m_strms[i]->cs;
- if(curchunk >= cs.GetCount()) continue;
+ if(m_strms.GetCount() < 2)
+ return(true);
+/*
+ if(m_avih.dwFlags&AVIF_ISINTERLEAVED) // not reliable, nandub can write f*cked up files and still sets it
+ return(true);
+*/
+ for(int i = 0; i < (int)m_avih.dwStreams; i++)
+ m_strms[i]->cs2.SetCount(m_strms[i]->cs.GetCount());
+
+ DWORD* curchunks = DNew DWORD[m_avih.dwStreams];
+ UINT64* cursizes = DNew UINT64[m_avih.dwStreams];
+
+ memset(curchunks, 0, sizeof(DWORD)*m_avih.dwStreams);
+ memset(cursizes, 0, sizeof(UINT64)*m_avih.dwStreams);
+
+ int end = 0;
+
+ while(1)
+ {
+ UINT64 fpmin = _I64_MAX;
+
+ DWORD n = -1;
+ for(int i = 0; i < (int)m_avih.dwStreams; i++)
+ {
+ int curchunk = curchunks[i];
+ CAtlArray<strm_t::chunk>& cs = m_strms[i]->cs;
+ if(curchunk >= cs.GetCount()) continue;
UINT64 fp = cs[curchunk].filepos;
- if(fp < fpmin)
- {
- fpmin = fp;
- n = i;
- }
- }
- if(n == -1) break;
-
- strm_t* s = m_strms[n];
- DWORD& curchunk = curchunks[n];
- UINT64& cursize = cursizes[n];
-
- if(!s->IsRawSubtitleStream())
- {
- strm_t::chunk2& cs2 = s->cs2[curchunk];
- cs2.t = (DWORD)(s->GetRefTime(curchunk, cursize) >> 13); // for comparing later it is just as good as /10000 to get a near [ms] accuracy
+ if(fp < fpmin) {fpmin = fp; n = i;}
+ }
+ if(n == -1) break;
+
+ strm_t* s = m_strms[n];
+ DWORD& curchunk = curchunks[n];
+ UINT64& cursize = cursizes[n];
+
+ if(!s->IsRawSubtitleStream())
+ {
+ strm_t::chunk2& cs2 = s->cs2[curchunk];
+ cs2.t = (DWORD)(s->GetRefTime(curchunk, cursize)>>13); // for comparing later it is just as good as /10000 to get a near [ms] accuracy
// cs2.t = (DWORD)(s->GetRefTime(curchunk, cursize)/10000);
- cs2.n = end++;
- }
+ cs2.n = end++;
+ }
- cursize = s->cs[curchunk].size;
- curchunk++;
- }
+ cursize = s->cs[curchunk].size;
+ curchunk++;
+ }
- memset(curchunks, 0, sizeof(DWORD)*m_avih.dwStreams);
+ memset(curchunks, 0, sizeof(DWORD)*m_avih.dwStreams);
- strm_t::chunk2 cs2last = { -1, 0};
+ strm_t::chunk2 cs2last = {-1, 0};
- bool fInterleaved = true;
+ bool fInterleaved = true;
- while(fInterleaved)
- {
- strm_t::chunk2 cs2min = {LONG_MAX, LONG_MAX};
+ while(fInterleaved)
+ {
+ strm_t::chunk2 cs2min = {LONG_MAX, LONG_MAX};
- int n = -1;
- for(int i = 0; i < (int)m_avih.dwStreams; i++)
- {
- int curchunk = curchunks[i];
- if(curchunk >= m_strms[i]->cs2.GetCount()) continue;
- strm_t::chunk2& cs2 = m_strms[i]->cs2[curchunk];
- if(cs2.t < cs2min.t)
- {
- cs2min = cs2;
- n = i;
- }
- }
- if(n == -1) break;
+ int n = -1;
+ for(int i = 0; i < (int)m_avih.dwStreams; i++)
+ {
+ int curchunk = curchunks[i];
+ if(curchunk >= m_strms[i]->cs2.GetCount()) continue;
+ strm_t::chunk2& cs2 = m_strms[i]->cs2[curchunk];
+ if(cs2.t < cs2min.t) {cs2min = cs2; n = i;}
+ }
+ if(n == -1) break;
- curchunks[n]++;
+ curchunks[n]++;
- if(cs2last.t >= 0 && abs((int)cs2min.n - (int)cs2last.n) >= 1000)
- fInterleaved = false;
+ if(cs2last.t >= 0 && abs((int)cs2min.n - (int)cs2last.n) >= 1000)
+ fInterleaved = false;
- cs2last = cs2min;
- }
+ cs2last = cs2min;
+ }
- delete [] curchunks;
- delete [] cursizes;
+ delete [] curchunks;
+ delete [] cursizes;
- if(fInterleaved && !fKeepInfo)
- {
- // this is not needed anymore, let's save a little memory then
- for(int i = 0; i < (int)m_avih.dwStreams; i++)
- m_strms[i]->cs2.RemoveAll();
- }
+ if(fInterleaved && !fKeepInfo)
+ {
+ // this is not needed anymore, let's save a little memory then
+ for(int i = 0; i < (int)m_avih.dwStreams; i++)
+ m_strms[i]->cs2.RemoveAll();
+ }
- return(fInterleaved);
+ return(fInterleaved);
}
REFERENCE_TIME CAviFile::strm_t::GetRefTime(DWORD frame, UINT64 size)
{
- float dframe = frame;
+ float dframe = frame;
- if(strh.fccType == FCC('auds'))
- {
- WAVEFORMATEX* wfe = (WAVEFORMATEX*)strf.GetData();
+ if(strh.fccType == FCC('auds'))
+ {
+ WAVEFORMATEX* wfe = (WAVEFORMATEX*)strf.GetData();
- dframe = wfe->nBlockAlign ? 1.0f * size / wfe->nBlockAlign : 0;
- }
+ dframe = wfe->nBlockAlign ? 1.0f * size / wfe->nBlockAlign : 0;
+ }
- float scale_per_rate = strh.dwRate ? 1.0f * strh.dwScale / strh.dwRate : 0;
+ float scale_per_rate = strh.dwRate ? 1.0f * strh.dwScale / strh.dwRate : 0;
- return (REFERENCE_TIME)(scale_per_rate * dframe * 10000000 + 0.5f);
+ return (REFERENCE_TIME)(scale_per_rate * dframe * 10000000 + 0.5f);
}
int CAviFile::strm_t::GetFrame(REFERENCE_TIME rt)
{
- int frame = -1;
+ int frame = -1;
- float rate_per_scale = strh.dwScale ? 1.0f * strh.dwRate / strh.dwScale : 0;
+ float rate_per_scale = strh.dwScale ? 1.0f * strh.dwRate / strh.dwScale : 0;
- if(strh.fccType == FCC('auds'))
- {
- WAVEFORMATEX* wfe = (WAVEFORMATEX*)strf.GetData();
+ if(strh.fccType == FCC('auds'))
+ {
+ WAVEFORMATEX* wfe = (WAVEFORMATEX*)strf.GetData();
- __int64 size = (__int64)(rate_per_scale * wfe->nBlockAlign * rt / 10000000 + 0.5f);
+ __int64 size = (__int64)(rate_per_scale * wfe->nBlockAlign * rt / 10000000 + 0.5f);
- for(frame = 0; frame < cs.GetCount(); frame++)
- {
- if(cs[frame].size > size)
- {
- frame--;
- break;
- }
- }
- }
- else
- {
- frame = (int)(rate_per_scale * rt / 10000000 + 0.5f);
- }
+ for(frame = 0; frame < cs.GetCount(); frame++)
+ {
+ if(cs[frame].size > size)
+ {
+ frame--;
+ break;
+ }
+ }
+ }
+ else
+ {
+ frame = (int)(rate_per_scale * rt / 10000000 + 0.5f);
+ }
- if(frame >= cs.GetCount()) frame = cs.GetCount() - 1;
+ if(frame >= cs.GetCount()) frame = cs.GetCount()-1;
- return frame;
+ return frame;
}
int CAviFile::strm_t::GetKeyFrame(REFERENCE_TIME rt)
{
- int i = GetFrame(rt);
- for(; i > 0; i--)
- {
- if(cs[i].fKeyFrame) break;
- }
- return(i);
+ int i = GetFrame(rt);
+ for(; i > 0; i--) {if(cs[i].fKeyFrame) break;}
+ return(i);
}
DWORD CAviFile::strm_t::GetChunkSize(DWORD size)
{
- if(strh.fccType == FCC('auds'))
- {
- WORD nBlockAlign = ((WAVEFORMATEX*)strf.GetData())->nBlockAlign;
- size = nBlockAlign ? (size + (nBlockAlign - 1)) / nBlockAlign * nBlockAlign : 0; // round up for nando's vbr hack
- }
+ if(strh.fccType == FCC('auds'))
+ {
+ WORD nBlockAlign = ((WAVEFORMATEX*)strf.GetData())->nBlockAlign;
+ size = nBlockAlign ? (size + (nBlockAlign-1)) / nBlockAlign * nBlockAlign : 0; // round up for nando's vbr hack
+ }
- return size;
+ return size;
}
bool CAviFile::strm_t::IsRawSubtitleStream()
{
- return strh.fccType == FCC('txts') && cs.GetCount() == 1;
+ return strh.fccType == FCC('txts') && cs.GetCount() == 1;
}
diff --git a/src/filters/parser/AviSplitter/AviFile.h b/src/filters/parser/AviSplitter/AviFile.h
index 5d7a8ddb0..6ef8cf9d3 100644
--- a/src/filters/parser/AviSplitter/AviFile.h
+++ b/src/filters/parser/AviSplitter/AviFile.h
@@ -5,62 +5,50 @@
class CAviFile : public CBaseSplitterFile
{
- HRESULT Init();
- HRESULT Parse(DWORD parentid, __int64 end);
- HRESULT BuildAMVIndex();
+ HRESULT Init();
+ HRESULT Parse(DWORD parentid, __int64 end);
+ HRESULT BuildAMVIndex();
public:
- CAviFile(IAsyncReader* pAsyncReader, HRESULT& hr);
+ CAviFile(IAsyncReader* pAsyncReader, HRESULT& hr);
- //using CBaseSplitterFile::Read;
- template<typename T> HRESULT Read(T& var, int offset = 0);
+ //using CBaseSplitterFile::Read;
+ template<typename T> HRESULT Read(T& var, int offset = 0);
- AVIMAINHEADER m_avih;
- struct ODMLExtendedAVIHeader
- {
- DWORD dwTotalFrames;
- } m_dmlh;
+ AVIMAINHEADER m_avih;
+ struct ODMLExtendedAVIHeader {DWORD dwTotalFrames;} m_dmlh;
// VideoPropHeader m_vprp;
- struct strm_t
- {
- AVISTREAMHEADER strh;
- CAtlArray<BYTE> strf;
- CStringA strn;
- CAutoPtr<AVISUPERINDEX> indx;
- struct chunk
- {
- UINT64 fKeyFrame: 1, fChunkHdr: 1, size: 62;
- UINT64 filepos;
- DWORD orgsize;
- };
- CAtlArray<chunk> cs;
- UINT64 totalsize;
- REFERENCE_TIME GetRefTime(DWORD frame, UINT64 size);
- int GetTime(DWORD frame, UINT64 size);
- int GetFrame(REFERENCE_TIME rt);
- int GetKeyFrame(REFERENCE_TIME rt);
- DWORD GetChunkSize(DWORD size);
- bool IsRawSubtitleStream();
-
- // tmp
- struct chunk2
- {
- DWORD t;
- DWORD n;
- };
- CAtlArray<chunk2> cs2;
- };
- CAutoPtrArray<strm_t> m_strms;
- CAtlMap<DWORD, CStringA> m_info;
- CAutoPtr<AVIOLDINDEX> m_idx1;
-
- CAtlList<UINT64> m_movis;
- bool m_isamv;
-
- REFERENCE_TIME GetTotalTime();
- HRESULT BuildIndex();
- void EmptyIndex();
- bool IsInterleaved(bool fKeepInfo = false);
+ struct strm_t
+ {
+ AVISTREAMHEADER strh;
+ CAtlArray<BYTE> strf;
+ CStringA strn;
+ CAutoPtr<AVISUPERINDEX> indx;
+ struct chunk {UINT64 fKeyFrame:1, fChunkHdr:1, size:62; UINT64 filepos; DWORD orgsize;};
+ CAtlArray<chunk> cs;
+ UINT64 totalsize;
+ REFERENCE_TIME GetRefTime(DWORD frame, UINT64 size);
+ int GetTime(DWORD frame, UINT64 size);
+ int GetFrame(REFERENCE_TIME rt);
+ int GetKeyFrame(REFERENCE_TIME rt);
+ DWORD GetChunkSize(DWORD size);
+ bool IsRawSubtitleStream();
+
+ // tmp
+ struct chunk2 {DWORD t; DWORD n;};
+ CAtlArray<chunk2> cs2;
+ };
+ CAutoPtrArray<strm_t> m_strms;
+ CAtlMap<DWORD, CStringA> m_info;
+ CAutoPtr<AVIOLDINDEX> m_idx1;
+
+ CAtlList<UINT64> m_movis;
+ bool m_isamv;
+
+ REFERENCE_TIME GetTotalTime();
+ HRESULT BuildIndex();
+ void EmptyIndex();
+ bool IsInterleaved(bool fKeepInfo = false);
};
#define TRACKNUM(fcc) (10*((fcc&0xff)-0x30) + (((fcc>>8)&0xff)-0x30))
diff --git a/src/filters/parser/AviSplitter/AviReportWnd.cpp b/src/filters/parser/AviSplitter/AviReportWnd.cpp
index 76e1a0ab4..95a20c668 100644
--- a/src/filters/parser/AviSplitter/AviReportWnd.cpp
+++ b/src/filters/parser/AviSplitter/AviReportWnd.cpp
@@ -7,165 +7,165 @@
CAviReportWnd::CAviReportWnd()
{
- m_font.CreateFont(12, 0, 0, 0, 400, 0, 0, 0, 1, 0, 0, 0, 0, _T("MS Shell Dlg"));
+ m_font.CreateFont(12, 0, 0, 0, 400, 0, 0, 0, 1, 0, 0, 0, 0, _T("MS Shell Dlg"));
}
bool CAviReportWnd::DoModal(CAviFile* pAF, bool fHideChecked, bool fShowWarningText)
{
- m_nChunks = 0;
- m_rtDur = 0;
+ m_nChunks = 0;
+ m_rtDur = 0;
- for(int i = 0; i < (int)pAF->m_avih.dwStreams; i++)
- {
- int cnt = pAF->m_strms[i]->cs2.GetCount();
- if(cnt <= 0) continue;
- CAviFile::strm_t::chunk2& c2 = pAF->m_strms[i]->cs2[cnt-1];
- m_nChunks = max(m_nChunks, c2.n);
- m_rtDur = max(m_rtDur, (REFERENCE_TIME)c2.t << 13);
- }
+ for(int i = 0; i < (int)pAF->m_avih.dwStreams; i++)
+ {
+ int cnt = pAF->m_strms[i]->cs2.GetCount();
+ if(cnt <= 0) continue;
+ CAviFile::strm_t::chunk2& c2 = pAF->m_strms[i]->cs2[cnt-1];
+ m_nChunks = max(m_nChunks, c2.n);
+ m_rtDur = max(m_rtDur, (REFERENCE_TIME)c2.t<<13);
+ }
- CRect r, r2;
- GetDesktopWindow()->GetWindowRect(r);
- r.DeflateRect(r.Width() / 4, r.Height() / 4);
+ CRect r, r2;
+ GetDesktopWindow()->GetWindowRect(r);
+ r.DeflateRect(r.Width()/4, r.Height()/4);
- LPCTSTR wndclass = AfxRegisterWndClass(
- CS_VREDRAW | CS_HREDRAW | CS_DBLCLKS,
- AfxGetApp()->LoadStandardCursor(IDC_ARROW),
- (HBRUSH)(COLOR_BTNFACE + 1), 0);
+ LPCTSTR wndclass = AfxRegisterWndClass(
+ CS_VREDRAW|CS_HREDRAW|CS_DBLCLKS,
+ AfxGetApp()->LoadStandardCursor(IDC_ARROW),
+ (HBRUSH)(COLOR_BTNFACE + 1), 0);
- CreateEx(0, wndclass, TITLE, WS_POPUPWINDOW | WS_CAPTION | WS_CLIPCHILDREN, r, NULL, 0);
+ CreateEx(0, wndclass, TITLE, WS_POPUPWINDOW|WS_CAPTION|WS_CLIPCHILDREN, r, NULL, 0);
- CRect cr;
- GetClientRect(cr);
- cr.DeflateRect(10, 10);
+ CRect cr;
+ GetClientRect(cr);
+ cr.DeflateRect(10, 10);
- SetFont(&m_font, FALSE);
+ SetFont(&m_font, FALSE);
- CDC* pDC = GetDC();
- CFont* pOldFont = pDC->SelectObject(&m_font);
+ CDC* pDC = GetDC();
+ CFont* pOldFont = pDC->SelectObject(&m_font);
- //
+ //
- CString str(
- _T("This AVI file was not prepared for sequential reading, the alternative ")
- _T("'Avi Splitter' will now let the default one handle it. ")
- _T("The complete reinterleaving of this file is strongly recommended before ")
- _T("burning it onto a slow media like cd-rom."));
+ CString str(
+ _T("This AVI file was not prepared for sequential reading, the alternative ")
+ _T("'Avi Splitter' will now let the default one handle it. ")
+ _T("The complete reinterleaving of this file is strongly recommended before ")
+ _T("burning it onto a slow media like cd-rom."));
- r = cr;
+ r = cr;
- pDC->DrawText(str, r, DT_WORDBREAK | DT_CALCRECT);
- r.right = cr.right;
+ pDC->DrawText(str, r, DT_WORDBREAK|DT_CALCRECT);
+ r.right = cr.right;
- m_message.Create(str, WS_CHILD | WS_VISIBLE, r, this);
- m_message.SetFont(&m_font, FALSE);
+ m_message.Create(str, WS_CHILD|WS_VISIBLE, r, this);
+ m_message.SetFont(&m_font, FALSE);
- //
+ //
- r.SetRect(cr.left, r.bottom + 10, cr.right, cr.bottom);
+ r.SetRect(cr.left, r.bottom + 10, cr.right, cr.bottom);
- str = _T("Do not show this dialog again (hold Shift to re-enable it)");
+ str = _T("Do not show this dialog again (hold Shift to re-enable it)");
- pDC->DrawText(str, r, DT_WORDBREAK | DT_CALCRECT);
- r.right = cr.right;
+ pDC->DrawText(str, r, DT_WORDBREAK|DT_CALCRECT);
+ r.right = cr.right;
- m_checkbox.Create(str, WS_CHILD | WS_VISIBLE | BS_CHECKBOX | BS_AUTOCHECKBOX, r, this, IDC_DONOTSHOWAGAINCHECK);
- m_checkbox.SetFont(&m_font, FALSE);
+ m_checkbox.Create(str, WS_CHILD|WS_VISIBLE|BS_CHECKBOX|BS_AUTOCHECKBOX, r, this, IDC_DONOTSHOWAGAINCHECK);
+ m_checkbox.SetFont(&m_font, FALSE);
- CheckDlgButton(IDC_DONOTSHOWAGAINCHECK, fHideChecked ? BST_CHECKED : BST_UNCHECKED);
+ CheckDlgButton(IDC_DONOTSHOWAGAINCHECK, fHideChecked?BST_CHECKED:BST_UNCHECKED);
- //
+ //
- if(!fShowWarningText)
- {
- m_message.ShowWindow(SW_HIDE);
- m_checkbox.ShowWindow(SW_HIDE);
- r = cr;
- }
- else
- {
- r.SetRect(cr.left, r.bottom + 10, cr.right, cr.bottom);
- }
+ if(!fShowWarningText)
+ {
+ m_message.ShowWindow(SW_HIDE);
+ m_checkbox.ShowWindow(SW_HIDE);
+ r = cr;
+ }
+ else
+ {
+ r.SetRect(cr.left, r.bottom + 10, cr.right, cr.bottom);
+ }
- m_graph.Create(pAF, r, this);
+ m_graph.Create(pAF, r, this);
- //
+ //
- pDC->SelectObject(pOldFont);
- ReleaseDC(pDC);
+ pDC->SelectObject(pOldFont);
+ ReleaseDC(pDC);
- SetWindowPos(&wndTop, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE);
- SetForegroundWindow();
- ShowWindow(SW_SHOWNORMAL);
+ SetWindowPos(&wndTop, 0, 0, 0, 0, SWP_NOMOVE|SWP_NOSIZE);
+ SetForegroundWindow();
+ ShowWindow(SW_SHOWNORMAL);
- return !!RunModalLoop();
+ return !!RunModalLoop();
}
IMPLEMENT_DYNCREATE(CAviReportWnd, CWnd)
BEGIN_MESSAGE_MAP(CAviReportWnd, CWnd)
- ON_WM_CLOSE()
- ON_WM_MOUSEMOVE()
+ ON_WM_CLOSE()
+ ON_WM_MOUSEMOVE()
END_MESSAGE_MAP()
void CAviReportWnd::OnClose()
{
- EndModalLoop(IsDlgButtonChecked(IDC_DONOTSHOWAGAINCHECK));
- __super::OnClose();
+ EndModalLoop(IsDlgButtonChecked(IDC_DONOTSHOWAGAINCHECK));
+ __super::OnClose();
}
void CAviReportWnd::OnMouseMove(UINT nFlags, CPoint p)
{
- MapWindowPoints(&m_graph, &p, 1);
-
- CRect r, r2;
- m_graph.GetClientRect(r);
- r2 = r;
- r.bottom -= GRAPHFOOTER;
- r2.top = r.bottom;
-
- if(r.PtInRect(p))
- {
- SetCapture();
-
- int x = p.x - r.left;
- int y = r.bottom - p.y;
-
- REFERENCE_TIME rt = m_rtDur * x / r.Width();
- int chunk = (int)(1.0 * m_nChunks * y / r.Height());
-
- rt /= 10000;
- int ms = (int)(rt % 1000);
- rt /= 1000;
- int s = (int)(rt % 60);
- rt /= 60;
- int m = (int)(rt % 60);
- rt /= 60;
- int h = (int)(rt);
-
- CString str;
- str.Format(_T("%s (%d - %d:%02d:%02d.%03d)"), TITLE, chunk, h, m, s, ms);
- SetWindowText(str);
- }
- else if(r2.PtInRect(p))
- {
- SetCapture();
-
- int dist = m_graph.GetChunkDist(p.x - r2.left);
- CString str;
- str.Format(_T("%s (chunk distance: %d"), TITLE, dist);
- if(dist >= 1000) str += _T(" - over the limit!");
- str += ")";
- SetWindowText(str);
- }
- else if(GetCapture() == this)
- {
- SetWindowText(TITLE);
-
- ReleaseCapture();
- }
-
- __super::OnMouseMove(nFlags, p);
+ MapWindowPoints(&m_graph, &p, 1);
+
+ CRect r, r2;
+ m_graph.GetClientRect(r);
+ r2 = r;
+ r.bottom -= GRAPHFOOTER;
+ r2.top = r.bottom;
+
+ if(r.PtInRect(p))
+ {
+ SetCapture();
+
+ int x = p.x - r.left;
+ int y = r.bottom - p.y;
+
+ REFERENCE_TIME rt = m_rtDur * x / r.Width();
+ int chunk = (int)(1.0 * m_nChunks * y / r.Height());
+
+ rt /= 10000;
+ int ms = (int)(rt%1000);
+ rt /= 1000;
+ int s = (int)(rt%60);
+ rt /= 60;
+ int m = (int)(rt%60);
+ rt /= 60;
+ int h = (int)(rt);
+
+ CString str;
+ str.Format(_T("%s (%d - %d:%02d:%02d.%03d)"), TITLE, chunk, h, m, s, ms);
+ SetWindowText(str);
+ }
+ else if(r2.PtInRect(p))
+ {
+ SetCapture();
+
+ int dist = m_graph.GetChunkDist(p.x - r2.left);
+ CString str;
+ str.Format(_T("%s (chunk distance: %d"), TITLE, dist);
+ if(dist >= 1000) str += _T(" - over the limit!");
+ str += ")";
+ SetWindowText(str);
+ }
+ else if(GetCapture() == this)
+ {
+ SetWindowText(TITLE);
+
+ ReleaseCapture();
+ }
+
+ __super::OnMouseMove(nFlags, p);
}
//////////////
@@ -176,187 +176,169 @@ CAviPlotterWnd::CAviPlotterWnd()
bool CAviPlotterWnd::Create(CAviFile* pAF, CRect r, CWnd* pParentWnd)
{
- if(!CreateEx(WS_EX_CLIENTEDGE, _T("STATIC"), _T(""), WS_CHILD | WS_VISIBLE, r, pParentWnd, 0))
- return(false);
-
- GetClientRect(r);
- int w = r.Width();
- int h = r.Height() - GRAPHFOOTER;
-
- CDC* pDC = GetDC();
- m_dc.CreateCompatibleDC(pDC);
- m_bm.CreateCompatibleBitmap(pDC, r.Width(), r.Height());
- ReleaseDC(pDC);
-
- CBitmap* pOldBitmap = m_dc.SelectObject(&m_bm);
-
- m_dc.FillSolidRect(r, 0);
-
- {
- CPen pen(PS_DOT, 1, 0x008000);
- CPen* pOldPen = m_dc.SelectObject(&pen);
- for(int y = 0, dy = max(h / 10, 1); y < h; y += dy)
- {
- if(y == 0) continue;
- m_dc.MoveTo(0, y);
- m_dc.LineTo(w, y);
- }
- for(int x = 0, dx = max(w / 10, 1); x < w; x += dx)
- {
- if(x == 0) continue;
- m_dc.MoveTo(x, 0);
- m_dc.LineTo(x, w);
- }
- m_dc.SelectObject(pOldPen);
- }
-
- {
- CPen pen(PS_SOLID, 1, 0x00ff00);
- CPen* pOldPen = m_dc.SelectObject(&pen);
- m_dc.MoveTo(15, 30);
- m_dc.LineTo(15, 2);
- m_dc.LineTo(19, 10);
- m_dc.LineTo(11, 10);
- m_dc.LineTo(15, 2);
- m_dc.MoveTo(w - 30 - 10, h - 15);
- m_dc.LineTo(w - 2 - 10, h - 15);
- m_dc.LineTo(w - 10 - 10, h - 19);
- m_dc.LineTo(w - 10 - 10, h - 11);
- m_dc.LineTo(w - 2 - 10, h - 15);
- m_dc.SelectObject(pOldPen);
-
- m_dc.SetTextColor(0x008000);
- m_dc.TextOut(20, 10, _T("Chunk"));
-
- CSize size = m_dc.GetTextExtent(_T("Time"));
- m_dc.TextOut(w - size.cx - 10, h - size.cy - 20, _T("Time"));
- }
-
- COLORREF clr[] = {0x0000ff, 0xff0000, 0x40ffff, 0xff40ff, 0xffff40, 0xffffff};
-
- for(int i = 0, y = 40, dy = m_dc.GetTextExtent(_T("Stream N")).cy + 1; i < (int)pAF->m_avih.dwStreams; i++, y += dy)
- {
- m_dc.SetTextColor(clr[i%pAF->m_avih.dwStreams]);
- m_dc.SetBkMode(TRANSPARENT);
- CString str;
- str.Format(_T("Stream %d"), i);
- m_dc.TextOut(10, y, str);
- }
-
- DWORD nmax = 0, tmax = 0;
-
- for(int i = 0; i < (int)pAF->m_avih.dwStreams; i++)
- {
- int cnt = pAF->m_strms[i]->cs2.GetCount();
- if(cnt <= 0) continue;
- CAviFile::strm_t::chunk2& c2 = pAF->m_strms[i]->cs2[cnt-1];
- nmax = max(nmax, c2.n);
- tmax = max(tmax, c2.t);
- }
-
- if(nmax > 0 && tmax > 0)
- {
- CAtlArray<CPen> pen;
- pen.SetCount(pAF->m_avih.dwStreams);
- for(int i = 0; i < pen.GetCount(); i++)
- pen[i].CreatePen(PS_SOLID, 2, clr[i]);
-
- CAtlArray<CPoint> pp;
- pp.SetCount(pAF->m_avih.dwStreams);
- for(int i = 0; i < pen.GetCount(); i++)
- pp[i].SetPoint(-1, -1);
-
- m_chunkdist.SetCount(w);
- memset(m_chunkdist.GetData(), 0, sizeof(int)*w);
-
- DWORD* curchunks = DNew DWORD[pAF->m_avih.dwStreams];
- memset(curchunks, 0, sizeof(DWORD)*pAF->m_avih.dwStreams);
-
- CAviFile::strm_t::chunk2 cs2last = { -1, 0};
-
- while(1)
- {
- CAviFile::strm_t::chunk2 cs2min = {LONG_MAX, LONG_MAX};
-
- int n = -1;
- for(int i = 0; i < (int)pAF->m_avih.dwStreams; i++)
- {
- int curchunk = curchunks[i];
- if(curchunk >= pAF->m_strms[i]->cs2.GetCount()) continue;
- CAviFile::strm_t::chunk2& cs2 = pAF->m_strms[i]->cs2[curchunk];
- if(cs2.t < cs2min.t)
- {
- cs2min = cs2;
- n = i;
- }
- }
- if(n == -1) break;
-
-
- CPoint p;
- p.x = (int)(1.0 * w * cs2min.t / tmax);
- p.y = (int)(h - 1.0 * h * cs2min.n / nmax);
- if(pp[n] != p)
- {
- CPen* pOldPen = m_dc.SelectObject(&pen[n]);
- if(pp[n] == CPoint(-1, -1)) m_dc.MoveTo(p);
- else
- {
- m_dc.MoveTo(pp[n]);
- m_dc.LineTo(p);
- }
- m_dc.SelectObject(pOldPen);
- pp[n] = p;
- }
-
- int dist = abs((int)cs2min.n - (int)cs2last.n);
-
- if(cs2last.t >= 0 /*&& dist >= 1000*/)
- {
- if(p.x >= 0 && p.x < w)
- {
- m_chunkdist[p.x] = max(m_chunkdist[p.x], dist);
- }
- }
-
- curchunks[n]++;
- cs2last = cs2min;
- }
-
- CPen red(PS_SOLID, 1, 0x0000ff);
- CPen green(PS_SOLID, 1, 0x00ff00);
-
- for(int x = 0; x < w; x++)
- {
- CPen* pOldPen = m_dc.SelectObject(m_chunkdist[x] >= 1000 ? &red : &green);
- m_dc.MoveTo(x, h);
- m_dc.LineTo(x, h + GRAPHFOOTER);
- m_dc.SelectObject(pOldPen);
- }
-
- delete [] curchunks;
- }
-
- m_dc.SelectObject(pOldBitmap);
-
- return(true);
+ if(!CreateEx(WS_EX_CLIENTEDGE, _T("STATIC"), _T(""), WS_CHILD|WS_VISIBLE, r, pParentWnd, 0))
+ return(false);
+
+ GetClientRect(r);
+ int w = r.Width();
+ int h = r.Height() - GRAPHFOOTER;
+
+ CDC* pDC = GetDC();
+ m_dc.CreateCompatibleDC(pDC);
+ m_bm.CreateCompatibleBitmap(pDC, r.Width(), r.Height());
+ ReleaseDC(pDC);
+
+ CBitmap* pOldBitmap = m_dc.SelectObject(&m_bm);
+
+ m_dc.FillSolidRect(r, 0);
+
+ {
+ CPen pen(PS_DOT, 1, 0x008000);
+ CPen* pOldPen = m_dc.SelectObject(&pen);
+ for(int y = 0, dy = max(h/10,1); y < h; y += dy) {if(y == 0) continue; m_dc.MoveTo(0, y); m_dc.LineTo(w, y);}
+ for(int x = 0, dx = max(w/10,1); x < w; x += dx) {if(x == 0) continue; m_dc.MoveTo(x, 0); m_dc.LineTo(x, w);}
+ m_dc.SelectObject(pOldPen);
+ }
+
+ {
+ CPen pen(PS_SOLID, 1, 0x00ff00);
+ CPen* pOldPen = m_dc.SelectObject(&pen);
+ m_dc.MoveTo(15, 30);
+ m_dc.LineTo(15, 2);
+ m_dc.LineTo(19, 10);
+ m_dc.LineTo(11, 10);
+ m_dc.LineTo(15, 2);
+ m_dc.MoveTo(w-30-10, h-15);
+ m_dc.LineTo(w-2-10, h-15);
+ m_dc.LineTo(w-10-10, h-19);
+ m_dc.LineTo(w-10-10, h-11);
+ m_dc.LineTo(w-2-10, h-15);
+ m_dc.SelectObject(pOldPen);
+
+ m_dc.SetTextColor(0x008000);
+ m_dc.TextOut(20, 10, _T("Chunk"));
+
+ CSize size = m_dc.GetTextExtent(_T("Time"));
+ m_dc.TextOut(w - size.cx - 10, h - size.cy - 20, _T("Time"));
+ }
+
+ COLORREF clr[] = {0x0000ff,0xff0000,0x40ffff,0xff40ff,0xffff40,0xffffff};
+
+ for(int i = 0, y = 40, dy = m_dc.GetTextExtent(_T("Stream N")).cy + 1; i < (int)pAF->m_avih.dwStreams; i++, y += dy)
+ {
+ m_dc.SetTextColor(clr[i%pAF->m_avih.dwStreams]);
+ m_dc.SetBkMode(TRANSPARENT);
+ CString str;
+ str.Format(_T("Stream %d"), i);
+ m_dc.TextOut(10, y, str);
+ }
+
+ DWORD nmax = 0, tmax = 0;
+
+ for(int i = 0; i < (int)pAF->m_avih.dwStreams; i++)
+ {
+ int cnt = pAF->m_strms[i]->cs2.GetCount();
+ if(cnt <= 0) continue;
+ CAviFile::strm_t::chunk2& c2 = pAF->m_strms[i]->cs2[cnt-1];
+ nmax = max(nmax, c2.n);
+ tmax = max(tmax, c2.t);
+ }
+
+ if(nmax > 0 && tmax > 0)
+ {
+ CAtlArray<CPen> pen;
+ pen.SetCount(pAF->m_avih.dwStreams);
+ for(int i = 0; i < pen.GetCount(); i++)
+ pen[i].CreatePen(PS_SOLID, 2, clr[i]);
+
+ CAtlArray<CPoint> pp;
+ pp.SetCount(pAF->m_avih.dwStreams);
+ for(int i = 0; i < pen.GetCount(); i++)
+ pp[i].SetPoint(-1, -1);
+
+ m_chunkdist.SetCount(w);
+ memset(m_chunkdist.GetData(), 0, sizeof(int)*w);
+
+ DWORD* curchunks = DNew DWORD[pAF->m_avih.dwStreams];
+ memset(curchunks, 0, sizeof(DWORD)*pAF->m_avih.dwStreams);
+
+ CAviFile::strm_t::chunk2 cs2last = {-1, 0};
+
+ while(1)
+ {
+ CAviFile::strm_t::chunk2 cs2min = {LONG_MAX, LONG_MAX};
+
+ int n = -1;
+ for(int i = 0; i < (int)pAF->m_avih.dwStreams; i++)
+ {
+ int curchunk = curchunks[i];
+ if(curchunk >= pAF->m_strms[i]->cs2.GetCount()) continue;
+ CAviFile::strm_t::chunk2& cs2 = pAF->m_strms[i]->cs2[curchunk];
+ if(cs2.t < cs2min.t) {cs2min = cs2; n = i;}
+ }
+ if(n == -1) break;
+
+
+ CPoint p;
+ p.x = (int)(1.0 * w * cs2min.t / tmax);
+ p.y = (int)(h - 1.0 * h * cs2min.n / nmax);
+ if(pp[n] != p)
+ {
+ CPen* pOldPen = m_dc.SelectObject(&pen[n]);
+ if(pp[n] == CPoint(-1, -1)) m_dc.MoveTo(p);
+ else {m_dc.MoveTo(pp[n]); m_dc.LineTo(p);}
+ m_dc.SelectObject(pOldPen);
+ pp[n] = p;
+ }
+
+ int dist = abs((int)cs2min.n - (int)cs2last.n);
+
+ if(cs2last.t >= 0 /*&& dist >= 1000*/)
+ {
+ if(p.x >= 0 && p.x < w)
+ {
+ m_chunkdist[p.x] = max(m_chunkdist[p.x], dist);
+ }
+ }
+
+ curchunks[n]++;
+ cs2last = cs2min;
+ }
+
+ CPen red(PS_SOLID, 1, 0x0000ff);
+ CPen green(PS_SOLID, 1, 0x00ff00);
+
+ for(int x = 0; x < w; x++)
+ {
+ CPen* pOldPen = m_dc.SelectObject(m_chunkdist[x] >= 1000 ? &red : &green);
+ m_dc.MoveTo(x, h);
+ m_dc.LineTo(x, h + GRAPHFOOTER);
+ m_dc.SelectObject(pOldPen);
+ }
+
+ delete [] curchunks;
+ }
+
+ m_dc.SelectObject(pOldBitmap);
+
+ return(true);
}
IMPLEMENT_DYNCREATE(CAviPlotterWnd, CWnd)
BEGIN_MESSAGE_MAP(CAviPlotterWnd, CWnd)
- ON_WM_PAINT()
+ ON_WM_PAINT()
END_MESSAGE_MAP()
void CAviPlotterWnd::OnPaint()
{
- CPaintDC dc(this); // device context for painting
+ CPaintDC dc(this); // device context for painting
- CRect r;
- GetClientRect(r);
+ CRect r;
+ GetClientRect(r);
- CBitmap* pOld = m_dc.SelectObject(&m_bm);
- dc.BitBlt(0, 0, r.Width(), r.Height(), &m_dc, 0, 0, SRCCOPY);
- m_dc.SelectObject(pOld);
+ CBitmap* pOld = m_dc.SelectObject(&m_bm);
+ dc.BitBlt(0, 0, r.Width(), r.Height(), &m_dc, 0, 0, SRCCOPY);
+ m_dc.SelectObject(pOld);
}
diff --git a/src/filters/parser/AviSplitter/AviReportWnd.h b/src/filters/parser/AviSplitter/AviReportWnd.h
index cd30807e0..cd5c3b331 100644
--- a/src/filters/parser/AviSplitter/AviReportWnd.h
+++ b/src/filters/parser/AviSplitter/AviReportWnd.h
@@ -4,47 +4,44 @@
class CAviPlotterWnd : public CStatic
{
- DECLARE_DYNCREATE(CAviPlotterWnd)
+ DECLARE_DYNCREATE(CAviPlotterWnd)
private:
- CDC m_dc;
- CBitmap m_bm;
+ CDC m_dc;
+ CBitmap m_bm;
- CAtlArray<int> m_chunkdist;
+ CAtlArray<int> m_chunkdist;
public:
- CAviPlotterWnd();
- bool Create(CAviFile* pAF, CRect r, CWnd* pParentWnd);
+ CAviPlotterWnd();
+ bool Create(CAviFile* pAF, CRect r, CWnd* pParentWnd);
- int GetChunkDist(int x)
- {
- return x >= 0 && x < m_chunkdist.GetCount() ? m_chunkdist[x] : 0;
- }
+ int GetChunkDist(int x) {return x >= 0 && x < m_chunkdist.GetCount() ? m_chunkdist[x] : 0;}
- DECLARE_MESSAGE_MAP()
- afx_msg void OnPaint();
+ DECLARE_MESSAGE_MAP()
+ afx_msg void OnPaint();
};
class CAviReportWnd : public CWnd
{
- DECLARE_DYNCREATE(CAviReportWnd)
+ DECLARE_DYNCREATE(CAviReportWnd)
protected:
- CFont m_font;
- CStatic m_message;
- CButton m_checkbox;
- CAviPlotterWnd m_graph;
+ CFont m_font;
+ CStatic m_message;
+ CButton m_checkbox;
+ CAviPlotterWnd m_graph;
- int m_nChunks;
- REFERENCE_TIME m_rtDur;
+ int m_nChunks;
+ REFERENCE_TIME m_rtDur;
public:
- CAviReportWnd();
- bool DoModal(CAviFile* pAF, bool fHideChecked, bool fShowWarningText);
+ CAviReportWnd();
+ bool DoModal(CAviFile* pAF, bool fHideChecked, bool fShowWarningText);
- DECLARE_MESSAGE_MAP()
- afx_msg void OnClose();
- afx_msg void OnMouseMove(UINT nFlags, CPoint point);
+ DECLARE_MESSAGE_MAP()
+ afx_msg void OnClose();
+ afx_msg void OnMouseMove(UINT nFlags, CPoint point);
};
diff --git a/src/filters/parser/AviSplitter/AviSplitter.cpp b/src/filters/parser/AviSplitter/AviSplitter.cpp
index a34593187..d31561221 100644
--- a/src/filters/parser/AviSplitter/AviSplitter.cpp
+++ b/src/filters/parser/AviSplitter/AviSplitter.cpp
@@ -1,4 +1,4 @@
-/*
+/*
* Copyright (C) 2003-2006 Gabest
* http://www.gabest.org
*
@@ -6,15 +6,15 @@
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2, or (at your option)
* any later version.
- *
+ *
* This Program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with GNU Make; see the file COPYING. If not, write to
- * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
+ * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
* http://www.gnu.org/copyleft/gpl.html
*
*/
@@ -29,8 +29,8 @@
const AMOVIESETUP_MEDIATYPE sudPinTypesIn[] =
{
- {&MEDIATYPE_Stream, &MEDIASUBTYPE_Avi},
- {&MEDIATYPE_Stream, &MEDIASUBTYPE_NULL},
+ {&MEDIATYPE_Stream, &MEDIASUBTYPE_Avi},
+ {&MEDIATYPE_Stream, &MEDIASUBTYPE_NULL},
};
const AMOVIESETUP_PIN sudpPins[] =
@@ -41,39 +41,39 @@ const AMOVIESETUP_PIN sudpPins[] =
const AMOVIESETUP_FILTER sudFilter[] =
{
- {&__uuidof(CAviSplitterFilter), L"MPC - Avi Splitter", MERIT_NORMAL + 1, countof(sudpPins), sudpPins, CLSID_LegacyAmFilterCategory},
- {&__uuidof(CAviSourceFilter), L"MPC - Avi Source", MERIT_NORMAL + 1, 0, NULL, CLSID_LegacyAmFilterCategory},
+ {&__uuidof(CAviSplitterFilter), L"MPC - Avi Splitter", MERIT_NORMAL+1, countof(sudpPins), sudpPins, CLSID_LegacyAmFilterCategory},
+ {&__uuidof(CAviSourceFilter), L"MPC - Avi Source", MERIT_NORMAL+1, 0, NULL, CLSID_LegacyAmFilterCategory},
};
CFactoryTemplate g_Templates[] =
{
- {sudFilter[0].strName, sudFilter[0].clsID, CreateInstance<CAviSplitterFilter>, NULL, &sudFilter[0]},
- {sudFilter[1].strName, sudFilter[1].clsID, CreateInstance<CAviSourceFilter>, NULL, &sudFilter[1]},
+ {sudFilter[0].strName, sudFilter[0].clsID, CreateInstance<CAviSplitterFilter>, NULL, &sudFilter[0]},
+ {sudFilter[1].strName, sudFilter[1].clsID, CreateInstance<CAviSourceFilter>, NULL, &sudFilter[1]},
};
int g_cTemplates = countof(g_Templates);
STDAPI DllRegisterServer()
{
- CAtlList<CString> chkbytes;
- chkbytes.AddTail(_T("0,4,,52494646,8,4,,41564920")); // 'RIFF' ... 'AVI '
- chkbytes.AddTail(_T("0,4,,52494646,8,4,,41564958")); // 'RIFF' ... 'AVIX'
- chkbytes.AddTail(_T("0,4,,52494646,8,4,,414D5620")); // 'RIFF' ... 'AMV '
-
- RegisterSourceFilter(
- CLSID_AsyncReader,
- MEDIASUBTYPE_Avi,
- chkbytes,
- _T(".avi"), _T(".divx"), _T(".vp6"), _T(".amv"), NULL);
-
- return AMovieDllRegisterServer2(TRUE);
+ CAtlList<CString> chkbytes;
+ chkbytes.AddTail(_T("0,4,,52494646,8,4,,41564920")); // 'RIFF' ... 'AVI '
+ chkbytes.AddTail(_T("0,4,,52494646,8,4,,41564958")); // 'RIFF' ... 'AVIX'
+ chkbytes.AddTail(_T("0,4,,52494646,8,4,,414D5620")); // 'RIFF' ... 'AMV '
+
+ RegisterSourceFilter(
+ CLSID_AsyncReader,
+ MEDIASUBTYPE_Avi,
+ chkbytes,
+ _T(".avi"), _T(".divx"), _T(".vp6"), _T(".amv"), NULL);
+
+ return AMovieDllRegisterServer2(TRUE);
}
STDAPI DllUnregisterServer()
{
// UnRegisterSourceFilter(MEDIASUBTYPE_Avi);
- return AMovieDllRegisterServer2(FALSE);
+ return AMovieDllRegisterServer2(FALSE);
}
extern "C" BOOL WINAPI DllEntryPoint(HINSTANCE, ULONG, LPVOID);
@@ -81,27 +81,27 @@ extern "C" BOOL WINAPI DllEntryPoint(HINSTANCE, ULONG, LPVOID);
class CAviSplitterApp : public CWinApp
{
public:
- CAviSplitterApp() {}
-
- BOOL InitInstance()
- {
- if(!__super::InitInstance()) return FALSE;
- DllEntryPoint(m_hInstance, DLL_PROCESS_ATTACH, 0);
- return TRUE;
- }
-
- BOOL ExitInstance()
- {
- DllEntryPoint(m_hInstance, DLL_PROCESS_DETACH, 0);
- return __super::ExitInstance();
- }
-
- void SetDefaultRegistryKey()
- {
- SetRegistryKey(_T("Gabest"));
- }
-
- DECLARE_MESSAGE_MAP()
+ CAviSplitterApp() {}
+
+ BOOL InitInstance()
+ {
+ if(!__super::InitInstance()) return FALSE;
+ DllEntryPoint(m_hInstance, DLL_PROCESS_ATTACH, 0);
+ return TRUE;
+ }
+
+ BOOL ExitInstance()
+ {
+ DllEntryPoint(m_hInstance, DLL_PROCESS_DETACH, 0);
+ return __super::ExitInstance();
+ }
+
+ void SetDefaultRegistryKey()
+ {
+ SetRegistryKey(_T("Gabest"));
+ }
+
+ DECLARE_MESSAGE_MAP()
};
BEGIN_MESSAGE_MAP(CAviSplitterApp, CWinApp)
@@ -116,737 +116,709 @@ CAviSplitterApp theApp;
//
CAviSplitterFilter::CAviSplitterFilter(LPUNKNOWN pUnk, HRESULT* phr)
- : CBaseSplitterFilter(NAME("CAviSplitterFilter"), pUnk, phr, __uuidof(this))
- , m_timeformat(TIME_FORMAT_MEDIA_TIME)
+ : CBaseSplitterFilter(NAME("CAviSplitterFilter"), pUnk, phr, __uuidof(this))
+ , m_timeformat(TIME_FORMAT_MEDIA_TIME)
{
}
STDMETHODIMP CAviSplitterFilter::NonDelegatingQueryInterface(REFIID riid, void** ppv)
{
- CheckPointer(ppv, E_POINTER);
+ CheckPointer(ppv, E_POINTER);
- *ppv = NULL;
+ *ppv = NULL;
- return
- __super::NonDelegatingQueryInterface(riid, ppv);
+ return
+ __super::NonDelegatingQueryInterface(riid, ppv);
}
HRESULT CAviSplitterFilter::CreateOutputs(IAsyncReader* pAsyncReader)
{
- CheckPointer(pAsyncReader, E_POINTER);
+ CheckPointer(pAsyncReader, E_POINTER);
- HRESULT hr = E_FAIL;
+ HRESULT hr = E_FAIL;
- m_pFile.Free();
- m_tFrame.Free();
+ m_pFile.Free();
+ m_tFrame.Free();
- m_pFile.Attach(DNew CAviFile(pAsyncReader, hr));
- if(!m_pFile) return E_OUTOFMEMORY;
+ m_pFile.Attach(DNew CAviFile(pAsyncReader, hr));
+ if(!m_pFile) return E_OUTOFMEMORY;
- bool fShiftDown = !!(::GetKeyState(VK_SHIFT) & 0x8000);
- bool fShowWarningText = !m_pFile->IsInterleaved(fShiftDown);
+ bool fShiftDown = !!(::GetKeyState(VK_SHIFT)&0x8000);
+ bool fShowWarningText = !m_pFile->IsInterleaved(fShiftDown);
- if(SUCCEEDED(hr) && (fShowWarningText || fShiftDown))
- {
+ if(SUCCEEDED(hr) && (fShowWarningText || fShiftDown))
+ {
#ifdef REGISTER_FILTER
- AFX_MANAGE_STATE(AfxGetStaticModuleState());
+ AFX_MANAGE_STATE(AfxGetStaticModuleState());
#endif
- bool fHideWarning = !!AfxGetApp()->GetProfileInt(_T("Settings"), _T("HideAviSplitterWarning"), 0);
-
- if(!fHideWarning && !dynamic_cast<CAviSourceFilter*>(this) || fShiftDown)
- {
- CAviReportWnd wnd;
- fHideWarning = wnd.DoModal(m_pFile, fHideWarning, fShowWarningText);
- AfxGetApp()->WriteProfileInt(_T("Settings"), _T("HideAviSplitterWarning"), fHideWarning);
- }
-
- if(fShowWarningText) hr = E_FAIL;
- }
-
- if(FAILED(hr))
- {
- m_pFile.Free();
- return hr;
- }
-
- m_rtNewStart = m_rtCurrent = 0;
- m_rtNewStop = m_rtStop = m_rtDuration = m_pFile->GetTotalTime();
-
- bool fHasIndex = false;
-
- for(DWORD i = 0; !fHasIndex && i < m_pFile->m_strms.GetCount(); i++)
- if(m_pFile->m_strms[i]->cs.GetCount() > 0)
- fHasIndex = true;
-
- for(DWORD i = 0; i < m_pFile->m_strms.GetCount(); i++)
- {
- CAviFile::strm_t* s = m_pFile->m_strms[i];
-
- if(fHasIndex && s->cs.GetCount() == 0) continue;
-
- CMediaType mt;
- CAtlArray<CMediaType> mts;
-
- CStringW name, label;
-
- if(s->strh.fccType == FCC('vids'))
- {
- label = L"Video";
-
- ASSERT(s->strf.GetCount() >= sizeof(BITMAPINFOHEADER));
-
- BITMAPINFOHEADER* pbmi = &((BITMAPINFO*)s->strf.GetData())->bmiHeader;
-
- mt.majortype = MEDIATYPE_Video;
- mt.subtype = FOURCCMap(pbmi->biCompression);
- mt.formattype = FORMAT_VideoInfo;
- VIDEOINFOHEADER* pvih = (VIDEOINFOHEADER*)mt.AllocFormatBuffer(sizeof(VIDEOINFOHEADER) + s->strf.GetCount() - sizeof(BITMAPINFOHEADER));
- memset(mt.Format(), 0, mt.FormatLength());
- memcpy(&pvih->bmiHeader, s->strf.GetData(), s->strf.GetCount());
- if(s->strh.dwRate > 0) pvih->AvgTimePerFrame = 10000000i64 * s->strh.dwScale / s->strh.dwRate;
- switch(pbmi->biCompression)
- {
- case BI_RGB:
- case BI_BITFIELDS:
- mt.subtype =
- pbmi->biBitCount == 1 ? MEDIASUBTYPE_RGB1 :
- pbmi->biBitCount == 4 ? MEDIASUBTYPE_RGB4 :
- pbmi->biBitCount == 8 ? MEDIASUBTYPE_RGB8 :
- pbmi->biBitCount == 16 ? MEDIASUBTYPE_RGB565 :
- pbmi->biBitCount == 24 ? MEDIASUBTYPE_RGB24 :
- pbmi->biBitCount == 32 ? MEDIASUBTYPE_ARGB32 :
- MEDIASUBTYPE_NULL;
- break;
+ bool fHideWarning = !!AfxGetApp()->GetProfileInt(_T("Settings"), _T("HideAviSplitterWarning"), 0);
+
+ if(!fHideWarning && !dynamic_cast<CAviSourceFilter*>(this) || fShiftDown)
+ {
+ CAviReportWnd wnd;
+ fHideWarning = wnd.DoModal(m_pFile, fHideWarning, fShowWarningText);
+ AfxGetApp()->WriteProfileInt(_T("Settings"), _T("HideAviSplitterWarning"), fHideWarning);
+ }
+
+ if(fShowWarningText) hr = E_FAIL;
+ }
+
+ if(FAILED(hr)) {m_pFile.Free(); return hr;}
+
+ m_rtNewStart = m_rtCurrent = 0;
+ m_rtNewStop = m_rtStop = m_rtDuration = m_pFile->GetTotalTime();
+
+ bool fHasIndex = false;
+
+ for(DWORD i = 0; !fHasIndex && i < m_pFile->m_strms.GetCount(); i++)
+ if(m_pFile->m_strms[i]->cs.GetCount() > 0)
+ fHasIndex = true;
+
+ for(DWORD i = 0; i < m_pFile->m_strms.GetCount(); i++)
+ {
+ CAviFile::strm_t* s = m_pFile->m_strms[i];
+
+ if(fHasIndex && s->cs.GetCount() == 0) continue;
+
+ CMediaType mt;
+ CAtlArray<CMediaType> mts;
+
+ CStringW name, label;
+
+ if(s->strh.fccType == FCC('vids'))
+ {
+ label = L"Video";
+
+ ASSERT(s->strf.GetCount() >= sizeof(BITMAPINFOHEADER));
+
+ BITMAPINFOHEADER* pbmi = &((BITMAPINFO*)s->strf.GetData())->bmiHeader;
+
+ mt.majortype = MEDIATYPE_Video;
+ mt.subtype = FOURCCMap(pbmi->biCompression);
+ mt.formattype = FORMAT_VideoInfo;
+ VIDEOINFOHEADER* pvih = (VIDEOINFOHEADER*)mt.AllocFormatBuffer(sizeof(VIDEOINFOHEADER) + s->strf.GetCount() - sizeof(BITMAPINFOHEADER));
+ memset(mt.Format(), 0, mt.FormatLength());
+ memcpy(&pvih->bmiHeader, s->strf.GetData(), s->strf.GetCount());
+ if(s->strh.dwRate > 0) pvih->AvgTimePerFrame = 10000000i64 * s->strh.dwScale / s->strh.dwRate;
+ switch(pbmi->biCompression)
+ {
+ case BI_RGB: case BI_BITFIELDS: mt.subtype =
+ pbmi->biBitCount == 1 ? MEDIASUBTYPE_RGB1 :
+ pbmi->biBitCount == 4 ? MEDIASUBTYPE_RGB4 :
+ pbmi->biBitCount == 8 ? MEDIASUBTYPE_RGB8 :
+ pbmi->biBitCount == 16 ? MEDIASUBTYPE_RGB565 :
+ pbmi->biBitCount == 24 ? MEDIASUBTYPE_RGB24 :
+ pbmi->biBitCount == 32 ? MEDIASUBTYPE_ARGB32 :
+ MEDIASUBTYPE_NULL;
+ break;
// case BI_RLE8: mt.subtype = MEDIASUBTYPE_RGB8; break;
// case BI_RLE4: mt.subtype = MEDIASUBTYPE_RGB4; break;
- }
-
- if(s->cs.GetCount() && pvih->AvgTimePerFrame > 0)
- {
- __int64 size = 0;
- for(int i = 0; i < s->cs.GetCount(); i++)
- size += s->cs[i].orgsize;
- pvih->dwBitRate = size * 8 / s->cs.GetCount() * 10000000i64 / pvih->AvgTimePerFrame;
- }
-
- mt.SetSampleSize(s->strh.dwSuggestedBufferSize > 0
- ? s->strh.dwSuggestedBufferSize * 3 / 2
- : (pvih->bmiHeader.biWidth * pvih->bmiHeader.biHeight * 4));
- mts.Add(mt);
- }
- else if(s->strh.fccType == FCC('auds') || s->strh.fccType == FCC('amva'))
- {
- label = L"Audio";
-
- ASSERT(s->strf.GetCount() >= sizeof(WAVEFORMATEX)
- || s->strf.GetCount() == sizeof(PCMWAVEFORMAT));
+ }
+
+ if(s->cs.GetCount() && pvih->AvgTimePerFrame > 0)
+ {
+ __int64 size = 0;
+ for(int i = 0; i < s->cs.GetCount(); i++)
+ size += s->cs[i].orgsize;
+ pvih->dwBitRate = size*8 / s->cs.GetCount() * 10000000i64 / pvih->AvgTimePerFrame;
+ }
+
+ mt.SetSampleSize(s->strh.dwSuggestedBufferSize > 0
+ ? s->strh.dwSuggestedBufferSize*3/2
+ : (pvih->bmiHeader.biWidth*pvih->bmiHeader.biHeight*4));
+ mts.Add(mt);
+ }
+ else if(s->strh.fccType == FCC('auds') || s->strh.fccType == FCC('amva'))
+ {
+ label = L"Audio";
+
+ ASSERT(s->strf.GetCount() >= sizeof(WAVEFORMATEX)
+ || s->strf.GetCount() == sizeof(PCMWAVEFORMAT));
WAVEFORMATEX* pwfe = (WAVEFORMATEX*)s->strf.GetData();
- if(pwfe->nBlockAlign == 0) continue;
-
- mt.majortype = MEDIATYPE_Audio;
- if(m_pFile->m_isamv)
- mt.subtype = FOURCCMap(MAKEFOURCC('A', 'M', 'V', 'A'));
- else
- mt.subtype = FOURCCMap(pwfe->wFormatTag);
- mt.formattype = FORMAT_WaveFormatEx;
- mt.SetFormat(s->strf.GetData(), max(s->strf.GetCount(), sizeof(WAVEFORMATEX)));
- pwfe = (WAVEFORMATEX*)mt.Format();
- if(s->strf.GetCount() == sizeof(PCMWAVEFORMAT)) pwfe->cbSize = 0;
- if(pwfe->wFormatTag == WAVE_FORMAT_PCM) pwfe->nBlockAlign = pwfe->nChannels * pwfe->wBitsPerSample >> 3;
- if(pwfe->wFormatTag == WAVE_FORMAT_EXTENSIBLE) mt.subtype = FOURCCMap(WAVE_FORMAT_PCM); // audio renderer doesn't accept fffe in the subtype
- mt.SetSampleSize(s->strh.dwSuggestedBufferSize > 0
- ? s->strh.dwSuggestedBufferSize * 3 / 2
- : (pwfe->nChannels * pwfe->nSamplesPerSec * 32 >> 3));
- mts.Add(mt);
- }
- else if(s->strh.fccType == FCC('mids'))
- {
- label = L"Midi";
-
- mt.majortype = MEDIATYPE_Midi;
- mt.subtype = MEDIASUBTYPE_NULL;
- mt.formattype = FORMAT_None;
- mt.SetSampleSize(s->strh.dwSuggestedBufferSize > 0
- ? s->strh.dwSuggestedBufferSize * 3 / 2
- : (1024 * 1024));
- mts.Add(mt);
- }
- else if(s->strh.fccType == FCC('txts'))
- {
- label = L"Text";
-
- mt.majortype = MEDIATYPE_Text;
- mt.subtype = MEDIASUBTYPE_NULL;
- mt.formattype = FORMAT_None;
- mt.SetSampleSize(s->strh.dwSuggestedBufferSize > 0
- ? s->strh.dwSuggestedBufferSize * 3 / 2
- : (1024 * 1024));
- mts.Add(mt);
- }
- else if(s->strh.fccType == FCC('iavs'))
- {
- label = L"Interleaved";
-
- ASSERT(s->strh.fccHandler == FCC('dvsd'));
-
- mt.majortype = MEDIATYPE_Interleaved;
- mt.subtype = FOURCCMap(s->strh.fccHandler);
- mt.formattype = FORMAT_DvInfo;
- mt.SetFormat(s->strf.GetData(), max(s->strf.GetCount(), sizeof(DVINFO)));
- mt.SetSampleSize(s->strh.dwSuggestedBufferSize > 0
- ? s->strh.dwSuggestedBufferSize * 3 / 2
- : (1024 * 1024));
- mts.Add(mt);
- }
-
- if(mts.IsEmpty())
- {
- TRACE(_T("CAviSourceFilter: Unsupported stream (%d)\n"), i);
- continue;
- }
-
- //Put filename at front sometime(eg. ~temp.avi) will cause filter graph
- //stop check this pin. Not sure the reason exactly. but it happens.
- //If you know why, please emailto: tomasen@gmail.com
- if(s->strn.IsEmpty())
- name.Format(L"%s %d", label , i);
- else
- name.Format(L"%s %d %s", label , i , CStringW(s->strn));
-
- HRESULT hr;
-
- CAutoPtr<CBaseSplitterOutputPin> pPinOut(DNew CAviSplitterOutputPin(mts, name, this, this, &hr));
- AddOutputPin(i, pPinOut);
- }
-
- POSITION pos = m_pFile->m_info.GetStartPosition();
- while(pos)
- {
- DWORD fcc;
- CStringA value;
- m_pFile->m_info.GetNextAssoc(pos, fcc, value);
+ if(pwfe->nBlockAlign == 0) continue;
+
+ mt.majortype = MEDIATYPE_Audio;
+ if (m_pFile->m_isamv)
+ mt.subtype = FOURCCMap(MAKEFOURCC('A','M','V','A'));
+ else
+ mt.subtype = FOURCCMap(pwfe->wFormatTag);
+ mt.formattype = FORMAT_WaveFormatEx;
+ mt.SetFormat(s->strf.GetData(), max(s->strf.GetCount(), sizeof(WAVEFORMATEX)));
+ pwfe = (WAVEFORMATEX*)mt.Format();
+ if(s->strf.GetCount() == sizeof(PCMWAVEFORMAT)) pwfe->cbSize = 0;
+ if(pwfe->wFormatTag == WAVE_FORMAT_PCM) pwfe->nBlockAlign = pwfe->nChannels*pwfe->wBitsPerSample>>3;
+ if(pwfe->wFormatTag == WAVE_FORMAT_EXTENSIBLE) mt.subtype = FOURCCMap(WAVE_FORMAT_PCM); // audio renderer doesn't accept fffe in the subtype
+ mt.SetSampleSize(s->strh.dwSuggestedBufferSize > 0
+ ? s->strh.dwSuggestedBufferSize*3/2
+ : (pwfe->nChannels*pwfe->nSamplesPerSec*32>>3));
+ mts.Add(mt);
+ }
+ else if(s->strh.fccType == FCC('mids'))
+ {
+ label = L"Midi";
+
+ mt.majortype = MEDIATYPE_Midi;
+ mt.subtype = MEDIASUBTYPE_NULL;
+ mt.formattype = FORMAT_None;
+ mt.SetSampleSize(s->strh.dwSuggestedBufferSize > 0
+ ? s->strh.dwSuggestedBufferSize*3/2
+ : (1024*1024));
+ mts.Add(mt);
+ }
+ else if(s->strh.fccType == FCC('txts'))
+ {
+ label = L"Text";
+
+ mt.majortype = MEDIATYPE_Text;
+ mt.subtype = MEDIASUBTYPE_NULL;
+ mt.formattype = FORMAT_None;
+ mt.SetSampleSize(s->strh.dwSuggestedBufferSize > 0
+ ? s->strh.dwSuggestedBufferSize*3/2
+ : (1024*1024));
+ mts.Add(mt);
+ }
+ else if(s->strh.fccType == FCC('iavs'))
+ {
+ label = L"Interleaved";
+
+ ASSERT(s->strh.fccHandler == FCC('dvsd'));
+
+ mt.majortype = MEDIATYPE_Interleaved;
+ mt.subtype = FOURCCMap(s->strh.fccHandler);
+ mt.formattype = FORMAT_DvInfo;
+ mt.SetFormat(s->strf.GetData(), max(s->strf.GetCount(), sizeof(DVINFO)));
+ mt.SetSampleSize(s->strh.dwSuggestedBufferSize > 0
+ ? s->strh.dwSuggestedBufferSize*3/2
+ : (1024*1024));
+ mts.Add(mt);
+ }
+
+ if(mts.IsEmpty())
+ {
+ TRACE(_T("CAviSourceFilter: Unsupported stream (%d)\n"), i);
+ continue;
+ }
+
+ //Put filename at front sometime(eg. ~temp.avi) will cause filter graph
+ //stop check this pin. Not sure the reason exactly. but it happens.
+ //If you know why, please emailto: tomasen@gmail.com
+ if(s->strn.IsEmpty())
+ name.Format(L"%s %d", label , i);
+ else
+ name.Format(L"%s %d %s", label , i , CStringW(s->strn) );
+
+ HRESULT hr;
+
+ CAutoPtr<CBaseSplitterOutputPin> pPinOut(DNew CAviSplitterOutputPin(mts, name, this, this, &hr));
+ AddOutputPin(i, pPinOut);
+ }
+
+ POSITION pos = m_pFile->m_info.GetStartPosition();
+ while(pos)
+ {
+ DWORD fcc;
+ CStringA value;
+ m_pFile->m_info.GetNextAssoc(pos, fcc, value);
switch(fcc)
- {
- case FCC('INAM'):
- SetProperty(L"TITL", CStringW(value));
- break;
- case FCC('IART'):
- SetProperty(L"AUTH", CStringW(value));
- break;
- case FCC('ICOP'):
- SetProperty(L"CPYR", CStringW(value));
- break;
- case FCC('ISBJ'):
- SetProperty(L"DESC", CStringW(value));
- break;
- }
- }
-
- m_tFrame.Attach(DNew DWORD[m_pFile->m_avih.dwStreams]);
-
- return m_pOutputs.GetCount() > 0 ? S_OK : E_FAIL;
+ {
+ case FCC('INAM'): SetProperty(L"TITL", CStringW(value)); break;
+ case FCC('IART'): SetProperty(L"AUTH", CStringW(value)); break;
+ case FCC('ICOP'): SetProperty(L"CPYR", CStringW(value)); break;
+ case FCC('ISBJ'): SetProperty(L"DESC", CStringW(value)); break;
+ }
+ }
+
+ m_tFrame.Attach(DNew DWORD[m_pFile->m_avih.dwStreams]);
+
+ return m_pOutputs.GetCount() > 0 ? S_OK : E_FAIL;
}
bool CAviSplitterFilter::DemuxInit()
{
- if(!m_pFile) return(false);
+ if(!m_pFile) return(false);
- // reindex if needed
+ // reindex if needed
- bool fReIndex = false;
+ bool fReIndex = false;
- for(int i = 0; i < (int)m_pFile->m_avih.dwStreams && !fReIndex; i++)
- {
- if(m_pFile->m_strms[i]->cs.GetCount() == 0 && GetOutputPin(i))
- fReIndex = true;
- }
+ for(int i = 0; i < (int)m_pFile->m_avih.dwStreams && !fReIndex; i++)
+ {
+ if(m_pFile->m_strms[i]->cs.GetCount() == 0 && GetOutputPin(i))
+ fReIndex = true;
+ }
- if(fReIndex)
- {
- m_pFile->EmptyIndex();
+ if(fReIndex)
+ {
+ m_pFile->EmptyIndex();
- m_fAbort = false;
- m_nOpenProgress = 0;
+ m_fAbort = false;
+ m_nOpenProgress = 0;
- m_rtDuration = 0;
+ m_rtDuration = 0;
- CAutoVectorPtr<UINT64> pSize;
- pSize.Allocate(m_pFile->m_avih.dwStreams);
- memset((UINT64*)pSize, 0, sizeof(UINT64)*m_pFile->m_avih.dwStreams);
- m_pFile->Seek(0);
+ CAutoVectorPtr<UINT64> pSize;
+ pSize.Allocate(m_pFile->m_avih.dwStreams);
+ memset((UINT64*)pSize, 0, sizeof(UINT64)*m_pFile->m_avih.dwStreams);
+ m_pFile->Seek(0);
ReIndex(m_pFile->GetLength(), pSize);
- if(m_fAbort) m_pFile->EmptyIndex();
+ if(m_fAbort) m_pFile->EmptyIndex();
- m_fAbort = false;
- m_nOpenProgress = 100;
- }
+ m_fAbort = false;
+ m_nOpenProgress = 100;
+ }
- return(true);
+ return(true);
}
HRESULT CAviSplitterFilter::ReIndex(__int64 end, UINT64* pSize)
{
- HRESULT hr = S_OK;
+ HRESULT hr = S_OK;
- while(S_OK == hr && m_pFile->GetPos() < end && SUCCEEDED(hr) && !m_fAbort)
- {
- __int64 pos = m_pFile->GetPos();
+ while(S_OK == hr && m_pFile->GetPos() < end && SUCCEEDED(hr) && !m_fAbort)
+ {
+ __int64 pos = m_pFile->GetPos();
- DWORD id = 0, size;
- if(S_OK != m_pFile->Read(id) || id == 0)
- return E_FAIL;
+ DWORD id = 0, size;
+ if(S_OK != m_pFile->Read(id) || id == 0)
+ return E_FAIL;
- if(id == FCC('RIFF') || id == FCC('LIST'))
- {
- if(S_OK != m_pFile->Read(size) || S_OK != m_pFile->Read(id))
- return E_FAIL;
+ if(id == FCC('RIFF') || id == FCC('LIST'))
+ {
+ if(S_OK != m_pFile->Read(size) || S_OK != m_pFile->Read(id))
+ return E_FAIL;
- size += (size & 1) + 8;
+ size += (size&1) + 8;
- if(id == FCC('AVI ') || id == FCC('AVIX') || id == FCC('movi') || id == FCC('rec '))
- hr = ReIndex(pos + size, pSize);
- }
- else
- {
- if(S_OK != m_pFile->Read(size))
- return E_FAIL;
+ if(id == FCC('AVI ') || id == FCC('AVIX') || id == FCC('movi') || id == FCC('rec '))
+ hr = ReIndex(pos + size, pSize);
+ }
+ else
+ {
+ if(S_OK != m_pFile->Read(size))
+ return E_FAIL;
- DWORD TrackNumber = TRACKNUM(id);
+ DWORD TrackNumber = TRACKNUM(id);
- if(TrackNumber < m_pFile->m_strms.GetCount())
- {
- CAviFile::strm_t* s = m_pFile->m_strms[TrackNumber];
+ if(TrackNumber < m_pFile->m_strms.GetCount())
+ {
+ CAviFile::strm_t* s = m_pFile->m_strms[TrackNumber];
- WORD type = TRACKTYPE(id);
+ WORD type = TRACKTYPE(id);
- if(type == 'db' || type == 'dc' || /*type == 'pc' ||*/ type == 'wb'
- || type == 'iv' || type == '__' || type == 'xx')
- {
- CAviFile::strm_t::chunk c;
- c.filepos = pos;
- c.size = pSize[TrackNumber];
- c.orgsize = size;
- c.fKeyFrame = size > 0; // TODO: find a better way...
- c.fChunkHdr = true;
- s->cs.Add(c);
+ if(type == 'db' || type == 'dc' || /*type == 'pc' ||*/ type == 'wb'
+ || type == 'iv' || type == '__' || type == 'xx')
+ {
+ CAviFile::strm_t::chunk c;
+ c.filepos = pos;
+ c.size = pSize[TrackNumber];
+ c.orgsize = size;
+ c.fKeyFrame = size > 0; // TODO: find a better way...
+ c.fChunkHdr = true;
+ s->cs.Add(c);
- pSize[TrackNumber] += s->GetChunkSize(size);
+ pSize[TrackNumber] += s->GetChunkSize(size);
- REFERENCE_TIME rt = s->GetRefTime(s->cs.GetCount() - 1, pSize[TrackNumber]);
- m_rtDuration = max(rt, m_rtDuration);
- }
- }
+ REFERENCE_TIME rt = s->GetRefTime(s->cs.GetCount()-1, pSize[TrackNumber]);
+ m_rtDuration = max(rt, m_rtDuration);
+ }
+ }
- size += (size & 1) + 8;
- }
+ size += (size&1) + 8;
+ }
- m_pFile->Seek(pos + size);
+ m_pFile->Seek(pos + size);
- m_nOpenProgress = m_pFile->GetPos() * 100 / m_pFile->GetLength();
+ m_nOpenProgress = m_pFile->GetPos()*100/m_pFile->GetLength();
- DWORD cmd;
- if(CheckRequest(&cmd))
- {
- if(cmd == CMD_EXIT) m_fAbort = true;
- else Reply(S_OK);
- }
- }
+ DWORD cmd;
+ if(CheckRequest(&cmd))
+ {
+ if(cmd == CMD_EXIT) m_fAbort = true;
+ else Reply(S_OK);
+ }
+ }
- return hr;
+ return hr;
}
void CAviSplitterFilter::DemuxSeek(REFERENCE_TIME rt)
{
- memset((DWORD*)m_tFrame, 0, sizeof(DWORD)*m_pFile->m_avih.dwStreams);
- m_pFile->Seek(0);
-
- DbgLog((LOG_TRACE, 0, _T("Seek: %I64d"), rt / 10000));
-
- if(rt > 0)
- {
- UINT64 minfp = _I64_MAX;
-
- for(int j = 0; j < (int)m_pFile->m_strms.GetCount(); j++)
- {
- CAviFile::strm_t* s = m_pFile->m_strms[j];
-
- int f = s->GetKeyFrame(rt);
- UINT64 fp = f >= 0 ? s->cs[f].filepos : m_pFile->GetLength();
-
- if(!s->IsRawSubtitleStream())
- minfp = min(minfp, fp);
- }
-
- for(int j = 0; j < (int)m_pFile->m_strms.GetCount(); j++)
- {
- CAviFile::strm_t* s = m_pFile->m_strms[j];
-
- for(int i = 0; i < s->cs.GetCount(); i++)
- {
- CAviFile::strm_t::chunk& c = s->cs[i];
- if(c.filepos >= minfp)
- {
- m_tFrame[j] = i;
- break;
- }
- }
- }
-
- DbgLog((LOG_TRACE, 0, _T("minfp: %I64d"), minfp));
- }
+ memset((DWORD*)m_tFrame, 0, sizeof(DWORD)*m_pFile->m_avih.dwStreams);
+ m_pFile->Seek(0);
+
+ DbgLog((LOG_TRACE, 0, _T("Seek: %I64d"), rt/10000));
+
+ if(rt > 0)
+ {
+ UINT64 minfp = _I64_MAX;
+
+ for(int j = 0; j < (int)m_pFile->m_strms.GetCount(); j++)
+ {
+ CAviFile::strm_t* s = m_pFile->m_strms[j];
+
+ int f = s->GetKeyFrame(rt);
+ UINT64 fp = f >= 0 ? s->cs[f].filepos : m_pFile->GetLength();
+
+ if(!s->IsRawSubtitleStream())
+ minfp = min(minfp, fp);
+ }
+
+ for(int j = 0; j < (int)m_pFile->m_strms.GetCount(); j++)
+ {
+ CAviFile::strm_t* s = m_pFile->m_strms[j];
+
+ for(int i = 0; i < s->cs.GetCount(); i++)
+ {
+ CAviFile::strm_t::chunk& c = s->cs[i];
+ if(c.filepos >= minfp)
+ {
+ m_tFrame[j] = i;
+ break;
+ }
+ }
+ }
+
+ DbgLog((LOG_TRACE, 0, _T("minfp: %I64d"), minfp));
+ }
}
bool CAviSplitterFilter::DemuxLoop()
{
- HRESULT hr = S_OK;
-
- int nTracks = (int)m_pFile->m_strms.GetCount();
-
- CAtlArray<BOOL> fDiscontinuity;
- fDiscontinuity.SetCount(nTracks);
- memset(fDiscontinuity.GetData(), 0, nTracks * sizeof(bool));
-
- while(SUCCEEDED(hr) && !CheckRequest(NULL))
- {
- int minTrack = nTracks;
- UINT64 minFilePos = _I64_MAX;
-
- for(int i = 0; i < nTracks; i++)
- {
- CAviFile::strm_t* s = m_pFile->m_strms[i];
-
- DWORD f = m_tFrame[i];
- if(f >= (DWORD)s->cs.GetCount()) continue;
-
- bool fUrgent = s->IsRawSubtitleStream();
-
- if(fUrgent || s->cs[f].filepos < minFilePos)
- {
- minTrack = i;
- minFilePos = s->cs[f].filepos;
- }
-
- if(fUrgent) break;
- }
-
- if(minTrack == nTracks)
- break;
-
- DWORD& f = m_tFrame[minTrack];
-
- do
- {
- CAviFile::strm_t* s = m_pFile->m_strms[minTrack];
-
- m_pFile->Seek(s->cs[f].filepos);
-
- DWORD size = 0;
-
- if(s->cs[f].fChunkHdr)
- {
- DWORD id = 0;
- if(S_OK != m_pFile->Read(id) || id == 0 || minTrack != TRACKNUM(id)
- || S_OK != m_pFile->Read(size))
- {
- fDiscontinuity[minTrack] = true;
- break;
- }
-
- UINT64 expectedsize = -1;
- expectedsize = f < (DWORD)s->cs.GetCount() - 1
- ? s->cs[f+1].size - s->cs[f].size
- : s->totalsize - s->cs[f].size;
-
- if(expectedsize != s->GetChunkSize(size))
- {
- fDiscontinuity[minTrack] = true;
- // ASSERT(0);
- break;
- }
- }
- else
- {
- size = s->cs[f].orgsize;
- }
-
- CAutoPtr<Packet> p(DNew Packet());
-
- p->TrackNumber = minTrack;
- p->bSyncPoint = (BOOL)s->cs[f].fKeyFrame;
- p->bDiscontinuity = fDiscontinuity[minTrack];
- p->rtStart = s->GetRefTime(f, s->cs[f].size);
- p->rtStop = s->GetRefTime(f + 1, f + 1 < (DWORD)s->cs.GetCount() ? s->cs[f+1].size : s->totalsize);
-
- p->SetCount(size);
- if(S_OK != (hr = m_pFile->ByteRead(p->GetData(), p->GetCount())))
- return(true); // break;
- /*
- DbgLog((LOG_TRACE, 0, _T("%d (%d): %I64d - %I64d, %I64d - %I64d (size = %d)"),
- minTrack, (int)p->bSyncPoint,
- (p->rtStart)/10000, (p->rtStop)/10000,
- (p->rtStart-m_rtStart)/10000, (p->rtStop-m_rtStart)/10000,
- size));
- */
- hr = DeliverPacket(p);
-
- fDiscontinuity[minTrack] = false;
- }
- while(0);
-
- f++;
- }
-
- return(true);
+ HRESULT hr = S_OK;
+
+ int nTracks = (int)m_pFile->m_strms.GetCount();
+
+ CAtlArray<BOOL> fDiscontinuity;
+ fDiscontinuity.SetCount(nTracks);
+ memset(fDiscontinuity.GetData(), 0, nTracks*sizeof(bool));
+
+ while(SUCCEEDED(hr) && !CheckRequest(NULL))
+ {
+ int minTrack = nTracks;
+ UINT64 minFilePos = _I64_MAX;
+
+ for(int i = 0; i < nTracks; i++)
+ {
+ CAviFile::strm_t* s = m_pFile->m_strms[i];
+
+ DWORD f = m_tFrame[i];
+ if(f >= (DWORD)s->cs.GetCount()) continue;
+
+ bool fUrgent = s->IsRawSubtitleStream();
+
+ if(fUrgent || s->cs[f].filepos < minFilePos)
+ {
+ minTrack = i;
+ minFilePos = s->cs[f].filepos;
+ }
+
+ if(fUrgent) break;
+ }
+
+ if(minTrack == nTracks)
+ break;
+
+ DWORD& f = m_tFrame[minTrack];
+
+ do
+ {
+ CAviFile::strm_t* s = m_pFile->m_strms[minTrack];
+
+ m_pFile->Seek(s->cs[f].filepos);
+
+ DWORD size = 0;
+
+ if(s->cs[f].fChunkHdr)
+ {
+ DWORD id = 0;
+ if(S_OK != m_pFile->Read(id) || id == 0 || minTrack != TRACKNUM(id)
+ || S_OK != m_pFile->Read(size))
+ {
+ fDiscontinuity[minTrack] = true;
+ break;
+ }
+
+ UINT64 expectedsize = -1;
+ expectedsize = f < (DWORD)s->cs.GetCount()-1
+ ? s->cs[f+1].size - s->cs[f].size
+ : s->totalsize - s->cs[f].size;
+
+ if(expectedsize != s->GetChunkSize(size))
+ {
+ fDiscontinuity[minTrack] = true;
+ // ASSERT(0);
+ break;
+ }
+ }
+ else
+ {
+ size = s->cs[f].orgsize;
+ }
+
+ CAutoPtr<Packet> p(DNew Packet());
+
+ p->TrackNumber = minTrack;
+ p->bSyncPoint = (BOOL)s->cs[f].fKeyFrame;
+ p->bDiscontinuity = fDiscontinuity[minTrack];
+ p->rtStart = s->GetRefTime(f, s->cs[f].size);
+ p->rtStop = s->GetRefTime(f+1, f+1 < (DWORD)s->cs.GetCount() ? s->cs[f+1].size : s->totalsize);
+
+ p->SetCount(size);
+ if(S_OK != (hr = m_pFile->ByteRead(p->GetData(), p->GetCount())))
+ return(true); // break;
+/*
+ DbgLog((LOG_TRACE, 0, _T("%d (%d): %I64d - %I64d, %I64d - %I64d (size = %d)"),
+ minTrack, (int)p->bSyncPoint,
+ (p->rtStart)/10000, (p->rtStop)/10000,
+ (p->rtStart-m_rtStart)/10000, (p->rtStop-m_rtStart)/10000,
+ size));
+*/
+ hr = DeliverPacket(p);
+
+ fDiscontinuity[minTrack] = false;
+ }
+ while(0);
+
+ f++;
+ }
+
+ return(true);
}
// IMediaSeeking
STDMETHODIMP CAviSplitterFilter::GetDuration(LONGLONG* pDuration)
{
- CheckPointer(pDuration, E_POINTER);
- CheckPointer(m_pFile, VFW_E_NOT_CONNECTED);
-
- if(m_timeformat == TIME_FORMAT_FRAME)
- {
- for(int i = 0; i < (int)m_pFile->m_strms.GetCount(); i++)
- {
- CAviFile::strm_t* s = m_pFile->m_strms[i];
- if(s->strh.fccType == FCC('vids'))
- {
- *pDuration = s->cs.GetCount();
- return S_OK;
- }
- }
-
- return E_UNEXPECTED;
- }
-
- return __super::GetDuration(pDuration);
+ CheckPointer(pDuration, E_POINTER);
+ CheckPointer(m_pFile, VFW_E_NOT_CONNECTED);
+
+ if(m_timeformat == TIME_FORMAT_FRAME)
+ {
+ for(int i = 0; i < (int)m_pFile->m_strms.GetCount(); i++)
+ {
+ CAviFile::strm_t* s = m_pFile->m_strms[i];
+ if(s->strh.fccType == FCC('vids'))
+ {
+ *pDuration = s->cs.GetCount();
+ return S_OK;
+ }
+ }
+
+ return E_UNEXPECTED;
+ }
+
+ return __super::GetDuration(pDuration);
}
//
STDMETHODIMP CAviSplitterFilter::IsFormatSupported(const GUID* pFormat)
{
- CheckPointer(pFormat, E_POINTER);
- HRESULT hr = __super::IsFormatSupported(pFormat);
- if(S_OK == hr) return hr;
- return *pFormat == TIME_FORMAT_FRAME ? S_OK : S_FALSE;
+ CheckPointer(pFormat, E_POINTER);
+ HRESULT hr = __super::IsFormatSupported(pFormat);
+ if(S_OK == hr) return hr;
+ return *pFormat == TIME_FORMAT_FRAME ? S_OK : S_FALSE;
}
STDMETHODIMP CAviSplitterFilter::GetTimeFormat(GUID* pFormat)
{
- CheckPointer(pFormat, E_POINTER);
- *pFormat = m_timeformat;
- return S_OK;
+ CheckPointer(pFormat, E_POINTER);
+ *pFormat = m_timeformat;
+ return S_OK;
}
STDMETHODIMP CAviSplitterFilter::IsUsingTimeFormat(const GUID* pFormat)
{
- CheckPointer(pFormat, E_POINTER);
- return *pFormat == m_timeformat ? S_OK : S_FALSE;
+ CheckPointer(pFormat, E_POINTER);
+ return *pFormat == m_timeformat ? S_OK : S_FALSE;
}
STDMETHODIMP CAviSplitterFilter::SetTimeFormat(const GUID* pFormat)
{
- CheckPointer(pFormat, E_POINTER);
- if(S_OK != IsFormatSupported(pFormat)) return E_FAIL;
- m_timeformat = *pFormat;
- return S_OK;
+ CheckPointer(pFormat, E_POINTER);
+ if(S_OK != IsFormatSupported(pFormat)) return E_FAIL;
+ m_timeformat = *pFormat;
+ return S_OK;
}
STDMETHODIMP CAviSplitterFilter::GetStopPosition(LONGLONG* pStop)
{
- CheckPointer(pStop, E_POINTER);
- if(FAILED(__super::GetStopPosition(pStop))) return E_FAIL;
- if(m_timeformat == TIME_FORMAT_MEDIA_TIME) return S_OK;
- LONGLONG rt = *pStop;
- if(FAILED(ConvertTimeFormat(pStop, &TIME_FORMAT_FRAME, rt, &TIME_FORMAT_MEDIA_TIME))) return E_FAIL;
- return S_OK;
+ CheckPointer(pStop, E_POINTER);
+ if(FAILED(__super::GetStopPosition(pStop))) return E_FAIL;
+ if(m_timeformat == TIME_FORMAT_MEDIA_TIME) return S_OK;
+ LONGLONG rt = *pStop;
+ if(FAILED(ConvertTimeFormat(pStop, &TIME_FORMAT_FRAME, rt, &TIME_FORMAT_MEDIA_TIME))) return E_FAIL;
+ return S_OK;
}
STDMETHODIMP CAviSplitterFilter::ConvertTimeFormat(LONGLONG* pTarget, const GUID* pTargetFormat, LONGLONG Source, const GUID* pSourceFormat)
{
- CheckPointer(pTarget, E_POINTER);
-
- const GUID& SourceFormat = pSourceFormat ? *pSourceFormat : m_timeformat;
- const GUID& TargetFormat = pTargetFormat ? *pTargetFormat : m_timeformat;
-
- if(TargetFormat == SourceFormat)
- {
- *pTarget = Source;
- return S_OK;
- }
- else if(TargetFormat == TIME_FORMAT_FRAME && SourceFormat == TIME_FORMAT_MEDIA_TIME)
- {
- for(int i = 0; i < (int)m_pFile->m_strms.GetCount(); i++)
- {
- CAviFile::strm_t* s = m_pFile->m_strms[i];
- if(s->strh.fccType == FCC('vids'))
- {
- *pTarget = s->GetFrame(Source);
- return S_OK;
- }
- }
- }
- else if(TargetFormat == TIME_FORMAT_MEDIA_TIME && SourceFormat == TIME_FORMAT_FRAME)
- {
- for(int i = 0; i < (int)m_pFile->m_strms.GetCount(); i++)
- {
- CAviFile::strm_t* s = m_pFile->m_strms[i];
- if(s->strh.fccType == FCC('vids'))
- {
- if(Source < 0 || Source >= s->cs.GetCount()) return E_FAIL;
- CAviFile::strm_t::chunk& c = s->cs[(int)Source];
- *pTarget = s->GetRefTime((DWORD)Source, c.size);
- return S_OK;
- }
- }
- }
-
- return E_FAIL;
+ CheckPointer(pTarget, E_POINTER);
+
+ const GUID& SourceFormat = pSourceFormat ? *pSourceFormat : m_timeformat;
+ const GUID& TargetFormat = pTargetFormat ? *pTargetFormat : m_timeformat;
+
+ if(TargetFormat == SourceFormat)
+ {
+ *pTarget = Source;
+ return S_OK;
+ }
+ else if(TargetFormat == TIME_FORMAT_FRAME && SourceFormat == TIME_FORMAT_MEDIA_TIME)
+ {
+ for(int i = 0; i < (int)m_pFile->m_strms.GetCount(); i++)
+ {
+ CAviFile::strm_t* s = m_pFile->m_strms[i];
+ if(s->strh.fccType == FCC('vids'))
+ {
+ *pTarget = s->GetFrame(Source);
+ return S_OK;
+ }
+ }
+ }
+ else if(TargetFormat == TIME_FORMAT_MEDIA_TIME && SourceFormat == TIME_FORMAT_FRAME)
+ {
+ for(int i = 0; i < (int)m_pFile->m_strms.GetCount(); i++)
+ {
+ CAviFile::strm_t* s = m_pFile->m_strms[i];
+ if(s->strh.fccType == FCC('vids'))
+ {
+ if(Source < 0 || Source >= s->cs.GetCount()) return E_FAIL;
+ CAviFile::strm_t::chunk& c = s->cs[(int)Source];
+ *pTarget = s->GetRefTime((DWORD)Source, c.size);
+ return S_OK;
+ }
+ }
+ }
+
+ return E_FAIL;
}
STDMETHODIMP CAviSplitterFilter::GetPositions(LONGLONG* pCurrent, LONGLONG* pStop)
{
- HRESULT hr;
- if(FAILED(hr = __super::GetPositions(pCurrent, pStop)) || m_timeformat != TIME_FORMAT_FRAME)
- return hr;
+ HRESULT hr;
+ if(FAILED(hr = __super::GetPositions(pCurrent, pStop)) || m_timeformat != TIME_FORMAT_FRAME)
+ return hr;
- if(pCurrent)
- if(FAILED(ConvertTimeFormat(pCurrent, &TIME_FORMAT_FRAME, *pCurrent, &TIME_FORMAT_MEDIA_TIME))) return E_FAIL;
- if(pStop)
- if(FAILED(ConvertTimeFormat(pStop, &TIME_FORMAT_FRAME, *pStop, &TIME_FORMAT_MEDIA_TIME))) return E_FAIL;
+ if(pCurrent)
+ if(FAILED(ConvertTimeFormat(pCurrent, &TIME_FORMAT_FRAME, *pCurrent, &TIME_FORMAT_MEDIA_TIME))) return E_FAIL;
+ if(pStop)
+ if(FAILED(ConvertTimeFormat(pStop, &TIME_FORMAT_FRAME, *pStop, &TIME_FORMAT_MEDIA_TIME))) return E_FAIL;
- return S_OK;
+ return S_OK;
}
HRESULT CAviSplitterFilter::SetPositionsInternal(void* id, LONGLONG* pCurrent, DWORD dwCurrentFlags, LONGLONG* pStop, DWORD dwStopFlags)
{
- if(m_timeformat != TIME_FORMAT_FRAME)
- return __super::SetPositionsInternal(id, pCurrent, dwCurrentFlags, pStop, dwStopFlags);
-
- if(!pCurrent && !pStop
- || (dwCurrentFlags & AM_SEEKING_PositioningBitsMask) == AM_SEEKING_NoPositioning
- && (dwStopFlags & AM_SEEKING_PositioningBitsMask) == AM_SEEKING_NoPositioning)
- return S_OK;
-
- REFERENCE_TIME
- rtCurrent = m_rtCurrent,
- rtStop = m_rtStop;
-
- if((dwCurrentFlags & AM_SEEKING_PositioningBitsMask)
- && FAILED(ConvertTimeFormat(&rtCurrent, &TIME_FORMAT_FRAME, rtCurrent, &TIME_FORMAT_MEDIA_TIME)))
- return E_FAIL;
- if((dwStopFlags & AM_SEEKING_PositioningBitsMask)
- && FAILED(ConvertTimeFormat(&rtStop, &TIME_FORMAT_FRAME, rtStop, &TIME_FORMAT_MEDIA_TIME)))
- return E_FAIL;
-
- if(pCurrent)
- switch(dwCurrentFlags & AM_SEEKING_PositioningBitsMask)
- {
- case AM_SEEKING_NoPositioning:
- break;
- case AM_SEEKING_AbsolutePositioning:
- rtCurrent = *pCurrent;
- break;
- case AM_SEEKING_RelativePositioning:
- rtCurrent = rtCurrent + *pCurrent;
- break;
- case AM_SEEKING_IncrementalPositioning:
- rtCurrent = rtCurrent + *pCurrent;
- break;
- }
-
- if(pStop)
- switch(dwStopFlags & AM_SEEKING_PositioningBitsMask)
- {
- case AM_SEEKING_NoPositioning:
- break;
- case AM_SEEKING_AbsolutePositioning:
- rtStop = *pStop;
- break;
- case AM_SEEKING_RelativePositioning:
- rtStop += *pStop;
- break;
- case AM_SEEKING_IncrementalPositioning:
- rtStop = rtCurrent + *pStop;
- break;
- }
-
- if((dwCurrentFlags & AM_SEEKING_PositioningBitsMask)
- && pCurrent)
- if(FAILED(ConvertTimeFormat(pCurrent, &TIME_FORMAT_MEDIA_TIME, rtCurrent, &TIME_FORMAT_FRAME))) return E_FAIL;
- if((dwStopFlags & AM_SEEKING_PositioningBitsMask)
- && pStop)
- if(FAILED(ConvertTimeFormat(pStop, &TIME_FORMAT_MEDIA_TIME, rtStop, &TIME_FORMAT_FRAME))) return E_FAIL;
-
- return __super::SetPositionsInternal(id, pCurrent, dwCurrentFlags, pStop, dwStopFlags);
+ if(m_timeformat != TIME_FORMAT_FRAME)
+ return __super::SetPositionsInternal(id, pCurrent, dwCurrentFlags, pStop, dwStopFlags);
+
+ if(!pCurrent && !pStop
+ || (dwCurrentFlags&AM_SEEKING_PositioningBitsMask) == AM_SEEKING_NoPositioning
+ && (dwStopFlags&AM_SEEKING_PositioningBitsMask) == AM_SEEKING_NoPositioning)
+ return S_OK;
+
+ REFERENCE_TIME
+ rtCurrent = m_rtCurrent,
+ rtStop = m_rtStop;
+
+ if((dwCurrentFlags&AM_SEEKING_PositioningBitsMask)
+ && FAILED(ConvertTimeFormat(&rtCurrent, &TIME_FORMAT_FRAME, rtCurrent, &TIME_FORMAT_MEDIA_TIME)))
+ return E_FAIL;
+ if((dwStopFlags&AM_SEEKING_PositioningBitsMask)
+ && FAILED(ConvertTimeFormat(&rtStop, &TIME_FORMAT_FRAME, rtStop, &TIME_FORMAT_MEDIA_TIME)))
+ return E_FAIL;
+
+ if(pCurrent)
+ switch(dwCurrentFlags&AM_SEEKING_PositioningBitsMask)
+ {
+ case AM_SEEKING_NoPositioning: break;
+ case AM_SEEKING_AbsolutePositioning: rtCurrent = *pCurrent; break;
+ case AM_SEEKING_RelativePositioning: rtCurrent = rtCurrent + *pCurrent; break;
+ case AM_SEEKING_IncrementalPositioning: rtCurrent = rtCurrent + *pCurrent; break;
+ }
+
+ if(pStop)
+ switch(dwStopFlags&AM_SEEKING_PositioningBitsMask)
+ {
+ case AM_SEEKING_NoPositioning: break;
+ case AM_SEEKING_AbsolutePositioning: rtStop = *pStop; break;
+ case AM_SEEKING_RelativePositioning: rtStop += *pStop; break;
+ case AM_SEEKING_IncrementalPositioning: rtStop = rtCurrent + *pStop; break;
+ }
+
+ if((dwCurrentFlags&AM_SEEKING_PositioningBitsMask)
+ && pCurrent)
+ if(FAILED(ConvertTimeFormat(pCurrent, &TIME_FORMAT_MEDIA_TIME, rtCurrent, &TIME_FORMAT_FRAME))) return E_FAIL;
+ if((dwStopFlags&AM_SEEKING_PositioningBitsMask)
+ && pStop)
+ if(FAILED(ConvertTimeFormat(pStop, &TIME_FORMAT_MEDIA_TIME, rtStop, &TIME_FORMAT_FRAME))) return E_FAIL;
+
+ return __super::SetPositionsInternal(id, pCurrent, dwCurrentFlags, pStop, dwStopFlags);
}
// IKeyFrameInfo
STDMETHODIMP CAviSplitterFilter::GetKeyFrameCount(UINT& nKFs)
{
- if(!m_pFile) return E_UNEXPECTED;
+ if(!m_pFile) return E_UNEXPECTED;
- HRESULT hr = S_OK;
+ HRESULT hr = S_OK;
- nKFs = 0;
+ nKFs = 0;
- for(int i = 0; i < (int)m_pFile->m_strms.GetCount(); i++)
- {
- CAviFile::strm_t* s = m_pFile->m_strms[i];
- if(s->strh.fccType != FCC('vids')) continue;
+ for(int i = 0; i < (int)m_pFile->m_strms.GetCount(); i++)
+ {
+ CAviFile::strm_t* s = m_pFile->m_strms[i];
+ if(s->strh.fccType != FCC('vids')) continue;
- for(int j = 0; j < s->cs.GetCount(); j++)
- {
- CAviFile::strm_t::chunk& c = s->cs[j];
- if(c.fKeyFrame) nKFs++;
- }
+ for(int j = 0; j < s->cs.GetCount(); j++)
+ {
+ CAviFile::strm_t::chunk& c = s->cs[j];
+ if(c.fKeyFrame) nKFs++;
+ }
- if(nKFs == s->cs.GetCount())
- hr = S_FALSE;
+ if(nKFs == s->cs.GetCount())
+ hr = S_FALSE;
- break;
- }
+ break;
+ }
- return hr;
+ return hr;
}
STDMETHODIMP CAviSplitterFilter::GetKeyFrames(const GUID* pFormat, REFERENCE_TIME* pKFs, UINT& nKFs)
{
- CheckPointer(pFormat, E_POINTER);
- CheckPointer(pKFs, E_POINTER);
+ CheckPointer(pFormat, E_POINTER);
+ CheckPointer(pKFs, E_POINTER);
- if(!m_pFile) return E_UNEXPECTED;
- if(*pFormat != TIME_FORMAT_MEDIA_TIME && *pFormat != TIME_FORMAT_FRAME) return E_INVALIDARG;
+ if(!m_pFile) return E_UNEXPECTED;
+ if(*pFormat != TIME_FORMAT_MEDIA_TIME && *pFormat != TIME_FORMAT_FRAME) return E_INVALIDARG;
- UINT nKFsTmp = 0;
+ UINT nKFsTmp = 0;
- for(int i = 0; i < (int)m_pFile->m_strms.GetCount(); i++)
- {
- CAviFile::strm_t* s = m_pFile->m_strms[i];
- if(s->strh.fccType != FCC('vids')) continue;
+ for(int i = 0; i < (int)m_pFile->m_strms.GetCount(); i++)
+ {
+ CAviFile::strm_t* s = m_pFile->m_strms[i];
+ if(s->strh.fccType != FCC('vids')) continue;
- bool fConvertToRefTime = !!(*pFormat == TIME_FORMAT_MEDIA_TIME);
+ bool fConvertToRefTime = !!(*pFormat == TIME_FORMAT_MEDIA_TIME);
- for(int j = 0; j < s->cs.GetCount() && nKFsTmp < nKFs; j++)
- {
- if(s->cs[j].fKeyFrame)
- pKFs[nKFsTmp++] = fConvertToRefTime ? s->GetRefTime(j, s->cs[j].size) : j;
- }
+ for(int j = 0; j < s->cs.GetCount() && nKFsTmp < nKFs; j++)
+ {
+ if(s->cs[j].fKeyFrame)
+ pKFs[nKFsTmp++] = fConvertToRefTime ? s->GetRefTime(j, s->cs[j].size) : j;
+ }
- break;
- }
+ break;
+ }
- nKFs = nKFsTmp;
+ nKFs = nKFsTmp;
- return S_OK;
+ return S_OK;
}
//
@@ -854,10 +826,10 @@ STDMETHODIMP CAviSplitterFilter::GetKeyFrames(const GUID* pFormat, REFERENCE_TIM
//
CAviSourceFilter::CAviSourceFilter(LPUNKNOWN pUnk, HRESULT* phr)
- : CAviSplitterFilter(pUnk, phr)
+ : CAviSplitterFilter(pUnk, phr)
{
- m_clsid = __uuidof(this);
- m_pInput.Free();
+ m_clsid = __uuidof(this);
+ m_pInput.Free();
}
//
@@ -865,29 +837,29 @@ CAviSourceFilter::CAviSourceFilter(LPUNKNOWN pUnk, HRESULT* phr)
//
CAviSplitterOutputPin::CAviSplitterOutputPin(CAtlArray<CMediaType>& mts, LPCWSTR pName, CBaseFilter* pFilter, CCritSec* pLock, HRESULT* phr)
- : CBaseSplitterOutputPin(mts, pName, pFilter, pLock, phr)
+ : CBaseSplitterOutputPin(mts, pName, pFilter, pLock, phr)
{
}
HRESULT CAviSplitterOutputPin::CheckConnect(IPin* pPin)
{
- int iPosition = 0;
- CMediaType mt;
- while(S_OK == GetMediaType(iPosition++, &mt))
- {
- if(mt.majortype == MEDIATYPE_Video
- && (mt.subtype == FOURCCMap(FCC('IV32'))
- || mt.subtype == FOURCCMap(FCC('IV31'))
- || mt.subtype == FOURCCMap(FCC('IF09'))))
- {
- CLSID clsid = GetCLSID(GetFilterFromPin(pPin));
- if(clsid == CLSID_VideoMixingRenderer || clsid == CLSID_OverlayMixer)
- return E_FAIL;
- }
-
- mt.InitMediaType();
- }
-
- return __super::CheckConnect(pPin);
+ int iPosition = 0;
+ CMediaType mt;
+ while(S_OK == GetMediaType(iPosition++, &mt))
+ {
+ if(mt.majortype == MEDIATYPE_Video
+ && (mt.subtype == FOURCCMap(FCC('IV32'))
+ || mt.subtype == FOURCCMap(FCC('IV31'))
+ || mt.subtype == FOURCCMap(FCC('IF09'))))
+ {
+ CLSID clsid = GetCLSID(GetFilterFromPin(pPin));
+ if(clsid == CLSID_VideoMixingRenderer || clsid == CLSID_OverlayMixer)
+ return E_FAIL;
+ }
+
+ mt.InitMediaType();
+ }
+
+ return __super::CheckConnect(pPin);
}
diff --git a/src/filters/parser/AviSplitter/AviSplitter.h b/src/filters/parser/AviSplitter/AviSplitter.h
index d8e59040b..f3e0c50cf 100644
--- a/src/filters/parser/AviSplitter/AviSplitter.h
+++ b/src/filters/parser/AviSplitter/AviSplitter.h
@@ -1,4 +1,4 @@
-/*
+/*
* Copyright (C) 2003-2006 Gabest
* http://www.gabest.org
*
@@ -6,15 +6,15 @@
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2, or (at your option)
* any later version.
- *
+ *
* This Program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with GNU Make; see the file COPYING. If not, write to
- * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
+ * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
* http://www.gnu.org/copyleft/gpl.html
*
*/
@@ -30,57 +30,57 @@ class CAviFile;
class CAviSplitterOutputPin : public CBaseSplitterOutputPin
{
public:
- CAviSplitterOutputPin(CAtlArray<CMediaType>& mts, LPCWSTR pName, CBaseFilter* pFilter, CCritSec* pLock, HRESULT* phr);
+ CAviSplitterOutputPin(CAtlArray<CMediaType>& mts, LPCWSTR pName, CBaseFilter* pFilter, CCritSec* pLock, HRESULT* phr);
- HRESULT CheckConnect(IPin* pPin);
+ HRESULT CheckConnect(IPin* pPin);
};
[uuid("9736D831-9D6C-4E72-B6E7-560EF9181001")]
class CAviSplitterFilter : public CBaseSplitterFilter
{
- CAutoVectorPtr<DWORD> m_tFrame;
+ CAutoVectorPtr<DWORD> m_tFrame;
protected:
- CAutoPtr<CAviFile> m_pFile;
- HRESULT CreateOutputs(IAsyncReader* pAsyncReader);
+ CAutoPtr<CAviFile> m_pFile;
+ HRESULT CreateOutputs(IAsyncReader* pAsyncReader);
- bool DemuxInit();
- void DemuxSeek(REFERENCE_TIME rt);
- bool DemuxLoop();
+ bool DemuxInit();
+ void DemuxSeek(REFERENCE_TIME rt);
+ bool DemuxLoop();
- HRESULT ReIndex(__int64 end, UINT64* pSize);
+ HRESULT ReIndex(__int64 end, UINT64* pSize);
public:
- CAviSplitterFilter(LPUNKNOWN pUnk, HRESULT* phr);
+ CAviSplitterFilter(LPUNKNOWN pUnk, HRESULT* phr);
- DECLARE_IUNKNOWN;
+ DECLARE_IUNKNOWN;
STDMETHODIMP NonDelegatingQueryInterface(REFIID riid, void** ppv);
- // IMediaSeeking
+ // IMediaSeeking
- STDMETHODIMP GetDuration(LONGLONG* pDuration);
+ STDMETHODIMP GetDuration(LONGLONG* pDuration);
- // TODO: this is too ugly, integrate this with the baseclass somehow
- GUID m_timeformat;
- STDMETHODIMP IsFormatSupported(const GUID* pFormat);
- STDMETHODIMP GetTimeFormat(GUID* pFormat);
- STDMETHODIMP IsUsingTimeFormat(const GUID* pFormat);
- STDMETHODIMP SetTimeFormat(const GUID* pFormat);
- STDMETHODIMP GetStopPosition(LONGLONG* pStop);
- STDMETHODIMP ConvertTimeFormat(LONGLONG* pTarget, const GUID* pTargetFormat, LONGLONG Source, const GUID* pSourceFormat);
- STDMETHODIMP GetPositions(LONGLONG* pCurrent, LONGLONG* pStop);
+ // TODO: this is too ugly, integrate this with the baseclass somehow
+ GUID m_timeformat;
+ STDMETHODIMP IsFormatSupported(const GUID* pFormat);
+ STDMETHODIMP GetTimeFormat(GUID* pFormat);
+ STDMETHODIMP IsUsingTimeFormat(const GUID* pFormat);
+ STDMETHODIMP SetTimeFormat(const GUID* pFormat);
+ STDMETHODIMP GetStopPosition(LONGLONG* pStop);
+ STDMETHODIMP ConvertTimeFormat(LONGLONG* pTarget, const GUID* pTargetFormat, LONGLONG Source, const GUID* pSourceFormat);
+ STDMETHODIMP GetPositions(LONGLONG* pCurrent, LONGLONG* pStop);
- HRESULT SetPositionsInternal(void* id, LONGLONG* pCurrent, DWORD dwCurrentFlags, LONGLONG* pStop, DWORD dwStopFlags);
+ HRESULT SetPositionsInternal(void* id, LONGLONG* pCurrent, DWORD dwCurrentFlags, LONGLONG* pStop, DWORD dwStopFlags);
- // IKeyFrameInfo
+ // IKeyFrameInfo
- STDMETHODIMP GetKeyFrameCount(UINT& nKFs);
- STDMETHODIMP GetKeyFrames(const GUID* pFormat, REFERENCE_TIME* pKFs, UINT& nKFs);
+ STDMETHODIMP GetKeyFrameCount(UINT& nKFs);
+ STDMETHODIMP GetKeyFrames(const GUID* pFormat, REFERENCE_TIME* pKFs, UINT& nKFs);
};
[uuid("CEA8DEFF-0AF7-4DB9-9A38-FB3C3AEFC0DE")]
class CAviSourceFilter : public CAviSplitterFilter
{
public:
- CAviSourceFilter(LPUNKNOWN pUnk, HRESULT* phr);
+ CAviSourceFilter(LPUNKNOWN pUnk, HRESULT* phr);
};
diff --git a/src/filters/parser/AviSplitter/resource.h b/src/filters/parser/AviSplitter/resource.h
index 80a8d5879..f29274003 100644
--- a/src/filters/parser/AviSplitter/resource.h
+++ b/src/filters/parser/AviSplitter/resource.h
@@ -3,7 +3,7 @@
// Used by AviSplitter.rc
// Next default values for new objects
-//
+//
#ifdef APSTUDIO_INVOKED
#ifndef APSTUDIO_READONLY_SYMBOLS
#define _APS_NEXT_RESOURCE_VALUE 101
diff --git a/src/filters/parser/AviSplitter/stdafx.cpp b/src/filters/parser/AviSplitter/stdafx.cpp
index 793af597c..c356f5dba 100644
--- a/src/filters/parser/AviSplitter/stdafx.cpp
+++ b/src/filters/parser/AviSplitter/stdafx.cpp
@@ -1,4 +1,4 @@
-/*
+/*
* Copyright (C) 2003-2006 Gabest
* http://www.gabest.org
*
@@ -6,15 +6,15 @@
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2, or (at your option)
* any later version.
- *
+ *
* This Program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with GNU Make; see the file COPYING. If not, write to
- * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
+ * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
* http://www.gnu.org/copyleft/gpl.html
*
*/
diff --git a/src/filters/parser/AviSplitter/stdafx.h b/src/filters/parser/AviSplitter/stdafx.h
index ec6ed9d77..5f53f59b5 100644
--- a/src/filters/parser/AviSplitter/stdafx.h
+++ b/src/filters/parser/AviSplitter/stdafx.h
@@ -1,4 +1,4 @@
-/*
+/*
* Copyright (C) 2003-2006 Gabest
* http://www.gabest.org
*
@@ -6,15 +6,15 @@
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2, or (at your option)
* any later version.
- *
+ *
* This Program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with GNU Make; see the file COPYING. If not, write to
- * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
+ * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
* http://www.gnu.org/copyleft/gpl.html
*
*/
diff --git a/src/filters/parser/BaseSplitter/AsyncReader.cpp b/src/filters/parser/BaseSplitter/AsyncReader.cpp
index 99161206f..2231aa440 100644
--- a/src/filters/parser/BaseSplitter/AsyncReader.cpp
+++ b/src/filters/parser/BaseSplitter/AsyncReader.cpp
@@ -1,4 +1,4 @@
-/*
+/*
* Copyright (C) 2003-2006 Gabest
* http://www.gabest.org
*
@@ -6,15 +6,15 @@
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2, or (at your option)
* any later version.
- *
+ *
* This Program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with GNU Make; see the file COPYING. If not, write to
- * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
+ * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
* http://www.gnu.org/copyleft/gpl.html
*
*/
@@ -30,205 +30,187 @@
// CAsyncFileReader
//
-CAsyncFileReader::CAsyncFileReader(CString fn, HRESULT& hr)
- : CUnknown(NAME("CAsyncFileReader"), NULL, &hr)
- , m_len(-1)
- , m_hBreakEvent(NULL)
- , m_lOsError(0)
+CAsyncFileReader::CAsyncFileReader(CString fn, HRESULT& hr)
+ : CUnknown(NAME("CAsyncFileReader"), NULL, &hr)
+ , m_len(-1)
+ , m_hBreakEvent(NULL)
+ , m_lOsError(0)
{
- hr = Open(fn, modeRead | shareDenyNone | typeBinary | osSequentialScan) ? S_OK : E_FAIL;
- if(SUCCEEDED(hr)) m_len = GetLength();
+ hr = Open(fn, modeRead|shareDenyNone|typeBinary|osSequentialScan) ? S_OK : E_FAIL;
+ if(SUCCEEDED(hr)) m_len = GetLength();
}
-CAsyncFileReader::CAsyncFileReader(CAtlList<CHdmvClipInfo::PlaylistItem>& Items, HRESULT& hr)
- : CUnknown(NAME("CAsyncFileReader"), NULL, &hr)
- , m_len(-1)
- , m_hBreakEvent(NULL)
- , m_lOsError(0)
+CAsyncFileReader::CAsyncFileReader(CAtlList<CHdmvClipInfo::PlaylistItem>& Items, HRESULT& hr)
+ : CUnknown(NAME("CAsyncFileReader"), NULL, &hr)
+ , m_len(-1)
+ , m_hBreakEvent(NULL)
+ , m_lOsError(0)
{
- hr = OpenFiles(Items, modeRead | shareDenyNone | typeBinary | osSequentialScan) ? S_OK : E_FAIL;
- if(SUCCEEDED(hr)) m_len = GetLength();
+ hr = OpenFiles(Items, modeRead|shareDenyNone|typeBinary|osSequentialScan) ? S_OK : E_FAIL;
+ if(SUCCEEDED(hr)) m_len = GetLength();
}
STDMETHODIMP CAsyncFileReader::NonDelegatingQueryInterface(REFIID riid, void** ppv)
{
- CheckPointer(ppv, E_POINTER);
+ CheckPointer(ppv, E_POINTER);
- return
- QI(IAsyncReader)
- QI(ISyncReader)
- QI(IFileHandle)
- __super::NonDelegatingQueryInterface(riid, ppv);
+ return
+ QI(IAsyncReader)
+ QI(ISyncReader)
+ QI(IFileHandle)
+ __super::NonDelegatingQueryInterface(riid, ppv);
}
// IAsyncReader
STDMETHODIMP CAsyncFileReader::SyncRead(LONGLONG llPosition, LONG lLength, BYTE* pBuffer)
{
- do
- {
- try
- {
- if(llPosition + lLength > GetLength()) return E_FAIL; // strange, but the Seek below can return llPosition even if the file is not that big (?)
- if(llPosition != Seek(llPosition, begin)) return E_FAIL;
- if((UINT)lLength < Read(pBuffer, lLength)) return E_FAIL;
+ do
+ {
+ try
+ {
+ if(llPosition+lLength > GetLength()) return E_FAIL; // strange, but the Seek below can return llPosition even if the file is not that big (?)
+ if(llPosition != Seek(llPosition, begin)) return E_FAIL;
+ if((UINT)lLength < Read(pBuffer, lLength)) return E_FAIL;
#if 0 // def DEBUG
- static __int64 s_total = 0, s_laststoppos = 0;
- s_total += lLength;
- if(s_laststoppos > llPosition)
- TRACE(_T("[%I64d - %I64d] %d (%I64d)\n"), llPosition, llPosition + lLength, lLength, s_total);
- s_laststoppos = llPosition + lLength;
+ static __int64 s_total = 0, s_laststoppos = 0;
+ s_total += lLength;
+ if(s_laststoppos > llPosition)
+ TRACE(_T("[%I64d - %I64d] %d (%I64d)\n"), llPosition, llPosition + lLength, lLength, s_total);
+ s_laststoppos = llPosition + lLength;
#endif
- return S_OK;
- }
- catch(CFileException* e)
- {
- m_lOsError = e->m_lOsError;
- e->Delete();
- Sleep(1);
- CString fn = m_strFileName;
- try
- {
- Close();
- }
- catch(CFileException* e)
- {
- e->Delete();
- }
- try
- {
- Open(fn, modeRead | shareDenyNone | typeBinary | osSequentialScan);
- }
- catch(CFileException* e)
- {
- e->Delete();
- }
- m_strFileName = fn;
- }
- }
- while(m_hBreakEvent && WaitForSingleObject(m_hBreakEvent, 0) == WAIT_TIMEOUT);
-
- return E_FAIL;
+ return S_OK;
+ }
+ catch(CFileException* e)
+ {
+ m_lOsError = e->m_lOsError;
+ e->Delete();
+ Sleep(1);
+ CString fn = m_strFileName;
+ try {Close();} catch(CFileException* e) {e->Delete();}
+ try {Open(fn, modeRead|shareDenyNone|typeBinary|osSequentialScan);} catch(CFileException* e) {e->Delete();}
+ m_strFileName = fn;
+ }
+ }
+ while(m_hBreakEvent && WaitForSingleObject(m_hBreakEvent, 0) == WAIT_TIMEOUT);
+
+ return E_FAIL;
}
STDMETHODIMP CAsyncFileReader::Length(LONGLONG* pTotal, LONGLONG* pAvailable)
{
- LONGLONG len = m_len >= 0 ? m_len : GetLength();
- if(pTotal) *pTotal = len;
- if(pAvailable) *pAvailable = len;
- return S_OK;
+ LONGLONG len = m_len >= 0 ? m_len : GetLength();
+ if(pTotal) *pTotal = len;
+ if(pAvailable) *pAvailable = len;
+ return S_OK;
}
// IFileHandle
STDMETHODIMP_(HANDLE) CAsyncFileReader::GetFileHandle()
{
- return m_hFile;
+ return m_hFile;
}
STDMETHODIMP_(LPCTSTR) CAsyncFileReader::GetFileName()
{
- return m_nCurPart != -1 ? m_strFiles[m_nCurPart] : m_strFiles[0];
+ return m_nCurPart != -1 ? m_strFiles[m_nCurPart] : m_strFiles[0];
}
//
// CAsyncUrlReader
//
-CAsyncUrlReader::CAsyncUrlReader(CString url, HRESULT& hr)
- : CAsyncFileReader(url, hr)
+CAsyncUrlReader::CAsyncUrlReader(CString url, HRESULT& hr)
+ : CAsyncFileReader(url, hr)
{
- if(SUCCEEDED(hr)) return;
+ if(SUCCEEDED(hr)) return;
- m_url = url;
+ m_url = url;
- if(CAMThread::Create())
- CallWorker(CMD_INIT);
+ if(CAMThread::Create())
+ CallWorker(CMD_INIT);
- hr = Open(m_fn, modeRead | shareDenyRead | typeBinary | osSequentialScan) ? S_OK : E_FAIL;
- m_len = -1; // force GetLength() return actual length always
+ hr = Open(m_fn, modeRead|shareDenyRead|typeBinary|osSequentialScan) ? S_OK : E_FAIL;
+ m_len = -1; // force GetLength() return actual length always
}
CAsyncUrlReader::~CAsyncUrlReader()
{
- if(ThreadExists())
- CallWorker(CMD_EXIT);
-
- if(!m_fn.IsEmpty())
- {
- CMultiFiles::Close();
- DeleteFile(m_fn);
- }
+ if(ThreadExists())
+ CallWorker(CMD_EXIT);
+
+ if(!m_fn.IsEmpty())
+ {
+ CMultiFiles::Close();
+ DeleteFile(m_fn);
+ }
}
// IAsyncReader
STDMETHODIMP CAsyncUrlReader::Length(LONGLONG* pTotal, LONGLONG* pAvailable)
{
- if(pTotal) *pTotal = 0;
- return __super::Length(NULL, pAvailable);
+ if(pTotal) *pTotal = 0;
+ return __super::Length(NULL, pAvailable);
}
// CAMThread
DWORD CAsyncUrlReader::ThreadProc()
{
- AfxSocketInit(NULL);
-
- DWORD cmd = GetRequest();
- if(cmd != CMD_INIT)
- {
- Reply(E_FAIL);
- return E_FAIL;
- }
-
- try
- {
- CInternetSession is;
- CAutoPtr<CStdioFile> fin(is.OpenURL(m_url, 1, INTERNET_FLAG_TRANSFER_BINARY | INTERNET_FLAG_EXISTING_CONNECT | INTERNET_FLAG_NO_CACHE_WRITE));
-
- TCHAR path[_MAX_PATH], fn[_MAX_PATH];
- CFile fout;
- if(GetTempPath(MAX_PATH, path) && GetTempFileName(path, _T("mpc_http"), 0, fn)
- && fout.Open(fn, modeCreate | modeWrite | shareDenyWrite | typeBinary))
- {
- m_fn = fn;
-
- char buff[1024];
- int len = fin->Read(buff, sizeof(buff));
- if(len > 0) fout.Write(buff, len);
-
- Reply(S_OK);
-
- while(!CheckRequest(&cmd))
- {
- int len = fin->Read(buff, sizeof(buff));
- if(len > 0) fout.Write(buff, len);
- }
- }
- else
- {
- Reply(E_FAIL);
- }
-
- fin->Close(); // must close it because the destructor doesn't seem to do it and we will get an exception when "is" is destroying
- }
- catch(CInternetException* ie)
- {
- ie->Delete();
- Reply(E_FAIL);
- }
-
- //
-
- cmd = GetRequest();
- ASSERT(cmd == CMD_EXIT);
- Reply(S_OK);
-
- //
-
- m_hThread = NULL;
-
- return S_OK;
+ AfxSocketInit(NULL);
+
+ DWORD cmd = GetRequest();
+ if(cmd != CMD_INIT) {Reply(E_FAIL); return E_FAIL;}
+
+ try
+ {
+ CInternetSession is;
+ CAutoPtr<CStdioFile> fin(is.OpenURL(m_url, 1, INTERNET_FLAG_TRANSFER_BINARY|INTERNET_FLAG_EXISTING_CONNECT|INTERNET_FLAG_NO_CACHE_WRITE));
+
+ TCHAR path[_MAX_PATH], fn[_MAX_PATH];
+ CFile fout;
+ if(GetTempPath(MAX_PATH, path) && GetTempFileName(path, _T("mpc_http"), 0, fn)
+ && fout.Open(fn, modeCreate|modeWrite|shareDenyWrite|typeBinary))
+ {
+ m_fn = fn;
+
+ char buff[1024];
+ int len = fin->Read(buff, sizeof(buff));
+ if(len > 0) fout.Write(buff, len);
+
+ Reply(S_OK);
+
+ while(!CheckRequest(&cmd))
+ {
+ int len = fin->Read(buff, sizeof(buff));
+ if(len > 0) fout.Write(buff, len);
+ }
+ }
+ else
+ {
+ Reply(E_FAIL);
+ }
+
+ fin->Close(); // must close it because the destructor doesn't seem to do it and we will get an exception when "is" is destroying
+ }
+ catch(CInternetException* ie)
+ {
+ ie->Delete();
+ Reply(E_FAIL);
+ }
+
+ //
+
+ cmd = GetRequest();
+ ASSERT(cmd == CMD_EXIT);
+ Reply(S_OK);
+
+ //
+
+ m_hThread = NULL;
+
+ return S_OK;
}
diff --git a/src/filters/parser/BaseSplitter/AsyncReader.h b/src/filters/parser/BaseSplitter/AsyncReader.h
index 8f9cdfcf0..d26552f0e 100644
--- a/src/filters/parser/BaseSplitter/AsyncReader.h
+++ b/src/filters/parser/BaseSplitter/AsyncReader.h
@@ -1,4 +1,4 @@
-/*
+/*
* Copyright (C) 2003-2006 Gabest
* http://www.gabest.org
*
@@ -6,15 +6,15 @@
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2, or (at your option)
* any later version.
- *
+ *
* This Program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with GNU Make; see the file COPYING. If not, write to
- * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
+ * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
* http://www.gnu.org/copyleft/gpl.html
*
*/
@@ -24,105 +24,73 @@
#include "MultiFiles.h"
[uuid("6DDB4EE7-45A0-4459-A508-BD77B32C91B2")]
-interface ISyncReader :
-public IUnknown
+interface ISyncReader : public IUnknown
{
- STDMETHOD_(void, SetBreakEvent)(HANDLE hBreakEvent) = 0;
- STDMETHOD_(bool, HasErrors)() = 0;
- STDMETHOD_(void, ClearErrors)() = 0;
- STDMETHOD_(void, SetPTSOffset)(REFERENCE_TIME* rtPTSOffset) = 0;
+ STDMETHOD_(void, SetBreakEvent) (HANDLE hBreakEvent) = 0;
+ STDMETHOD_(bool, HasErrors) () = 0;
+ STDMETHOD_(void, ClearErrors) () = 0;
+ STDMETHOD_(void, SetPTSOffset) (REFERENCE_TIME* rtPTSOffset) = 0;
};
[uuid("7D55F67A-826E-40B9-8A7D-3DF0CBBD272D")]
-interface IFileHandle :
-public IUnknown
+interface IFileHandle : public IUnknown
{
- STDMETHOD_(HANDLE, GetFileHandle)() = 0;
- STDMETHOD_(LPCTSTR, GetFileName)() = 0;
+ STDMETHOD_(HANDLE, GetFileHandle)() = 0;
+ STDMETHOD_(LPCTSTR, GetFileName)() = 0;
};
class CAsyncFileReader : public CUnknown, public CMultiFiles, public IAsyncReader, public ISyncReader, public IFileHandle
{
protected:
- ULONGLONG m_len;
- HANDLE m_hBreakEvent;
- LONG m_lOsError; // CFileException::m_lOsError
+ ULONGLONG m_len;
+ HANDLE m_hBreakEvent;
+ LONG m_lOsError; // CFileException::m_lOsError
public:
- CAsyncFileReader(CString fn, HRESULT& hr);
- CAsyncFileReader(CAtlList<CHdmvClipInfo::PlaylistItem>& Items, HRESULT& hr);
-
- DECLARE_IUNKNOWN;
- STDMETHODIMP NonDelegatingQueryInterface(REFIID riid, void** ppv);
-
- // IAsyncReader
-
- STDMETHODIMP RequestAllocator(IMemAllocator* pPreferred, ALLOCATOR_PROPERTIES* pProps, IMemAllocator** ppActual)
- {
- return E_NOTIMPL;
- }
- STDMETHODIMP Request(IMediaSample* pSample, DWORD_PTR dwUser)
- {
- return E_NOTIMPL;
- }
- STDMETHODIMP WaitForNext(DWORD dwTimeout, IMediaSample** ppSample, DWORD_PTR* pdwUser)
- {
- return E_NOTIMPL;
- }
- STDMETHODIMP SyncReadAligned(IMediaSample* pSample)
- {
- return E_NOTIMPL;
- }
- STDMETHODIMP SyncRead(LONGLONG llPosition, LONG lLength, BYTE* pBuffer);
- STDMETHODIMP Length(LONGLONG* pTotal, LONGLONG* pAvailable);
- STDMETHODIMP BeginFlush()
- {
- return E_NOTIMPL;
- }
- STDMETHODIMP EndFlush()
- {
- return E_NOTIMPL;
- }
-
- // ISyncReader
-
- STDMETHODIMP_(void) SetBreakEvent(HANDLE hBreakEvent)
- {
- m_hBreakEvent = hBreakEvent;
- }
- STDMETHODIMP_(bool) HasErrors()
- {
- return m_lOsError != 0;
- }
- STDMETHODIMP_(void) ClearErrors()
- {
- m_lOsError = 0;
- }
- STDMETHODIMP_(void) SetPTSOffset(REFERENCE_TIME* rtPTSOffset)
- {
- m_pCurrentPTSOffset = rtPTSOffset;
- };
-
- // IFileHandle
-
- STDMETHODIMP_(HANDLE) GetFileHandle();
- STDMETHODIMP_(LPCTSTR) GetFileName();
+ CAsyncFileReader(CString fn, HRESULT& hr);
+ CAsyncFileReader(CAtlList<CHdmvClipInfo::PlaylistItem>& Items, HRESULT& hr);
+
+ DECLARE_IUNKNOWN;
+ STDMETHODIMP NonDelegatingQueryInterface(REFIID riid, void** ppv);
+
+ // IAsyncReader
+
+ STDMETHODIMP RequestAllocator(IMemAllocator* pPreferred, ALLOCATOR_PROPERTIES* pProps, IMemAllocator** ppActual) {return E_NOTIMPL;}
+ STDMETHODIMP Request(IMediaSample* pSample, DWORD_PTR dwUser) {return E_NOTIMPL;}
+ STDMETHODIMP WaitForNext(DWORD dwTimeout, IMediaSample** ppSample, DWORD_PTR* pdwUser) {return E_NOTIMPL;}
+ STDMETHODIMP SyncReadAligned(IMediaSample* pSample) {return E_NOTIMPL;}
+ STDMETHODIMP SyncRead(LONGLONG llPosition, LONG lLength, BYTE* pBuffer);
+ STDMETHODIMP Length(LONGLONG* pTotal, LONGLONG* pAvailable);
+ STDMETHODIMP BeginFlush() {return E_NOTIMPL;}
+ STDMETHODIMP EndFlush() {return E_NOTIMPL;}
+
+ // ISyncReader
+
+ STDMETHODIMP_(void) SetBreakEvent(HANDLE hBreakEvent) {m_hBreakEvent = hBreakEvent;}
+ STDMETHODIMP_(bool) HasErrors() {return m_lOsError != 0;}
+ STDMETHODIMP_(void) ClearErrors() {m_lOsError = 0;}
+ STDMETHODIMP_(void) SetPTSOffset (REFERENCE_TIME* rtPTSOffset) { m_pCurrentPTSOffset = rtPTSOffset;};
+
+ // IFileHandle
+
+ STDMETHODIMP_(HANDLE) GetFileHandle();
+ STDMETHODIMP_(LPCTSTR) GetFileName();
};
class CAsyncUrlReader : public CAsyncFileReader, protected CAMThread
{
- CString m_url, m_fn;
+ CString m_url, m_fn;
protected:
- enum {CMD_EXIT, CMD_INIT};
+ enum {CMD_EXIT, CMD_INIT};
DWORD ThreadProc();
public:
- CAsyncUrlReader(CString url, HRESULT& hr);
- virtual ~CAsyncUrlReader();
+ CAsyncUrlReader(CString url, HRESULT& hr);
+ virtual ~CAsyncUrlReader();
- // IAsyncReader
+ // IAsyncReader
- STDMETHODIMP Length(LONGLONG* pTotal, LONGLONG* pAvailable);
+ STDMETHODIMP Length(LONGLONG* pTotal, LONGLONG* pAvailable);
};
diff --git a/src/filters/parser/BaseSplitter/BaseSplitter.cpp b/src/filters/parser/BaseSplitter/BaseSplitter.cpp
index 783230bb6..1a57ed507 100644
--- a/src/filters/parser/BaseSplitter/BaseSplitter.cpp
+++ b/src/filters/parser/BaseSplitter/BaseSplitter.cpp
@@ -1,4 +1,4 @@
-/*
+/*
* Copyright (C) 2003-2006 Gabest
* http://www.gabest.org
*
@@ -6,15 +6,15 @@
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2, or (at your option)
* any later version.
- *
+ *
* This Program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with GNU Make; see the file COPYING. If not, write to
- * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
+ * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
* http://www.gnu.org/copyleft/gpl.html
*
*/
@@ -43,57 +43,57 @@ CPacketQueue::CPacketQueue() : m_size(0)
void CPacketQueue::Add(CAutoPtr<Packet> p)
{
- CAutoLock cAutoLock(this);
+ CAutoLock cAutoLock(this);
+
+ if(p)
+ {
+ m_size += p->GetDataSize();
- if(p)
- {
- m_size += p->GetDataSize();
-
- if(p->bAppendable && !p->bDiscontinuity && !p->pmt
- && p->rtStart == Packet::INVALID_TIME
- && !IsEmpty() && GetTail()->rtStart != Packet::INVALID_TIME)
- {
- Packet* tail = GetTail();
- int oldsize = tail->GetCount();
- int newsize = tail->GetCount() + p->GetCount();
- tail->SetCount(newsize, max(1024, newsize)); // doubles the reserved buffer size
- memcpy(tail->GetData() + oldsize, p->GetData(), p->GetCount());
- /*
- GetTail()->Append(*p); // too slow
- */
- return;
- }
- }
-
- AddTail(p);
+ if(p->bAppendable && !p->bDiscontinuity && !p->pmt
+ && p->rtStart == Packet::INVALID_TIME
+ && !IsEmpty() && GetTail()->rtStart != Packet::INVALID_TIME)
+ {
+ Packet* tail = GetTail();
+ int oldsize = tail->GetCount();
+ int newsize = tail->GetCount() + p->GetCount();
+ tail->SetCount(newsize, max(1024, newsize)); // doubles the reserved buffer size
+ memcpy(tail->GetData() + oldsize, p->GetData(), p->GetCount());
+ /*
+ GetTail()->Append(*p); // too slow
+ */
+ return;
+ }
+ }
+
+ AddTail(p);
}
CAutoPtr<Packet> CPacketQueue::Remove()
{
- CAutoLock cAutoLock(this);
- ASSERT(__super::GetCount() > 0);
- CAutoPtr<Packet> p = RemoveHead();
- if(p) m_size -= p->GetDataSize();
- return p;
+ CAutoLock cAutoLock(this);
+ ASSERT(__super::GetCount() > 0);
+ CAutoPtr<Packet> p = RemoveHead();
+ if(p) m_size -= p->GetDataSize();
+ return p;
}
void CPacketQueue::RemoveAll()
{
- CAutoLock cAutoLock(this);
- m_size = 0;
- __super::RemoveAll();
+ CAutoLock cAutoLock(this);
+ m_size = 0;
+ __super::RemoveAll();
}
int CPacketQueue::GetCount()
{
- CAutoLock cAutoLock(this);
- return __super::GetCount();
+ CAutoLock cAutoLock(this);
+ return __super::GetCount();
}
int CPacketQueue::GetSize()
{
- CAutoLock cAutoLock(this);
- return m_size;
+ CAutoLock cAutoLock(this);
+ return m_size;
}
//
@@ -101,7 +101,7 @@ int CPacketQueue::GetSize()
//
CBaseSplitterInputPin::CBaseSplitterInputPin(TCHAR* pName, CBaseSplitterFilter* pFilter, CCritSec* pLock, HRESULT* phr)
- : CBasePin(pName, pFilter, pLock, phr, L"Input", PINDIR_INPUT)
+ : CBasePin(pName, pFilter, pLock, phr, L"Input", PINDIR_INPUT)
{
}
@@ -111,80 +111,80 @@ CBaseSplitterInputPin::~CBaseSplitterInputPin()
HRESULT CBaseSplitterInputPin::GetAsyncReader(IAsyncReader** ppAsyncReader)
{
- CheckPointer(ppAsyncReader, E_POINTER);
- *ppAsyncReader = NULL;
- CheckPointer(m_pAsyncReader, VFW_E_NOT_CONNECTED);
- (*ppAsyncReader = m_pAsyncReader)->AddRef();
- return S_OK;
+ CheckPointer(ppAsyncReader, E_POINTER);
+ *ppAsyncReader = NULL;
+ CheckPointer(m_pAsyncReader, VFW_E_NOT_CONNECTED);
+ (*ppAsyncReader = m_pAsyncReader)->AddRef();
+ return S_OK;
}
STDMETHODIMP CBaseSplitterInputPin::NonDelegatingQueryInterface(REFIID riid, void** ppv)
{
- CheckPointer(ppv, E_POINTER);
+ CheckPointer(ppv, E_POINTER);
- return
- __super::NonDelegatingQueryInterface(riid, ppv);
+ return
+ __super::NonDelegatingQueryInterface(riid, ppv);
}
HRESULT CBaseSplitterInputPin::CheckMediaType(const CMediaType* pmt)
{
- return S_OK;
- /*
- return pmt->majortype == MEDIATYPE_Stream
- ? S_OK
- : E_INVALIDARG;
- */
+ return S_OK;
+/*
+ return pmt->majortype == MEDIATYPE_Stream
+ ? S_OK
+ : E_INVALIDARG;
+*/
}
HRESULT CBaseSplitterInputPin::CheckConnect(IPin* pPin)
{
- HRESULT hr;
- if(FAILED(hr = __super::CheckConnect(pPin)))
- return hr;
+ HRESULT hr;
+ if(FAILED(hr = __super::CheckConnect(pPin)))
+ return hr;
- return CComQIPtr<IAsyncReader>(pPin) ? S_OK : E_NOINTERFACE;
+ return CComQIPtr<IAsyncReader>(pPin) ? S_OK : E_NOINTERFACE;
}
HRESULT CBaseSplitterInputPin::BreakConnect()
{
- HRESULT hr;
+ HRESULT hr;
- if(FAILED(hr = __super::BreakConnect()))
- return hr;
+ if(FAILED(hr = __super::BreakConnect()))
+ return hr;
- if(FAILED(hr = (static_cast<CBaseSplitterFilter*>(m_pFilter))->BreakConnect(PINDIR_INPUT, this)))
- return hr;
+ if(FAILED(hr = (static_cast<CBaseSplitterFilter*>(m_pFilter))->BreakConnect(PINDIR_INPUT, this)))
+ return hr;
- m_pAsyncReader.Release();
+ m_pAsyncReader.Release();
- return S_OK;
+ return S_OK;
}
HRESULT CBaseSplitterInputPin::CompleteConnect(IPin* pPin)
{
- HRESULT hr;
+ HRESULT hr;
- if(FAILED(hr = __super::CompleteConnect(pPin)))
- return hr;
+ if(FAILED(hr = __super::CompleteConnect(pPin)))
+ return hr;
- CheckPointer(pPin, E_POINTER);
- m_pAsyncReader = pPin;
- CheckPointer(m_pAsyncReader, E_NOINTERFACE);
+ CheckPointer(pPin, E_POINTER);
+ m_pAsyncReader = pPin;
+ CheckPointer(m_pAsyncReader, E_NOINTERFACE);
- if(FAILED(hr = (static_cast<CBaseSplitterFilter*>(m_pFilter))->CompleteConnect(PINDIR_INPUT, this)))
- return hr;
+ if(FAILED(hr = (static_cast<CBaseSplitterFilter*>(m_pFilter))->CompleteConnect(PINDIR_INPUT, this)))
+ return hr;
- return S_OK;
+ return S_OK;
}
STDMETHODIMP CBaseSplitterInputPin::BeginFlush()
{
- return E_UNEXPECTED;
+ return E_UNEXPECTED;
}
STDMETHODIMP CBaseSplitterInputPin::EndFlush()
{
- return E_UNEXPECTED;
+ return E_UNEXPECTED;
}
//
@@ -192,26 +192,26 @@ STDMETHODIMP CBaseSplitterInputPin::EndFlush()
//
CBaseSplitterOutputPin::CBaseSplitterOutputPin(CAtlArray<CMediaType>& mts, LPCWSTR pName, CBaseFilter* pFilter, CCritSec* pLock, HRESULT* phr, int nBuffers)
- : CBaseOutputPin(NAME("CBaseSplitterOutputPin"), pFilter, pLock, phr, pName)
- , m_hrDeliver(S_OK) // just in case it were asked before the worker thread could be created and reset it
- , m_fFlushing(false)
- , m_eEndFlush(TRUE)
+ : CBaseOutputPin(NAME("CBaseSplitterOutputPin"), pFilter, pLock, phr, pName)
+ , m_hrDeliver(S_OK) // just in case it were asked before the worker thread could be created and reset it
+ , m_fFlushing(false)
+ , m_eEndFlush(TRUE)
{
- m_mts.Copy(mts);
- m_nBuffers = max(nBuffers, 1);
- memset(&m_brs, 0, sizeof(m_brs));
- m_brs.rtLastDeliverTime = Packet::INVALID_TIME;
+ m_mts.Copy(mts);
+ m_nBuffers = max(nBuffers, 1);
+ memset(&m_brs, 0, sizeof(m_brs));
+ m_brs.rtLastDeliverTime = Packet::INVALID_TIME;
}
CBaseSplitterOutputPin::CBaseSplitterOutputPin(LPCWSTR pName, CBaseFilter* pFilter, CCritSec* pLock, HRESULT* phr, int nBuffers)
- : CBaseOutputPin(NAME("CBaseSplitterOutputPin"), pFilter, pLock, phr, pName)
- , m_hrDeliver(S_OK) // just in case it were asked before the worker thread could be created and reset it
- , m_fFlushing(false)
- , m_eEndFlush(TRUE)
+ : CBaseOutputPin(NAME("CBaseSplitterOutputPin"), pFilter, pLock, phr, pName)
+ , m_hrDeliver(S_OK) // just in case it were asked before the worker thread could be created and reset it
+ , m_fFlushing(false)
+ , m_eEndFlush(TRUE)
{
- m_nBuffers = max(nBuffers, 1);
- memset(&m_brs, 0, sizeof(m_brs));
- m_brs.rtLastDeliverTime = Packet::INVALID_TIME;
+ m_nBuffers = max(nBuffers, 1);
+ memset(&m_brs, 0, sizeof(m_brs));
+ m_brs.rtLastDeliverTime = Packet::INVALID_TIME;
}
CBaseSplitterOutputPin::~CBaseSplitterOutputPin()
@@ -220,26 +220,26 @@ CBaseSplitterOutputPin::~CBaseSplitterOutputPin()
STDMETHODIMP CBaseSplitterOutputPin::NonDelegatingQueryInterface(REFIID riid, void** ppv)
{
- CheckPointer(ppv, E_POINTER);
+ CheckPointer(ppv, E_POINTER);
- return
-// riid == __uuidof(IMediaSeeking) ? m_pFilter->QueryInterface(riid, ppv) :
- QI(IMediaSeeking)
- QI(IPropertyBag)
- QI(IPropertyBag2)
- QI(IDSMPropertyBag)
- QI(IBitRateInfo)
- __super::NonDelegatingQueryInterface(riid, ppv);
+ return
+// riid == __uuidof(IMediaSeeking) ? m_pFilter->QueryInterface(riid, ppv) :
+ QI(IMediaSeeking)
+ QI(IPropertyBag)
+ QI(IPropertyBag2)
+ QI(IDSMPropertyBag)
+ QI(IBitRateInfo)
+ __super::NonDelegatingQueryInterface(riid, ppv);
}
HRESULT CBaseSplitterOutputPin::SetName(LPCWSTR pName)
{
- CheckPointer(pName, E_POINTER);
- if(m_pName) delete [] m_pName;
- m_pName = DNew WCHAR[wcslen(pName)+1];
- CheckPointer(m_pName, E_OUTOFMEMORY);
- wcscpy(m_pName, pName);
- return S_OK;
+ CheckPointer(pName, E_POINTER);
+ if(m_pName) delete [] m_pName;
+ m_pName = DNew WCHAR[wcslen(pName)+1];
+ CheckPointer(m_pName, E_OUTOFMEMORY);
+ wcscpy(m_pName, pName);
+ return S_OK;
}
HRESULT CBaseSplitterOutputPin::DecideBufferSize(IMemAllocator* pAlloc, ALLOCATOR_PROPERTIES* pProperties)
@@ -249,14 +249,14 @@ HRESULT CBaseSplitterOutputPin::DecideBufferSize(IMemAllocator* pAlloc, ALLOCATO
HRESULT hr = NOERROR;
- pProperties->cBuffers = m_nBuffers;
- pProperties->cbBuffer = max(m_mt.lSampleSize, 1);
+ pProperties->cBuffers = m_nBuffers;
+ pProperties->cbBuffer = max(m_mt.lSampleSize, 1);
- if(m_mt.subtype == MEDIASUBTYPE_Vorbis && m_mt.formattype == FORMAT_VorbisFormat)
- {
- // oh great, the oggds vorbis decoder assumes there will be two at least, stupid thing...
- pProperties->cBuffers = max(pProperties->cBuffers, 2);
- }
+ if(m_mt.subtype == MEDIASUBTYPE_Vorbis && m_mt.formattype == FORMAT_VorbisFormat)
+ {
+ // oh great, the oggds vorbis decoder assumes there will be two at least, stupid thing...
+ pProperties->cBuffers = max(pProperties->cBuffers, 2);
+ }
ALLOCATOR_PROPERTIES Actual;
if(FAILED(hr = pAlloc->SetProperties(pProperties, &Actual))) return hr;
@@ -269,30 +269,30 @@ HRESULT CBaseSplitterOutputPin::DecideBufferSize(IMemAllocator* pAlloc, ALLOCATO
HRESULT CBaseSplitterOutputPin::CheckMediaType(const CMediaType* pmt)
{
- for(int i = 0; i < m_mts.GetCount(); i++)
- {
- if(*pmt == m_mts[i])
- return S_OK;
- }
+ for(int i = 0; i < m_mts.GetCount(); i++)
+ {
+ if(*pmt == m_mts[i])
+ return S_OK;
+ }
- return E_INVALIDARG;
+ return E_INVALIDARG;
}
HRESULT CBaseSplitterOutputPin::GetMediaType(int iPosition, CMediaType* pmt)
{
CAutoLock cAutoLock(m_pLock);
- if(iPosition < 0) return E_INVALIDARG;
- if(iPosition >= m_mts.GetCount()) return VFW_S_NO_MORE_ITEMS;
+ if(iPosition < 0) return E_INVALIDARG;
+ if(iPosition >= m_mts.GetCount()) return VFW_S_NO_MORE_ITEMS;
- *pmt = m_mts[iPosition];
+ *pmt = m_mts[iPosition];
- return S_OK;
+ return S_OK;
}
STDMETHODIMP CBaseSplitterOutputPin::Notify(IBaseFilter* pSender, Quality q)
{
- return E_NOTIMPL;
+ return E_NOTIMPL;
}
//
@@ -301,394 +301,393 @@ HRESULT CBaseSplitterOutputPin::Active()
{
CAutoLock cAutoLock(m_pLock);
- if(m_Connected)
- Create();
+ if(m_Connected)
+ Create();
- return __super::Active();
+ return __super::Active();
}
HRESULT CBaseSplitterOutputPin::Inactive()
{
CAutoLock cAutoLock(m_pLock);
- if(ThreadExists())
- CallWorker(CMD_EXIT);
+ if(ThreadExists())
+ CallWorker(CMD_EXIT);
- return __super::Inactive();
+ return __super::Inactive();
}
HRESULT CBaseSplitterOutputPin::DeliverBeginFlush()
{
- m_eEndFlush.Reset();
- m_fFlushed = false;
- m_fFlushing = true;
- m_hrDeliver = S_FALSE;
- m_queue.RemoveAll();
- HRESULT hr = IsConnected() ? GetConnected()->BeginFlush() : S_OK;
- if(S_OK != hr) m_eEndFlush.Set();
- return(hr);
+ m_eEndFlush.Reset();
+ m_fFlushed = false;
+ m_fFlushing = true;
+ m_hrDeliver = S_FALSE;
+ m_queue.RemoveAll();
+ HRESULT hr = IsConnected() ? GetConnected()->BeginFlush() : S_OK;
+ if(S_OK != hr) m_eEndFlush.Set();
+ return(hr);
}
HRESULT CBaseSplitterOutputPin::DeliverEndFlush()
{
- if(!ThreadExists()) return S_FALSE;
- HRESULT hr = IsConnected() ? GetConnected()->EndFlush() : S_OK;
- m_hrDeliver = S_OK;
- m_fFlushing = false;
- m_fFlushed = true;
- m_eEndFlush.Set();
- return hr;
+ if(!ThreadExists()) return S_FALSE;
+ HRESULT hr = IsConnected() ? GetConnected()->EndFlush() : S_OK;
+ m_hrDeliver = S_OK;
+ m_fFlushing = false;
+ m_fFlushed = true;
+ m_eEndFlush.Set();
+ return hr;
}
HRESULT CBaseSplitterOutputPin::DeliverNewSegment(REFERENCE_TIME tStart, REFERENCE_TIME tStop, double dRate)
{
- m_brs.rtLastDeliverTime = Packet::INVALID_TIME;
- if(m_fFlushing) return S_FALSE;
- m_rtStart = tStart;
- if(!ThreadExists()) return S_FALSE;
- HRESULT hr = __super::DeliverNewSegment(tStart, tStop, dRate);
- if(S_OK != hr) return hr;
- MakeISCRHappy();
- return hr;
+ m_brs.rtLastDeliverTime = Packet::INVALID_TIME;
+ if(m_fFlushing) return S_FALSE;
+ m_rtStart = tStart;
+ if(!ThreadExists()) return S_FALSE;
+ HRESULT hr = __super::DeliverNewSegment(tStart, tStop, dRate);
+ if(S_OK != hr) return hr;
+ MakeISCRHappy();
+ return hr;
}
int CBaseSplitterOutputPin::QueueCount()
{
- return m_queue.GetCount();
+ return m_queue.GetCount();
}
int CBaseSplitterOutputPin::QueueSize()
{
- return m_queue.GetSize();
+ return m_queue.GetSize();
}
HRESULT CBaseSplitterOutputPin::QueueEndOfStream()
{
- return QueuePacket(CAutoPtr<Packet>()); // NULL means EndOfStream
+ return QueuePacket(CAutoPtr<Packet>()); // NULL means EndOfStream
}
HRESULT CBaseSplitterOutputPin::QueuePacket(CAutoPtr<Packet> p)
{
- if(!ThreadExists()) return S_FALSE;
+ if(!ThreadExists()) return S_FALSE;
- while(S_OK == m_hrDeliver
- && (!(static_cast<CBaseSplitterFilter*>(m_pFilter))->IsAnyPinDrying()
- || m_queue.GetSize() > MAXPACKETSIZE * 100))
- Sleep(1);
+ while(S_OK == m_hrDeliver
+ && (!(static_cast<CBaseSplitterFilter*>(m_pFilter))->IsAnyPinDrying()
+ || m_queue.GetSize() > MAXPACKETSIZE*100))
+ Sleep(1);
- if(S_OK != m_hrDeliver)
- return m_hrDeliver;
+ if(S_OK != m_hrDeliver)
+ return m_hrDeliver;
- m_queue.Add(p);
+ m_queue.Add(p);
- return m_hrDeliver;
+ return m_hrDeliver;
}
bool CBaseSplitterOutputPin::IsDiscontinuous()
{
- return m_mt.majortype == MEDIATYPE_Text
- || m_mt.majortype == MEDIATYPE_ScriptCommand
- || m_mt.majortype == MEDIATYPE_Subtitle
- || m_mt.subtype == MEDIASUBTYPE_DVD_SUBPICTURE
- || m_mt.subtype == MEDIASUBTYPE_CVD_SUBPICTURE
- || m_mt.subtype == MEDIASUBTYPE_SVCD_SUBPICTURE;
+ return m_mt.majortype == MEDIATYPE_Text
+ || m_mt.majortype == MEDIATYPE_ScriptCommand
+ || m_mt.majortype == MEDIATYPE_Subtitle
+ || m_mt.subtype == MEDIASUBTYPE_DVD_SUBPICTURE
+ || m_mt.subtype == MEDIASUBTYPE_CVD_SUBPICTURE
+ || m_mt.subtype == MEDIASUBTYPE_SVCD_SUBPICTURE;
}
bool CBaseSplitterOutputPin::IsActive()
{
- CComPtr<IPin> pPin = this;
- do
- {
- CComPtr<IPin> pPinTo;
- CComQIPtr<IStreamSwitcherInputPin> pSSIP;
- if(S_OK == pPin->ConnectedTo(&pPinTo) && (pSSIP = pPinTo) && !pSSIP->IsActive())
- return(false);
- pPin = GetFirstPin(GetFilterFromPin(pPinTo), PINDIR_OUTPUT);
- }
- while(pPin);
+ CComPtr<IPin> pPin = this;
+ do
+ {
+ CComPtr<IPin> pPinTo;
+ CComQIPtr<IStreamSwitcherInputPin> pSSIP;
+ if(S_OK == pPin->ConnectedTo(&pPinTo) && (pSSIP = pPinTo) && !pSSIP->IsActive())
+ return(false);
+ pPin = GetFirstPin(GetFilterFromPin(pPinTo), PINDIR_OUTPUT);
+ }
+ while(pPin);
- return(true);
+ return(true);
}
DWORD CBaseSplitterOutputPin::ThreadProc()
{
- m_hrDeliver = S_OK;
- m_fFlushing = m_fFlushed = false;
- m_eEndFlush.Set();
-
- while(1)
- {
- Sleep(1);
-
- DWORD cmd;
- if(CheckRequest(&cmd))
- {
- m_hThread = NULL;
- cmd = GetRequest();
- Reply(S_OK);
- ASSERT(cmd == CMD_EXIT);
- return 0;
- }
-
- int cnt = 0;
- do
- {
- CAutoPtr<Packet> p;
-
- {
- CAutoLock cAutoLock(&m_queue);
- if((cnt = m_queue.GetCount()) > 0)
- p = m_queue.Remove();
- }
-
- if(S_OK == m_hrDeliver && cnt > 0)
- {
- ASSERT(!m_fFlushing);
-
- m_fFlushed = false;
-
- // flushing can still start here, to release a blocked deliver call
-
- HRESULT hr = p
- ? DeliverPacket(p)
- : DeliverEndOfStream();
-
- m_eEndFlush.Wait(); // .. so we have to wait until it is done
-
- if(hr != S_OK && !m_fFlushed) // and only report the error in m_hrDeliver if we didn't flush the stream
- {
- // CAutoLock cAutoLock(&m_csQueueLock);
- m_hrDeliver = hr;
- break;
- }
- }
- }
- while(--cnt > 0);
- }
+ m_hrDeliver = S_OK;
+ m_fFlushing = m_fFlushed = false;
+ m_eEndFlush.Set();
+
+ while(1)
+ {
+ Sleep(1);
+
+ DWORD cmd;
+ if(CheckRequest(&cmd))
+ {
+ m_hThread = NULL;
+ cmd = GetRequest();
+ Reply(S_OK);
+ ASSERT(cmd == CMD_EXIT);
+ return 0;
+ }
+
+ int cnt = 0;
+ do
+ {
+ CAutoPtr<Packet> p;
+
+ {
+ CAutoLock cAutoLock(&m_queue);
+ if((cnt = m_queue.GetCount()) > 0)
+ p = m_queue.Remove();
+ }
+
+ if(S_OK == m_hrDeliver && cnt > 0)
+ {
+ ASSERT(!m_fFlushing);
+
+ m_fFlushed = false;
+
+ // flushing can still start here, to release a blocked deliver call
+
+ HRESULT hr = p
+ ? DeliverPacket(p)
+ : DeliverEndOfStream();
+
+ m_eEndFlush.Wait(); // .. so we have to wait until it is done
+
+ if(hr != S_OK && !m_fFlushed) // and only report the error in m_hrDeliver if we didn't flush the stream
+ {
+ // CAutoLock cAutoLock(&m_csQueueLock);
+ m_hrDeliver = hr;
+ break;
+ }
+ }
+ }
+ while(--cnt > 0);
+ }
}
HRESULT CBaseSplitterOutputPin::DeliverPacket(CAutoPtr<Packet> p)
{
- HRESULT hr;
-
- INT_PTR nBytes = p->GetCount();
-
- if(nBytes == 0)
- {
- return S_OK;
- }
-
- m_brs.nBytesSinceLastDeliverTime += nBytes;
-
- if(p->rtStart != Packet::INVALID_TIME)
- {
- if(m_brs.rtLastDeliverTime == Packet::INVALID_TIME)
- {
- m_brs.rtLastDeliverTime = p->rtStart;
- m_brs.nBytesSinceLastDeliverTime = 0;
- }
-
- if(m_brs.rtLastDeliverTime + 10000000 < p->rtStart)
- {
- REFERENCE_TIME rtDiff = p->rtStart - m_brs.rtLastDeliverTime;
-
- double secs, bits;
-
- secs = (double)rtDiff / 10000000;
- bits = 8.0 * m_brs.nBytesSinceLastDeliverTime;
- m_brs.nCurrentBitRate = (DWORD)(bits / secs);
-
- m_brs.rtTotalTimeDelivered += rtDiff;
- m_brs.nTotalBytesDelivered += m_brs.nBytesSinceLastDeliverTime;
-
- secs = (double)m_brs.rtTotalTimeDelivered / 10000000;
- bits = 8.0 * m_brs.nTotalBytesDelivered;
- m_brs.nAverageBitRate = (DWORD)(bits / secs);
-
- m_brs.rtLastDeliverTime = p->rtStart;
- m_brs.nBytesSinceLastDeliverTime = 0;
- /*
- TRACE(_T("[%d] c: %d kbps, a: %d kbps\n"),
- p->TrackNumber,
- (m_brs.nCurrentBitRate+500)/1000,
- (m_brs.nAverageBitRate+500)/1000);
- */
- }
-
- double dRate = 1.0;
- if(SUCCEEDED((static_cast<CBaseSplitterFilter*>(m_pFilter))->GetRate(&dRate)))
- {
- p->rtStart = (REFERENCE_TIME)((double)p->rtStart / dRate);
- p->rtStop = (REFERENCE_TIME)((double)p->rtStop / dRate);
- }
- }
-
- do
- {
- CComPtr<IMediaSample> pSample;
- if(S_OK != (hr = GetDeliveryBuffer(&pSample, NULL, NULL, 0))) break;
-
- if(nBytes > pSample->GetSize())
- {
- pSample.Release();
-
- ALLOCATOR_PROPERTIES props, actual;
- if(S_OK != (hr = m_pAllocator->GetProperties(&props))) break;
- props.cbBuffer = nBytes * 3 / 2;
-
- if(props.cBuffers > 1)
- {
- if(S_OK != (hr = __super::DeliverBeginFlush())) break;
- if(S_OK != (hr = __super::DeliverEndFlush())) break;
- }
-
- if(S_OK != (hr = m_pAllocator->Decommit())) break;
- if(S_OK != (hr = m_pAllocator->SetProperties(&props, &actual))) break;
- if(S_OK != (hr = m_pAllocator->Commit())) break;
- if(S_OK != (hr = GetDeliveryBuffer(&pSample, NULL, NULL, 0))) break;
- }
-
- if(p->pmt)
- {
- pSample->SetMediaType(p->pmt);
- p->bDiscontinuity = true;
-
- CAutoLock cAutoLock(m_pLock);
- m_mts.RemoveAll();
- m_mts.Add(*p->pmt);
- }
-
- bool fTimeValid = p->rtStart != Packet::INVALID_TIME;
- /*
- //if(p->TrackNumber == 1)
- //if(p->rtStart != Packet::INVALID_TIME)
- TRACE(_T("[%d]: d%d s%d p%d, b=%d, %I64d-%I64d \n"),
- p->TrackNumber,
- p->bDiscontinuity, p->bSyncPoint, fTimeValid && p->rtStart < 0,
- nBytes, p->rtStart, p->rtStop);
- */
- ASSERT(!p->bSyncPoint || fTimeValid);
-
- BYTE* pData = NULL;
- if(S_OK != (hr = pSample->GetPointer(&pData)) || !pData) break;
- memcpy(pData, p->GetData(), nBytes);
- if(S_OK != (hr = pSample->SetActualDataLength(nBytes))) break;
- if(S_OK != (hr = pSample->SetTime(fTimeValid ? &p->rtStart : NULL, fTimeValid ? &p->rtStop : NULL))) break;
- if(S_OK != (hr = pSample->SetMediaTime(NULL, NULL))) break;
- if(S_OK != (hr = pSample->SetDiscontinuity(p->bDiscontinuity))) break;
- if(S_OK != (hr = pSample->SetSyncPoint(p->bSyncPoint))) break;
- if(S_OK != (hr = pSample->SetPreroll(fTimeValid && p->rtStart < 0))) break;
- if(S_OK != (hr = Deliver(pSample))) break;
- }
- while(false);
-
- return hr;
+ HRESULT hr;
+
+ INT_PTR nBytes = p->GetCount();
+
+ if(nBytes == 0)
+ {
+ return S_OK;
+ }
+
+ m_brs.nBytesSinceLastDeliverTime += nBytes;
+
+ if(p->rtStart != Packet::INVALID_TIME)
+ {
+ if(m_brs.rtLastDeliverTime == Packet::INVALID_TIME)
+ {
+ m_brs.rtLastDeliverTime = p->rtStart;
+ m_brs.nBytesSinceLastDeliverTime = 0;
+ }
+
+ if(m_brs.rtLastDeliverTime + 10000000 < p->rtStart)
+ {
+ REFERENCE_TIME rtDiff = p->rtStart - m_brs.rtLastDeliverTime;
+
+ double secs, bits;
+
+ secs = (double)rtDiff / 10000000;
+ bits = 8.0 * m_brs.nBytesSinceLastDeliverTime;
+ m_brs.nCurrentBitRate = (DWORD)(bits / secs);
+
+ m_brs.rtTotalTimeDelivered += rtDiff;
+ m_brs.nTotalBytesDelivered += m_brs.nBytesSinceLastDeliverTime;
+
+ secs = (double)m_brs.rtTotalTimeDelivered / 10000000;
+ bits = 8.0 * m_brs.nTotalBytesDelivered;
+ m_brs.nAverageBitRate = (DWORD)(bits / secs);
+
+ m_brs.rtLastDeliverTime = p->rtStart;
+ m_brs.nBytesSinceLastDeliverTime = 0;
+/*
+ TRACE(_T("[%d] c: %d kbps, a: %d kbps\n"),
+ p->TrackNumber,
+ (m_brs.nCurrentBitRate+500)/1000,
+ (m_brs.nAverageBitRate+500)/1000);
+*/
+ }
+
+ double dRate = 1.0;
+ if(SUCCEEDED((static_cast<CBaseSplitterFilter*>(m_pFilter))->GetRate(&dRate)))
+ {
+ p->rtStart = (REFERENCE_TIME)((double)p->rtStart / dRate);
+ p->rtStop = (REFERENCE_TIME)((double)p->rtStop / dRate);
+ }
+ }
+
+ do
+ {
+ CComPtr<IMediaSample> pSample;
+ if(S_OK != (hr = GetDeliveryBuffer(&pSample, NULL, NULL, 0))) break;
+
+ if(nBytes > pSample->GetSize())
+ {
+ pSample.Release();
+
+ ALLOCATOR_PROPERTIES props, actual;
+ if(S_OK != (hr = m_pAllocator->GetProperties(&props))) break;
+ props.cbBuffer = nBytes*3/2;
+
+ if(props.cBuffers > 1)
+ {
+ if(S_OK != (hr = __super::DeliverBeginFlush())) break;
+ if(S_OK != (hr = __super::DeliverEndFlush())) break;
+ }
+
+ if(S_OK != (hr = m_pAllocator->Decommit())) break;
+ if(S_OK != (hr = m_pAllocator->SetProperties(&props, &actual))) break;
+ if(S_OK != (hr = m_pAllocator->Commit())) break;
+ if(S_OK != (hr = GetDeliveryBuffer(&pSample, NULL, NULL, 0))) break;
+ }
+
+ if(p->pmt)
+ {
+ pSample->SetMediaType(p->pmt);
+ p->bDiscontinuity = true;
+
+ CAutoLock cAutoLock(m_pLock);
+ m_mts.RemoveAll();
+ m_mts.Add(*p->pmt);
+ }
+
+ bool fTimeValid = p->rtStart != Packet::INVALID_TIME;
+/*
+//if(p->TrackNumber == 1)
+//if(p->rtStart != Packet::INVALID_TIME)
+TRACE(_T("[%d]: d%d s%d p%d, b=%d, %I64d-%I64d \n"),
+ p->TrackNumber,
+ p->bDiscontinuity, p->bSyncPoint, fTimeValid && p->rtStart < 0,
+ nBytes, p->rtStart, p->rtStop);
+*/
+ ASSERT(!p->bSyncPoint || fTimeValid);
+
+ BYTE* pData = NULL;
+ if(S_OK != (hr = pSample->GetPointer(&pData)) || !pData) break;
+ memcpy(pData, p->GetData(), nBytes);
+ if(S_OK != (hr = pSample->SetActualDataLength(nBytes))) break;
+ if(S_OK != (hr = pSample->SetTime(fTimeValid ? &p->rtStart : NULL, fTimeValid ? &p->rtStop : NULL))) break;
+ if(S_OK != (hr = pSample->SetMediaTime(NULL, NULL))) break;
+ if(S_OK != (hr = pSample->SetDiscontinuity(p->bDiscontinuity))) break;
+ if(S_OK != (hr = pSample->SetSyncPoint(p->bSyncPoint))) break;
+ if(S_OK != (hr = pSample->SetPreroll(fTimeValid && p->rtStart < 0))) break;
+ if(S_OK != (hr = Deliver(pSample))) break;
+ }
+ while(false);
+
+ return hr;
}
void CBaseSplitterOutputPin::MakeISCRHappy()
{
- CComPtr<IPin> pPinTo = this, pTmp;
- while(pPinTo && SUCCEEDED(pPinTo->ConnectedTo(&pTmp)) && (pPinTo = pTmp))
- {
- pTmp = NULL;
+ CComPtr<IPin> pPinTo = this, pTmp;
+ while(pPinTo && SUCCEEDED(pPinTo->ConnectedTo(&pTmp)) && (pPinTo = pTmp))
+ {
+ pTmp = NULL;
- CComPtr<IBaseFilter> pBF = GetFilterFromPin(pPinTo);
+ CComPtr<IBaseFilter> pBF = GetFilterFromPin(pPinTo);
- if(GetCLSID(pBF) == GUIDFromCString(_T("{48025243-2D39-11CE-875D-00608CB78066}"))) // ISCR
- {
- CAutoPtr<Packet> p(DNew Packet());
- p->TrackNumber = (DWORD) - 1;
- p->rtStart = -1;
- p->rtStop = 0;
- p->bSyncPoint = FALSE;
- p->SetData(" ", 2);
- QueuePacket(p);
- break;
- }
+ if(GetCLSID(pBF) == GUIDFromCString(_T("{48025243-2D39-11CE-875D-00608CB78066}"))) // ISCR
+ {
+ CAutoPtr<Packet> p(DNew Packet());
+ p->TrackNumber = (DWORD)-1;
+ p->rtStart = -1; p->rtStop = 0;
+ p->bSyncPoint = FALSE;
+ p->SetData(" ", 2);
+ QueuePacket(p);
+ break;
+ }
- pPinTo = GetFirstPin(pBF, PINDIR_OUTPUT);
- }
+ pPinTo = GetFirstPin(pBF, PINDIR_OUTPUT);
+ }
}
HRESULT CBaseSplitterOutputPin::GetDeliveryBuffer(IMediaSample** ppSample, REFERENCE_TIME* pStartTime, REFERENCE_TIME* pEndTime, DWORD dwFlags)
{
- return __super::GetDeliveryBuffer(ppSample, pStartTime, pEndTime, dwFlags);
+ return __super::GetDeliveryBuffer(ppSample, pStartTime, pEndTime, dwFlags);
}
HRESULT CBaseSplitterOutputPin::Deliver(IMediaSample* pSample)
{
- return __super::Deliver(pSample);
+ return __super::Deliver(pSample);
}
// IMediaSeeking
STDMETHODIMP CBaseSplitterOutputPin::GetCapabilities(DWORD* pCapabilities)
{
- return (static_cast<CBaseSplitterFilter*>(m_pFilter))->GetCapabilities(pCapabilities);
+ return (static_cast<CBaseSplitterFilter*>(m_pFilter))->GetCapabilities(pCapabilities);
}
STDMETHODIMP CBaseSplitterOutputPin::CheckCapabilities(DWORD* pCapabilities)
{
- return (static_cast<CBaseSplitterFilter*>(m_pFilter))->CheckCapabilities(pCapabilities);
+ return (static_cast<CBaseSplitterFilter*>(m_pFilter))->CheckCapabilities(pCapabilities);
}
STDMETHODIMP CBaseSplitterOutputPin::IsFormatSupported(const GUID* pFormat)
{
- return (static_cast<CBaseSplitterFilter*>(m_pFilter))->IsFormatSupported(pFormat);
+ return (static_cast<CBaseSplitterFilter*>(m_pFilter))->IsFormatSupported(pFormat);
}
STDMETHODIMP CBaseSplitterOutputPin::QueryPreferredFormat(GUID* pFormat)
{
- return (static_cast<CBaseSplitterFilter*>(m_pFilter))->QueryPreferredFormat(pFormat);
+ return (static_cast<CBaseSplitterFilter*>(m_pFilter))->QueryPreferredFormat(pFormat);
}
STDMETHODIMP CBaseSplitterOutputPin::GetTimeFormat(GUID* pFormat)
{
- return (static_cast<CBaseSplitterFilter*>(m_pFilter))->GetTimeFormat(pFormat);
+ return (static_cast<CBaseSplitterFilter*>(m_pFilter))->GetTimeFormat(pFormat);
}
STDMETHODIMP CBaseSplitterOutputPin::IsUsingTimeFormat(const GUID* pFormat)
{
- return (static_cast<CBaseSplitterFilter*>(m_pFilter))->IsUsingTimeFormat(pFormat);
+ return (static_cast<CBaseSplitterFilter*>(m_pFilter))->IsUsingTimeFormat(pFormat);
}
STDMETHODIMP CBaseSplitterOutputPin::SetTimeFormat(const GUID* pFormat)
{
- return (static_cast<CBaseSplitterFilter*>(m_pFilter))->SetTimeFormat(pFormat);
+ return (static_cast<CBaseSplitterFilter*>(m_pFilter))->SetTimeFormat(pFormat);
}
STDMETHODIMP CBaseSplitterOutputPin::GetDuration(LONGLONG* pDuration)
{
- return (static_cast<CBaseSplitterFilter*>(m_pFilter))->GetDuration(pDuration);
+ return (static_cast<CBaseSplitterFilter*>(m_pFilter))->GetDuration(pDuration);
}
STDMETHODIMP CBaseSplitterOutputPin::GetStopPosition(LONGLONG* pStop)
{
- return (static_cast<CBaseSplitterFilter*>(m_pFilter))->GetStopPosition(pStop);
+ return (static_cast<CBaseSplitterFilter*>(m_pFilter))->GetStopPosition(pStop);
}
STDMETHODIMP CBaseSplitterOutputPin::GetCurrentPosition(LONGLONG* pCurrent)
{
- return (static_cast<CBaseSplitterFilter*>(m_pFilter))->GetCurrentPosition(pCurrent);
+ return (static_cast<CBaseSplitterFilter*>(m_pFilter))->GetCurrentPosition(pCurrent);
}
STDMETHODIMP CBaseSplitterOutputPin::ConvertTimeFormat(LONGLONG* pTarget, const GUID* pTargetFormat, LONGLONG Source, const GUID* pSourceFormat)
{
- return (static_cast<CBaseSplitterFilter*>(m_pFilter))->ConvertTimeFormat(pTarget, pTargetFormat, Source, pSourceFormat);
+ return (static_cast<CBaseSplitterFilter*>(m_pFilter))->ConvertTimeFormat(pTarget, pTargetFormat, Source, pSourceFormat);
}
STDMETHODIMP CBaseSplitterOutputPin::SetPositions(LONGLONG* pCurrent, DWORD dwCurrentFlags, LONGLONG* pStop, DWORD dwStopFlags)
{
- return (static_cast<CBaseSplitterFilter*>(m_pFilter))->SetPositionsInternal(this, pCurrent, dwCurrentFlags, pStop, dwStopFlags);
+ return (static_cast<CBaseSplitterFilter*>(m_pFilter))->SetPositionsInternal(this, pCurrent, dwCurrentFlags, pStop, dwStopFlags);
}
STDMETHODIMP CBaseSplitterOutputPin::GetPositions(LONGLONG* pCurrent, LONGLONG* pStop)
{
- return (static_cast<CBaseSplitterFilter*>(m_pFilter))->GetPositions(pCurrent, pStop);
+ return (static_cast<CBaseSplitterFilter*>(m_pFilter))->GetPositions(pCurrent, pStop);
}
STDMETHODIMP CBaseSplitterOutputPin::GetAvailable(LONGLONG* pEarliest, LONGLONG* pLatest)
{
- return (static_cast<CBaseSplitterFilter*>(m_pFilter))->GetAvailable(pEarliest, pLatest);
+ return (static_cast<CBaseSplitterFilter*>(m_pFilter))->GetAvailable(pEarliest, pLatest);
}
STDMETHODIMP CBaseSplitterOutputPin::SetRate(double dRate)
{
- return (static_cast<CBaseSplitterFilter*>(m_pFilter))->SetRate(dRate);
+ return (static_cast<CBaseSplitterFilter*>(m_pFilter))->SetRate(dRate);
}
STDMETHODIMP CBaseSplitterOutputPin::GetRate(double* pdRate)
{
- return (static_cast<CBaseSplitterFilter*>(m_pFilter))->GetRate(pdRate);
+ return (static_cast<CBaseSplitterFilter*>(m_pFilter))->GetRate(pdRate);
}
STDMETHODIMP CBaseSplitterOutputPin::GetPreroll(LONGLONG* pllPreroll)
{
- return (static_cast<CBaseSplitterFilter*>(m_pFilter))->GetPreroll(pllPreroll);
+ return (static_cast<CBaseSplitterFilter*>(m_pFilter))->GetPreroll(pllPreroll);
}
//
@@ -696,784 +695,729 @@ STDMETHODIMP CBaseSplitterOutputPin::GetPreroll(LONGLONG* pllPreroll)
//
CBaseSplitterFilter::CBaseSplitterFilter(LPCTSTR pName, LPUNKNOWN pUnk, HRESULT* phr, const CLSID& clsid)
- : CBaseFilter(pName, pUnk, this, clsid)
- , m_rtDuration(0), m_rtStart(0), m_rtStop(0), m_rtCurrent(0)
- , m_dRate(1.0)
- , m_nOpenProgress(100)
- , m_fAbort(false)
- , m_rtLastStart(_I64_MIN)
- , m_rtLastStop(_I64_MIN)
- , m_priority(THREAD_PRIORITY_NORMAL)
+ : CBaseFilter(pName, pUnk, this, clsid)
+ , m_rtDuration(0), m_rtStart(0), m_rtStop(0), m_rtCurrent(0)
+ , m_dRate(1.0)
+ , m_nOpenProgress(100)
+ , m_fAbort(false)
+ , m_rtLastStart(_I64_MIN)
+ , m_rtLastStop(_I64_MIN)
+ , m_priority(THREAD_PRIORITY_NORMAL)
{
- if(phr) *phr = S_OK;
+ if(phr) *phr = S_OK;
- m_pInput.Attach(DNew CBaseSplitterInputPin(NAME("CBaseSplitterInputPin"), this, this, phr));
+ m_pInput.Attach(DNew CBaseSplitterInputPin(NAME("CBaseSplitterInputPin"), this, this, phr));
}
CBaseSplitterFilter::~CBaseSplitterFilter()
{
- CAutoLock cAutoLock(this);
+ CAutoLock cAutoLock(this);
- CAMThread::CallWorker(CMD_EXIT);
- CAMThread::Close();
+ CAMThread::CallWorker(CMD_EXIT);
+ CAMThread::Close();
}
STDMETHODIMP CBaseSplitterFilter::NonDelegatingQueryInterface(REFIID riid, void** ppv)
{
- CheckPointer(ppv, E_POINTER);
+ CheckPointer(ppv, E_POINTER);
- *ppv = NULL;
+ *ppv = NULL;
- if(m_pInput && riid == __uuidof(IFileSourceFilter))
- return E_NOINTERFACE;
+ if(m_pInput && riid == __uuidof(IFileSourceFilter))
+ return E_NOINTERFACE;
- return
- QI(IFileSourceFilter)
- QI(IMediaSeeking)
- QI(IAMOpenProgress)
- QI2(IAMMediaContent)
- QI2(IAMExtendedSeeking)
- QI(IKeyFrameInfo)
- QI(IBufferInfo)
- QI(IPropertyBag)
- QI(IPropertyBag2)
- QI(IDSMPropertyBag)
- QI(IDSMResourceBag)
- QI(IDSMChapterBag)
- __super::NonDelegatingQueryInterface(riid, ppv);
+ return
+ QI(IFileSourceFilter)
+ QI(IMediaSeeking)
+ QI(IAMOpenProgress)
+ QI2(IAMMediaContent)
+ QI2(IAMExtendedSeeking)
+ QI(IKeyFrameInfo)
+ QI(IBufferInfo)
+ QI(IPropertyBag)
+ QI(IPropertyBag2)
+ QI(IDSMPropertyBag)
+ QI(IDSMResourceBag)
+ QI(IDSMChapterBag)
+ __super::NonDelegatingQueryInterface(riid, ppv);
}
CBaseSplitterOutputPin* CBaseSplitterFilter::GetOutputPin(DWORD TrackNum)
{
- CAutoLock cAutoLock(&m_csPinMap);
+ CAutoLock cAutoLock(&m_csPinMap);
CBaseSplitterOutputPin* pPin = NULL;
- m_pPinMap.Lookup(TrackNum, pPin);
- return pPin;
+ m_pPinMap.Lookup(TrackNum, pPin);
+ return pPin;
}
DWORD CBaseSplitterFilter::GetOutputTrackNum(CBaseSplitterOutputPin* pPin)
{
- CAutoLock cAutoLock(&m_csPinMap);
+ CAutoLock cAutoLock(&m_csPinMap);
- POSITION pos = m_pPinMap.GetStartPosition();
- while(pos)
- {
- DWORD TrackNum;
- CBaseSplitterOutputPin* pPinTmp;
- m_pPinMap.GetNextAssoc(pos, TrackNum, pPinTmp);
- if(pPinTmp == pPin) return TrackNum;
- }
+ POSITION pos = m_pPinMap.GetStartPosition();
+ while(pos)
+ {
+ DWORD TrackNum;
+ CBaseSplitterOutputPin* pPinTmp;
+ m_pPinMap.GetNextAssoc(pos, TrackNum, pPinTmp);
+ if(pPinTmp == pPin) return TrackNum;
+ }
- return (DWORD) - 1;
+ return (DWORD)-1;
}
HRESULT CBaseSplitterFilter::RenameOutputPin(DWORD TrackNumSrc, DWORD TrackNumDst, const AM_MEDIA_TYPE* pmt)
{
- CAutoLock cAutoLock(&m_csPinMap);
+ CAutoLock cAutoLock(&m_csPinMap);
- CBaseSplitterOutputPin* pPin;
- if(m_pPinMap.Lookup(TrackNumSrc, pPin))
- {
- if(CComQIPtr<IPin> pPinTo = pPin->GetConnected())
- {
- if(pmt && S_OK != pPinTo->QueryAccept(pmt))
- return VFW_E_TYPE_NOT_ACCEPTED;
- }
+ CBaseSplitterOutputPin* pPin;
+ if(m_pPinMap.Lookup(TrackNumSrc, pPin))
+ {
+ if(CComQIPtr<IPin> pPinTo = pPin->GetConnected())
+ {
+ if(pmt && S_OK != pPinTo->QueryAccept(pmt))
+ return VFW_E_TYPE_NOT_ACCEPTED;
+ }
- m_pPinMap.RemoveKey(TrackNumSrc);
- m_pPinMap[TrackNumDst] = pPin;
+ m_pPinMap.RemoveKey(TrackNumSrc);
+ m_pPinMap[TrackNumDst] = pPin;
- if(pmt)
- {
- CAutoLock cAutoLock(&m_csmtnew);
- m_mtnew[TrackNumDst] = *pmt;
- }
+ if(pmt)
+ {
+ CAutoLock cAutoLock(&m_csmtnew);
+ m_mtnew[TrackNumDst] = *pmt;
+ }
- return S_OK;
- }
+ return S_OK;
+ }
- return E_FAIL;
+ return E_FAIL;
}
HRESULT CBaseSplitterFilter::AddOutputPin(DWORD TrackNum, CAutoPtr<CBaseSplitterOutputPin> pPin)
{
- CAutoLock cAutoLock(&m_csPinMap);
+ CAutoLock cAutoLock(&m_csPinMap);
- if(!pPin) return E_INVALIDARG;
- m_pPinMap[TrackNum] = pPin;
- m_pOutputs.AddTail(pPin);
- return S_OK;
+ if(!pPin) return E_INVALIDARG;
+ m_pPinMap[TrackNum] = pPin;
+ m_pOutputs.AddTail(pPin);
+ return S_OK;
}
HRESULT CBaseSplitterFilter::DeleteOutputs()
{
- m_rtDuration = 0;
+ m_rtDuration = 0;
- m_pRetiredOutputs.RemoveAll();
+ m_pRetiredOutputs.RemoveAll();
- CAutoLock cAutoLockF(this);
- if(m_State != State_Stopped) return VFW_E_NOT_STOPPED;
+ CAutoLock cAutoLockF(this);
+ if(m_State != State_Stopped) return VFW_E_NOT_STOPPED;
- while(m_pOutputs.GetCount())
- {
- CAutoPtr<CBaseSplitterOutputPin> pPin = m_pOutputs.RemoveHead();
- if(IPin* pPinTo = pPin->GetConnected()) pPinTo->Disconnect();
- pPin->Disconnect();
- // we can't just let it be deleted now, something might have AddRefed on it (graphedit...)
- m_pRetiredOutputs.AddTail(pPin);
- }
+ while(m_pOutputs.GetCount())
+ {
+ CAutoPtr<CBaseSplitterOutputPin> pPin = m_pOutputs.RemoveHead();
+ if(IPin* pPinTo = pPin->GetConnected()) pPinTo->Disconnect();
+ pPin->Disconnect();
+ // we can't just let it be deleted now, something might have AddRefed on it (graphedit...)
+ m_pRetiredOutputs.AddTail(pPin);
+ }
- CAutoLock cAutoLockPM(&m_csPinMap);
- m_pPinMap.RemoveAll();
+ CAutoLock cAutoLockPM(&m_csPinMap);
+ m_pPinMap.RemoveAll();
- CAutoLock cAutoLockMT(&m_csmtnew);
- m_mtnew.RemoveAll();
+ CAutoLock cAutoLockMT(&m_csmtnew);
+ m_mtnew.RemoveAll();
- RemoveAll();
- ResRemoveAll();
- ChapRemoveAll();
+ RemoveAll();
+ ResRemoveAll();
+ ChapRemoveAll();
- m_fontinst.UninstallFonts();
+ m_fontinst.UninstallFonts();
- m_pSyncReader.Release();
+ m_pSyncReader.Release();
- return S_OK;
+ return S_OK;
}
void CBaseSplitterFilter::DeliverBeginFlush()
{
- m_fFlushing = true;
- POSITION pos = m_pOutputs.GetHeadPosition();
- while(pos) m_pOutputs.GetNext(pos)->DeliverBeginFlush();
+ m_fFlushing = true;
+ POSITION pos = m_pOutputs.GetHeadPosition();
+ while(pos) m_pOutputs.GetNext(pos)->DeliverBeginFlush();
}
void CBaseSplitterFilter::DeliverEndFlush()
{
- POSITION pos = m_pOutputs.GetHeadPosition();
- while(pos) m_pOutputs.GetNext(pos)->DeliverEndFlush();
- m_fFlushing = false;
- m_eEndFlush.Set();
+ POSITION pos = m_pOutputs.GetHeadPosition();
+ while(pos) m_pOutputs.GetNext(pos)->DeliverEndFlush();
+ m_fFlushing = false;
+ m_eEndFlush.Set();
}
DWORD CBaseSplitterFilter::ThreadProc()
{
- if(m_pSyncReader)
- m_pSyncReader->SetBreakEvent(GetRequestHandle());
+ if(m_pSyncReader)
+ m_pSyncReader->SetBreakEvent(GetRequestHandle());
- if(!DemuxInit())
- {
- while(1)
- {
- DWORD cmd = GetRequest();
- if(cmd == CMD_EXIT) CAMThread::m_hThread = NULL;
- Reply(S_OK);
- if(cmd == CMD_EXIT) return 0;
- }
- }
+ if(!DemuxInit())
+ {
+ while(1)
+ {
+ DWORD cmd = GetRequest();
+ if(cmd == CMD_EXIT) CAMThread::m_hThread = NULL;
+ Reply(S_OK);
+ if(cmd == CMD_EXIT) return 0;
+ }
+ }
- m_eEndFlush.Set();
- m_fFlushing = false;
+ m_eEndFlush.Set();
+ m_fFlushing = false;
- for(DWORD cmd = -1; ; cmd = GetRequest())
- {
- if(cmd == CMD_EXIT)
- {
- m_hThread = NULL;
- Reply(S_OK);
- return 0;
- }
+ for(DWORD cmd = -1; ; cmd = GetRequest())
+ {
+ if(cmd == CMD_EXIT)
+ {
+ m_hThread = NULL;
+ Reply(S_OK);
+ return 0;
+ }
- SetThreadPriority(m_hThread, m_priority = THREAD_PRIORITY_NORMAL);
+ SetThreadPriority(m_hThread, m_priority = THREAD_PRIORITY_NORMAL);
- m_rtStart = m_rtNewStart;
- m_rtStop = m_rtNewStop;
+ m_rtStart = m_rtNewStart;
+ m_rtStop = m_rtNewStop;
- DemuxSeek(m_rtStart);
+ DemuxSeek(m_rtStart);
- if(cmd != -1)
- Reply(S_OK);
+ if(cmd != -1)
+ Reply(S_OK);
- m_eEndFlush.Wait();
+ m_eEndFlush.Wait();
- m_pActivePins.RemoveAll();
+ m_pActivePins.RemoveAll();
- POSITION pos = m_pOutputs.GetHeadPosition();
- while(pos && !m_fFlushing)
- {
- CBaseSplitterOutputPin* pPin = m_pOutputs.GetNext(pos);
- if(pPin->IsConnected() && pPin->IsActive())
- {
- m_pActivePins.AddTail(pPin);
- pPin->DeliverNewSegment(m_rtStart, m_rtStop, m_dRate);
- }
- }
+ POSITION pos = m_pOutputs.GetHeadPosition();
+ while(pos && !m_fFlushing)
+ {
+ CBaseSplitterOutputPin* pPin = m_pOutputs.GetNext(pos);
+ if(pPin->IsConnected() && pPin->IsActive())
+ {
+ m_pActivePins.AddTail(pPin);
+ pPin->DeliverNewSegment(m_rtStart, m_rtStop, m_dRate);
+ }
+ }
- do
- {
- m_bDiscontinuitySent.RemoveAll();
- }
- while(!DemuxLoop());
+ do {m_bDiscontinuitySent.RemoveAll();}
+ while(!DemuxLoop());
- pos = m_pActivePins.GetHeadPosition();
- while(pos && !CheckRequest(&cmd))
- m_pActivePins.GetNext(pos)->QueueEndOfStream();
- }
+ pos = m_pActivePins.GetHeadPosition();
+ while(pos && !CheckRequest(&cmd))
+ m_pActivePins.GetNext(pos)->QueueEndOfStream();
+ }
- ASSERT(0); // we should only exit via CMD_EXIT
+ ASSERT(0); // we should only exit via CMD_EXIT
- m_hThread = NULL;
- return 0;
+ m_hThread = NULL;
+ return 0;
}
HRESULT CBaseSplitterFilter::DeliverPacket(CAutoPtr<Packet> p)
{
- HRESULT hr = S_FALSE;
+ HRESULT hr = S_FALSE;
- CBaseSplitterOutputPin* pPin = GetOutputPin(p->TrackNumber);
- if(!pPin || !pPin->IsConnected() || !m_pActivePins.Find(pPin))
- return S_FALSE;
+ CBaseSplitterOutputPin* pPin = GetOutputPin(p->TrackNumber);
+ if(!pPin || !pPin->IsConnected() || !m_pActivePins.Find(pPin))
+ return S_FALSE;
- if(p->rtStart != Packet::INVALID_TIME)
- {
- m_rtCurrent = p->rtStart;
+ if(p->rtStart != Packet::INVALID_TIME)
+ {
+ m_rtCurrent = p->rtStart;
- p->rtStart -= m_rtStart;
- p->rtStop -= m_rtStart;
+ p->rtStart -= m_rtStart;
+ p->rtStop -= m_rtStart;
- ASSERT(p->rtStart <= p->rtStop);
- }
+ ASSERT(p->rtStart <= p->rtStop);
+ }
- {
- CAutoLock cAutoLock(&m_csmtnew);
+ {
+ CAutoLock cAutoLock(&m_csmtnew);
- CMediaType mt;
- if(m_mtnew.Lookup(p->TrackNumber, mt))
- {
- p->pmt = CreateMediaType(&mt);
- m_mtnew.RemoveKey(p->TrackNumber);
- }
- }
+ CMediaType mt;
+ if(m_mtnew.Lookup(p->TrackNumber, mt))
+ {
+ p->pmt = CreateMediaType(&mt);
+ m_mtnew.RemoveKey(p->TrackNumber);
+ }
+ }
- if(!m_bDiscontinuitySent.Find(p->TrackNumber))
- p->bDiscontinuity = TRUE;
+ if(!m_bDiscontinuitySent.Find(p->TrackNumber))
+ p->bDiscontinuity = TRUE;
- DWORD TrackNumber = p->TrackNumber;
- BOOL bDiscontinuity = p->bDiscontinuity;
- /*
- //if(p->TrackNumber == 1)
- //if(p->rtStart != Packet::INVALID_TIME)
- TRACE(_T("[%d]: d%d s%d p%d, b=%d, %I64d-%I64d \n"),
- p->TrackNumber,
- p->bDiscontinuity, p->bSyncPoint, p->rtStart != Packet::INVALID_TIME && p->rtStart < 0,
- p->GetCount(), p->rtStart, p->rtStop);
- */
+ DWORD TrackNumber = p->TrackNumber;
+ BOOL bDiscontinuity = p->bDiscontinuity;
+/*
+//if(p->TrackNumber == 1)
+//if(p->rtStart != Packet::INVALID_TIME)
+TRACE(_T("[%d]: d%d s%d p%d, b=%d, %I64d-%I64d \n"),
+ p->TrackNumber,
+ p->bDiscontinuity, p->bSyncPoint, p->rtStart != Packet::INVALID_TIME && p->rtStart < 0,
+ p->GetCount(), p->rtStart, p->rtStop);
+*/
- hr = pPin->QueuePacket(p);
+ hr = pPin->QueuePacket(p);
- if(S_OK != hr)
- {
- if(POSITION pos = m_pActivePins.Find(pPin))
- m_pActivePins.RemoveAt(pos);
+ if(S_OK != hr)
+ {
+ if(POSITION pos = m_pActivePins.Find(pPin))
+ m_pActivePins.RemoveAt(pos);
- if(!m_pActivePins.IsEmpty()) // only die when all pins are down
- hr = S_OK;
+ if(!m_pActivePins.IsEmpty()) // only die when all pins are down
+ hr = S_OK;
- return hr;
- }
+ return hr;
+ }
- if(bDiscontinuity)
- m_bDiscontinuitySent.AddTail(TrackNumber);
+ if(bDiscontinuity)
+ m_bDiscontinuitySent.AddTail(TrackNumber);
- return hr;
+ return hr;
}
bool CBaseSplitterFilter::IsAnyPinDrying()
{
- int totalcount = 0, totalsize = 0;
+ int totalcount = 0, totalsize = 0;
- POSITION pos = m_pActivePins.GetHeadPosition();
- while(pos)
- {
- CBaseSplitterOutputPin* pPin = m_pActivePins.GetNext(pos);
- int count = pPin->QueueCount();
- int size = pPin->QueueSize();
- if(!pPin->IsDiscontinuous() && (count < MINPACKETS || size < MINPACKETSIZE))
- {
+ POSITION pos = m_pActivePins.GetHeadPosition();
+ while(pos)
+ {
+ CBaseSplitterOutputPin* pPin = m_pActivePins.GetNext(pos);
+ int count = pPin->QueueCount();
+ int size = pPin->QueueSize();
+ if(!pPin->IsDiscontinuous() && (count < MINPACKETS || size < MINPACKETSIZE))
+ {
// if(m_priority != THREAD_PRIORITY_ABOVE_NORMAL && (count < MINPACKETS/3 || size < MINPACKETSIZE/3))
- if(m_priority != THREAD_PRIORITY_BELOW_NORMAL && (count < MINPACKETS / 3 || size < MINPACKETSIZE / 3))
- {
- // SetThreadPriority(m_hThread, m_priority = THREAD_PRIORITY_ABOVE_NORMAL);
- POSITION pos = m_pOutputs.GetHeadPosition();
- while(pos) m_pOutputs.GetNext(pos)->SetThreadPriority(THREAD_PRIORITY_BELOW_NORMAL);
- m_priority = THREAD_PRIORITY_BELOW_NORMAL;
- }
- return(true);
- }
- totalcount += count;
- totalsize += size;
- }
-
- if(m_priority != THREAD_PRIORITY_NORMAL && (totalcount > MAXPACKETS * 2 / 3 || totalsize > MAXPACKETSIZE * 2 / 3))
- {
+ if(m_priority != THREAD_PRIORITY_BELOW_NORMAL && (count < MINPACKETS/3 || size < MINPACKETSIZE/3))
+ {
+ // SetThreadPriority(m_hThread, m_priority = THREAD_PRIORITY_ABOVE_NORMAL);
+ POSITION pos = m_pOutputs.GetHeadPosition();
+ while(pos) m_pOutputs.GetNext(pos)->SetThreadPriority(THREAD_PRIORITY_BELOW_NORMAL);
+ m_priority = THREAD_PRIORITY_BELOW_NORMAL;
+ }
+ return(true);
+ }
+ totalcount += count;
+ totalsize += size;
+ }
+
+ if(m_priority != THREAD_PRIORITY_NORMAL && (totalcount > MAXPACKETS*2/3 || totalsize > MAXPACKETSIZE*2/3))
+ {
// SetThreadPriority(m_hThread, m_priority = THREAD_PRIORITY_NORMAL);
- POSITION pos = m_pOutputs.GetHeadPosition();
- while(pos) m_pOutputs.GetNext(pos)->SetThreadPriority(THREAD_PRIORITY_NORMAL);
- m_priority = THREAD_PRIORITY_NORMAL;
- }
+ POSITION pos = m_pOutputs.GetHeadPosition();
+ while(pos) m_pOutputs.GetNext(pos)->SetThreadPriority(THREAD_PRIORITY_NORMAL);
+ m_priority = THREAD_PRIORITY_NORMAL;
+ }
- if(totalcount < MAXPACKETS && totalsize < MAXPACKETSIZE)
- return(true);
+ if(totalcount < MAXPACKETS && totalsize < MAXPACKETSIZE)
+ return(true);
- return(false);
+ return(false);
}
HRESULT CBaseSplitterFilter::BreakConnect(PIN_DIRECTION dir, CBasePin* pPin)
{
- CheckPointer(pPin, E_POINTER);
+ CheckPointer(pPin, E_POINTER);
- if(dir == PINDIR_INPUT)
- {
- DeleteOutputs();
- }
- else if(dir == PINDIR_OUTPUT)
- {
- }
- else
- {
- return E_UNEXPECTED;
- }
+ if(dir == PINDIR_INPUT)
+ {
+ DeleteOutputs();
+ }
+ else if(dir == PINDIR_OUTPUT)
+ {
+ }
+ else
+ {
+ return E_UNEXPECTED;
+ }
- return S_OK;
+ return S_OK;
}
HRESULT CBaseSplitterFilter::CompleteConnect(PIN_DIRECTION dir, CBasePin* pPin)
{
- CheckPointer(pPin, E_POINTER);
+ CheckPointer(pPin, E_POINTER);
- if(dir == PINDIR_INPUT)
- {
- CBaseSplitterInputPin* pIn = static_cast<CBaseSplitterInputPin*>(pPin);
+ if(dir == PINDIR_INPUT)
+ {
+ CBaseSplitterInputPin* pIn = static_cast<CBaseSplitterInputPin*>(pPin);
- HRESULT hr;
+ HRESULT hr;
- CComPtr<IAsyncReader> pAsyncReader;
- if(FAILED(hr = pIn->GetAsyncReader(&pAsyncReader))
- || FAILED(hr = DeleteOutputs())
- || FAILED(hr = CreateOutputs(pAsyncReader)))
- return hr;
+ CComPtr<IAsyncReader> pAsyncReader;
+ if(FAILED(hr = pIn->GetAsyncReader(&pAsyncReader))
+ || FAILED(hr = DeleteOutputs())
+ || FAILED(hr = CreateOutputs(pAsyncReader)))
+ return hr;
- ChapSort();
+ ChapSort();
- m_pSyncReader = pAsyncReader;
- }
- else if(dir == PINDIR_OUTPUT)
- {
- m_pRetiredOutputs.RemoveAll();
- }
- else
- {
- return E_UNEXPECTED;
- }
+ m_pSyncReader = pAsyncReader;
+ }
+ else if(dir == PINDIR_OUTPUT)
+ {
+ m_pRetiredOutputs.RemoveAll();
+ }
+ else
+ {
+ return E_UNEXPECTED;
+ }
- return S_OK;
+ return S_OK;
}
int CBaseSplitterFilter::GetPinCount()
{
- return (m_pInput ? 1 : 0) + m_pOutputs.GetCount();
+ return (m_pInput ? 1 : 0) + m_pOutputs.GetCount();
}
CBasePin* CBaseSplitterFilter::GetPin(int n)
{
CAutoLock cAutoLock(this);
- if(n >= 0 && n < (int)m_pOutputs.GetCount())
- {
- if(POSITION pos = m_pOutputs.FindIndex(n))
- return m_pOutputs.GetAt(pos);
- }
+ if(n >= 0 && n < (int)m_pOutputs.GetCount())
+ {
+ if(POSITION pos = m_pOutputs.FindIndex(n))
+ return m_pOutputs.GetAt(pos);
+ }
- if(n == m_pOutputs.GetCount() && m_pInput)
- {
- return m_pInput;
- }
+ if(n == m_pOutputs.GetCount() && m_pInput)
+ {
+ return m_pInput;
+ }
- return NULL;
+ return NULL;
}
STDMETHODIMP CBaseSplitterFilter::Stop()
{
- CAutoLock cAutoLock(this);
+ CAutoLock cAutoLock(this);
- DeliverBeginFlush();
- CallWorker(CMD_EXIT);
- DeliverEndFlush();
+ DeliverBeginFlush();
+ CallWorker(CMD_EXIT);
+ DeliverEndFlush();
- HRESULT hr;
- if(FAILED(hr = __super::Stop()))
- return hr;
+ HRESULT hr;
+ if(FAILED(hr = __super::Stop()))
+ return hr;
- return S_OK;
+ return S_OK;
}
STDMETHODIMP CBaseSplitterFilter::Pause()
{
- CAutoLock cAutoLock(this);
+ CAutoLock cAutoLock(this);
- FILTER_STATE fs = m_State;
+ FILTER_STATE fs = m_State;
- HRESULT hr;
- if(FAILED(hr = __super::Pause()))
- return hr;
+ HRESULT hr;
+ if(FAILED(hr = __super::Pause()))
+ return hr;
- if(fs == State_Stopped)
- {
- Create();
- }
+ if(fs == State_Stopped)
+ {
+ Create();
+ }
- return S_OK;
+ return S_OK;
}
STDMETHODIMP CBaseSplitterFilter::Run(REFERENCE_TIME tStart)
{
- CAutoLock cAutoLock(this);
+ CAutoLock cAutoLock(this);
- HRESULT hr;
- if(FAILED(hr = __super::Run(tStart)))
- return hr;
+ HRESULT hr;
+ if(FAILED(hr = __super::Run(tStart)))
+ return hr;
- return S_OK;
+ return S_OK;
}
// IFileSourceFilter
STDMETHODIMP CBaseSplitterFilter::Load(LPCOLESTR pszFileName, const AM_MEDIA_TYPE* pmt)
{
- CheckPointer(pszFileName, E_POINTER);
+ CheckPointer(pszFileName, E_POINTER);
- m_fn = pszFileName;
- HRESULT hr = E_FAIL;
- CComPtr<IAsyncReader> pAsyncReader;
- CAtlList<CHdmvClipInfo::PlaylistItem> Items;
- if(BuildPlaylist(pszFileName, Items))
- pAsyncReader = (IAsyncReader*)DNew CAsyncFileReader(Items, hr);
- else
- pAsyncReader = (IAsyncReader*)DNew CAsyncFileReader(CString(pszFileName), hr);
- if(FAILED(hr)
- || FAILED(hr = DeleteOutputs())
- || FAILED(hr = CreateOutputs(pAsyncReader)))
- {
- m_fn = "";
- return hr;
- }
+ m_fn = pszFileName;
+ HRESULT hr = E_FAIL;
+ CComPtr<IAsyncReader> pAsyncReader;
+ CAtlList<CHdmvClipInfo::PlaylistItem> Items;
+ if (BuildPlaylist (pszFileName, Items))
+ pAsyncReader = (IAsyncReader*)DNew CAsyncFileReader(Items, hr);
+ else
+ pAsyncReader = (IAsyncReader*)DNew CAsyncFileReader(CString(pszFileName), hr);
+ if(FAILED(hr)
+ || FAILED(hr = DeleteOutputs())
+ || FAILED(hr = CreateOutputs(pAsyncReader)))
+ {
+ m_fn = "";
+ return hr;
+ }
- ChapSort();
+ ChapSort();
- m_pSyncReader = pAsyncReader;
+ m_pSyncReader = pAsyncReader;
- return S_OK;
+ return S_OK;
}
STDMETHODIMP CBaseSplitterFilter::GetCurFile(LPOLESTR* ppszFileName, AM_MEDIA_TYPE* pmt)
{
- CheckPointer(ppszFileName, E_POINTER);
- if(!(*ppszFileName = (LPOLESTR)CoTaskMemAlloc((m_fn.GetLength() + 1) * sizeof(WCHAR))))
- return E_OUTOFMEMORY;
- wcscpy(*ppszFileName, m_fn);
- return S_OK;
+ CheckPointer(ppszFileName, E_POINTER);
+ if(!(*ppszFileName = (LPOLESTR)CoTaskMemAlloc((m_fn.GetLength()+1)*sizeof(WCHAR))))
+ return E_OUTOFMEMORY;
+ wcscpy(*ppszFileName, m_fn);
+ return S_OK;
}
LPCTSTR CBaseSplitterFilter::GetPartFilename(IAsyncReader* pAsyncReader)
{
- CComQIPtr<IFileHandle> pFH = pAsyncReader;
- return pFH ? pFH->GetFileName() : m_fn;
+ CComQIPtr<IFileHandle> pFH = pAsyncReader;
+ return pFH ? pFH->GetFileName() : m_fn;
}
// IMediaSeeking
STDMETHODIMP CBaseSplitterFilter::GetCapabilities(DWORD* pCapabilities)
{
- return pCapabilities ? *pCapabilities =
- AM_SEEKING_CanGetStopPos |
- AM_SEEKING_CanGetDuration |
- AM_SEEKING_CanSeekAbsolute |
- AM_SEEKING_CanSeekForwards |
- AM_SEEKING_CanSeekBackwards, S_OK : E_POINTER;
+ return pCapabilities ? *pCapabilities =
+ AM_SEEKING_CanGetStopPos|
+ AM_SEEKING_CanGetDuration|
+ AM_SEEKING_CanSeekAbsolute|
+ AM_SEEKING_CanSeekForwards|
+ AM_SEEKING_CanSeekBackwards, S_OK : E_POINTER;
}
STDMETHODIMP CBaseSplitterFilter::CheckCapabilities(DWORD* pCapabilities)
{
- CheckPointer(pCapabilities, E_POINTER);
- if(*pCapabilities == 0) return S_OK;
- DWORD caps;
- GetCapabilities(&caps);
- if((caps&*pCapabilities) == 0) return E_FAIL;
- if(caps == *pCapabilities) return S_OK;
- return S_FALSE;
-}
-STDMETHODIMP CBaseSplitterFilter::IsFormatSupported(const GUID* pFormat)
-{
- return !pFormat ? E_POINTER : *pFormat == TIME_FORMAT_MEDIA_TIME ? S_OK : S_FALSE;
-}
-STDMETHODIMP CBaseSplitterFilter::QueryPreferredFormat(GUID* pFormat)
-{
- return GetTimeFormat(pFormat);
-}
-STDMETHODIMP CBaseSplitterFilter::GetTimeFormat(GUID* pFormat)
-{
- return pFormat ? *pFormat = TIME_FORMAT_MEDIA_TIME, S_OK : E_POINTER;
-}
-STDMETHODIMP CBaseSplitterFilter::IsUsingTimeFormat(const GUID* pFormat)
-{
- return IsFormatSupported(pFormat);
-}
-STDMETHODIMP CBaseSplitterFilter::SetTimeFormat(const GUID* pFormat)
-{
- return S_OK == IsFormatSupported(pFormat) ? S_OK : E_INVALIDARG;
-}
-STDMETHODIMP CBaseSplitterFilter::GetDuration(LONGLONG* pDuration)
-{
- CheckPointer(pDuration, E_POINTER);
- *pDuration = m_rtDuration;
- return S_OK;
-}
-STDMETHODIMP CBaseSplitterFilter::GetStopPosition(LONGLONG* pStop)
-{
- return GetDuration(pStop);
-}
-STDMETHODIMP CBaseSplitterFilter::GetCurrentPosition(LONGLONG* pCurrent)
-{
- return E_NOTIMPL;
-}
-STDMETHODIMP CBaseSplitterFilter::ConvertTimeFormat(LONGLONG* pTarget, const GUID* pTargetFormat, LONGLONG Source, const GUID* pSourceFormat)
-{
- return E_NOTIMPL;
-}
+ CheckPointer(pCapabilities, E_POINTER);
+ if(*pCapabilities == 0) return S_OK;
+ DWORD caps;
+ GetCapabilities(&caps);
+ if((caps&*pCapabilities) == 0) return E_FAIL;
+ if(caps == *pCapabilities) return S_OK;
+ return S_FALSE;
+}
+STDMETHODIMP CBaseSplitterFilter::IsFormatSupported(const GUID* pFormat) {return !pFormat ? E_POINTER : *pFormat == TIME_FORMAT_MEDIA_TIME ? S_OK : S_FALSE;}
+STDMETHODIMP CBaseSplitterFilter::QueryPreferredFormat(GUID* pFormat) {return GetTimeFormat(pFormat);}
+STDMETHODIMP CBaseSplitterFilter::GetTimeFormat(GUID* pFormat) {return pFormat ? *pFormat = TIME_FORMAT_MEDIA_TIME, S_OK : E_POINTER;}
+STDMETHODIMP CBaseSplitterFilter::IsUsingTimeFormat(const GUID* pFormat) {return IsFormatSupported(pFormat);}
+STDMETHODIMP CBaseSplitterFilter::SetTimeFormat(const GUID* pFormat) {return S_OK == IsFormatSupported(pFormat) ? S_OK : E_INVALIDARG;}
+STDMETHODIMP CBaseSplitterFilter::GetDuration(LONGLONG* pDuration) {CheckPointer(pDuration, E_POINTER); *pDuration = m_rtDuration; return S_OK;}
+STDMETHODIMP CBaseSplitterFilter::GetStopPosition(LONGLONG* pStop) {return GetDuration(pStop);}
+STDMETHODIMP CBaseSplitterFilter::GetCurrentPosition(LONGLONG* pCurrent) {return E_NOTIMPL;}
+STDMETHODIMP CBaseSplitterFilter::ConvertTimeFormat(LONGLONG* pTarget, const GUID* pTargetFormat, LONGLONG Source, const GUID* pSourceFormat) {return E_NOTIMPL;}
STDMETHODIMP CBaseSplitterFilter::SetPositions(LONGLONG* pCurrent, DWORD dwCurrentFlags, LONGLONG* pStop, DWORD dwStopFlags)
{
- return SetPositionsInternal(this, pCurrent, dwCurrentFlags, pStop, dwStopFlags);
+ return SetPositionsInternal(this, pCurrent, dwCurrentFlags, pStop, dwStopFlags);
}
STDMETHODIMP CBaseSplitterFilter::GetPositions(LONGLONG* pCurrent, LONGLONG* pStop)
{
- if(pCurrent) *pCurrent = m_rtCurrent;
- if(pStop) *pStop = m_rtStop;
- return S_OK;
+ if(pCurrent) *pCurrent = m_rtCurrent;
+ if(pStop) *pStop = m_rtStop;
+ return S_OK;
}
STDMETHODIMP CBaseSplitterFilter::GetAvailable(LONGLONG* pEarliest, LONGLONG* pLatest)
{
- if(pEarliest) *pEarliest = 0;
- return GetDuration(pLatest);
-}
-STDMETHODIMP CBaseSplitterFilter::SetRate(double dRate)
-{
- return dRate > 0 ? m_dRate = dRate, S_OK : E_INVALIDARG;
-}
-STDMETHODIMP CBaseSplitterFilter::GetRate(double* pdRate)
-{
- return pdRate ? *pdRate = m_dRate, S_OK : E_POINTER;
-}
-STDMETHODIMP CBaseSplitterFilter::GetPreroll(LONGLONG* pllPreroll)
-{
- return pllPreroll ? *pllPreroll = 0, S_OK : E_POINTER;
+ if(pEarliest) *pEarliest = 0;
+ return GetDuration(pLatest);
}
+STDMETHODIMP CBaseSplitterFilter::SetRate(double dRate) {return dRate > 0 ? m_dRate = dRate, S_OK : E_INVALIDARG;}
+STDMETHODIMP CBaseSplitterFilter::GetRate(double* pdRate) {return pdRate ? *pdRate = m_dRate, S_OK : E_POINTER;}
+STDMETHODIMP CBaseSplitterFilter::GetPreroll(LONGLONG* pllPreroll) {return pllPreroll ? *pllPreroll = 0, S_OK : E_POINTER;}
HRESULT CBaseSplitterFilter::SetPositionsInternal(void* id, LONGLONG* pCurrent, DWORD dwCurrentFlags, LONGLONG* pStop, DWORD dwStopFlags)
{
- CAutoLock cAutoLock(this);
+ CAutoLock cAutoLock(this);
+
+ if(!pCurrent && !pStop
+ || (dwCurrentFlags&AM_SEEKING_PositioningBitsMask) == AM_SEEKING_NoPositioning
+ && (dwStopFlags&AM_SEEKING_PositioningBitsMask) == AM_SEEKING_NoPositioning)
+ return S_OK;
+
+ REFERENCE_TIME
+ rtCurrent = m_rtCurrent,
+ rtStop = m_rtStop;
+
+ if(pCurrent)
+ switch(dwCurrentFlags&AM_SEEKING_PositioningBitsMask)
+ {
+ case AM_SEEKING_NoPositioning: break;
+ case AM_SEEKING_AbsolutePositioning: rtCurrent = *pCurrent; break;
+ case AM_SEEKING_RelativePositioning: rtCurrent = rtCurrent + *pCurrent; break;
+ case AM_SEEKING_IncrementalPositioning: rtCurrent = rtCurrent + *pCurrent; break;
+ }
+
+ if(pStop)
+ switch(dwStopFlags&AM_SEEKING_PositioningBitsMask)
+ {
+ case AM_SEEKING_NoPositioning: break;
+ case AM_SEEKING_AbsolutePositioning: rtStop = *pStop; break;
+ case AM_SEEKING_RelativePositioning: rtStop += *pStop; break;
+ case AM_SEEKING_IncrementalPositioning: rtStop = rtCurrent + *pStop; break;
+ }
+
+ if(m_rtCurrent == rtCurrent && m_rtStop == rtStop)
+ return S_OK;
- if(!pCurrent && !pStop
- || (dwCurrentFlags & AM_SEEKING_PositioningBitsMask) == AM_SEEKING_NoPositioning
- && (dwStopFlags & AM_SEEKING_PositioningBitsMask) == AM_SEEKING_NoPositioning)
- return S_OK;
-
- REFERENCE_TIME
- rtCurrent = m_rtCurrent,
- rtStop = m_rtStop;
-
- if(pCurrent)
- switch(dwCurrentFlags & AM_SEEKING_PositioningBitsMask)
- {
- case AM_SEEKING_NoPositioning:
- break;
- case AM_SEEKING_AbsolutePositioning:
- rtCurrent = *pCurrent;
- break;
- case AM_SEEKING_RelativePositioning:
- rtCurrent = rtCurrent + *pCurrent;
- break;
- case AM_SEEKING_IncrementalPositioning:
- rtCurrent = rtCurrent + *pCurrent;
- break;
- }
-
- if(pStop)
- switch(dwStopFlags & AM_SEEKING_PositioningBitsMask)
- {
- case AM_SEEKING_NoPositioning:
- break;
- case AM_SEEKING_AbsolutePositioning:
- rtStop = *pStop;
- break;
- case AM_SEEKING_RelativePositioning:
- rtStop += *pStop;
- break;
- case AM_SEEKING_IncrementalPositioning:
- rtStop = rtCurrent + *pStop;
- break;
- }
-
- if(m_rtCurrent == rtCurrent && m_rtStop == rtStop)
- return S_OK;
-
- if(m_rtLastStart == rtCurrent && m_rtLastStop == rtStop && !m_LastSeekers.Find(id))
- {
- m_LastSeekers.AddTail(id);
- return S_OK;
- }
-
- m_rtLastStart = rtCurrent;
- m_rtLastStop = rtStop;
- m_LastSeekers.RemoveAll();
- m_LastSeekers.AddTail(id);
-
- DbgLog((LOG_TRACE, 0, _T("Seek Started %I64d"), rtCurrent));
-
- m_rtNewStart = m_rtCurrent = rtCurrent;
- m_rtNewStop = rtStop;
-
- if(ThreadExists())
- {
- DeliverBeginFlush();
- CallWorker(CMD_SEEK);
- DeliverEndFlush();
- }
-
- DbgLog((LOG_TRACE, 0, _T("Seek Ended")));
-
- return S_OK;
+ if(m_rtLastStart == rtCurrent && m_rtLastStop == rtStop && !m_LastSeekers.Find(id))
+ {
+ m_LastSeekers.AddTail(id);
+ return S_OK;
+ }
+
+ m_rtLastStart = rtCurrent;
+ m_rtLastStop = rtStop;
+ m_LastSeekers.RemoveAll();
+ m_LastSeekers.AddTail(id);
+
+DbgLog((LOG_TRACE, 0, _T("Seek Started %I64d"), rtCurrent));
+
+ m_rtNewStart = m_rtCurrent = rtCurrent;
+ m_rtNewStop = rtStop;
+
+ if(ThreadExists())
+ {
+ DeliverBeginFlush();
+ CallWorker(CMD_SEEK);
+ DeliverEndFlush();
+ }
+
+DbgLog((LOG_TRACE, 0, _T("Seek Ended")));
+
+ return S_OK;
}
// IAMOpenProgress
STDMETHODIMP CBaseSplitterFilter::QueryProgress(LONGLONG* pllTotal, LONGLONG* pllCurrent)
{
- CheckPointer(pllTotal, E_POINTER);
- CheckPointer(pllCurrent, E_POINTER);
+ CheckPointer(pllTotal, E_POINTER);
+ CheckPointer(pllCurrent, E_POINTER);
- *pllTotal = 100;
- *pllCurrent = m_nOpenProgress;
+ *pllTotal = 100;
+ *pllCurrent = m_nOpenProgress;
- return S_OK;
+ return S_OK;
}
STDMETHODIMP CBaseSplitterFilter::AbortOperation()
{
- m_fAbort = true;
- return S_OK;
+ m_fAbort = true;
+ return S_OK;
}
// IAMMediaContent
STDMETHODIMP CBaseSplitterFilter::get_AuthorName(BSTR* pbstrAuthorName)
{
- return GetProperty(L"AUTH", pbstrAuthorName);
+ return GetProperty(L"AUTH", pbstrAuthorName);
}
STDMETHODIMP CBaseSplitterFilter::get_Title(BSTR* pbstrTitle)
{
- return GetProperty(L"TITL", pbstrTitle);
+ return GetProperty(L"TITL", pbstrTitle);
}
STDMETHODIMP CBaseSplitterFilter::get_Rating(BSTR* pbstrRating)
{
- return GetProperty(L"RTNG", pbstrRating);
+ return GetProperty(L"RTNG", pbstrRating);
}
STDMETHODIMP CBaseSplitterFilter::get_Description(BSTR* pbstrDescription)
{
- return GetProperty(L"DESC", pbstrDescription);
+ return GetProperty(L"DESC", pbstrDescription);
}
STDMETHODIMP CBaseSplitterFilter::get_Copyright(BSTR* pbstrCopyright)
{
- return GetProperty(L"CPYR", pbstrCopyright);
+ return GetProperty(L"CPYR", pbstrCopyright);
}
// IAMExtendedSeeking
STDMETHODIMP CBaseSplitterFilter::get_ExSeekCapabilities(long* pExCapabilities)
{
- CheckPointer(pExCapabilities, E_POINTER);
- *pExCapabilities = AM_EXSEEK_CANSEEK;
- if(ChapGetCount()) *pExCapabilities |= AM_EXSEEK_MARKERSEEK;
- return S_OK;
+ CheckPointer(pExCapabilities, E_POINTER);
+ *pExCapabilities = AM_EXSEEK_CANSEEK;
+ if(ChapGetCount()) *pExCapabilities |= AM_EXSEEK_MARKERSEEK;
+ return S_OK;
}
STDMETHODIMP CBaseSplitterFilter::get_MarkerCount(long* pMarkerCount)
{
- CheckPointer(pMarkerCount, E_POINTER);
- *pMarkerCount = (long)ChapGetCount();
- return S_OK;
+ CheckPointer(pMarkerCount, E_POINTER);
+ *pMarkerCount = (long)ChapGetCount();
+ return S_OK;
}
STDMETHODIMP CBaseSplitterFilter::get_CurrentMarker(long* pCurrentMarker)
{
- CheckPointer(pCurrentMarker, E_POINTER);
- REFERENCE_TIME rt = m_rtCurrent;
- long i = ChapLookup(&rt);
- if(i < 0) return E_FAIL;
- *pCurrentMarker = i + 1;
- return S_OK;
+ CheckPointer(pCurrentMarker, E_POINTER);
+ REFERENCE_TIME rt = m_rtCurrent;
+ long i = ChapLookup(&rt);
+ if(i < 0) return E_FAIL;
+ *pCurrentMarker = i+1;
+ return S_OK;
}
STDMETHODIMP CBaseSplitterFilter::GetMarkerTime(long MarkerNum, double* pMarkerTime)
{
- CheckPointer(pMarkerTime, E_POINTER);
- REFERENCE_TIME rt;
- if(FAILED(ChapGet((int)MarkerNum - 1, &rt))) return E_FAIL;
- *pMarkerTime = (double)rt / 10000000;
- return S_OK;
+ CheckPointer(pMarkerTime, E_POINTER);
+ REFERENCE_TIME rt;
+ if(FAILED(ChapGet((int)MarkerNum-1, &rt))) return E_FAIL;
+ *pMarkerTime = (double)rt / 10000000;
+ return S_OK;
}
STDMETHODIMP CBaseSplitterFilter::GetMarkerName(long MarkerNum, BSTR* pbstrMarkerName)
{
- return ChapGet((int)MarkerNum - 1, NULL, pbstrMarkerName);
+ return ChapGet((int)MarkerNum-1, NULL, pbstrMarkerName);
}
// IKeyFrameInfo
STDMETHODIMP CBaseSplitterFilter::GetKeyFrameCount(UINT& nKFs)
{
- return E_NOTIMPL;
+ return E_NOTIMPL;
}
STDMETHODIMP CBaseSplitterFilter::GetKeyFrames(const GUID* pFormat, REFERENCE_TIME* pKFs, UINT& nKFs)
{
- return E_NOTIMPL;
+ return E_NOTIMPL;
}
// IBufferInfo
STDMETHODIMP_(int) CBaseSplitterFilter::GetCount()
{
- CAutoLock cAutoLock(m_pLock);
+ CAutoLock cAutoLock(m_pLock);
- return m_pOutputs.GetCount();
+ return m_pOutputs.GetCount();
}
STDMETHODIMP CBaseSplitterFilter::GetStatus(int i, int& samples, int& size)
{
- CAutoLock cAutoLock(m_pLock);
+ CAutoLock cAutoLock(m_pLock);
- if(POSITION pos = m_pOutputs.FindIndex(i))
- {
- CBaseSplitterOutputPin* pPin = m_pOutputs.GetAt(pos);
- samples = pPin->QueueCount();
- size = pPin->QueueSize();
- return pPin->IsConnected() ? S_OK : S_FALSE;
- }
+ if(POSITION pos = m_pOutputs.FindIndex(i))
+ {
+ CBaseSplitterOutputPin* pPin = m_pOutputs.GetAt(pos);
+ samples = pPin->QueueCount();
+ size = pPin->QueueSize();
+ return pPin->IsConnected() ? S_OK : S_FALSE;
+ }
- return E_INVALIDARG;
+ return E_INVALIDARG;
}
STDMETHODIMP_(DWORD) CBaseSplitterFilter::GetPriority()
diff --git a/src/filters/parser/BaseSplitter/BaseSplitter.h b/src/filters/parser/BaseSplitter/BaseSplitter.h
index e8bb0d5f5..68114f7e7 100644
--- a/src/filters/parser/BaseSplitter/BaseSplitter.h
+++ b/src/filters/parser/BaseSplitter/BaseSplitter.h
@@ -1,4 +1,4 @@
-/*
+/*
* Copyright (C) 2003-2006 Gabest
* http://www.gabest.org
*
@@ -6,15 +6,15 @@
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2, or (at your option)
* any later version.
- *
+ *
* This Program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with GNU Make; see the file COPYING. If not, write to
- * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
+ * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
* http://www.gnu.org/copyleft/gpl.html
*
*/
@@ -35,416 +35,341 @@
class Packet : public CAtlArray<BYTE>
{
public:
- DWORD TrackNumber;
- BOOL bDiscontinuity, bSyncPoint, bAppendable;
- static const REFERENCE_TIME INVALID_TIME = _I64_MIN;
- REFERENCE_TIME rtStart, rtStop;
- AM_MEDIA_TYPE* pmt;
- Packet()
- {
- pmt = NULL;
- bDiscontinuity = bAppendable = FALSE;
- }
- virtual ~Packet()
- {
- if(pmt) DeleteMediaType(pmt);
- }
- virtual int GetDataSize()
- {
- return GetCount();
- }
- void SetData(const void* ptr, DWORD len)
- {
- SetCount(len);
- memcpy(GetData(), ptr, len);
- }
+ DWORD TrackNumber;
+ BOOL bDiscontinuity, bSyncPoint, bAppendable;
+ static const REFERENCE_TIME INVALID_TIME = _I64_MIN;
+ REFERENCE_TIME rtStart, rtStop;
+ AM_MEDIA_TYPE* pmt;
+ Packet() {pmt = NULL; bDiscontinuity = bAppendable = FALSE;}
+ virtual ~Packet() {if(pmt) DeleteMediaType(pmt);}
+ virtual int GetDataSize() {return GetCount();}
+ void SetData(const void* ptr, DWORD len) {SetCount(len); memcpy(GetData(), ptr, len);}
};
-class CPacketQueue
- : public CCritSec
- , protected CAutoPtrList<Packet>
+class CPacketQueue
+ : public CCritSec
+ , protected CAutoPtrList<Packet>
{
- int m_size;
+ int m_size;
public:
- CPacketQueue();
- void Add(CAutoPtr<Packet> p);
- CAutoPtr<Packet> Remove();
- void RemoveAll();
- int GetCount(), GetSize();
+ CPacketQueue();
+ void Add(CAutoPtr<Packet> p);
+ CAutoPtr<Packet> Remove();
+ void RemoveAll();
+ int GetCount(), GetSize();
};
class CBaseSplitterFilter;
-class CBaseSplitterInputPin
- : public CBasePin
+class CBaseSplitterInputPin
+ : public CBasePin
{
protected:
- CComQIPtr<IAsyncReader> m_pAsyncReader;
+ CComQIPtr<IAsyncReader> m_pAsyncReader;
public:
- CBaseSplitterInputPin(TCHAR* pName, CBaseSplitterFilter* pFilter, CCritSec* pLock, HRESULT* phr);
- virtual ~CBaseSplitterInputPin();
+ CBaseSplitterInputPin(TCHAR* pName, CBaseSplitterFilter* pFilter, CCritSec* pLock, HRESULT* phr);
+ virtual ~CBaseSplitterInputPin();
- HRESULT GetAsyncReader(IAsyncReader** ppAsyncReader);
+ HRESULT GetAsyncReader(IAsyncReader** ppAsyncReader);
- DECLARE_IUNKNOWN;
+ DECLARE_IUNKNOWN;
STDMETHODIMP NonDelegatingQueryInterface(REFIID riid, void** ppv);
HRESULT CheckMediaType(const CMediaType* pmt);
HRESULT CheckConnect(IPin* pPin);
HRESULT BreakConnect();
- HRESULT CompleteConnect(IPin* pPin);
+ HRESULT CompleteConnect(IPin* pPin);
- STDMETHODIMP BeginFlush();
- STDMETHODIMP EndFlush();
+ STDMETHODIMP BeginFlush();
+ STDMETHODIMP EndFlush();
};
-class CBaseSplitterOutputPin
- : public CBaseOutputPin
- , public IDSMPropertyBagImpl
- , protected CAMThread
- , public IMediaSeeking
- , public IBitRateInfo
+class CBaseSplitterOutputPin
+ : public CBaseOutputPin
+ , public IDSMPropertyBagImpl
+ , protected CAMThread
+ , public IMediaSeeking
+ , public IBitRateInfo
{
protected:
- CAtlArray<CMediaType> m_mts;
- int m_nBuffers;
+ CAtlArray<CMediaType> m_mts;
+ int m_nBuffers;
private:
- CPacketQueue m_queue;
+ CPacketQueue m_queue;
- HRESULT m_hrDeliver;
+ HRESULT m_hrDeliver;
- bool m_fFlushing, m_fFlushed;
- CAMEvent m_eEndFlush;
+ bool m_fFlushing, m_fFlushed;
+ CAMEvent m_eEndFlush;
- enum {CMD_EXIT};
+ enum {CMD_EXIT};
DWORD ThreadProc();
- void MakeISCRHappy();
+ void MakeISCRHappy();
- // please only use DeliverPacket from the derived class
+ // please only use DeliverPacket from the derived class
HRESULT GetDeliveryBuffer(IMediaSample** ppSample, REFERENCE_TIME* pStartTime, REFERENCE_TIME* pEndTime, DWORD dwFlags);
HRESULT Deliver(IMediaSample* pSample);
- // bitrate stats
+ // bitrate stats
- struct
- {
- UINT64 nTotalBytesDelivered;
- REFERENCE_TIME rtTotalTimeDelivered;
- UINT64 nBytesSinceLastDeliverTime;
- REFERENCE_TIME rtLastDeliverTime;
- DWORD nCurrentBitRate;
- DWORD nAverageBitRate;
- } m_brs;
+ struct
+ {
+ UINT64 nTotalBytesDelivered;
+ REFERENCE_TIME rtTotalTimeDelivered;
+ UINT64 nBytesSinceLastDeliverTime;
+ REFERENCE_TIME rtLastDeliverTime;
+ DWORD nCurrentBitRate;
+ DWORD nAverageBitRate;
+ } m_brs;
protected:
- REFERENCE_TIME m_rtStart;
-
- // override this if you need some second level stream specific demuxing (optional)
- // the default implementation will send the sample as is
- virtual HRESULT DeliverPacket(CAutoPtr<Packet> p);
-
- // IMediaSeeking
-
- STDMETHODIMP GetCapabilities(DWORD* pCapabilities);
- STDMETHODIMP CheckCapabilities(DWORD* pCapabilities);
- STDMETHODIMP IsFormatSupported(const GUID* pFormat);
- STDMETHODIMP QueryPreferredFormat(GUID* pFormat);
- STDMETHODIMP GetTimeFormat(GUID* pFormat);
- STDMETHODIMP IsUsingTimeFormat(const GUID* pFormat);
- STDMETHODIMP SetTimeFormat(const GUID* pFormat);
- STDMETHODIMP GetDuration(LONGLONG* pDuration);
- STDMETHODIMP GetStopPosition(LONGLONG* pStop);
- STDMETHODIMP GetCurrentPosition(LONGLONG* pCurrent);
- STDMETHODIMP ConvertTimeFormat(LONGLONG* pTarget, const GUID* pTargetFormat, LONGLONG Source, const GUID* pSourceFormat);
- STDMETHODIMP SetPositions(LONGLONG* pCurrent, DWORD dwCurrentFlags, LONGLONG* pStop, DWORD dwStopFlags);
- STDMETHODIMP GetPositions(LONGLONG* pCurrent, LONGLONG* pStop);
- STDMETHODIMP GetAvailable(LONGLONG* pEarliest, LONGLONG* pLatest);
- STDMETHODIMP SetRate(double dRate);
- STDMETHODIMP GetRate(double* pdRate);
- STDMETHODIMP GetPreroll(LONGLONG* pllPreroll);
+ REFERENCE_TIME m_rtStart;
+
+ // override this if you need some second level stream specific demuxing (optional)
+ // the default implementation will send the sample as is
+ virtual HRESULT DeliverPacket(CAutoPtr<Packet> p);
+
+ // IMediaSeeking
+
+ STDMETHODIMP GetCapabilities(DWORD* pCapabilities);
+ STDMETHODIMP CheckCapabilities(DWORD* pCapabilities);
+ STDMETHODIMP IsFormatSupported(const GUID* pFormat);
+ STDMETHODIMP QueryPreferredFormat(GUID* pFormat);
+ STDMETHODIMP GetTimeFormat(GUID* pFormat);
+ STDMETHODIMP IsUsingTimeFormat(const GUID* pFormat);
+ STDMETHODIMP SetTimeFormat(const GUID* pFormat);
+ STDMETHODIMP GetDuration(LONGLONG* pDuration);
+ STDMETHODIMP GetStopPosition(LONGLONG* pStop);
+ STDMETHODIMP GetCurrentPosition(LONGLONG* pCurrent);
+ STDMETHODIMP ConvertTimeFormat(LONGLONG* pTarget, const GUID* pTargetFormat, LONGLONG Source, const GUID* pSourceFormat);
+ STDMETHODIMP SetPositions(LONGLONG* pCurrent, DWORD dwCurrentFlags, LONGLONG* pStop, DWORD dwStopFlags);
+ STDMETHODIMP GetPositions(LONGLONG* pCurrent, LONGLONG* pStop);
+ STDMETHODIMP GetAvailable(LONGLONG* pEarliest, LONGLONG* pLatest);
+ STDMETHODIMP SetRate(double dRate);
+ STDMETHODIMP GetRate(double* pdRate);
+ STDMETHODIMP GetPreroll(LONGLONG* pllPreroll);
public:
- CBaseSplitterOutputPin(CAtlArray<CMediaType>& mts, LPCWSTR pName, CBaseFilter* pFilter, CCritSec* pLock, HRESULT* phr, int nBuffers = 0);
- CBaseSplitterOutputPin(LPCWSTR pName, CBaseFilter* pFilter, CCritSec* pLock, HRESULT* phr, int nBuffers = 0);
- virtual ~CBaseSplitterOutputPin();
+ CBaseSplitterOutputPin(CAtlArray<CMediaType>& mts, LPCWSTR pName, CBaseFilter* pFilter, CCritSec* pLock, HRESULT* phr, int nBuffers = 0);
+ CBaseSplitterOutputPin(LPCWSTR pName, CBaseFilter* pFilter, CCritSec* pLock, HRESULT* phr, int nBuffers = 0);
+ virtual ~CBaseSplitterOutputPin();
- DECLARE_IUNKNOWN;
+ DECLARE_IUNKNOWN;
STDMETHODIMP NonDelegatingQueryInterface(REFIID riid, void** ppv);
- HRESULT SetName(LPCWSTR pName);
+ HRESULT SetName(LPCWSTR pName);
HRESULT DecideBufferSize(IMemAllocator* pAlloc, ALLOCATOR_PROPERTIES* pProperties);
HRESULT CheckMediaType(const CMediaType* pmt);
HRESULT GetMediaType(int iPosition, CMediaType* pmt);
- CMediaType& CurrentMediaType()
- {
- return m_mt;
- }
-
- STDMETHODIMP Notify(IBaseFilter* pSender, Quality q);
-
- // Queueing
-
- HANDLE GetThreadHandle()
- {
- ASSERT(m_hThread != NULL);
- return m_hThread;
- }
- void SetThreadPriority(int nPriority)
- {
- if(m_hThread) ::SetThreadPriority(m_hThread, nPriority);
- }
-
- HRESULT Active();
+ CMediaType& CurrentMediaType() {return m_mt;}
+
+ STDMETHODIMP Notify(IBaseFilter* pSender, Quality q);
+
+ // Queueing
+
+ HANDLE GetThreadHandle() {ASSERT(m_hThread != NULL); return m_hThread;}
+ void SetThreadPriority(int nPriority) {if(m_hThread) ::SetThreadPriority(m_hThread, nPriority);}
+
+ HRESULT Active();
HRESULT Inactive();
HRESULT DeliverBeginFlush();
- HRESULT DeliverEndFlush();
+ HRESULT DeliverEndFlush();
HRESULT DeliverNewSegment(REFERENCE_TIME tStart, REFERENCE_TIME tStop, double dRate);
- int QueueCount();
- int QueueSize();
+ int QueueCount();
+ int QueueSize();
HRESULT QueueEndOfStream();
- HRESULT QueuePacket(CAutoPtr<Packet> p);
+ HRESULT QueuePacket(CAutoPtr<Packet> p);
- // returns true for everything which (the lack of) would not block other streams (subtitle streams, basically)
- virtual bool IsDiscontinuous();
+ // returns true for everything which (the lack of) would not block other streams (subtitle streams, basically)
+ virtual bool IsDiscontinuous();
- // returns IStreamsSwitcherInputPin::IsActive(), when it can find one downstream
- bool IsActive();
+ // returns IStreamsSwitcherInputPin::IsActive(), when it can find one downstream
+ bool IsActive();
- // IBitRateInfo
+ // IBitRateInfo
- STDMETHODIMP_(DWORD) GetCurrentBitRate()
- {
- return m_brs.nCurrentBitRate;
- }
- STDMETHODIMP_(DWORD) GetAverageBitRate()
- {
- return m_brs.nAverageBitRate;
- }
+ STDMETHODIMP_(DWORD) GetCurrentBitRate() {return m_brs.nCurrentBitRate;}
+ STDMETHODIMP_(DWORD) GetAverageBitRate() {return m_brs.nAverageBitRate;}
};
-class CBaseSplitterFilter
- : public CBaseFilter
- , public CCritSec
- , public IDSMPropertyBagImpl
- , public IDSMResourceBagImpl
- , public IDSMChapterBagImpl
- , protected CAMThread
- , public IFileSourceFilter
- , public IMediaSeeking
- , public IAMOpenProgress
- , public IAMMediaContent
- , public IAMExtendedSeeking
- , public IKeyFrameInfo
- , public IBufferInfo
+class CBaseSplitterFilter
+ : public CBaseFilter
+ , public CCritSec
+ , public IDSMPropertyBagImpl
+ , public IDSMResourceBagImpl
+ , public IDSMChapterBagImpl
+ , protected CAMThread
+ , public IFileSourceFilter
+ , public IMediaSeeking
+ , public IAMOpenProgress
+ , public IAMMediaContent
+ , public IAMExtendedSeeking
+ , public IKeyFrameInfo
+ , public IBufferInfo
{
- CCritSec m_csPinMap;
- CAtlMap<DWORD, CBaseSplitterOutputPin*> m_pPinMap;
+ CCritSec m_csPinMap;
+ CAtlMap<DWORD, CBaseSplitterOutputPin*> m_pPinMap;
- CCritSec m_csmtnew;
- CAtlMap<DWORD, CMediaType> m_mtnew;
+ CCritSec m_csmtnew;
+ CAtlMap<DWORD, CMediaType> m_mtnew;
- CAutoPtrList<CBaseSplitterOutputPin> m_pRetiredOutputs;
+ CAutoPtrList<CBaseSplitterOutputPin> m_pRetiredOutputs;
- CComQIPtr<ISyncReader> m_pSyncReader;
+ CComQIPtr<ISyncReader> m_pSyncReader;
protected:
- CStringW m_fn;
+ CStringW m_fn;
- CAutoPtr<CBaseSplitterInputPin> m_pInput;
- CAutoPtrList<CBaseSplitterOutputPin> m_pOutputs;
+ CAutoPtr<CBaseSplitterInputPin> m_pInput;
+ CAutoPtrList<CBaseSplitterOutputPin> m_pOutputs;
- CBaseSplitterOutputPin* GetOutputPin(DWORD TrackNum);
- DWORD GetOutputTrackNum(CBaseSplitterOutputPin* pPin);
- HRESULT AddOutputPin(DWORD TrackNum, CAutoPtr<CBaseSplitterOutputPin> pPin);
- HRESULT RenameOutputPin(DWORD TrackNumSrc, DWORD TrackNumDst, const AM_MEDIA_TYPE* pmt);
- virtual HRESULT DeleteOutputs();
- virtual HRESULT CreateOutputs(IAsyncReader* pAsyncReader) = 0; // override this ...
- virtual LPCTSTR GetPartFilename(IAsyncReader* pAsyncReader);
+ CBaseSplitterOutputPin* GetOutputPin(DWORD TrackNum);
+ DWORD GetOutputTrackNum(CBaseSplitterOutputPin* pPin);
+ HRESULT AddOutputPin(DWORD TrackNum, CAutoPtr<CBaseSplitterOutputPin> pPin);
+ HRESULT RenameOutputPin(DWORD TrackNumSrc, DWORD TrackNumDst, const AM_MEDIA_TYPE* pmt);
+ virtual HRESULT DeleteOutputs();
+ virtual HRESULT CreateOutputs(IAsyncReader* pAsyncReader) = 0; // override this ...
+ virtual LPCTSTR GetPartFilename(IAsyncReader* pAsyncReader);
- LONGLONG m_nOpenProgress;
- bool m_fAbort;
+ LONGLONG m_nOpenProgress;
+ bool m_fAbort;
- REFERENCE_TIME m_rtDuration; // derived filter should set this at the end of CreateOutputs
- REFERENCE_TIME m_rtStart, m_rtStop, m_rtCurrent, m_rtNewStart, m_rtNewStop;
- double m_dRate;
+ REFERENCE_TIME m_rtDuration; // derived filter should set this at the end of CreateOutputs
+ REFERENCE_TIME m_rtStart, m_rtStop, m_rtCurrent, m_rtNewStart, m_rtNewStop;
+ double m_dRate;
- CAtlList<UINT64> m_bDiscontinuitySent;
- CAtlList<CBaseSplitterOutputPin*> m_pActivePins;
+ CAtlList<UINT64> m_bDiscontinuitySent;
+ CAtlList<CBaseSplitterOutputPin*> m_pActivePins;
- CAMEvent m_eEndFlush;
- bool m_fFlushing;
+ CAMEvent m_eEndFlush;
+ bool m_fFlushing;
- void DeliverBeginFlush();
- void DeliverEndFlush();
- HRESULT DeliverPacket(CAutoPtr<Packet> p);
+ void DeliverBeginFlush();
+ void DeliverEndFlush();
+ HRESULT DeliverPacket(CAutoPtr<Packet> p);
- DWORD m_priority;
+ DWORD m_priority;
- CFontInstaller m_fontinst;
+ CFontInstaller m_fontinst;
protected:
- enum {CMD_EXIT, CMD_SEEK};
+ enum {CMD_EXIT, CMD_SEEK};
DWORD ThreadProc();
- // ... and also override all these too
- virtual bool DemuxInit() = 0;
- virtual void DemuxSeek(REFERENCE_TIME rt) = 0;
- virtual bool DemuxLoop() = 0;
- virtual bool BuildPlaylist(LPCTSTR pszFileName, CAtlList<CHdmvClipInfo::PlaylistItem>& Items)
- {
- return false;
- };
+ // ... and also override all these too
+ virtual bool DemuxInit() = 0;
+ virtual void DemuxSeek(REFERENCE_TIME rt) = 0;
+ virtual bool DemuxLoop() = 0;
+ virtual bool BuildPlaylist(LPCTSTR pszFileName, CAtlList<CHdmvClipInfo::PlaylistItem>& Items) { return false; };
public:
- CBaseSplitterFilter(LPCTSTR pName, LPUNKNOWN pUnk, HRESULT* phr, const CLSID& clsid);
- virtual ~CBaseSplitterFilter();
+ CBaseSplitterFilter(LPCTSTR pName, LPUNKNOWN pUnk, HRESULT* phr, const CLSID& clsid);
+ virtual ~CBaseSplitterFilter();
- DECLARE_IUNKNOWN;
+ DECLARE_IUNKNOWN;
STDMETHODIMP NonDelegatingQueryInterface(REFIID riid, void** ppv);
- bool IsAnyPinDrying();
+ bool IsAnyPinDrying();
- HRESULT BreakConnect(PIN_DIRECTION dir, CBasePin* pPin);
- HRESULT CompleteConnect(PIN_DIRECTION dir, CBasePin* pPin);
+ HRESULT BreakConnect(PIN_DIRECTION dir, CBasePin* pPin);
+ HRESULT CompleteConnect(PIN_DIRECTION dir, CBasePin* pPin);
- int GetPinCount();
- CBasePin* GetPin(int n);
+ int GetPinCount();
+ CBasePin* GetPin(int n);
- STDMETHODIMP Stop();
- STDMETHODIMP Pause();
- STDMETHODIMP Run(REFERENCE_TIME tStart);
+ STDMETHODIMP Stop();
+ STDMETHODIMP Pause();
+ STDMETHODIMP Run(REFERENCE_TIME tStart);
- // IFileSourceFilter
+ // IFileSourceFilter
- STDMETHODIMP Load(LPCOLESTR pszFileName, const AM_MEDIA_TYPE* pmt);
- STDMETHODIMP GetCurFile(LPOLESTR* ppszFileName, AM_MEDIA_TYPE* pmt);
+ STDMETHODIMP Load(LPCOLESTR pszFileName, const AM_MEDIA_TYPE* pmt);
+ STDMETHODIMP GetCurFile(LPOLESTR* ppszFileName, AM_MEDIA_TYPE* pmt);
- // IMediaSeeking
+ // IMediaSeeking
- STDMETHODIMP GetCapabilities(DWORD* pCapabilities);
- STDMETHODIMP CheckCapabilities(DWORD* pCapabilities);
- STDMETHODIMP IsFormatSupported(const GUID* pFormat);
- STDMETHODIMP QueryPreferredFormat(GUID* pFormat);
- STDMETHODIMP GetTimeFormat(GUID* pFormat);
- STDMETHODIMP IsUsingTimeFormat(const GUID* pFormat);
- STDMETHODIMP SetTimeFormat(const GUID* pFormat);
- STDMETHODIMP GetDuration(LONGLONG* pDuration);
- STDMETHODIMP GetStopPosition(LONGLONG* pStop);
- STDMETHODIMP GetCurrentPosition(LONGLONG* pCurrent);
- STDMETHODIMP ConvertTimeFormat(LONGLONG* pTarget, const GUID* pTargetFormat, LONGLONG Source, const GUID* pSourceFormat);
- STDMETHODIMP SetPositions(LONGLONG* pCurrent, DWORD dwCurrentFlags, LONGLONG* pStop, DWORD dwStopFlags);
- STDMETHODIMP GetPositions(LONGLONG* pCurrent, LONGLONG* pStop);
- STDMETHODIMP GetAvailable(LONGLONG* pEarliest, LONGLONG* pLatest);
- STDMETHODIMP SetRate(double dRate);
- STDMETHODIMP GetRate(double* pdRate);
- STDMETHODIMP GetPreroll(LONGLONG* pllPreroll);
+ STDMETHODIMP GetCapabilities(DWORD* pCapabilities);
+ STDMETHODIMP CheckCapabilities(DWORD* pCapabilities);
+ STDMETHODIMP IsFormatSupported(const GUID* pFormat);
+ STDMETHODIMP QueryPreferredFormat(GUID* pFormat);
+ STDMETHODIMP GetTimeFormat(GUID* pFormat);
+ STDMETHODIMP IsUsingTimeFormat(const GUID* pFormat);
+ STDMETHODIMP SetTimeFormat(const GUID* pFormat);
+ STDMETHODIMP GetDuration(LONGLONG* pDuration);
+ STDMETHODIMP GetStopPosition(LONGLONG* pStop);
+ STDMETHODIMP GetCurrentPosition(LONGLONG* pCurrent);
+ STDMETHODIMP ConvertTimeFormat(LONGLONG* pTarget, const GUID* pTargetFormat, LONGLONG Source, const GUID* pSourceFormat);
+ STDMETHODIMP SetPositions(LONGLONG* pCurrent, DWORD dwCurrentFlags, LONGLONG* pStop, DWORD dwStopFlags);
+ STDMETHODIMP GetPositions(LONGLONG* pCurrent, LONGLONG* pStop);
+ STDMETHODIMP GetAvailable(LONGLONG* pEarliest, LONGLONG* pLatest);
+ STDMETHODIMP SetRate(double dRate);
+ STDMETHODIMP GetRate(double* pdRate);
+ STDMETHODIMP GetPreroll(LONGLONG* pllPreroll);
protected:
- friend class CBaseSplitterOutputPin;
- virtual HRESULT SetPositionsInternal(void* id, LONGLONG* pCurrent, DWORD dwCurrentFlags, LONGLONG* pStop, DWORD dwStopFlags);
+ friend class CBaseSplitterOutputPin;
+ virtual HRESULT SetPositionsInternal(void* id, LONGLONG* pCurrent, DWORD dwCurrentFlags, LONGLONG* pStop, DWORD dwStopFlags);
private:
- REFERENCE_TIME m_rtLastStart, m_rtLastStop;
- CAtlList<void*> m_LastSeekers;
+ REFERENCE_TIME m_rtLastStart, m_rtLastStop;
+ CAtlList<void*> m_LastSeekers;
public:
- // IAMOpenProgress
-
- STDMETHODIMP QueryProgress(LONGLONG* pllTotal, LONGLONG* pllCurrent);
- STDMETHODIMP AbortOperation();
-
- // IDispatch
-
- STDMETHODIMP GetTypeInfoCount(UINT* pctinfo)
- {
- return E_NOTIMPL;
- }
- STDMETHODIMP GetTypeInfo(UINT itinfo, LCID lcid, ITypeInfo** pptinfo)
- {
- return E_NOTIMPL;
- }
- STDMETHODIMP GetIDsOfNames(REFIID riid, OLECHAR** rgszNames, UINT cNames, LCID lcid, DISPID* rgdispid)
- {
- return E_NOTIMPL;
- }
- STDMETHODIMP Invoke(DISPID dispidMember, REFIID riid, LCID lcid, WORD wFlags, DISPPARAMS* pdispparams, VARIANT* pvarResult, EXCEPINFO* pexcepinfo, UINT* puArgErr)
- {
- return E_NOTIMPL;
- }
-
- // IAMMediaContent
-
- STDMETHODIMP get_AuthorName(BSTR* pbstrAuthorName);
- STDMETHODIMP get_Title(BSTR* pbstrTitle);
- STDMETHODIMP get_Rating(BSTR* pbstrRating);
- STDMETHODIMP get_Description(BSTR* pbstrDescription);
- STDMETHODIMP get_Copyright(BSTR* pbstrCopyright);
- STDMETHODIMP get_BaseURL(BSTR* pbstrBaseURL)
- {
- return E_NOTIMPL;
- }
- STDMETHODIMP get_LogoURL(BSTR* pbstrLogoURL)
- {
- return E_NOTIMPL;
- }
- STDMETHODIMP get_LogoIconURL(BSTR* pbstrLogoURL)
- {
- return E_NOTIMPL;
- }
- STDMETHODIMP get_WatermarkURL(BSTR* pbstrWatermarkURL)
- {
- return E_NOTIMPL;
- }
- STDMETHODIMP get_MoreInfoURL(BSTR* pbstrMoreInfoURL)
- {
- return E_NOTIMPL;
- }
- STDMETHODIMP get_MoreInfoBannerImage(BSTR* pbstrMoreInfoBannerImage)
- {
- return E_NOTIMPL;
- }
- STDMETHODIMP get_MoreInfoBannerURL(BSTR* pbstrMoreInfoBannerURL)
- {
- return E_NOTIMPL;
- }
- STDMETHODIMP get_MoreInfoText(BSTR* pbstrMoreInfoText)
- {
- return E_NOTIMPL;
- }
-
- // IAMExtendedSeeking
-
- STDMETHODIMP get_ExSeekCapabilities(long* pExCapabilities);
- STDMETHODIMP get_MarkerCount(long* pMarkerCount);
- STDMETHODIMP get_CurrentMarker(long* pCurrentMarker);
- STDMETHODIMP GetMarkerTime(long MarkerNum, double* pMarkerTime);
- STDMETHODIMP GetMarkerName(long MarkerNum, BSTR* pbstrMarkerName);
- STDMETHODIMP put_PlaybackSpeed(double Speed)
- {
- return E_NOTIMPL;
- }
- STDMETHODIMP get_PlaybackSpeed(double* pSpeed)
- {
- return E_NOTIMPL;
- }
-
- // IKeyFrameInfo
-
- STDMETHODIMP_(HRESULT) GetKeyFrameCount(UINT& nKFs);
- STDMETHODIMP_(HRESULT) GetKeyFrames(const GUID* pFormat, REFERENCE_TIME* pKFs, UINT& nKFs);
-
- // IBufferInfo
-
- STDMETHODIMP_(int) GetCount();
- STDMETHODIMP GetStatus(int i, int& samples, int& size);
- STDMETHODIMP_(DWORD) GetPriority();
+ // IAMOpenProgress
+
+ STDMETHODIMP QueryProgress(LONGLONG* pllTotal, LONGLONG* pllCurrent);
+ STDMETHODIMP AbortOperation();
+
+ // IDispatch
+
+ STDMETHODIMP GetTypeInfoCount(UINT* pctinfo) {return E_NOTIMPL;}
+ STDMETHODIMP GetTypeInfo(UINT itinfo, LCID lcid, ITypeInfo** pptinfo) {return E_NOTIMPL;}
+ STDMETHODIMP GetIDsOfNames(REFIID riid, OLECHAR** rgszNames, UINT cNames, LCID lcid, DISPID* rgdispid) {return E_NOTIMPL;}
+ STDMETHODIMP Invoke(DISPID dispidMember, REFIID riid, LCID lcid, WORD wFlags, DISPPARAMS* pdispparams, VARIANT* pvarResult, EXCEPINFO* pexcepinfo, UINT* puArgErr) {return E_NOTIMPL;}
+
+ // IAMMediaContent
+
+ STDMETHODIMP get_AuthorName(BSTR* pbstrAuthorName);
+ STDMETHODIMP get_Title(BSTR* pbstrTitle);
+ STDMETHODIMP get_Rating(BSTR* pbstrRating);
+ STDMETHODIMP get_Description(BSTR* pbstrDescription);
+ STDMETHODIMP get_Copyright(BSTR* pbstrCopyright);
+ STDMETHODIMP get_BaseURL(BSTR* pbstrBaseURL) {return E_NOTIMPL;}
+ STDMETHODIMP get_LogoURL(BSTR* pbstrLogoURL) {return E_NOTIMPL;}
+ STDMETHODIMP get_LogoIconURL(BSTR* pbstrLogoURL) {return E_NOTIMPL;}
+ STDMETHODIMP get_WatermarkURL(BSTR* pbstrWatermarkURL) {return E_NOTIMPL;}
+ STDMETHODIMP get_MoreInfoURL(BSTR* pbstrMoreInfoURL) {return E_NOTIMPL;}
+ STDMETHODIMP get_MoreInfoBannerImage(BSTR* pbstrMoreInfoBannerImage) {return E_NOTIMPL;}
+ STDMETHODIMP get_MoreInfoBannerURL(BSTR* pbstrMoreInfoBannerURL) {return E_NOTIMPL;}
+ STDMETHODIMP get_MoreInfoText(BSTR* pbstrMoreInfoText) {return E_NOTIMPL;}
+
+ // IAMExtendedSeeking
+
+ STDMETHODIMP get_ExSeekCapabilities(long* pExCapabilities);
+ STDMETHODIMP get_MarkerCount(long* pMarkerCount);
+ STDMETHODIMP get_CurrentMarker(long* pCurrentMarker);
+ STDMETHODIMP GetMarkerTime(long MarkerNum, double* pMarkerTime);
+ STDMETHODIMP GetMarkerName(long MarkerNum, BSTR* pbstrMarkerName);
+ STDMETHODIMP put_PlaybackSpeed(double Speed) {return E_NOTIMPL;}
+ STDMETHODIMP get_PlaybackSpeed(double* pSpeed) {return E_NOTIMPL;}
+
+ // IKeyFrameInfo
+
+ STDMETHODIMP_(HRESULT) GetKeyFrameCount(UINT& nKFs);
+ STDMETHODIMP_(HRESULT) GetKeyFrames(const GUID* pFormat, REFERENCE_TIME* pKFs, UINT& nKFs);
+
+ // IBufferInfo
+
+ STDMETHODIMP_(int) GetCount();
+ STDMETHODIMP GetStatus(int i, int& samples, int& size);
+ STDMETHODIMP_(DWORD) GetPriority();
};
diff --git a/src/filters/parser/BaseSplitter/BaseSplitterFile.cpp b/src/filters/parser/BaseSplitter/BaseSplitterFile.cpp
index 577bafc8e..64571d736 100644
--- a/src/filters/parser/BaseSplitter/BaseSplitterFile.cpp
+++ b/src/filters/parser/BaseSplitter/BaseSplitterFile.cpp
@@ -1,4 +1,4 @@
-/*
+/*
* Copyright (C) 2003-2006 Gabest
* http://www.gabest.org
*
@@ -6,15 +6,15 @@
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2, or (at your option)
* any later version.
- *
+ *
* This Program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with GNU Make; see the file COPYING. If not, write to
- * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
+ * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
* http://www.gnu.org/copyleft/gpl.html
*
*/
@@ -28,228 +28,217 @@
//
CBaseSplitterFile::CBaseSplitterFile(IAsyncReader* pAsyncReader, HRESULT& hr, int cachelen, bool fRandomAccess, bool fStreaming)
- : m_pAsyncReader(pAsyncReader)
- , m_fStreaming(false)
- , m_fRandomAccess(false)
- , m_pos(0), m_len(0)
- , m_bitbuff(0), m_bitlen(0)
- , m_cachepos(0), m_cachelen(0)
+ : m_pAsyncReader(pAsyncReader)
+ , m_fStreaming(false)
+ , m_fRandomAccess(false)
+ , m_pos(0), m_len(0)
+ , m_bitbuff(0), m_bitlen(0)
+ , m_cachepos(0), m_cachelen(0)
{
- if(!m_pAsyncReader)
- {
- hr = E_UNEXPECTED;
- return;
- }
-
- LONGLONG total = 0, available;
- hr = m_pAsyncReader->Length(&total, &available);
-
- m_fStreaming = total == 0 && available > 0;
- m_fRandomAccess = total > 0 && total == available;
- m_len = total;
-
- if(FAILED(hr) || fRandomAccess && !m_fRandomAccess || !fStreaming && m_fStreaming || m_len < 0)
- {
- hr = E_FAIL;
- return;
- }
-
- if(!SetCacheSize(cachelen))
- {
- hr = E_OUTOFMEMORY;
- return;
- }
-
- hr = S_OK;
+ if(!m_pAsyncReader) {hr = E_UNEXPECTED; return;}
+
+ LONGLONG total = 0, available;
+ hr = m_pAsyncReader->Length(&total, &available);
+
+ m_fStreaming = total == 0 && available > 0;
+ m_fRandomAccess = total > 0 && total == available;
+ m_len = total;
+
+ if(FAILED(hr) || fRandomAccess && !m_fRandomAccess || !fStreaming && m_fStreaming || m_len < 0)
+ {
+ hr = E_FAIL;
+ return;
+ }
+
+ if(!SetCacheSize(cachelen))
+ {
+ hr = E_OUTOFMEMORY;
+ return;
+ }
+
+ hr = S_OK;
}
bool CBaseSplitterFile::SetCacheSize(int cachelen)
{
- m_pCache.Free();
- m_cachetotal = 0;
- m_pCache.Allocate((size_t)cachelen);
- if(!m_pCache) return false;
- m_cachetotal = cachelen;
- m_cachelen = 0;
- return true;
+ m_pCache.Free();
+ m_cachetotal = 0;
+ m_pCache.Allocate((size_t)cachelen);
+ if(!m_pCache) return false;
+ m_cachetotal = cachelen;
+ m_cachelen = 0;
+ return true;
}
__int64 CBaseSplitterFile::GetPos()
{
- return m_pos - (m_bitlen >> 3);
+ return m_pos - (m_bitlen>>3);
}
__int64 CBaseSplitterFile::GetAvailable()
{
- LONGLONG total, available = 0;
- m_pAsyncReader->Length(&total, &available);
- return available;
+ LONGLONG total, available = 0;
+ m_pAsyncReader->Length(&total, &available);
+ return available;
}
__int64 CBaseSplitterFile::GetLength(bool fUpdate)
{
- if(m_fStreaming)
- {
- m_len = GetAvailable();
- }
- else if(fUpdate)
- {
- LONGLONG total = 0, available;
- m_pAsyncReader->Length(&total, &available);
- m_len = total;
- }
-
- return m_len;
+ if(m_fStreaming)
+ {
+ m_len = GetAvailable();
+ }
+ else if(fUpdate)
+ {
+ LONGLONG total = 0, available;
+ m_pAsyncReader->Length(&total, &available);
+ m_len = total;
+ }
+
+ return m_len;
}
void CBaseSplitterFile::Seek(__int64 pos)
{
- __int64 len = GetLength();
- m_pos = min(max(pos, 0), len);
- BitFlush();
+ __int64 len = GetLength();
+ m_pos = min(max(pos, 0), len);
+ BitFlush();
}
HRESULT CBaseSplitterFile::Read(BYTE* pData, __int64 len)
{
- CheckPointer(m_pAsyncReader, E_NOINTERFACE);
-
- HRESULT hr = S_OK;
-
- if(!m_fRandomAccess)
- {
- LONGLONG total = 0, available = -1;
- m_pAsyncReader->Length(&total, &available);
- if(total == available)
- {
- m_fRandomAccess = true;
- OnComplete();
- }
- }
-
- if(m_cachetotal == 0 || !m_pCache)
- {
- hr = m_pAsyncReader->SyncRead(m_pos, (long)len, pData);
- m_pos += len;
- return hr;
- }
-
- BYTE* pCache = m_pCache;
-
- if(m_cachepos <= m_pos && m_pos < m_cachepos + m_cachelen)
- {
- __int64 minlen = min(len, m_cachelen - (m_pos - m_cachepos));
-
- memcpy(pData, &pCache[m_pos - m_cachepos], (size_t)minlen);
-
- len -= minlen;
- m_pos += minlen;
- pData += minlen;
- }
-
- while(len > m_cachetotal)
- {
- hr = m_pAsyncReader->SyncRead(m_pos, (long)m_cachetotal, pData);
- if(S_OK != hr) return hr;
-
- len -= m_cachetotal;
- m_pos += m_cachetotal;
- pData += m_cachetotal;
- }
-
- while(len > 0)
- {
- __int64 tmplen = GetLength();
- __int64 maxlen = min(tmplen - m_pos, m_cachetotal);
- __int64 minlen = min(len, maxlen);
- if(minlen <= 0) return S_FALSE;
-
- hr = m_pAsyncReader->SyncRead(m_pos, (long)maxlen, pCache);
- if(S_OK != hr) return hr;
-
- m_cachepos = m_pos;
- m_cachelen = maxlen;
-
- memcpy(pData, pCache, (size_t)minlen);
-
- len -= minlen;
- m_pos += minlen;
- pData += minlen;
- }
-
- return hr;
+ CheckPointer(m_pAsyncReader, E_NOINTERFACE);
+
+ HRESULT hr = S_OK;
+
+ if(!m_fRandomAccess)
+ {
+ LONGLONG total = 0, available = -1;
+ m_pAsyncReader->Length(&total, &available);
+ if(total == available) {m_fRandomAccess = true; OnComplete();}
+ }
+
+ if(m_cachetotal == 0 || !m_pCache)
+ {
+ hr = m_pAsyncReader->SyncRead(m_pos, (long)len, pData);
+ m_pos += len;
+ return hr;
+ }
+
+ BYTE* pCache = m_pCache;
+
+ if(m_cachepos <= m_pos && m_pos < m_cachepos + m_cachelen)
+ {
+ __int64 minlen = min(len, m_cachelen - (m_pos - m_cachepos));
+
+ memcpy(pData, &pCache[m_pos - m_cachepos], (size_t)minlen);
+
+ len -= minlen;
+ m_pos += minlen;
+ pData += minlen;
+ }
+
+ while(len > m_cachetotal)
+ {
+ hr = m_pAsyncReader->SyncRead(m_pos, (long)m_cachetotal, pData);
+ if(S_OK != hr) return hr;
+
+ len -= m_cachetotal;
+ m_pos += m_cachetotal;
+ pData += m_cachetotal;
+ }
+
+ while(len > 0)
+ {
+ __int64 tmplen = GetLength();
+ __int64 maxlen = min(tmplen - m_pos, m_cachetotal);
+ __int64 minlen = min(len, maxlen);
+ if(minlen <= 0) return S_FALSE;
+
+ hr = m_pAsyncReader->SyncRead(m_pos, (long)maxlen, pCache);
+ if(S_OK != hr) return hr;
+
+ m_cachepos = m_pos;
+ m_cachelen = maxlen;
+
+ memcpy(pData, pCache, (size_t)minlen);
+
+ len -= minlen;
+ m_pos += minlen;
+ pData += minlen;
+ }
+
+ return hr;
}
UINT64 CBaseSplitterFile::BitRead(int nBits, bool fPeek)
{
- ASSERT(nBits >= 0 && nBits <= 64);
+ ASSERT(nBits >= 0 && nBits <= 64);
- while(m_bitlen < nBits)
- {
- m_bitbuff <<= 8;
- if(S_OK != Read((BYTE*)&m_bitbuff, 1))
- {
- return 0; // EOF? // ASSERT(0);
- }
- m_bitlen += 8;
- }
+ while(m_bitlen < nBits)
+ {
+ m_bitbuff <<= 8;
+ if(S_OK != Read((BYTE*)&m_bitbuff, 1)) {return 0;} // EOF? // ASSERT(0);
+ m_bitlen += 8;
+ }
- int bitlen = m_bitlen - nBits;
+ int bitlen = m_bitlen - nBits;
- UINT64 ret = (m_bitbuff >> bitlen) & ((1ui64 << nBits) - 1);
+ UINT64 ret = (m_bitbuff >> bitlen) & ((1ui64 << nBits) - 1);
- if(!fPeek)
- {
- m_bitbuff &= ((1ui64 << bitlen) - 1);
- m_bitlen = bitlen;
- }
+ if(!fPeek)
+ {
+ m_bitbuff &= ((1ui64 << bitlen) - 1);
+ m_bitlen = bitlen;
+ }
- return ret;
+ return ret;
}
void CBaseSplitterFile::BitByteAlign()
{
- m_bitlen &= ~7;
+ m_bitlen &= ~7;
}
void CBaseSplitterFile::BitFlush()
{
- m_bitlen = 0;
+ m_bitlen = 0;
}
HRESULT CBaseSplitterFile::ByteRead(BYTE* pData, __int64 len)
{
Seek(GetPos());
- return Read(pData, len);
+ return Read(pData, len);
}
UINT64 CBaseSplitterFile::UExpGolombRead()
{
- int n = -1;
- for(BYTE b = 0; !b; n++) b = BitRead(1);
- return (1ui64 << n) - 1 + BitRead(n);
+ int n = -1;
+ for(BYTE b = 0; !b; n++) b = BitRead(1);
+ return (1ui64 << n) - 1 + BitRead(n);
}
INT64 CBaseSplitterFile::SExpGolombRead()
{
- UINT64 k = UExpGolombRead();
- return ((k & 1) ? 1 : -1) * ((k + 1) >> 1);
+ UINT64 k = UExpGolombRead();
+ return ((k&1) ? 1 : -1) * ((k + 1) >> 1);
}
HRESULT CBaseSplitterFile::HasMoreData(__int64 len, DWORD ms)
{
- __int64 available = GetLength() - GetPos();
+ __int64 available = GetLength() - GetPos();
- if(!m_fStreaming)
- {
- return available < 1 ? E_FAIL : S_OK;
- }
+ if(!m_fStreaming)
+ {
+ return available < 1 ? E_FAIL : S_OK;
+ }
- if(available < len)
- {
- if(ms > 0) Sleep(ms);
- return S_FALSE;
- }
+ if(available < len)
+ {
+ if(ms > 0) Sleep(ms);
+ return S_FALSE;
+ }
- return S_OK;
+ return S_OK;
}
diff --git a/src/filters/parser/BaseSplitter/BaseSplitterFile.h b/src/filters/parser/BaseSplitter/BaseSplitterFile.h
index 88c544a6b..e7498223e 100644
--- a/src/filters/parser/BaseSplitter/BaseSplitterFile.h
+++ b/src/filters/parser/BaseSplitter/BaseSplitterFile.h
@@ -1,4 +1,4 @@
-/*
+/*
* Copyright (C) 2003-2006 Gabest
* http://www.gabest.org
*
@@ -6,15 +6,15 @@
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2, or (at your option)
* any later version.
- *
+ *
* This Program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with GNU Make; see the file COPYING. If not, write to
- * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
+ * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
* http://www.gnu.org/copyleft/gpl.html
*
*/
@@ -27,51 +27,42 @@
class CBaseSplitterFile
{
- CComPtr<IAsyncReader> m_pAsyncReader;
- CAutoVectorPtr<BYTE> m_pCache;
- __int64 m_cachepos, m_cachelen, m_cachetotal;
+ CComPtr<IAsyncReader> m_pAsyncReader;
+ CAutoVectorPtr<BYTE> m_pCache;
+ __int64 m_cachepos, m_cachelen, m_cachetotal;
- bool m_fStreaming, m_fRandomAccess;
- __int64 m_pos, m_len;
+ bool m_fStreaming, m_fRandomAccess;
+ __int64 m_pos, m_len;
- virtual HRESULT Read(BYTE* pData, __int64 len); // use ByteRead
+ virtual HRESULT Read(BYTE* pData, __int64 len); // use ByteRead
protected:
- UINT64 m_bitbuff;
- int m_bitlen;
+ UINT64 m_bitbuff;
+ int m_bitlen;
- virtual void OnComplete() {}
+ virtual void OnComplete() {}
public:
- CBaseSplitterFile(IAsyncReader* pReader, HRESULT& hr, int cachelen = DEFAULT_CACHE_LENGTH, bool fRandomAccess = true, bool fStreaming = false);
- virtual ~CBaseSplitterFile() {}
+ CBaseSplitterFile(IAsyncReader* pReader, HRESULT& hr, int cachelen = DEFAULT_CACHE_LENGTH, bool fRandomAccess = true, bool fStreaming = false);
+ virtual ~CBaseSplitterFile() {}
- bool SetCacheSize(int cachelen = DEFAULT_CACHE_LENGTH);
+ bool SetCacheSize(int cachelen = DEFAULT_CACHE_LENGTH);
- __int64 GetPos();
- __int64 GetAvailable();
- __int64 GetLength(bool fUpdate = false);
- __int64 GetRemaining()
- {
- return max(0, GetLength() - GetPos());
- }
- virtual void Seek(__int64 pos);
+ __int64 GetPos();
+ __int64 GetAvailable();
+ __int64 GetLength(bool fUpdate = false);
+ __int64 GetRemaining() {return max(0, GetLength() - GetPos());}
+ virtual void Seek(__int64 pos);
- UINT64 UExpGolombRead();
- INT64 SExpGolombRead();
+ UINT64 UExpGolombRead();
+ INT64 SExpGolombRead();
- UINT64 BitRead(int nBits, bool fPeek = false);
- void BitByteAlign(), BitFlush();
- HRESULT ByteRead(BYTE* pData, __int64 len);
+ UINT64 BitRead(int nBits, bool fPeek = false);
+ void BitByteAlign(), BitFlush();
+ HRESULT ByteRead(BYTE* pData, __int64 len);
- bool IsStreaming() const
- {
- return m_fStreaming;
- }
- bool IsRandomAccess() const
- {
- return m_fRandomAccess;
- }
+ bool IsStreaming() const {return m_fStreaming;}
+ bool IsRandomAccess() const {return m_fRandomAccess;}
- HRESULT HasMoreData(__int64 len = 1, DWORD ms = 1);
+ HRESULT HasMoreData(__int64 len = 1, DWORD ms = 1);
};
diff --git a/src/filters/parser/BaseSplitter/BaseSplitterFileEx.cpp b/src/filters/parser/BaseSplitter/BaseSplitterFileEx.cpp
index 16519f316..acb44acef 100644
--- a/src/filters/parser/BaseSplitter/BaseSplitterFileEx.cpp
+++ b/src/filters/parser/BaseSplitter/BaseSplitterFileEx.cpp
@@ -1,4 +1,4 @@
-/*
+/*
* Copyright (C) 2003-2006 Gabest
* http://www.gabest.org
*
@@ -6,15 +6,15 @@
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2, or (at your option)
* any later version.
- *
+ *
* This Program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with GNU Make; see the file COPYING. If not, write to
- * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
+ * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
* http://www.gnu.org/copyleft/gpl.html
*
*/
@@ -34,9 +34,9 @@
//
CBaseSplitterFileEx::CBaseSplitterFileEx(IAsyncReader* pReader, HRESULT& hr, int cachelen, bool fRandomAccess, bool fStreaming)
- : CBaseSplitterFile(pReader, hr, cachelen, fRandomAccess, fStreaming)
- , m_tslen(0)
- , m_rtPTSOffset(0)
+ : CBaseSplitterFile(pReader, hr, cachelen, fRandomAccess, fStreaming)
+ , m_tslen(0)
+ ,m_rtPTSOffset(0)
{
}
@@ -48,16 +48,16 @@ CBaseSplitterFileEx::~CBaseSplitterFileEx()
bool CBaseSplitterFileEx::NextMpegStartCode(BYTE& code, __int64 len)
{
- BitByteAlign();
- DWORD dw = -1;
- do
- {
- if(len-- == 0 || !GetRemaining()) return(false);
- dw = (dw << 8) | (BYTE)BitRead(8);
- }
- while((dw & 0xffffff00) != 0x00000100);
- code = (BYTE)(dw & 0xff);
- return(true);
+ BitByteAlign();
+ DWORD dw = -1;
+ do
+ {
+ if(len-- == 0 || !GetRemaining()) return(false);
+ dw = (dw << 8) | (BYTE)BitRead(8);
+ }
+ while((dw&0xffffff00) != 0x00000100);
+ code = (BYTE)(dw&0xff);
+ return(true);
}
//
@@ -66,651 +66,602 @@ bool CBaseSplitterFileEx::NextMpegStartCode(BYTE& code, __int64 len)
bool CBaseSplitterFileEx::Read(pshdr& h)
{
- memset(&h, 0, sizeof(h));
-
- BYTE b = (BYTE)BitRead(8, true);
-
- if((b & 0xf1) == 0x21)
- {
- h.type = mpeg1;
-
- EXECUTE_ASSERT(BitRead(4) == 2);
-
- h.scr = 0;
- h.scr |= BitRead(3) << 30;
- MARKER; // 32..30
- h.scr |= BitRead(15) << 15;
- MARKER; // 29..15
- h.scr |= BitRead(15);
- MARKER;
- MARKER; // 14..0
- h.bitrate = BitRead(22);
- MARKER;
- }
- else if((b & 0xc4) == 0x44)
- {
- h.type = mpeg2;
-
- EXECUTE_ASSERT(BitRead(2) == 1);
-
- h.scr = 0;
- h.scr |= BitRead(3) << 30;
- MARKER; // 32..30
- h.scr |= BitRead(15) << 15;
- MARKER; // 29..15
- h.scr |= BitRead(15);
- MARKER; // 14..0
- h.scr = (h.scr * 300 + BitRead(9)) * 10 / 27;
- MARKER;
- h.bitrate = BitRead(22);
- MARKER;
- MARKER;
- BitRead(5); // reserved
- UINT64 stuffing = BitRead(3);
- while(stuffing-- > 0) EXECUTE_ASSERT(BitRead(8) == 0xff);
- }
- else
- {
- return(false);
- }
-
- h.bitrate *= 400;
-
- return(true);
+ memset(&h, 0, sizeof(h));
+
+ BYTE b = (BYTE)BitRead(8, true);
+
+ if((b&0xf1) == 0x21)
+ {
+ h.type = mpeg1;
+
+ EXECUTE_ASSERT(BitRead(4) == 2);
+
+ h.scr = 0;
+ h.scr |= BitRead(3) << 30; MARKER; // 32..30
+ h.scr |= BitRead(15) << 15; MARKER; // 29..15
+ h.scr |= BitRead(15); MARKER; MARKER; // 14..0
+ h.bitrate = BitRead(22); MARKER;
+ }
+ else if((b&0xc4) == 0x44)
+ {
+ h.type = mpeg2;
+
+ EXECUTE_ASSERT(BitRead(2) == 1);
+
+ h.scr = 0;
+ h.scr |= BitRead(3) << 30; MARKER; // 32..30
+ h.scr |= BitRead(15) << 15; MARKER; // 29..15
+ h.scr |= BitRead(15); MARKER; // 14..0
+ h.scr = (h.scr*300 + BitRead(9)) * 10 / 27; MARKER;
+ h.bitrate = BitRead(22); MARKER; MARKER;
+ BitRead(5); // reserved
+ UINT64 stuffing = BitRead(3);
+ while(stuffing-- > 0) EXECUTE_ASSERT(BitRead(8) == 0xff);
+ }
+ else
+ {
+ return(false);
+ }
+
+ h.bitrate *= 400;
+
+ return(true);
}
bool CBaseSplitterFileEx::Read(pssyshdr& h)
{
- memset(&h, 0, sizeof(h));
-
- WORD len = (WORD)BitRead(16);
- MARKER;
- h.rate_bound = (DWORD)BitRead(22);
- MARKER;
- h.audio_bound = (BYTE)BitRead(6);
- h.fixed_rate = !!BitRead(1);
- h.csps = !!BitRead(1);
- h.sys_audio_loc_flag = !!BitRead(1);
- h.sys_video_loc_flag = !!BitRead(1);
- MARKER;
- h.video_bound = (BYTE)BitRead(5);
-
- EXECUTE_ASSERT((BitRead(8) & 0x7f) == 0x7f); // reserved (should be 0xff, but not in reality)
-
- for(len -= 6; len > 3; len -= 3) // TODO: also store these, somewhere, if needed
- {
- UINT64 stream_id = BitRead(8);
- EXECUTE_ASSERT(BitRead(2) == 3);
- UINT64 p_std_buff_size_bound = (BitRead(1) ? 1024 : 128) * BitRead(13);
- }
-
- return(true);
+ memset(&h, 0, sizeof(h));
+
+ WORD len = (WORD)BitRead(16); MARKER;
+ h.rate_bound = (DWORD)BitRead(22); MARKER;
+ h.audio_bound = (BYTE)BitRead(6);
+ h.fixed_rate = !!BitRead(1);
+ h.csps = !!BitRead(1);
+ h.sys_audio_loc_flag = !!BitRead(1);
+ h.sys_video_loc_flag = !!BitRead(1); MARKER;
+ h.video_bound = (BYTE)BitRead(5);
+
+ EXECUTE_ASSERT((BitRead(8)&0x7f) == 0x7f); // reserved (should be 0xff, but not in reality)
+
+ for(len -= 6; len > 3; len -= 3) // TODO: also store these, somewhere, if needed
+ {
+ UINT64 stream_id = BitRead(8);
+ EXECUTE_ASSERT(BitRead(2) == 3);
+ UINT64 p_std_buff_size_bound = (BitRead(1)?1024:128)*BitRead(13);
+ }
+
+ return(true);
}
bool CBaseSplitterFileEx::Read(peshdr& h, BYTE code)
{
- memset(&h, 0, sizeof(h));
-
- if(!(code >= 0xbd && code < 0xf0 || code == 0xfd)) // 0xfd => blu-ray (.m2ts)
- return(false);
-
- h.len = (WORD)BitRead(16);
-
- if(code == 0xbe || code == 0xbf)
- return(true);
-
- // mpeg1 stuffing (ff ff .. , max 16x)
- for(int i = 0; i < 16 && BitRead(8, true) == 0xff; i++)
- {
- BitRead(8);
- if(h.len) h.len--;
- }
-
- h.type = (BYTE)BitRead(2, true) == mpeg2 ? mpeg2 : mpeg1;
-
- if(h.type == mpeg1)
- {
- BYTE b = (BYTE)BitRead(2);
-
- if(b == 1)
- {
- h.std_buff_size = (BitRead(1) ? 1024 : 128) * BitRead(13);
- if(h.len) h.len -= 2;
- b = (BYTE)BitRead(2);
- }
-
- if(b == 0)
- {
- h.fpts = (BYTE)BitRead(1);
- h.fdts = (BYTE)BitRead(1);
- }
- }
- else if(h.type == mpeg2)
- {
- EXECUTE_ASSERT(BitRead(2) == mpeg2);
- h.scrambling = (BYTE)BitRead(2);
- h.priority = (BYTE)BitRead(1);
- h.alignment = (BYTE)BitRead(1);
- h.copyright = (BYTE)BitRead(1);
- h.original = (BYTE)BitRead(1);
- h.fpts = (BYTE)BitRead(1);
- h.fdts = (BYTE)BitRead(1);
- h.escr = (BYTE)BitRead(1);
- h.esrate = (BYTE)BitRead(1);
- h.dsmtrickmode = (BYTE)BitRead(1);
- h.morecopyright = (BYTE)BitRead(1);
- h.crc = (BYTE)BitRead(1);
- h.extension = (BYTE)BitRead(1);
- h.hdrlen = (BYTE)BitRead(8);
- }
- else
- {
- if(h.len) while(h.len-- > 0) BitRead(8);
- return(false);
- }
-
- if(h.fpts)
- {
- if(h.type == mpeg2)
- {
- BYTE b = (BYTE)BitRead(4);
- if(!(h.fdts && b == 3 || !h.fdts && b == 2))
- {
- ASSERT(0);
- return(false);
- }
- }
-
- h.pts = 0;
- h.pts |= BitRead(3) << 30;
- MARKER; // 32..30
- h.pts |= BitRead(15) << 15;
- MARKER; // 29..15
- h.pts |= BitRead(15);
- MARKER; // 14..0
- h.pts = 10000 * h.pts / 90 + m_rtPTSOffset;
- }
-
- if(h.fdts)
- {
- if((BYTE)BitRead(4) != 1)
- {
- ASSERT(0);
- return(false);
- }
-
- h.dts = 0;
- h.dts |= BitRead(3) << 30;
- MARKER; // 32..30
- h.dts |= BitRead(15) << 15;
- MARKER; // 29..15
- h.dts |= BitRead(15);
- MARKER; // 14..0
- h.dts = 10000 * h.dts / 90 + m_rtPTSOffset;
- }
-
- // skip to the end of header
-
- if(h.type == mpeg1)
- {
- if(!h.fpts && !h.fdts && BitRead(4) != 0xf)
- {
- /*ASSERT(0);*/ return(false);
- }
-
- if(h.len)
- {
- h.len--;
- if(h.pts) h.len -= 4;
- if(h.dts) h.len -= 5;
- }
- }
-
- if(h.type == mpeg2)
- {
- if(h.len) h.len -= 3 + h.hdrlen;
-
- int left = h.hdrlen;
- if(h.fpts) left -= 5;
- if(h.fdts) left -= 5;
- while(left-- > 0) BitRead(8);
- /*
- // mpeg2 stuffing (ff ff .. , max 32x)
- while(BitRead(8, true) == 0xff) {BitRead(8); if(h.len) h.len--;}
- Seek(GetPos()); // put last peeked byte back for Read()
-
- // FIXME: this doesn't seems to be here,
- // infact there can be ff's as part of the data
- // right at the beginning of the packet, which
- // we should not skip...
- */
- }
+ memset(&h, 0, sizeof(h));
+
+ if(!(code >= 0xbd && code < 0xf0 || code == 0xfd)) // 0xfd => blu-ray (.m2ts)
+ return(false);
+
+ h.len = (WORD)BitRead(16);
+
+ if(code == 0xbe || code == 0xbf)
+ return(true);
+
+ // mpeg1 stuffing (ff ff .. , max 16x)
+ for(int i = 0; i < 16 && BitRead(8, true) == 0xff; i++)
+ {
+ BitRead(8);
+ if(h.len) h.len--;
+ }
+
+ h.type = (BYTE)BitRead(2, true) == mpeg2 ? mpeg2 : mpeg1;
+
+ if(h.type == mpeg1)
+ {
+ BYTE b = (BYTE)BitRead(2);
+
+ if(b == 1)
+ {
+ h.std_buff_size = (BitRead(1)?1024:128)*BitRead(13);
+ if(h.len) h.len -= 2;
+ b = (BYTE)BitRead(2);
+ }
+
+ if(b == 0)
+ {
+ h.fpts = (BYTE)BitRead(1);
+ h.fdts = (BYTE)BitRead(1);
+ }
+ }
+ else if(h.type == mpeg2)
+ {
+ EXECUTE_ASSERT(BitRead(2) == mpeg2);
+ h.scrambling = (BYTE)BitRead(2);
+ h.priority = (BYTE)BitRead(1);
+ h.alignment = (BYTE)BitRead(1);
+ h.copyright = (BYTE)BitRead(1);
+ h.original = (BYTE)BitRead(1);
+ h.fpts = (BYTE)BitRead(1);
+ h.fdts = (BYTE)BitRead(1);
+ h.escr = (BYTE)BitRead(1);
+ h.esrate = (BYTE)BitRead(1);
+ h.dsmtrickmode = (BYTE)BitRead(1);
+ h.morecopyright = (BYTE)BitRead(1);
+ h.crc = (BYTE)BitRead(1);
+ h.extension = (BYTE)BitRead(1);
+ h.hdrlen = (BYTE)BitRead(8);
+ }
+ else
+ {
+ if(h.len) while(h.len-- > 0) BitRead(8);
+ return(false);
+ }
+
+ if(h.fpts)
+ {
+ if(h.type == mpeg2)
+ {
+ BYTE b = (BYTE)BitRead(4);
+ if(!(h.fdts && b == 3 || !h.fdts && b == 2)) {ASSERT(0); return(false);}
+ }
+
+ h.pts = 0;
+ h.pts |= BitRead(3) << 30; MARKER; // 32..30
+ h.pts |= BitRead(15) << 15; MARKER; // 29..15
+ h.pts |= BitRead(15); MARKER; // 14..0
+ h.pts = 10000*h.pts/90 + m_rtPTSOffset;
+ }
+
+ if(h.fdts)
+ {
+ if((BYTE)BitRead(4) != 1) {ASSERT(0); return(false);}
+
+ h.dts = 0;
+ h.dts |= BitRead(3) << 30; MARKER; // 32..30
+ h.dts |= BitRead(15) << 15; MARKER; // 29..15
+ h.dts |= BitRead(15); MARKER; // 14..0
+ h.dts = 10000*h.dts/90 + m_rtPTSOffset;
+ }
+
+ // skip to the end of header
+
+ if(h.type == mpeg1)
+ {
+ if(!h.fpts && !h.fdts && BitRead(4) != 0xf) {/*ASSERT(0);*/ return(false);}
+
+ if(h.len)
+ {
+ h.len--;
+ if(h.pts) h.len -= 4;
+ if(h.dts) h.len -= 5;
+ }
+ }
+
+ if(h.type == mpeg2)
+ {
+ if(h.len) h.len -= 3+h.hdrlen;
+
+ int left = h.hdrlen;
+ if(h.fpts) left -= 5;
+ if(h.fdts) left -= 5;
+ while(left-- > 0) BitRead(8);
+/*
+ // mpeg2 stuffing (ff ff .. , max 32x)
+ while(BitRead(8, true) == 0xff) {BitRead(8); if(h.len) h.len--;}
+ Seek(GetPos()); // put last peeked byte back for Read()
+
+ // FIXME: this doesn't seems to be here,
+ // infact there can be ff's as part of the data
+ // right at the beginning of the packet, which
+ // we should not skip...
+*/
+ }
- return(true);
+ return(true);
}
bool CBaseSplitterFileEx::Read(seqhdr& h, int len, CMediaType* pmt)
{
- __int64 endpos = GetPos() + len; // - sequence header length
+ __int64 endpos = GetPos() + len; // - sequence header length
- BYTE id = 0;
+ BYTE id = 0;
- while(GetPos() < endpos && id != 0xb3)
- {
- if(!NextMpegStartCode(id, len))
- return(false);
- }
+ while(GetPos() < endpos && id != 0xb3)
+ {
+ if(!NextMpegStartCode(id, len))
+ return(false);
+ }
- if(id != 0xb3)
- return(false);
+ if(id != 0xb3)
+ return(false);
- __int64 shpos = GetPos() - 4;
+ __int64 shpos = GetPos() - 4;
- h.width = (WORD)BitRead(12);
- h.height = (WORD)BitRead(12);
- h.ar = BitRead(4);
+ h.width = (WORD)BitRead(12);
+ h.height = (WORD)BitRead(12);
+ h.ar = BitRead(4);
static int ifps[16] = {0, 1126125, 1125000, 1080000, 900900, 900000, 540000, 450450, 450000, 0, 0, 0, 0, 0, 0, 0};
- h.ifps = ifps[BitRead(4)];
- h.bitrate = (DWORD)BitRead(18);
- MARKER;
- h.vbv = (DWORD)BitRead(10);
- h.constrained = BitRead(1);
-
- if(h.fiqm = BitRead(1))
- for(int i = 0; i < countof(h.iqm); i++)
- h.iqm[i] = (BYTE)BitRead(8);
-
- if(h.fniqm = BitRead(1))
- for(int i = 0; i < countof(h.niqm); i++)
- h.niqm[i] = (BYTE)BitRead(8);
-
- __int64 shlen = GetPos() - shpos;
-
- static float ar[] =
- {
- 1.0000f, 1.0000f, 0.6735f, 0.7031f, 0.7615f, 0.8055f, 0.8437f, 0.8935f,
- 0.9157f, 0.9815f, 1.0255f, 1.0695f, 1.0950f, 1.1575f, 1.2015f, 1.0000f
- };
-
- h.arx = (int)((float)h.width / ar[h.ar] + 0.5);
- h.ary = h.height;
-
- mpeg_t type = mpeg1;
-
- __int64 shextpos = 0, shextlen = 0;
-
- if(NextMpegStartCode(id, 8) && id == 0xb5) // sequence header ext
- {
- shextpos = GetPos() - 4;
-
- h.startcodeid = BitRead(4);
- h.profile_levelescape = BitRead(1); // reserved, should be 0
- h.profile = BitRead(3);
- h.level = BitRead(4);
- h.progressive = BitRead(1);
- h.chroma = BitRead(2);
- h.width |= (BitRead(2) << 12);
- h.height |= (BitRead(2) << 12);
- h.bitrate |= (BitRead(12) << 18);
- MARKER;
- h.vbv |= (BitRead(8) << 10);
- h.lowdelay = BitRead(1);
- h.ifps = (DWORD)(h.ifps * (BitRead(2) + 1) / (BitRead(5) + 1));
-
- shextlen = GetPos() - shextpos;
-
- struct
- {
- DWORD x, y;
- } ar[] = {{h.width, h.height}, {4, 3}, {16, 9}, {221, 100}, {h.width, h.height}};
- int i = min(max(h.ar, 1), 5) - 1;
- h.arx = ar[i].x;
- h.ary = ar[i].y;
-
- type = mpeg2;
- }
-
- h.ifps = 10 * h.ifps / 27;
- h.bitrate = h.bitrate == (1 << 30) - 1 ? 0 : h.bitrate * 400;
-
- DWORD a = h.arx, b = h.ary;
- while(a)
- {
- DWORD tmp = a;
- a = b % tmp;
- b = tmp;
- }
- if(b) h.arx /= b, h.ary /= b;
-
- if(!pmt) return(true);
-
- pmt->majortype = MEDIATYPE_Video;
-
- if(type == mpeg1)
- {
- pmt->subtype = MEDIASUBTYPE_MPEG1Payload;
- pmt->formattype = FORMAT_MPEGVideo;
- int len = FIELD_OFFSET(MPEG1VIDEOINFO, bSequenceHeader) + shlen + shextlen;
- MPEG1VIDEOINFO* vi = (MPEG1VIDEOINFO*)DNew BYTE[len];
- memset(vi, 0, len);
- vi->hdr.dwBitRate = h.bitrate;
- vi->hdr.AvgTimePerFrame = h.ifps;
- vi->hdr.bmiHeader.biSize = sizeof(vi->hdr.bmiHeader);
- vi->hdr.bmiHeader.biWidth = h.width;
- vi->hdr.bmiHeader.biHeight = h.height;
- vi->hdr.bmiHeader.biXPelsPerMeter = h.width * h.ary;
- vi->hdr.bmiHeader.biYPelsPerMeter = h.height * h.arx;
- vi->cbSequenceHeader = shlen + shextlen;
- Seek(shpos);
- ByteRead((BYTE*)&vi->bSequenceHeader[0], shlen);
- if(shextpos && shextlen) Seek(shextpos);
- ByteRead((BYTE*)&vi->bSequenceHeader[0] + shlen, shextlen);
- pmt->SetFormat((BYTE*)vi, len);
- delete [] vi;
- }
- else if(type == mpeg2)
- {
- pmt->subtype = MEDIASUBTYPE_MPEG2_VIDEO;
- pmt->formattype = FORMAT_MPEG2_VIDEO;
- int len = FIELD_OFFSET(MPEG2VIDEOINFO, dwSequenceHeader) + shlen + shextlen;
- MPEG2VIDEOINFO* vi = (MPEG2VIDEOINFO*)DNew BYTE[len];
- memset(vi, 0, len);
- vi->hdr.dwBitRate = h.bitrate;
- vi->hdr.AvgTimePerFrame = h.ifps;
- vi->hdr.dwPictAspectRatioX = h.arx;
- vi->hdr.dwPictAspectRatioY = h.ary;
- vi->hdr.bmiHeader.biSize = sizeof(vi->hdr.bmiHeader);
- vi->hdr.bmiHeader.biWidth = h.width;
- vi->hdr.bmiHeader.biHeight = h.height;
- vi->dwProfile = h.profile;
- vi->dwLevel = h.level;
- vi->cbSequenceHeader = shlen + shextlen;
- Seek(shpos);
- ByteRead((BYTE*)&vi->dwSequenceHeader[0], shlen);
- if(shextpos && shextlen) Seek(shextpos);
- ByteRead((BYTE*)&vi->dwSequenceHeader[0] + shlen, shextlen);
- pmt->SetFormat((BYTE*)vi, len);
- delete [] vi;
- }
- else
- {
- return(false);
- }
-
- return(true);
+ h.ifps = ifps[BitRead(4)];
+ h.bitrate = (DWORD)BitRead(18); MARKER;
+ h.vbv = (DWORD)BitRead(10);
+ h.constrained = BitRead(1);
+
+ if(h.fiqm = BitRead(1))
+ for(int i = 0; i < countof(h.iqm); i++)
+ h.iqm[i] = (BYTE)BitRead(8);
+
+ if(h.fniqm = BitRead(1))
+ for(int i = 0; i < countof(h.niqm); i++)
+ h.niqm[i] = (BYTE)BitRead(8);
+
+ __int64 shlen = GetPos() - shpos;
+
+ static float ar[] =
+ {
+ 1.0000f,1.0000f,0.6735f,0.7031f,0.7615f,0.8055f,0.8437f,0.8935f,
+ 0.9157f,0.9815f,1.0255f,1.0695f,1.0950f,1.1575f,1.2015f,1.0000f
+ };
+
+ h.arx = (int)((float)h.width / ar[h.ar] + 0.5);
+ h.ary = h.height;
+
+ mpeg_t type = mpeg1;
+
+ __int64 shextpos = 0, shextlen = 0;
+
+ if(NextMpegStartCode(id, 8) && id == 0xb5) // sequence header ext
+ {
+ shextpos = GetPos() - 4;
+
+ h.startcodeid = BitRead(4);
+ h.profile_levelescape = BitRead(1); // reserved, should be 0
+ h.profile = BitRead(3);
+ h.level = BitRead(4);
+ h.progressive = BitRead(1);
+ h.chroma = BitRead(2);
+ h.width |= (BitRead(2)<<12);
+ h.height |= (BitRead(2)<<12);
+ h.bitrate |= (BitRead(12)<<18); MARKER;
+ h.vbv |= (BitRead(8)<<10);
+ h.lowdelay = BitRead(1);
+ h.ifps = (DWORD)(h.ifps * (BitRead(2)+1) / (BitRead(5)+1));
+
+ shextlen = GetPos() - shextpos;
+
+ struct {DWORD x, y;} ar[] = {{h.width,h.height},{4,3},{16,9},{221,100},{h.width,h.height}};
+ int i = min(max(h.ar, 1), 5)-1;
+ h.arx = ar[i].x;
+ h.ary = ar[i].y;
+
+ type = mpeg2;
+ }
+
+ h.ifps = 10 * h.ifps / 27;
+ h.bitrate = h.bitrate == (1<<30)-1 ? 0 : h.bitrate * 400;
+
+ DWORD a = h.arx, b = h.ary;
+ while(a) {DWORD tmp = a; a = b % tmp; b = tmp;}
+ if(b) h.arx /= b, h.ary /= b;
+
+ if(!pmt) return(true);
+
+ pmt->majortype = MEDIATYPE_Video;
+
+ if(type == mpeg1)
+ {
+ pmt->subtype = MEDIASUBTYPE_MPEG1Payload;
+ pmt->formattype = FORMAT_MPEGVideo;
+ int len = FIELD_OFFSET(MPEG1VIDEOINFO, bSequenceHeader) + shlen + shextlen;
+ MPEG1VIDEOINFO* vi = (MPEG1VIDEOINFO*)DNew BYTE[len];
+ memset(vi, 0, len);
+ vi->hdr.dwBitRate = h.bitrate;
+ vi->hdr.AvgTimePerFrame = h.ifps;
+ vi->hdr.bmiHeader.biSize = sizeof(vi->hdr.bmiHeader);
+ vi->hdr.bmiHeader.biWidth = h.width;
+ vi->hdr.bmiHeader.biHeight = h.height;
+ vi->hdr.bmiHeader.biXPelsPerMeter = h.width * h.ary;
+ vi->hdr.bmiHeader.biYPelsPerMeter = h.height * h.arx;
+ vi->cbSequenceHeader = shlen + shextlen;
+ Seek(shpos);
+ ByteRead((BYTE*)&vi->bSequenceHeader[0], shlen);
+ if(shextpos && shextlen) Seek(shextpos);
+ ByteRead((BYTE*)&vi->bSequenceHeader[0] + shlen, shextlen);
+ pmt->SetFormat((BYTE*)vi, len);
+ delete [] vi;
+ }
+ else if(type == mpeg2)
+ {
+ pmt->subtype = MEDIASUBTYPE_MPEG2_VIDEO;
+ pmt->formattype = FORMAT_MPEG2_VIDEO;
+ int len = FIELD_OFFSET(MPEG2VIDEOINFO, dwSequenceHeader) + shlen + shextlen;
+ MPEG2VIDEOINFO* vi = (MPEG2VIDEOINFO*)DNew BYTE[len];
+ memset(vi, 0, len);
+ vi->hdr.dwBitRate = h.bitrate;
+ vi->hdr.AvgTimePerFrame = h.ifps;
+ vi->hdr.dwPictAspectRatioX = h.arx;
+ vi->hdr.dwPictAspectRatioY = h.ary;
+ vi->hdr.bmiHeader.biSize = sizeof(vi->hdr.bmiHeader);
+ vi->hdr.bmiHeader.biWidth = h.width;
+ vi->hdr.bmiHeader.biHeight = h.height;
+ vi->dwProfile = h.profile;
+ vi->dwLevel = h.level;
+ vi->cbSequenceHeader = shlen + shextlen;
+ Seek(shpos);
+ ByteRead((BYTE*)&vi->dwSequenceHeader[0], shlen);
+ if(shextpos && shextlen) Seek(shextpos);
+ ByteRead((BYTE*)&vi->dwSequenceHeader[0] + shlen, shextlen);
+ pmt->SetFormat((BYTE*)vi, len);
+ delete [] vi;
+ }
+ else
+ {
+ return(false);
+ }
+
+ return(true);
}
bool CBaseSplitterFileEx::Read(mpahdr& h, int len, bool fAllowV25, CMediaType* pmt)
{
- memset(&h, 0, sizeof(h));
-
- int syncbits = fAllowV25 ? 11 : 12;
-
- for(; len >= 4 && BitRead(syncbits, true) != (1 << syncbits) - 1; len--)
- BitRead(8);
-
- if(len < 4)
- return(false);
-
- h.sync = BitRead(11);
- h.version = BitRead(2);
- h.layer = BitRead(2);
- h.crc = BitRead(1);
- h.bitrate = BitRead(4);
- h.freq = BitRead(2);
- h.padding = BitRead(1);
- h.privatebit = BitRead(1);
- h.channels = BitRead(2);
- h.modeext = BitRead(2);
- h.copyright = BitRead(1);
- h.original = BitRead(1);
- h.emphasis = BitRead(2);
-
- if(h.version == 1 || h.layer == 0 || h.freq == 3 || h.bitrate == 15 || h.emphasis == 2)
- return(false);
-
- if(h.version == 3 && h.layer == 2)
- {
- if((h.bitrate == 1 || h.bitrate == 2 || h.bitrate == 3 || h.bitrate == 5) && h.channels != 3
- && (h.bitrate >= 11 && h.bitrate <= 14) && h.channels == 3)
- return(false);
- }
-
- h.layer = 4 - h.layer;
-
- //
-
- static int brtbl[][5] =
- {
- {0, 0, 0, 0, 0},
- {32, 32, 32, 32, 8},
- {64, 48, 40, 48, 16},
- {96, 56, 48, 56, 24},
- {128, 64, 56, 64, 32},
- {160, 80, 64, 80, 40},
- {192, 96, 80, 96, 48},
- {224, 112, 96, 112, 56},
- {256, 128, 112, 128, 64},
- {288, 160, 128, 144, 80},
- {320, 192, 160, 160, 96},
- {352, 224, 192, 176, 112},
- {384, 256, 224, 192, 128},
- {416, 320, 256, 224, 144},
- {448, 384, 320, 256, 160},
- {0, 0, 0, 0, 0},
- };
-
- static int brtblcol[][4] = {{0, 3, 4, 4}, {0, 0, 1, 2}};
- int bitrate = 1000 * brtbl[h.bitrate][brtblcol[h.version&1][h.layer]];
- if(bitrate == 0) return(false);
-
- static int freq[][4] = {{11025, 0, 22050, 44100}, {12000, 0, 24000, 48000}, {8000, 0, 16000, 32000}};
-
- bool l3ext = h.layer == 3 && !(h.version & 1);
-
- h.nSamplesPerSec = freq[h.freq][h.version];
- h.FrameSize = h.layer == 1
- ? (12 * bitrate / h.nSamplesPerSec + h.padding) * 4
- : (l3ext ? 72 : 144) * bitrate / h.nSamplesPerSec + h.padding;
- h.rtDuration = 10000000i64 * (h.layer == 1 ? 384 : l3ext ? 576 : 1152) / h.nSamplesPerSec;// / (h.channels == 3 ? 1 : 2);
- h.nBytesPerSec = bitrate / 8;
-
- if(!pmt) return(true);
-
- /*int*/
- len = h.layer == 3
- ? sizeof(WAVEFORMATEX/*MPEGLAYER3WAVEFORMAT*/) // no need to overcomplicate this...
- : sizeof(MPEG1WAVEFORMAT);
- WAVEFORMATEX* wfe = (WAVEFORMATEX*)DNew BYTE[len];
- memset(wfe, 0, len);
- wfe->cbSize = len - sizeof(WAVEFORMATEX);
-
- if(h.layer == 3)
- {
- wfe->wFormatTag = WAVE_FORMAT_MP3;
-
- /* MPEGLAYER3WAVEFORMAT* f = (MPEGLAYER3WAVEFORMAT*)wfe;
- f->wfx.wFormatTag = WAVE_FORMAT_MP3;
- f->wID = MPEGLAYER3_ID_UNKNOWN;
- f->fdwFlags = h.padding ? MPEGLAYER3_FLAG_PADDING_ON : MPEGLAYER3_FLAG_PADDING_OFF; // _OFF or _ISO ?
- */
- }
- else
- {
- MPEG1WAVEFORMAT* f = (MPEG1WAVEFORMAT*)wfe;
- f->wfx.wFormatTag = WAVE_FORMAT_MPEG;
- f->fwHeadMode = 1 << h.channels;
- f->fwHeadModeExt = 1 << h.modeext;
- f->wHeadEmphasis = h.emphasis + 1;
- if(h.privatebit) f->fwHeadFlags |= ACM_MPEG_PRIVATEBIT;
- if(h.copyright) f->fwHeadFlags |= ACM_MPEG_COPYRIGHT;
- if(h.original) f->fwHeadFlags |= ACM_MPEG_ORIGINALHOME;
- if(h.crc == 0) f->fwHeadFlags |= ACM_MPEG_PROTECTIONBIT;
- if(h.version == 3) f->fwHeadFlags |= ACM_MPEG_ID_MPEG1;
- f->fwHeadLayer = 1 << (h.layer - 1);
- f->dwHeadBitrate = bitrate;
- }
-
- wfe->nChannels = h.channels == 3 ? 1 : 2;
- wfe->nSamplesPerSec = h.nSamplesPerSec;
- wfe->nBlockAlign = h.FrameSize;
- wfe->nAvgBytesPerSec = h.nBytesPerSec;
-
- pmt->majortype = MEDIATYPE_Audio;
- pmt->subtype = FOURCCMap(wfe->wFormatTag);
- pmt->formattype = FORMAT_WaveFormatEx;
- pmt->SetFormat((BYTE*)wfe, sizeof(WAVEFORMATEX) + wfe->cbSize);
-
- delete [] wfe;
-
- return(true);
+ memset(&h, 0, sizeof(h));
+
+ int syncbits = fAllowV25 ? 11 : 12;
+
+ for(; len >= 4 && BitRead(syncbits, true) != (1<<syncbits) - 1; len--)
+ BitRead(8);
+
+ if(len < 4)
+ return(false);
+
+ h.sync = BitRead(11);
+ h.version = BitRead(2);
+ h.layer = BitRead(2);
+ h.crc = BitRead(1);
+ h.bitrate = BitRead(4);
+ h.freq = BitRead(2);
+ h.padding = BitRead(1);
+ h.privatebit = BitRead(1);
+ h.channels = BitRead(2);
+ h.modeext = BitRead(2);
+ h.copyright = BitRead(1);
+ h.original = BitRead(1);
+ h.emphasis = BitRead(2);
+
+ if(h.version == 1 || h.layer == 0 || h.freq == 3 || h.bitrate == 15 || h.emphasis == 2)
+ return(false);
+
+ if(h.version == 3 && h.layer == 2)
+ {
+ if((h.bitrate == 1 || h.bitrate == 2 || h.bitrate == 3 || h.bitrate == 5) && h.channels != 3
+ && (h.bitrate >= 11 && h.bitrate <= 14) && h.channels == 3)
+ return(false);
+ }
+
+ h.layer = 4 - h.layer;
+
+ //
+
+ static int brtbl[][5] =
+ {
+ {0,0,0,0,0},
+ {32,32,32,32,8},
+ {64,48,40,48,16},
+ {96,56,48,56,24},
+ {128,64,56,64,32},
+ {160,80,64,80,40},
+ {192,96,80,96,48},
+ {224,112,96,112,56},
+ {256,128,112,128,64},
+ {288,160,128,144,80},
+ {320,192,160,160,96},
+ {352,224,192,176,112},
+ {384,256,224,192,128},
+ {416,320,256,224,144},
+ {448,384,320,256,160},
+ {0,0,0,0,0},
+ };
+
+ static int brtblcol[][4] = {{0,3,4,4},{0,0,1,2}};
+ int bitrate = 1000*brtbl[h.bitrate][brtblcol[h.version&1][h.layer]];
+ if(bitrate == 0) return(false);
+
+ static int freq[][4] = {{11025,0,22050,44100},{12000,0,24000,48000},{8000,0,16000,32000}};
+
+ bool l3ext = h.layer == 3 && !(h.version&1);
+
+ h.nSamplesPerSec = freq[h.freq][h.version];
+ h.FrameSize = h.layer == 1
+ ? (12 * bitrate / h.nSamplesPerSec + h.padding) * 4
+ : (l3ext ? 72 : 144) * bitrate / h.nSamplesPerSec + h.padding;
+ h.rtDuration = 10000000i64 * (h.layer == 1 ? 384 : l3ext ? 576 : 1152) / h.nSamplesPerSec;// / (h.channels == 3 ? 1 : 2);
+ h.nBytesPerSec = bitrate / 8;
+
+ if(!pmt) return(true);
+
+ /*int*/ len = h.layer == 3
+ ? sizeof(WAVEFORMATEX/*MPEGLAYER3WAVEFORMAT*/) // no need to overcomplicate this...
+ : sizeof(MPEG1WAVEFORMAT);
+ WAVEFORMATEX* wfe = (WAVEFORMATEX*)DNew BYTE[len];
+ memset(wfe, 0, len);
+ wfe->cbSize = len - sizeof(WAVEFORMATEX);
+
+ if(h.layer == 3)
+ {
+ wfe->wFormatTag = WAVE_FORMAT_MP3;
+
+/* MPEGLAYER3WAVEFORMAT* f = (MPEGLAYER3WAVEFORMAT*)wfe;
+ f->wfx.wFormatTag = WAVE_FORMAT_MP3;
+ f->wID = MPEGLAYER3_ID_UNKNOWN;
+ f->fdwFlags = h.padding ? MPEGLAYER3_FLAG_PADDING_ON : MPEGLAYER3_FLAG_PADDING_OFF; // _OFF or _ISO ?
+*/
+ }
+ else
+ {
+ MPEG1WAVEFORMAT* f = (MPEG1WAVEFORMAT*)wfe;
+ f->wfx.wFormatTag = WAVE_FORMAT_MPEG;
+ f->fwHeadMode = 1 << h.channels;
+ f->fwHeadModeExt = 1 << h.modeext;
+ f->wHeadEmphasis = h.emphasis+1;
+ if(h.privatebit) f->fwHeadFlags |= ACM_MPEG_PRIVATEBIT;
+ if(h.copyright) f->fwHeadFlags |= ACM_MPEG_COPYRIGHT;
+ if(h.original) f->fwHeadFlags |= ACM_MPEG_ORIGINALHOME;
+ if(h.crc == 0) f->fwHeadFlags |= ACM_MPEG_PROTECTIONBIT;
+ if(h.version == 3) f->fwHeadFlags |= ACM_MPEG_ID_MPEG1;
+ f->fwHeadLayer = 1 << (h.layer-1);
+ f->dwHeadBitrate = bitrate;
+ }
+
+ wfe->nChannels = h.channels == 3 ? 1 : 2;
+ wfe->nSamplesPerSec = h.nSamplesPerSec;
+ wfe->nBlockAlign = h.FrameSize;
+ wfe->nAvgBytesPerSec = h.nBytesPerSec;
+
+ pmt->majortype = MEDIATYPE_Audio;
+ pmt->subtype = FOURCCMap(wfe->wFormatTag);
+ pmt->formattype = FORMAT_WaveFormatEx;
+ pmt->SetFormat((BYTE*)wfe, sizeof(WAVEFORMATEX) + wfe->cbSize);
+
+ delete [] wfe;
+
+ return(true);
}
bool CBaseSplitterFileEx::Read(aachdr& h, int len, CMediaType* pmt)
{
- memset(&h, 0, sizeof(h));
+ memset(&h, 0, sizeof(h));
- for(; len >= 7 && BitRead(12, true) != 0xfff; len--)
- BitRead(8);
+ for(; len >= 7 && BitRead(12, true) != 0xfff; len--)
+ BitRead(8);
- if(len < 7)
- return(false);
+ if(len < 7)
+ return(false);
- h.sync = BitRead(12);
- h.version = BitRead(1);
- h.layer = BitRead(2);
- h.fcrc = BitRead(1);
- h.profile = BitRead(2);
- h.freq = BitRead(4);
- h.privatebit = BitRead(1);
- h.channels = BitRead(3);
- h.original = BitRead(1);
- h.home = BitRead(1);
+ h.sync = BitRead(12);
+ h.version = BitRead(1);
+ h.layer = BitRead(2);
+ h.fcrc = BitRead(1);
+ h.profile = BitRead(2);
+ h.freq = BitRead(4);
+ h.privatebit = BitRead(1);
+ h.channels = BitRead(3);
+ h.original = BitRead(1);
+ h.home = BitRead(1);
- h.copyright_id_bit = BitRead(1);
- h.copyright_id_start = BitRead(1);
- h.aac_frame_length = BitRead(13);
- h.adts_buffer_fullness = BitRead(11);
- h.no_raw_data_blocks_in_frame = BitRead(2);
+ h.copyright_id_bit = BitRead(1);
+ h.copyright_id_start = BitRead(1);
+ h.aac_frame_length = BitRead(13);
+ h.adts_buffer_fullness = BitRead(11);
+ h.no_raw_data_blocks_in_frame = BitRead(2);
- if(h.fcrc == 0) h.crc = BitRead(16);
+ if(h.fcrc == 0) h.crc = BitRead(16);
- if(h.layer != 0 || h.freq >= 12 || h.aac_frame_length <= (h.fcrc == 0 ? 9 : 7))
- return(false);
+ if(h.layer != 0 || h.freq >= 12 || h.aac_frame_length <= (h.fcrc == 0 ? 9 : 7))
+ return(false);
- h.FrameSize = h.aac_frame_length - (h.fcrc == 0 ? 9 : 7);
+ h.FrameSize = h.aac_frame_length - (h.fcrc == 0 ? 9 : 7);
static int freq[] = {96000, 88200, 64000, 48000, 44100, 32000, 24000, 22050, 16000, 12000, 11025, 8000};
- h.nBytesPerSec = h.aac_frame_length * freq[h.freq] / 1024; // ok?
- h.rtDuration = 10000000i64 * 1024 / freq[h.freq]; // ok?
+ h.nBytesPerSec = h.aac_frame_length * freq[h.freq] / 1024; // ok?
+ h.rtDuration = 10000000i64 * 1024 / freq[h.freq]; // ok?
- if(!pmt) return(true);
+ if(!pmt) return(true);
- WAVEFORMATEX* wfe = (WAVEFORMATEX*)DNew BYTE[sizeof(WAVEFORMATEX)+5];
- memset(wfe, 0, sizeof(WAVEFORMATEX) + 5);
- wfe->wFormatTag = WAVE_FORMAT_AAC;
- wfe->nChannels = h.channels <= 6 ? h.channels : 2;
- wfe->nSamplesPerSec = freq[h.freq];
- wfe->nBlockAlign = h.aac_frame_length;
- wfe->nAvgBytesPerSec = h.nBytesPerSec;
- wfe->cbSize = MakeAACInitData((BYTE*)(wfe + 1), h.profile, wfe->nSamplesPerSec, wfe->nChannels);
+ WAVEFORMATEX* wfe = (WAVEFORMATEX*)DNew BYTE[sizeof(WAVEFORMATEX)+5];
+ memset(wfe, 0, sizeof(WAVEFORMATEX)+5);
+ wfe->wFormatTag = WAVE_FORMAT_AAC;
+ wfe->nChannels = h.channels <= 6 ? h.channels : 2;
+ wfe->nSamplesPerSec = freq[h.freq];
+ wfe->nBlockAlign = h.aac_frame_length;
+ wfe->nAvgBytesPerSec = h.nBytesPerSec;
+ wfe->cbSize = MakeAACInitData((BYTE*)(wfe+1), h.profile, wfe->nSamplesPerSec, wfe->nChannels);
- pmt->majortype = MEDIATYPE_Audio;
- pmt->subtype = MEDIASUBTYPE_AAC;
- pmt->formattype = FORMAT_WaveFormatEx;
- pmt->SetFormat((BYTE*)wfe, sizeof(WAVEFORMATEX) + wfe->cbSize);
+ pmt->majortype = MEDIATYPE_Audio;
+ pmt->subtype = MEDIASUBTYPE_AAC;
+ pmt->formattype = FORMAT_WaveFormatEx;
+ pmt->SetFormat((BYTE*)wfe, sizeof(WAVEFORMATEX)+wfe->cbSize);
- delete [] wfe;
+ delete [] wfe;
- return(true);
+ return(true);
}
bool CBaseSplitterFileEx::Read(ac3hdr& h, int len, CMediaType* pmt)
{
- memset(&h, 0, sizeof(h));
-
- for(; len >= 7 && BitRead(16, true) != 0x0b77; len--)
- BitRead(8);
-
- if(len < 7)
- return(false);
-
- h.sync = (WORD)BitRead(16);
- if(h.sync != 0x0B77)
- return(false);
-
- h.crc1 = (WORD)BitRead(16);
- h.fscod = BitRead(2);
- h.frmsizecod = BitRead(6);
- h.bsid = BitRead(5);
- h.bsmod = BitRead(3);
- h.acmod = BitRead(3);
- if((h.acmod & 1) && h.acmod != 1) h.cmixlev = BitRead(2);
- if(h.acmod & 4) h.surmixlev = BitRead(2);
- if(h.acmod == 2) h.dsurmod = BitRead(2);
- h.lfeon = BitRead(1);
-
- if(h.bsid >= 17 || h.fscod == 3 || h.frmsizecod >= 48)
- return(false);
-
- if(!pmt) return(true);
-
- WAVEFORMATEX wfe;
- memset(&wfe, 0, sizeof(wfe));
- wfe.wFormatTag = WAVE_FORMAT_DOLBY_AC3;
-
- static int channels[] = {2, 1, 2, 3, 3, 4, 4, 5};
- wfe.nChannels = channels[h.acmod] + h.lfeon;
-
- static int freq[] = {48000, 44100, 32000, 0};
- wfe.nSamplesPerSec = freq[h.fscod];
-
- switch(h.bsid)
- {
- case 9:
- wfe.nSamplesPerSec >>= 1;
- break;
- case 10:
- wfe.nSamplesPerSec >>= 2;
- break;
- case 11:
- wfe.nSamplesPerSec >>= 3;
- break;
- default:
- break;
- }
+ memset(&h, 0, sizeof(h));
+
+ for(; len >= 7 && BitRead(16, true) != 0x0b77; len--)
+ BitRead(8);
+
+ if(len < 7)
+ return(false);
+
+ h.sync = (WORD)BitRead(16);
+ if(h.sync != 0x0B77)
+ return(false);
+
+ h.crc1 = (WORD)BitRead(16);
+ h.fscod = BitRead(2);
+ h.frmsizecod = BitRead(6);
+ h.bsid = BitRead(5);
+ h.bsmod = BitRead(3);
+ h.acmod = BitRead(3);
+ if((h.acmod & 1) && h.acmod != 1) h.cmixlev = BitRead(2);
+ if(h.acmod & 4) h.surmixlev = BitRead(2);
+ if(h.acmod == 2) h.dsurmod = BitRead(2);
+ h.lfeon = BitRead(1);
+
+ if(h.bsid >= 17 || h.fscod == 3 || h.frmsizecod >= 48)
+ return(false);
+
+ if(!pmt) return(true);
+
+ WAVEFORMATEX wfe;
+ memset(&wfe, 0, sizeof(wfe));
+ wfe.wFormatTag = WAVE_FORMAT_DOLBY_AC3;
- static int rate[] = {32, 40, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320, 384, 448, 512, 576, 640, 768, 896, 1024, 1152, 1280};
+ static int channels[] = {2, 1, 2, 3, 3, 4, 4, 5};
+ wfe.nChannels = channels[h.acmod] + h.lfeon;
- wfe.nAvgBytesPerSec = (rate[h.frmsizecod>>1] * 1000) / 8;
- wfe.nBlockAlign = (WORD)(1536 * wfe.nAvgBytesPerSec / wfe.nSamplesPerSec);
+ static int freq[] = {48000, 44100, 32000, 0};
+ wfe.nSamplesPerSec = freq[h.fscod];
- pmt->majortype = MEDIATYPE_Audio;
- pmt->subtype = MEDIASUBTYPE_DOLBY_AC3;
- pmt->formattype = FORMAT_WaveFormatEx;
- pmt->SetFormat((BYTE*)&wfe, sizeof(wfe));
+ switch(h.bsid)
+ {
+ case 9: wfe.nSamplesPerSec >>= 1; break;
+ case 10: wfe.nSamplesPerSec >>= 2; break;
+ case 11: wfe.nSamplesPerSec >>= 3; break;
+ default: break;
+ }
- return(true);
+ static int rate[] = {32, 40, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320, 384, 448, 512, 576, 640, 768, 896, 1024, 1152, 1280};
+
+ wfe.nAvgBytesPerSec = (rate[h.frmsizecod>>1] * 1000) / 8;
+ wfe.nBlockAlign = (WORD)(1536 * wfe.nAvgBytesPerSec / wfe.nSamplesPerSec);
+
+ pmt->majortype = MEDIATYPE_Audio;
+ pmt->subtype = MEDIASUBTYPE_DOLBY_AC3;
+ pmt->formattype = FORMAT_WaveFormatEx;
+ pmt->SetFormat((BYTE*)&wfe, sizeof(wfe));
+
+ return(true);
}
bool CBaseSplitterFileEx::Read(dtshdr& h, int len, CMediaType* pmt)
{
- memset(&h, 0, sizeof(h));
+ memset(&h, 0, sizeof(h));
- for(; len >= 10 && BitRead(32, true) != 0x7ffe8001; len--)
- BitRead(8);
+ for(; len >= 10 && BitRead(32, true) != 0x7ffe8001; len--)
+ BitRead(8);
- if(len < 10)
- return(false);
+ if(len < 10)
+ return(false);
- h.sync = (DWORD)BitRead(32);
- h.frametype = BitRead(1);
- h.deficitsamplecount = BitRead(5);
- h.fcrc = BitRead(1);
- h.nblocks = BitRead(7);
- h.framebytes = (WORD)BitRead(14) + 1;
- h.amode = BitRead(6);
- h.sfreq = BitRead(4);
- h.rate = BitRead(5);
+ h.sync = (DWORD)BitRead(32);
+ h.frametype = BitRead(1);
+ h.deficitsamplecount = BitRead(5);
+ h.fcrc = BitRead(1);
+ h.nblocks = BitRead(7);
+ h.framebytes = (WORD)BitRead(14)+1;
+ h.amode = BitRead(6);
+ h.sfreq = BitRead(4);
+ h.rate = BitRead(5);
h.downmix = BitRead(1);
h.dynrange = BitRead(1);
@@ -724,1006 +675,981 @@ bool CBaseSplitterFileEx::Read(dtshdr& h, int len, CMediaType* pmt)
h.predictor_history = BitRead(1);
- if(!pmt) return(true);
+ if(!pmt) return(true);
- WAVEFORMATEX wfe;
- memset(&wfe, 0, sizeof(wfe));
- wfe.wFormatTag = WAVE_FORMAT_DVD_DTS;
+ WAVEFORMATEX wfe;
+ memset(&wfe, 0, sizeof(wfe));
+ wfe.wFormatTag = WAVE_FORMAT_DVD_DTS;
- static int channels[] = {1, 2, 2, 2, 2, 3, 3, 4, 4, 5, 6, 6, 6, 7, 8, 8};
+ static int channels[] = {1, 2, 2, 2, 2, 3, 3, 4, 4, 5, 6, 6, 6, 7, 8, 8};
- if(h.amode < countof(channels))
- {
- wfe.nChannels = channels[h.amode];
- if(h.lfe > 0)
- ++wfe.nChannels;
- }
+ if(h.amode < countof(channels))
+ {
+ wfe.nChannels = channels[h.amode];
+ if (h.lfe > 0)
+ ++wfe.nChannels;
+ }
- static int freq[] = {0, 8000, 16000, 32000, 0, 0, 11025, 22050, 44100, 0, 0, 12000, 24000, 48000, 0, 0};
- wfe.nSamplesPerSec = freq[h.sfreq];
+ static int freq[] = {0,8000,16000,32000,0,0,11025,22050,44100,0,0,12000,24000,48000,0,0};
+ wfe.nSamplesPerSec = freq[h.sfreq];
- static int rate[] =
- {
- 32000, 56000, 64000, 96000, 112000, 128000, 192000, 224000,
- 256000, 320000, 384000, 448000, 512000, 576000, 640000, 754500,
- 960000, 1024000, 1152000, 1280000, 1344000, 1408000, 1411200, 1472000,
- 1509750, 1920000, 2048000, 3072000, 3840000, 0, 0, 0
- };
+ static int rate[] =
+ {
+ 32000,56000,64000,96000,112000,128000,192000,224000,
+ 256000,320000,384000,448000,512000,576000,640000,754500,
+ 960000,1024000,1152000,1280000,1344000,1408000,1411200,1472000,
+ 1509750,1920000,2048000,3072000,3840000,0,0,0
+ };
- wfe.nAvgBytesPerSec = (rate[h.rate] + 4) / 8;
- wfe.nBlockAlign = h.framebytes;
+ wfe.nAvgBytesPerSec = (rate[h.rate] + 4) / 8;
+ wfe.nBlockAlign = h.framebytes;
- pmt->majortype = MEDIATYPE_Audio;
- pmt->subtype = MEDIASUBTYPE_DTS;
- pmt->formattype = FORMAT_WaveFormatEx;
- pmt->SetFormat((BYTE*)&wfe, sizeof(wfe));
+ pmt->majortype = MEDIATYPE_Audio;
+ pmt->subtype = MEDIASUBTYPE_DTS;
+ pmt->formattype = FORMAT_WaveFormatEx;
+ pmt->SetFormat((BYTE*)&wfe, sizeof(wfe));
- return(true);
+ return(true);
}
bool CBaseSplitterFileEx::Read(hdmvlpcmhdr& h, CMediaType* pmt)
{
- memset(&h, 0, sizeof(h));
+ memset(&h, 0, sizeof(h));
- h.size = BitRead(16);
- h.channels = BitRead(4);
- h.samplerate = BitRead(4);
- h.bitpersample = BitRead(2);
+ h.size = BitRead(16);
+ h.channels = BitRead(4);
+ h.samplerate = BitRead(4);
+ h.bitpersample = BitRead(2);
- if(h.channels == 0 || h.channels == 2 ||
- (h.samplerate != 1 && h.samplerate != 4 && h.samplerate != 5) ||
- h.bitpersample < 0 || h.bitpersample > 3)
- return(false);
+ if (h.channels==0 || h.channels==2 ||
+ (h.samplerate != 1 && h.samplerate!= 4 && h.samplerate!= 5) ||
+ h.bitpersample<0 || h.bitpersample>3)
+ return(false);
- if(!pmt) return(true);
+ if(!pmt) return(true);
- WAVEFORMATEX_HDMV_LPCM wfe;
- wfe.wFormatTag = WAVE_FORMAT_PCM;
+ WAVEFORMATEX_HDMV_LPCM wfe;
+ wfe.wFormatTag = WAVE_FORMAT_PCM;
- static int channels[] = {0, 1, 0, 2, 3, 3, 4, 4, 5, 6, 7, 8};
- wfe.nChannels = channels[h.channels];
- wfe.channel_conf = h.channels;
+ static int channels[] = {0, 1, 0, 2, 3, 3, 4, 4, 5, 6, 7, 8};
+ wfe.nChannels = channels[h.channels];
+ wfe.channel_conf = h.channels;
- static int freq[] = {0, 48000, 0, 0, 96000, 192000};
- wfe.nSamplesPerSec = freq[h.samplerate];
+ static int freq[] = {0, 48000, 0, 0, 96000, 192000};
+ wfe.nSamplesPerSec = freq[h.samplerate];
- static int bitspersample[] = {0, 16, 20, 24};
- wfe.wBitsPerSample = bitspersample[h.bitpersample];
+ static int bitspersample[] = {0, 16, 20, 24};
+ wfe.wBitsPerSample = bitspersample[h.bitpersample];
- wfe.nBlockAlign = wfe.nChannels * wfe.wBitsPerSample >> 3;
- wfe.nAvgBytesPerSec = wfe.nBlockAlign * wfe.nSamplesPerSec;
+ wfe.nBlockAlign = wfe.nChannels*wfe.wBitsPerSample>>3;
+ wfe.nAvgBytesPerSec = wfe.nBlockAlign*wfe.nSamplesPerSec;
- pmt->majortype = MEDIATYPE_Audio;
- pmt->subtype = MEDIASUBTYPE_HDMV_LPCM_AUDIO;
- pmt->formattype = FORMAT_WaveFormatEx;
- pmt->SetFormat((BYTE*)&wfe, sizeof(wfe));
+ pmt->majortype = MEDIATYPE_Audio;
+ pmt->subtype = MEDIASUBTYPE_HDMV_LPCM_AUDIO;
+ pmt->formattype = FORMAT_WaveFormatEx;
+ pmt->SetFormat((BYTE*)&wfe, sizeof(wfe));
- return(true);
+ return(true);
}
bool CBaseSplitterFileEx::Read(lpcmhdr& h, CMediaType* pmt)
{
- memset(&h, 0, sizeof(h));
-
- h.emphasis = BitRead(1);
- h.mute = BitRead(1);
- h.reserved1 = BitRead(1);
- h.framenum = BitRead(5);
- h.quantwordlen = BitRead(2);
- h.freq = BitRead(2);
- h.reserved2 = BitRead(1);
- h.channels = BitRead(3);
- h.drc = (BYTE)BitRead(8);
-
- if(h.quantwordlen == 3 || h.reserved1 || h.reserved2)
- return(false);
-
- if(!pmt) return(true);
-
- WAVEFORMATEX wfe;
- memset(&wfe, 0, sizeof(wfe));
- wfe.wFormatTag = WAVE_FORMAT_PCM;
- wfe.nChannels = h.channels + 1;
- static int freq[] = {48000, 96000, 44100, 32000};
- wfe.nSamplesPerSec = freq[h.freq];
- switch(h.quantwordlen)
- {
- case 0:
- wfe.wBitsPerSample = 16;
- break;
- case 1:
- wfe.wBitsPerSample = 20;
- break;
- case 2:
- wfe.wBitsPerSample = 24;
- break;
- }
- wfe.nBlockAlign = (wfe.nChannels * 2 * wfe.wBitsPerSample) / 8;
- wfe.nAvgBytesPerSec = (wfe.nBlockAlign * wfe.nSamplesPerSec) / 2;
-
- pmt->majortype = MEDIATYPE_Audio;
- pmt->subtype = MEDIASUBTYPE_DVD_LPCM_AUDIO;
- pmt->formattype = FORMAT_WaveFormatEx;
- pmt->SetFormat((BYTE*)&wfe, sizeof(wfe));
-
- // TODO: what to do with dvd-audio lpcm?
-
- return(true);
+ memset(&h, 0, sizeof(h));
+
+ h.emphasis = BitRead(1);
+ h.mute = BitRead(1);
+ h.reserved1 = BitRead(1);
+ h.framenum = BitRead(5);
+ h.quantwordlen = BitRead(2);
+ h.freq = BitRead(2);
+ h.reserved2 = BitRead(1);
+ h.channels = BitRead(3);
+ h.drc = (BYTE)BitRead(8);
+
+ if(h.quantwordlen == 3 || h.reserved1 || h.reserved2)
+ return(false);
+
+ if(!pmt) return(true);
+
+ WAVEFORMATEX wfe;
+ memset(&wfe, 0, sizeof(wfe));
+ wfe.wFormatTag = WAVE_FORMAT_PCM;
+ wfe.nChannels = h.channels+1;
+ static int freq[] = {48000, 96000, 44100, 32000};
+ wfe.nSamplesPerSec = freq[h.freq];
+ switch (h.quantwordlen)
+ {
+ case 0:
+ wfe.wBitsPerSample = 16;
+ break;
+ case 1:
+ wfe.wBitsPerSample = 20;
+ break;
+ case 2:
+ wfe.wBitsPerSample = 24;
+ break;
+ }
+ wfe.nBlockAlign = (wfe.nChannels*2*wfe.wBitsPerSample) / 8;
+ wfe.nAvgBytesPerSec = (wfe.nBlockAlign*wfe.nSamplesPerSec) / 2;
+
+ pmt->majortype = MEDIATYPE_Audio;
+ pmt->subtype = MEDIASUBTYPE_DVD_LPCM_AUDIO;
+ pmt->formattype = FORMAT_WaveFormatEx;
+ pmt->SetFormat((BYTE*)&wfe, sizeof(wfe));
+
+ // TODO: what to do with dvd-audio lpcm?
+
+ return(true);
}
bool CBaseSplitterFileEx::Read(dvdspuhdr& h, CMediaType* pmt)
{
- memset(&h, 0, sizeof(h));
+ memset(&h, 0, sizeof(h));
- if(!pmt) return(true);
+ if(!pmt) return(true);
- pmt->majortype = MEDIATYPE_Video;
- pmt->subtype = MEDIASUBTYPE_DVD_SUBPICTURE;
- pmt->formattype = FORMAT_None;
+ pmt->majortype = MEDIATYPE_Video;
+ pmt->subtype = MEDIASUBTYPE_DVD_SUBPICTURE;
+ pmt->formattype = FORMAT_None;
- return(true);
+ return(true);
}
bool CBaseSplitterFileEx::Read(hdmvsubhdr& h, CMediaType* pmt, const char* language_code)
{
- memset(&h, 0, sizeof(h));
+ memset(&h, 0, sizeof(h));
- if(!pmt) return(true);
+ if(!pmt) return(true);
- pmt->majortype = MEDIATYPE_Subtitle;
- pmt->subtype = MEDIASUBTYPE_HDMVSUB;
- pmt->formattype = FORMAT_None;
+ pmt->majortype = MEDIATYPE_Subtitle;
+ pmt->subtype = MEDIASUBTYPE_HDMVSUB;
+ pmt->formattype = FORMAT_None;
- SUBTITLEINFO* psi = (SUBTITLEINFO*)pmt->AllocFormatBuffer(sizeof(SUBTITLEINFO));
- if(psi)
- {
- memset(psi, 0, pmt->FormatLength());
- strcpy(psi->IsoLang, language_code ? language_code : "eng");
- }
+ SUBTITLEINFO* psi = (SUBTITLEINFO*)pmt->AllocFormatBuffer(sizeof(SUBTITLEINFO));
+ if (psi)
+ {
+ memset(psi, 0, pmt->FormatLength());
+ strcpy(psi->IsoLang, language_code ? language_code : "eng");
+ }
- return(true);
+ return(true);
}
bool CBaseSplitterFileEx::Read(svcdspuhdr& h, CMediaType* pmt)
{
- memset(&h, 0, sizeof(h));
+ memset(&h, 0, sizeof(h));
- if(!pmt) return(true);
+ if(!pmt) return(true);
- pmt->majortype = MEDIATYPE_Video;
- pmt->subtype = MEDIASUBTYPE_SVCD_SUBPICTURE;
- pmt->formattype = FORMAT_None;
+ pmt->majortype = MEDIATYPE_Video;
+ pmt->subtype = MEDIASUBTYPE_SVCD_SUBPICTURE;
+ pmt->formattype = FORMAT_None;
- return(true);
+ return(true);
}
bool CBaseSplitterFileEx::Read(cvdspuhdr& h, CMediaType* pmt)
{
- memset(&h, 0, sizeof(h));
+ memset(&h, 0, sizeof(h));
- if(!pmt) return(true);
+ if(!pmt) return(true);
- pmt->majortype = MEDIATYPE_Video;
- pmt->subtype = MEDIASUBTYPE_CVD_SUBPICTURE;
- pmt->formattype = FORMAT_None;
+ pmt->majortype = MEDIATYPE_Video;
+ pmt->subtype = MEDIASUBTYPE_CVD_SUBPICTURE;
+ pmt->formattype = FORMAT_None;
- return(true);
+ return(true);
}
bool CBaseSplitterFileEx::Read(ps2audhdr& h, CMediaType* pmt)
{
- memset(&h, 0, sizeof(h));
-
- if(BitRead(16, true) != 'SS')
- return(false);
-
- __int64 pos = GetPos();
-
- while(BitRead(16, true) == 'SS')
- {
- DWORD tag = (DWORD)BitRead(32, true);
- DWORD size = 0;
-
- if(tag == 'SShd')
- {
- BitRead(32);
- ByteRead((BYTE*)&size, sizeof(size));
- ASSERT(size == 0x18);
- Seek(GetPos());
- ByteRead((BYTE*)&h, sizeof(h));
- }
- else if(tag == 'SSbd')
- {
- BitRead(32);
- ByteRead((BYTE*)&size, sizeof(size));
- break;
- }
- }
-
- Seek(pos);
-
- if(!pmt) return(true);
-
- WAVEFORMATEXPS2 wfe;
- wfe.wFormatTag =
- h.unk1 == 0x01 ? WAVE_FORMAT_PS2_PCM :
- h.unk1 == 0x10 ? WAVE_FORMAT_PS2_ADPCM :
- WAVE_FORMAT_UNKNOWN;
- wfe.nChannels = (WORD)h.channels;
- wfe.nSamplesPerSec = h.freq;
- wfe.wBitsPerSample = 16; // always?
- wfe.nBlockAlign = wfe.nChannels * wfe.wBitsPerSample >> 3;
- wfe.nAvgBytesPerSec = wfe.nBlockAlign * wfe.nSamplesPerSec;
- wfe.dwInterleave = h.interleave;
-
- pmt->majortype = MEDIATYPE_Audio;
- pmt->subtype = FOURCCMap(wfe.wFormatTag);
- pmt->formattype = FORMAT_WaveFormatEx;
- pmt->SetFormat((BYTE*)&wfe, sizeof(wfe));
-
- return(true);
+ memset(&h, 0, sizeof(h));
+
+ if(BitRead(16, true) != 'SS')
+ return(false);
+
+ __int64 pos = GetPos();
+
+ while(BitRead(16, true) == 'SS')
+ {
+ DWORD tag = (DWORD)BitRead(32, true);
+ DWORD size = 0;
+
+ if(tag == 'SShd')
+ {
+ BitRead(32);
+ ByteRead((BYTE*)&size, sizeof(size));
+ ASSERT(size == 0x18);
+ Seek(GetPos());
+ ByteRead((BYTE*)&h, sizeof(h));
+ }
+ else if(tag == 'SSbd')
+ {
+ BitRead(32);
+ ByteRead((BYTE*)&size, sizeof(size));
+ break;
+ }
+ }
+
+ Seek(pos);
+
+ if(!pmt) return(true);
+
+ WAVEFORMATEXPS2 wfe;
+ wfe.wFormatTag =
+ h.unk1 == 0x01 ? WAVE_FORMAT_PS2_PCM :
+ h.unk1 == 0x10 ? WAVE_FORMAT_PS2_ADPCM :
+ WAVE_FORMAT_UNKNOWN;
+ wfe.nChannels = (WORD)h.channels;
+ wfe.nSamplesPerSec = h.freq;
+ wfe.wBitsPerSample = 16; // always?
+ wfe.nBlockAlign = wfe.nChannels*wfe.wBitsPerSample>>3;
+ wfe.nAvgBytesPerSec = wfe.nBlockAlign*wfe.nSamplesPerSec;
+ wfe.dwInterleave = h.interleave;
+
+ pmt->majortype = MEDIATYPE_Audio;
+ pmt->subtype = FOURCCMap(wfe.wFormatTag);
+ pmt->formattype = FORMAT_WaveFormatEx;
+ pmt->SetFormat((BYTE*)&wfe, sizeof(wfe));
+
+ return(true);
}
bool CBaseSplitterFileEx::Read(ps2subhdr& h, CMediaType* pmt)
{
- memset(&h, 0, sizeof(h));
+ memset(&h, 0, sizeof(h));
- if(!pmt) return(true);
+ if(!pmt) return(true);
- pmt->majortype = MEDIATYPE_Subtitle;
- pmt->subtype = MEDIASUBTYPE_PS2_SUB;
- pmt->formattype = FORMAT_None;
+ pmt->majortype = MEDIATYPE_Subtitle;
+ pmt->subtype = MEDIASUBTYPE_PS2_SUB;
+ pmt->formattype = FORMAT_None;
- return(true);
+ return(true);
}
bool CBaseSplitterFileEx::Read(trhdr& h, bool fSync)
{
- memset(&h, 0, sizeof(h));
-
- BitByteAlign();
-
- if(m_tslen == 0)
- {
- __int64 pos = GetPos();
-
- for(int i = 0; i < 192; i++)
- {
- if(BitRead(8, true) == 0x47)
- {
- __int64 pos = GetPos();
- Seek(pos + 188);
- if(BitRead(8, true) == 0x47)
- {
- m_tslen = 188; // TS stream
- break;
- }
- Seek(pos + 192);
- if(BitRead(8, true) == 0x47)
- {
- m_tslen = 192; // M2TS stream
- break;
- }
- }
-
- BitRead(8);
- }
-
- Seek(pos);
-
- if(m_tslen == 0)
- {
- return(false);
- }
- }
-
- if(fSync)
- {
- for(int i = 0; i < m_tslen; i++)
- {
- if(BitRead(8, true) == 0x47)
- {
- if(i == 0) break;
- Seek(GetPos() + m_tslen);
- if(BitRead(8, true) == 0x47)
- {
- Seek(GetPos() - m_tslen);
- break;
- }
- }
-
- BitRead(8);
-
- if(i == m_tslen - 1)
- return(false);
- }
- }
-
- if(BitRead(8, true) != 0x47)
- return(false);
-
- h.next = GetPos() + m_tslen;
-
- h.sync = (BYTE)BitRead(8);
- h.error = BitRead(1);
- h.payloadstart = BitRead(1);
- h.transportpriority = BitRead(1);
- h.pid = BitRead(13);
- h.scrambling = BitRead(2);
- h.adapfield = BitRead(1);
- h.payload = BitRead(1);
- h.counter = BitRead(4);
-
- h.bytes = 188 - 4;
-
- if(h.adapfield)
- {
- h.length = (BYTE)BitRead(8);
-
- if(h.length > 0)
- {
- h.discontinuity = BitRead(1);
- h.randomaccess = BitRead(1);
- h.priority = BitRead(1);
- h.fPCR = BitRead(1);
- h.OPCR = BitRead(1);
- h.splicingpoint = BitRead(1);
- h.privatedata = BitRead(1);
- h.extension = BitRead(1);
-
- int i = 1;
-
- if(h.fPCR)
- {
- h.PCR = BitRead(33);
- BitRead(6);
- UINT64 PCRExt = BitRead(9);
- h.PCR = (h.PCR * 300 + PCRExt) * 10 / 27;
- i += 6;
- }
-
- ASSERT(i <= h.length);
-
- for(; i < h.length; i++)
- BitRead(8);
- }
-
- h.bytes -= h.length + 1;
-
- if(h.bytes < 0)
- {
- ASSERT(0);
- return false;
- }
- }
-
- return true;
+ memset(&h, 0, sizeof(h));
+
+ BitByteAlign();
+
+ if(m_tslen == 0)
+ {
+ __int64 pos = GetPos();
+
+ for(int i = 0; i < 192; i++)
+ {
+ if(BitRead(8, true) == 0x47)
+ {
+ __int64 pos = GetPos();
+ Seek(pos + 188);
+ if(BitRead(8, true) == 0x47) {m_tslen = 188; break;} // TS stream
+ Seek(pos + 192);
+ if(BitRead(8, true) == 0x47) {m_tslen = 192; break;} // M2TS stream
+ }
+
+ BitRead(8);
+ }
+
+ Seek(pos);
+
+ if(m_tslen == 0)
+ {
+ return(false);
+ }
+ }
+
+ if(fSync)
+ {
+ for(int i = 0; i < m_tslen; i++)
+ {
+ if(BitRead(8, true) == 0x47)
+ {
+ if(i == 0) break;
+ Seek(GetPos()+m_tslen);
+ if(BitRead(8, true) == 0x47) {Seek(GetPos()-m_tslen); break;}
+ }
+
+ BitRead(8);
+
+ if(i == m_tslen-1)
+ return(false);
+ }
+ }
+
+ if(BitRead(8, true) != 0x47)
+ return(false);
+
+ h.next = GetPos() + m_tslen;
+
+ h.sync = (BYTE)BitRead(8);
+ h.error = BitRead(1);
+ h.payloadstart = BitRead(1);
+ h.transportpriority = BitRead(1);
+ h.pid = BitRead(13);
+ h.scrambling = BitRead(2);
+ h.adapfield = BitRead(1);
+ h.payload = BitRead(1);
+ h.counter = BitRead(4);
+
+ h.bytes = 188 - 4;
+
+ if(h.adapfield)
+ {
+ h.length = (BYTE)BitRead(8);
+
+ if(h.length > 0)
+ {
+ h.discontinuity = BitRead(1);
+ h.randomaccess = BitRead(1);
+ h.priority = BitRead(1);
+ h.fPCR = BitRead(1);
+ h.OPCR = BitRead(1);
+ h.splicingpoint = BitRead(1);
+ h.privatedata = BitRead(1);
+ h.extension = BitRead(1);
+
+ int i = 1;
+
+ if(h.fPCR)
+ {
+ h.PCR = BitRead(33);
+ BitRead(6);
+ UINT64 PCRExt = BitRead(9);
+ h.PCR = (h.PCR*300 + PCRExt) * 10 / 27;
+ i += 6;
+ }
+
+ ASSERT(i <= h.length);
+
+ for(; i < h.length; i++)
+ BitRead(8);
+ }
+
+ h.bytes -= h.length+1;
+
+ if(h.bytes < 0) {ASSERT(0); return false;}
+ }
+
+ return true;
}
bool CBaseSplitterFileEx::Read(trsechdr& h)
{
- BYTE pointer_field = BitRead(8);
- while(pointer_field-- > 0) BitRead(8);
- h.table_id = BitRead(8);
- h.section_syntax_indicator = BitRead(1);
- h.zero = BitRead(1);
- h.reserved1 = BitRead(2);
- h.section_length = BitRead(12);
- h.transport_stream_id = BitRead(16);
- h.reserved2 = BitRead(2);
- h.version_number = BitRead(5);
- h.current_next_indicator = BitRead(1);
- h.section_number = BitRead(8);
- h.last_section_number = BitRead(8);
- return h.section_syntax_indicator == 1 && h.zero == 0;
+ BYTE pointer_field = BitRead(8);
+ while(pointer_field-- > 0) BitRead(8);
+ h.table_id = BitRead(8);
+ h.section_syntax_indicator = BitRead(1);
+ h.zero = BitRead(1);
+ h.reserved1 = BitRead(2);
+ h.section_length = BitRead(12);
+ h.transport_stream_id = BitRead(16);
+ h.reserved2 = BitRead(2);
+ h.version_number = BitRead(5);
+ h.current_next_indicator = BitRead(1);
+ h.section_number = BitRead(8);
+ h.last_section_number = BitRead(8);
+ return h.section_syntax_indicator == 1 && h.zero == 0;
}
bool CBaseSplitterFileEx::Read(pvahdr& h, bool fSync)
{
- memset(&h, 0, sizeof(h));
-
- BitByteAlign();
-
- if(fSync)
- {
- for(int i = 0; i < 65536; i++)
- {
- if((BitRead(64, true) & 0xfffffc00ffe00000i64) == 0x4156000055000000i64)
- break;
- BitRead(8);
- }
- }
-
- if((BitRead(64, true) & 0xfffffc00ffe00000i64) != 0x4156000055000000i64)
- return(false);
-
- h.sync = (WORD)BitRead(16);
- h.streamid = (BYTE)BitRead(8);
- h.counter = (BYTE)BitRead(8);
- h.res1 = (BYTE)BitRead(8);
- h.res2 = BitRead(3);
- h.fpts = BitRead(1);
- h.postbytes = BitRead(2);
- h.prebytes = BitRead(2);
- h.length = (WORD)BitRead(16);
-
- if(h.length > 6136)
- return(false);
-
- __int64 pos = GetPos();
-
- if(h.streamid == 1 && h.fpts)
- {
- h.pts = 10000 * BitRead(32) / 90 + m_rtPTSOffset;
- }
- else if(h.streamid == 2 && (h.fpts || (BitRead(32, true) & 0xffffffe0) == 0x000001c0))
- {
- BYTE b;
- if(!NextMpegStartCode(b, 4)) return(false);
- peshdr h2;
- if(!Read(h2, b)) return(false);
- if(h.fpts = h2.fpts) h.pts = h2.pts;
- }
-
- BitRead(8 * h.prebytes);
-
- h.length -= GetPos() - pos;
-
- return(true);
+ memset(&h, 0, sizeof(h));
+
+ BitByteAlign();
+
+ if(fSync)
+ {
+ for(int i = 0; i < 65536; i++)
+ {
+ if((BitRead(64, true)&0xfffffc00ffe00000i64) == 0x4156000055000000i64)
+ break;
+ BitRead(8);
+ }
+ }
+
+ if((BitRead(64, true)&0xfffffc00ffe00000i64) != 0x4156000055000000i64)
+ return(false);
+
+ h.sync = (WORD)BitRead(16);
+ h.streamid = (BYTE)BitRead(8);
+ h.counter = (BYTE)BitRead(8);
+ h.res1 = (BYTE)BitRead(8);
+ h.res2 = BitRead(3);
+ h.fpts = BitRead(1);
+ h.postbytes = BitRead(2);
+ h.prebytes = BitRead(2);
+ h.length = (WORD)BitRead(16);
+
+ if(h.length > 6136)
+ return(false);
+
+ __int64 pos = GetPos();
+
+ if(h.streamid == 1 && h.fpts)
+ {
+ h.pts = 10000*BitRead(32)/90 + m_rtPTSOffset;
+ }
+ else if(h.streamid == 2 && (h.fpts || (BitRead(32, true)&0xffffffe0) == 0x000001c0))
+ {
+ BYTE b;
+ if(!NextMpegStartCode(b, 4)) return(false);
+ peshdr h2;
+ if(!Read(h2, b)) return(false);
+ if(h.fpts = h2.fpts) h.pts = h2.pts;
+ }
+
+ BitRead(8*h.prebytes);
+
+ h.length -= GetPos() - pos;
+
+ return(true);
}
void CBaseSplitterFileEx::RemoveMpegEscapeCode(BYTE* dst, BYTE* src, int length)
-{
- int si = 0;
- int di = 0;
- while(si + 2 < length)
- {
+{
+ int si=0;
+ int di=0;
+ while(si+2<length){
//remove escapes (very rare 1:2^22)
- if(src[si+2] > 3)
- {
- dst[di++] = src[si++];
- dst[di++] = src[si++];
- }
- else if(src[si] == 0 && src[si+1] == 0)
- {
- if(src[si+2] == 3) //escape
- {
- dst[di++] = 0;
- dst[di++] = 0;
- si += 3;
+ if(src[si+2]>3){
+ dst[di++]= src[si++];
+ dst[di++]= src[si++];
+ }else if(src[si]==0 && src[si+1]==0){
+ if(src[si+2]==3){ //escape
+ dst[di++]= 0;
+ dst[di++]= 0;
+ si+=3;
continue;
- }
- else //next start code
+ }else //next start code
return;
}
- dst[di++] = src[si++];
+ dst[di++]= src[si++];
}
}
bool CBaseSplitterFileEx::Read(avchdr& h, int len, CMediaType* pmt)
{
- __int64 endpos = GetPos() + len; // - sequence header length
+ __int64 endpos = GetPos() + len; // - sequence header length
- DWORD dwStartCode;
+ DWORD dwStartCode;
- while(GetPos() < endpos + 4 && BitRead(32, true) == 0x00000001 && (!h.spslen || !h.ppslen))
- {
- __int64 pos = GetPos();
+ while(GetPos() < endpos+4 && BitRead(32, true) == 0x00000001 && (!h.spslen || !h.ppslen))
+ {
+ __int64 pos = GetPos();
- BitRead(32);
- BYTE id = BitRead(8);
-
- if((id & 0x9f) == 0x07 && (id & 0x60) != 0)
- {
+ BitRead(32);
+ BYTE id = BitRead(8);
+
+ if((id&0x9f) == 0x07 && (id&0x60) != 0)
+ {
#if 1
- BYTE SPSTemp[MAX_SPS];
- BYTE SPSBuff[MAX_SPS];
- CGolombBuffer gb(SPSBuff, MAX_SPS);
- __int64 num_units_in_tick;
- __int64 time_scale;
- long fixed_frame_rate_flag;
-
- h.spspos = pos;
-
- // Manage H264 escape codes (see "remove escapes (very rare 1:2^22)" in ffmpeg h264.c file)
- ByteRead((BYTE*)SPSTemp, MAX_SPS);
- RemoveMpegEscapeCode(SPSBuff, SPSTemp, MAX_SPS);
-
- h.profile = (BYTE)gb.BitRead(8);
- gb.BitRead(8);
- h.level = (BYTE)gb.BitRead(8);
-
- gb.UExpGolombRead(); // seq_parameter_set_id
-
- if(h.profile >= 100) // high profile
- {
- if(gb.UExpGolombRead() == 3) // chroma_format_idc
- {
- gb.BitRead(1); // residue_transform_flag
- }
-
- gb.UExpGolombRead(); // bit_depth_luma_minus8
- gb.UExpGolombRead(); // bit_depth_chroma_minus8
-
- gb.BitRead(1); // qpprime_y_zero_transform_bypass_flag
-
- if(gb.BitRead(1)) // seq_scaling_matrix_present_flag
- for(int i = 0; i < 8; i++)
- if(gb.BitRead(1)) // seq_scaling_list_present_flag
- for(int j = 0, size = i < 6 ? 16 : 64, next = 8; j < size && next != 0; ++j)
- next = (next + gb.SExpGolombRead() + 256) & 255;
- }
-
- gb.UExpGolombRead(); // log2_max_frame_num_minus4
-
- UINT64 pic_order_cnt_type = gb.UExpGolombRead();
-
- if(pic_order_cnt_type == 0)
- {
- gb.UExpGolombRead(); // log2_max_pic_order_cnt_lsb_minus4
- }
- else if(pic_order_cnt_type == 1)
- {
- gb.BitRead(1); // delta_pic_order_always_zero_flag
- gb.SExpGolombRead(); // offset_for_non_ref_pic
- gb.SExpGolombRead(); // offset_for_top_to_bottom_field
- UINT64 num_ref_frames_in_pic_order_cnt_cycle = gb.UExpGolombRead();
- for(int i = 0; i < num_ref_frames_in_pic_order_cnt_cycle; i++)
- gb.SExpGolombRead(); // offset_for_ref_frame[i]
- }
-
- gb.UExpGolombRead(); // num_ref_frames
- gb.BitRead(1); // gaps_in_frame_num_value_allowed_flag
-
- UINT64 pic_width_in_mbs_minus1 = gb.UExpGolombRead();
- UINT64 pic_height_in_map_units_minus1 = gb.UExpGolombRead();
- BYTE frame_mbs_only_flag = (BYTE)gb.BitRead(1);
-
- h.width = (pic_width_in_mbs_minus1 + 1) * 16;
- h.height = (2 - frame_mbs_only_flag) * (pic_height_in_map_units_minus1 + 1) * 16;
-
- if(h.height == 1088) h.height = 1080; // Prevent blur lines
-
- if(!frame_mbs_only_flag)
- gb.BitRead(1); // mb_adaptive_frame_field_flag
- gb.BitRead(1); // direct_8x8_inference_flag
- if(gb.BitRead(1)) // frame_cropping_flag
- {
- gb.UExpGolombRead(); // frame_cropping_rect_left_offset
- gb.UExpGolombRead(); // frame_cropping_rect_right_offset
- gb.UExpGolombRead(); // frame_cropping_rect_top_offset
- gb.UExpGolombRead(); // frame_cropping_rect_bottom_offset
- }
-
- if(gb.BitRead(1)) // vui_parameters_present_flag
- {
- if(gb.BitRead(1)) // aspect_ratio_info_present_flag
- {
- if(255 == (BYTE)gb.BitRead(8)) // aspect_ratio_idc)
- {
- gb.BitRead(16); // sar_width
- gb.BitRead(16); // sar_height
- }
- }
-
- if(gb.BitRead(1)) // overscan_info_present_flag
- {
- gb.BitRead(1); // overscan_appropriate_flag
- }
-
- if(gb.BitRead(1)) // video_signal_type_present_flag
- {
- gb.BitRead(3); // video_format
- gb.BitRead(1); // video_full_range_flag
- if(gb.BitRead(1)) // colour_description_present_flag
- {
- gb.BitRead(8); // colour_primaries
- gb.BitRead(8); // transfer_characteristics
- gb.BitRead(8); // matrix_coefficients
- }
- }
- if(gb.BitRead(1)) // chroma_location_info_present_flag
- {
- gb.UExpGolombRead(); // chroma_sample_loc_type_top_field
- gb.UExpGolombRead(); // chroma_sample_loc_type_bottom_field
- }
- if(gb.BitRead(1)) // timing_info_present_flag
- {
- num_units_in_tick = gb.BitRead(32);
- time_scale = gb.BitRead(32);
- fixed_frame_rate_flag = gb.BitRead(1);
-
- // Trick for weird parameters (10x to Madshi)!
- if((num_units_in_tick < 1000) || (num_units_in_tick > 1001))
- {
- if((time_scale % num_units_in_tick != 0) && ((time_scale * 1001) % num_units_in_tick == 0))
- {
- time_scale = (time_scale * 1001) / num_units_in_tick;
- num_units_in_tick = 1001;
- }
- else
- {
- time_scale = (time_scale * 1000) / num_units_in_tick;
- num_units_in_tick = 1000;
- }
- }
- time_scale = time_scale / 2; // VUI consider fields even for progressive stream : divide by 2!
-
- if(time_scale)
- h.AvgTimePerFrame = (10000000I64 * num_units_in_tick) / time_scale;
- }
- }
-
- Seek(h.spspos + gb.GetPos());
+ BYTE SPSTemp[MAX_SPS];
+ BYTE SPSBuff[MAX_SPS];
+ CGolombBuffer gb (SPSBuff, MAX_SPS);
+ __int64 num_units_in_tick;
+ __int64 time_scale;
+ long fixed_frame_rate_flag;
+
+ h.spspos = pos;
+
+ // Manage H264 escape codes (see "remove escapes (very rare 1:2^22)" in ffmpeg h264.c file)
+ ByteRead((BYTE*)SPSTemp, MAX_SPS);
+ RemoveMpegEscapeCode (SPSBuff, SPSTemp, MAX_SPS);
+
+ h.profile = (BYTE)gb.BitRead(8);
+ gb.BitRead(8);
+ h.level = (BYTE)gb.BitRead(8);
+
+ gb.UExpGolombRead(); // seq_parameter_set_id
+
+ if(h.profile >= 100) // high profile
+ {
+ if(gb.UExpGolombRead() == 3) // chroma_format_idc
+ {
+ gb.BitRead(1); // residue_transform_flag
+ }
+
+ gb.UExpGolombRead(); // bit_depth_luma_minus8
+ gb.UExpGolombRead(); // bit_depth_chroma_minus8
+
+ gb.BitRead(1); // qpprime_y_zero_transform_bypass_flag
+
+ if(gb.BitRead(1)) // seq_scaling_matrix_present_flag
+ for(int i = 0; i < 8; i++)
+ if(gb.BitRead(1)) // seq_scaling_list_present_flag
+ for(int j = 0, size = i < 6 ? 16 : 64, next = 8; j < size && next != 0; ++j)
+ next = (next + gb.SExpGolombRead() + 256) & 255;
+ }
+
+ gb.UExpGolombRead(); // log2_max_frame_num_minus4
+
+ UINT64 pic_order_cnt_type = gb.UExpGolombRead();
+
+ if(pic_order_cnt_type == 0)
+ {
+ gb.UExpGolombRead(); // log2_max_pic_order_cnt_lsb_minus4
+ }
+ else if(pic_order_cnt_type == 1)
+ {
+ gb.BitRead(1); // delta_pic_order_always_zero_flag
+ gb.SExpGolombRead(); // offset_for_non_ref_pic
+ gb.SExpGolombRead(); // offset_for_top_to_bottom_field
+ UINT64 num_ref_frames_in_pic_order_cnt_cycle = gb.UExpGolombRead();
+ for(int i = 0; i < num_ref_frames_in_pic_order_cnt_cycle; i++)
+ gb.SExpGolombRead(); // offset_for_ref_frame[i]
+ }
+
+ gb.UExpGolombRead(); // num_ref_frames
+ gb.BitRead(1); // gaps_in_frame_num_value_allowed_flag
+
+ UINT64 pic_width_in_mbs_minus1 = gb.UExpGolombRead();
+ UINT64 pic_height_in_map_units_minus1 = gb.UExpGolombRead();
+ BYTE frame_mbs_only_flag = (BYTE)gb.BitRead(1);
+
+ h.width = (pic_width_in_mbs_minus1 + 1) * 16;
+ h.height = (2 - frame_mbs_only_flag) * (pic_height_in_map_units_minus1 + 1) * 16;
+
+ if (h.height == 1088) h.height = 1080; // Prevent blur lines
+
+ if (!frame_mbs_only_flag)
+ gb.BitRead(1); // mb_adaptive_frame_field_flag
+ gb.BitRead(1); // direct_8x8_inference_flag
+ if (gb.BitRead(1)) // frame_cropping_flag
+ {
+ gb.UExpGolombRead(); // frame_cropping_rect_left_offset
+ gb.UExpGolombRead(); // frame_cropping_rect_right_offset
+ gb.UExpGolombRead(); // frame_cropping_rect_top_offset
+ gb.UExpGolombRead(); // frame_cropping_rect_bottom_offset
+ }
+
+ if (gb.BitRead(1)) // vui_parameters_present_flag
+ {
+ if (gb.BitRead(1)) // aspect_ratio_info_present_flag
+ {
+ if (255==(BYTE)gb.BitRead(8)) // aspect_ratio_idc)
+ {
+ gb.BitRead(16); // sar_width
+ gb.BitRead(16); // sar_height
+ }
+ }
+
+ if (gb.BitRead(1)) // overscan_info_present_flag
+ {
+ gb.BitRead(1); // overscan_appropriate_flag
+ }
+
+ if (gb.BitRead(1)) // video_signal_type_present_flag
+ {
+ gb.BitRead(3); // video_format
+ gb.BitRead(1); // video_full_range_flag
+ if(gb.BitRead(1)) // colour_description_present_flag
+ {
+ gb.BitRead(8); // colour_primaries
+ gb.BitRead(8); // transfer_characteristics
+ gb.BitRead(8); // matrix_coefficients
+ }
+ }
+ if(gb.BitRead(1)) // chroma_location_info_present_flag
+ {
+ gb.UExpGolombRead(); // chroma_sample_loc_type_top_field
+ gb.UExpGolombRead(); // chroma_sample_loc_type_bottom_field
+ }
+ if (gb.BitRead(1)) // timing_info_present_flag
+ {
+ num_units_in_tick = gb.BitRead(32);
+ time_scale = gb.BitRead(32);
+ fixed_frame_rate_flag = gb.BitRead(1);
+
+ // Trick for weird parameters (10x to Madshi)!
+ if ((num_units_in_tick < 1000) || (num_units_in_tick > 1001))
+ {
+ if ((time_scale % num_units_in_tick != 0) && ((time_scale*1001) % num_units_in_tick == 0))
+ {
+ time_scale = (time_scale * 1001) / num_units_in_tick;
+ num_units_in_tick = 1001;
+ }
+ else
+ {
+ time_scale = (time_scale * 1000) / num_units_in_tick;
+ num_units_in_tick = 1000;
+ }
+ }
+ time_scale = time_scale / 2; // VUI consider fields even for progressive stream : divide by 2!
+
+ if (time_scale)
+ h.AvgTimePerFrame = (10000000I64*num_units_in_tick)/time_scale;
+ }
+ }
+
+ Seek(h.spspos+gb.GetPos());
#else
- __int64 num_units_in_tick;
- __int64 time_scale;
- long fixed_frame_rate_flag;
-
- h.spspos = pos;
-
- h.profile = (BYTE)BitRead(8);
- BitRead(8);
- h.level = (BYTE)BitRead(8);
-
- UExpGolombRead(); // seq_parameter_set_id
-
- if(h.profile >= 100) // high profile
- {
- if(UExpGolombRead() == 3) // chroma_format_idc
- {
- BitRead(1); // residue_transform_flag
- }
-
- UExpGolombRead(); // bit_depth_luma_minus8
- UExpGolombRead(); // bit_depth_chroma_minus8
-
- BitRead(1); // qpprime_y_zero_transform_bypass_flag
-
- if(BitRead(1)) // seq_scaling_matrix_present_flag
- for(int i = 0; i < 8; i++)
- if(BitRead(1)) // seq_scaling_list_present_flag
- for(int j = 0, size = i < 6 ? 16 : 64, next = 8; j < size && next != 0; ++j)
- next = (next + SExpGolombRead() + 256) & 255;
- }
-
- UExpGolombRead(); // log2_max_frame_num_minus4
-
- UINT64 pic_order_cnt_type = UExpGolombRead();
-
- if(pic_order_cnt_type == 0)
- {
- UExpGolombRead(); // log2_max_pic_order_cnt_lsb_minus4
- }
- else if(pic_order_cnt_type == 1)
- {
- BitRead(1); // delta_pic_order_always_zero_flag
- SExpGolombRead(); // offset_for_non_ref_pic
- SExpGolombRead(); // offset_for_top_to_bottom_field
- UINT64 num_ref_frames_in_pic_order_cnt_cycle = UExpGolombRead();
- for(int i = 0; i < num_ref_frames_in_pic_order_cnt_cycle; i++)
- SExpGolombRead(); // offset_for_ref_frame[i]
- }
-
- UExpGolombRead(); // num_ref_frames
- BitRead(1); // gaps_in_frame_num_value_allowed_flag
-
- UINT64 pic_width_in_mbs_minus1 = UExpGolombRead();
- UINT64 pic_height_in_map_units_minus1 = UExpGolombRead();
- BYTE frame_mbs_only_flag = (BYTE)BitRead(1);
-
- h.width = (pic_width_in_mbs_minus1 + 1) * 16;
- h.height = (2 - frame_mbs_only_flag) * (pic_height_in_map_units_minus1 + 1) * 16;
-
- if(h.height == 1088) h.height = 1080; // Prevent blur lines
-
- if(!frame_mbs_only_flag)
- BitRead(1); // mb_adaptive_frame_field_flag
- BitRead(1); // direct_8x8_inference_flag
- if(BitRead(1)) // frame_cropping_flag
- {
- UExpGolombRead(); // frame_cropping_rect_left_offset
- UExpGolombRead(); // frame_cropping_rect_right_offset
- UExpGolombRead(); // frame_cropping_rect_top_offset
- UExpGolombRead(); // frame_cropping_rect_bottom_offset
- }
-
- if(BitRead(1)) // vui_parameters_present_flag
- {
- if(BitRead(1)) // aspect_ratio_info_present_flag
- {
- if(255 == (BYTE)BitRead(8)) // aspect_ratio_idc)
- {
- BitRead(16); // sar_width
- BitRead(16); // sar_height
- }
- }
-
- if(BitRead(1)) // overscan_info_present_flag
- {
- BitRead(1); // overscan_appropriate_flag
- }
-
- if(BitRead(1)) // video_signal_type_present_flag
- {
- BitRead(3); // video_format
- BitRead(1); // video_full_range_flag
- if(BitRead(1)) // colour_description_present_flag
- {
- BitRead(8); // colour_primaries
- BitRead(8); // transfer_characteristics
- BitRead(8); // matrix_coefficients
- }
- }
- if(BitRead(1)) // chroma_location_info_present_flag
- {
- UExpGolombRead(); // chroma_sample_loc_type_top_field
- UExpGolombRead(); // chroma_sample_loc_type_bottom_field
- }
- if(BitRead(1)) // timing_info_present_flag
- {
- num_units_in_tick = BitRead(32);
- time_scale = BitRead(32);
- fixed_frame_rate_flag = BitRead(1);
-
- // Trick for weird parameters (10x to Madshi)!
- if((num_units_in_tick < 1000) || (num_units_in_tick > 1001))
- {
- if((time_scale % num_units_in_tick != 0) && ((time_scale * 1001) % num_units_in_tick == 0))
- {
- time_scale = (time_scale * 1001) / num_units_in_tick;
- num_units_in_tick = 1001;
- }
- else
- {
- time_scale = (time_scale * 1000) / num_units_in_tick;
- num_units_in_tick = 1000;
- }
- }
- time_scale = time_scale / 2; // VUI consider fields even for progressive stream : divide by 2!
-
- if(time_scale)
- h.AvgTimePerFrame = (10000000I64 * num_units_in_tick) / time_scale;
- }
- }
+ __int64 num_units_in_tick;
+ __int64 time_scale;
+ long fixed_frame_rate_flag;
+
+ h.spspos = pos;
+
+ h.profile = (BYTE)BitRead(8);
+ BitRead(8);
+ h.level = (BYTE)BitRead(8);
+
+ UExpGolombRead(); // seq_parameter_set_id
+
+ if(h.profile >= 100) // high profile
+ {
+ if(UExpGolombRead() == 3) // chroma_format_idc
+ {
+ BitRead(1); // residue_transform_flag
+ }
+
+ UExpGolombRead(); // bit_depth_luma_minus8
+ UExpGolombRead(); // bit_depth_chroma_minus8
+
+ BitRead(1); // qpprime_y_zero_transform_bypass_flag
+
+ if(BitRead(1)) // seq_scaling_matrix_present_flag
+ for(int i = 0; i < 8; i++)
+ if(BitRead(1)) // seq_scaling_list_present_flag
+ for(int j = 0, size = i < 6 ? 16 : 64, next = 8; j < size && next != 0; ++j)
+ next = (next + SExpGolombRead() + 256) & 255;
+ }
+
+ UExpGolombRead(); // log2_max_frame_num_minus4
+
+ UINT64 pic_order_cnt_type = UExpGolombRead();
+
+ if(pic_order_cnt_type == 0)
+ {
+ UExpGolombRead(); // log2_max_pic_order_cnt_lsb_minus4
+ }
+ else if(pic_order_cnt_type == 1)
+ {
+ BitRead(1); // delta_pic_order_always_zero_flag
+ SExpGolombRead(); // offset_for_non_ref_pic
+ SExpGolombRead(); // offset_for_top_to_bottom_field
+ UINT64 num_ref_frames_in_pic_order_cnt_cycle = UExpGolombRead();
+ for(int i = 0; i < num_ref_frames_in_pic_order_cnt_cycle; i++)
+ SExpGolombRead(); // offset_for_ref_frame[i]
+ }
+
+ UExpGolombRead(); // num_ref_frames
+ BitRead(1); // gaps_in_frame_num_value_allowed_flag
+
+ UINT64 pic_width_in_mbs_minus1 = UExpGolombRead();
+ UINT64 pic_height_in_map_units_minus1 = UExpGolombRead();
+ BYTE frame_mbs_only_flag = (BYTE)BitRead(1);
+
+ h.width = (pic_width_in_mbs_minus1 + 1) * 16;
+ h.height = (2 - frame_mbs_only_flag) * (pic_height_in_map_units_minus1 + 1) * 16;
+
+ if (h.height == 1088) h.height = 1080; // Prevent blur lines
+
+ if (!frame_mbs_only_flag)
+ BitRead(1); // mb_adaptive_frame_field_flag
+ BitRead(1); // direct_8x8_inference_flag
+ if (BitRead(1)) // frame_cropping_flag
+ {
+ UExpGolombRead(); // frame_cropping_rect_left_offset
+ UExpGolombRead(); // frame_cropping_rect_right_offset
+ UExpGolombRead(); // frame_cropping_rect_top_offset
+ UExpGolombRead(); // frame_cropping_rect_bottom_offset
+ }
+
+ if (BitRead(1)) // vui_parameters_present_flag
+ {
+ if (BitRead(1)) // aspect_ratio_info_present_flag
+ {
+ if (255==(BYTE)BitRead(8)) // aspect_ratio_idc)
+ {
+ BitRead(16); // sar_width
+ BitRead(16); // sar_height
+ }
+ }
+
+ if (BitRead(1)) // overscan_info_present_flag
+ {
+ BitRead(1); // overscan_appropriate_flag
+ }
+
+ if (BitRead(1)) // video_signal_type_present_flag
+ {
+ BitRead(3); // video_format
+ BitRead(1); // video_full_range_flag
+ if(BitRead(1)) // colour_description_present_flag
+ {
+ BitRead(8); // colour_primaries
+ BitRead(8); // transfer_characteristics
+ BitRead(8); // matrix_coefficients
+ }
+ }
+ if(BitRead(1)) // chroma_location_info_present_flag
+ {
+ UExpGolombRead(); // chroma_sample_loc_type_top_field
+ UExpGolombRead(); // chroma_sample_loc_type_bottom_field
+ }
+ if (BitRead(1)) // timing_info_present_flag
+ {
+ num_units_in_tick = BitRead(32);
+ time_scale = BitRead(32);
+ fixed_frame_rate_flag = BitRead(1);
+
+ // Trick for weird parameters (10x to Madshi)!
+ if ((num_units_in_tick < 1000) || (num_units_in_tick > 1001))
+ {
+ if ((time_scale % num_units_in_tick != 0) && ((time_scale*1001) % num_units_in_tick == 0))
+ {
+ time_scale = (time_scale * 1001) / num_units_in_tick;
+ num_units_in_tick = 1001;
+ }
+ else
+ {
+ time_scale = (time_scale * 1000) / num_units_in_tick;
+ num_units_in_tick = 1000;
+ }
+ }
+ time_scale = time_scale / 2; // VUI consider fields even for progressive stream : divide by 2!
+
+ if (time_scale)
+ h.AvgTimePerFrame = (10000000I64*num_units_in_tick)/time_scale;
+ }
+ }
#endif
- }
- else if((id & 0x9f) == 0x08 && (id & 0x60) != 0)
- {
- h.ppspos = pos;
- }
+ }
+ else if((id&0x9f) == 0x08 && (id&0x60) != 0)
+ {
+ h.ppspos = pos;
+ }
- BitByteAlign();
+ BitByteAlign();
- dwStartCode = BitRead(32, true);
- while(GetPos() < endpos + 4 && (dwStartCode != 0x00000001) && (dwStartCode & 0xFFFFFF00) != 0x00000100)
- {
- BitRead(8);
- dwStartCode = BitRead(32, true);
- }
+ dwStartCode = BitRead(32, true);
+ while(GetPos() < endpos+4 && (dwStartCode != 0x00000001) && (dwStartCode & 0xFFFFFF00) != 0x00000100)
+ {
+ BitRead(8);
+ dwStartCode = BitRead(32, true);
+ }
- if(h.spspos != 0 && h.spslen == 0)
- h.spslen = GetPos() - h.spspos;
- else if(h.ppspos != 0 && h.ppslen == 0)
- h.ppslen = GetPos() - h.ppspos;
+ if(h.spspos != 0 && h.spslen == 0)
+ h.spslen = GetPos() - h.spspos;
+ else if(h.ppspos != 0 && h.ppslen == 0)
+ h.ppslen = GetPos() - h.ppspos;
- }
+ }
- if(!h.spspos || !h.spslen || !h.ppspos || !h.ppslen)
- return(false);
+ if(!h.spspos || !h.spslen || !h.ppspos || !h.ppslen)
+ return(false);
- if(!pmt) return(true);
+ if(!pmt) return(true);
- {
- int extra = 2 + h.spslen - 4 + 2 + h.ppslen - 4;
+ {
+ int extra = 2+h.spslen-4 + 2+h.ppslen-4;
- pmt->majortype = MEDIATYPE_Video;
- pmt->subtype = FOURCCMap('1CVA');
+ pmt->majortype = MEDIATYPE_Video;
+ pmt->subtype = FOURCCMap('1CVA');
//pmt->subtype = MEDIASUBTYPE_H264; // TODO : put MEDIASUBTYPE_H264 to support Windows 7 decoder !
- pmt->formattype = FORMAT_MPEG2_VIDEO;
- int len = FIELD_OFFSET(MPEG2VIDEOINFO, dwSequenceHeader) + extra;
- MPEG2VIDEOINFO* vi = (MPEG2VIDEOINFO*)DNew BYTE[len];
- memset(vi, 0, len);
- // vi->hdr.dwBitRate = ;
- vi->hdr.AvgTimePerFrame = h.AvgTimePerFrame;
- vi->hdr.dwPictAspectRatioX = h.width;
- vi->hdr.dwPictAspectRatioY = h.height;
- vi->hdr.bmiHeader.biSize = sizeof(vi->hdr.bmiHeader);
- vi->hdr.bmiHeader.biWidth = h.width;
- vi->hdr.bmiHeader.biHeight = h.height;
- vi->hdr.bmiHeader.biCompression = '1CVA';
- vi->dwProfile = h.profile;
- vi->dwFlags = 4; // ?
- vi->dwLevel = h.level;
- vi->cbSequenceHeader = extra;
- BYTE* p = (BYTE*)&vi->dwSequenceHeader[0];
- *p++ = (h.spslen - 4) >> 8;
- *p++ = (h.spslen - 4) & 0xff;
- Seek(h.spspos + 4);
- ByteRead(p, h.spslen - 4);
- p += h.spslen - 4;
- *p++ = (h.ppslen - 4) >> 8;
- *p++ = (h.ppslen - 4) & 0xff;
- Seek(h.ppspos + 4);
- ByteRead(p, h.ppslen - 4);
- p += h.ppslen - 4;
- pmt->SetFormat((BYTE*)vi, len);
- delete [] vi;
- }
-
- return(true);
+ pmt->formattype = FORMAT_MPEG2_VIDEO;
+ int len = FIELD_OFFSET(MPEG2VIDEOINFO, dwSequenceHeader) + extra;
+ MPEG2VIDEOINFO* vi = (MPEG2VIDEOINFO*)DNew BYTE[len];
+ memset(vi, 0, len);
+ // vi->hdr.dwBitRate = ;
+ vi->hdr.AvgTimePerFrame = h.AvgTimePerFrame;
+ vi->hdr.dwPictAspectRatioX = h.width;
+ vi->hdr.dwPictAspectRatioY = h.height;
+ vi->hdr.bmiHeader.biSize = sizeof(vi->hdr.bmiHeader);
+ vi->hdr.bmiHeader.biWidth = h.width;
+ vi->hdr.bmiHeader.biHeight = h.height;
+ vi->hdr.bmiHeader.biCompression = '1CVA';
+ vi->dwProfile = h.profile;
+ vi->dwFlags = 4; // ?
+ vi->dwLevel = h.level;
+ vi->cbSequenceHeader = extra;
+ BYTE* p = (BYTE*)&vi->dwSequenceHeader[0];
+ *p++ = (h.spslen-4) >> 8;
+ *p++ = (h.spslen-4) & 0xff;
+ Seek(h.spspos+4);
+ ByteRead(p, h.spslen-4);
+ p += h.spslen-4;
+ *p++ = (h.ppslen-4) >> 8;
+ *p++ = (h.ppslen-4) & 0xff;
+ Seek(h.ppspos+4);
+ ByteRead(p, h.ppslen-4);
+ p += h.ppslen-4;
+ pmt->SetFormat((BYTE*)vi, len);
+ delete [] vi;
+ }
+
+ return(true);
}
bool CBaseSplitterFileEx::Read(vc1hdr& h, int len, CMediaType* pmt)
{
- __int64 endpos = GetPos() + len; // - sequence header length
- __int64 extrapos = 0, extralen = 0;
- int nFrameRateNum = 0, nFrameRateDen = 1;
-
- if(GetPos() < endpos + 4 && BitRead(32, true) == 0x0000010F)
- {
- extrapos = GetPos();
-
- BitRead(32);
-
- h.profile = BitRead(2);
-
- // Check if advanced profile
- if(h.profile != 3) return(false);
-
- h.level = BitRead(3);
- h.chromaformat = BitRead(2);
-
- // (fps-2)/4 (->30)
- h.frmrtq_postproc = BitRead(3); //common
- // (bitrate-32kbps)/64kbps
- h.bitrtq_postproc = BitRead(5); //common
- h.postprocflag = BitRead(1); //common
-
- h.width = (BitRead(12) + 1) << 1;
- h.height = (BitRead(12) + 1) << 1;
-
- h.broadcast = BitRead(1);
- h.interlace = BitRead(1);
- h.tfcntrflag = BitRead(1);
- h.finterpflag = BitRead(1);
- BitRead(1); // reserved
- h.psf = BitRead(1);
- if(BitRead(1))
- {
- int ar = 0;
- h.ArX = BitRead(14) + 1;
- h.ArY = BitRead(14) + 1;
- if(BitRead(1))
- ar = BitRead(4);
- // TODO : next is not the true A/R!
- if(ar && ar < 14)
- {
+ __int64 endpos = GetPos() + len; // - sequence header length
+ __int64 extrapos = 0, extralen = 0;
+ int nFrameRateNum = 0, nFrameRateDen = 1;
+
+ if (GetPos() < endpos+4 && BitRead(32, true) == 0x0000010F)
+ {
+ extrapos = GetPos();
+
+ BitRead(32);
+
+ h.profile = BitRead(2);
+
+ // Check if advanced profile
+ if (h.profile != 3) return(false);
+
+ h.level = BitRead (3);
+ h.chromaformat = BitRead (2);
+
+ // (fps-2)/4 (->30)
+ h.frmrtq_postproc = BitRead (3); //common
+ // (bitrate-32kbps)/64kbps
+ h.bitrtq_postproc = BitRead (5); //common
+ h.postprocflag = BitRead (1); //common
+
+ h.width = (BitRead (12) + 1) << 1;
+ h.height = (BitRead (12) + 1) << 1;
+
+ h.broadcast = BitRead (1);
+ h.interlace = BitRead (1);
+ h.tfcntrflag = BitRead (1);
+ h.finterpflag = BitRead (1);
+ BitRead (1); // reserved
+ h.psf = BitRead (1);
+ if(BitRead (1))
+ {
+ int ar = 0;
+ h.ArX = BitRead (14) + 1;
+ h.ArY = BitRead (14) + 1;
+ if(BitRead (1))
+ ar = BitRead (4);
+ // TODO : next is not the true A/R!
+ if(ar && ar < 14)
+ {
// h.ArX = ff_vc1_pixel_aspect[ar].num;
// h.ArY = ff_vc1_pixel_aspect[ar].den;
- }
- else if(ar == 15)
- {
- /*h.ArX =*/ BitRead(8);
- /*h.ArY =*/
- BitRead(8);
- }
-
- // Read framerate
- const int ff_vc1_fps_nr[5] = { 24, 25, 30, 50, 60 },
- ff_vc1_fps_dr[2] = { 1000, 1001 };
-
- if(BitRead(1))
- {
- if(BitRead(1))
- {
- nFrameRateNum = 32;
- nFrameRateDen = BitRead(16) + 1;
- }
- else
- {
- int nr, dr;
- nr = BitRead(8);
- dr = BitRead(4);
- if(nr && nr < 8 && dr && dr < 3)
- {
- nFrameRateNum = ff_vc1_fps_dr[dr - 1];
- nFrameRateDen = ff_vc1_fps_nr[nr - 1] * 1000;
- }
- }
- }
-
- }
-
- Seek(extrapos + 4);
- extralen = 0;
- long parse = 0;
-
- while(GetPos() < endpos + 4 && ((parse == 0x0000010E) || (parse & 0xFFFFFF00) != 0x00000100))
- {
- parse = (parse << 8) | BitRead(8);
- extralen++;
- }
- }
-
- if(!extrapos || !extralen)
- return(false);
-
- if(!pmt) return(true);
-
- {
- //pmt->majortype = MEDIATYPE_Video;
- //pmt->subtype = FOURCCMap('1CVW');
- //pmt->formattype = FORMAT_MPEG2_VIDEO;
- //int len = FIELD_OFFSET(MPEG2VIDEOINFO, dwSequenceHeader) + extralen + 1;
- //MPEG2VIDEOINFO* vi = (MPEG2VIDEOINFO*)DNew BYTE[len];
- //memset(vi, 0, len);
- //// vi->hdr.dwBitRate = ;
- //vi->hdr.AvgTimePerFrame = (10000000I64*nFrameRateNum)/nFrameRateDen;
- //vi->hdr.dwPictAspectRatioX = h.width;
- //vi->hdr.dwPictAspectRatioY = h.height;
- //vi->hdr.bmiHeader.biSize = sizeof(vi->hdr.bmiHeader);
- //vi->hdr.bmiHeader.biWidth = h.width;
- //vi->hdr.bmiHeader.biHeight = h.height;
- //vi->hdr.bmiHeader.biCompression = '1CVW';
- //vi->dwProfile = h.profile;
- //vi->dwFlags = 4; // ?
- //vi->dwLevel = h.level;
- //vi->cbSequenceHeader = extralen+1;
- //BYTE* p = (BYTE*)&vi->dwSequenceHeader[0];
- //*p++ = 0;
- //Seek(extrapos);
- //ByteRead(p, extralen);
- //pmt->SetFormat((BYTE*)vi, len);
- //delete [] vi;
-
- pmt->majortype = MEDIATYPE_Video;
- pmt->subtype = FOURCCMap('1CVW');
- pmt->formattype = FORMAT_VIDEOINFO2;
- int len = sizeof(VIDEOINFOHEADER2) + extralen + 1;
- VIDEOINFOHEADER2* vi = (VIDEOINFOHEADER2*)DNew BYTE[len];
- memset(vi, 0, len);
- vi->AvgTimePerFrame = (10000000I64 * nFrameRateNum) / nFrameRateDen;
- vi->dwPictAspectRatioX = h.width;
- vi->dwPictAspectRatioY = h.height;
- vi->bmiHeader.biSize = sizeof(vi->bmiHeader);
- vi->bmiHeader.biWidth = h.width;
- vi->bmiHeader.biHeight = h.height;
- vi->bmiHeader.biCompression = '1CVW';
- BYTE* p = (BYTE*)vi + sizeof(VIDEOINFOHEADER2);
- *p++ = 0;
- Seek(extrapos);
- ByteRead(p, extralen);
- pmt->SetFormat((BYTE*)vi, len);
- delete [] vi;
- }
-
- return(true);
+ }
+ else if(ar == 15)
+ {
+ /*h.ArX =*/ BitRead (8);
+ /*h.ArY =*/ BitRead (8);
+ }
+
+ // Read framerate
+ const int ff_vc1_fps_nr[5] = { 24, 25, 30, 50, 60 },
+ ff_vc1_fps_dr[2] = { 1000, 1001 };
+
+ if(BitRead (1))
+ {
+ if(BitRead (1))
+ {
+ nFrameRateNum = 32;
+ nFrameRateDen = BitRead (16) + 1;
+ } else {
+ int nr, dr;
+ nr = BitRead (8);
+ dr = BitRead (4);
+ if(nr && nr < 8 && dr && dr < 3)
+ {
+ nFrameRateNum = ff_vc1_fps_dr[dr - 1];
+ nFrameRateDen = ff_vc1_fps_nr[nr - 1] * 1000;
+ }
+ }
+ }
+
+ }
+
+ Seek(extrapos+4);
+ extralen = 0;
+ long parse = 0;
+
+ while (GetPos() < endpos+4 && ((parse == 0x0000010E) || (parse & 0xFFFFFF00) != 0x00000100))
+ {
+ parse = (parse<<8) | BitRead(8);
+ extralen++;
+ }
+ }
+
+ if(!extrapos || !extralen)
+ return(false);
+
+ if(!pmt) return(true);
+
+ {
+ //pmt->majortype = MEDIATYPE_Video;
+ //pmt->subtype = FOURCCMap('1CVW');
+ //pmt->formattype = FORMAT_MPEG2_VIDEO;
+ //int len = FIELD_OFFSET(MPEG2VIDEOINFO, dwSequenceHeader) + extralen + 1;
+ //MPEG2VIDEOINFO* vi = (MPEG2VIDEOINFO*)DNew BYTE[len];
+ //memset(vi, 0, len);
+ //// vi->hdr.dwBitRate = ;
+ //vi->hdr.AvgTimePerFrame = (10000000I64*nFrameRateNum)/nFrameRateDen;
+ //vi->hdr.dwPictAspectRatioX = h.width;
+ //vi->hdr.dwPictAspectRatioY = h.height;
+ //vi->hdr.bmiHeader.biSize = sizeof(vi->hdr.bmiHeader);
+ //vi->hdr.bmiHeader.biWidth = h.width;
+ //vi->hdr.bmiHeader.biHeight = h.height;
+ //vi->hdr.bmiHeader.biCompression = '1CVW';
+ //vi->dwProfile = h.profile;
+ //vi->dwFlags = 4; // ?
+ //vi->dwLevel = h.level;
+ //vi->cbSequenceHeader = extralen+1;
+ //BYTE* p = (BYTE*)&vi->dwSequenceHeader[0];
+ //*p++ = 0;
+ //Seek(extrapos);
+ //ByteRead(p, extralen);
+ //pmt->SetFormat((BYTE*)vi, len);
+ //delete [] vi;
+
+ pmt->majortype = MEDIATYPE_Video;
+ pmt->subtype = FOURCCMap('1CVW');
+ pmt->formattype = FORMAT_VIDEOINFO2;
+ int len = sizeof(VIDEOINFOHEADER2) + extralen + 1;
+ VIDEOINFOHEADER2* vi = (VIDEOINFOHEADER2*)DNew BYTE[len];
+ memset(vi, 0, len);
+ vi->AvgTimePerFrame = (10000000I64*nFrameRateNum)/nFrameRateDen;
+ vi->dwPictAspectRatioX = h.width;
+ vi->dwPictAspectRatioY = h.height;
+ vi->bmiHeader.biSize = sizeof(vi->bmiHeader);
+ vi->bmiHeader.biWidth = h.width;
+ vi->bmiHeader.biHeight = h.height;
+ vi->bmiHeader.biCompression = '1CVW';
+ BYTE* p = (BYTE*)vi + sizeof(VIDEOINFOHEADER2);
+ *p++ = 0;
+ Seek(extrapos);
+ ByteRead(p, extralen);
+ pmt->SetFormat((BYTE*)vi, len);
+ delete [] vi;
+ }
+
+ return(true);
}
bool CBaseSplitterFileEx::Read(dvbsub& h, int len, CMediaType* pmt)
{
- __int64 endpos = GetPos() + len; // - sequence header length
- __int64 extrapos = 0, extralen = 0;
- int nFrameRateNum = 0, nFrameRateDen = 1;
+ __int64 endpos = GetPos() + len; // - sequence header length
+ __int64 extrapos = 0, extralen = 0;
+ int nFrameRateNum = 0, nFrameRateDen = 1;
- if((BitRead(32, true) & 0xFFFFFF00) == 0x20000f00)
- {
- static const SUBTITLEINFO SubFormat = { 0, "", L"" };
+ if ((BitRead(32, true) & 0xFFFFFF00) == 0x20000f00)
+ {
+ static const SUBTITLEINFO SubFormat = { 0, "", L"" };
- pmt->majortype = MEDIATYPE_Subtitle;
- pmt->subtype = MEDIASUBTYPE_DVB_SUBTITLES;
- pmt->formattype = FORMAT_None;
- pmt->SetFormat((BYTE*)&SubFormat, sizeof(SUBTITLEINFO));
+ pmt->majortype = MEDIATYPE_Subtitle;
+ pmt->subtype = MEDIASUBTYPE_DVB_SUBTITLES;
+ pmt->formattype = FORMAT_None;
+ pmt->SetFormat ((BYTE*)&SubFormat, sizeof(SUBTITLEINFO));
- return true;
- }
+ return true;
+ }
- return false;
+ return false;
}
/*
diff --git a/src/filters/parser/BaseSplitter/BaseSplitterFileEx.h b/src/filters/parser/BaseSplitter/BaseSplitterFileEx.h
index 7cb0ae0d6..72f604c85 100644
--- a/src/filters/parser/BaseSplitter/BaseSplitterFileEx.h
+++ b/src/filters/parser/BaseSplitter/BaseSplitterFileEx.h
@@ -1,4 +1,4 @@
-/*
+/*
* Copyright (C) 2003-2006 Gabest
* http://www.gabest.org
*
@@ -6,15 +6,15 @@
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2, or (at your option)
* any later version.
- *
+ *
* This Program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with GNU Make; see the file COPYING. If not, write to
- * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
+ * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
* http://www.gnu.org/copyleft/gpl.html
*
*/
@@ -25,363 +25,360 @@
class CBaseSplitterFileEx : public CBaseSplitterFile
{
- int m_tslen; // transport stream packet length (188 or 192 bytes, auto-detected)
+ int m_tslen; // transport stream packet length (188 or 192 bytes, auto-detected)
protected :
- REFERENCE_TIME m_rtPTSOffset;
+ REFERENCE_TIME m_rtPTSOffset;
public:
- CBaseSplitterFileEx(IAsyncReader* pReader, HRESULT& hr, int cachelen = DEFAULT_CACHE_LENGTH, bool fRandomAccess = true, bool fStreaming = false);
- virtual ~CBaseSplitterFileEx();
+ CBaseSplitterFileEx(IAsyncReader* pReader, HRESULT& hr, int cachelen = DEFAULT_CACHE_LENGTH, bool fRandomAccess = true, bool fStreaming = false);
+ virtual ~CBaseSplitterFileEx();
- // using CBaseSplitterFile::Read;
+ // using CBaseSplitterFile::Read;
- bool NextMpegStartCode(BYTE& b, __int64 len = 65536);
+ bool NextMpegStartCode(BYTE& b, __int64 len = 65536);
#pragma pack(push, 1)
- enum mpeg_t {mpegunk, mpeg1, mpeg2};
-
- struct pshdr
- {
- mpeg_t type;
- UINT64 scr, bitrate;
- };
-
- struct pssyshdr
- {
- DWORD rate_bound;
- BYTE video_bound, audio_bound;
- bool fixed_rate, csps;
- bool sys_video_loc_flag, sys_audio_loc_flag;
- };
-
- struct peshdr
- {
- WORD len;
-
- BYTE type: 2, fpts: 1, fdts: 1;
- REFERENCE_TIME pts, dts;
-
- // mpeg1 stuff
- UINT64 std_buff_size;
-
- // mpeg2 stuff
- BYTE scrambling: 2, priority: 1, alignment: 1, copyright: 1, original: 1;
- BYTE escr: 1, esrate: 1, dsmtrickmode: 1, morecopyright: 1, crc: 1, extension: 1;
- BYTE hdrlen;
-
- struct peshdr()
- {
- memset(this, 0, sizeof(*this));
- }
- };
-
- class seqhdr
- {
- public:
- WORD width;
- WORD height;
- BYTE ar: 4;
- DWORD ifps;
- DWORD bitrate;
- DWORD vbv;
- BYTE constrained: 1;
- BYTE fiqm: 1;
- BYTE iqm[64];
- BYTE fniqm: 1;
- BYTE niqm[64];
- // ext
- BYTE startcodeid: 4;
- BYTE profile_levelescape: 1;
- BYTE profile: 3;
- BYTE level: 4;
- BYTE progressive: 1;
- BYTE chroma: 2;
- BYTE lowdelay: 1;
- // misc
- int arx, ary;
- };
-
- class mpahdr
- {
- public:
- WORD sync: 11;
- WORD version: 2;
- WORD layer: 2;
- WORD crc: 1;
- WORD bitrate: 4;
- WORD freq: 2;
- WORD padding: 1;
- WORD privatebit: 1;
- WORD channels: 2;
- WORD modeext: 2;
- WORD copyright: 1;
- WORD original: 1;
- WORD emphasis: 2;
-
- int nSamplesPerSec, FrameSize, nBytesPerSec;
- REFERENCE_TIME rtDuration;
- };
-
- class aachdr
- {
- public:
- WORD sync: 12;
- WORD version: 1;
- WORD layer: 2;
- WORD fcrc: 1;
- WORD profile: 2;
- WORD freq: 4;
- WORD privatebit: 1;
- WORD channels: 3;
- WORD original: 1;
- WORD home: 1; // ?
-
- WORD copyright_id_bit: 1;
- WORD copyright_id_start: 1;
- WORD aac_frame_length: 13;
- WORD adts_buffer_fullness: 11;
- WORD no_raw_data_blocks_in_frame: 2;
-
- WORD crc;
-
- int FrameSize, nBytesPerSec;
- REFERENCE_TIME rtDuration;
- };
-
- class ac3hdr
- {
- public:
- WORD sync;
- WORD crc1;
- BYTE fscod: 2;
- BYTE frmsizecod: 6;
- BYTE bsid: 5;
- BYTE bsmod: 3;
- BYTE acmod: 3;
- BYTE cmixlev: 2;
- BYTE surmixlev: 2;
- BYTE dsurmod: 2;
- BYTE lfeon: 1;
- // the rest is unimportant for us
- };
-
- class dtshdr
- {
- public:
- DWORD sync;
- BYTE frametype: 1;
- BYTE deficitsamplecount: 5;
- BYTE fcrc: 1;
- BYTE nblocks: 7;
- WORD framebytes;
- BYTE amode: 6;
- BYTE sfreq: 4;
- BYTE rate: 5;
-
- BYTE downmix: 1;
- BYTE dynrange: 1;
- BYTE timestamp: 1;
- BYTE aux_data: 1;
- BYTE hdcd: 1;
- BYTE ext_descr: 3;
- BYTE ext_coding: 1;
- BYTE aspf: 1;
- BYTE lfe: 2;
- BYTE predictor_history: 1;
-
- };
-
- class lpcmhdr
- {
- public:
- BYTE emphasis: 1;
- BYTE mute: 1;
- BYTE reserved1: 1;
- BYTE framenum: 5;
- BYTE quantwordlen: 2;
- BYTE freq: 2; // 48, 96, 44.1, 32
- BYTE reserved2: 1;
- BYTE channels: 3; // +1
- BYTE drc; // 0x80: off
- };
-
- class hdmvlpcmhdr
- {
- public:
- WORD size;
- BYTE channels: 4;
- BYTE samplerate: 4;
- BYTE bitpersample: 2;
- };
-
- class dvdspuhdr
- {
- public:
- // nothing ;)
- };
-
- class hdmvsubhdr
- {
- public:
- // nothing ;)
- };
-
- class svcdspuhdr
- {
- public:
- // nothing ;)
- };
-
- class cvdspuhdr
- {
- public:
- // nothing ;)
- };
-
- class ps2audhdr
- {
- public:
- // 'SShd' + len (0x18)
- DWORD unk1;
- DWORD freq;
- DWORD channels;
- DWORD interleave; // bytes per channel
- // padding: FF .. FF
- // 'SSbd' + len
- // pcm or adpcm data
- };
-
- class ps2subhdr
- {
- public:
- // nothing ;)
- };
-
- struct trhdr
- {
- BYTE sync; // 0x47
- BYTE error: 1;
- BYTE payloadstart: 1;
- BYTE transportpriority: 1;
- WORD pid: 13;
- BYTE scrambling: 2;
- BYTE adapfield: 1;
- BYTE payload: 1;
- BYTE counter: 4;
- // if adapfield set
- BYTE length;
- BYTE discontinuity: 1;
- BYTE randomaccess: 1;
- BYTE priority: 1;
- BYTE fPCR: 1;
- BYTE OPCR: 1;
- BYTE splicingpoint: 1;
- BYTE privatedata: 1;
- BYTE extension: 1;
- // TODO: add more fields here when the flags above are set (they aren't very interesting...)
- __int64 PCR;
-
- int bytes;
- __int64 next;
- };
-
- struct trsechdr
- {
- BYTE table_id;
- WORD section_syntax_indicator: 1;
- WORD zero: 1;
- WORD reserved1: 2;
- WORD section_length: 12;
- WORD transport_stream_id;
- BYTE reserved2: 2;
- BYTE version_number: 5;
- BYTE current_next_indicator: 1;
- BYTE section_number;
- BYTE last_section_number;
- };
-
- // http://www.technotrend.de/download/av_format_v1.pdf
-
- struct pvahdr
- {
- WORD sync; // 'VA'
- BYTE streamid; // 1 - video, 2 - audio
- BYTE counter;
- BYTE res1; // 0x55
- BYTE res2: 3;
- BYTE fpts: 1;
- BYTE postbytes: 2;
- BYTE prebytes: 2;
- WORD length;
- REFERENCE_TIME pts;
- };
-
- struct avchdr
- {
- BYTE profile, level;
- unsigned int width, height;
- __int64 spspos, spslen;
- __int64 ppspos, ppslen;
- __int64 AvgTimePerFrame;
-
- avchdr()
- {
- spspos = 0;
- spslen = 0;
- ppspos = 0;
- ppslen = 0;
- AvgTimePerFrame = 0;
- }
- };
-
- struct vc1hdr
- {
- BYTE profile;
- BYTE level;
- BYTE chromaformat;
- BYTE frmrtq_postproc;
- BYTE bitrtq_postproc;
- BYTE postprocflag;
- BYTE broadcast;
- BYTE interlace;
- BYTE tfcntrflag;
- BYTE finterpflag;
- BYTE psf;
- UINT ArX;
- UINT ArY;
- unsigned int width, height;
- };
-
- struct dvbsub
- {
- };
+ enum mpeg_t {mpegunk, mpeg1, mpeg2};
+
+ struct pshdr
+ {
+ mpeg_t type;
+ UINT64 scr, bitrate;
+ };
+
+ struct pssyshdr
+ {
+ DWORD rate_bound;
+ BYTE video_bound, audio_bound;
+ bool fixed_rate, csps;
+ bool sys_video_loc_flag, sys_audio_loc_flag;
+ };
+
+ struct peshdr
+ {
+ WORD len;
+
+ BYTE type:2, fpts:1, fdts:1;
+ REFERENCE_TIME pts, dts;
+
+ // mpeg1 stuff
+ UINT64 std_buff_size;
+
+ // mpeg2 stuff
+ BYTE scrambling:2, priority:1, alignment:1, copyright:1, original:1;
+ BYTE escr:1, esrate:1, dsmtrickmode:1, morecopyright:1, crc:1, extension:1;
+ BYTE hdrlen;
+
+ struct peshdr() {memset(this, 0, sizeof(*this));}
+ };
+
+ class seqhdr
+ {
+ public:
+ WORD width;
+ WORD height;
+ BYTE ar:4;
+ DWORD ifps;
+ DWORD bitrate;
+ DWORD vbv;
+ BYTE constrained:1;
+ BYTE fiqm:1;
+ BYTE iqm[64];
+ BYTE fniqm:1;
+ BYTE niqm[64];
+ // ext
+ BYTE startcodeid:4;
+ BYTE profile_levelescape:1;
+ BYTE profile:3;
+ BYTE level:4;
+ BYTE progressive:1;
+ BYTE chroma:2;
+ BYTE lowdelay:1;
+ // misc
+ int arx, ary;
+ };
+
+ class mpahdr
+ {
+ public:
+ WORD sync:11;
+ WORD version:2;
+ WORD layer:2;
+ WORD crc:1;
+ WORD bitrate:4;
+ WORD freq:2;
+ WORD padding:1;
+ WORD privatebit:1;
+ WORD channels:2;
+ WORD modeext:2;
+ WORD copyright:1;
+ WORD original:1;
+ WORD emphasis:2;
+
+ int nSamplesPerSec, FrameSize, nBytesPerSec;
+ REFERENCE_TIME rtDuration;
+ };
+
+ class aachdr
+ {
+ public:
+ WORD sync:12;
+ WORD version:1;
+ WORD layer:2;
+ WORD fcrc:1;
+ WORD profile:2;
+ WORD freq:4;
+ WORD privatebit:1;
+ WORD channels:3;
+ WORD original:1;
+ WORD home:1; // ?
+
+ WORD copyright_id_bit:1;
+ WORD copyright_id_start:1;
+ WORD aac_frame_length:13;
+ WORD adts_buffer_fullness:11;
+ WORD no_raw_data_blocks_in_frame:2;
+
+ WORD crc;
+
+ int FrameSize, nBytesPerSec;
+ REFERENCE_TIME rtDuration;
+ };
+
+ class ac3hdr
+ {
+ public:
+ WORD sync;
+ WORD crc1;
+ BYTE fscod:2;
+ BYTE frmsizecod:6;
+ BYTE bsid:5;
+ BYTE bsmod:3;
+ BYTE acmod:3;
+ BYTE cmixlev:2;
+ BYTE surmixlev:2;
+ BYTE dsurmod:2;
+ BYTE lfeon:1;
+ // the rest is unimportant for us
+ };
+
+ class dtshdr
+ {
+ public:
+ DWORD sync;
+ BYTE frametype:1;
+ BYTE deficitsamplecount:5;
+ BYTE fcrc:1;
+ BYTE nblocks:7;
+ WORD framebytes;
+ BYTE amode:6;
+ BYTE sfreq:4;
+ BYTE rate:5;
+
+ BYTE downmix:1;
+ BYTE dynrange:1;
+ BYTE timestamp:1;
+ BYTE aux_data:1;
+ BYTE hdcd:1;
+ BYTE ext_descr:3;
+ BYTE ext_coding:1;
+ BYTE aspf:1;
+ BYTE lfe:2;
+ BYTE predictor_history:1;
+
+ };
+
+ class lpcmhdr
+ {
+ public:
+ BYTE emphasis:1;
+ BYTE mute:1;
+ BYTE reserved1:1;
+ BYTE framenum:5;
+ BYTE quantwordlen:2;
+ BYTE freq:2; // 48, 96, 44.1, 32
+ BYTE reserved2:1;
+ BYTE channels:3; // +1
+ BYTE drc; // 0x80: off
+ };
+
+ class hdmvlpcmhdr
+ {
+ public:
+ WORD size;
+ BYTE channels:4;
+ BYTE samplerate:4;
+ BYTE bitpersample:2;
+ };
+
+ class dvdspuhdr
+ {
+ public:
+ // nothing ;)
+ };
+
+ class hdmvsubhdr
+ {
+ public:
+ // nothing ;)
+ };
+
+ class svcdspuhdr
+ {
+ public:
+ // nothing ;)
+ };
+
+ class cvdspuhdr
+ {
+ public:
+ // nothing ;)
+ };
+
+ class ps2audhdr
+ {
+ public:
+ // 'SShd' + len (0x18)
+ DWORD unk1;
+ DWORD freq;
+ DWORD channels;
+ DWORD interleave; // bytes per channel
+ // padding: FF .. FF
+ // 'SSbd' + len
+ // pcm or adpcm data
+ };
+
+ class ps2subhdr
+ {
+ public:
+ // nothing ;)
+ };
+
+ struct trhdr
+ {
+ BYTE sync; // 0x47
+ BYTE error:1;
+ BYTE payloadstart:1;
+ BYTE transportpriority:1;
+ WORD pid:13;
+ BYTE scrambling:2;
+ BYTE adapfield:1;
+ BYTE payload:1;
+ BYTE counter:4;
+ // if adapfield set
+ BYTE length;
+ BYTE discontinuity:1;
+ BYTE randomaccess:1;
+ BYTE priority:1;
+ BYTE fPCR:1;
+ BYTE OPCR:1;
+ BYTE splicingpoint:1;
+ BYTE privatedata:1;
+ BYTE extension:1;
+ // TODO: add more fields here when the flags above are set (they aren't very interesting...)
+ __int64 PCR;
+
+ int bytes;
+ __int64 next;
+ };
+
+ struct trsechdr
+ {
+ BYTE table_id;
+ WORD section_syntax_indicator:1;
+ WORD zero:1;
+ WORD reserved1:2;
+ WORD section_length:12;
+ WORD transport_stream_id;
+ BYTE reserved2:2;
+ BYTE version_number:5;
+ BYTE current_next_indicator:1;
+ BYTE section_number;
+ BYTE last_section_number;
+ };
+
+ // http://www.technotrend.de/download/av_format_v1.pdf
+
+ struct pvahdr
+ {
+ WORD sync; // 'VA'
+ BYTE streamid; // 1 - video, 2 - audio
+ BYTE counter;
+ BYTE res1; // 0x55
+ BYTE res2:3;
+ BYTE fpts:1;
+ BYTE postbytes:2;
+ BYTE prebytes:2;
+ WORD length;
+ REFERENCE_TIME pts;
+ };
+
+ struct avchdr
+ {
+ BYTE profile, level;
+ unsigned int width, height;
+ __int64 spspos, spslen;
+ __int64 ppspos, ppslen;
+ __int64 AvgTimePerFrame;
+
+ avchdr()
+ {
+ spspos = 0;
+ spslen = 0;
+ ppspos = 0;
+ ppslen = 0;
+ AvgTimePerFrame = 0;
+ }
+ };
+
+ struct vc1hdr
+ {
+ BYTE profile;
+ BYTE level;
+ BYTE chromaformat;
+ BYTE frmrtq_postproc;
+ BYTE bitrtq_postproc;
+ BYTE postprocflag;
+ BYTE broadcast;
+ BYTE interlace;
+ BYTE tfcntrflag;
+ BYTE finterpflag;
+ BYTE psf;
+ UINT ArX;
+ UINT ArY;
+ unsigned int width, height;
+ };
+
+ struct dvbsub
+ {
+ };
#pragma pack(pop)
- bool Read(pshdr& h);
- bool Read(pssyshdr& h);
- bool Read(peshdr& h, BYTE code);
- bool Read(seqhdr& h, int len, CMediaType* pmt = NULL);
- bool Read(mpahdr& h, int len, bool fAllowV25, CMediaType* pmt = NULL);
- bool Read(aachdr& h, int len, CMediaType* pmt = NULL);
- bool Read(ac3hdr& h, int len, CMediaType* pmt = NULL);
- bool Read(dtshdr& h, int len, CMediaType* pmt = NULL);
- bool Read(lpcmhdr& h, CMediaType* pmt = NULL);
- bool Read(hdmvlpcmhdr& h, CMediaType* pmt = NULL);
- bool Read(dvdspuhdr& h, CMediaType* pmt = NULL);
- bool Read(hdmvsubhdr& h, CMediaType* pmt = NULL, const char* language_code = NULL);
- bool Read(svcdspuhdr& h, CMediaType* pmt = NULL);
- bool Read(cvdspuhdr& h, CMediaType* pmt = NULL);
- bool Read(ps2audhdr& h, CMediaType* pmt = NULL);
- bool Read(ps2subhdr& h, CMediaType* pmt = NULL);
- bool Read(trhdr& h, bool fSync = true);
- bool Read(trsechdr& h);
- bool Read(pvahdr& h, bool fSync = true);
- bool Read(avchdr& h, int len, CMediaType* pmt = NULL);
- bool Read(vc1hdr& h, int len, CMediaType* pmt = NULL);
- bool Read(dvbsub& h, int len, CMediaType* pmt = NULL);
-
- void RemoveMpegEscapeCode(BYTE* dst, BYTE* src, int length);
+ bool Read(pshdr& h);
+ bool Read(pssyshdr& h);
+ bool Read(peshdr& h, BYTE code);
+ bool Read(seqhdr& h, int len, CMediaType* pmt = NULL);
+ bool Read(mpahdr& h, int len, bool fAllowV25, CMediaType* pmt = NULL);
+ bool Read(aachdr& h, int len, CMediaType* pmt = NULL);
+ bool Read(ac3hdr& h, int len, CMediaType* pmt = NULL);
+ bool Read(dtshdr& h, int len, CMediaType* pmt = NULL);
+ bool Read(lpcmhdr& h, CMediaType* pmt = NULL);
+ bool Read(hdmvlpcmhdr& h, CMediaType* pmt = NULL);
+ bool Read(dvdspuhdr& h, CMediaType* pmt = NULL);
+ bool Read(hdmvsubhdr& h, CMediaType* pmt = NULL, const char* language_code = NULL);
+ bool Read(svcdspuhdr& h, CMediaType* pmt = NULL);
+ bool Read(cvdspuhdr& h, CMediaType* pmt = NULL);
+ bool Read(ps2audhdr& h, CMediaType* pmt = NULL);
+ bool Read(ps2subhdr& h, CMediaType* pmt = NULL);
+ bool Read(trhdr& h, bool fSync = true);
+ bool Read(trsechdr& h);
+ bool Read(pvahdr& h, bool fSync = true);
+ bool Read(avchdr& h, int len, CMediaType* pmt = NULL);
+ bool Read(vc1hdr& h, int len, CMediaType* pmt = NULL);
+ bool Read(dvbsub& h, int len, CMediaType* pmt = NULL);
+
+ void RemoveMpegEscapeCode(BYTE* dst, BYTE* src, int length);
};
diff --git a/src/filters/parser/BaseSplitter/MultiFiles.cpp b/src/filters/parser/BaseSplitter/MultiFiles.cpp
index 0e1443d89..c40610d85 100644
--- a/src/filters/parser/BaseSplitter/MultiFiles.cpp
+++ b/src/filters/parser/BaseSplitter/MultiFiles.cpp
@@ -28,182 +28,181 @@
IMPLEMENT_DYNAMIC(CMultiFiles, CObject)
CMultiFiles::CMultiFiles()
- : m_hFile(INVALID_HANDLE_VALUE)
- , m_llTotalLength(0)
- , m_nCurPart(-1)
- , m_pCurrentPTSOffset(NULL)
+ : m_hFile(INVALID_HANDLE_VALUE)
+ , m_llTotalLength(0)
+ , m_nCurPart(-1)
+ , m_pCurrentPTSOffset(NULL)
{
}
void CMultiFiles::Reset()
{
- m_strFiles.RemoveAll();
- m_FilesSize.RemoveAll();
- m_rtPtsOffsets.RemoveAll();
- m_llTotalLength = 0;
+ m_strFiles.RemoveAll();
+ m_FilesSize.RemoveAll();
+ m_rtPtsOffsets.RemoveAll();
+ m_llTotalLength = 0;
}
BOOL CMultiFiles::Open(LPCTSTR lpszFileName, UINT nOpenFlags)
{
- Reset();
- m_strFiles.Add(lpszFileName);
+ Reset();
+ m_strFiles.Add (lpszFileName);
- return OpenPart(0);
+ return OpenPart(0);
}
BOOL CMultiFiles::OpenFiles(CAtlList<CHdmvClipInfo::PlaylistItem>& files, UINT nOpenFlags)
{
- POSITION pos = files.GetHeadPosition();
- LARGE_INTEGER llSize;
- int nPos = 0;
- REFERENCE_TIME rtDur = 0;
-
- Reset();
- while(pos)
- {
- CHdmvClipInfo::PlaylistItem& s = files.GetNext(pos);
- m_strFiles.Add(s.m_strFileName);
- if(!OpenPart(nPos)) return false;
-
- llSize.QuadPart = 0;
- GetFileSizeEx(m_hFile, &llSize);
- m_llTotalLength += llSize.QuadPart;
- m_FilesSize.Add(llSize.QuadPart);
- m_rtPtsOffsets.Add(rtDur);
- rtDur += s.Duration();
- nPos++;
- }
-
- if(files.GetCount() > 1) ClosePart();
-
- return TRUE;
+ POSITION pos = files.GetHeadPosition();
+ LARGE_INTEGER llSize;
+ int nPos = 0;
+ REFERENCE_TIME rtDur = 0;
+
+ Reset();
+ while(pos)
+ {
+ CHdmvClipInfo::PlaylistItem& s = files.GetNext(pos);
+ m_strFiles.Add(s.m_strFileName);
+ if (!OpenPart(nPos)) return false;
+
+ llSize.QuadPart = 0;
+ GetFileSizeEx (m_hFile, &llSize);
+ m_llTotalLength += llSize.QuadPart;
+ m_FilesSize.Add (llSize.QuadPart);
+ m_rtPtsOffsets.Add (rtDur);
+ rtDur += s.Duration();
+ nPos++;
+ }
+
+ if (files.GetCount() > 1) ClosePart();
+
+ return TRUE;
}
ULONGLONG CMultiFiles::Seek(LONGLONG lOff, UINT nFrom)
{
- LARGE_INTEGER llNewPos;
- LARGE_INTEGER llOff;
-
- if(m_strFiles.GetCount() == 1)
- {
- llOff.QuadPart = lOff;
- SetFilePointerEx(m_hFile, llOff, &llNewPos, nFrom);
-
- return llNewPos.QuadPart;
- }
- else
- {
- LONGLONG lAbsolutePos = GetAbsolutePosition(lOff, nFrom);
- int nNewPart = 0;
- ULONGLONG llSum = 0;
-
- while(m_FilesSize[nNewPart] + llSum <= lAbsolutePos)
- {
- llSum += m_FilesSize[nNewPart];
- nNewPart++;
- }
-
- OpenPart(nNewPart);
- llOff.QuadPart = lAbsolutePos - llSum;
- SetFilePointerEx(m_hFile, llOff, &llNewPos, FILE_BEGIN);
-
- return llSum + llNewPos.QuadPart;
- }
+ LARGE_INTEGER llNewPos;
+ LARGE_INTEGER llOff;
+
+ if (m_strFiles.GetCount() == 1)
+ {
+ llOff.QuadPart = lOff;
+ SetFilePointerEx (m_hFile, llOff, &llNewPos, nFrom);
+
+ return llNewPos.QuadPart;
+ }
+ else
+ {
+ LONGLONG lAbsolutePos = GetAbsolutePosition(lOff, nFrom);
+ int nNewPart = 0;
+ ULONGLONG llSum = 0;
+
+ while (m_FilesSize[nNewPart]+llSum <= lAbsolutePos)
+ {
+ llSum += m_FilesSize[nNewPart];
+ nNewPart++;
+ }
+
+ OpenPart (nNewPart);
+ llOff.QuadPart = lAbsolutePos - llSum;
+ SetFilePointerEx (m_hFile, llOff, &llNewPos, FILE_BEGIN);
+
+ return llSum + llNewPos.QuadPart;
+ }
}
ULONGLONG CMultiFiles::GetAbsolutePosition(LONGLONG lOff, UINT nFrom)
{
- LARGE_INTEGER llNoMove = {0, 0};
- LARGE_INTEGER llCurPos;
-
- switch(nFrom)
- {
- case begin :
- return lOff;
- case current :
- SetFilePointerEx(m_hFile, llNoMove, &llCurPos, FILE_CURRENT);
- return llCurPos.QuadPart + lOff;
- case end :
- return m_llTotalLength - lOff;
- default:
- return 0; // just used to quash "not all control paths return a value" warning
- }
+ LARGE_INTEGER llNoMove = {0, 0};
+ LARGE_INTEGER llCurPos;
+
+ switch (nFrom)
+ {
+ case begin :
+ return lOff;
+ case current :
+ SetFilePointerEx (m_hFile, llNoMove, &llCurPos, FILE_CURRENT);
+ return llCurPos.QuadPart + lOff;
+ case end :
+ return m_llTotalLength - lOff;
+ default:
+ return 0; // just used to quash "not all control paths return a value" warning
+ }
}
ULONGLONG CMultiFiles::GetLength() const
{
- if(m_strFiles.GetCount() == 1)
- {
- ULONGLONG llTotalSize = 0;
- LARGE_INTEGER llSize;
- GetFileSizeEx(m_hFile, &llSize);
- return llSize.QuadPart;
- }
- else
- return m_llTotalLength;
+ if (m_strFiles.GetCount() == 1)
+ {
+ ULONGLONG llTotalSize = 0;
+ LARGE_INTEGER llSize;
+ GetFileSizeEx (m_hFile, &llSize);
+ return llSize.QuadPart;
+ }
+ else
+ return m_llTotalLength;
}
UINT CMultiFiles::Read(void* lpBuf, UINT nCount)
{
- DWORD dwRead;
- do
- {
- if(!ReadFile(m_hFile, lpBuf, nCount, &dwRead, NULL))
- break;
-
- if(dwRead != nCount && m_nCurPart < m_strFiles.GetCount() - 1)
- {
- OpenPart(m_nCurPart + 1);
- lpBuf = (void*)((BYTE*)lpBuf + dwRead);
- nCount -= dwRead;
- }
- }
- while(nCount != dwRead && m_nCurPart < m_strFiles.GetCount() - 1);
- return dwRead;
+ DWORD dwRead;
+ do
+ {
+ if (!ReadFile(m_hFile, lpBuf, nCount, &dwRead, NULL))
+ break;
+
+ if (dwRead != nCount && m_nCurPart < m_strFiles.GetCount()-1)
+ {
+ OpenPart (m_nCurPart+1);
+ lpBuf = (void*)((BYTE*)lpBuf + dwRead);
+ nCount -= dwRead;
+ }
+ } while (nCount != dwRead && m_nCurPart < m_strFiles.GetCount()-1);
+ return dwRead;
}
void CMultiFiles::Close()
{
- ClosePart();
- Reset();
+ ClosePart();
+ Reset();
}
CMultiFiles::~CMultiFiles()
{
- Close();
+ Close();
}
BOOL CMultiFiles::OpenPart(int nPart)
{
- if(m_nCurPart == nPart)
- return TRUE;
- else
- {
- CString fn;
+ if (m_nCurPart == nPart)
+ return TRUE;
+ else
+ {
+ CString fn;
- ClosePart();
+ ClosePart();
- fn = m_strFiles.GetAt(nPart);
- m_hFile = CreateFile(fn, GENERIC_READ, FILE_SHARE_DELETE | FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, NULL);
+ fn = m_strFiles.GetAt(nPart);
+ m_hFile = CreateFile (fn, GENERIC_READ, FILE_SHARE_DELETE|FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, NULL);
- if(m_hFile != INVALID_HANDLE_VALUE)
- {
- m_nCurPart = nPart;
- if(m_pCurrentPTSOffset != NULL) *m_pCurrentPTSOffset = m_rtPtsOffsets[nPart];
- }
+ if (m_hFile != INVALID_HANDLE_VALUE)
+ {
+ m_nCurPart = nPart;
+ if (m_pCurrentPTSOffset != NULL) *m_pCurrentPTSOffset = m_rtPtsOffsets[nPart];
+ }
- return (m_hFile != INVALID_HANDLE_VALUE);
- }
+ return (m_hFile != INVALID_HANDLE_VALUE);
+ }
}
void CMultiFiles::ClosePart()
{
- if(m_hFile != INVALID_HANDLE_VALUE)
- {
- CloseHandle(m_hFile);
- m_hFile = INVALID_HANDLE_VALUE;
- m_nCurPart = -1;
- }
+ if (m_hFile != INVALID_HANDLE_VALUE)
+ {
+ CloseHandle (m_hFile);
+ m_hFile = INVALID_HANDLE_VALUE;
+ m_nCurPart = -1;
+ }
}
diff --git a/src/filters/parser/BaseSplitter/MultiFiles.h b/src/filters/parser/BaseSplitter/MultiFiles.h
index 003601cd0..b07862a0a 100644
--- a/src/filters/parser/BaseSplitter/MultiFiles.h
+++ b/src/filters/parser/BaseSplitter/MultiFiles.h
@@ -28,75 +28,73 @@
class CMultiFiles : public CObject
{
- DECLARE_DYNAMIC(CMultiFiles)
+ DECLARE_DYNAMIC(CMultiFiles)
public:
// Flag values
- enum OpenFlags
- {
- modeRead = (int) 0x00000,
- modeWrite = (int) 0x00001,
- modeReadWrite = (int) 0x00002,
- shareCompat = (int) 0x00000,
- shareExclusive = (int) 0x00010,
- shareDenyWrite = (int) 0x00020,
- shareDenyRead = (int) 0x00030,
- shareDenyNone = (int) 0x00040,
- modeNoInherit = (int) 0x00080,
- modeCreate = (int) 0x01000,
- modeNoTruncate = (int) 0x02000,
- typeText = (int) 0x04000, // typeText and typeBinary are
- typeBinary = (int) 0x08000, // used in derived classes only
- osNoBuffer = (int) 0x10000,
- osWriteThrough = (int) 0x20000,
- osRandomAccess = (int) 0x40000,
- osSequentialScan = (int) 0x80000,
- };
+ enum OpenFlags {
+ modeRead = (int) 0x00000,
+ modeWrite = (int) 0x00001,
+ modeReadWrite = (int) 0x00002,
+ shareCompat = (int) 0x00000,
+ shareExclusive = (int) 0x00010,
+ shareDenyWrite = (int) 0x00020,
+ shareDenyRead = (int) 0x00030,
+ shareDenyNone = (int) 0x00040,
+ modeNoInherit = (int) 0x00080,
+ modeCreate = (int) 0x01000,
+ modeNoTruncate = (int) 0x02000,
+ typeText = (int) 0x04000, // typeText and typeBinary are
+ typeBinary = (int) 0x08000, // used in derived classes only
+ osNoBuffer = (int) 0x10000,
+ osWriteThrough = (int) 0x20000,
+ osRandomAccess = (int) 0x40000,
+ osSequentialScan = (int) 0x80000,
+ };
- enum Attribute
- {
- normal = 0x00,
- readOnly = 0x01,
- hidden = 0x02,
- system = 0x04,
- volume = 0x08,
- directory = 0x10,
- archive = 0x20
- };
+ enum Attribute {
+ normal = 0x00,
+ readOnly = 0x01,
+ hidden = 0x02,
+ system = 0x04,
+ volume = 0x08,
+ directory = 0x10,
+ archive = 0x20
+ };
- enum SeekPosition { begin = 0x0, current = 0x1, end = 0x2 };
+ enum SeekPosition { begin = 0x0, current = 0x1, end = 0x2 };
// Constructors
- CMultiFiles();
+ CMultiFiles();
- CString m_strFileName;
+ CString m_strFileName;
// Operations
- virtual BOOL Open(LPCTSTR lpszFileName, UINT nOpenFlags);
- virtual BOOL OpenFiles(CAtlList<CHdmvClipInfo::PlaylistItem>& files, UINT nOpenFlags);
+ virtual BOOL Open(LPCTSTR lpszFileName, UINT nOpenFlags);
+ virtual BOOL OpenFiles(CAtlList<CHdmvClipInfo::PlaylistItem>& files, UINT nOpenFlags);
- virtual ULONGLONG Seek(LONGLONG lOff, UINT nFrom);
- virtual ULONGLONG GetLength() const;
+ virtual ULONGLONG Seek(LONGLONG lOff, UINT nFrom);
+ virtual ULONGLONG GetLength() const;
- virtual UINT Read(void* lpBuf, UINT nCount);
- virtual void Close();
+ virtual UINT Read(void* lpBuf, UINT nCount);
+ virtual void Close();
// Implementation
public:
- virtual ~CMultiFiles();
+ virtual ~CMultiFiles();
protected:
- REFERENCE_TIME* m_pCurrentPTSOffset;
- CAtlArray<CString> m_strFiles;
- CAtlArray<ULONGLONG> m_FilesSize;
- CAtlArray<REFERENCE_TIME> m_rtPtsOffsets;
- HANDLE m_hFile;
- int m_nCurPart;
- ULONGLONG m_llTotalLength;
+ REFERENCE_TIME* m_pCurrentPTSOffset;
+ CAtlArray<CString> m_strFiles;
+ CAtlArray<ULONGLONG> m_FilesSize;
+ CAtlArray<REFERENCE_TIME> m_rtPtsOffsets;
+ HANDLE m_hFile;
+ int m_nCurPart;
+ ULONGLONG m_llTotalLength;
- BOOL OpenPart(int nPart);
- void ClosePart();
- ULONGLONG GetAbsolutePosition(LONGLONG lOff, UINT nFrom);
- void Reset();
+ BOOL OpenPart(int nPart);
+ void ClosePart();
+ ULONGLONG GetAbsolutePosition(LONGLONG lOff, UINT nFrom);
+ void Reset();
};
diff --git a/src/filters/parser/BaseSplitter/stdafx.cpp b/src/filters/parser/BaseSplitter/stdafx.cpp
index 0533f2b32..4c0a34f8e 100644
--- a/src/filters/parser/BaseSplitter/stdafx.cpp
+++ b/src/filters/parser/BaseSplitter/stdafx.cpp
@@ -1,4 +1,4 @@
-/*
+/*
* Copyright (C) 2003-2006 Gabest
* http://www.gabest.org
*
@@ -6,15 +6,15 @@
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2, or (at your option)
* any later version.
- *
+ *
* This Program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with GNU Make; see the file COPYING. If not, write to
- * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
+ * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
* http://www.gnu.org/copyleft/gpl.html
*
*/
diff --git a/src/filters/parser/BaseSplitter/stdafx.h b/src/filters/parser/BaseSplitter/stdafx.h
index 6fe7f24f9..f7ba733d1 100644
--- a/src/filters/parser/BaseSplitter/stdafx.h
+++ b/src/filters/parser/BaseSplitter/stdafx.h
@@ -1,4 +1,4 @@
-/*
+/*
* Copyright (C) 2003-2006 Gabest
* http://www.gabest.org
*
@@ -6,15 +6,15 @@
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2, or (at your option)
* any later version.
- *
+ *
* This Program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with GNU Make; see the file COPYING. If not, write to
- * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
+ * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
* http://www.gnu.org/copyleft/gpl.html
*
*/
diff --git a/src/filters/parser/DSMSplitter/DSMSplitter.cpp b/src/filters/parser/DSMSplitter/DSMSplitter.cpp
index 4e40972f8..300a3cf7a 100644
--- a/src/filters/parser/DSMSplitter/DSMSplitter.cpp
+++ b/src/filters/parser/DSMSplitter/DSMSplitter.cpp
@@ -1,4 +1,4 @@
-/*
+/*
* Copyright (C) 2003-2006 Gabest
* http://www.gabest.org
*
@@ -6,15 +6,15 @@
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2, or (at your option)
* any later version.
- *
+ *
* This Program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with GNU Make; see the file COPYING. If not, write to
- * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
+ * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
* http://www.gnu.org/copyleft/gpl.html
*
*/
@@ -30,49 +30,49 @@
const AMOVIESETUP_MEDIATYPE sudPinTypesIn[] =
{
- {&MEDIATYPE_Stream, &MEDIASUBTYPE_DirectShowMedia},
- {&MEDIATYPE_Stream, &MEDIASUBTYPE_NULL},
+ {&MEDIATYPE_Stream, &MEDIASUBTYPE_DirectShowMedia},
+ {&MEDIATYPE_Stream, &MEDIASUBTYPE_NULL},
};
const AMOVIESETUP_PIN sudpPins[] =
{
- {L"Input", FALSE, FALSE, FALSE, FALSE, &CLSID_NULL, NULL, countof(sudPinTypesIn), sudPinTypesIn},
- {L"Output", FALSE, TRUE, FALSE, FALSE, &CLSID_NULL, NULL, 0, NULL}
+ {L"Input", FALSE, FALSE, FALSE, FALSE, &CLSID_NULL, NULL, countof(sudPinTypesIn), sudPinTypesIn},
+ {L"Output", FALSE, TRUE, FALSE, FALSE, &CLSID_NULL, NULL, 0, NULL}
};
const AMOVIESETUP_FILTER sudFilter[] =
{
- {&__uuidof(CDSMSplitterFilter), L"MPC - DSM Splitter", MERIT_NORMAL, countof(sudpPins), sudpPins, CLSID_LegacyAmFilterCategory},
- {&__uuidof(CDSMSourceFilter), L"MPC - DSM Source", MERIT_NORMAL, 0, NULL, CLSID_LegacyAmFilterCategory},
+ {&__uuidof(CDSMSplitterFilter), L"MPC - DSM Splitter", MERIT_NORMAL, countof(sudpPins), sudpPins, CLSID_LegacyAmFilterCategory},
+ {&__uuidof(CDSMSourceFilter), L"MPC - DSM Source", MERIT_NORMAL, 0, NULL, CLSID_LegacyAmFilterCategory},
};
CFactoryTemplate g_Templates[] =
{
- {sudFilter[0].strName, sudFilter[0].clsID, CreateInstance<CDSMSplitterFilter>, NULL, &sudFilter[0]},
- {sudFilter[1].strName, sudFilter[1].clsID, CreateInstance<CDSMSourceFilter>, NULL, &sudFilter[1]},
+ {sudFilter[0].strName, sudFilter[0].clsID, CreateInstance<CDSMSplitterFilter>, NULL, &sudFilter[0]},
+ {sudFilter[1].strName, sudFilter[1].clsID, CreateInstance<CDSMSourceFilter>, NULL, &sudFilter[1]},
};
int g_cTemplates = countof(g_Templates);
STDAPI DllRegisterServer()
{
- CString str;
- str.Format(_T("0,%d,,%%0%dI64x"), DSMSW_SIZE, DSMSW_SIZE * 2);
- str.Format(CString(str), DSMSW);
+ CString str;
+ str.Format(_T("0,%d,,%%0%dI64x"), DSMSW_SIZE, DSMSW_SIZE*2);
+ str.Format(CString(str), DSMSW);
- RegisterSourceFilter(
- CLSID_AsyncReader,
- MEDIASUBTYPE_DirectShowMedia,
- str, NULL);
+ RegisterSourceFilter(
+ CLSID_AsyncReader,
+ MEDIASUBTYPE_DirectShowMedia,
+ str, NULL);
- return AMovieDllRegisterServer2(TRUE);
+ return AMovieDllRegisterServer2(TRUE);
}
STDAPI DllUnregisterServer()
{
- UnRegisterSourceFilter(MEDIASUBTYPE_DirectShowMedia);
+ UnRegisterSourceFilter(MEDIASUBTYPE_DirectShowMedia);
- return AMovieDllRegisterServer2(FALSE);
+ return AMovieDllRegisterServer2(FALSE);
}
#include "../../FilterApp.h"
@@ -86,7 +86,7 @@ CFilterApp theApp;
//
CDSMSplitterFilter::CDSMSplitterFilter(LPUNKNOWN pUnk, HRESULT* phr)
- : CBaseSplitterFilter(NAME("CDSMSplitterFilter"), pUnk, phr, __uuidof(this))
+ : CBaseSplitterFilter(NAME("CDSMSplitterFilter"), pUnk, phr, __uuidof(this))
{
}
@@ -94,168 +94,156 @@ CDSMSplitterFilter::~CDSMSplitterFilter()
{
}
-static int compare_id(const void* id1, const void* id2)
-{
- return (int) * (BYTE*)id1 - (int) * (BYTE*)id2;
-}
+static int compare_id(const void* id1, const void* id2) {return (int)*(BYTE*)id1 - (int)*(BYTE*)id2;}
HRESULT CDSMSplitterFilter::CreateOutputs(IAsyncReader* pAsyncReader)
{
- CheckPointer(pAsyncReader, E_POINTER);
-
- HRESULT hr = E_FAIL;
-
- m_pFile.Free();
- m_pFile.Attach(DNew CDSMSplitterFile(pAsyncReader, hr, *this, *this));
- if(!m_pFile) return E_OUTOFMEMORY;
- if(FAILED(hr))
- {
- m_pFile.Free();
- return hr;
- }
-
- m_rtNewStart = m_rtCurrent = 0;
- m_rtNewStop = m_rtStop = m_rtDuration = m_pFile->m_rtDuration;
-
- CAtlArray<BYTE> ids;
-
- POSITION pos = m_pFile->m_mts.GetStartPosition();
- while(pos)
- {
- BYTE id;
- CMediaType mt;
- m_pFile->m_mts.GetNextAssoc(pos, id, mt);
- ids.Add(id);
- }
-
- qsort(ids.GetData(), ids.GetCount(), sizeof(BYTE), compare_id);
-
- for(int i = 0; i < ids.GetCount(); i++)
- {
- BYTE id = ids[i];
- CMediaType& mt = m_pFile->m_mts[id];
-
- CStringW name, lang;
- name.Format(L"Output %02d", id);
-
- CAtlArray<CMediaType> mts;
- mts.Add(mt);
-
- CAutoPtr<CBaseSplitterOutputPin> pPinOut(DNew CBaseSplitterOutputPin(mts, name, this, this, &hr));
-
- name.Empty();
-
- pos = m_pFile->m_sim[id].GetStartPosition();
- while(pos)
- {
- CStringA key;
- CStringW value;
- m_pFile->m_sim[id].GetNextAssoc(pos, key, value);
- pPinOut->SetProperty(CStringW(key), value);
-
- if(key == "NAME") name = value;
- if(key == "LANG") if((lang = ISO6392ToLanguage(CStringA(CString(value)))).IsEmpty()) lang = value;
- }
-
- if(!name.IsEmpty() || !lang.IsEmpty())
- {
- if(!name.IsEmpty())
- {
- if(!lang.IsEmpty()) name += L" (" + lang + L")";
- }
- else if(!lang.IsEmpty()) name = lang;
- pPinOut->SetName(name);
- }
-
- EXECUTE_ASSERT(SUCCEEDED(AddOutputPin(id, pPinOut)));
- }
-
- pos = m_pFile->m_fim.GetStartPosition();
- while(pos)
- {
- CStringA key;
- CStringW value;
- m_pFile->m_fim.GetNextAssoc(pos, key, value);
- SetProperty(CStringW(key), value);
- }
-
- for(int i = 0; i < m_resources.GetCount(); i++)
- {
- const CDSMResource& r = m_resources[i];
- if(r.mime == "application/x-truetype-font")
- m_fontinst.InstallFont(r.data);
- }
-
- return m_pOutputs.GetCount() > 0 ? S_OK : E_FAIL;
+ CheckPointer(pAsyncReader, E_POINTER);
+
+ HRESULT hr = E_FAIL;
+
+ m_pFile.Free();
+ m_pFile.Attach(DNew CDSMSplitterFile(pAsyncReader, hr, *this, *this));
+ if(!m_pFile) return E_OUTOFMEMORY;
+ if(FAILED(hr)) {m_pFile.Free(); return hr;}
+
+ m_rtNewStart = m_rtCurrent = 0;
+ m_rtNewStop = m_rtStop = m_rtDuration = m_pFile->m_rtDuration;
+
+ CAtlArray<BYTE> ids;
+
+ POSITION pos = m_pFile->m_mts.GetStartPosition();
+ while(pos)
+ {
+ BYTE id;
+ CMediaType mt;
+ m_pFile->m_mts.GetNextAssoc(pos, id, mt);
+ ids.Add(id);
+ }
+
+ qsort(ids.GetData(), ids.GetCount(), sizeof(BYTE), compare_id);
+
+ for(int i = 0; i < ids.GetCount(); i++)
+ {
+ BYTE id = ids[i];
+ CMediaType& mt = m_pFile->m_mts[id];
+
+ CStringW name, lang;
+ name.Format(L"Output %02d", id);
+
+ CAtlArray<CMediaType> mts;
+ mts.Add(mt);
+
+ CAutoPtr<CBaseSplitterOutputPin> pPinOut(DNew CBaseSplitterOutputPin(mts, name, this, this, &hr));
+
+ name.Empty();
+
+ pos = m_pFile->m_sim[id].GetStartPosition();
+ while(pos)
+ {
+ CStringA key; CStringW value;
+ m_pFile->m_sim[id].GetNextAssoc(pos, key, value);
+ pPinOut->SetProperty(CStringW(key), value);
+
+ if(key == "NAME") name = value;
+ if(key == "LANG") if((lang = ISO6392ToLanguage(CStringA(CString(value)))).IsEmpty()) lang = value;
+ }
+
+ if(!name.IsEmpty() || !lang.IsEmpty())
+ {
+ if(!name.IsEmpty()) {if(!lang.IsEmpty()) name += L" (" + lang + L")";}
+ else if(!lang.IsEmpty()) name = lang;
+ pPinOut->SetName(name);
+ }
+
+ EXECUTE_ASSERT(SUCCEEDED(AddOutputPin(id, pPinOut)));
+ }
+
+ pos = m_pFile->m_fim.GetStartPosition();
+ while(pos)
+ {
+ CStringA key; CStringW value;
+ m_pFile->m_fim.GetNextAssoc(pos, key, value);
+ SetProperty(CStringW(key), value);
+ }
+
+ for(int i = 0; i < m_resources.GetCount(); i++)
+ {
+ const CDSMResource& r = m_resources[i];
+ if(r.mime == "application/x-truetype-font")
+ m_fontinst.InstallFont(r.data);
+ }
+
+ return m_pOutputs.GetCount() > 0 ? S_OK : E_FAIL;
}
bool CDSMSplitterFilter::DemuxInit()
{
- return true;
+ return true;
}
void CDSMSplitterFilter::DemuxSeek(REFERENCE_TIME rt)
{
- m_pFile->Seek(m_pFile->FindSyncPoint(rt));
+ m_pFile->Seek(m_pFile->FindSyncPoint(rt));
}
bool CDSMSplitterFilter::DemuxLoop()
{
- HRESULT hr = S_OK;
+ HRESULT hr = S_OK;
- while(SUCCEEDED(hr) && !CheckRequest(NULL) && m_pFile->GetRemaining())
- {
- dsmp_t type;
- UINT64 len;
+ while(SUCCEEDED(hr) && !CheckRequest(NULL) && m_pFile->GetRemaining())
+ {
+ dsmp_t type;
+ UINT64 len;
- if(!m_pFile->Sync(type, len))
- continue;
+ if(!m_pFile->Sync(type, len))
+ continue;
- __int64 pos = m_pFile->GetPos();
+ __int64 pos = m_pFile->GetPos();
- if(type == DSMP_SAMPLE)
- {
- CAutoPtr<Packet> p(DNew Packet());
- if(m_pFile->Read(len, p))
- {
- if(p->rtStart != Packet::INVALID_TIME)
- {
- p->rtStart -= m_pFile->m_rtFirst;
- p->rtStop -= m_pFile->m_rtFirst;
- }
+ if(type == DSMP_SAMPLE)
+ {
+ CAutoPtr<Packet> p(DNew Packet());
+ if(m_pFile->Read(len, p))
+ {
+ if(p->rtStart != Packet::INVALID_TIME)
+ {
+ p->rtStart -= m_pFile->m_rtFirst;
+ p->rtStop -= m_pFile->m_rtFirst;
+ }
- hr = DeliverPacket(p);
- }
- }
+ hr = DeliverPacket(p);
+ }
+ }
- m_pFile->Seek(pos + len);
- }
+ m_pFile->Seek(pos + len);
+ }
- return(true);
+ return(true);
}
// IKeyFrameInfo
STDMETHODIMP CDSMSplitterFilter::GetKeyFrameCount(UINT& nKFs)
{
- CheckPointer(m_pFile, E_UNEXPECTED);
- nKFs = m_pFile->m_sps.GetCount();
- return S_OK;
+ CheckPointer(m_pFile, E_UNEXPECTED);
+ nKFs = m_pFile->m_sps.GetCount();
+ return S_OK;
}
STDMETHODIMP CDSMSplitterFilter::GetKeyFrames(const GUID* pFormat, REFERENCE_TIME* pKFs, UINT& nKFs)
{
- CheckPointer(pFormat, E_POINTER);
- CheckPointer(pKFs, E_POINTER);
- CheckPointer(m_pFile, E_UNEXPECTED);
+ CheckPointer(pFormat, E_POINTER);
+ CheckPointer(pKFs, E_POINTER);
+ CheckPointer(m_pFile, E_UNEXPECTED);
- if(*pFormat != TIME_FORMAT_MEDIA_TIME) return E_INVALIDARG;
+ if(*pFormat != TIME_FORMAT_MEDIA_TIME) return E_INVALIDARG;
- // these aren't really the keyframes, but quicky accessable points in the stream
- for(nKFs = 0; nKFs < m_pFile->m_sps.GetCount(); nKFs++)
- pKFs[nKFs] = m_pFile->m_sps[nKFs].rt;
+ // these aren't really the keyframes, but quicky accessable points in the stream
+ for(nKFs = 0; nKFs < m_pFile->m_sps.GetCount(); nKFs++)
+ pKFs[nKFs] = m_pFile->m_sps[nKFs].rt;
- return S_OK;
+ return S_OK;
}
//
@@ -263,8 +251,8 @@ STDMETHODIMP CDSMSplitterFilter::GetKeyFrames(const GUID* pFormat, REFERENCE_TIM
//
CDSMSourceFilter::CDSMSourceFilter(LPUNKNOWN pUnk, HRESULT* phr)
- : CDSMSplitterFilter(pUnk, phr)
+ : CDSMSplitterFilter(pUnk, phr)
{
- m_clsid = __uuidof(this);
- m_pInput.Free();
+ m_clsid = __uuidof(this);
+ m_pInput.Free();
}
diff --git a/src/filters/parser/DSMSplitter/DSMSplitter.h b/src/filters/parser/DSMSplitter/DSMSplitter.h
index 81469b232..77bc53cad 100644
--- a/src/filters/parser/DSMSplitter/DSMSplitter.h
+++ b/src/filters/parser/DSMSplitter/DSMSplitter.h
@@ -1,4 +1,4 @@
-/*
+/*
* Copyright (C) 2003-2006 Gabest
* http://www.gabest.org
*
@@ -6,15 +6,15 @@
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2, or (at your option)
* any later version.
- *
+ *
* This Program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with GNU Make; see the file COPYING. If not, write to
- * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
+ * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
* http://www.gnu.org/copyleft/gpl.html
*
*/
@@ -30,26 +30,26 @@
class CDSMSplitterFilter : public CBaseSplitterFilter
{
protected:
- CAutoPtr<CDSMSplitterFile> m_pFile;
- HRESULT CreateOutputs(IAsyncReader* pAsyncReader);
+ CAutoPtr<CDSMSplitterFile> m_pFile;
+ HRESULT CreateOutputs(IAsyncReader* pAsyncReader);
- bool DemuxInit();
- void DemuxSeek(REFERENCE_TIME rt);
- bool DemuxLoop();
+ bool DemuxInit();
+ void DemuxSeek(REFERENCE_TIME rt);
+ bool DemuxLoop();
public:
- CDSMSplitterFilter(LPUNKNOWN pUnk, HRESULT* phr);
- virtual ~CDSMSplitterFilter();
+ CDSMSplitterFilter(LPUNKNOWN pUnk, HRESULT* phr);
+ virtual ~CDSMSplitterFilter();
- // IKeyFrameInfo
+ // IKeyFrameInfo
- STDMETHODIMP_(HRESULT) GetKeyFrameCount(UINT& nKFs);
- STDMETHODIMP_(HRESULT) GetKeyFrames(const GUID* pFormat, REFERENCE_TIME* pKFs, UINT& nKFs);
+ STDMETHODIMP_(HRESULT) GetKeyFrameCount(UINT& nKFs);
+ STDMETHODIMP_(HRESULT) GetKeyFrames(const GUID* pFormat, REFERENCE_TIME* pKFs, UINT& nKFs);
};
[uuid("803E8280-F3CE-4201-982C-8CD8FB512004")]
class CDSMSourceFilter : public CDSMSplitterFilter
{
public:
- CDSMSourceFilter(LPUNKNOWN pUnk, HRESULT* phr);
+ CDSMSourceFilter(LPUNKNOWN pUnk, HRESULT* phr);
};
diff --git a/src/filters/parser/DSMSplitter/DSMSplitterFile.cpp b/src/filters/parser/DSMSplitter/DSMSplitterFile.cpp
index 4d6f56e53..f4448f661 100644
--- a/src/filters/parser/DSMSplitter/DSMSplitterFile.cpp
+++ b/src/filters/parser/DSMSplitter/DSMSplitterFile.cpp
@@ -3,428 +3,395 @@
#include "../../../DSUtil/DSUtil.h"
#include <moreuuids.h>
-CDSMSplitterFile::CDSMSplitterFile(IAsyncReader* pReader, HRESULT& hr, IDSMResourceBagImpl& res, IDSMChapterBagImpl& chap)
- : CBaseSplitterFile(pReader, hr, DEFAULT_CACHE_LENGTH, false)
- , m_rtFirst(0)
- , m_rtDuration(0)
+CDSMSplitterFile::CDSMSplitterFile(IAsyncReader* pReader, HRESULT& hr, IDSMResourceBagImpl& res, IDSMChapterBagImpl& chap)
+ : CBaseSplitterFile(pReader, hr, DEFAULT_CACHE_LENGTH, false)
+ , m_rtFirst(0)
+ , m_rtDuration(0)
{
- if(FAILED(hr)) return;
+ if(FAILED(hr)) return;
- hr = Init(res, chap);
+ hr = Init(res, chap);
}
HRESULT CDSMSplitterFile::Init(IDSMResourceBagImpl& res, IDSMChapterBagImpl& chap)
{
- Seek(0);
-
- if(BitRead(DSMSW_SIZE << 3) != DSMSW || BitRead(5) != DSMP_FILEINFO)
- return E_FAIL;
-
- Seek(0);
-
- m_mts.RemoveAll();
- m_rtFirst = m_rtDuration = 0;
- m_fim.RemoveAll();
- m_sim.RemoveAll();
- res.ResRemoveAll();
- chap.ChapRemoveAll();
-
- dsmp_t type;
- UINT64 len;
- int limit = 65536;
-
- // examine the beginning of the file ...
-
- while(Sync(type, len, 0))
- {
- __int64 pos = GetPos();
-
- if(type == DSMP_MEDIATYPE)
- {
- BYTE id;
- CMediaType mt;
- if(Read(len, id, mt)) m_mts[id] = mt;
- }
- else if(type == DSMP_SAMPLE)
- {
- Packet p;
- if(Read(len, &p, false) && p.rtStart != Packet::INVALID_TIME)
- {
- m_rtFirst = p.rtStart;
- break;
- }
- }
- else if(type == DSMP_FILEINFO)
- {
- if((BYTE)BitRead(8) > DSMF_VERSION) return E_FAIL;
- Read(len - 1, m_fim);
- }
- else if(type == DSMP_STREAMINFO)
- {
- Read(len - 1, m_sim[(BYTE)BitRead(8)]);
- }
- else if(type == DSMP_SYNCPOINTS)
- {
- Read(len, m_sps);
- }
- else if(type == DSMP_RESOURCE)
- {
- Read(len, res);
- }
- else if(type == DSMP_CHAPTERS)
- {
- Read(len, chap);
- }
-
- Seek(pos + len);
- }
-
- if(type != DSMP_SAMPLE)
- return E_FAIL;
-
- // ... and the end
-
- if(IsRandomAccess())
- for(int i = 1, j = (int)((GetLength() + limit / 2) / limit); i <= j; i++)
- {
- __int64 seekpos = max(0, (__int64)GetLength() - i * limit);
- Seek(seekpos);
-
- while(Sync(type, len, limit) && GetPos() < seekpos + limit)
- {
- __int64 pos = GetPos();
-
- if(type == DSMP_SAMPLE)
- {
- Packet p;
- if(Read(len, &p, false) && p.rtStart != Packet::INVALID_TIME)
- {
- m_rtDuration = max(m_rtDuration, p.rtStop - m_rtFirst); // max isn't really needed, only for safety
- i = j;
- }
- }
- else if(type == DSMP_SYNCPOINTS)
- {
- Read(len, m_sps);
- }
- else if(type == DSMP_RESOURCE)
- {
- Read(len, res);
- }
- else if(type == DSMP_CHAPTERS)
- {
- Read(len, chap);
- }
-
- Seek(pos + len);
- }
- }
-
- if(m_rtFirst < 0)
- {
- m_rtDuration += m_rtFirst;
- m_rtFirst = 0;
- }
-
- return m_mts.GetCount() > 0 ? S_OK : E_FAIL;
+ Seek(0);
+
+ if(BitRead(DSMSW_SIZE<<3) != DSMSW || BitRead(5) != DSMP_FILEINFO)
+ return E_FAIL;
+
+ Seek(0);
+
+ m_mts.RemoveAll();
+ m_rtFirst = m_rtDuration = 0;
+ m_fim.RemoveAll();
+ m_sim.RemoveAll();
+ res.ResRemoveAll();
+ chap.ChapRemoveAll();
+
+ dsmp_t type;
+ UINT64 len;
+ int limit = 65536;
+
+ // examine the beginning of the file ...
+
+ while(Sync(type, len, 0))
+ {
+ __int64 pos = GetPos();
+
+ if(type == DSMP_MEDIATYPE)
+ {
+ BYTE id;
+ CMediaType mt;
+ if(Read(len, id, mt)) m_mts[id] = mt;
+ }
+ else if(type == DSMP_SAMPLE)
+ {
+ Packet p;
+ if(Read(len, &p, false) && p.rtStart != Packet::INVALID_TIME)
+ {
+ m_rtFirst = p.rtStart;
+ break;
+ }
+ }
+ else if(type == DSMP_FILEINFO) {if((BYTE)BitRead(8) > DSMF_VERSION) return E_FAIL; Read(len-1, m_fim);}
+ else if(type == DSMP_STREAMINFO) {Read(len-1, m_sim[(BYTE)BitRead(8)]);}
+ else if(type == DSMP_SYNCPOINTS) {Read(len, m_sps);}
+ else if(type == DSMP_RESOURCE) {Read(len, res);}
+ else if(type == DSMP_CHAPTERS) {Read(len, chap);}
+
+ Seek(pos + len);
+ }
+
+ if(type != DSMP_SAMPLE)
+ return E_FAIL;
+
+ // ... and the end
+
+ if(IsRandomAccess())
+ for(int i = 1, j = (int)((GetLength()+limit/2)/limit); i <= j; i++)
+ {
+ __int64 seekpos = max(0, (__int64)GetLength()-i*limit);
+ Seek(seekpos);
+
+ while(Sync(type, len, limit) && GetPos() < seekpos+limit)
+ {
+ __int64 pos = GetPos();
+
+ if(type == DSMP_SAMPLE)
+ {
+ Packet p;
+ if(Read(len, &p, false) && p.rtStart != Packet::INVALID_TIME)
+ {
+ m_rtDuration = max(m_rtDuration, p.rtStop - m_rtFirst); // max isn't really needed, only for safety
+ i = j;
+ }
+ }
+ else if(type == DSMP_SYNCPOINTS) {Read(len, m_sps);}
+ else if(type == DSMP_RESOURCE) {Read(len, res);}
+ else if(type == DSMP_CHAPTERS) {Read(len, chap);}
+
+ Seek(pos + len);
+ }
+ }
+
+ if(m_rtFirst < 0)
+ {
+ m_rtDuration += m_rtFirst;
+ m_rtFirst = 0;
+ }
+
+ return m_mts.GetCount() > 0 ? S_OK : E_FAIL;
}
bool CDSMSplitterFile::Sync(dsmp_t& type, UINT64& len, __int64 limit)
{
- UINT64 pos;
- return Sync(pos, type, len, limit);
+ UINT64 pos;
+ return Sync(pos, type, len, limit);
}
bool CDSMSplitterFile::Sync(UINT64& syncpos, dsmp_t& type, UINT64& len, __int64 limit)
{
- BitByteAlign();
+ BitByteAlign();
- limit += DSMSW_SIZE;
+ limit += DSMSW_SIZE;
- for(UINT64 id = 0; (id&((1ui64 << (DSMSW_SIZE << 3)) - 1)) != DSMSW; id = (id << 8) | (BYTE)BitRead(8))
- {
- if(limit-- <= 0 || GetRemaining() <= 2)
- return(false);
- }
+ for(UINT64 id = 0; (id&((1ui64<<(DSMSW_SIZE<<3))-1)) != DSMSW; id = (id << 8) | (BYTE)BitRead(8))
+ {
+ if(limit-- <= 0 || GetRemaining() <= 2)
+ return(false);
+ }
- syncpos = GetPos() - (DSMSW_SIZE << 3);
- type = (dsmp_t)BitRead(5);
- len = BitRead(((int)BitRead(3) + 1) << 3);
+ syncpos = GetPos() - (DSMSW_SIZE<<3);
+ type = (dsmp_t)BitRead(5);
+ len = BitRead(((int)BitRead(3)+1)<<3);
- return(true);
+ return(true);
}
bool CDSMSplitterFile::Read(__int64 len, BYTE& id, CMediaType& mt)
{
- id = (BYTE)BitRead(8);
- ByteRead((BYTE*)&mt.majortype, sizeof(mt.majortype));
- ByteRead((BYTE*)&mt.subtype, sizeof(mt.subtype));
- mt.bFixedSizeSamples = (BOOL)BitRead(1);
- mt.bTemporalCompression = (BOOL)BitRead(1);
- mt.lSampleSize = (ULONG)BitRead(30);
- ByteRead((BYTE*)&mt.formattype, sizeof(mt.formattype));
- len -= 5 + sizeof(GUID) * 3;
- ASSERT(len >= 0);
- if(len > 0)
- {
- mt.AllocFormatBuffer((LONG)len);
- ByteRead(mt.Format(), mt.FormatLength());
- }
- else mt.ResetFormatBuffer();
- return true;
+ id = (BYTE)BitRead(8);
+ ByteRead((BYTE*)&mt.majortype, sizeof(mt.majortype));
+ ByteRead((BYTE*)&mt.subtype, sizeof(mt.subtype));
+ mt.bFixedSizeSamples = (BOOL)BitRead(1);
+ mt.bTemporalCompression = (BOOL)BitRead(1);
+ mt.lSampleSize = (ULONG)BitRead(30);
+ ByteRead((BYTE*)&mt.formattype, sizeof(mt.formattype));
+ len -= 5 + sizeof(GUID)*3;
+ ASSERT(len >= 0);
+ if(len > 0) {mt.AllocFormatBuffer((LONG)len); ByteRead(mt.Format(), mt.FormatLength());}
+ else mt.ResetFormatBuffer();
+ return true;
}
bool CDSMSplitterFile::Read(__int64 len, Packet* p, bool fData)
{
- if(!p) return false;
-
- p->TrackNumber = (DWORD)BitRead(8);
- p->bSyncPoint = (BOOL)BitRead(1);
- bool fSign = !!BitRead(1);
- int iTimeStamp = (int)BitRead(3);
- int iDuration = (int)BitRead(3);
-
- if(fSign && !iTimeStamp)
- {
- ASSERT(!iDuration);
- p->rtStart = Packet::INVALID_TIME;
- p->rtStop = Packet::INVALID_TIME + 1;
- }
- else
- {
- p->rtStart = (REFERENCE_TIME)BitRead(iTimeStamp << 3) * (fSign ? -1 : 1);
- p->rtStop = p->rtStart + BitRead(iDuration << 3);
- }
-
- if(fData)
- {
+ if(!p) return false;
+
+ p->TrackNumber = (DWORD)BitRead(8);
+ p->bSyncPoint = (BOOL)BitRead(1);
+ bool fSign = !!BitRead(1);
+ int iTimeStamp = (int)BitRead(3);
+ int iDuration = (int)BitRead(3);
+
+ if(fSign && !iTimeStamp)
+ {
+ ASSERT(!iDuration);
+ p->rtStart = Packet::INVALID_TIME;
+ p->rtStop = Packet::INVALID_TIME + 1;
+ }
+ else
+ {
+ p->rtStart = (REFERENCE_TIME)BitRead(iTimeStamp<<3) * (fSign ? -1 : 1);
+ p->rtStop = p->rtStart + BitRead(iDuration<<3);
+ }
+
+ if(fData)
+ {
p->SetCount((INT_PTR)len - (2 + iTimeStamp + iDuration));
- ByteRead(p->GetData(), p->GetCount());
- }
+ ByteRead(p->GetData(), p->GetCount());
+ }
- return true;
+ return true;
}
bool CDSMSplitterFile::Read(__int64 len, CAtlArray<SyncPoint>& sps)
{
- SyncPoint sp = {0, 0};
- sps.RemoveAll();
+ SyncPoint sp = {0, 0};
+ sps.RemoveAll();
- while(len > 0)
- {
- bool fSign = !!BitRead(1);
- int iTimeStamp = (int)BitRead(3);
- int iFilePos = (int)BitRead(3);
- BitRead(1); // reserved
+ while(len > 0)
+ {
+ bool fSign = !!BitRead(1);
+ int iTimeStamp = (int)BitRead(3);
+ int iFilePos = (int)BitRead(3);
+ BitRead(1); // reserved
- sp.rt += (REFERENCE_TIME)BitRead(iTimeStamp << 3) * (fSign ? -1 : 1);
- sp.fp += BitRead(iFilePos << 3);
- sps.Add(sp);
+ sp.rt += (REFERENCE_TIME)BitRead(iTimeStamp<<3) * (fSign ? -1 : 1);
+ sp.fp += BitRead(iFilePos<<3);
+ sps.Add(sp);
- len -= 1 + iTimeStamp + iFilePos;
- }
+ len -= 1 + iTimeStamp + iFilePos;
+ }
- if(len != 0)
- {
- sps.RemoveAll();
- return false;
- }
+ if(len != 0)
+ {
+ sps.RemoveAll();
+ return false;
+ }
- // TODO: sort sps
+ // TODO: sort sps
- return true;
+ return true;
}
bool CDSMSplitterFile::Read(__int64 len, CStreamInfoMap& im)
{
- while(len >= 5)
- {
- CStringA key;
- ByteRead((BYTE*)key.GetBufferSetLength(4), 4);
- len -= 4;
- len -= Read(len, im[key]);
- }
-
- return len == 0;
+ while(len >= 5)
+ {
+ CStringA key;
+ ByteRead((BYTE*)key.GetBufferSetLength(4), 4);
+ len -= 4;
+ len -= Read(len, im[key]);
+ }
+
+ return len == 0;
}
bool CDSMSplitterFile::Read(__int64 len, IDSMResourceBagImpl& res)
{
- BYTE compression = (BYTE)BitRead(2);
- BYTE reserved = (BYTE)BitRead(6);
- len--;
+ BYTE compression = (BYTE)BitRead(2);
+ BYTE reserved = (BYTE)BitRead(6);
+ len--;
- CDSMResource r;
- len -= Read(len, r.name);
- len -= Read(len, r.desc);
- len -= Read(len, r.mime);
+ CDSMResource r;
+ len -= Read(len, r.name);
+ len -= Read(len, r.desc);
+ len -= Read(len, r.mime);
- if(compression != 0) return false; // TODO
+ if(compression != 0) return false; // TODO
- r.data.SetCount(len);
- ByteRead(r.data.GetData(), r.data.GetCount());
+ r.data.SetCount(len);
+ ByteRead(r.data.GetData(), r.data.GetCount());
- res += r;
+ res += r;
- return true;
+ return true;
}
bool CDSMSplitterFile::Read(__int64 len, IDSMChapterBagImpl& chap)
{
- CDSMChapter c(0, L"");
+ CDSMChapter c(0, L"");
- while(len > 0)
- {
- bool fSign = !!BitRead(1);
- int iTimeStamp = (int)BitRead(3);
- BitRead(4); // reserved
- len--;
+ while(len > 0)
+ {
+ bool fSign = !!BitRead(1);
+ int iTimeStamp = (int)BitRead(3);
+ BitRead(4); // reserved
+ len--;
- c.rt += (REFERENCE_TIME)BitRead(iTimeStamp << 3) * (fSign ? -1 : 1);
- len -= iTimeStamp;
- len -= Read(len, c.name);
+ c.rt += (REFERENCE_TIME)BitRead(iTimeStamp<<3) * (fSign ? -1 : 1);
+ len -= iTimeStamp;
+ len -= Read(len, c.name);
- chap += c;
- }
+ chap += c;
+ }
- chap.ChapSort();
+ chap.ChapSort();
- return len == 0;
+ return len == 0;
}
__int64 CDSMSplitterFile::Read(__int64 len, CStringW& str)
{
- char c;
- CStringA s;
- __int64 i = 0;
- while(i++ < len && (c = (char)BitRead(8)) != 0) s += c;
- str = UTF8To16(s);
- return i;
+ char c;
+ CStringA s;
+ __int64 i = 0;
+ while(i++ < len && (c = (char)BitRead(8)) != 0) s += c;
+ str = UTF8To16(s);
+ return i;
}
__int64 CDSMSplitterFile::FindSyncPoint(REFERENCE_TIME rt)
{
- if(/*!m_sps.IsEmpty()*/ m_sps.GetCount() > 1)
- {
- int i = range_bsearch(m_sps, m_rtFirst + rt);
- return i >= 0 ? m_sps[i].fp : 0;
- }
-
- if(m_rtDuration <= 0 || rt <= m_rtFirst)
- return 0;
-
- // ok, do the hard way then
-
- dsmp_t type;
- UINT64 syncpos, len;
-
- // 1. find some boundaries close to rt's position (minpos, maxpos)
-
- __int64 minpos = 0, maxpos = GetLength();
-
- for(int i = 0; i < 10 && (maxpos - minpos) >= 1024 * 1024; i++)
- {
- Seek((minpos + maxpos) / 2);
-
- while(GetPos() < maxpos)
- {
- if(!Sync(syncpos, type, len))
- continue;
-
- __int64 pos = GetPos();
-
- if(type == DSMP_SAMPLE)
- {
- Packet p;
- if(Read(len, &p, false) && p.rtStart != Packet::INVALID_TIME)
- {
- REFERENCE_TIME dt = (p.rtStart -= m_rtFirst) - rt;
- if(dt >= 0) maxpos = max((__int64)syncpos - 65536, minpos);
- else minpos = syncpos;
- break;
- }
- }
-
- Seek(pos + len);
- }
- }
-
- // 2. find the first packet just after rt (maxpos)
-
- Seek(minpos);
-
- while(GetRemaining())
- {
- if(!Sync(syncpos, type, len))
- continue;
-
- __int64 pos = GetPos();
-
- if(type == DSMP_SAMPLE)
- {
- Packet p;
- if(Read(len, &p, false) && p.rtStart != Packet::INVALID_TIME)
- {
- REFERENCE_TIME dt = (p.rtStart -= m_rtFirst) - rt;
- if(dt >= 0)
- {
- maxpos = (__int64)syncpos;
- break;
- }
- }
- }
-
- Seek(pos + len);
- }
-
- // 3. iterate backwards from maxpos and find at least one syncpoint for every stream, except for subtitle streams
-
- CAtlMap<BYTE, BYTE> ids;
-
- {
- POSITION pos = m_mts.GetStartPosition();
- while(pos)
- {
- BYTE id;
- CMediaType mt;
- m_mts.GetNextAssoc(pos, id, mt);
- if(mt.majortype != MEDIATYPE_Text && mt.majortype != MEDIATYPE_Subtitle)
- ids[id] = 0;
- }
- }
-
- __int64 ret = maxpos;
-
- while(maxpos > 0 && !ids.IsEmpty())
- {
- minpos = max(0, maxpos - 65536);
-
- Seek(minpos);
-
- while(Sync(syncpos, type, len) && GetPos() < maxpos)
- {
- UINT64 pos = GetPos();
-
- if(type == DSMP_SAMPLE)
- {
- Packet p;
- if(Read(len, &p, false) && p.rtStart != Packet::INVALID_TIME && p.bSyncPoint)
- {
- BYTE id = (BYTE)p.TrackNumber, tmp;
- if(ids.Lookup(id, tmp))
- {
- ids.RemoveKey((BYTE)p.TrackNumber);
- ret = min(ret, (__int64)syncpos);
- }
- }
- }
-
- Seek(pos + len);
- }
-
- maxpos = minpos;
- }
-
- return ret;
+ if(/*!m_sps.IsEmpty()*/ m_sps.GetCount() > 1)
+ {
+ int i = range_bsearch(m_sps, m_rtFirst + rt);
+ return i >= 0 ? m_sps[i].fp : 0;
+ }
+
+ if(m_rtDuration <= 0 || rt <= m_rtFirst)
+ return 0;
+
+ // ok, do the hard way then
+
+ dsmp_t type;
+ UINT64 syncpos, len;
+
+ // 1. find some boundaries close to rt's position (minpos, maxpos)
+
+ __int64 minpos = 0, maxpos = GetLength();
+
+ for(int i = 0; i < 10 && (maxpos - minpos) >= 1024*1024; i++)
+ {
+ Seek((minpos + maxpos) / 2);
+
+ while(GetPos() < maxpos)
+ {
+ if(!Sync(syncpos, type, len))
+ continue;
+
+ __int64 pos = GetPos();
+
+ if(type == DSMP_SAMPLE)
+ {
+ Packet p;
+ if(Read(len, &p, false) && p.rtStart != Packet::INVALID_TIME)
+ {
+ REFERENCE_TIME dt = (p.rtStart -= m_rtFirst) - rt;
+ if(dt >= 0) maxpos = max((__int64)syncpos - 65536, minpos);
+ else minpos = syncpos;
+ break;
+ }
+ }
+
+ Seek(pos + len);
+ }
+ }
+
+ // 2. find the first packet just after rt (maxpos)
+
+ Seek(minpos);
+
+ while(GetRemaining())
+ {
+ if(!Sync(syncpos, type, len))
+ continue;
+
+ __int64 pos = GetPos();
+
+ if(type == DSMP_SAMPLE)
+ {
+ Packet p;
+ if(Read(len, &p, false) && p.rtStart != Packet::INVALID_TIME)
+ {
+ REFERENCE_TIME dt = (p.rtStart -= m_rtFirst) - rt;
+ if(dt >= 0) {maxpos = (__int64)syncpos; break;}
+ }
+ }
+
+ Seek(pos + len);
+ }
+
+ // 3. iterate backwards from maxpos and find at least one syncpoint for every stream, except for subtitle streams
+
+ CAtlMap<BYTE,BYTE> ids;
+
+ {
+ POSITION pos = m_mts.GetStartPosition();
+ while(pos)
+ {
+ BYTE id;
+ CMediaType mt;
+ m_mts.GetNextAssoc(pos, id, mt);
+ if(mt.majortype != MEDIATYPE_Text && mt.majortype != MEDIATYPE_Subtitle)
+ ids[id] = 0;
+ }
+ }
+
+ __int64 ret = maxpos;
+
+ while(maxpos > 0 && !ids.IsEmpty())
+ {
+ minpos = max(0, maxpos - 65536);
+
+ Seek(minpos);
+
+ while(Sync(syncpos, type, len) && GetPos() < maxpos)
+ {
+ UINT64 pos = GetPos();
+
+ if(type == DSMP_SAMPLE)
+ {
+ Packet p;
+ if(Read(len, &p, false) && p.rtStart != Packet::INVALID_TIME && p.bSyncPoint)
+ {
+ BYTE id = (BYTE)p.TrackNumber, tmp;
+ if(ids.Lookup(id, tmp))
+ {
+ ids.RemoveKey((BYTE)p.TrackNumber);
+ ret = min(ret, (__int64)syncpos);
+ }
+ }
+ }
+
+ Seek(pos + len);
+ }
+
+ maxpos = minpos;
+ }
+
+ return ret;
}
diff --git a/src/filters/parser/DSMSplitter/DSMSplitterFile.h b/src/filters/parser/DSMSplitter/DSMSplitterFile.h
index 21fb2fde5..7c350db2f 100644
--- a/src/filters/parser/DSMSplitter/DSMSplitterFile.h
+++ b/src/filters/parser/DSMSplitter/DSMSplitterFile.h
@@ -6,34 +6,30 @@
class CDSMSplitterFile : public CBaseSplitterFile
{
- HRESULT Init(IDSMResourceBagImpl& res, IDSMChapterBagImpl& chap);
+ HRESULT Init(IDSMResourceBagImpl& res, IDSMChapterBagImpl& chap);
public:
- CDSMSplitterFile(IAsyncReader* pReader, HRESULT& hr, IDSMResourceBagImpl& res, IDSMChapterBagImpl& chap);
-
- CAtlMap<BYTE, CMediaType> m_mts;
- REFERENCE_TIME m_rtFirst, m_rtDuration;
-
- struct SyncPoint
- {
- REFERENCE_TIME rt;
- __int64 fp;
- };
- CAtlArray<SyncPoint> m_sps;
-
- typedef CAtlMap<CStringA, CStringW, CStringElementTraits<CStringA>, CStringElementTraits<CStringW> > CStreamInfoMap;
- CStreamInfoMap m_fim;
- CAtlMap<BYTE, CStreamInfoMap> m_sim;
-
- bool Sync(dsmp_t& type, UINT64& len, __int64 limit = 65536);
- bool Sync(UINT64& syncpos, dsmp_t& type, UINT64& len, __int64 limit = 65536);
- bool Read(__int64 len, BYTE& id, CMediaType& mt);
- bool Read(__int64 len, Packet* p, bool fData = true);
- bool Read(__int64 len, CAtlArray<SyncPoint>& sps);
- bool Read(__int64 len, CStreamInfoMap& im);
- bool Read(__int64 len, IDSMResourceBagImpl& res);
- bool Read(__int64 len, IDSMChapterBagImpl& chap);
- __int64 Read(__int64 len, CStringW& str);
-
- __int64 FindSyncPoint(REFERENCE_TIME rt);
+ CDSMSplitterFile(IAsyncReader* pReader, HRESULT& hr, IDSMResourceBagImpl& res, IDSMChapterBagImpl& chap);
+
+ CAtlMap<BYTE, CMediaType> m_mts;
+ REFERENCE_TIME m_rtFirst, m_rtDuration;
+
+ struct SyncPoint {REFERENCE_TIME rt; __int64 fp;};
+ CAtlArray<SyncPoint> m_sps;
+
+ typedef CAtlMap<CStringA, CStringW, CStringElementTraits<CStringA>, CStringElementTraits<CStringW> > CStreamInfoMap;
+ CStreamInfoMap m_fim;
+ CAtlMap<BYTE, CStreamInfoMap> m_sim;
+
+ bool Sync(dsmp_t& type, UINT64& len, __int64 limit = 65536);
+ bool Sync(UINT64& syncpos, dsmp_t& type, UINT64& len, __int64 limit = 65536);
+ bool Read(__int64 len, BYTE& id, CMediaType& mt);
+ bool Read(__int64 len, Packet* p, bool fData = true);
+ bool Read(__int64 len, CAtlArray<SyncPoint>& sps);
+ bool Read(__int64 len, CStreamInfoMap& im);
+ bool Read(__int64 len, IDSMResourceBagImpl& res);
+ bool Read(__int64 len, IDSMChapterBagImpl& chap);
+ __int64 Read(__int64 len, CStringW& str);
+
+ __int64 FindSyncPoint(REFERENCE_TIME rt);
};
diff --git a/src/filters/parser/DSMSplitter/resource.h b/src/filters/parser/DSMSplitter/resource.h
index 003e79ee4..66d1331cb 100644
--- a/src/filters/parser/DSMSplitter/resource.h
+++ b/src/filters/parser/DSMSplitter/resource.h
@@ -3,7 +3,7 @@
// Used by DSMSplitter.rc
// Next default values for new objects
-//
+//
#ifdef APSTUDIO_INVOKED
#ifndef APSTUDIO_READONLY_SYMBOLS
#define _APS_NEXT_RESOURCE_VALUE 101
diff --git a/src/filters/parser/DSMSplitter/stdafx.cpp b/src/filters/parser/DSMSplitter/stdafx.cpp
index 0046e7260..0a00e1846 100644
--- a/src/filters/parser/DSMSplitter/stdafx.cpp
+++ b/src/filters/parser/DSMSplitter/stdafx.cpp
@@ -1,4 +1,4 @@
-/*
+/*
* Copyright (C) 2003-2006 Gabest
* http://www.gabest.org
*
@@ -6,15 +6,15 @@
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2, or (at your option)
* any later version.
- *
+ *
* This Program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with GNU Make; see the file COPYING. If not, write to
- * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
+ * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
* http://www.gnu.org/copyleft/gpl.html
*
*/
diff --git a/src/filters/parser/DSMSplitter/stdafx.h b/src/filters/parser/DSMSplitter/stdafx.h
index 089cf8fa0..e8beccd47 100644
--- a/src/filters/parser/DSMSplitter/stdafx.h
+++ b/src/filters/parser/DSMSplitter/stdafx.h
@@ -1,4 +1,4 @@
-/*
+/*
* Copyright (C) 2003-2006 Gabest
* http://www.gabest.org
*
@@ -6,15 +6,15 @@
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2, or (at your option)
* any later version.
- *
+ *
* This Program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with GNU Make; see the file COPYING. If not, write to
- * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
+ * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
* http://www.gnu.org/copyleft/gpl.html
*
*/
diff --git a/src/filters/parser/DiracSplitter/DiracSplitter.cpp b/src/filters/parser/DiracSplitter/DiracSplitter.cpp
index b9e3cc8b7..db544603f 100644
--- a/src/filters/parser/DiracSplitter/DiracSplitter.cpp
+++ b/src/filters/parser/DiracSplitter/DiracSplitter.cpp
@@ -1,4 +1,4 @@
-/*
+/*
* Copyright (C) 2003-2004 Gabest
* http://www.gabest.org
*
@@ -6,15 +6,15 @@
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2, or (at your option)
* any later version.
- *
+ *
* This Program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with GNU Make; see the file COPYING. If not, write to
- * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
+ * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
* http://www.gnu.org/copyleft/gpl.html
*
*/
@@ -28,7 +28,7 @@
#ifdef REGISTER_FILTER
const AMOVIESETUP_MEDIATYPE sudPinTypesIn[] =
-{
+{
{&MEDIATYPE_Stream, &MEDIASUBTYPE_Dirac},
{&MEDIATYPE_Stream, &MEDIASUBTYPE_NULL}
};
@@ -74,8 +74,8 @@ int g_cTemplates = countof(g_Templates);
STDAPI DllRegisterServer()
{
RegisterSourceFilter(
- CLSID_AsyncReader,
- MEDIASUBTYPE_Dirac,
+ CLSID_AsyncReader,
+ MEDIASUBTYPE_Dirac,
_T("0,8,,4B572D4449524143"), // KW-DIRAC
_T(".drc"), NULL);
@@ -107,7 +107,7 @@ STDMETHODIMP CDiracSplitterFilter::NonDelegatingQueryInterface(REFIID riid, void
{
CheckPointer(ppv, E_POINTER);
- return
+ return
__super::NonDelegatingQueryInterface(riid, ppv);
}
@@ -121,11 +121,7 @@ HRESULT CDiracSplitterFilter::CreateOutputs(IAsyncReader* pAsyncReader)
m_pFile.Attach(DNew CDiracSplitterFile(pAsyncReader, hr));
if(!m_pFile) return E_OUTOFMEMORY;
- if(FAILED(hr))
- {
- m_pFile.Free();
- return hr;
- }
+ if(FAILED(hr)) {m_pFile.Free(); return hr;}
CAtlArray<CMediaType> mts;
mts.Add(m_pFile->GetMediaType());
@@ -162,7 +158,7 @@ void CDiracSplitterFilter::DemuxSeek(REFERENCE_TIME rt)
// TODO
__int64 len = m_pFile->GetLength();
- __int64 seekpos = (__int64)(1.0 * rt / m_rtDuration * len);
+ __int64 seekpos = (__int64)(1.0*rt/m_rtDuration*len);
m_pFile->Seek(seekpos);
seekpos = 0;
@@ -176,11 +172,7 @@ void CDiracSplitterFilter::DemuxSeek(REFERENCE_TIME rt)
for(int j = 0; j < 10; j++)
{
while(m_pFile->Next(code) && code != AU_START_CODE);
- if(code != AU_START_CODE)
- {
- m_pFile->Seek(seekpos >>= 1);
- continue;
- }
+ if(code != AU_START_CODE) {m_pFile->Seek(seekpos >>= 1); continue;}
__int64 pos = m_pFile->GetPos() - 5;
@@ -194,7 +186,7 @@ void CDiracSplitterFilter::DemuxSeek(REFERENCE_TIME rt)
break;
}
- m_pFile->Seek(pos - (__int64)(1.0 * dt / m_rtDuration * len));
+ m_pFile->Seek(pos - (__int64)(1.0*dt/m_rtDuration*len));
pdt = dt;
}
@@ -222,7 +214,7 @@ bool CDiracSplitterFilter::DemuxLoop()
memcpy(p->GetData(), pBuff, size);
p->TrackNumber = 0;
- p->rtStart = rtAvgTimePerFrame * fnum;
+ p->rtStart = rtAvgTimePerFrame*fnum;
p->rtStop = p->rtStart + rtAvgTimePerFrame;
p->bSyncPoint = code == AU_START_CODE;
@@ -283,8 +275,7 @@ void CDiracVideoDecoder::FreeDecoder()
{
dirac_decoder_close((dirac_decoder_t*)m_decoder);
m_decoder = NULL;
- delete [] m_pYUV[0];
- m_pYUV[0] = NULL;
+ delete [] m_pYUV[0]; m_pYUV[0] = NULL;
}
}
@@ -304,7 +295,7 @@ HRESULT CDiracVideoDecoder::Receive(IMediaSample* pIn)
long len = pIn->GetActualDataLength();
if(len <= 0) return S_OK; // nothing to do
- if(pIn->IsDiscontinuity() == S_OK)
+ if(pIn->IsDiscontinuity() == S_OK)
InitDecoder();
dirac_decoder_t* decoder = (dirac_decoder_t*)m_decoder;
@@ -326,7 +317,7 @@ HRESULT CDiracVideoDecoder::Receive(IMediaSample* pIn)
{
DIRACINFOHEADER* dvih = (DIRACINFOHEADER*)m_pInput->CurrentMediaType().Format();
if(dvih->hdr.bmiHeader.biWidth != decoder->src_params.width
- || dvih->hdr.bmiHeader.biHeight != decoder->src_params.height)
+ || dvih->hdr.bmiHeader.biHeight != decoder->src_params.height)
return E_FAIL; // hmm
}
@@ -335,14 +326,13 @@ HRESULT CDiracVideoDecoder::Receive(IMediaSample* pIn)
int w = decoder->src_params.width;
int h = decoder->src_params.height;
int wc = decoder->src_params.chroma_width;
- int hc = decoder->src_params.chroma_height;
- delete [] m_pYUV[0];
- m_pYUV[0] = NULL;
+ int hc = decoder->src_params.chroma_height;
+ delete [] m_pYUV[0]; m_pYUV[0] = NULL;
m_pYUV[0] = DNew BYTE[w*h + wc*hc*2 + w/2*h/2];
- m_pYUV[1] = m_pYUV[0] + w * h;
- m_pYUV[2] = m_pYUV[1] + wc * hc;
- m_pYUV[3] = m_pYUV[2] + wc * hc;
- memset(m_pYUV[3], 0x80, w / 2 * h / 2);
+ m_pYUV[1] = m_pYUV[0] + w*h;
+ m_pYUV[2] = m_pYUV[1] + wc*hc;
+ m_pYUV[3] = m_pYUV[2] + wc*hc;
+ memset(m_pYUV[3], 0x80, w/2*h/2);
m_rtAvgTimePerFrame = 10000000i64 * decoder->src_params.frame_rate.denominator / decoder->src_params.frame_rate.numerator;
dirac_set_buf(decoder, m_pYUV, NULL);
}
@@ -379,7 +369,7 @@ HRESULT CDiracVideoDecoder::Deliver(IMediaSample* pIn, REFERENCE_TIME rtStart, R
CComPtr<IMediaSample> pOut;
BYTE* pDataOut = NULL;
if(FAILED(hr = m_pOutput->GetDeliveryBuffer(&pOut, NULL, NULL, 0))
- || FAILED(hr = pOut->GetPointer(&pDataOut)))
+ || FAILED(hr = pOut->GetPointer(&pDataOut)))
return hr;
AM_MEDIA_TYPE* pmt;
@@ -423,28 +413,28 @@ void CDiracVideoDecoder::Copy(BYTE* pOut)
int pitchIn = w;
BYTE* pY = m_pYUV[0];
- BYTE* pU = w / 2 == wc && h / 2 == hc ? m_pYUV[1] : m_pYUV[3]; // FIXME
- BYTE* pV = w / 2 == wc && h / 2 == hc ? m_pYUV[2] : m_pYUV[3]; // FIXME
+ BYTE* pU = w/2 == wc && h/2 == hc ? m_pYUV[1] : m_pYUV[3]; // FIXME
+ BYTE* pV = w/2 == wc && h/2 == hc ? m_pYUV[2] : m_pYUV[3]; // FIXME
if(bihOut.biCompression == '2YUY')
{
- BitBltFromI420ToYUY2(w, h, pOut, bihOut.biWidth * 2, pY, pU, pV, pitchIn);
+ BitBltFromI420ToYUY2(w, h, pOut, bihOut.biWidth*2, pY, pU, pV, pitchIn);
}
else if(bihOut.biCompression == 'I420' || bihOut.biCompression == 'VUYI')
{
- BitBltFromI420ToI420(w, h, pOut, pOut + bihOut.biWidth * h, pOut + bihOut.biWidth * h * 5 / 4, bihOut.biWidth, pY, pU, pV, pitchIn);
+ BitBltFromI420ToI420(w, h, pOut, pOut + bihOut.biWidth*h, pOut + bihOut.biWidth*h*5/4, bihOut.biWidth, pY, pU, pV, pitchIn);
}
else if(bihOut.biCompression == '21VY')
{
- BitBltFromI420ToI420(w, h, pOut, pOut + bihOut.biWidth * h * 5 / 4, pOut + bihOut.biWidth * h, bihOut.biWidth, pY, pU, pV, pitchIn);
+ BitBltFromI420ToI420(w, h, pOut, pOut + bihOut.biWidth*h*5/4, pOut + bihOut.biWidth*h, bihOut.biWidth, pY, pU, pV, pitchIn);
}
else if(bihOut.biCompression == BI_RGB || bihOut.biCompression == BI_BITFIELDS)
{
- int pitchOut = bihOut.biWidth * bihOut.biBitCount >> 3;
+ int pitchOut = bihOut.biWidth*bihOut.biBitCount>>3;
if(bihOut.biHeight > 0)
{
- pOut += pitchOut * (h - 1);
+ pOut += pitchOut*(h-1);
pitchOut = -pitchOut;
}
@@ -460,10 +450,10 @@ HRESULT CDiracVideoDecoder::CheckInputType(const CMediaType* mtIn)
{
DIRACINFOHEADER* dvih = (DIRACINFOHEADER*)mtIn->Format();
- if(mtIn->majortype != MEDIATYPE_Video
- || mtIn->subtype != MEDIASUBTYPE_DiracVideo
- || mtIn->formattype != FORMAT_DiracVideoInfo
- || (dvih->hdr.bmiHeader.biWidth & 1) || (dvih->hdr.bmiHeader.biHeight & 1))
+ if(mtIn->majortype != MEDIATYPE_Video
+ || mtIn->subtype != MEDIASUBTYPE_DiracVideo
+ || mtIn->formattype != FORMAT_DiracVideoInfo
+ || (dvih->hdr.bmiHeader.biWidth&1) || (dvih->hdr.bmiHeader.biHeight&1))
return VFW_E_TYPE_NOT_ACCEPTED;
return S_OK;
@@ -475,22 +465,22 @@ HRESULT CDiracVideoDecoder::CheckTransform(const CMediaType* mtIn, const CMediaT
{
BITMAPINFOHEADER bih1, bih2;
if(ExtractBIH(mtOut, &bih1) && ExtractBIH(&m_pOutput->CurrentMediaType(), &bih2)
- && abs(bih1.biHeight) != abs(bih2.biHeight))
+ && abs(bih1.biHeight) != abs(bih2.biHeight))
return VFW_E_TYPE_NOT_ACCEPTED;
}
return mtIn->majortype == MEDIATYPE_Video && mtIn->subtype == MEDIASUBTYPE_DiracVideo
- && mtOut->majortype == MEDIATYPE_Video && (mtOut->subtype == MEDIASUBTYPE_YUY2
- || mtOut->subtype == MEDIASUBTYPE_YV12
- || mtOut->subtype == MEDIASUBTYPE_I420
- || mtOut->subtype == MEDIASUBTYPE_IYUV
- || mtOut->subtype == MEDIASUBTYPE_ARGB32
- || mtOut->subtype == MEDIASUBTYPE_RGB32
- || mtOut->subtype == MEDIASUBTYPE_RGB24
- || mtOut->subtype == MEDIASUBTYPE_RGB565
- || mtOut->subtype == MEDIASUBTYPE_RGB555)
- ? S_OK
- : VFW_E_TYPE_NOT_ACCEPTED;
+ && mtOut->majortype == MEDIATYPE_Video && (mtOut->subtype == MEDIASUBTYPE_YUY2
+ || mtOut->subtype == MEDIASUBTYPE_YV12
+ || mtOut->subtype == MEDIASUBTYPE_I420
+ || mtOut->subtype == MEDIASUBTYPE_IYUV
+ || mtOut->subtype == MEDIASUBTYPE_ARGB32
+ || mtOut->subtype == MEDIASUBTYPE_RGB32
+ || mtOut->subtype == MEDIASUBTYPE_RGB24
+ || mtOut->subtype == MEDIASUBTYPE_RGB565
+ || mtOut->subtype == MEDIASUBTYPE_RGB555)
+ ? S_OK
+ : VFW_E_TYPE_NOT_ACCEPTED;
}
HRESULT CDiracVideoDecoder::DecideBufferSize(IMemAllocator* pAllocator, ALLOCATOR_PROPERTIES* pProperties)
@@ -507,24 +497,19 @@ HRESULT CDiracVideoDecoder::DecideBufferSize(IMemAllocator* pAllocator, ALLOCATO
HRESULT hr;
ALLOCATOR_PROPERTIES Actual;
- if(FAILED(hr = pAllocator->SetProperties(pProperties, &Actual)))
+ if(FAILED(hr = pAllocator->SetProperties(pProperties, &Actual)))
return hr;
return(pProperties->cBuffers > Actual.cBuffers || pProperties->cbBuffer > Actual.cbBuffer
- ? E_FAIL
- : NOERROR);
+ ? E_FAIL
+ : NOERROR);
}
HRESULT CDiracVideoDecoder::GetMediaType(int iPosition, CMediaType* pmt)
{
if(m_pInput->IsConnected() == FALSE) return E_UNEXPECTED;
- struct
- {
- const GUID* subtype;
- WORD biPlanes, biBitCount;
- DWORD biCompression;
- } fmts[] =
+ struct {const GUID* subtype; WORD biPlanes, biBitCount; DWORD biCompression;} fmts[] =
{
{&MEDIASUBTYPE_YV12, 3, 12, '21VY'},
{&MEDIASUBTYPE_I420, 3, 12, '024I'},
@@ -543,10 +528,10 @@ HRESULT CDiracVideoDecoder::GetMediaType(int iPosition, CMediaType* pmt)
};
if(m_pInput->CurrentMediaType().formattype == FORMAT_VideoInfo)
- iPosition = iPosition * 2 + 1;
+ iPosition = iPosition*2 + 1;
if(iPosition < 0) return E_INVALIDARG;
- if(iPosition >= 2 * countof(fmts)) return VFW_S_NO_MORE_ITEMS;
+ if(iPosition >= 2*countof(fmts)) return VFW_S_NO_MORE_ITEMS;
BITMAPINFOHEADER bih;
ExtractBIH(&m_pInput->CurrentMediaType(), &bih);
@@ -562,9 +547,9 @@ HRESULT CDiracVideoDecoder::GetMediaType(int iPosition, CMediaType* pmt)
bihOut.biPlanes = fmts[iPosition/2].biPlanes;
bihOut.biBitCount = fmts[iPosition/2].biBitCount;
bihOut.biCompression = fmts[iPosition/2].biCompression;
- bihOut.biSizeImage = bih.biWidth * bih.biHeight * bihOut.biBitCount >> 3;
+ bihOut.biSizeImage = bih.biWidth*bih.biHeight*bihOut.biBitCount>>3;
- if(iPosition & 1)
+ if(iPosition&1)
{
pmt->formattype = FORMAT_VideoInfo;
VIDEOINFOHEADER* vih = (VIDEOINFOHEADER*)pmt->AllocFormatBuffer(sizeof(VIDEOINFOHEADER));
@@ -575,7 +560,7 @@ HRESULT CDiracVideoDecoder::GetMediaType(int iPosition, CMediaType* pmt)
{
vih->bmiHeader.biWidth = ((VIDEOINFOHEADER2*)m_pInput->CurrentMediaType().Format())->dwPictAspectRatioX;
vih->bmiHeader.biHeight = ((VIDEOINFOHEADER2*)m_pInput->CurrentMediaType().Format())->dwPictAspectRatioY;
- vih->bmiHeader.biSizeImage = vih->bmiHeader.biWidth * vih->bmiHeader.biHeight * vih->bmiHeader.biBitCount >> 3;
+ vih->bmiHeader.biSizeImage = vih->bmiHeader.biWidth*vih->bmiHeader.biHeight*vih->bmiHeader.biBitCount>>3;
}
}
else
@@ -617,7 +602,7 @@ HRESULT CDiracVideoDecoder::NewSegment(REFERENCE_TIME tStart, REFERENCE_TIME tSt
HRESULT CDiracVideoDecoder::AlterQuality(Quality q)
{
- if(q.Late > 500 * 10000i64) m_fDropFrames = true;
+ if(q.Late > 500*10000i64) m_fDropFrames = true;
if(q.Late <= 0) m_fDropFrames = false;
return E_NOTIMPL;
}
diff --git a/src/filters/parser/DiracSplitter/DiracSplitter.h b/src/filters/parser/DiracSplitter/DiracSplitter.h
index 4b3915ba2..0ed5d14cb 100644
--- a/src/filters/parser/DiracSplitter/DiracSplitter.h
+++ b/src/filters/parser/DiracSplitter/DiracSplitter.h
@@ -1,4 +1,4 @@
-/*
+/*
* Copyright (C) 2003-2006 Gabest
* http://www.gabest.org
*
@@ -6,15 +6,15 @@
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2, or (at your option)
* any later version.
- *
+ *
* This Program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with GNU Make; see the file COPYING. If not, write to
- * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
+ * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
* http://www.gnu.org/copyleft/gpl.html
*
*/
@@ -28,17 +28,17 @@
class CDiracSplitterFilter : public CBaseSplitterFilter
{
protected:
- CAutoPtr<CDiracSplitterFile> m_pFile;
- HRESULT CreateOutputs(IAsyncReader* pAsyncReader);
+ CAutoPtr<CDiracSplitterFile> m_pFile;
+ HRESULT CreateOutputs(IAsyncReader* pAsyncReader);
- bool DemuxInit();
- void DemuxSeek(REFERENCE_TIME rt);
- bool DemuxLoop();
+ bool DemuxInit();
+ void DemuxSeek(REFERENCE_TIME rt);
+ bool DemuxLoop();
public:
- CDiracSplitterFilter(LPUNKNOWN pUnk, HRESULT* phr);
+ CDiracSplitterFilter(LPUNKNOWN pUnk, HRESULT* phr);
- DECLARE_IUNKNOWN
+ DECLARE_IUNKNOWN
STDMETHODIMP NonDelegatingQueryInterface(REFIID riid, void** ppv);
};
@@ -46,35 +46,35 @@ public:
class CDiracSourceFilter : public CDiracSplitterFilter
{
public:
- CDiracSourceFilter(LPUNKNOWN pUnk, HRESULT* phr);
+ CDiracSourceFilter(LPUNKNOWN pUnk, HRESULT* phr);
};
[uuid("F78CF248-180E-4713-B107-B13F7B5C31E1")]
class CDiracVideoDecoder : public CTransformFilter
{
void* m_decoder; // dirac_decoder_t*
- void InitDecoder(), FreeDecoder();
- BYTE* m_pYUV[4];
- bool m_fDropFrames;
- REFERENCE_TIME m_tStart, m_rtAvgTimePerFrame;
+ void InitDecoder(), FreeDecoder();
+ BYTE* m_pYUV[4];
+ bool m_fDropFrames;
+ REFERENCE_TIME m_tStart, m_rtAvgTimePerFrame;
- HRESULT Deliver(IMediaSample* pIn, REFERENCE_TIME rtStart, REFERENCE_TIME rtStop);
- void Copy(BYTE* pOut);
+ HRESULT Deliver(IMediaSample* pIn, REFERENCE_TIME rtStart, REFERENCE_TIME rtStop);
+ void Copy(BYTE* pOut);
public:
- CDiracVideoDecoder(LPUNKNOWN lpunk, HRESULT* phr);
- virtual ~CDiracVideoDecoder();
+ CDiracVideoDecoder(LPUNKNOWN lpunk, HRESULT* phr);
+ virtual ~CDiracVideoDecoder();
- HRESULT Receive(IMediaSample* pIn);
- HRESULT CheckInputType(const CMediaType* mtIn);
- HRESULT CheckTransform(const CMediaType* mtIn, const CMediaType* mtOut);
- HRESULT DecideBufferSize(IMemAllocator* pAllocator, ALLOCATOR_PROPERTIES* pProperties);
- HRESULT GetMediaType(int iPosition, CMediaType* pMediaType);
+ HRESULT Receive(IMediaSample* pIn);
+ HRESULT CheckInputType(const CMediaType* mtIn);
+ HRESULT CheckTransform(const CMediaType* mtIn, const CMediaType* mtOut);
+ HRESULT DecideBufferSize(IMemAllocator* pAllocator, ALLOCATOR_PROPERTIES* pProperties);
+ HRESULT GetMediaType(int iPosition, CMediaType* pMediaType);
- HRESULT StartStreaming();
- HRESULT StopStreaming();
+ HRESULT StartStreaming();
+ HRESULT StopStreaming();
HRESULT NewSegment(REFERENCE_TIME tStart, REFERENCE_TIME tStop, double dRate);
- HRESULT AlterQuality(Quality q);
+ HRESULT AlterQuality(Quality q);
}; \ No newline at end of file
diff --git a/src/filters/parser/DiracSplitter/DiracSplitterFile.cpp b/src/filters/parser/DiracSplitter/DiracSplitterFile.cpp
index 7bae7f357..de3b42b45 100644
--- a/src/filters/parser/DiracSplitter/DiracSplitterFile.cpp
+++ b/src/filters/parser/DiracSplitter/DiracSplitterFile.cpp
@@ -18,11 +18,11 @@ HRESULT CDiracSplitterFile::Init()
HRESULT hr = E_FAIL;
Seek(0);
-
+
// Dirac streams are no longer preceded with KW-DIRAC
//UINT64 hdr;
//if(FAILED(Read((BYTE*)&hdr, sizeof(hdr))) || hdr != 0x43415249442D574Bui64) // KW-DIRAC
- //return E_FAIL;
+ //return E_FAIL;
dirac_decoder_t* decoder = dirac_decoder_init(0);
@@ -31,20 +31,12 @@ HRESULT CDiracSplitterFile::Init()
while(GetPos() < limit)
{
BYTE b;
- if(!Next(b))
- {
- ASSERT(0);
- break;
- }
+ if(!Next(b)) {ASSERT(0); break;}
if(b == AU_START_CODE)
{
__int64 pos = GetPos() - 13; //Parse info size = 13
- if(!Next(b))
- {
- ASSERT(0);
- break;
- }
+ if(!Next(b)) {ASSERT(0); break;}
__int64 len = GetPos() - pos;
Seek(pos);
@@ -61,14 +53,10 @@ HRESULT CDiracSplitterFile::Init()
dirac_buffer(decoder, (BYTE*)&dvih->dwSequenceHeader[0], (BYTE*)&dvih->dwSequenceHeader[0] + len);
DecoderState dec_state = dirac_parse(decoder);
- if(dec_state != STATE_SEQUENCE)
- {
- ASSERT(0);
- break;
- }
+ if(dec_state != STATE_SEQUENCE) {ASSERT(0); break;}
if(decoder->src_params.frame_rate.denominator)
- dvih->hdr.AvgTimePerFrame = 10000000i64 * decoder->src_params.frame_rate.denominator / decoder->src_params.frame_rate.numerator;
+ dvih->hdr.AvgTimePerFrame = 10000000i64 * decoder->src_params.frame_rate.denominator / decoder->src_params.frame_rate.numerator;
dvih->hdr.bmiHeader.biSize = sizeof(dvih->hdr.bmiHeader);
dvih->hdr.bmiHeader.biWidth = decoder->src_params.width;
dvih->hdr.bmiHeader.biHeight = decoder->src_params.height;
@@ -94,7 +82,7 @@ HRESULT CDiracSplitterFile::Init()
}
UINT64 CDiracSplitterFile::UnsignedGolombDecode()
-{
+{
int M = 0;
while(M < 64 && !BitRead(1))
M++;
@@ -103,7 +91,7 @@ UINT64 CDiracSplitterFile::UnsignedGolombDecode()
for(int i = 0; i < M; i++)
info |= BitRead(1) << i;
- return (1ui64 << M) - 1 + info;
+ return (1ui64<<M)-1 + info;
}
bool CDiracSplitterFile::Next(BYTE& code, __int64 len)
@@ -115,10 +103,10 @@ bool CDiracSplitterFile::Next(BYTE& code, __int64 len)
if(len-- == 0 || GetPos() >= GetLength()) return(false);
qw = (qw << 8) | (BYTE)BitRead(8);
}
- while((qw & 0xffffffff00) != ((UINT64)START_CODE_PREFIX << 8));
+ while((qw&0xffffffff00) != ((UINT64)START_CODE_PREFIX<<8));
int size_bytes = 0;
// Read in the 6 bytes of next and previous parse unit offsets.
- while(size_bytes < 6)
+ while (size_bytes < 6)
{
if(len-- == 0 || GetPos() >= GetLength()) return(false);
BitRead(8);
@@ -143,7 +131,7 @@ const BYTE* CDiracSplitterFile::NextBlock(BYTE& code, int& size, int& fnum)
if(size == 0)
{
- if((qw & 0xffffffff00) == ((UINT64)START_CODE_PREFIX << 8))
+ if((qw & 0xffffffff00) == ((UINT64)START_CODE_PREFIX<<8) )
code = (BYTE)(qw & 0xff);
if(isFrameStartCode(code))
@@ -157,14 +145,14 @@ const BYTE* CDiracSplitterFile::NextBlock(BYTE& code, int& size, int& fnum)
}
else
{
- if((qw & 0xffffffff00) == ((UINT64)START_CODE_PREFIX << 8))
+ if((qw & 0xffffffff00) == ((UINT64)START_CODE_PREFIX<<8))
break;
}
}
if(size >= m_pBuff.GetSize())
{
- int newsize = max(1024, size * 2);
+ int newsize = max(1024, size*2);
m_pBuff.SetSize(newsize, newsize);
pBuff = m_pBuff.GetData();
}
diff --git a/src/filters/parser/DiracSplitter/DiracSplitterFile.h b/src/filters/parser/DiracSplitter/DiracSplitterFile.h
index a69e61fb1..cc2ec185a 100644
--- a/src/filters/parser/DiracSplitter/DiracSplitterFile.h
+++ b/src/filters/parser/DiracSplitter/DiracSplitterFile.h
@@ -7,27 +7,21 @@
class CDiracSplitterFile : public CBaseSplitterFile
{
- CMediaType m_mt;
- REFERENCE_TIME m_rtDuration;
- CArray<BYTE> m_pBuff;
+ CMediaType m_mt;
+ REFERENCE_TIME m_rtDuration;
+ CArray<BYTE> m_pBuff;
- HRESULT Init();
+ HRESULT Init();
public:
- CDiracSplitterFile(IAsyncReader* pAsyncReader, HRESULT& hr);
+ CDiracSplitterFile(IAsyncReader* pAsyncReader, HRESULT& hr);
// using CBaseSplitterFile::Read;
- bool Next(BYTE& code, __int64 len = -1);
- const BYTE* NextBlock(BYTE& code, int& size, int& fnum);
- UINT64 UnsignedGolombDecode();
+ bool Next(BYTE& code, __int64 len = -1);
+ const BYTE* NextBlock(BYTE& code, int& size, int& fnum);
+ UINT64 UnsignedGolombDecode();
- const CMediaType& GetMediaType()
- {
- return m_mt;
- }
- REFERENCE_TIME GetDuration()
- {
- return m_rtDuration;
- }
+ const CMediaType& GetMediaType() {return m_mt;}
+ REFERENCE_TIME GetDuration() {return m_rtDuration;}
};
diff --git a/src/filters/parser/DiracSplitter/libdirac/libdirac_byteio/accessunit_byteio.cpp b/src/filters/parser/DiracSplitter/libdirac/libdirac_byteio/accessunit_byteio.cpp
index 8248a0003..33bb8ff9f 100644
--- a/src/filters/parser/DiracSplitter/libdirac/libdirac_byteio/accessunit_byteio.cpp
+++ b/src/filters/parser/DiracSplitter/libdirac/libdirac_byteio/accessunit_byteio.cpp
@@ -42,40 +42,40 @@
using namespace dirac;
// Constructor for encoding
-SequenceHeaderByteIO::SequenceHeaderByteIO(SourceParams& src_params,
- EncoderParams& enc_params):
- ParseUnitByteIO(),
- m_parseparams_byteio(*this, m_parse_params, enc_params),
+SequenceHeaderByteIO::SequenceHeaderByteIO( SourceParams& src_params,
+ EncoderParams& enc_params):
+ParseUnitByteIO(),
+m_parseparams_byteio(*this, m_parse_params, enc_params),
// create default source parameters for comparisions
- m_default_src_params(src_params.GetVideoFormat()),
- m_src_params(src_params),
- m_sourceparams_byteio(m_src_params,
- m_default_src_params,
- *this),
- m_codec_params(enc_params),
- m_codingparams_byteio(m_src_params,
- m_codec_params,
- m_default_src_params,
- *this)
+m_default_src_params(src_params.GetVideoFormat()),
+m_src_params(src_params),
+m_sourceparams_byteio( m_src_params,
+ m_default_src_params,
+ *this),
+m_codec_params(enc_params),
+m_codingparams_byteio(m_src_params,
+ m_codec_params,
+ m_default_src_params,
+ *this)
{
}
// Constructor for decoding
SequenceHeaderByteIO::SequenceHeaderByteIO(const ParseUnitByteIO& parseunit_byteio,
- ParseParams& parse_params,
- SourceParams& src_params,
- CodecParams& codec_params) :
- ParseUnitByteIO(parseunit_byteio),
- m_parseparams_byteio(parseunit_byteio, parse_params),
- m_src_params(src_params),
- m_sourceparams_byteio(m_src_params,
- m_default_src_params,
- parseunit_byteio),
- m_codec_params(codec_params),
- m_codingparams_byteio(m_src_params,
- m_codec_params,
- m_default_src_params,
- parseunit_byteio)
+ ParseParams& parse_params,
+ SourceParams& src_params,
+ CodecParams& codec_params) :
+ParseUnitByteIO(parseunit_byteio),
+m_parseparams_byteio( parseunit_byteio, parse_params),
+m_src_params(src_params),
+m_sourceparams_byteio( m_src_params,
+ m_default_src_params,
+ parseunit_byteio),
+m_codec_params(codec_params),
+m_codingparams_byteio( m_src_params,
+ m_codec_params,
+ m_default_src_params,
+ parseunit_byteio)
{
}
@@ -84,7 +84,7 @@ SequenceHeaderByteIO::~SequenceHeaderByteIO()
}
//-----public------------------------------------------------------
-bool SequenceHeaderByteIO::Input()
+bool SequenceHeaderByteIO::Input()
{
//int o=mp_stream->tellg();
InputParseParams();
@@ -92,22 +92,22 @@ bool SequenceHeaderByteIO::Input()
// Inout Video format
SetByteParams(m_parseparams_byteio);
VideoFormat vf = IntToVideoFormat(ReadUint());
- if(vf == VIDEO_FORMAT_UNDEFINED)
- DIRAC_THROW_EXCEPTION(
- ERR_INVALID_VIDEO_FORMAT,
- "Dirac does not recognise the specified video-format",
- SEVERITY_ACCESSUNIT_ERROR);
+ if(vf==VIDEO_FORMAT_UNDEFINED)
+ DIRAC_THROW_EXCEPTION(
+ ERR_INVALID_VIDEO_FORMAT,
+ "Dirac does not recognise the specified video-format",
+ SEVERITY_ACCESSUNIT_ERROR);
SourceParams src_params(vf, true);
m_src_params = src_params;
-
+
InputSourceParams();
-
+
CodecParams codec_params(vf);
m_codec_params = codec_params;
-
+
InputCodingParams();
-
+
return true;
}
@@ -122,15 +122,15 @@ void SequenceHeaderByteIO::Output()
OutputSourceParams();
OutputCodingParams();
-
+
}
int SequenceHeaderByteIO::GetSize() const
{
- return ParseUnitByteIO::GetSize() +
- m_parseparams_byteio.GetSize() +
- ByteIO::GetSize() +
- m_sourceparams_byteio.GetSize() +
+ return ParseUnitByteIO::GetSize()+
+ m_parseparams_byteio.GetSize()+
+ ByteIO::GetSize() +
+ m_sourceparams_byteio.GetSize()+
m_codingparams_byteio.GetSize();
}
@@ -150,7 +150,7 @@ unsigned char SequenceHeaderByteIO::CalcParseCode() const
void SequenceHeaderByteIO::InputSourceParams()
{
- // copy current input params
+ // copy current input params
m_sourceparams_byteio.SetByteParams(*this);
m_sourceparams_byteio.Input();
diff --git a/src/filters/parser/DiracSplitter/libdirac/libdirac_byteio/accessunit_byteio.h b/src/filters/parser/DiracSplitter/libdirac/libdirac_byteio/accessunit_byteio.h
index 346bd4110..2c2966ed8 100644
--- a/src/filters/parser/DiracSplitter/libdirac/libdirac_byteio/accessunit_byteio.h
+++ b/src/filters/parser/DiracSplitter/libdirac/libdirac_byteio/accessunit_byteio.h
@@ -50,135 +50,132 @@
namespace dirac
{
-/**
-* A random access point within a Dirac bytestream
-*/
-class SequenceHeaderByteIO : public ParseUnitByteIO
-{
-public:
-
/**
- * Constructor (encoding)
- *@param src_params Source parameters for current AccessUnit
- *@param enc_params Encoder parameters for current AccessUnit
+ * A random access point within a Dirac bytestream
*/
- SequenceHeaderByteIO(SourceParams& src_params,
- EncoderParams& enc_params);
-
- /**
- * Constructor (decoding)
- *@param parseunit_byteio Source of data
- *@param parse_params Destination of parse paramters data
- *@param src_params Destination of source paramters data
- *@param codec_params Destination of coding paramters data
- */
- SequenceHeaderByteIO(const ParseUnitByteIO& parseunit_byteio,
+ class SequenceHeaderByteIO : public ParseUnitByteIO
+ {
+ public:
+
+ /**
+ * Constructor (encoding)
+ *@param src_params Source parameters for current AccessUnit
+ *@param enc_params Encoder parameters for current AccessUnit
+ */
+ SequenceHeaderByteIO( SourceParams& src_params,
+ EncoderParams& enc_params);
+
+ /**
+ * Constructor (decoding)
+ *@param parseunit_byteio Source of data
+ *@param parse_params Destination of parse paramters data
+ *@param src_params Destination of source paramters data
+ *@param codec_params Destination of coding paramters data
+ */
+ SequenceHeaderByteIO(const ParseUnitByteIO& parseunit_byteio,
ParseParams& parse_params,
SourceParams& src_params,
CodecParams& codec_params);
- /**
- * Destructor
- */
- ~SequenceHeaderByteIO();
-
- /**
- * Parses data in Dirac-stream format (decoding)
- */
- bool Input();
-
- /**
- * Writes access-unit info to Dirac stream-format (encoding)
- */
- void Output();
-
- /*
- * Gets size of access-unit (in bytes)
- */
- int GetSize() const;
-
- /**
- * Gets parse-unit type
- */
- ParseUnitType GetType() const
- {
- return PU_SEQ_HEADER;
- }
-
-private:
-
- /**
- * Calculates parse-code based on access-unit parameters (encoding)
- *@return Char bit-set
- */
- unsigned char CalcParseCode() const;
-
- /**
- * Parse source attributes from bytestream-compatible input (decoding)
- */
- void InputSourceParams();
-
- /**
- * Parse parse attributes from bytestream-compatible input (decoding)
- */
- void InputParseParams();
-
- /**
- * Parse Coding attributes from bytestream-compatible input (decoding)
- */
- void InputCodingParams();
-
- /**
- * Output source attributes for bytestream-compatible output (encoding)
- */
- void OutputSourceParams();
-
- /**
- * Output parse attributes for bytestream-compatible output (encoding)
- */
- void OutputParseParams();
-
- /**
- * Output coding attributes for bytestream-compatible output (encoding)
- */
- void OutputCodingParams();
-
- /**
- * Current parse parameters
- */
- ParseParams m_parse_params;
-
-
- /**
- * Parse-params byte input/output
- */
- ParseParamsByteIO m_parseparams_byteio;
-
- /**
- * Default source parameters
- */
- SourceParams m_default_src_params;
-
- /**
- * Current source parameters
- */
- SourceParams& m_src_params;
-
- /**
- * Source-params byte input/output
- */
- SourceParamsByteIO m_sourceparams_byteio;
-
- /**
- * Current codec parameters
- */
- CodecParams& m_codec_params;
-
- /**
- * Coding-params byte input/output
- */
- CodingParamsByteIO m_codingparams_byteio;
-};
+ /**
+ * Destructor
+ */
+ ~SequenceHeaderByteIO();
+
+ /**
+ * Parses data in Dirac-stream format (decoding)
+ */
+ bool Input();
+
+ /**
+ * Writes access-unit info to Dirac stream-format (encoding)
+ */
+ void Output();
+
+ /*
+ * Gets size of access-unit (in bytes)
+ */
+ int GetSize() const;
+
+ /**
+ * Gets parse-unit type
+ */
+ ParseUnitType GetType() const { return PU_SEQ_HEADER;}
+
+ private:
+
+ /**
+ * Calculates parse-code based on access-unit parameters (encoding)
+ *@return Char bit-set
+ */
+ unsigned char CalcParseCode() const;
+
+ /**
+ * Parse source attributes from bytestream-compatible input (decoding)
+ */
+ void InputSourceParams();
+
+ /**
+ * Parse parse attributes from bytestream-compatible input (decoding)
+ */
+ void InputParseParams();
+
+ /**
+ * Parse Coding attributes from bytestream-compatible input (decoding)
+ */
+ void InputCodingParams();
+
+ /**
+ * Output source attributes for bytestream-compatible output (encoding)
+ */
+ void OutputSourceParams();
+
+ /**
+ * Output parse attributes for bytestream-compatible output (encoding)
+ */
+ void OutputParseParams();
+
+ /**
+ * Output coding attributes for bytestream-compatible output (encoding)
+ */
+ void OutputCodingParams();
+
+ /**
+ * Current parse parameters
+ */
+ ParseParams m_parse_params;
+
+
+ /**
+ * Parse-params byte input/output
+ */
+ ParseParamsByteIO m_parseparams_byteio;
+
+ /**
+ * Default source parameters
+ */
+ SourceParams m_default_src_params;
+
+ /**
+ * Current source parameters
+ */
+ SourceParams& m_src_params;
+
+ /**
+ * Source-params byte input/output
+ */
+ SourceParamsByteIO m_sourceparams_byteio;
+
+ /**
+ * Current codec parameters
+ */
+ CodecParams& m_codec_params;
+
+ /**
+ * Coding-params byte input/output
+ */
+ CodingParamsByteIO m_codingparams_byteio;
+ };
} // namespace dirac
diff --git a/src/filters/parser/DiracSplitter/libdirac/libdirac_byteio/byteio.cpp b/src/filters/parser/DiracSplitter/libdirac/libdirac_byteio/byteio.cpp
index 724239e54..12b129953 100644
--- a/src/filters/parser/DiracSplitter/libdirac/libdirac_byteio/byteio.cpp
+++ b/src/filters/parser/DiracSplitter/libdirac/libdirac_byteio/byteio.cpp
@@ -42,37 +42,37 @@ using namespace dirac;
using namespace std;
ByteIO::ByteIO(bool new_stream):
- m_current_byte(0),
- m_current_pos(0),
- m_num_bytes(0),
- m_new_stream(true),
- m_bits_left(0)
+m_current_byte(0),
+m_current_pos(0),
+m_num_bytes(0),
+m_new_stream(true),
+m_bits_left(0)
{
if(new_stream)
mp_stream = new stringstream(stringstream::in | stringstream::out |
stringstream::binary);
-
+
}
ByteIO::ByteIO(const ByteIO& stream_data):
- m_current_byte(0),
- m_current_pos(0),
- m_num_bytes(0),
- m_new_stream(false),
- m_bits_left(0)
+m_current_byte(0),
+m_current_pos(0),
+m_num_bytes(0),
+m_new_stream(false),
+m_bits_left(0)
{
- mp_stream = stream_data.mp_stream;
+ mp_stream=stream_data.mp_stream;
}
ByteIO::~ByteIO()
{
- if(m_new_stream)
+ if (m_new_stream)
delete mp_stream;
}
-const string ByteIO::GetBytes()
+const string ByteIO::GetBytes()
{
return mp_stream->str();
}
@@ -84,35 +84,35 @@ int ByteIO::GetSize() const
void ByteIO::SetByteParams(const ByteIO& byte_io)
{
- mp_stream = byte_io.mp_stream;
- m_current_byte = byte_io.m_current_byte;
- m_current_pos = byte_io.m_current_pos;
+ mp_stream=byte_io.mp_stream;
+ m_current_byte=byte_io.m_current_byte;
+ m_current_pos=byte_io.m_current_pos;
}
//----------protected---------------------------------------------------------------
void ByteIO::ByteAlignInput()
{
- m_current_pos = 0;
- m_current_byte = 0;
+ m_current_pos=0;
+ m_current_byte=0;
}
void ByteIO::ByteAlignOutput()
{
- if(m_current_pos != 0)
+ if(m_current_pos!=0)
OutputCurrentByte();
}
int ByteIO::ReadBit()
{
if(m_current_pos == CHAR_BIT)
- m_current_pos = 0;
+ m_current_pos=0;
- if(m_current_pos == 0)
+ if (m_current_pos == 0)
m_current_byte = InputUnByte();
#if 1
// MSB to LSB
- return GetBit(m_current_byte, (CHAR_BIT - 1 - m_current_pos++));
+ return GetBit(m_current_byte, (CHAR_BIT-1-m_current_pos++));
#else
// LSB to MSB
return GetBit(m_current_byte, m_current_pos++);
@@ -121,7 +121,7 @@ int ByteIO::ReadBit()
int ByteIO::ReadBitB()
{
- if(m_bits_left)
+ if (m_bits_left)
{
--m_bits_left;
return ReadBit();
@@ -143,7 +143,7 @@ bool ByteIO::ReadBoolB()
unsigned int ByteIO::ReadNBits(int count)
{
unsigned int val = 0;
- for(int i = 0; i < count; ++i)
+ for (int i = 0; i < count; ++i)
{
val <<= 1;
val += ReadBit();
@@ -166,14 +166,14 @@ int ByteIO::ReadSint()
int val = ReadUint();
bool bit;
- //get the sign
- if(val != 0)
+ //get the sign
+ if (val != 0)
{
bit = ReadBit();
- if(bit)
+ if (bit )
val = -val;
}
- return val;
+ return val;
}
int ByteIO::ReadSintB()
@@ -182,24 +182,24 @@ int ByteIO::ReadSintB()
int val = ReadUintB();
bool bit;
- //get the sign
- if(val != 0)
+ //get the sign
+ if (val != 0)
{
bit = ReadBitB();
- if(bit)
+ if (bit )
val = -val;
}
- return val;
+ return val;
}
unsigned int ByteIO::ReadUint()
{
unsigned int value = 1;
- while(!ReadBit())
+ while (!ReadBit())
{
value <<= 1;
- if(ReadBit())
- value += 1;
+ if (ReadBit())
+ value +=1;
}
--value;
return value;
@@ -208,11 +208,11 @@ unsigned int ByteIO::ReadUint()
unsigned int ByteIO::ReadUintB()
{
unsigned int value = 1;
- while(!ReadBitB())
+ while (!ReadBitB())
{
value <<= 1;
- if(ReadBitB())
- value += 1;
+ if (ReadBitB())
+ value +=1;
}
--value;
return value;
@@ -223,21 +223,21 @@ void ByteIO::WriteBit(const bool& bit)
if(bit)
#if 1
// MSB to LSB
- SetBit(m_current_byte, CHAR_BIT - 1 - m_current_pos);
+ SetBit(m_current_byte, CHAR_BIT-1-m_current_pos);
#else
// LSB to MSB
SetBit(m_current_byte, m_current_pos);
#endif
- if(m_current_pos == CHAR_BIT - 1)
- {
+ if ( m_current_pos == CHAR_BIT-1)
+ {
// If a whole byte has been written, output to stream
OutputCurrentByte();
m_current_byte = 0;
m_current_pos = 0;
- }
+ }
else
- // Shift mask to next bit in the output byte
+ // Shift mask to next bit in the output byte
++m_current_pos;
}
@@ -245,7 +245,7 @@ void ByteIO::WriteNBits(unsigned int val, int count)
{
do
{
- WriteBit(val & (1 << (count - 1)));
+ WriteBit(val & ( 1 << (count-1)));
count--;
}
while(count > 0);
@@ -253,7 +253,7 @@ void ByteIO::WriteNBits(unsigned int val, int count)
int ByteIO::WriteNBits(unsigned int val)
{
- int nbits = static_cast<int>(log(static_cast<double>(val)) / log(2.0)) + 1;
+ int nbits = static_cast<int>(log(static_cast<double>(val))/log(2.0)) + 1;
WriteNBits(val, nbits);
return nbits;
}
@@ -265,24 +265,24 @@ void ByteIO::WriteSint(int val)
WriteUint(value);
//do sign
- if(val < 0) WriteBit(1);
- else if(val > 0) WriteBit(0);
+ if (val<0) WriteBit(1);
+ else if (val>0) WriteBit(0);
}
void ByteIO::WriteUint(unsigned int value)
{
- unsigned int val = value + 1;
+ unsigned int val = value+1;
int num_follow_zeroes = 0;
- while(val >= (1U << num_follow_zeroes))
+ while (val >= (1U <<num_follow_zeroes))
++num_follow_zeroes;
--num_follow_zeroes;
- for(int i = num_follow_zeroes - 1; i >= 0; --i)
+ for (int i=num_follow_zeroes-1; i>=0; --i)
{
WriteBit(BIT_ZERO);
- WriteBit(val&(1 << i));
+ WriteBit(val&(1<<i));
}
WriteBit(BIT_ONE);
}
@@ -290,10 +290,10 @@ void ByteIO::WriteUint(unsigned int value)
void ByteIO::RemoveRedundantBytes(const int size)
{
int prev_pos = mp_stream->tellg();
- string data = mp_stream->str();
+ string data=mp_stream->str();
data.erase(0, size);
mp_stream->str(data);
- m_num_bytes = data.size();
+ m_num_bytes=data.size();
if(data.size())
- SeekGet(max(prev_pos - size, 0), ios_base::beg);
+ SeekGet(max(prev_pos-size, 0), ios_base::beg);
}
diff --git a/src/filters/parser/DiracSplitter/libdirac/libdirac_byteio/byteio.h b/src/filters/parser/DiracSplitter/libdirac/libdirac_byteio/byteio.h
index 806d98a55..db885d658 100644
--- a/src/filters/parser/DiracSplitter/libdirac/libdirac_byteio/byteio.h
+++ b/src/filters/parser/DiracSplitter/libdirac/libdirac_byteio/byteio.h
@@ -53,371 +53,342 @@
namespace dirac
{
+
+ // BIT DEFS
+ #define BIT_ZERO 0
+ #define BIT_ONE 1
+
+ // most significant bit in a character
+ #define MS_BIT (1 << (CHAR_BIT - 1))
+
+ /* array index for character containing bit */
+ //#define BIT_IN_CHAR(bit) (1 << (CHAR_BIT-1-bit))
+ #define BIT_IN_CHAR(bit) (1 << bit)
+
+
+ /**
+ * Class ByteIO - top-level class for reading/writing bytes to a stream
+ */
+ class ByteIO
+ {
+ public:
+
+ /**
+ * Default constructor
+ *@param new_stream <B>Has Creates & owns data buffer </B>
+ */
+ ByteIO(bool new_stream=true);
+
+ /**
+ * Constructor
+ *@param stream_data Copies data buffer details
+ */
+ ByteIO(const ByteIO& stream_data);
+
+ /**
+ * Destructor
+ */
+ virtual ~ByteIO();
+
+ /**
+ * Gathers byte-stream statistics
+ *@param dirac_byte_stats Collates byte information
+ */
+ virtual void CollateByteStats(DiracByteStats& dirac_byte_stats)
+ { dirac_byte_stats.Clear(); }
+
+ /**
+ * Get bytes in Dirac-bytestream format
+ */
+ virtual const std::string GetBytes();
+
+ /**
+ * Get position of read stream pointer
+ */
+ int GetReadBytePosition() const { return mp_stream->tellg();};
+
+
+ /**
+ *Gets size (in bytes)
+ */
+ virtual int GetSize() const;
+
+ /**
+ * Copies stream source/destination info
+ *@param byte_io Byte source/destination
+ */
+ void SetByteParams(const ByteIO& byte_io);
+
+ /**
+ * Sync input for byte-alignment
+ */
+ void ByteAlignOutput();
+
+ /**
+ * Ouputs an unsigned integer in interleaved exp Golomb format
+ *@param value Integer to be output
+ */
+ //void OutputVarLengthUint(const unsigned int& value);
+ void WriteUint(unsigned int value);
+
+ /**
+ * Sets input size in bits. Read is limited by this
+ */
+ void SetBitsLeft(int left_bits) { m_bits_left = left_bits; }
+
+ /**
+ * Sets input size in bits. Read is limited by this
+ */
+ int BitsLeft(void) { return m_bits_left; }
+
+ protected:
+
+ inline bool CanRead() const { return(!mp_stream->eof()); }
+
+ inline bool GetBit(unsigned char& c, int pos) const { return (c & BIT_IN_CHAR(pos)); }
+
+ inline void SetBit(unsigned char& c, int pos) const { c |= BIT_IN_CHAR(pos); }
+
+ inline void SetBits(unsigned char& c, unsigned char bits) const { c |= bits; }
+
+ /**
+ * Sync input for byte-alignment
+ */
+ void ByteAlignInput();
+
+
+ /**
+ * Reads boolean value
+ */
+ bool ReadBool();
+
+ /**
+ * Reads boolean value - bounded i/o
+ */
+ bool ReadBoolB();
+
+ /**
+ * Reads next bit
+ */
+ int ReadBit();
+
+ /**
+ * Reads next bit - bounded i/o
+ */
+ int ReadBitB();
+
+ /**
+ * Reads next 'count' bits
+ *@param count number of bits to be read
+ *@return unsigned interger read
+ */
+ unsigned int ReadNBits(int count);
+
+ /**
+ * Reads from stream
+ *@param data Start of char buffer
+ *@param count Number of bytes to read
+ */
+ void InputBytes(char* data, int count)
+ {
+ //int j=mp_stream->tellg();
+ mp_stream->read(data, count);
-// BIT DEFS
-#define BIT_ZERO 0
-#define BIT_ONE 1
-
-// most significant bit in a character
-#define MS_BIT (1 << (CHAR_BIT - 1))
-
-/* array index for character containing bit */
-//#define BIT_IN_CHAR(bit) (1 << (CHAR_BIT-1-bit))
-#define BIT_IN_CHAR(bit) (1 << bit)
-
+ //int h=mp_stream->tellg();
+ }
-/**
-* Class ByteIO - top-level class for reading/writing bytes to a stream
-*/
-class ByteIO
-{
-public:
-
- /**
- * Default constructor
- *@param new_stream <B>Has Creates & owns data buffer </B>
- */
- ByteIO(bool new_stream = true);
-
- /**
- * Constructor
- *@param stream_data Copies data buffer details
- */
- ByteIO(const ByteIO& stream_data);
-
- /**
- * Destructor
- */
- virtual ~ByteIO();
-
- /**
- * Gathers byte-stream statistics
- *@param dirac_byte_stats Collates byte information
- */
- virtual void CollateByteStats(DiracByteStats& dirac_byte_stats)
- {
- dirac_byte_stats.Clear();
- }
-
- /**
- * Get bytes in Dirac-bytestream format
- */
- virtual const std::string GetBytes();
-
- /**
- * Get position of read stream pointer
- */
- int GetReadBytePosition() const
- {
- return mp_stream->tellg();
- };
-
-
- /**
- *Gets size (in bytes)
- */
- virtual int GetSize() const;
-
- /**
- * Copies stream source/destination info
- *@param byte_io Byte source/destination
- */
- void SetByteParams(const ByteIO& byte_io);
-
- /**
- * Sync input for byte-alignment
- */
- void ByteAlignOutput();
-
- /**
- * Ouputs an unsigned integer in interleaved exp Golomb format
- *@param value Integer to be output
- */
- //void OutputVarLengthUint(const unsigned int& value);
- void WriteUint(unsigned int value);
-
- /**
- * Sets input size in bits. Read is limited by this
- */
- void SetBitsLeft(int left_bits)
- {
- m_bits_left = left_bits;
- }
-
- /**
- * Sets input size in bits. Read is limited by this
- */
- int BitsLeft(void)
- {
- return m_bits_left;
- }
-
-protected:
-
- inline bool CanRead() const
- {
- return(!mp_stream->eof());
- }
-
- inline bool GetBit(unsigned char& c, int pos) const
- {
- return (c & BIT_IN_CHAR(pos));
- }
-
- inline void SetBit(unsigned char& c, int pos) const
- {
- c |= BIT_IN_CHAR(pos);
- }
-
- inline void SetBits(unsigned char& c, unsigned char bits) const
- {
- c |= bits;
- }
-
- /**
- * Sync input for byte-alignment
- */
- void ByteAlignInput();
-
-
- /**
- * Reads boolean value
- */
- bool ReadBool();
-
- /**
- * Reads boolean value - bounded i/o
- */
- bool ReadBoolB();
-
- /**
- * Reads next bit
- */
- int ReadBit();
-
- /**
- * Reads next bit - bounded i/o
- */
- int ReadBitB();
-
- /**
- * Reads next 'count' bits
- *@param count number of bits to be read
- *@return unsigned interger read
- */
- unsigned int ReadNBits(int count);
-
- /**
- * Reads from stream
- *@param data Start of char buffer
- *@param count Number of bytes to read
- */
- void InputBytes(char* data, int count)
- {
- //int j=mp_stream->tellg();
- mp_stream->read(data, count);
-
- //int h=mp_stream->tellg();
- }
-
- /**
- * Flushes the bounde input
- */
- void FlushInputB();
-
- /**
- * Reads a signed integer in interleaved exp-Golomb format
- *return Signed integer read
- */
- //int InputVarLengthInt();
- int ReadSint();
-
- /**
- * Reads a signed integer in interleaved exp-Golomb format from bounded input
- *return Signed integer read
- */
- int ReadSintB();
-
- /**
- * Reads an unsigned integer in interleaved exp Golomb format
- *@return Unsigned Integer read
- */
- //unsigned int InputVarLengthUint();
- unsigned int ReadUint();
-
- /**
- * Reads an unsigned integer in interleaved exp Golomb format from bounded input
- *@return Unsigned Integer read
- */
- //unsigned int InputVarLengthUint();
- unsigned int ReadUintB();
-
- /**
- * Reads a fixed length unsigned integer from the stream in big endian
- *@param byte_size Number of bytes in fixed length integer
- *@return Unsigned Integer read
- */
- //inline unsigned int InputFixedLengthUint(const int byte_size) {
- inline unsigned int ReadUintLit(const int byte_size)
- {
- unsigned int val = 0;
- for(int i = 0; i < byte_size; ++i)
+ /**
+ * Flushes the bounde input
+ */
+ void FlushInputB();
+
+ /**
+ * Reads a signed integer in interleaved exp-Golomb format
+ *return Signed integer read
+ */
+ //int InputVarLengthInt();
+ int ReadSint();
+
+ /**
+ * Reads a signed integer in interleaved exp-Golomb format from bounded input
+ *return Signed integer read
+ */
+ int ReadSintB();
+
+ /**
+ * Reads an unsigned integer in interleaved exp Golomb format
+ *@return Unsigned Integer read
+ */
+ //unsigned int InputVarLengthUint();
+ unsigned int ReadUint();
+
+ /**
+ * Reads an unsigned integer in interleaved exp Golomb format from bounded input
+ *@return Unsigned Integer read
+ */
+ //unsigned int InputVarLengthUint();
+ unsigned int ReadUintB();
+
+ /**
+ * Reads a fixed length unsigned integer from the stream in big endian
+ *@param byte_size Number of bytes in fixed length integer
+ *@return Unsigned Integer read
+ */
+ //inline unsigned int InputFixedLengthUint(const int byte_size) {
+ inline unsigned int ReadUintLit(const int byte_size) {
+ unsigned int val=0;
+ for(int i=0; i < byte_size; ++i)
+ {
+ val <<= 8;
+ val += (unsigned char)mp_stream->get();
+ }
+ m_num_bytes+=byte_size;
+ return val;
+ }
+
+ /**
+ * Reads a byte from the stream
+ */
+ inline unsigned char InputUnByte() {m_num_bytes++ ; return mp_stream->get(); }
+
+ /**
+ * Reads a series of bytes from a stream
+ */
+ inline std::string InputUnString(const int count)
{
- val <<= 8;
- val += (unsigned char)mp_stream->get();
+ std::string str;
+ for(int index=0; index < count; ++index)
+ str.push_back(InputUnByte());
+ return str;
}
- m_num_bytes += byte_size;
- return val;
- }
-
- /**
- * Reads a byte from the stream
- */
- inline unsigned char InputUnByte()
- {
- m_num_bytes++ ;
- return mp_stream->get();
- }
-
- /**
- * Reads a series of bytes from a stream
- */
- inline std::string InputUnString(const int count)
- {
- std::string str;
- for(int index = 0; index < count; ++index)
- str.push_back(InputUnByte());
- return str;
- }
-
- /**
- * Outputs a bit
- *@param bit 1/0 Output
- */
- void WriteBit(const bool& bit);
-
- /**
- * Outputs an unsigned integer
- *@param val Integer to be output
- *@return number of bits written
- */
- int WriteNBits(unsigned int val);
-
- /**
- * Outputs an n bit integer
- *@param val Unsigned Integer to be output
- *@param count number of bits to be written
- */
- void WriteNBits(unsigned int val, int count);
-
-
-
- /**
- * Outputs a series of bytes
- */
- void OutputBytes(const std::string& bytes)
- {
- int cur_pos = mp_stream->tellg();
- mp_stream->str(mp_stream->str() + bytes);
- m_num_bytes += bytes.size();
+
+ /**
+ * Outputs a bit
+ *@param bit 1/0 Output
+ */
+ void WriteBit(const bool& bit);
+
+ /**
+ * Outputs an unsigned integer
+ *@param val Integer to be output
+ *@return number of bits written
+ */
+ int WriteNBits(unsigned int val);
+
+ /**
+ * Outputs an n bit integer
+ *@param val Unsigned Integer to be output
+ *@param count number of bits to be written
+ */
+ void WriteNBits(unsigned int val, int count);
+
+
+
+ /**
+ * Outputs a series of bytes
+ */
+ void OutputBytes(const std::string& bytes) {
+ int cur_pos = mp_stream->tellg();
+ mp_stream->str(mp_stream->str()+bytes);
+ m_num_bytes+=bytes.size();
// *mp_stream << bytes;
- mp_stream->seekg(std::max(cur_pos, 0), std::ios_base::beg);
- }
-
- /**
- * Outputs current byte contents
- */
- inline void OutputCurrentByte()
- {
- if(m_current_pos)
- {
- *mp_stream << (m_current_byte);
- ++m_num_bytes;
- m_current_pos = 0;
- m_current_byte = 0;
+ mp_stream->seekg(std::max(cur_pos,0), std::ios_base::beg);
}
- };
-
- /**
- * Outputs an integer in Golomb signed integer format
- *@param val Integer to be output
- */
- //void OutputVarLengthInt(const int val);
- void WriteSint(int val);
-
- /**
- * Output unsigned int value in big endian format
- * @param value Integer to be output
- * @param length number of bytes in val to output
- */
- //inline void OutputFixedLengthUint(const unsigned int& value, const int& length)
- inline void WriteUintLit(const unsigned int& value, const int& length)
- {
- for(int i = length - 1; i >= 0 ; --i)
+
+ /**
+ * Outputs current byte contents
+ */
+ inline void OutputCurrentByte()
{
- unsigned char cp = (value >> (i * 8)) & 0xff;
- *mp_stream << cp;
- }
- m_num_bytes += length;
- }
-
- /**
- * Removes portion of byte-stream no longer required
- *@param count Number of bytes to be removed from beginning of stream
- */
- void RemoveRedundantBytes(const int count);
-
- inline void SeekGet(const int offset, std::ios_base::seekdir dir)
- {
- mp_stream->seekg(offset, dir);
- }
-
- /**
- * Input/output steam
- */
- std::stringstream* mp_stream;
-
-
-private:
-
- /**
- * ArithCodec can see internals for getting/setting bits
- */
- friend class ArithCodecBase;
-
- /**
- * VLC entropy coder can see internals for getting/setting bits
- */
- friend class ArithCodecToVLCAdapter;
-
- /**
- * Char used for temporary storage of op data bits
- */
- unsigned char m_current_byte;
-
- /**
- * Used to set individual bit within the current header byte
- */
- int m_current_pos;
-
- /**
- * Number of bytes processed
- */
- int m_num_bytes;
-
- /**
- * stream alloc flag
- */
- bool m_new_stream;
-
- /**
- * num bits left to read
- */
- int m_bits_left;
-protected:
-
-
-};
+ if (m_current_pos)
+ {
+ *mp_stream << (m_current_byte);
+ ++m_num_bytes;
+ m_current_pos = 0;
+ m_current_byte = 0;
+ }
+ };
+
+ /**
+ * Outputs an integer in Golomb signed integer format
+ *@param val Integer to be output
+ */
+ //void OutputVarLengthInt(const int val);
+ void WriteSint(int val);
+
+ /**
+ * Output unsigned int value in big endian format
+ * @param value Integer to be output
+ * @param length number of bytes in val to output
+ */
+ //inline void OutputFixedLengthUint(const unsigned int& value, const int& length)
+ inline void WriteUintLit(const unsigned int& value, const int& length)
+ {
+ for(int i=length-1; i >=0 ; --i)
+ {
+ unsigned char cp = (value>>(i*8))&0xff;
+ *mp_stream << cp;
+ }
+ m_num_bytes+=length;
+ }
+
+ /**
+ * Removes portion of byte-stream no longer required
+ *@param count Number of bytes to be removed from beginning of stream
+ */
+ void RemoveRedundantBytes(const int count);
+
+ inline void SeekGet(const int offset, std::ios_base::seekdir dir)
+ {
+ mp_stream->seekg(offset, dir);
+ }
+
+ /**
+ * Input/output steam
+ */
+ std::stringstream* mp_stream;
+
+
+ private:
+
+ /**
+ * ArithCodec can see internals for getting/setting bits
+ */
+ friend class ArithCodecBase;
+
+ /**
+ * VLC entropy coder can see internals for getting/setting bits
+ */
+ friend class ArithCodecToVLCAdapter;
+
+ /**
+ * Char used for temporary storage of op data bits
+ */
+ unsigned char m_current_byte;
+
+ /**
+ * Used to set individual bit within the current header byte
+ */
+ int m_current_pos;
+
+ /**
+ * Number of bytes processed
+ */
+ int m_num_bytes;
+
+ /**
+ * stream alloc flag
+ */
+ bool m_new_stream;
+
+ /**
+ * num bits left to read
+ */
+ int m_bits_left;
+ protected:
+
+
+ };
diff --git a/src/filters/parser/DiracSplitter/libdirac/libdirac_byteio/codingparams_byteio.cpp b/src/filters/parser/DiracSplitter/libdirac/libdirac_byteio/codingparams_byteio.cpp
index 69875e31b..7326b4562 100644
--- a/src/filters/parser/DiracSplitter/libdirac/libdirac_byteio/codingparams_byteio.cpp
+++ b/src/filters/parser/DiracSplitter/libdirac/libdirac_byteio/codingparams_byteio.cpp
@@ -42,13 +42,13 @@
using namespace dirac;
CodingParamsByteIO::CodingParamsByteIO(const SourceParams& src_params,
- CodecParams& codec_params,
- const SourceParams& default_source_params,
- const ByteIO& stream_data):
- ByteIO(stream_data),
- m_src_params(src_params),
- m_codec_params(codec_params),
- m_default_source_params(default_source_params)
+ CodecParams& codec_params,
+ const SourceParams& default_source_params,
+ const ByteIO& stream_data):
+ByteIO(stream_data),
+m_src_params(src_params),
+m_codec_params(codec_params),
+m_default_source_params(default_source_params)
{
}
@@ -75,22 +75,22 @@ void CodingParamsByteIO::Input()
// If source was coded as fields, halve the vertical dimensions
// to set them to field dimensions
- if(m_codec_params.FieldCoding())
+ if (m_codec_params.FieldCoding())
{
- m_codec_params.SetYl(m_codec_params.Yl() >> 1);
- m_codec_params.SetChromaYl(m_codec_params.ChromaYl() >> 1);
+ m_codec_params.SetYl(m_codec_params.Yl()>>1);
+ m_codec_params.SetChromaYl(m_codec_params.ChromaYl()>>1);
}
unsigned int luma_depth = static_cast<unsigned int>
- (
- std::log((double)m_src_params.LumaExcursion()) / std::log(2.0) + 1
- );
+ (
+ std::log((double)m_src_params.LumaExcursion())/std::log(2.0) + 1
+ );
m_codec_params.SetLumaDepth(luma_depth);
unsigned int chroma_depth = static_cast<unsigned int>
- (
- std::log((double)m_src_params.ChromaExcursion()) / std::log(2.0) + 1
- );
+ (
+ std::log((double)m_src_params.ChromaExcursion())/std::log(2.0) + 1
+ );
m_codec_params.SetChromaDepth(chroma_depth);
// byte align
@@ -112,7 +112,7 @@ void CodingParamsByteIO::Output()
void CodingParamsByteIO::InputPictureCodingMode()
{
unsigned int coding_mode = ReadUint();
- if(coding_mode > 1)
+ if (coding_mode > 1)
{
std::ostringstream errstr;
errstr << "Picture coding mode " << coding_mode
diff --git a/src/filters/parser/DiracSplitter/libdirac/libdirac_byteio/codingparams_byteio.h b/src/filters/parser/DiracSplitter/libdirac/libdirac_byteio/codingparams_byteio.h
index 05b512df8..b96b037a0 100644
--- a/src/filters/parser/DiracSplitter/libdirac/libdirac_byteio/codingparams_byteio.h
+++ b/src/filters/parser/DiracSplitter/libdirac/libdirac_byteio/codingparams_byteio.h
@@ -51,83 +51,83 @@
namespace dirac
{
-
-/**
-* Represents compressed sequence-parameter data used in an AccessUnit
-*/
-class CodingParamsByteIO : public ByteIO
-{
-public:
-
- /**
- * Constructor
- *@param src_params Source parameters
- *@param codec_params Coding parameters
- *@param default_source_params Default source parameters
- *@param stream_data Source/Destination of data
- */
- CodingParamsByteIO(const SourceParams& src_params,
- CodecParams& codec_params,
- const SourceParams& default_source_params,
- const ByteIO& stream_data);
-
-
- /**
- * Destructor
- */
- ~CodingParamsByteIO();
-
- /**
- * Reads sequence information from Dirac byte-format
- */
- void Input();
-
- /**
- * Outputs sequence information to Dirac byte-format
- */
- void Output();
-
-protected:
-
-
-private:
-
- /**
- * Reads number of bits used to compress input signal
- */
- void InputVideoDepth();
-
- /**
- * Reads picture coding mode - 0 - frames, 1 - fields
- */
- void InputPictureCodingMode();
-
- /**
- * Outputs number of bits used to compress input signal
- */
- void OutputVideoDepth();
-
+
/**
- * Outputs how input was coded - i.e. frames or fields
+ * Represents compressed sequence-parameter data used in an AccessUnit
*/
- void OutputPictureCodingMode();
-
- /**
- * Source paramters for intput/output
- */
- const SourceParams& m_src_params;
-
- /**
- * Coding paramters for intput/output
- */
- CodecParams& m_codec_params;
-
- /**
- * Default source parameters
- */
- const SourceParams& m_default_source_params;
-
-};
+ class CodingParamsByteIO : public ByteIO
+ {
+ public:
+
+ /**
+ * Constructor
+ *@param src_params Source parameters
+ *@param codec_params Coding parameters
+ *@param default_source_params Default source parameters
+ *@param stream_data Source/Destination of data
+ */
+ CodingParamsByteIO(const SourceParams& src_params,
+ CodecParams& codec_params,
+ const SourceParams& default_source_params,
+ const ByteIO& stream_data);
+
+
+ /**
+ * Destructor
+ */
+ ~CodingParamsByteIO();
+
+ /**
+ * Reads sequence information from Dirac byte-format
+ */
+ void Input();
+
+ /**
+ * Outputs sequence information to Dirac byte-format
+ */
+ void Output();
+
+ protected:
+
+
+ private:
+
+ /**
+ * Reads number of bits used to compress input signal
+ */
+ void InputVideoDepth();
+
+ /**
+ * Reads picture coding mode - 0 - frames, 1 - fields
+ */
+ void InputPictureCodingMode();
+
+ /**
+ * Outputs number of bits used to compress input signal
+ */
+ void OutputVideoDepth();
+
+ /**
+ * Outputs how input was coded - i.e. frames or fields
+ */
+ void OutputPictureCodingMode();
+
+ /**
+ * Source paramters for intput/output
+ */
+ const SourceParams& m_src_params;
+
+ /**
+ * Coding paramters for intput/output
+ */
+ CodecParams& m_codec_params;
+
+ /**
+ * Default source parameters
+ */
+ const SourceParams& m_default_source_params;
+
+ };
} // namespace dirac
diff --git a/src/filters/parser/DiracSplitter/libdirac/libdirac_byteio/component_byteio.cpp b/src/filters/parser/DiracSplitter/libdirac/libdirac_byteio/component_byteio.cpp
index 88a63811a..07f5433d1 100644
--- a/src/filters/parser/DiracSplitter/libdirac/libdirac_byteio/component_byteio.cpp
+++ b/src/filters/parser/DiracSplitter/libdirac/libdirac_byteio/component_byteio.cpp
@@ -42,13 +42,13 @@ using namespace std;
ComponentByteIO::ComponentByteIO(CompSort cs,
const ByteIO& byteio):
- ByteIO(byteio),
- m_compsort(cs)
+ByteIO(byteio),
+m_compsort(cs)
{}
ComponentByteIO::ComponentByteIO(CompSort cs):
- ByteIO(),
- m_compsort(cs)
+ByteIO(),
+m_compsort(cs)
{}
ComponentByteIO::~ComponentByteIO()
@@ -83,16 +83,16 @@ void ComponentByteIO::CollateByteStats(DiracByteStats& dirac_byte_stats)
bool ComponentByteIO::Input()
{
-
- return true;
+
+ return true;
}
void ComponentByteIO::Output()
{
-
+
}
//-------------private-------------------------------------------------------
-
+
diff --git a/src/filters/parser/DiracSplitter/libdirac/libdirac_byteio/component_byteio.h b/src/filters/parser/DiracSplitter/libdirac/libdirac_byteio/component_byteio.h
index 03ee2f1ea..e80b0877a 100644
--- a/src/filters/parser/DiracSplitter/libdirac/libdirac_byteio/component_byteio.h
+++ b/src/filters/parser/DiracSplitter/libdirac/libdirac_byteio/component_byteio.h
@@ -52,73 +52,73 @@
namespace dirac
{
-/**
-* Picture component in Dirac bytestream format
-*/
-class ComponentByteIO : public ByteIO
-{
-public:
-
- /**
- * Constructor
- *@param cs Picture-component type
- *@param byteIO Input/output Byte stream
- */
- ComponentByteIO(CompSort cs,
- const ByteIO& byteIO);
-
- /**
- * Constructor
- *@param cs Picture-component type
- */
- ComponentByteIO(CompSort cs);
-
/**
- * Destructor
+ * Picture component in Dirac bytestream format
*/
- ~ComponentByteIO();
-
- /**
- * Gathers byte stats on the component data
- *@param dirac_byte_stats Stat container
- */
- void CollateByteStats(DiracByteStats& dirac_byte_stats);
-
- /**
- * Add a subband byte-stream to this component
- *@param p_subband_byteio Subband to be added
- */
- void AddSubband(SubbandByteIO *p_subband_byteio);
-
- /**
- * Inputs data from Dirac stream-format
- */
- bool Input();
-
- /**
- * Outputs picture values to Dirac stream-format
- */
- void Output();
-
-
-
-protected:
-
-
-private:
-
- /**
- * Picture component type
- */
- CompSort m_compsort;
-
- /**
- * List of subbands in output/input order
- */
- std::vector<ByteIO*> m_subband_list;
-
-
-};
+ class ComponentByteIO : public ByteIO
+ {
+ public:
+
+ /**
+ * Constructor
+ *@param cs Picture-component type
+ *@param byteIO Input/output Byte stream
+ */
+ ComponentByteIO(CompSort cs,
+ const ByteIO& byteIO);
+
+ /**
+ * Constructor
+ *@param cs Picture-component type
+ */
+ ComponentByteIO(CompSort cs);
+
+ /**
+ * Destructor
+ */
+ ~ComponentByteIO();
+
+ /**
+ * Gathers byte stats on the component data
+ *@param dirac_byte_stats Stat container
+ */
+ void CollateByteStats(DiracByteStats& dirac_byte_stats);
+
+ /**
+ * Add a subband byte-stream to this component
+ *@param p_subband_byteio Subband to be added
+ */
+ void AddSubband(SubbandByteIO *p_subband_byteio);
+
+ /**
+ * Inputs data from Dirac stream-format
+ */
+ bool Input();
+
+ /**
+ * Outputs picture values to Dirac stream-format
+ */
+ void Output();
+
+
+
+ protected:
+
+
+ private:
+
+ /**
+ * Picture component type
+ */
+ CompSort m_compsort;
+
+ /**
+ * List of subbands in output/input order
+ */
+ std::vector<ByteIO*> m_subband_list;
+
+
+ };
} // namespace dirac
diff --git a/src/filters/parser/DiracSplitter/libdirac/libdirac_byteio/dirac_byte_stats.cpp b/src/filters/parser/DiracSplitter/libdirac/libdirac_byteio/dirac_byte_stats.cpp
index 883badb14..9c697bc3d 100644
--- a/src/filters/parser/DiracSplitter/libdirac/libdirac_byteio/dirac_byte_stats.cpp
+++ b/src/filters/parser/DiracSplitter/libdirac/libdirac_byteio/dirac_byte_stats.cpp
@@ -46,7 +46,7 @@ DiracByteStats::DiracByteStats()
}
DiracByteStats::DiracByteStats(const DiracByteStats& dirac_byte_stats):
- m_byte_count(dirac_byte_stats.m_byte_count)
+m_byte_count(dirac_byte_stats.m_byte_count)
{
}
@@ -60,25 +60,25 @@ void DiracByteStats::Clear()
m_byte_count.clear();
}
-int64_t DiracByteStats::GetBitCount(const StatType& stat_type) const
+int64_t DiracByteStats::GetBitCount(const StatType& stat_type) const
{
return GetByteCount(stat_type) * CHAR_BIT;
}
int64_t DiracByteStats::GetByteCount(const StatType& stat_type) const
{
- std::map<StatType, int64_t>::const_iterator it;
- it = m_byte_count.find(stat_type);
- if(it == m_byte_count.end())
- return 0;
+ std::map<StatType, int64_t>::const_iterator it;
+ it = m_byte_count.find(stat_type);
+ if(it==m_byte_count.end())
+ return 0;
- return it->second;
+ return it->second;
}
void DiracByteStats::SetByteCount(const StatType& stat_type, int64_t count)
{
- if(m_byte_count.find(stat_type) == m_byte_count.end())
- m_byte_count[stat_type] = 0;
+ if(m_byte_count.find(stat_type)==m_byte_count.end())
+ m_byte_count[stat_type]=0;
- m_byte_count[stat_type] += count;
-}
+ m_byte_count[stat_type]+=count;
+ }
diff --git a/src/filters/parser/DiracSplitter/libdirac/libdirac_byteio/dirac_byte_stats.h b/src/filters/parser/DiracSplitter/libdirac/libdirac_byteio/dirac_byte_stats.h
index d32635a2a..0da273f0a 100644
--- a/src/filters/parser/DiracSplitter/libdirac/libdirac_byteio/dirac_byte_stats.h
+++ b/src/filters/parser/DiracSplitter/libdirac/libdirac_byteio/dirac_byte_stats.h
@@ -50,71 +50,70 @@
namespace dirac
{
-#ifdef _MSC_VER
-// char length
-#define CHAR_BIT 8
+ #ifdef _MSC_VER
+ // char length
+ #define CHAR_BIT 8
#endif
-typedef enum
-{
- STAT_TOTAL_BYTE_COUNT = 0,
- STAT_MV_BYTE_COUNT,
- STAT_YCOMP_BYTE_COUNT,
- STAT_UCOMP_BYTE_COUNT,
- STAT_VCOMP_BYTE_COUNT
-} StatType;
-
-
-/**
-* Class DiracByteStats - for collecting statistics on aspects of the Dirac byte-stream
-*/
-class DiracByteStats
-{
-public:
- /**
- * Constructor
- */
- DiracByteStats();
-
- /**
- * Copy constructor
- */
- DiracByteStats(const DiracByteStats& dirac_byte_stats);
-
- /**
- * Destructor
- */
- ~DiracByteStats();
-
- /**
- * Clears data
- */
- void Clear();
-
- /**
- * Gets number of bits for a particular stat-type
- */
- int64_t GetBitCount(const StatType& stat_type) const;
-
- /**
- * Gets number of bytes for a particular stat-type
- */
- int64_t GetByteCount(const StatType& stat_type) const;
-
- /**
- * Sets number of bytes for a particular stat-type
- */
- void SetByteCount(const StatType& stat_type, int64_t count);
-
-
-private:
-
- /**
- * Map of byte-counts
- */
- std::map<StatType, int64_t> m_byte_count;
-
-};
+ typedef enum {
+ STAT_TOTAL_BYTE_COUNT=0,
+ STAT_MV_BYTE_COUNT,
+ STAT_YCOMP_BYTE_COUNT,
+ STAT_UCOMP_BYTE_COUNT,
+ STAT_VCOMP_BYTE_COUNT
+ } StatType;
+
+
+ /**
+ * Class DiracByteStats - for collecting statistics on aspects of the Dirac byte-stream
+ */
+ class DiracByteStats
+ {
+ public:
+ /**
+ * Constructor
+ */
+ DiracByteStats();
+
+ /**
+ * Copy constructor
+ */
+ DiracByteStats(const DiracByteStats& dirac_byte_stats);
+
+ /**
+ * Destructor
+ */
+ ~DiracByteStats();
+
+ /**
+ * Clears data
+ */
+ void Clear();
+
+ /**
+ * Gets number of bits for a particular stat-type
+ */
+ int64_t GetBitCount(const StatType& stat_type) const;
+
+ /**
+ * Gets number of bytes for a particular stat-type
+ */
+ int64_t GetByteCount(const StatType& stat_type) const;
+
+ /**
+ * Sets number of bytes for a particular stat-type
+ */
+ void SetByteCount(const StatType& stat_type, int64_t count);
+
+
+ private:
+
+ /**
+ * Map of byte-counts
+ */
+ std::map<StatType, int64_t> m_byte_count;
+
+ };
} // namespace dirac
diff --git a/src/filters/parser/DiracSplitter/libdirac/libdirac_byteio/dirac_byte_stream.cpp b/src/filters/parser/DiracSplitter/libdirac/libdirac_byteio/dirac_byte_stream.cpp
index b31e8de47..a45e54706 100644
--- a/src/filters/parser/DiracSplitter/libdirac/libdirac_byteio/dirac_byte_stream.cpp
+++ b/src/filters/parser/DiracSplitter/libdirac/libdirac_byteio/dirac_byte_stream.cpp
@@ -44,8 +44,8 @@ using namespace dirac;
using namespace std;
DiracByteStream::DiracByteStream():
- ByteIO(),
- mp_prev_parse_unit(NULL)
+ByteIO(),
+mp_prev_parse_unit(NULL)
{
}
@@ -86,29 +86,29 @@ void DiracByteStream::Reset(ParseUnitByteIO* p_curr_unit, int pos)
ParseUnitByteIO* DiracByteStream::GetNextParseUnit()
{
- if(GetSize() == 0)
+ if(GetSize()==0)
return NULL;
- int pos = 0;
+ int pos=0;
if(mp_prev_parse_unit)
{
// remove the unwanted bytes associated with the previous parse-unit
int prev_offset = mp_prev_parse_unit->GetNextParseOffset();
RemoveRedundantBytes(prev_offset ? prev_offset : mp_prev_parse_unit->GetSize());
delete mp_prev_parse_unit;
- mp_prev_parse_unit = NULL;
+ mp_prev_parse_unit=NULL;
if(!GetSize())
return NULL;
}
- ParseUnitByteIO* p_curr_unit = NULL;
+ ParseUnitByteIO* p_curr_unit=NULL;
while(true)
{
pos = GetReadBytePosition();
p_curr_unit = new ParseUnitByteIO(*this);
- if(!p_curr_unit->Input())
+ if (!p_curr_unit->Input())
{
Reset(p_curr_unit, pos);
return NULL;
@@ -121,7 +121,7 @@ ParseUnitByteIO* DiracByteStream::GetNextParseUnit()
return NULL;
}
- if(p_curr_unit->IsEndOfSequence())
+ if (p_curr_unit->IsEndOfSequence())
{
break;
}
@@ -140,15 +140,15 @@ ParseUnitByteIO* DiracByteStream::GetNextParseUnit()
} // while
// Remove all redundant bytes that are not part of a parse unit
- int remove_size = std::max(0, GetReadBytePosition() - p_curr_unit->GetSize());
- if(remove_size)
+ int remove_size = std::max (0, GetReadBytePosition()-p_curr_unit->GetSize());
+ if (remove_size)
{
- //std::cerr << "Size="<<GetSize() << " Un-useful bytes=" << remove_size << std::endl;
+ //std::cerr << "Size="<<GetSize() << " Un-useful bytes=" << remove_size << std::endl;
RemoveRedundantBytes(remove_size);
}
- mp_prev_parse_unit = p_curr_unit;
- return p_curr_unit;
+ mp_prev_parse_unit=p_curr_unit;
+ return p_curr_unit;
}
DiracByteStats DiracByteStream::GetSequenceStats() const
@@ -161,7 +161,7 @@ DiracByteStats DiracByteStream::GetSequenceStats() const
void DiracByteStream::AddSequenceHeader(SequenceHeaderByteIO *p_seqheader_byteio)
{
// set previous parse-unit details
- ParseUnitByteIO *mp_previous_parse_unit = mp_prev_parse_unit;
+ ParseUnitByteIO *mp_previous_parse_unit=mp_prev_parse_unit;
if(!m_parse_unit_list.empty())
mp_previous_parse_unit = m_parse_unit_list.back().second;
@@ -170,7 +170,7 @@ void DiracByteStream::AddSequenceHeader(SequenceHeaderByteIO *p_seqheader_byteio
p_seqheader_byteio->SetAdjacentParseUnits(mp_previous_parse_unit);
// push onto to pending list
- m_parse_unit_list.push(std::make_pair(PU_SEQ_HEADER, p_seqheader_byteio));
+ m_parse_unit_list.push(std::make_pair (PU_SEQ_HEADER, p_seqheader_byteio) );
// set previous parse-unit
mp_previous_parse_unit = p_seqheader_byteio;
@@ -182,7 +182,7 @@ void DiracByteStream::AddSequenceHeader(SequenceHeaderByteIO *p_seqheader_byteio
void DiracByteStream::AddPicture(PictureByteIO *p_frame_byteio)
{
// set previous parse-unit details
- ParseUnitByteIO *mp_previous_parse_unit = mp_prev_parse_unit;
+ ParseUnitByteIO *mp_previous_parse_unit=mp_prev_parse_unit;
if(!m_parse_unit_list.empty())
mp_previous_parse_unit = m_parse_unit_list.back().second;
@@ -190,26 +190,26 @@ void DiracByteStream::AddPicture(PictureByteIO *p_frame_byteio)
// set adjacent parse-unit
p_frame_byteio->SetAdjacentParseUnits(mp_previous_parse_unit);
- // push onto to pending list
- m_parse_unit_list.push(std::make_pair(PU_PICTURE, p_frame_byteio));
+ // push onto to pending list
+ m_parse_unit_list.push(std::make_pair(PU_PICTURE, p_frame_byteio ) );
- // set previous parse-unit
+ // set previous parse-unit
mp_previous_parse_unit = p_frame_byteio;
- // save stats
+ // save stats
p_frame_byteio->CollateByteStats(m_sequence_stats);
}
void DiracByteStream::Clear()
{
- while(!m_parse_unit_list.empty())
+ while(!m_parse_unit_list.empty())
{
- ParseUnitByteIO* p_parse_unit = m_parse_unit_list.front().second;
+ ParseUnitByteIO* p_parse_unit=m_parse_unit_list.front().second;
m_parse_unit_list.pop();
if(m_parse_unit_list.empty())
{
delete mp_prev_parse_unit;
- mp_prev_parse_unit = p_parse_unit;
+ mp_prev_parse_unit=p_parse_unit;
}
else
delete p_parse_unit;
@@ -221,8 +221,8 @@ DiracByteStats DiracByteStream::EndSequence()
// create
EndOfSequenceByteIO *p_endofsequence_byteio = new EndOfSequenceByteIO(*this);
- // set previous parse-unit details
- ParseUnitByteIO *mp_previous_parse_unit = mp_prev_parse_unit;
+ // set previous parse-unit details
+ ParseUnitByteIO *mp_previous_parse_unit=mp_prev_parse_unit;
if(!m_parse_unit_list.empty())
mp_previous_parse_unit = m_parse_unit_list.back().second;
@@ -230,8 +230,8 @@ DiracByteStats DiracByteStream::EndSequence()
// set adjacent parse-unit
p_endofsequence_byteio->SetAdjacentParseUnits(mp_previous_parse_unit);
- // push onto to pending list
- m_parse_unit_list.push(std::make_pair(PU_END_OF_SEQUENCE, p_endofsequence_byteio));
+ // push onto to pending list
+ m_parse_unit_list.push(std::make_pair(PU_END_OF_SEQUENCE, p_endofsequence_byteio) );
p_endofsequence_byteio->CollateByteStats(m_sequence_stats);
diff --git a/src/filters/parser/DiracSplitter/libdirac/libdirac_byteio/dirac_byte_stream.h b/src/filters/parser/DiracSplitter/libdirac/libdirac_byteio/dirac_byte_stream.h
index 6d2bf229d..d448b5fca 100644
--- a/src/filters/parser/DiracSplitter/libdirac/libdirac_byteio/dirac_byte_stream.h
+++ b/src/filters/parser/DiracSplitter/libdirac/libdirac_byteio/dirac_byte_stream.h
@@ -53,105 +53,105 @@
namespace dirac
{
-/**
-* Represents a series of bytes in the Dirac bytestream specfication format.
-* These bytes are grouped into more managable parse units by this class.
-*/
-class DiracByteStream : public ByteIO
-{
-public:
-
- /**
- * Constructor
- */
- DiracByteStream();
-
- /**
- * Destructor
- */
- ~DiracByteStream();
-
- /**
- * Adds Dirac-formatted bytes to internal-byte-stream for processing
- *@param start Start of char list
- *@param count Number of chars
- */
- void AddBytes(char* start, int count);
-
- /**
- * Gets the statistics of the most recent parse-unit to be processed
- *@return Byte-statistics
- */
- DiracByteStats GetLastUnitStats();
-
- /**
- * Gets the next parse-unit in the current byte-stream
- */
- ParseUnitByteIO* GetNextParseUnit();
-
-
- /**
- * Gets stats for current sequence
- */
- DiracByteStats GetSequenceStats() const;
-
- /**
- * Adds a random access point to the current Dirac byte stream
- *@param p_seqheader_byteio Sequence header data.
- */
- void AddSequenceHeader(SequenceHeaderByteIO *p_seqheader_byteio);
-
/**
- * Adds a picture to the current Dirac byte stream
- *@param p_frame_byteio Picture stream. This class is now responsible for deleting.
+ * Represents a series of bytes in the Dirac bytestream specfication format.
+ * These bytes are grouped into more managable parse units by this class.
*/
- void AddPicture(PictureByteIO *p_frame_byteio);
-
- /**
- * Clear parse-units
- */
- void Clear();
-
- /**
- * Insert end-of-sequence data
- *@return Sequence stats
- */
- DiracByteStats EndSequence();
-
- /**
- * Gets a pointer to all current output bytes
- */
- const std::string GetBytes();
-
- /**
- * Any info pending?
- */
- bool IsUnitAvailable() const;
-
-private:
-
- void Reset(ParseUnitByteIO* p_curr_unit, int pos);
-
-private:
-
- /**
- * Parse-units in Dirac stream
- */
- typedef std::queue< std::pair <ParseUnitType, ParseUnitByteIO*> > ParseUnitList;
- ParseUnitList m_parse_unit_list;
-
- /**
- * Last unit to be processed
- * Required for specifying the previous parse-unit
- */
- ParseUnitByteIO* mp_prev_parse_unit;
-
- /**
- * Stats for current sequence
- */
- DiracByteStats m_sequence_stats;
-
-};
+ class DiracByteStream : public ByteIO
+ {
+ public:
+
+ /**
+ * Constructor
+ */
+ DiracByteStream();
+
+ /**
+ * Destructor
+ */
+ ~DiracByteStream();
+
+ /**
+ * Adds Dirac-formatted bytes to internal-byte-stream for processing
+ *@param start Start of char list
+ *@param count Number of chars
+ */
+ void AddBytes(char* start, int count);
+
+ /**
+ * Gets the statistics of the most recent parse-unit to be processed
+ *@return Byte-statistics
+ */
+ DiracByteStats GetLastUnitStats();
+
+ /**
+ * Gets the next parse-unit in the current byte-stream
+ */
+ ParseUnitByteIO* GetNextParseUnit();
+
+
+ /**
+ * Gets stats for current sequence
+ */
+ DiracByteStats GetSequenceStats() const;
+
+ /**
+ * Adds a random access point to the current Dirac byte stream
+ *@param p_seqheader_byteio Sequence header data.
+ */
+ void AddSequenceHeader(SequenceHeaderByteIO *p_seqheader_byteio);
+
+ /**
+ * Adds a picture to the current Dirac byte stream
+ *@param p_frame_byteio Picture stream. This class is now responsible for deleting.
+ */
+ void AddPicture(PictureByteIO *p_frame_byteio);
+
+ /**
+ * Clear parse-units
+ */
+ void Clear();
+
+ /**
+ * Insert end-of-sequence data
+ *@return Sequence stats
+ */
+ DiracByteStats EndSequence();
+
+ /**
+ * Gets a pointer to all current output bytes
+ */
+ const std::string GetBytes();
+
+ /**
+ * Any info pending?
+ */
+ bool IsUnitAvailable() const;
+
+ private:
+
+ void Reset(ParseUnitByteIO* p_curr_unit, int pos);
+
+ private:
+
+ /**
+ * Parse-units in Dirac stream
+ */
+ typedef std::queue< std::pair <ParseUnitType, ParseUnitByteIO*> > ParseUnitList;
+ ParseUnitList m_parse_unit_list;
+
+ /**
+ * Last unit to be processed
+ * Required for specifying the previous parse-unit
+ */
+ ParseUnitByteIO* mp_prev_parse_unit;
+
+ /**
+ * Stats for current sequence
+ */
+ DiracByteStats m_sequence_stats;
+
+ };
} // namespace dirac
diff --git a/src/filters/parser/DiracSplitter/libdirac/libdirac_byteio/displayparams_byteio.cpp b/src/filters/parser/DiracSplitter/libdirac/libdirac_byteio/displayparams_byteio.cpp
index f1faa202c..e74a4f278 100644
--- a/src/filters/parser/DiracSplitter/libdirac/libdirac_byteio/displayparams_byteio.cpp
+++ b/src/filters/parser/DiracSplitter/libdirac/libdirac_byteio/displayparams_byteio.cpp
@@ -40,14 +40,14 @@
using namespace dirac;
-SourceParamsByteIO::SourceParamsByteIO(SourceParams& src_params,
- const SourceParams& default_src_params,
- const ByteIO& stream_data):
- ByteIO(stream_data),
- m_src_params(src_params),
- m_default_src_params(default_src_params)
+SourceParamsByteIO::SourceParamsByteIO( SourceParams& src_params,
+ const SourceParams& default_src_params,
+ const ByteIO& stream_data):
+ByteIO(stream_data),
+m_src_params(src_params),
+m_default_src_params(default_src_params)
{
-
+
}
@@ -71,7 +71,7 @@ void SourceParamsByteIO::Input()
// input frame rate
InputFrameRate();
- // input pixel aspect ratio
+ // input pixel aspect ratio
InputPixelAspectRatio();
// input clean area
@@ -98,7 +98,7 @@ void SourceParamsByteIO::Output()
// output frame rate
OutputFrameRate();
- // output pixel aspect ratio
+ // output pixel aspect ratio
OutputPixelAspectRatio();
// output clean area
@@ -135,12 +135,12 @@ void SourceParamsByteIO::InputChromaSamplingFormat()
// set chroma
ChromaFormat chroma_format = IntToChromaFormat(ReadUint());
- if(chroma_format == formatNK)
+ if(chroma_format==formatNK)
DIRAC_THROW_EXCEPTION(
- ERR_INVALID_CHROMA_FORMAT,
- "Dirac does not recognise the specified chroma-format",
- SEVERITY_ACCESSUNIT_ERROR)
- m_src_params.SetCFormat(chroma_format);
+ ERR_INVALID_CHROMA_FORMAT,
+ "Dirac does not recognise the specified chroma-format",
+ SEVERITY_ACCESSUNIT_ERROR)
+ m_src_params.SetCFormat(chroma_format);
}
void SourceParamsByteIO::InputPixelAspectRatio()
@@ -151,24 +151,24 @@ void SourceParamsByteIO::InputPixelAspectRatio()
// read index value
int pixel_aspect_ratio_index = ReadUint();
- PixelAspectRatioType pixel_aspect_ratio = IntToPixelAspectRatioType(pixel_aspect_ratio_index);
- if(pixel_aspect_ratio == PIXEL_ASPECT_RATIO_UNDEFINED)
- DIRAC_THROW_EXCEPTION(
- ERR_INVALID_PIXEL_ASPECT_RATIO,
- "Dirac does not recognise the specified pixel_aspect_ratio",
- SEVERITY_ACCESSUNIT_ERROR)
-
- if(pixel_aspect_ratio_index != PIXEL_ASPECT_RATIO_CUSTOM)
- {
- m_src_params.SetPixelAspectRatio(pixel_aspect_ratio);
- }
- else
- {
- // read num/denom
- int numerator = ReadUint();
- int denominator = ReadUint();
- m_src_params.SetPixelAspectRatio(numerator, denominator);
- }
+ PixelAspectRatioType pixel_aspect_ratio=IntToPixelAspectRatioType(pixel_aspect_ratio_index);
+ if(pixel_aspect_ratio==PIXEL_ASPECT_RATIO_UNDEFINED)
+ DIRAC_THROW_EXCEPTION(
+ ERR_INVALID_PIXEL_ASPECT_RATIO,
+ "Dirac does not recognise the specified pixel_aspect_ratio",
+ SEVERITY_ACCESSUNIT_ERROR)
+
+ if(pixel_aspect_ratio_index!=PIXEL_ASPECT_RATIO_CUSTOM)
+ {
+ m_src_params.SetPixelAspectRatio(pixel_aspect_ratio);
+ }
+ else
+ {
+ // read num/denom
+ int numerator = ReadUint();
+ int denominator = ReadUint();
+ m_src_params.SetPixelAspectRatio(numerator, denominator);
+ }
}
@@ -178,10 +178,10 @@ void SourceParamsByteIO::InputCleanArea()
if(!clean_area_flag)
return;
- m_src_params.SetCleanWidth(ReadUint());
- m_src_params.SetCleanHeight(ReadUint());
- m_src_params.SetLeftOffset(ReadUint());
- m_src_params.SetTopOffset(ReadUint());
+ m_src_params.SetCleanWidth( ReadUint() );
+ m_src_params.SetCleanHeight( ReadUint() );
+ m_src_params.SetLeftOffset( ReadUint() );
+ m_src_params.SetTopOffset( ReadUint() );
}
void SourceParamsByteIO::InputColourMatrix()
@@ -214,8 +214,8 @@ void SourceParamsByteIO::InputColourSpecification()
// read index value
int colour_spec_index = ReadUint();
- m_src_params.SetColourSpecification(colour_spec_index);
- if(colour_spec_index == 0)
+ m_src_params.SetColourSpecification( colour_spec_index );
+ if(colour_spec_index==0)
{
InputColourPrimaries();
InputColourMatrix();
@@ -230,24 +230,24 @@ void SourceParamsByteIO::InputFrameRate()
return;
int frame_rate_index = ReadUint();
- FrameRateType frame_rate = IntToFrameRateType(frame_rate_index);
- if(frame_rate == FRAMERATE_UNDEFINED)
+ FrameRateType frame_rate=IntToFrameRateType(frame_rate_index);
+ if(frame_rate==FRAMERATE_UNDEFINED)
DIRAC_THROW_EXCEPTION(
- ERR_INVALID_PICTURE_RATE,
- "Dirac does not recognise the specified frame-rate",
- SEVERITY_ACCESSUNIT_ERROR)
+ ERR_INVALID_PICTURE_RATE,
+ "Dirac does not recognise the specified frame-rate",
+ SEVERITY_ACCESSUNIT_ERROR)
- if(frame_rate_index != FRAMERATE_CUSTOM)
- {
- m_src_params.SetFrameRate(frame_rate);
- }
- else
- {
- // read num/denom
- int numerator = ReadUint();
- int denominator = ReadUint();
- m_src_params.SetFrameRate(numerator, denominator);
- }
+ if(frame_rate_index!=FRAMERATE_CUSTOM)
+ {
+ m_src_params.SetFrameRate(frame_rate);
+ }
+ else
+ {
+ // read num/denom
+ int numerator = ReadUint();
+ int denominator = ReadUint();
+ m_src_params.SetFrameRate(numerator, denominator);
+ }
}
void SourceParamsByteIO::InputScanFormat()
@@ -257,7 +257,7 @@ void SourceParamsByteIO::InputScanFormat()
return;
unsigned int source_sampling = ReadUint();
- if(source_sampling > 1)
+ if (source_sampling > 1)
{
std::ostringstream errstr;
errstr << "Source Sampling " << source_sampling
@@ -279,25 +279,25 @@ void SourceParamsByteIO::InputSignalRange()
// read index value
int signal_range_index = ReadUint();
SignalRangeType signal_range = IntToSignalRangeType(signal_range_index);
- if(signal_range == SIGNAL_RANGE_UNDEFINED)
+ if(signal_range==SIGNAL_RANGE_UNDEFINED)
DIRAC_THROW_EXCEPTION(
- ERR_INVALID_SIGNAL_RANGE,
- "Dirac does not recognise the specified signal-range",
- SEVERITY_ACCESSUNIT_ERROR)
+ ERR_INVALID_SIGNAL_RANGE,
+ "Dirac does not recognise the specified signal-range",
+ SEVERITY_ACCESSUNIT_ERROR)
- if(signal_range_index != SIGNAL_RANGE_CUSTOM)
- {
- m_src_params.SetSignalRange(signal_range);
- }
- else
- {
- // read luma values
- m_src_params.SetLumaOffset(ReadUint());
- m_src_params.SetLumaExcursion(ReadUint());
- // read chroma values
- m_src_params.SetChromaOffset(ReadUint());
- m_src_params.SetChromaExcursion(ReadUint());
- }
+ if(signal_range_index!=SIGNAL_RANGE_CUSTOM)
+ {
+ m_src_params.SetSignalRange(signal_range);
+ }
+ else
+ {
+ // read luma values
+ m_src_params.SetLumaOffset( ReadUint() );
+ m_src_params.SetLumaExcursion( ReadUint() );
+ // read chroma values
+ m_src_params.SetChromaOffset( ReadUint() );
+ m_src_params.SetChromaExcursion( ReadUint() );
+ }
}
void SourceParamsByteIO::InputTransferFunction()
@@ -315,8 +315,8 @@ void SourceParamsByteIO::OutputFrameSize()
{
// output 'is custom' dimensions flag
- bool is_custom = (m_src_params.Xl() != m_default_src_params.Xl() ||
- m_src_params.Yl() != m_default_src_params.Yl());
+ bool is_custom = (m_src_params.Xl()!=m_default_src_params.Xl() ||
+ m_src_params.Yl()!=m_default_src_params.Yl());
WriteBit(is_custom);
@@ -332,8 +332,8 @@ void SourceParamsByteIO::OutputFrameSize()
void SourceParamsByteIO::OutputChromaSamplingFormat()
{
// output 'is default' flag
- bool not_default = m_src_params.CFormat() != m_default_src_params.CFormat();
-
+ bool not_default = m_src_params.CFormat()!=m_default_src_params.CFormat();
+
WriteBit(not_default);
if(!not_default)
@@ -346,20 +346,20 @@ void SourceParamsByteIO::OutputChromaSamplingFormat()
void SourceParamsByteIO::OutputPixelAspectRatio()
{
- if(m_src_params.PixelAspectRatioIndex() != PIXEL_ASPECT_RATIO_CUSTOM
- && m_src_params.PixelAspectRatioIndex() == m_default_src_params.PixelAspectRatioIndex())
+ if (m_src_params.PixelAspectRatioIndex()!= PIXEL_ASPECT_RATIO_CUSTOM
+ && m_src_params.PixelAspectRatioIndex() == m_default_src_params.PixelAspectRatioIndex())
{
// default frame rate index
WriteBit(0);
return;
}
// Non-defaults
- WriteBit(1);
+ WriteBit(1);
// Picture rate index
WriteUint(m_src_params.PixelAspectRatioIndex());
-
- if(!m_src_params.PixelAspectRatioIndex()) // i,e. custom value
+
+ if (!m_src_params.PixelAspectRatioIndex()) // i,e. custom value
{
WriteUint(m_src_params.PixelAspectRatio().m_num);
WriteUint(m_src_params.PixelAspectRatio().m_denom);
@@ -369,10 +369,10 @@ void SourceParamsByteIO::OutputPixelAspectRatio()
void SourceParamsByteIO::OutputCleanArea()
{
- if(m_src_params.CleanWidth() != m_default_src_params.CleanWidth() ||
- m_src_params.CleanHeight() != m_default_src_params.CleanHeight() ||
- m_src_params.LeftOffset() != m_default_src_params.LeftOffset() ||
- m_src_params.TopOffset() != m_default_src_params.TopOffset())
+ if (m_src_params.CleanWidth() != m_default_src_params.CleanWidth() ||
+ m_src_params.CleanHeight() != m_default_src_params.CleanHeight() ||
+ m_src_params.LeftOffset() != m_default_src_params.LeftOffset() ||
+ m_src_params.TopOffset() != m_default_src_params.TopOffset())
{
WriteBit(1); // non-default value
WriteUint(m_src_params.CleanWidth());
@@ -386,9 +386,9 @@ void SourceParamsByteIO::OutputCleanArea()
void SourceParamsByteIO::OutputColourSpecification()
{
- if(m_src_params.ColourSpecificationIndex() &&
- m_src_params.ColourSpecificationIndex() ==
- m_default_src_params.ColourSpecificationIndex())
+ if (m_src_params.ColourSpecificationIndex() &&
+ m_src_params.ColourSpecificationIndex() ==
+ m_default_src_params.ColourSpecificationIndex())
{
// default colour specification
WriteBit(0);
@@ -396,14 +396,14 @@ void SourceParamsByteIO::OutputColourSpecification()
}
// Non-defaults
- WriteBit(1);
+ WriteBit(1);
// Output Colour specification index
WriteUint(m_src_params.ColourSpecificationIndex());
- if(!m_src_params.ColourSpecificationIndex()) // i,e, custom values
+ if (!m_src_params.ColourSpecificationIndex()) // i,e, custom values
{
// Output Colour Primaries
- if(m_src_params.ColourPrimariesIndex() == m_default_src_params.ColourPrimariesIndex())
+ if (m_src_params.ColourPrimariesIndex() == m_default_src_params.ColourPrimariesIndex())
{
// default value
WriteBit(0);
@@ -415,7 +415,7 @@ void SourceParamsByteIO::OutputColourSpecification()
}
// Output Colour Matrix
- if(m_src_params.ColourMatrixIndex() == m_default_src_params.ColourMatrixIndex())
+ if (m_src_params.ColourMatrixIndex() == m_default_src_params.ColourMatrixIndex())
{
// default value
WriteBit(0);
@@ -427,7 +427,7 @@ void SourceParamsByteIO::OutputColourSpecification()
}
// Output TransferFunction
- if(m_src_params.TransferFunctionIndex() == m_default_src_params.TransferFunctionIndex())
+ if (m_src_params.TransferFunctionIndex() == m_default_src_params.TransferFunctionIndex())
{
// default value
WriteBit(0);
@@ -442,20 +442,20 @@ void SourceParamsByteIO::OutputColourSpecification()
void SourceParamsByteIO::OutputFrameRate()
{
- if(m_src_params.FrameRateIndex() != FRAMERATE_CUSTOM
- && m_src_params.FrameRateIndex() == m_default_src_params.FrameRateIndex())
+ if (m_src_params.FrameRateIndex()!=FRAMERATE_CUSTOM
+ && m_src_params.FrameRateIndex() == m_default_src_params.FrameRateIndex())
{
// default frame rate index
WriteBit(0);
return;
}
// Non-defaults
- WriteBit(1);
+ WriteBit(1);
// Picture rate index
WriteUint(m_src_params.FrameRateIndex());
-
- if(!m_src_params.FrameRateIndex()) // i,e. custom value
+
+ if (!m_src_params.FrameRateIndex()) // i,e. custom value
{
WriteUint(m_src_params.FrameRate().m_num);
WriteUint(m_src_params.FrameRate().m_denom);
@@ -465,8 +465,8 @@ void SourceParamsByteIO::OutputFrameRate()
void SourceParamsByteIO::OutputScanFormat()
{
// output 'is default' flag
- bool not_interlace_default = m_src_params.SourceSampling() != m_default_src_params.SourceSampling();
-
+ bool not_interlace_default = m_src_params.SourceSampling()!=m_default_src_params.SourceSampling();
+
WriteBit(not_interlace_default);
if(!not_interlace_default)
@@ -479,20 +479,20 @@ void SourceParamsByteIO::OutputScanFormat()
void SourceParamsByteIO::OutputSignalRange()
{
- if(m_src_params.SignalRangeIndex() != SIGNAL_RANGE_CUSTOM &&
- m_src_params.SignalRangeIndex() == m_default_src_params.SignalRangeIndex())
+ if (m_src_params.SignalRangeIndex()!=SIGNAL_RANGE_CUSTOM &&
+ m_src_params.SignalRangeIndex() == m_default_src_params.SignalRangeIndex())
{
// defaults
WriteBit(0);
return;
}
-
+
// Non-defaults
- WriteBit(1);
+ WriteBit(1);
// Output Signal Range Index
WriteUint(m_src_params.SignalRangeIndex());
- if(!m_src_params.SignalRangeIndex()) // i.e. custom values
+ if (!m_src_params.SignalRangeIndex()) // i.e. custom values
{
WriteUint(m_src_params.LumaOffset());
WriteUint(m_src_params.LumaExcursion());
diff --git a/src/filters/parser/DiracSplitter/libdirac/libdirac_byteio/displayparams_byteio.h b/src/filters/parser/DiracSplitter/libdirac/libdirac_byteio/displayparams_byteio.h
index 12cf7cec6..bc5fe823d 100644
--- a/src/filters/parser/DiracSplitter/libdirac/libdirac_byteio/displayparams_byteio.h
+++ b/src/filters/parser/DiracSplitter/libdirac/libdirac_byteio/displayparams_byteio.h
@@ -51,148 +51,148 @@
namespace dirac
{
-
-/**
-* Represents compressed source-parameter data contained in a sequence header
-*/
-class SourceParamsByteIO : public ByteIO
-{
-public:
-
- /**
- * Constructor for Input/Output
- *@param src_params Source parameters
- *@param default_src_params Default Source parameters
- *@param stream_data Source/Destination of data
- */
- SourceParamsByteIO(SourceParams& src_params,
- const SourceParams& default_src_params,
- const ByteIO& stream_data);
- /**
- * Destructor
- */
- ~SourceParamsByteIO();
-
- /**
- * Reads source params information from Dirac byte-format
- */
- void Input();
-
- /**
- * Outputs source params information to Dirac byte-format
- */
- void Output();
-
-protected:
-
-
-private:
-
- /**
- * Reads frame dimensions
- */
- void InputFrameSize();
-
- /**
- * Reads Chroma Sampling Format
- */
- void InputChromaSamplingFormat();
-
- /**
- * Reads pixel aspect ratio info
- */
- void InputPixelAspectRatio();
-
- /**
- * Reads clean-area info
- */
- void InputCleanArea();
-
- /**
- * Reads colour-matrix info
- */
- void InputColourMatrix();
-
- /**
- * Reads primary-colour info
- */
- void InputColourPrimaries();
-
- /**
- * Reads colour spec info
- */
- void InputColourSpecification();
-
- /**
- * Reads frame-rate info
- */
- void InputFrameRate();
-
- /**
- * Reads Scan info
- */
- void InputScanFormat();
-
- /**
- * Reads signal range info
- */
- void InputSignalRange();
-
- /**
- * Reads transfer-function info
- */
- void InputTransferFunction();
-
- /**
- * Outputs frame dimensions
- */
- void OutputFrameSize();
-
- /**
- * Outputs Chroma Sampling Format
- */
- void OutputChromaSamplingFormat();
-
- /**
- * Outputs pixel aspect ratio info
- */
- void OutputPixelAspectRatio();
-
- /**
- * Outputs clean-area info
- */
- void OutputCleanArea();
-
- /**
- * Outputs colour spec info
- */
- void OutputColourSpecification();
-
- /**
- * Outputs frame-rate info
- */
- void OutputFrameRate();
-
- /**
- * Outputs Scan info
- */
- void OutputScanFormat();
-
- /**
- * Outputs signal range info
- */
- void OutputSignalRange();
-
- /**
- * Source parameters for input/ouput
- */
- SourceParams& m_src_params;
-
- /**
- * Default source parameters
- */
- const SourceParams& m_default_src_params;
-};
+
+ /**
+ * Represents compressed source-parameter data contained in a sequence header
+ */
+ class SourceParamsByteIO : public ByteIO
+ {
+ public:
+
+ /**
+ * Constructor for Input/Output
+ *@param src_params Source parameters
+ *@param default_src_params Default Source parameters
+ *@param stream_data Source/Destination of data
+ */
+ SourceParamsByteIO( SourceParams& src_params,
+ const SourceParams& default_src_params,
+ const ByteIO& stream_data);
+ /**
+ * Destructor
+ */
+ ~SourceParamsByteIO();
+
+ /**
+ * Reads source params information from Dirac byte-format
+ */
+ void Input();
+
+ /**
+ * Outputs source params information to Dirac byte-format
+ */
+ void Output();
+
+ protected:
+
+
+ private:
+
+ /**
+ * Reads frame dimensions
+ */
+ void InputFrameSize();
+
+ /**
+ * Reads Chroma Sampling Format
+ */
+ void InputChromaSamplingFormat();
+
+ /**
+ * Reads pixel aspect ratio info
+ */
+ void InputPixelAspectRatio();
+
+ /**
+ * Reads clean-area info
+ */
+ void InputCleanArea();
+
+ /**
+ * Reads colour-matrix info
+ */
+ void InputColourMatrix();
+
+ /**
+ * Reads primary-colour info
+ */
+ void InputColourPrimaries();
+
+ /**
+ * Reads colour spec info
+ */
+ void InputColourSpecification();
+
+ /**
+ * Reads frame-rate info
+ */
+ void InputFrameRate();
+
+ /**
+ * Reads Scan info
+ */
+ void InputScanFormat();
+
+ /**
+ * Reads signal range info
+ */
+ void InputSignalRange();
+
+ /**
+ * Reads transfer-function info
+ */
+ void InputTransferFunction();
+
+ /**
+ * Outputs frame dimensions
+ */
+ void OutputFrameSize();
+
+ /**
+ * Outputs Chroma Sampling Format
+ */
+ void OutputChromaSamplingFormat();
+
+ /**
+ * Outputs pixel aspect ratio info
+ */
+ void OutputPixelAspectRatio();
+
+ /**
+ * Outputs clean-area info
+ */
+ void OutputCleanArea();
+
+ /**
+ * Outputs colour spec info
+ */
+ void OutputColourSpecification();
+
+ /**
+ * Outputs frame-rate info
+ */
+ void OutputFrameRate();
+
+ /**
+ * Outputs Scan info
+ */
+ void OutputScanFormat();
+
+ /**
+ * Outputs signal range info
+ */
+ void OutputSignalRange();
+
+ /**
+ * Source parameters for input/ouput
+ */
+ SourceParams& m_src_params;
+
+ /**
+ * Default source parameters
+ */
+ const SourceParams& m_default_src_params;
+ };
} // namespace dirac
diff --git a/src/filters/parser/DiracSplitter/libdirac/libdirac_byteio/endofsequence_byteio.cpp b/src/filters/parser/DiracSplitter/libdirac/libdirac_byteio/endofsequence_byteio.cpp
index 58f74870a..ca0144e8e 100644
--- a/src/filters/parser/DiracSplitter/libdirac/libdirac_byteio/endofsequence_byteio.cpp
+++ b/src/filters/parser/DiracSplitter/libdirac/libdirac_byteio/endofsequence_byteio.cpp
@@ -46,9 +46,9 @@ using namespace std;
EndOfSequenceByteIO::EndOfSequenceByteIO(const ByteIO& byte_io):
- ParseUnitByteIO(byte_io)
+ParseUnitByteIO(byte_io)
{
-
+
}
@@ -65,14 +65,14 @@ void EndOfSequenceByteIO::CollateByteStats(DiracByteStats& dirac_byte_stats)
//-------------private-------------------------------------------------------
-
+
unsigned char EndOfSequenceByteIO::CalcParseCode() const
{
unsigned char code = 0;
- // set end-of-sequence parse-code
- SetBits(code, PARSE_CODE_END_OF_SEQUENCE);
+ // set end-of-sequence parse-code
+ SetBits(code, PARSE_CODE_END_OF_SEQUENCE);
- return code;
+ return code;
}
diff --git a/src/filters/parser/DiracSplitter/libdirac/libdirac_byteio/endofsequence_byteio.h b/src/filters/parser/DiracSplitter/libdirac/libdirac_byteio/endofsequence_byteio.h
index f1b7bdb87..0bce3997f 100644
--- a/src/filters/parser/DiracSplitter/libdirac/libdirac_byteio/endofsequence_byteio.h
+++ b/src/filters/parser/DiracSplitter/libdirac/libdirac_byteio/endofsequence_byteio.h
@@ -50,60 +50,54 @@
namespace dirac
{
-/**
-* Signals the end of a sequence in a Dirac-formatted bitstream. Current Accessunit parameters
-* are no longer valid for subsequent frames
-*/
-class EndOfSequenceByteIO : public ParseUnitByteIO
-{
-public:
-
- /**
- * Constructor
- *@param stream_data Stream parameters
- */
- EndOfSequenceByteIO(const ByteIO& stream_data);
-
- /**
- * Destructor
- */
- ~EndOfSequenceByteIO();
-
-
- /**
- * Gets parse-unit type
- */
- ParseUnitType GetType() const
- {
- return PU_END_OF_SEQUENCE;
- }
-
- /**
- * Gathers byte stats on the end of sequence data
- *@param dirac_byte_stats Stat container
- */
- void CollateByteStats(DiracByteStats& dirac_byte_stats);
-protected:
-
/**
- * Calculates number of bytes to start of next unit
- *@return Zero(0) End of sequence does not specify a 'next'unit
+ * Signals the end of a sequence in a Dirac-formatted bitstream. Current Accessunit parameters
+ * are no longer valid for subsequent frames
*/
- int CalcNextUnitOffset()
+ class EndOfSequenceByteIO : public ParseUnitByteIO
{
- return 0;
- }
-
-private:
-
- /**
- * Calculates parse-code based on picture parameters
- *@return Char bit-set
- */
- unsigned char CalcParseCode() const;
-
-
-};
+ public:
+
+ /**
+ * Constructor
+ *@param stream_data Stream parameters
+ */
+ EndOfSequenceByteIO(const ByteIO& stream_data);
+
+ /**
+ * Destructor
+ */
+ ~EndOfSequenceByteIO();
+
+
+ /**
+ * Gets parse-unit type
+ */
+ ParseUnitType GetType() const { return PU_END_OF_SEQUENCE;}
+
+ /**
+ * Gathers byte stats on the end of sequence data
+ *@param dirac_byte_stats Stat container
+ */
+ void CollateByteStats(DiracByteStats& dirac_byte_stats);
+ protected:
+
+ /**
+ * Calculates number of bytes to start of next unit
+ *@return Zero(0) End of sequence does not specify a 'next'unit
+ */
+ int CalcNextUnitOffset() { return 0;}
+
+ private:
+
+ /**
+ * Calculates parse-code based on picture parameters
+ *@return Char bit-set
+ */
+ unsigned char CalcParseCode() const;
+
+
+ };
} // namespace dirac
diff --git a/src/filters/parser/DiracSplitter/libdirac/libdirac_byteio/mvdata_byteio.cpp b/src/filters/parser/DiracSplitter/libdirac/libdirac_byteio/mvdata_byteio.cpp
index 075fe0176..2ed0357aa 100644
--- a/src/filters/parser/DiracSplitter/libdirac/libdirac_byteio/mvdata_byteio.cpp
+++ b/src/filters/parser/DiracSplitter/libdirac/libdirac_byteio/mvdata_byteio.cpp
@@ -42,35 +42,35 @@
using namespace dirac;
MvDataByteIO::MvDataByteIO(PictureParams& pparams,
- PicturePredParams& picpredparams):
- ByteIO(),
- m_pparams(pparams),
- m_picpredparams(picpredparams),
- m_splitmode_data(),
- m_predmode_data(),
- m_mv1hblock_data(),
- m_mv1vblock_data(),
- m_mv2hblock_data(),
- m_mv2vblock_data(),
- m_ydcblock_data(),
- m_udcblock_data(),
- m_vdcblock_data()
+ PicturePredParams& picpredparams):
+ByteIO(),
+m_pparams(pparams),
+m_picpredparams(picpredparams),
+m_splitmode_data(),
+m_predmode_data(),
+m_mv1hblock_data(),
+m_mv1vblock_data(),
+m_mv2hblock_data(),
+m_mv2vblock_data(),
+m_ydcblock_data(),
+m_udcblock_data(),
+m_vdcblock_data()
{}
MvDataByteIO::MvDataByteIO(ByteIO &byte_io, PictureParams& pparams,
- PicturePredParams& picpredparams):
- ByteIO(byte_io),
- m_pparams(pparams),
- m_picpredparams(picpredparams),
- m_splitmode_data(byte_io),
- m_predmode_data(byte_io),
- m_mv1hblock_data(byte_io),
- m_mv1vblock_data(byte_io),
- m_mv2hblock_data(byte_io),
- m_mv2vblock_data(byte_io),
- m_ydcblock_data(byte_io),
- m_udcblock_data(byte_io),
- m_vdcblock_data(byte_io)
+ PicturePredParams& picpredparams):
+ByteIO(byte_io),
+m_pparams(pparams),
+m_picpredparams(picpredparams),
+m_splitmode_data(byte_io),
+m_predmode_data(byte_io),
+m_mv1hblock_data(byte_io),
+m_mv1vblock_data(byte_io),
+m_mv2hblock_data(byte_io),
+m_mv2vblock_data(byte_io),
+m_ydcblock_data(byte_io),
+m_udcblock_data(byte_io),
+m_vdcblock_data(byte_io)
{}
MvDataByteIO::~MvDataByteIO()
@@ -85,50 +85,50 @@ void MvDataByteIO::CollateByteStats(DiracByteStats& dirac_byte_stats)
int MvDataByteIO::GetSize() const
{
- if(m_pparams.NumRefs() == 2)
+ if (m_pparams.NumRefs()==2)
return ByteIO::GetSize() +
- m_splitmode_data.GetSize() +
- m_predmode_data.GetSize() +
- m_mv1hblock_data.GetSize() +
- m_mv1vblock_data.GetSize() +
- m_mv2hblock_data.GetSize() +
- m_mv2vblock_data.GetSize() +
- m_ydcblock_data.GetSize() +
- m_udcblock_data.GetSize() +
+ m_splitmode_data.GetSize()+
+ m_predmode_data.GetSize()+
+ m_mv1hblock_data.GetSize()+
+ m_mv1vblock_data.GetSize()+
+ m_mv2hblock_data.GetSize()+
+ m_mv2vblock_data.GetSize()+
+ m_ydcblock_data.GetSize()+
+ m_udcblock_data.GetSize()+
m_vdcblock_data.GetSize();
else
return ByteIO::GetSize() +
- m_splitmode_data.GetSize() +
- m_predmode_data.GetSize() +
- m_mv1hblock_data.GetSize() +
- m_mv1vblock_data.GetSize() +
- m_ydcblock_data.GetSize() +
- m_udcblock_data.GetSize() +
+ m_splitmode_data.GetSize()+
+ m_predmode_data.GetSize()+
+ m_mv1hblock_data.GetSize()+
+ m_mv1vblock_data.GetSize()+
+ m_ydcblock_data.GetSize()+
+ m_udcblock_data.GetSize()+
m_vdcblock_data.GetSize();
}
const std::string MvDataByteIO::GetBytes()
{
//Output header and block data
- if(m_pparams.NumRefs() == 2)
+ if (m_pparams.NumRefs()==2 )
return ByteIO::GetBytes() +
- m_splitmode_data.GetBytes() +
- m_predmode_data.GetBytes() +
- m_mv1hblock_data.GetBytes() +
- m_mv1vblock_data.GetBytes() +
- m_mv2hblock_data.GetBytes() +
- m_mv2vblock_data.GetBytes() +
- m_ydcblock_data.GetBytes() +
- m_udcblock_data.GetBytes() +
+ m_splitmode_data.GetBytes()+
+ m_predmode_data.GetBytes()+
+ m_mv1hblock_data.GetBytes()+
+ m_mv1vblock_data.GetBytes()+
+ m_mv2hblock_data.GetBytes()+
+ m_mv2vblock_data.GetBytes()+
+ m_ydcblock_data.GetBytes()+
+ m_udcblock_data.GetBytes()+
m_vdcblock_data.GetBytes();
else
return ByteIO::GetBytes() +
- m_splitmode_data.GetBytes() +
- m_predmode_data.GetBytes() +
- m_mv1hblock_data.GetBytes() +
- m_mv1vblock_data.GetBytes() +
- m_ydcblock_data.GetBytes() +
- m_udcblock_data.GetBytes() +
+ m_splitmode_data.GetBytes()+
+ m_predmode_data.GetBytes()+
+ m_mv1hblock_data.GetBytes()+
+ m_mv1vblock_data.GetBytes()+
+ m_ydcblock_data.GetBytes()+
+ m_udcblock_data.GetBytes()+
m_vdcblock_data.GetBytes();
}
@@ -186,7 +186,7 @@ void MvDataByteIO::OutputBlockParams()
// output custom block params flag
unsigned int pidx = BlockParametersIndex(olb_params);
WriteUint(pidx);
- if(pidx == 0) // custom block params
+ if (pidx == 0) // custom block params
{
// output Xblen
WriteUint(olb_params.Xblen());
@@ -204,7 +204,7 @@ void MvDataByteIO::InputBlockParams()
OLBParams olb_params;
unsigned int p_idx = ReadUint();
- if(p_idx == 0)
+ if (p_idx == 0)
{
// Input Xblen
olb_params.SetXblen(ReadUint());
@@ -216,7 +216,7 @@ void MvDataByteIO::InputBlockParams()
olb_params.SetYbsep(ReadUint());
}
else
- SetDefaultBlockParameters(olb_params, p_idx);
+ SetDefaultBlockParameters (olb_params, p_idx);
m_picpredparams.SetLumaBlockParams(olb_params);
}
@@ -231,13 +231,13 @@ void MvDataByteIO::InputMVPrecision()
{
// Input Motion vector precision
MVPrecisionType mv_prec = IntToMVPrecisionType(ReadUint());
- if(mv_prec == MV_PRECISION_UNDEFINED)
+ if(mv_prec==MV_PRECISION_UNDEFINED)
DIRAC_THROW_EXCEPTION(
- ERR_INVALID_MOTION_VECTOR_PRECISION,
- "Dirac does not recognise the specified MV precision",
- SEVERITY_PICTURE_ERROR)
+ ERR_INVALID_MOTION_VECTOR_PRECISION,
+ "Dirac does not recognise the specified MV precision",
+ SEVERITY_PICTURE_ERROR)
- m_picpredparams.SetMVPrecision(mv_prec);
+ m_picpredparams.SetMVPrecision(mv_prec);
}
void MvDataByteIO::OutputGlobalMotionParams()
@@ -252,15 +252,15 @@ void MvDataByteIO::InputGlobalMotionParams()
{
// Always setting global motion to false
// Using Global motion flag
- if(ReadBool())
+ if (ReadBool())
{
m_picpredparams.SetUsingGlobalMotion(true);
// NOTE: FIXME - input actual global motion params in future
DIRAC_THROW_EXCEPTION(
- ERR_UNSUPPORTED_STREAM_DATA,
- "Cannot handle global motion parameters",
- SEVERITY_PICTURE_ERROR)
+ ERR_UNSUPPORTED_STREAM_DATA,
+ "Cannot handle global motion parameters",
+ SEVERITY_PICTURE_ERROR)
}
else
m_picpredparams.SetUsingGlobalMotion(false);
@@ -278,7 +278,7 @@ void MvDataByteIO::InputFramePredictionMode()
// TODO - need to process this field when alternative prediction modes
// become available.
unsigned int frame_pred_mode = ReadUint();
- if(frame_pred_mode != 0)
+ if (frame_pred_mode != 0)
{
DIRAC_THROW_EXCEPTION(
ERR_UNSUPPORTED_STREAM_DATA,
@@ -291,16 +291,16 @@ void MvDataByteIO::InputFramePredictionMode()
void MvDataByteIO::OutputPictureWeights()
{
// Output default weights flags
- if(m_picpredparams.PictureWeightsBits() != 1 ||
- m_picpredparams.Ref1Weight() != 1 ||
- (m_pparams.Refs().size() > 1 && m_picpredparams.Ref2Weight() != 1))
+ if (m_picpredparams.PictureWeightsBits() != 1 ||
+ m_picpredparams.Ref1Weight() != 1 ||
+ (m_pparams.Refs().size() > 1 && m_picpredparams.Ref2Weight() != 1) )
{
- WriteBit(true);
+ WriteBit(true);
// Output weight precision bits
WriteUint(m_picpredparams.PictureWeightsBits());
// Output Ref1 weight
WriteSint(m_picpredparams.Ref1Weight());
- if(m_pparams.Refs().size() > 1)
+ if (m_pparams.Refs().size() > 1)
{
// Output Ref1 weight
WriteSint(m_picpredparams.Ref2Weight());
@@ -308,17 +308,17 @@ void MvDataByteIO::OutputPictureWeights()
}
else
{
- WriteBit(false);
+ WriteBit(false);
}
}
void MvDataByteIO::InputPictureWeights()
{
- if(ReadBool())
+ if (ReadBool())
{
m_picpredparams.SetPictureWeightsPrecision(ReadUint());
m_picpredparams.SetRef1Weight(ReadSint());
- if(m_pparams.Refs().size() > 1)
+ if (m_pparams.Refs().size() > 1)
m_picpredparams.SetRef2Weight(ReadSint());
else
m_picpredparams.SetRef2Weight(0);
diff --git a/src/filters/parser/DiracSplitter/libdirac/libdirac_byteio/mvdata_byteio.h b/src/filters/parser/DiracSplitter/libdirac/libdirac_byteio/mvdata_byteio.h
index ff809c3d5..578a3594e 100644
--- a/src/filters/parser/DiracSplitter/libdirac/libdirac_byteio/mvdata_byteio.h
+++ b/src/filters/parser/DiracSplitter/libdirac/libdirac_byteio/mvdata_byteio.h
@@ -53,244 +53,217 @@
namespace dirac
{
-/**
-* Represents compressed sequence-parameter data used in an AccessUnit
-*/
-class MvDataByteIO : public ByteIO
-{
-public:
-
- /**
- * Constructor
- *@param pparams Picture Params
- *@param picpredparams Picture prediction parameters
- */
- MvDataByteIO(PictureParams& pparams,
- PicturePredParams& picpredparams);
-
- /**
- * Constructor
- *@param byte_io Input/Output Byte stream
- *@param pparams Picture Params
- *@param picpredparams Picture prediction parameters
- */
- MvDataByteIO(ByteIO &byte_io, PictureParams& pparams,
- PicturePredParams& picpredparams);
-
- /**
- * Destructor
- */
- virtual ~MvDataByteIO();
-
- /**
- * Gathers byte stats on the motion vector data
- *@param dirac_byte_stats Stat container
- */
- void CollateByteStats(DiracByteStats& dirac_byte_stats);
-
- /**
- * Outputs motion vector data Dirac byte-format
- */
- void Output();
-
- /**
- * Inputs motion vector information
- */
- void Input();
-
-
- /**
- * Get string containing coded bytes
- */
- virtual const std::string GetBytes();
-
/**
- * Return pointer to the superblock splitting modes ByteIO stream
+ * Represents compressed sequence-parameter data used in an AccessUnit
*/
- MvDataElementByteIO* SplitModeData()
+ class MvDataByteIO : public ByteIO
{
- return &m_splitmode_data;
+ public:
+
+ /**
+ * Constructor
+ *@param pparams Picture Params
+ *@param picpredparams Picture prediction parameters
+ */
+ MvDataByteIO(PictureParams& pparams,
+ PicturePredParams& picpredparams);
+
+ /**
+ * Constructor
+ *@param byte_io Input/Output Byte stream
+ *@param pparams Picture Params
+ *@param picpredparams Picture prediction parameters
+ */
+ MvDataByteIO(ByteIO &byte_io, PictureParams& pparams,
+ PicturePredParams& picpredparams);
+
+ /**
+ * Destructor
+ */
+ virtual ~MvDataByteIO();
+
+ /**
+ * Gathers byte stats on the motion vector data
+ *@param dirac_byte_stats Stat container
+ */
+ void CollateByteStats(DiracByteStats& dirac_byte_stats);
+
+ /**
+ * Outputs motion vector data Dirac byte-format
+ */
+ void Output();
+
+ /**
+ * Inputs motion vector information
+ */
+ void Input();
+
+
+ /**
+ * Get string containing coded bytes
+ */
+ virtual const std::string GetBytes();
+
+ /**
+ * Return pointer to the superblock splitting modes ByteIO stream
+ */
+ MvDataElementByteIO* SplitModeData() { return &m_splitmode_data; };
+
+ /**
+ * Return pointer to the superblock splitting modes ByteIO stream
+ */
+ MvDataElementByteIO* PredModeData() { return &m_predmode_data; };
+
+ /**
+ * Return pointer to the block MVs reference 1 ByteIO stream
+ */
+ MvDataElementByteIO* MV1HorizData() { return &m_mv1hblock_data; };
+
+ /**
+ * Return pointer to the block MVs reference 1 ByteIO stream
+ */
+ MvDataElementByteIO* MV1VertData() { return &m_mv1vblock_data; };
+
+ /**
+ * Return pointer to the block MV reference 2 ByteIO stream
+ */
+ MvDataElementByteIO* MV2HorizData() { return &m_mv2hblock_data; };
+
+ /**
+ * Return pointer to the block MV reference 2 ByteIO stream
+ */
+ MvDataElementByteIO* MV2VertData() { return &m_mv2vblock_data; };
+
+ /**
+ * Return pointer to the block Y DC values ByteIO stream
+ */
+ MvDataElementByteIO* YDCData() { return &m_ydcblock_data; };
+
+ /**
+ * Return pointer to the block U DC values ByteIO stream
+ */
+ MvDataElementByteIO* UDCData() { return &m_udcblock_data; };
+
+ /**
+ * Return pointer to the block V DC values ByteIO stream
+ */
+ MvDataElementByteIO* VDCData() { return &m_vdcblock_data; };
+
+ /**
+ * Return the size
+ */
+ int GetSize() const;
+
+ protected:
+
+
+ private:
+ /**
+ * Inputs block parameters
+ */
+ void InputBlockParams();
+
+ /**
+ * Inputs Motion vector precision data
+ */
+ void InputMVPrecision();
+
+ /**
+ * Inputs global motion parameters
+ */
+ void InputGlobalMotionParams();
+
+ /**
+ * Inputs picture prediction mode
+ */
+ void InputFramePredictionMode();
+
+ /**
+ * Inputs Picture Weights
+ */
+ void InputPictureWeights();
+
+ /**
+ * Outputs block parameters
+ */
+ void OutputBlockParams();
+
+ /**
+ * Outputs Motion vector precision data
+ */
+ void OutputMVPrecision();
+
+ /**
+ * Outputs global motion parameters
+ */
+ void OutputGlobalMotionParams();
+
+ /**
+ * Outputs picture prediction mode
+ */
+ void OutputFramePredictionMode();
+
+ /**
+ * Outputs Picture Weights
+ */
+ void OutputPictureWeights();
+
+ /**
+ * Sequence paramters for intput/output
+ */
+ PictureParams& m_pparams;
+
+ /**
+ * Codec params - EncParams for Output and DecParams for input
+ */
+ PicturePredParams& m_picpredparams;
+
+ /**
+ * block data containing split modes
+ */
+ MvDataElementByteIO m_splitmode_data;
+
+ /**
+ * block data containing prediction modes
+ */
+ MvDataElementByteIO m_predmode_data;
+
+ /**
+ * block data containing horizontal MV components for reference 1
+ */
+ MvDataElementByteIO m_mv1hblock_data;
+
+ /**
+ * block data containing vertical MV components for reference 1
+ */
+ MvDataElementByteIO m_mv1vblock_data;
+
+ /**
+ * block data containing horizontal MV components for reference 2
+ */
+ MvDataElementByteIO m_mv2hblock_data;
+
+ /**
+ * block data containing vertical MV components for reference 2
+ */
+ MvDataElementByteIO m_mv2vblock_data;
+
+ /**
+ * block data containing Y DC data
+ */
+ MvDataElementByteIO m_ydcblock_data;
+
+ /**
+ * block data containing U DC data
+ */
+ MvDataElementByteIO m_udcblock_data;
+
+ /**
+ * block data containing V DC data
+ */
+ MvDataElementByteIO m_vdcblock_data;
};
- /**
- * Return pointer to the superblock splitting modes ByteIO stream
- */
- MvDataElementByteIO* PredModeData()
- {
- return &m_predmode_data;
- };
-
- /**
- * Return pointer to the block MVs reference 1 ByteIO stream
- */
- MvDataElementByteIO* MV1HorizData()
- {
- return &m_mv1hblock_data;
- };
-
- /**
- * Return pointer to the block MVs reference 1 ByteIO stream
- */
- MvDataElementByteIO* MV1VertData()
- {
- return &m_mv1vblock_data;
- };
-
- /**
- * Return pointer to the block MV reference 2 ByteIO stream
- */
- MvDataElementByteIO* MV2HorizData()
- {
- return &m_mv2hblock_data;
- };
-
- /**
- * Return pointer to the block MV reference 2 ByteIO stream
- */
- MvDataElementByteIO* MV2VertData()
- {
- return &m_mv2vblock_data;
- };
-
- /**
- * Return pointer to the block Y DC values ByteIO stream
- */
- MvDataElementByteIO* YDCData()
- {
- return &m_ydcblock_data;
- };
-
- /**
- * Return pointer to the block U DC values ByteIO stream
- */
- MvDataElementByteIO* UDCData()
- {
- return &m_udcblock_data;
- };
-
- /**
- * Return pointer to the block V DC values ByteIO stream
- */
- MvDataElementByteIO* VDCData()
- {
- return &m_vdcblock_data;
- };
-
- /**
- * Return the size
- */
- int GetSize() const;
-
-protected:
-
-
-private:
- /**
- * Inputs block parameters
- */
- void InputBlockParams();
-
- /**
- * Inputs Motion vector precision data
- */
- void InputMVPrecision();
-
- /**
- * Inputs global motion parameters
- */
- void InputGlobalMotionParams();
-
- /**
- * Inputs picture prediction mode
- */
- void InputFramePredictionMode();
-
- /**
- * Inputs Picture Weights
- */
- void InputPictureWeights();
-
- /**
- * Outputs block parameters
- */
- void OutputBlockParams();
-
- /**
- * Outputs Motion vector precision data
- */
- void OutputMVPrecision();
-
- /**
- * Outputs global motion parameters
- */
- void OutputGlobalMotionParams();
-
- /**
- * Outputs picture prediction mode
- */
- void OutputFramePredictionMode();
-
- /**
- * Outputs Picture Weights
- */
- void OutputPictureWeights();
-
- /**
- * Sequence paramters for intput/output
- */
- PictureParams& m_pparams;
-
- /**
- * Codec params - EncParams for Output and DecParams for input
- */
- PicturePredParams& m_picpredparams;
-
- /**
- * block data containing split modes
- */
- MvDataElementByteIO m_splitmode_data;
-
- /**
- * block data containing prediction modes
- */
- MvDataElementByteIO m_predmode_data;
-
- /**
- * block data containing horizontal MV components for reference 1
- */
- MvDataElementByteIO m_mv1hblock_data;
-
- /**
- * block data containing vertical MV components for reference 1
- */
- MvDataElementByteIO m_mv1vblock_data;
-
- /**
- * block data containing horizontal MV components for reference 2
- */
- MvDataElementByteIO m_mv2hblock_data;
-
- /**
- * block data containing vertical MV components for reference 2
- */
- MvDataElementByteIO m_mv2vblock_data;
-
- /**
- * block data containing Y DC data
- */
- MvDataElementByteIO m_ydcblock_data;
-
- /**
- * block data containing U DC data
- */
- MvDataElementByteIO m_udcblock_data;
-
- /**
- * block data containing V DC data
- */
- MvDataElementByteIO m_vdcblock_data;
-};
-
} // namespace dirac
#endif
diff --git a/src/filters/parser/DiracSplitter/libdirac/libdirac_byteio/mvdataelement_byteio.cpp b/src/filters/parser/DiracSplitter/libdirac/libdirac_byteio/mvdataelement_byteio.cpp
index 524845df4..f8785616d 100644
--- a/src/filters/parser/DiracSplitter/libdirac/libdirac_byteio/mvdataelement_byteio.cpp
+++ b/src/filters/parser/DiracSplitter/libdirac/libdirac_byteio/mvdataelement_byteio.cpp
@@ -44,14 +44,14 @@
using namespace dirac;
MvDataElementByteIO::MvDataElementByteIO():
- ByteIO(),
- m_block_data()
+ByteIO(),
+m_block_data()
{
}
MvDataElementByteIO::MvDataElementByteIO(ByteIO &byte_io):
- ByteIO(byte_io),
- m_block_data(byte_io)
+ByteIO(byte_io),
+m_block_data(byte_io)
{
}
@@ -88,7 +88,7 @@ void MvDataElementByteIO::Input()
}
void MvDataElementByteIO::Output()
-{
+{
//Output size of block data
WriteUint(m_block_data.GetSize());
diff --git a/src/filters/parser/DiracSplitter/libdirac/libdirac_byteio/mvdataelement_byteio.h b/src/filters/parser/DiracSplitter/libdirac/libdirac_byteio/mvdataelement_byteio.h
index 6896ac7ea..2e0aa4211 100644
--- a/src/filters/parser/DiracSplitter/libdirac/libdirac_byteio/mvdataelement_byteio.h
+++ b/src/filters/parser/DiracSplitter/libdirac/libdirac_byteio/mvdataelement_byteio.h
@@ -53,80 +53,74 @@
namespace dirac
{
-
-/**
-* Represents compressed sequence-parameter data used in an AccessUnit
-*/
-class MvDataElementByteIO : public ByteIO
-{
-public:
-
- /**
- * Constructor
- */
- MvDataElementByteIO();
-
- /**
- * Constructor
- *@param byte_io Input/Output Byte stream
- */
- MvDataElementByteIO(ByteIO &byte_io);
-
- /**
- * Destructor
- */
- virtual ~MvDataElementByteIO();
-
- /**
- * Outputs motion vector data Dirac byte-format
- */
- void Output();
-
- /**
- * Inputs motion vector information
- */
- void Input();
-
-
- /**
- * Get string containing coded bytes
- */
- virtual const std::string GetBytes();
-
+
/**
- * Return pointer to the block data ByteIO stream
+ * Represents compressed sequence-parameter data used in an AccessUnit
*/
- ByteIO* DataBlock()
+ class MvDataElementByteIO : public ByteIO
{
- return &m_block_data;
+ public:
+
+ /**
+ * Constructor
+ */
+ MvDataElementByteIO();
+
+ /**
+ * Constructor
+ *@param byte_io Input/Output Byte stream
+ */
+ MvDataElementByteIO(ByteIO &byte_io);
+
+ /**
+ * Destructor
+ */
+ virtual ~MvDataElementByteIO();
+
+ /**
+ * Outputs motion vector data Dirac byte-format
+ */
+ void Output();
+
+ /**
+ * Inputs motion vector information
+ */
+ void Input();
+
+
+ /**
+ * Get string containing coded bytes
+ */
+ virtual const std::string GetBytes();
+
+ /**
+ * Return pointer to the block data ByteIO stream
+ */
+ ByteIO* DataBlock() { return &m_block_data; };
+
+ /**
+ * Return the input block data size
+ */
+ unsigned int DataBlockSize() { return m_block_size; }
+
+ /**
+ * Return the size
+ */
+ int GetSize() const;
+
+ protected:
+
+ /**
+ * block data
+ */
+ ByteIO m_block_data;
+
+ /**
+ * In block data size
+ */
+ unsigned int m_block_size;
};
- /**
- * Return the input block data size
- */
- unsigned int DataBlockSize()
- {
- return m_block_size;
- }
-
- /**
- * Return the size
- */
- int GetSize() const;
-
-protected:
-
- /**
- * block data
- */
- ByteIO m_block_data;
-
- /**
- * In block data size
- */
- unsigned int m_block_size;
-};
-
} // namespace dirac
#endif
diff --git a/src/filters/parser/DiracSplitter/libdirac/libdirac_byteio/parseparams_byteio.cpp b/src/filters/parser/DiracSplitter/libdirac/libdirac_byteio/parseparams_byteio.cpp
index cd3691ee0..5034933bc 100644
--- a/src/filters/parser/DiracSplitter/libdirac/libdirac_byteio/parseparams_byteio.cpp
+++ b/src/filters/parser/DiracSplitter/libdirac/libdirac_byteio/parseparams_byteio.cpp
@@ -44,15 +44,15 @@ const unsigned int PP_AU_PICTURE_NUM_SIZE = 4;
using namespace dirac;
-ParseParamsByteIO::ParseParamsByteIO(const ByteIO& stream_data,
- ParseParams &parse_params,
- EncoderParams &enc_params):
- ByteIO(stream_data),
- m_parse_params(parse_params)
+ParseParamsByteIO::ParseParamsByteIO( const ByteIO& stream_data,
+ ParseParams &parse_params,
+ EncoderParams &enc_params):
+ByteIO(stream_data),
+m_parse_params(parse_params)
{
- if(enc_params.NumL1() == 0)
+ if (enc_params.NumL1() == 0)
{
- if(!enc_params.UsingAC())
+ if (!enc_params.UsingAC())
{
// Simple Profile
m_parse_params.SetProfile(1);
@@ -66,15 +66,15 @@ ParseParamsByteIO::ParseParamsByteIO(const ByteIO& stream_data,
else
{
// Main (Long GOP) profile
- m_parse_params.SetProfile(8);
+ m_parse_params.SetProfile(8);
}
// FIXME - no support for Low Delay Profile
}
-ParseParamsByteIO::ParseParamsByteIO(const ByteIO& stream_data,
+ParseParamsByteIO::ParseParamsByteIO( const ByteIO& stream_data,
ParseParams &parse_params):
- ByteIO(stream_data),
- m_parse_params(parse_params)
+ByteIO(stream_data),
+m_parse_params(parse_params)
{
@@ -89,8 +89,8 @@ void ParseParamsByteIO::CheckVersion()
std::ostringstream errstr;
ParseParams def_parse_params;
- if(m_parse_params.MajorVersion() > def_parse_params.MajorVersion() ||
- m_parse_params.MajorVersion() == 0 ||
+ if (m_parse_params.MajorVersion() > def_parse_params.MajorVersion() ||
+ m_parse_params.MajorVersion() == 0 ||
(m_parse_params.MajorVersion() == def_parse_params.MajorVersion() &&
m_parse_params.MinorVersion() > def_parse_params.MinorVersion()))
{
@@ -103,7 +103,7 @@ void ParseParamsByteIO::CheckVersion()
errstr << ". May not be able to decode bitstream correctly" << std::endl;
}
- if(errstr.str().size())
+ if (errstr.str().size())
{
DiracException err(
ERR_UNSUPPORTED_STREAM_DATA,
@@ -120,21 +120,21 @@ void ParseParamsByteIO::CheckProfile()
// No profiles were specified in versions 1.0, 1.1, and 2.0 and 2.1.
// So for these versions profile should be 0 in the bitstream
- if(m_parse_params.MajorVersion() <= 2 &&
- m_parse_params.MinorVersion() < 2 &&
- m_parse_params.Profile() != 0)
+ if (m_parse_params.MajorVersion() <= 2 &&
+ m_parse_params.MinorVersion() < 2 &&
+ m_parse_params.Profile() != 0)
{
errstr << "Cannot handle profile " << m_parse_params.Profile()
<< " for bitstream version " << m_parse_params.MajorVersion()
<< "." << m_parse_params.MinorVersion();
errstr << ". May not be able to decode bitstream correctly" << std::endl;
}
- else if(m_parse_params.MajorVersion() == def_parse_params.MajorVersion() &&
- m_parse_params.MinorVersion() == def_parse_params.MinorVersion() &&
- m_parse_params.Profile() != 1 /* Simple */ &&
- m_parse_params.Profile() != 2 /* Main (Intra) */ &&
- m_parse_params.Profile() != 8 /* Main (Long GOP) */
- )
+ else if (m_parse_params.MajorVersion() == def_parse_params.MajorVersion() &&
+ m_parse_params.MinorVersion() == def_parse_params.MinorVersion() &&
+ m_parse_params.Profile() != 1 /* Simple */ &&
+ m_parse_params.Profile() != 2 /* Main (Intra) */ &&
+ m_parse_params.Profile() != 8 /* Main (Long GOP) */
+ )
{
errstr << "Cannot handle profile " << m_parse_params.Profile()
<< " for bitstream version " << m_parse_params.MajorVersion()
@@ -144,7 +144,7 @@ void ParseParamsByteIO::CheckProfile()
errstr << ". May not be able to decode bitstream correctly" << std::endl;
}
- if(errstr.str().size())
+ if (errstr.str().size())
{
DiracException err(
ERR_UNSUPPORTED_STREAM_DATA,
@@ -160,15 +160,15 @@ void ParseParamsByteIO::CheckLevel()
ParseParams def_parse_params;
// No resources constraints for decoder
- if(def_parse_params.Level() == 0)
+ if (def_parse_params.Level() == 0)
return;
// Constraints on Decoder. Can Handles level 1 for Simple and Main (Intra)
// profiles, and level 128 for Main (Long GOP) Profile.
- if(def_parse_params.Level() != 0)
+ if (def_parse_params.Level() != 0)
{
- if((m_parse_params.Profile() <= 2 && m_parse_params.Level() != 1) ||
- (m_parse_params.Profile() == 8 && m_parse_params.Level() != 128))
+ if ((m_parse_params.Profile() <= 2 && m_parse_params.Level() != 1) ||
+ (m_parse_params.Profile() ==8 && m_parse_params.Level() != 128))
{
errstr << "Cannot handle Level " << m_parse_params.Level()
<< " for bitstream version " << m_parse_params.MajorVersion()
@@ -180,7 +180,7 @@ void ParseParamsByteIO::CheckLevel()
}
}
- if(errstr.str().size())
+ if (errstr.str().size())
{
DiracException err(
ERR_UNSUPPORTED_STREAM_DATA,
diff --git a/src/filters/parser/DiracSplitter/libdirac/libdirac_byteio/parseparams_byteio.h b/src/filters/parser/DiracSplitter/libdirac/libdirac_byteio/parseparams_byteio.h
index 04f040c2d..1e5423f31 100644
--- a/src/filters/parser/DiracSplitter/libdirac/libdirac_byteio/parseparams_byteio.h
+++ b/src/filters/parser/DiracSplitter/libdirac/libdirac_byteio/parseparams_byteio.h
@@ -51,65 +51,65 @@
namespace dirac
{
-
-/**
-* Represents compressed parse-parameter data used in an AccessUnit
-*/
-class ParseParamsByteIO : public ByteIO
-{
-public:
-
- /**
- * Constructor
- *@param stream_data Destination of data
- *@param parse_params Parse parameters
- *@param enc_params Encoder parameters
- */
- ParseParamsByteIO(const ByteIO& stream_data,
- ParseParams &parse_params,
- EncoderParams &enc_params);
-
- /**
- * Constructor
- *@param stream_data Source of data
- *@param parse_params Destination of parse params
- */
- ParseParamsByteIO(const ByteIO& stream_data,
- ParseParams &parse_params);
-
- /**
- * Destructor
- */
- ~ParseParamsByteIO();
-
- /**
- * Reads parse information from Dirac byte-format
- */
- void Input();
-
- /**
- * Outputs parse information to Dirac byte-format
- */
- void Output();
-
- /**
- * Get access-unit number
- */
- int GetIdNumber() const;
-
-protected:
-
-private:
- void CheckVersion();
- void CheckProfile();
- void CheckLevel();
-
-private:
+
/**
- * Reference to parse parameters
+ * Represents compressed parse-parameter data used in an AccessUnit
*/
- ParseParams& m_parse_params;
-};
+ class ParseParamsByteIO : public ByteIO
+ {
+ public:
+
+ /**
+ * Constructor
+ *@param stream_data Destination of data
+ *@param parse_params Parse parameters
+ *@param enc_params Encoder parameters
+ */
+ ParseParamsByteIO(const ByteIO& stream_data,
+ ParseParams &parse_params,
+ EncoderParams &enc_params);
+
+ /**
+ * Constructor
+ *@param stream_data Source of data
+ *@param parse_params Destination of parse params
+ */
+ ParseParamsByteIO(const ByteIO& stream_data,
+ ParseParams &parse_params);
+
+ /**
+ * Destructor
+ */
+ ~ParseParamsByteIO();
+
+ /**
+ * Reads parse information from Dirac byte-format
+ */
+ void Input();
+
+ /**
+ * Outputs parse information to Dirac byte-format
+ */
+ void Output();
+
+ /**
+ * Get access-unit number
+ */
+ int GetIdNumber() const;
+
+ protected:
+
+ private:
+ void CheckVersion();
+ void CheckProfile();
+ void CheckLevel();
+
+ private:
+ /**
+ * Reference to parse parameters
+ */
+ ParseParams& m_parse_params;
+ };
} // namespace dirac
diff --git a/src/filters/parser/DiracSplitter/libdirac/libdirac_byteio/parseunit_byteio.cpp b/src/filters/parser/DiracSplitter/libdirac/libdirac_byteio/parseunit_byteio.cpp
index 9d4ac83de..56c0ebb8b 100644
--- a/src/filters/parser/DiracSplitter/libdirac/libdirac_byteio/parseunit_byteio.cpp
+++ b/src/filters/parser/DiracSplitter/libdirac/libdirac_byteio/parseunit_byteio.cpp
@@ -52,30 +52,30 @@ const int PU_NEXT_PARSE_OFFSET_SIZE = 4;
const int PU_PREVIOUS_PARSE_OFFSET_SIZE = 4;
const int PU_PREFIX_SIZE = 4;
const int PU_PARSE_CODE_SIZE = 1;
-const int PU_PARSEUNIT_SIZE = PU_NEXT_PARSE_OFFSET_SIZE + PU_PREVIOUS_PARSE_OFFSET_SIZE +
+const int PU_PARSEUNIT_SIZE = PU_NEXT_PARSE_OFFSET_SIZE + PU_PREVIOUS_PARSE_OFFSET_SIZE+
PU_PREFIX_SIZE + PU_PARSE_CODE_SIZE;
ParseUnitByteIO::ParseUnitByteIO():
- ByteIO(),
- m_previous_parse_offset(0),
- m_next_parse_offset(0)
+ByteIO(),
+m_previous_parse_offset(0),
+m_next_parse_offset(0)
{
}
ParseUnitByteIO::ParseUnitByteIO(const ByteIO& byte_io):
- ByteIO(byte_io),
- m_previous_parse_offset(0),
- m_next_parse_offset(0)
+ByteIO(byte_io),
+m_previous_parse_offset(0),
+m_next_parse_offset(0)
{
}
ParseUnitByteIO::ParseUnitByteIO(const ParseUnitByteIO& parseunit_byteio):
- ByteIO(parseunit_byteio),
- m_previous_parse_offset(parseunit_byteio.m_previous_parse_offset),
- m_next_parse_offset(parseunit_byteio.m_next_parse_offset),
- m_parse_code(parseunit_byteio.m_parse_code)
+ByteIO(parseunit_byteio),
+m_previous_parse_offset(parseunit_byteio.m_previous_parse_offset),
+m_next_parse_offset(parseunit_byteio.m_next_parse_offset),
+m_parse_code(parseunit_byteio.m_parse_code)
{
}
@@ -113,16 +113,16 @@ bool ParseUnitByteIO::Input()
bool ParseUnitByteIO::IsValid()
{
- if(IsEndOfSequence())
+ if (IsEndOfSequence())
return true;
// Skip past the end of current parse unit
- SeekGet(m_next_parse_offset - GetSize(), ios_base::cur);
+ SeekGet(m_next_parse_offset-GetSize(), ios_base::cur);
// check the next series of bytes are the parse-info prefix
string prefix = InputUnString(PU_PREFIX_SIZE);
- if(prefix == PU_PREFIX)
+ if(prefix==PU_PREFIX)
{
unsigned char next_parse_code;
@@ -133,28 +133,28 @@ bool ParseUnitByteIO::IsValid()
int next_unit_previous_parse_offset;
next_unit_previous_parse_offset = ReadUintLit(PU_PREVIOUS_PARSE_OFFSET_SIZE);
- if(next_unit_previous_parse_offset == m_next_parse_offset)
+ if (next_unit_previous_parse_offset == m_next_parse_offset)
{
- SeekGet(-(m_next_parse_offset - GetSize() + PU_PARSEUNIT_SIZE), ios_base::cur);
+ SeekGet(-(m_next_parse_offset-GetSize()+PU_PARSEUNIT_SIZE), ios_base::cur);
return true;
}
}
- SeekGet(-(m_next_parse_offset - GetSize()), ios_base::cur);
+ SeekGet(-(m_next_parse_offset-GetSize()), ios_base::cur);
return false;
}
bool ParseUnitByteIO::CanSkip()
{
- if(m_next_parse_offset == 0 || m_next_parse_offset == GetSize())
+ if(m_next_parse_offset==0 || m_next_parse_offset == GetSize())
return true;
// Skip past the end of current parse unit and past the header of the
// next unit
- SeekGet(m_next_parse_offset - GetSize() + GetSize(), ios_base::cur);
+ SeekGet(m_next_parse_offset-GetSize() + GetSize(), ios_base::cur);
if(GetReadBytePosition() >= 0)
{
- SeekGet(-(m_next_parse_offset - GetSize() + GetSize()), ios_base::cur);
- return true; // success
+ SeekGet(-(m_next_parse_offset-GetSize() + GetSize()), ios_base::cur);
+ return true; // success
}
// end of stream reached
@@ -171,15 +171,15 @@ const string ParseUnitByteIO::GetBytes()
//FIXME : Need to do this properly.
// Write the parse offsets in Big Endian format
- for(int i = PU_NEXT_PARSE_OFFSET_SIZE - 1; i >= 0; --i)
+ for(int i=PU_NEXT_PARSE_OFFSET_SIZE-1; i >= 0; --i)
{
- unsigned char cp = (m_next_parse_offset >> (i * 8)) & 0xff;
+ unsigned char cp = (m_next_parse_offset>>(i*8)) & 0xff;
parse_string << cp;
}
- for(int i = PU_PREVIOUS_PARSE_OFFSET_SIZE - 1; i >= 0; --i)
+ for(int i=PU_PREVIOUS_PARSE_OFFSET_SIZE-1; i >= 0; --i)
{
- unsigned char cp = (m_previous_parse_offset >> (i * 8)) & 0xff;
+ unsigned char cp = (m_previous_parse_offset>>(i*8)) & 0xff;
parse_string << cp;
}
@@ -251,32 +251,32 @@ int ParseUnitByteIO::CalcNextUnitOffset()
bool ParseUnitByteIO::SyncToUnitStart()
{
- // locate parse-unit prefix
+ // locate parse-unit prefix
string byte_buffer;
- while(CanRead() == true && mp_stream->tellg() >= 0)
+ while(CanRead()==true && mp_stream->tellg() >= 0)
{
// ensure current buffer length
if((int)byte_buffer.size() == PU_PREFIX_SIZE)
{
- byte_buffer.assign(byte_buffer.substr(1, PU_PREFIX_SIZE - 1));
+ byte_buffer.assign(byte_buffer.substr(1,PU_PREFIX_SIZE-1));
}
// read next byte
byte_buffer.push_back(InputUnByte());
//look to see if we have prefix
- if(byte_buffer == PU_PREFIX)
+ if(byte_buffer==PU_PREFIX)
{
// check we can read a parse-unit
//int prev_pos = mp_stream->tellg();
- mp_stream->seekg(PU_PARSEUNIT_SIZE - PU_PREFIX_SIZE, ios_base::cur);
+ mp_stream->seekg (PU_PARSEUNIT_SIZE-PU_PREFIX_SIZE, ios_base::cur);
int cur_pos = mp_stream->tellg();
- if(cur_pos < 0) // past end of stream
+ if (cur_pos < 0) // past end of stream
{
mp_stream->clear();
return false;
}
- mp_stream->seekg(-(PU_PARSEUNIT_SIZE - PU_PREFIX_SIZE), ios_base::cur);
+ mp_stream->seekg(-(PU_PARSEUNIT_SIZE-PU_PREFIX_SIZE), ios_base::cur);
return true;
}
diff --git a/src/filters/parser/DiracSplitter/libdirac/libdirac_byteio/parseunit_byteio.h b/src/filters/parser/DiracSplitter/libdirac/libdirac_byteio/parseunit_byteio.h
index ab015d1fe..8d7742afa 100644
--- a/src/filters/parser/DiracSplitter/libdirac/libdirac_byteio/parseunit_byteio.h
+++ b/src/filters/parser/DiracSplitter/libdirac/libdirac_byteio/parseunit_byteio.h
@@ -53,216 +53,193 @@
namespace dirac
{
-/* Types of parse-unit */
-typedef enum
-{
- PU_SEQ_HEADER = 0,
- PU_PICTURE,
- PU_END_OF_SEQUENCE,
- PU_AUXILIARY_DATA,
- PU_PADDING_DATA,
- PU_CORE_PICTURE,
- PU_LOW_DELAY_PICTURE,
- PU_UNDEFINED
-} ParseUnitType;
-
-/**
-* Represents a collection of data in a Dirac bytestream that can be parsed as a
-* self-contained unit
-*/
-class ParseUnitByteIO : public ByteIO
-{
-public:
-
- /**
- * Constructor
- */
- ParseUnitByteIO();
-
- /**
- * Constructor
- *@param byte_io Stream parameters
- */
- ParseUnitByteIO(const ByteIO& byte_io);
-
- /**
- * Constructor
- *@param parseunit_byteio Parse-unit parameters
- */
- ParseUnitByteIO(const ParseUnitByteIO& parseunit_byteio);
-
- /**
- * Destructor
- */
- ~ParseUnitByteIO();
-
- /**
- * Gathers byte stats on the parse-unit data
- *@param dirac_byte_stats Stat container
- */
- virtual void CollateByteStats(DiracByteStats& dirac_byte_stats);
-
- /**
- * Reads from byte-stream to find parse data
- *@return <B>false</B> if not enough data in stream
- */
- bool Input(); // decoding
-
- /**
- * Accesses validity of a unit by comparing it with an adjacent unit
- */
- bool IsValid();
-
- /**
- * Can Skip past the entire parse-unit
- *@return <B>false</B> Nothing to skip to
- */
- bool CanSkip();
-
- /**
- * Gets string containing coded bytes
- */
- virtual const std::string GetBytes(); // encoding
-
- /**
- * Set next/previous parse-unit values
- *@param p_prev_parseunit Previous parse-unit
- */
- void SetAdjacentParseUnits(ParseUnitByteIO *p_prev_parseunit); // encoding
-
- /*
- * Gets number of bytes input/output within unit
- */
- virtual int GetSize() const;
-
- /**
- * Gets expected number of bytes to start of next parse-unit
- */
- int GetNextParseOffset() const;
-
- /**
- * Gets number of bytes to start of previous parse-unit
- */
- int GetPreviousParseOffset() const;
-
- /**
- * Gets parse-unit type
- */
- virtual ParseUnitType GetType() const;
-
- /**
- * Returns true is parse unit is a Sequence Header
- */
- bool IsSeqHeader() const
- {
- return m_parse_code == 0x00;
- }
-
- /**
- * Returns true is parse unit is an End of Sequence unit
- */
- bool IsEndOfSequence() const
- {
- return m_parse_code == 0x10;
- }
-
- /**
- * Returns true is parse unit is Auxiliary Data
- */
- bool IsAuxiliaryData() const
- {
- return (m_parse_code & 0xF8) == 0x20;
- }
-
- /**
- * Returns true is parse unit is Padding data
- */
- bool IsPaddingData() const
- {
- return m_parse_code == 0x30;
- }
-
- /**
- * Returns true is parse unit is Picture data
- */
- bool IsPicture() const
- {
- return ((m_parse_code & 0x08) == 0x08);
- }
-
- /**
- * Returns true is parse unit is Low Delay Sybtax unit
- */
- bool IsLowDelay() const
- {
- return ((m_parse_code & 0x88) == 0x88);
- }
-
- /**
- * Returns true is parse unit is Core syntax unit
- */
- bool IsCoreSyntax() const
- {
- return ((m_parse_code & 0x88) == 0x08);
- }
-
- /**
- * Returns true is parse unit uses Arithmetic coding
- */
- bool IsUsingAC() const
+ /* Types of parse-unit */
+ typedef enum {
+ PU_SEQ_HEADER=0,
+ PU_PICTURE,
+ PU_END_OF_SEQUENCE,
+ PU_AUXILIARY_DATA,
+ PU_PADDING_DATA,
+ PU_CORE_PICTURE,
+ PU_LOW_DELAY_PICTURE,
+ PU_UNDEFINED
+ } ParseUnitType;
+
+ /**
+ * Represents a collection of data in a Dirac bytestream that can be parsed as a
+ * self-contained unit
+ */
+ class ParseUnitByteIO : public ByteIO
{
- return ((m_parse_code & 0x48) == 0x08);
- }
-
-protected:
-
- /**
- * Calculates number of bytes to start of next unit
- *@return Number of bytes to next unit
- */
- virtual int CalcNextUnitOffset();
-
- /**
- * Pure virtual method for calculating parse-code
- *@return Char containing bit-set for parse-unit parameters
- */
- virtual unsigned char CalcParseCode() const
- {
- return 0; // encoding
- }
-
- /**
- * Locates start of parse-unit
- *@return <B>false</B> if not enough data
- */
- bool SyncToUnitStart(); // decoding
-
- /**
- * Get parse code
- */
- unsigned char GetParseCode() const
- {
- return m_parse_code;
- }
-
-private:
-
- /**
- * Number of bytes to next parse-unit
- */
- int m_previous_parse_offset;
-
- /**
- * Number of bytes to previous parse-unit
- */
- int m_next_parse_offset;
-
- /**
- * Parse-type-identifier
- */
- unsigned char m_parse_code;
-
-};
+ public:
+
+ /**
+ * Constructor
+ */
+ ParseUnitByteIO();
+
+ /**
+ * Constructor
+ *@param byte_io Stream parameters
+ */
+ ParseUnitByteIO(const ByteIO& byte_io);
+
+ /**
+ * Constructor
+ *@param parseunit_byteio Parse-unit parameters
+ */
+ ParseUnitByteIO(const ParseUnitByteIO& parseunit_byteio);
+
+ /**
+ * Destructor
+ */
+ ~ParseUnitByteIO();
+
+ /**
+ * Gathers byte stats on the parse-unit data
+ *@param dirac_byte_stats Stat container
+ */
+ virtual void CollateByteStats(DiracByteStats& dirac_byte_stats);
+
+ /**
+ * Reads from byte-stream to find parse data
+ *@return <B>false</B> if not enough data in stream
+ */
+ bool Input(); // decoding
+
+ /**
+ * Accesses validity of a unit by comparing it with an adjacent unit
+ */
+ bool IsValid();
+
+ /**
+ * Can Skip past the entire parse-unit
+ *@return <B>false</B> Nothing to skip to
+ */
+ bool CanSkip();
+
+ /**
+ * Gets string containing coded bytes
+ */
+ virtual const std::string GetBytes(); // encoding
+
+ /**
+ * Set next/previous parse-unit values
+ *@param p_prev_parseunit Previous parse-unit
+ */
+ void SetAdjacentParseUnits(ParseUnitByteIO *p_prev_parseunit); // encoding
+
+ /*
+ * Gets number of bytes input/output within unit
+ */
+ virtual int GetSize() const;
+
+ /**
+ * Gets expected number of bytes to start of next parse-unit
+ */
+ int GetNextParseOffset() const;
+
+ /**
+ * Gets number of bytes to start of previous parse-unit
+ */
+ int GetPreviousParseOffset() const;
+
+ /**
+ * Gets parse-unit type
+ */
+ virtual ParseUnitType GetType() const;
+
+ /**
+ * Returns true is parse unit is a Sequence Header
+ */
+ bool IsSeqHeader() const
+ { return m_parse_code==0x00; }
+
+ /**
+ * Returns true is parse unit is an End of Sequence unit
+ */
+ bool IsEndOfSequence() const
+ { return m_parse_code==0x10; }
+
+ /**
+ * Returns true is parse unit is Auxiliary Data
+ */
+ bool IsAuxiliaryData() const
+ { return (m_parse_code&0xF8)==0x20; }
+
+ /**
+ * Returns true is parse unit is Padding data
+ */
+ bool IsPaddingData() const
+ { return m_parse_code==0x30; }
+
+ /**
+ * Returns true is parse unit is Picture data
+ */
+ bool IsPicture() const
+ { return ((m_parse_code&0x08)==0x08); }
+
+ /**
+ * Returns true is parse unit is Low Delay Sybtax unit
+ */
+ bool IsLowDelay() const
+ { return ((m_parse_code&0x88)==0x88); }
+
+ /**
+ * Returns true is parse unit is Core syntax unit
+ */
+ bool IsCoreSyntax() const
+ { return ((m_parse_code&0x88)==0x08); }
+
+ /**
+ * Returns true is parse unit uses Arithmetic coding
+ */
+ bool IsUsingAC() const
+ { return ((m_parse_code&0x48)==0x08); }
+
+ protected:
+
+ /**
+ * Calculates number of bytes to start of next unit
+ *@return Number of bytes to next unit
+ */
+ virtual int CalcNextUnitOffset();
+
+ /**
+ * Pure virtual method for calculating parse-code
+ *@return Char containing bit-set for parse-unit parameters
+ */
+ virtual unsigned char CalcParseCode() const { return 0;} // encoding
+
+ /**
+ * Locates start of parse-unit
+ *@return <B>false</B> if not enough data
+ */
+ bool SyncToUnitStart(); // decoding
+
+ /**
+ * Get parse code
+ */
+ unsigned char GetParseCode() const { return m_parse_code;}
+
+ private:
+
+ /**
+ * Number of bytes to next parse-unit
+ */
+ int m_previous_parse_offset;
+
+ /**
+ * Number of bytes to previous parse-unit
+ */
+ int m_next_parse_offset;
+
+ /**
+ * Parse-type-identifier
+ */
+ unsigned char m_parse_code;
+
+ };
} // namespace dirac
diff --git a/src/filters/parser/DiracSplitter/libdirac/libdirac_byteio/picture_byteio.cpp b/src/filters/parser/DiracSplitter/libdirac/libdirac_byteio/picture_byteio.cpp
index 06b52aa62..23231bea7 100644
--- a/src/filters/parser/DiracSplitter/libdirac/libdirac_byteio/picture_byteio.cpp
+++ b/src/filters/parser/DiracSplitter/libdirac/libdirac_byteio/picture_byteio.cpp
@@ -54,37 +54,37 @@ const int CODE_VLC_ENTROPY_CODING_BIT = 6;
const unsigned int MAX_NUM_REFS = 2;
PictureByteIO::PictureByteIO(PictureParams& frame_params,
- int frame_num) :
- ParseUnitByteIO(),
- m_frame_params(frame_params),
- m_frame_num(frame_num),
- m_mv_data(0),
- m_transform_data(0)
+ int frame_num) :
+ParseUnitByteIO(),
+m_frame_params(frame_params),
+m_frame_num(frame_num),
+m_mv_data(0),
+m_transform_data(0)
{
-
+
}
PictureByteIO::PictureByteIO(PictureParams& frame_params,
- const ParseUnitByteIO& parseunit_byteio):
- ParseUnitByteIO(parseunit_byteio),
- m_frame_params(frame_params),
- m_frame_num(0),
- m_mv_data(0),
- m_transform_data(0)
+ const ParseUnitByteIO& parseunit_byteio ):
+ParseUnitByteIO(parseunit_byteio),
+m_frame_params(frame_params),
+m_frame_num(0),
+m_mv_data(0),
+m_transform_data(0)
{
-
+
}
PictureByteIO::~PictureByteIO()
{
//delete block data
- if(m_mv_data)
+ if (m_mv_data)
{
delete m_mv_data;
m_mv_data = 0;
}
- if(m_transform_data)
+ if (m_transform_data)
{
delete m_transform_data;
m_transform_data = 0;
@@ -110,13 +110,13 @@ bool PictureByteIO::Input()
// Use of VLC for entropy coding is supported for
// intra frames only
- if(m_frame_params.GetPictureType() == INTER_PICTURE &&
- m_frame_params.UsingAC() == false)
+ if (m_frame_params.GetPictureType() == INTER_PICTURE &&
+ m_frame_params.UsingAC() == false)
{
DIRAC_THROW_EXCEPTION(
- ERR_UNSUPPORTED_STREAM_DATA,
- "VLC codes for entropy coding of coefficient data supported for Intra frames only",
- SEVERITY_PICTURE_ERROR);
+ ERR_UNSUPPORTED_STREAM_DATA,
+ "VLC codes for entropy coding of coefficient data supported for Intra frames only",
+ SEVERITY_PICTURE_ERROR);
}
// input picture number
@@ -125,10 +125,10 @@ bool PictureByteIO::Input()
// input reference Picture numbers
InputReferencePictures();
-
+
// input retired Picture numbers list
m_frame_params.SetRetiredPictureNum(-1);
- if(IsRef())
+ if (IsRef())
InputRetiredPicture();
// byte align
@@ -137,7 +137,7 @@ bool PictureByteIO::Input()
return true;
}
-const string PictureByteIO::GetBytes()
+const string PictureByteIO::GetBytes()
{
// Write mv data
if(m_frame_params.PicSort().IsInter() && m_mv_data)
@@ -146,7 +146,7 @@ const string PictureByteIO::GetBytes()
}
// Write transform header
- if(m_transform_data)
+ if (m_transform_data)
{
OutputBytes(m_transform_data->GetBytes());
}
@@ -156,15 +156,15 @@ const string PictureByteIO::GetBytes()
int PictureByteIO::GetSize() const
{
int size = 0;
- if(m_mv_data)
+ if (m_mv_data)
size += m_mv_data->GetSize();
- if(m_transform_data)
+ if (m_transform_data)
size += m_transform_data->GetSize();
//std::cerr << "Picture Header Size=" << ByteIO::GetSize();
//std::cerr << "Data Size=" << size << std::endl;
- return size + ParseUnitByteIO::GetSize() + ByteIO::GetSize();
+ return size+ParseUnitByteIO::GetSize()+ByteIO::GetSize();
}
void PictureByteIO::Output()
@@ -172,23 +172,23 @@ void PictureByteIO::Output()
// output picture number
WriteUintLit(m_frame_num, PP_PICTURE_NUM_SIZE);
- if(m_frame_params.GetPictureType() == INTER_PICTURE)
+ if(m_frame_params.GetPictureType()==INTER_PICTURE)
{
// output reference picture numbers
const std::vector<int>& refs = m_frame_params.Refs();
- for(size_t i = 0; i < refs.size() && i < MAX_NUM_REFS; ++i)
+ for(size_t i=0; i < refs.size() && i < MAX_NUM_REFS; ++i)
WriteSint(refs[i] - m_frame_num);
}
// output retired picture
- ASSERTM(m_frame_params.GetReferenceType() == REFERENCE_PICTURE || m_frame_params.RetiredPictureNum() == -1, "Only Reference frames can retire frames");
+ ASSERTM (m_frame_params.GetReferenceType() == REFERENCE_PICTURE || m_frame_params.RetiredPictureNum() == -1, "Only Reference frames can retire frames");
if(m_frame_params.GetReferenceType() == REFERENCE_PICTURE)
{
- if(m_frame_params.RetiredPictureNum() == -1)
+ if (m_frame_params.RetiredPictureNum() == -1)
WriteSint(0);
else
{
- WriteSint(m_frame_params.RetiredPictureNum() - m_frame_num);
+ WriteSint (m_frame_params.RetiredPictureNum() - m_frame_num);
}
}
// byte align output
@@ -198,14 +198,14 @@ void PictureByteIO::Output()
//-------------private-------------------------------------------------------
-
+
unsigned char PictureByteIO::CalcParseCode() const
{
unsigned char code = 0;
int num_refs = m_frame_params.Refs().size();
- if(m_frame_params.GetPictureType() == INTER_PICTURE)
+ if(m_frame_params.GetPictureType()==INTER_PICTURE)
{
// set number of refs
if(num_refs == 1)
@@ -214,42 +214,42 @@ unsigned char PictureByteIO::CalcParseCode() const
SetBit(code, CODE_TWO_REF_BIT);
}
// set ref type
- if(m_frame_params.GetReferenceType() == REFERENCE_PICTURE)
+ if(m_frame_params.GetReferenceType()==REFERENCE_PICTURE)
SetBit(code, CODE_REF_PICTURE_BIT);
// Set parse unit type
SetBit(code, CODE_PUTYPE_1_BIT);
// Set Entropy Coding type
- if(!m_frame_params.UsingAC())
+ if (!m_frame_params.UsingAC())
{
SetBit(code, CODE_VLC_ENTROPY_CODING_BIT);
}
return code;
-
+
}
-void PictureByteIO::InputReferencePictures()
+void PictureByteIO::InputReferencePictures()
{
// get number of frames referred to
- int ref_count = NumRefs();
+ int ref_count = NumRefs();
- // get the number of these frames
+ // get the number of these frames
vector<int>& refs = m_frame_params.Refs();
refs.resize(ref_count);
- for(int i = 0; i < ref_count; ++i)
- refs[i] = m_frame_num + ReadSint();
+ for(int i=0; i < ref_count; ++i)
+ refs[i]=m_frame_num+ReadSint();
}
-
-void PictureByteIO::InputRetiredPicture()
+
+void PictureByteIO::InputRetiredPicture()
{
TESTM(IsRef(), "Retired Picture offset only set for Reference Frames");
// input retired picture offset
int offset = ReadSint();
// input retired frames
- if(offset)
+ if (offset)
{
m_frame_params.SetRetiredPictureNum(m_frame_num + offset);
}
diff --git a/src/filters/parser/DiracSplitter/libdirac/libdirac_byteio/picture_byteio.h b/src/filters/parser/DiracSplitter/libdirac/libdirac_byteio/picture_byteio.h
index 1fcd0cb9c..bdca76f40 100644
--- a/src/filters/parser/DiracSplitter/libdirac/libdirac_byteio/picture_byteio.h
+++ b/src/filters/parser/DiracSplitter/libdirac/libdirac_byteio/picture_byteio.h
@@ -54,178 +54,154 @@
namespace dirac
{
-/**
-* A compressed picture in Dirac bytestream format
-*/
-class PictureByteIO : public ParseUnitByteIO
-{
-public:
-
- /**
- * Constructor
- *@param frame_params Picture parameters
- *@param frame_num Picture number
- */
- PictureByteIO(PictureParams& frame_params,
- int frame_num);
-
-
- /**
- * Constructor
- *@param frame_params Destination of data
- *@param parseunit_byteio Source of data
- */
- PictureByteIO(PictureParams& frame_params,
- const ParseUnitByteIO& parseunit_byteio);
-
- /**
- * Destructor
- */
- virtual ~PictureByteIO();
-
- /**
- * Gathers byte stats on the picture data
- *@param dirac_byte_stats Stat container
- */
- void CollateByteStats(DiracByteStats& dirac_byte_stats);
-
- /**
- * Inputs data from Dirac stream-format
- */
- bool Input();
-
- /**
- * Outputs picture values to Dirac stream-format
- */
- void Output();
-
-
-
- const std::string GetBytes();
-
- int GetSize() const;
-
- /**
- * Gets parse-unit type
- */
- ParseUnitType GetType() const
- {
- return PU_PICTURE;
- }
-
- /**
- * Returns true is picture in Reference picture
- */
- int IsRef() const
- {
- return (GetParseCode() & 0x0C) == 0x0C;
- }
-
- /**
- * Returns true is picture in Non-Reference picture
- */
- int IsNonRef() const
- {
- return (GetParseCode() & 0x0C) == 0x08;
- }
-
- /**
- * Gets parse-unit type
- */
- int NumRefs() const
- {
- return (GetParseCode() & 0x03);
- }
-
- /**
- * Returns true is picture is Intra picture
- */
- bool IsIntra() const
- {
- return IsPicture() && (NumRefs() == 0) ;
- }
-
/**
- * Returns true is picture is Inter picture
- */
- bool IsInter() const
- {
- return IsPicture() && (NumRefs() > 0) ;
- }
-
- /***
- * Sets the MVDataIO
+ * A compressed picture in Dirac bytestream format
*/
- void SetMvData(MvDataByteIO *mv_data)
+ class PictureByteIO : public ParseUnitByteIO
{
- m_mv_data = mv_data;
- }
-
- /***
- * Sets the TransformByteIo
- */
- void SetTransformData(TransformByteIO *transform_data)
- {
- m_transform_data = transform_data;
- }
-
-protected:
-
-
-private:
-
- /**
- * Calculates parse-code based on picture parameters
- *@return Char bit-set
- */
- unsigned char CalcParseCode() const;
-
- /**
- * Reads reference-picture data
- */
- void InputReferencePictures();
-
- /**
- * Reads retired picture number
- */
- void InputRetiredPicture();
-
- /**
- * Calculates picture-type (eg INTRA/INTER) of picture
- */
- void SetPictureType();
-
- /**
- * Calculates reference-type of picture
- */
- void SetReferenceType();
-
- /**
- * Sets the entropy coding flag in the picture parameters
- */
- void SetEntropyCodingFlag();
-
- /**
- * Picture parameters
- */
- PictureParams& m_frame_params;
-
- /**
- * Picture number
- */
- int m_frame_num;
-
- /**
- * MV data
- */
- MvDataByteIO * m_mv_data;
-
- /**
- * Transform data
- */
- TransformByteIO * m_transform_data;
-
-};
+ public:
+
+ /**
+ * Constructor
+ *@param frame_params Picture parameters
+ *@param frame_num Picture number
+ */
+ PictureByteIO(PictureParams& frame_params,
+ int frame_num);
+
+
+ /**
+ * Constructor
+ *@param frame_params Destination of data
+ *@param parseunit_byteio Source of data
+ */
+ PictureByteIO(PictureParams& frame_params,
+ const ParseUnitByteIO& parseunit_byteio);
+
+ /**
+ * Destructor
+ */
+ virtual ~PictureByteIO();
+
+ /**
+ * Gathers byte stats on the picture data
+ *@param dirac_byte_stats Stat container
+ */
+ void CollateByteStats(DiracByteStats& dirac_byte_stats);
+
+ /**
+ * Inputs data from Dirac stream-format
+ */
+ bool Input();
+
+ /**
+ * Outputs picture values to Dirac stream-format
+ */
+ void Output();
+
+
+
+ const std::string GetBytes();
+
+ int GetSize() const;
+
+ /**
+ * Gets parse-unit type
+ */
+ ParseUnitType GetType() const { return PU_PICTURE;}
+
+ /**
+ * Returns true is picture in Reference picture
+ */
+ int IsRef() const { return (GetParseCode()&0x0C)==0x0C;}
+
+ /**
+ * Returns true is picture in Non-Reference picture
+ */
+ int IsNonRef() const { return (GetParseCode()&0x0C)==0x08;}
+
+ /**
+ * Gets parse-unit type
+ */
+ int NumRefs() const { return (GetParseCode()&0x03);}
+
+ /**
+ * Returns true is picture is Intra picture
+ */
+ bool IsIntra() const { return IsPicture() && (NumRefs()==0) ; }
+
+ /**
+ * Returns true is picture is Inter picture
+ */
+ bool IsInter() const { return IsPicture() && (NumRefs()>0) ; }
+
+ /***
+ * Sets the MVDataIO
+ */
+ void SetMvData(MvDataByteIO *mv_data) {m_mv_data = mv_data; }
+
+ /***
+ * Sets the TransformByteIo
+ */
+ void SetTransformData(TransformByteIO *transform_data) {m_transform_data = transform_data; }
+
+ protected:
+
+
+ private:
+
+ /**
+ * Calculates parse-code based on picture parameters
+ *@return Char bit-set
+ */
+ unsigned char CalcParseCode() const;
+
+ /**
+ * Reads reference-picture data
+ */
+ void InputReferencePictures();
+
+ /**
+ * Reads retired picture number
+ */
+ void InputRetiredPicture();
+
+ /**
+ * Calculates picture-type (eg INTRA/INTER) of picture
+ */
+ void SetPictureType();
+
+ /**
+ * Calculates reference-type of picture
+ */
+ void SetReferenceType();
+
+ /**
+ * Sets the entropy coding flag in the picture parameters
+ */
+ void SetEntropyCodingFlag();
+
+ /**
+ * Picture parameters
+ */
+ PictureParams& m_frame_params;
+
+ /**
+ * Picture number
+ */
+ int m_frame_num;
+
+ /**
+ * MV data
+ */
+ MvDataByteIO * m_mv_data;
+
+ /**
+ * Transform data
+ */
+ TransformByteIO * m_transform_data;
+
+ };
} // namespace dirac
diff --git a/src/filters/parser/DiracSplitter/libdirac/libdirac_byteio/subband_byteio.cpp b/src/filters/parser/DiracSplitter/libdirac/libdirac_byteio/subband_byteio.cpp
index 41b6fcb66..63d0607b9 100644
--- a/src/filters/parser/DiracSplitter/libdirac/libdirac_byteio/subband_byteio.cpp
+++ b/src/filters/parser/DiracSplitter/libdirac/libdirac_byteio/subband_byteio.cpp
@@ -42,19 +42,19 @@ using namespace std;
SubbandByteIO::SubbandByteIO(Subband& sub_band,
const ByteIO& byteio):
- ByteIO(byteio),
- m_subband(sub_band),
- m_band_data_length(0)
+ByteIO(byteio),
+m_subband(sub_band),
+m_band_data_length(0)
{
-
+
}
SubbandByteIO::SubbandByteIO(Subband& sub_band):
- ByteIO(),
- m_subband(sub_band),
- m_band_data_length(0)
+ByteIO(),
+m_subband(sub_band),
+m_band_data_length(0)
{
-
+
}
SubbandByteIO::~SubbandByteIO()
@@ -70,7 +70,7 @@ bool SubbandByteIO::Input()
m_band_data_length = ReadUint();
// set skip flag if no data
- m_subband.SetSkip(m_band_data_length == 0 ? true : false);
+ m_subband.SetSkip(m_band_data_length==0 ? true : false);
// check for zero-length sub-band
if(m_subband.Skipped())
@@ -79,16 +79,16 @@ bool SubbandByteIO::Input()
return true;
}
- // If we're not skipped, we need a quantisation index for the subband
- m_subband.SetQuantIndex(ReadUint());
+ // If we're not skipped, we need a quantisation index for the subband
+ m_subband.SetQuantIndex(ReadUint() );
- if(!m_subband.UsingMultiQuants())
+ if ( !m_subband.UsingMultiQuants() )
{
- // Propogate the quantiser index to all the code blocks if we
+ // Propogate the quantiser index to all the code blocks if we
// don't have multiquants
- for(int j = 0 ; j < m_subband.GetCodeBlocks().LengthY() ; ++j)
- for(int i = 0 ; i < m_subband.GetCodeBlocks().LengthX() ; ++i)
- m_subband.GetCodeBlocks()[j][i].SetQuantIndex(m_subband.QuantIndex());
+ for ( int j=0 ; j<m_subband.GetCodeBlocks().LengthY() ; ++j )
+ for ( int i=0 ; i<m_subband.GetCodeBlocks().LengthX() ; ++i )
+ m_subband.GetCodeBlocks()[j][i].SetQuantIndex( m_subband.QuantIndex() );
}
// byte align
@@ -98,12 +98,12 @@ bool SubbandByteIO::Input()
return true;
}
-int SubbandByteIO::GetBandDataLength() const
+int SubbandByteIO::GetBandDataLength() const
{
return m_band_data_length;
}
-const string SubbandByteIO::GetBytes()
+const string SubbandByteIO::GetBytes()
{
ByteIO byte_io;
@@ -113,7 +113,7 @@ const string SubbandByteIO::GetBytes()
byte_io.WriteUint(GetSize());
// check for zero-length sub-band
- if(GetSize() == 0)
+ if(GetSize()==0)
{
byte_io.ByteAlignOutput();
return byte_io.GetBytes();
@@ -128,10 +128,10 @@ const string SubbandByteIO::GetBytes()
//std::cerr << "Subband hdr size=" << byte_io.GetSize();
//std::cerr << " Arithdata size=" << this->GetSize()<< std::endl;
- return byte_io.GetBytes() + ByteIO::GetBytes();
+ return byte_io.GetBytes()+ByteIO::GetBytes();
}
//-------------private-------------------------------------------------------
-
+
diff --git a/src/filters/parser/DiracSplitter/libdirac/libdirac_byteio/subband_byteio.h b/src/filters/parser/DiracSplitter/libdirac/libdirac_byteio/subband_byteio.h
index ad8460c6b..88d03cf87 100644
--- a/src/filters/parser/DiracSplitter/libdirac/libdirac_byteio/subband_byteio.h
+++ b/src/filters/parser/DiracSplitter/libdirac/libdirac_byteio/subband_byteio.h
@@ -50,65 +50,65 @@
namespace dirac
{
-/**
-* Subband Dirac-bytestream input/output
-*/
-class SubbandByteIO : public ByteIO
-{
-public:
-
- /**
- * Constructor
- *@param sub_band Corresponding Subband
- *@param byteio Source/Destination of data
- */
- SubbandByteIO(Subband& sub_band,
- const ByteIO& byteio);
-
-
- /* Constructor
- *@param sub_band Corresponding Subband
- *@param byteio Source/Destination of data
- */
- SubbandByteIO(Subband& sub_band);
-
- /**
- * Destructor
- */
- ~SubbandByteIO();
-
- /**
- * Inputs data from Dirac stream-format
- */
- bool Input();
-
-
- /**
- * Gets number of bytes in Arith-coded data block
- */
- int GetBandDataLength() const;
-
- /**
- * Gets subband bytes in Dirac-bytestream format
- */
- const std::string GetBytes();
-
-
-protected:
-
-
-private:
-
- /**
- * Sub-band that is inputed/outputed
- */
- Subband& m_subband;
-
/**
- * Number of bytes in arith-coded data block
+ * Subband Dirac-bytestream input/output
*/
- int m_band_data_length;
-};
+ class SubbandByteIO : public ByteIO
+ {
+ public:
+
+ /**
+ * Constructor
+ *@param sub_band Corresponding Subband
+ *@param byteio Source/Destination of data
+ */
+ SubbandByteIO(Subband& sub_band,
+ const ByteIO& byteio);
+
+
+ /* Constructor
+ *@param sub_band Corresponding Subband
+ *@param byteio Source/Destination of data
+ */
+ SubbandByteIO(Subband& sub_band);
+
+ /**
+ * Destructor
+ */
+ ~SubbandByteIO();
+
+ /**
+ * Inputs data from Dirac stream-format
+ */
+ bool Input();
+
+
+ /**
+ * Gets number of bytes in Arith-coded data block
+ */
+ int GetBandDataLength() const;
+
+ /**
+ * Gets subband bytes in Dirac-bytestream format
+ */
+ const std::string GetBytes();
+
+
+ protected:
+
+
+ private:
+
+ /**
+ * Sub-band that is inputed/outputed
+ */
+ Subband& m_subband;
+
+ /**
+ * Number of bytes in arith-coded data block
+ */
+ int m_band_data_length;
+ };
} // namespace dirac
diff --git a/src/filters/parser/DiracSplitter/libdirac/libdirac_byteio/transform_byteio.cpp b/src/filters/parser/DiracSplitter/libdirac/libdirac_byteio/transform_byteio.cpp
index 918b781fe..6eba5a31d 100644
--- a/src/filters/parser/DiracSplitter/libdirac/libdirac_byteio/transform_byteio.cpp
+++ b/src/filters/parser/DiracSplitter/libdirac/libdirac_byteio/transform_byteio.cpp
@@ -43,57 +43,57 @@ using namespace dirac;
TransformByteIO::TransformByteIO(PictureParams& fparams,
CodecParams& cparams):
- ByteIO(),
- m_fparams(fparams),
- m_cparams(cparams),
- m_default_cparams(cparams.GetVideoFormat(), fparams.GetPictureType(), fparams.Refs().size(), true)
+ByteIO(),
+m_fparams(fparams),
+m_cparams(cparams),
+m_default_cparams(cparams.GetVideoFormat(), fparams.GetPictureType(), fparams.Refs().size(), true)
{
}
TransformByteIO::TransformByteIO(ByteIO &byte_io,
PictureParams& fparams,
CodecParams& cparams):
- ByteIO(byte_io),
- m_fparams(fparams),
- m_cparams(cparams),
- m_default_cparams(cparams.GetVideoFormat(), fparams.GetPictureType(), fparams.Refs().size(), true)
+ByteIO(byte_io),
+m_fparams(fparams),
+m_cparams(cparams),
+m_default_cparams(cparams.GetVideoFormat(), fparams.GetPictureType(), fparams.Refs().size(), true)
{
}
TransformByteIO::~TransformByteIO()
{
- for(size_t index = 0; index < m_component_list.size(); ++index)
- delete m_component_list[index];
+ for(size_t index=0; index < m_component_list.size(); ++index)
+ delete m_component_list[index];
}
void TransformByteIO::CollateByteStats(DiracByteStats& dirac_byte_stats)
{
// set number of component bytes
- for(size_t index = 0; index < m_component_list.size(); ++index)
+ for(size_t index=0; index < m_component_list.size(); ++index)
m_component_list[index]->CollateByteStats(dirac_byte_stats);
}
int TransformByteIO::GetSize() const
{
//std::cerr << "Transform Size=" << ByteIO::GetSize() << std::endl;
- int size = 0;
- for(size_t index = 0; index < m_component_list.size(); ++index)
+ int size=0;
+ for(size_t index=0; index < m_component_list.size(); ++index)
size += m_component_list[index]->GetSize();
- return ByteIO::GetSize() + size;
+ return ByteIO::GetSize()+size;
}
const std::string TransformByteIO::GetBytes()
{
std::string bytes;
- for(size_t index = 0; index < m_component_list.size(); ++index)
+ for(size_t index=0; index < m_component_list.size(); ++index)
bytes += m_component_list[index]->GetBytes();
- return ByteIO::GetBytes() + bytes;
+ return ByteIO::GetBytes()+bytes;
}
void TransformByteIO::Output()
{
// Zero Transform flag - applies only to inter frames
- if(m_fparams.PicSort().IsInter())
+ if (m_fparams.PicSort().IsInter())
WriteBit(false);
// Wavelet index
WriteUint(m_cparams.TransformFilter());
@@ -103,9 +103,9 @@ void TransformByteIO::Output()
// Spatial Partition flag
WriteBit(m_cparams.SpatialPartition());
- if(m_cparams.SpatialPartition())
+ if (m_cparams.SpatialPartition())
{
- for(unsigned int i = 0; i <= m_cparams.TransformDepth(); ++i)
+ for (unsigned int i = 0; i <= m_cparams.TransformDepth(); ++i)
{
const CodeBlocks &cb = m_cparams.GetCodeBlocks(i);
// Number of Horizontal code blocks for level i
@@ -127,25 +127,25 @@ void TransformByteIO::Input()
m_cparams.SetZeroTransform(false);
// Zero transform flag - applies only for inter frames
- if(m_fparams.PicSort().IsInter())
+ if (m_fparams.PicSort().IsInter())
m_cparams.SetZeroTransform(ReadBool());
- if(m_cparams.ZeroTransform())
+ if (m_cparams.ZeroTransform())
return;
// Transform filter
m_cparams.SetTransformFilter(ReadUint());
// transform depth
- m_cparams.SetTransformDepth(ReadUint());
+ m_cparams.SetTransformDepth(ReadUint());
// Spatial partition flag
m_cparams.SetSpatialPartition(ReadBool());
- if(m_cparams.SpatialPartition())
+ if (m_cparams.SpatialPartition())
{
// Input number of code blocks for each level
- for(unsigned int i = 0; i <= m_cparams.TransformDepth(); ++i)
+ for (unsigned int i = 0; i <= m_cparams.TransformDepth(); ++i)
{
// number of horizontal code blocks for level i
unsigned int hblocks = ReadUint();
@@ -162,7 +162,7 @@ void TransformByteIO::Input()
void TransformByteIO::AddComponent(ComponentByteIO* component_byteio)
{
- m_component_list.push_back(component_byteio);
+ m_component_list.push_back(component_byteio);
}
diff --git a/src/filters/parser/DiracSplitter/libdirac/libdirac_byteio/transform_byteio.h b/src/filters/parser/DiracSplitter/libdirac/libdirac_byteio/transform_byteio.h
index 0153c8302..6fa1c0c5f 100644
--- a/src/filters/parser/DiracSplitter/libdirac/libdirac_byteio/transform_byteio.h
+++ b/src/filters/parser/DiracSplitter/libdirac/libdirac_byteio/transform_byteio.h
@@ -52,94 +52,94 @@
namespace dirac
{
-
-/**
-* Represents compressed sequence-parameter data used in an AccessUnit
-*/
-class TransformByteIO : public ByteIO
-{
-public:
-
- /**
- * Output Constructor
- *@param fparams Picture parameters
- *@param c_params Codec params
- */
- TransformByteIO(PictureParams& fparams,
- CodecParams& c_params);
-
- /**
- * Input Constructor
- *@param byte_io ByteIO object for copy constructor
- *@param fparams Picture parameters
- *@param c_params Codec params
- */
- TransformByteIO(ByteIO &byte_io, PictureParams& fparams,
- CodecParams& c_params);
-
- /**
- * Destructor
- */
- virtual ~TransformByteIO();
-
- /**
- * Gathers byte stats on the transform data
- *@param dirac_byte_stats Stats container
- */
- void CollateByteStats(DiracByteStats& dirac_byte_stats);
-
- /**
- * Outputs sequence information to Dirac byte-format
- */
- void Output();
-
- /**
- * Outputs sequence information to Dirac byte-format
- */
- void Input();
-
-
- /**
- * Get string containing coded bytes
- */
- virtual const std::string GetBytes();
-
- /**
- * Return the size
- */
- int GetSize() const;
-
- /**
- * Adds a Picture-component in Dirac-bytestream format
- *@param component_byteio Picture-component bytestream
- */
- void AddComponent(ComponentByteIO *component_byteio);
-
-protected:
-
-
-private:
-
- /**
- * Sequence paramters for intput/output
- */
- PictureParams& m_fparams;
-
+
/**
- * Codec params - EncParams for Output and DecParams for input
- */
- CodecParams& m_cparams;
-
- /**
- * Default Codec params - EncParams for Output and DecParams for input
- */
- CodecParams m_default_cparams;
-
- /***
- * Transform Component data
+ * Represents compressed sequence-parameter data used in an AccessUnit
*/
- std::vector<ComponentByteIO *> m_component_list;
-};
+ class TransformByteIO : public ByteIO
+ {
+ public:
+
+ /**
+ * Output Constructor
+ *@param fparams Picture parameters
+ *@param c_params Codec params
+ */
+ TransformByteIO(PictureParams& fparams,
+ CodecParams& c_params);
+
+ /**
+ * Input Constructor
+ *@param byte_io ByteIO object for copy constructor
+ *@param fparams Picture parameters
+ *@param c_params Codec params
+ */
+ TransformByteIO(ByteIO &byte_io, PictureParams& fparams,
+ CodecParams& c_params);
+
+ /**
+ * Destructor
+ */
+ virtual ~TransformByteIO();
+
+ /**
+ * Gathers byte stats on the transform data
+ *@param dirac_byte_stats Stats container
+ */
+ void CollateByteStats(DiracByteStats& dirac_byte_stats);
+
+ /**
+ * Outputs sequence information to Dirac byte-format
+ */
+ void Output();
+
+ /**
+ * Outputs sequence information to Dirac byte-format
+ */
+ void Input();
+
+
+ /**
+ * Get string containing coded bytes
+ */
+ virtual const std::string GetBytes();
+
+ /**
+ * Return the size
+ */
+ int GetSize() const;
+
+ /**
+ * Adds a Picture-component in Dirac-bytestream format
+ *@param component_byteio Picture-component bytestream
+ */
+ void AddComponent(ComponentByteIO *component_byteio);
+
+ protected:
+
+
+ private:
+
+ /**
+ * Sequence paramters for intput/output
+ */
+ PictureParams& m_fparams;
+
+ /**
+ * Codec params - EncParams for Output and DecParams for input
+ */
+ CodecParams& m_cparams;
+
+ /**
+ * Default Codec params - EncParams for Output and DecParams for input
+ */
+ CodecParams m_default_cparams;
+
+ /***
+ * Transform Component data
+ */
+ std::vector<ComponentByteIO *> m_component_list;
+ };
} // namespace dirac
diff --git a/src/filters/parser/DiracSplitter/libdirac/libdirac_common/arith_codec.cpp b/src/filters/parser/DiracSplitter/libdirac/libdirac_common/arith_codec.cpp
index 1ee3b4777..756ac19b5 100644
--- a/src/filters/parser/DiracSplitter/libdirac/libdirac_common/arith_codec.cpp
+++ b/src/filters/parser/DiracSplitter/libdirac/libdirac_common/arith_codec.cpp
@@ -37,139 +37,133 @@
#include <libdirac_common/arith_codec.h>
-namespace dirac
-{
-
-const unsigned int Context::lut[256] =
-{
- //LUT corresponds to window = 16 @ p0=0.5 & 8 @ p=1.0
- 0, 2, 5, 8, 11, 15, 20, 24,
- 29, 35, 41, 47, 53, 60, 67, 74,
- 82, 89, 97, 106, 114, 123, 132, 141,
- 150, 160, 170, 180, 190, 201, 211, 222,
- 233, 244, 256, 267, 279, 291, 303, 315,
- 327, 340, 353, 366, 379, 392, 405, 419,
- 433, 447, 461, 475, 489, 504, 518, 533,
- 548, 563, 578, 593, 609, 624, 640, 656,
- 672, 688, 705, 721, 738, 754, 771, 788,
- 805, 822, 840, 857, 875, 892, 910, 928,
- 946, 964, 983, 1001, 1020, 1038, 1057, 1076,
- 1095, 1114, 1133, 1153, 1172, 1192, 1211, 1231,
- 1251, 1271, 1291, 1311, 1332, 1352, 1373, 1393,
- 1414, 1435, 1456, 1477, 1498, 1520, 1541, 1562,
- 1584, 1606, 1628, 1649, 1671, 1694, 1716, 1738,
- 1760, 1783, 1806, 1828, 1851, 1874, 1897, 1920,
- 1935, 1942, 1949, 1955, 1961, 1968, 1974, 1980,
- 1985, 1991, 1996, 2001, 2006, 2011, 2016, 2021,
- 2025, 2029, 2033, 2037, 2040, 2044, 2047, 2050,
- 2053, 2056, 2058, 2061, 2063, 2065, 2066, 2068,
- 2069, 2070, 2071, 2072, 2072, 2072, 2072, 2072,
- 2072, 2071, 2070, 2069, 2068, 2066, 2065, 2063,
- 2060, 2058, 2055, 2052, 2049, 2045, 2042, 2038,
- 2033, 2029, 2024, 2019, 2013, 2008, 2002, 1996,
- 1989, 1982, 1975, 1968, 1960, 1952, 1943, 1934,
- 1925, 1916, 1906, 1896, 1885, 1874, 1863, 1851,
- 1839, 1827, 1814, 1800, 1786, 1772, 1757, 1742,
- 1727, 1710, 1694, 1676, 1659, 1640, 1622, 1602,
- 1582, 1561, 1540, 1518, 1495, 1471, 1447, 1422,
- 1396, 1369, 1341, 1312, 1282, 1251, 1219, 1186,
- 1151, 1114, 1077, 1037, 995, 952, 906, 857,
- 805, 750, 690, 625, 553, 471, 376, 255
-};
-
-ArithCodecBase::ArithCodecBase(ByteIO* p_byteio, size_t number_of_contexts):
- m_context_list(number_of_contexts),
- m_scount(0),
- m_byteio(p_byteio),
- m_decode_data_ptr(0)
-{
- // nothing needed here
-}
-
-ArithCodecBase::~ArithCodecBase()
-{
- delete[] m_decode_data_ptr;
-}
-
-
-void ArithCodecBase::InitEncoder()
-{
- // Set the m_code word stuff
- m_low_code = 0;
- m_range = 0xFFFF;
- m_underflow = 0;
-}
-
-void ArithCodecBase::FlushEncoder()
-{
-
- // Do final renormalisation and output
- while(((m_low_code + m_range - 1) ^ m_low_code) < 0x8000)
+namespace dirac{
+
+ const unsigned int Context::lut[256] = {
+ //LUT corresponds to window = 16 @ p0=0.5 & 8 @ p=1.0
+ 0, 2, 5, 8, 11, 15, 20, 24,
+ 29, 35, 41, 47, 53, 60, 67, 74,
+ 82, 89, 97, 106, 114, 123, 132, 141,
+ 150, 160, 170, 180, 190, 201, 211, 222,
+ 233, 244, 256, 267, 279, 291, 303, 315,
+ 327, 340, 353, 366, 379, 392, 405, 419,
+ 433, 447, 461, 475, 489, 504, 518, 533,
+ 548, 563, 578, 593, 609, 624, 640, 656,
+ 672, 688, 705, 721, 738, 754, 771, 788,
+ 805, 822, 840, 857, 875, 892, 910, 928,
+ 946, 964, 983, 1001, 1020, 1038, 1057, 1076,
+ 1095, 1114, 1133, 1153, 1172, 1192, 1211, 1231,
+ 1251, 1271, 1291, 1311, 1332, 1352, 1373, 1393,
+ 1414, 1435, 1456, 1477, 1498, 1520, 1541, 1562,
+ 1584, 1606, 1628, 1649, 1671, 1694, 1716, 1738,
+ 1760, 1783, 1806, 1828, 1851, 1874, 1897, 1920,
+ 1935, 1942, 1949, 1955, 1961, 1968, 1974, 1980,
+ 1985, 1991, 1996, 2001, 2006, 2011, 2016, 2021,
+ 2025, 2029, 2033, 2037, 2040, 2044, 2047, 2050,
+ 2053, 2056, 2058, 2061, 2063, 2065, 2066, 2068,
+ 2069, 2070, 2071, 2072, 2072, 2072, 2072, 2072,
+ 2072, 2071, 2070, 2069, 2068, 2066, 2065, 2063,
+ 2060, 2058, 2055, 2052, 2049, 2045, 2042, 2038,
+ 2033, 2029, 2024, 2019, 2013, 2008, 2002, 1996,
+ 1989, 1982, 1975, 1968, 1960, 1952, 1943, 1934,
+ 1925, 1916, 1906, 1896, 1885, 1874, 1863, 1851,
+ 1839, 1827, 1814, 1800, 1786, 1772, 1757, 1742,
+ 1727, 1710, 1694, 1676, 1659, 1640, 1622, 1602,
+ 1582, 1561, 1540, 1518, 1495, 1471, 1447, 1422,
+ 1396, 1369, 1341, 1312, 1282, 1251, 1219, 1186,
+ 1151, 1114, 1077, 1037, 995, 952, 906, 857,
+ 805, 750, 690, 625, 553, 471, 376, 255
+ };
+
+ ArithCodecBase::ArithCodecBase(ByteIO* p_byteio, size_t number_of_contexts):
+ m_context_list( number_of_contexts ),
+ m_scount( 0 ),
+ m_byteio(p_byteio ),
+ m_decode_data_ptr( 0 )
{
- m_byteio->WriteBit(m_low_code & 0x8000);
- for(; m_underflow > 0; m_underflow--)
- m_byteio->WriteBit(~m_low_code & 0x8000);
-
- m_low_code <<= 1;
- m_low_code &= 0xFFFF;
- m_range <<= 1;
+ // nothing needed here
}
- while((m_low_code & 0x4000) && !((m_low_code + m_range - 1) & 0x4000))
+ ArithCodecBase::~ArithCodecBase() {
+ delete[] m_decode_data_ptr; }
+
+
+ void ArithCodecBase::InitEncoder()
{
- m_underflow += 1;
- m_low_code ^= 0x4000;
- m_low_code <<= 1;
- m_low_code &= 0xFFFF;
- m_range <<= 1;
+ // Set the m_code word stuff
+ m_low_code = 0;
+ m_range = 0xFFFF;
+ m_underflow = 0;
}
- m_byteio->WriteBit(m_low_code & 0x4000);
- while(m_underflow >= 0)
+ void ArithCodecBase::FlushEncoder()
{
- m_byteio->WriteBit(~m_low_code & 0x4000);
- m_underflow -= 1;
+
+ // Do final renormalisation and output
+ while (((m_low_code+m_range-1)^m_low_code)<0x8000 )
+ {
+ m_byteio->WriteBit( m_low_code & 0x8000);
+ for (; m_underflow > 0; m_underflow-- )
+ m_byteio->WriteBit(~m_low_code & 0x8000);
+
+ m_low_code <<= 1;
+ m_low_code &= 0xFFFF;
+ m_range <<= 1;
+ }
+
+ while ( (m_low_code & 0x4000) && !((m_low_code+m_range-1) & 0x4000) )
+ {
+ m_underflow += 1;
+ m_low_code ^= 0x4000;
+ m_low_code <<= 1;
+ m_low_code &= 0xFFFF;
+ m_range <<= 1;
+ }
+
+ m_byteio->WriteBit(m_low_code & 0x4000);
+ while ( m_underflow >= 0 ) {
+ m_byteio->WriteBit(~m_low_code & 0x4000);
+ m_underflow -= 1; }
+
+ // byte align
+ m_byteio->ByteAlignOutput();
}
+
+ void ArithCodecBase::InitDecoder(int num_bytes)
+ {
+ ReadAllData(num_bytes);
+ m_input_bits_left = 8;
- // byte align
- m_byteio->ByteAlignOutput();
-}
+ m_code = 0;
+ m_low_code = 0;
-void ArithCodecBase::InitDecoder(int num_bytes)
-{
- ReadAllData(num_bytes);
- m_input_bits_left = 8;
+ m_range = 0xFFFF;
- m_code = 0;
- m_low_code = 0;
+ m_code = 0;
+ for (int i=0; i<16; ++i)
+ {
+ m_code <<= 1;
+ m_code += InputBit();
+ }
- m_range = 0xFFFF;
+ }
- m_code = 0;
- for(int i = 0; i < 16; ++i)
+ int ArithCodecBase::ByteCount() const
{
- m_code <<= 1;
- m_code += InputBit();
+ return m_byteio->GetSize();
}
-}
-
-int ArithCodecBase::ByteCount() const
-{
- return m_byteio->GetSize();
-}
-
-void ArithCodecBase::ReadAllData(int num_bytes)
-{
- if(m_decode_data_ptr)
- delete[] m_decode_data_ptr;
+ void ArithCodecBase::ReadAllData(int num_bytes)
+ {
+ if ( m_decode_data_ptr )
+ delete[] m_decode_data_ptr;
- m_decode_data_ptr = new char[num_bytes+2];
- m_byteio->InputBytes(m_decode_data_ptr , num_bytes);
- m_decode_data_ptr[num_bytes] = (char)255;
- m_decode_data_ptr[num_bytes+1] = (char)255;
+ m_decode_data_ptr = new char[num_bytes+2];
+ m_byteio->InputBytes( m_decode_data_ptr , num_bytes );
+ m_decode_data_ptr[num_bytes] = (char)255;
+ m_decode_data_ptr[num_bytes+1] = (char)255;
- m_data_ptr = m_decode_data_ptr;
-}
+ m_data_ptr = m_decode_data_ptr;
+ }
}// namespace dirac
diff --git a/src/filters/parser/DiracSplitter/libdirac/libdirac_common/arith_codec.h b/src/filters/parser/DiracSplitter/libdirac/libdirac_common/arith_codec.h
index d4a47106a..72da756a4 100644
--- a/src/filters/parser/DiracSplitter/libdirac/libdirac_common/arith_codec.h
+++ b/src/filters/parser/DiracSplitter/libdirac/libdirac_common/arith_codec.h
@@ -62,422 +62,407 @@
namespace dirac
{
-class Context
-{
-public:
-
- //! Default Constructor.
- /*!
- Default constructor initialises counts to 1 each of 0 and 1.
- */
- inline Context();
-
- //Class is POD
- //Use built in copy constructor, assignment and destructor.
-
- //! Returns estimate of probability of 0 (false) scaled to 2**16
-
- inline unsigned int GetScaledProb0() const
- {
- return m_prob0;
- }
-
- //! Updates context counts
- inline void Update(bool symbol)
- {
- if(symbol) m_prob0 -= lut[m_prob0>>8];
- else m_prob0 += lut[255-(m_prob0>>8)];
- }
-
-private:
-
- int m_prob0;
- static const unsigned int lut[256]; //Probability update table
-};
-
-Context::Context(): m_prob0(0x8000) {}
-
-class ArithCodecBase
-{
-
-public:
-
- //! Constructor
- /*!
- Creates an ArithCodec object to decode input based on a set of
- parameters.
- \param p_byteio input/output for encoded bits
- \param number_of_contexts the number of contexts used
- */
- ArithCodecBase(ByteIO* p_byteio, size_t number_of_contexts);
-
- //! Destructor
- /*!
- Destructor is virtual as this class is abstract.
- */
- virtual ~ArithCodecBase();
+ class Context {
+ public:
-protected:
+ //! Default Constructor.
+ /*!
+ Default constructor initialises counts to 1 each of 0 and 1.
+ */
+ inline Context();
- //core encode functions
- ////////////////////////////
+ //Class is POD
+ //Use built in copy constructor, assignment and destructor.
- //! Initialises the Encoder
- void InitEncoder();
+ //! Returns estimate of probability of 0 (false) scaled to 2**16
- //! encodes a symbol and writes to output
- void EncodeSymbol(const bool symbol, const int context_num);
+ inline unsigned int GetScaledProb0( ) const{ return m_prob0;}
- void EncodeUInt(const unsigned int value, const int bin1, const int max_bin);
+ //! Updates context counts
+ inline void Update( bool symbol ) {
+ if (symbol) m_prob0 -= lut[m_prob0>>8];
+ else m_prob0 += lut[255-(m_prob0>>8)];
+ }
- void EncodeSInt(const int value, const int bin1, const int max_bin);
+ private:
- //! flushes the output of the encoder.
- void FlushEncoder();
+ int m_prob0;
+ static const unsigned int lut[256]; //Probability update table
+ };
+
+ Context::Context(): m_prob0( 0x8000 ) {}
- int ByteCount() const;
+ class ArithCodecBase {
- // core decode functions
- ////////////////////////////
+ public:
- //! Initialise the Decoder
- void InitDecoder(int num_bytes);
+ //! Constructor
+ /*!
+ Creates an ArithCodec object to decode input based on a set of
+ parameters.
+ \param p_byteio input/output for encoded bits
+ \param number_of_contexts the number of contexts used
+ */
+ ArithCodecBase(ByteIO* p_byteio, size_t number_of_contexts);
- //! Decodes a symbol given a context number
- bool DecodeSymbol(int context_num);
+ //! Destructor
+ /*!
+ Destructor is virtual as this class is abstract.
+ */
+ virtual ~ArithCodecBase();
- unsigned int DecodeUInt(const int bin1, const int max_bin);
+ protected:
- int DecodeSInt(const int bin1, const int max_bin);
+ //core encode functions
+ ////////////////////////////
- //! List of contexts
- std::vector<Context> m_context_list;
+ //! Initialises the Encoder
+ void InitEncoder();
-private:
+ //! encodes a symbol and writes to output
+ void EncodeSymbol(const bool symbol, const int context_num);
- //! private, bodyless copy constructor: class should not be copied
- ArithCodecBase(const ArithCodecBase & cpy);
+ void EncodeUInt(const unsigned int value, const int bin1, const int max_bin);
- //! private, bodyless copy operator=: class should not be assigned
- ArithCodecBase & operator = (const ArithCodecBase & rhs);
+ void EncodeSInt(const int value, const int bin1, const int max_bin);
+ //! flushes the output of the encoder.
+ void FlushEncoder();
- // Decode functions
- ////////////////////////////
+ int ByteCount() const;
- //! Read all the data in
- void ReadAllData(int num_bytes);
+ // core decode functions
+ ////////////////////////////
- //! Read in a bit of data
- inline bool InputBit();
+ //! Initialise the Decoder
+ void InitDecoder(int num_bytes);
- // Codec data
- ////////////////////////////
+ //! Decodes a symbol given a context number
+ bool DecodeSymbol( int context_num );
- unsigned int m_scount;
+ unsigned int DecodeUInt(const int bin1, const int max_bin);
- //! Start of the current code range
- unsigned int m_low_code;
+ int DecodeSInt(const int bin1, const int max_bin);
+
+ //! List of contexts
+ std::vector<Context> m_context_list;
- //! Length of the current code range
- unsigned int m_range;
+ private:
+
+ //! private, bodyless copy constructor: class should not be copied
+ ArithCodecBase(const ArithCodecBase & cpy);
- //! Input/output stream of Dirac-format bytes
- ByteIO *m_byteio;
+ //! private, bodyless copy operator=: class should not be assigned
+ ArithCodecBase & operator = (const ArithCodecBase & rhs);
+
+
+ // Decode functions
+ ////////////////////////////
- // For encoder only
+ //! Read all the data in
+ void ReadAllData(int num_bytes);
- //! Number of underflow bits
- int m_underflow;
+ //! Read in a bit of data
+ inline bool InputBit();
- //! A pointer to the data for reading in
- char* m_decode_data_ptr;
+ // Codec data
+ ////////////////////////////
+
+ unsigned int m_scount;
+
+ //! Start of the current code range
+ unsigned int m_low_code;
+
+ //! Length of the current code range
+ unsigned int m_range;
- //! A point to the byte currently being read
- char* m_data_ptr;
+ //! Input/output stream of Dirac-format bytes
+ ByteIO *m_byteio;
- //! The index of the bit of the byte being read
- int m_input_bits_left;
+ // For encoder only
- //! The present input code
- unsigned int m_code;
+ //! Number of underflow bits
+ int m_underflow;
-};
+ //! A pointer to the data for reading in
+ char* m_decode_data_ptr;
+ //! A point to the byte currently being read
+ char* m_data_ptr;
-inline bool ArithCodecBase::DecodeSymbol(int context_num)
-{
+ //! The index of the bit of the byte being read
+ int m_input_bits_left;
- // Determine the next symbol value by placing code within
- // the [low,high] interval.
+ //! The present input code
+ unsigned int m_code;
- // Fetch the statistical context to be used
- Context& ctx = m_context_list[context_num];
+ };
- // Decode as per updated specification
- const unsigned int count = m_code - m_low_code ;
- const unsigned int range_x_prob = (m_range * ctx.GetScaledProb0()) >> 16;
- const bool symbol = (count >= range_x_prob);
- // Rescale the interval
- if(symbol) //symbol is 1
- {
- m_low_code += range_x_prob;
- m_range -= range_x_prob;
- }
- else //symbol is 0, so m_low_code unchanged
+ inline bool ArithCodecBase::DecodeSymbol( int context_num )
{
- m_range = range_x_prob;
- }
+
+ // Determine the next symbol value by placing code within
+ // the [low,high] interval.
- // Update the statistical context
- ctx.Update(symbol);
+ // Fetch the statistical context to be used
+ Context& ctx = m_context_list[context_num];
- while(m_range <= 0x4000)
- {
- if(((m_low_code + m_range - 1) ^ m_low_code) >= 0x8000)
+ // Decode as per updated specification
+ const unsigned int count = m_code - m_low_code ;
+ const unsigned int range_x_prob = ( m_range* ctx.GetScaledProb0())>>16;
+ const bool symbol = ( count >= range_x_prob );
+
+ // Rescale the interval
+ if( symbol ) //symbol is 1
+ {
+ m_low_code += range_x_prob;
+ m_range -= range_x_prob;
+ }
+ else //symbol is 0, so m_low_code unchanged
{
- // Straddle condition
- // We must have an underflow situation with
- // low = 0x01... and high = 0x10...
- // Flip 2nd bit prior to rescaling
- m_code ^= 0x4000;
- m_low_code ^= 0x4000;
+ m_range = range_x_prob;
}
- // Double low and range, throw away top bit of low
- m_low_code <<= 1;
- m_range <<= 1;
- m_low_code &= 0xFFFF;
+ // Update the statistical context
+ ctx.Update( symbol );
- // Shift in another bit of code
- m_code <<= 1;
- m_code += InputBit();
- m_code &= 0xFFFF;
+ while ( m_range<=0x4000 )
+ {
+ if( ( (m_low_code+m_range-1)^m_low_code)>=0x8000 )
+ {
+ // Straddle condition
+ // We must have an underflow situation with
+ // low = 0x01... and high = 0x10...
+ // Flip 2nd bit prior to rescaling
+ m_code ^= 0x4000;
+ m_low_code ^= 0x4000;
+ }
+
+ // Double low and range, throw away top bit of low
+ m_low_code <<= 1;
+ m_range <<= 1;
+ m_low_code &= 0xFFFF;
+
+ // Shift in another bit of code
+ m_code <<= 1;
+ m_code += InputBit();
+ m_code &= 0xFFFF;
+
+ }
+ return symbol;
}
- return symbol;
-}
-
-inline unsigned int ArithCodecBase::DecodeUInt(const int bin1, const int max_bin)
-{
- const int info_ctx = (max_bin + 1);
- int bin = bin1;
- unsigned int value = 1;
- while(!DecodeSymbol(bin))
- {
- value <<= 1;
- if(DecodeSymbol(info_ctx)) value += 1;
- if(bin < max_bin) bin += 1;
+ inline unsigned int ArithCodecBase::DecodeUInt(const int bin1, const int max_bin) {
+ const int info_ctx = (max_bin+1);
+ int bin = bin1;
+ unsigned int value = 1;
+ while (!DecodeSymbol(bin)) {
+ value <<= 1;
+ if (DecodeSymbol(info_ctx)) value+=1;
+ if (bin<max_bin) bin+=1;
+ }
+ value -= 1;
+ return value;
}
- value -= 1;
- return value;
-}
-inline int ArithCodecBase::DecodeSInt(const int bin1, const int max_bin)
-{
- int value = 0;
- const int magnitude = DecodeUInt(bin1, max_bin);
- if(magnitude != 0)
- {
- if(DecodeSymbol(max_bin + 2)) value = -magnitude;
- else value = magnitude;
+ inline int ArithCodecBase::DecodeSInt(const int bin1, const int max_bin) {
+ int value = 0;
+ const int magnitude = DecodeUInt(bin1, max_bin);
+ if (magnitude!=0) {
+ if (DecodeSymbol(max_bin+2)) value=-magnitude;
+ else value=magnitude;
+ }
+ return value;
}
- return value;
-}
-
-inline void ArithCodecBase::EncodeSymbol(const bool symbol, const int context_num)
-{
-
- // Adjust high and low (rescale interval) based on the symbol we are encoding
-
- Context& ctx = m_context_list[context_num];
- const unsigned int range_x_prob = (m_range * ctx.GetScaledProb0()) >> 16;
-
- if(symbol) //symbol is 1
- {
- m_low_code += range_x_prob;
- m_range -= range_x_prob;
- }
- else // symbol is 0, so m_low_code unchanged
+ inline void ArithCodecBase::EncodeSymbol(const bool symbol, const int context_num)
{
- m_range = range_x_prob;
- }
- // Update the statistical context
- ctx.Update(symbol);
+ // Adjust high and low (rescale interval) based on the symbol we are encoding
- while(m_range <= 0x4000)
- {
- if(((m_low_code + m_range - 1) ^ m_low_code) >= 0x8000)
- {
- // Straddle condition
- // We must have an underflow situation with
- // low = 0x01... and high = 0x10...
+ Context& ctx = m_context_list[context_num];
- m_low_code ^= 0x4000;
- m_underflow++;
+ const unsigned int range_x_prob = ( m_range* ctx.GetScaledProb0())>>16;
+ if ( symbol ) //symbol is 1
+ {
+ m_low_code += range_x_prob;
+ m_range -= range_x_prob;
}
- else
+ else // symbol is 0, so m_low_code unchanged
{
- // Bits agree - output them
- m_byteio->WriteBit(m_low_code & 0x8000);
- for(; m_underflow > 0; m_underflow--)
- m_byteio->WriteBit(~m_low_code & 0x8000);
+ m_range = range_x_prob;
}
-
- // Double low value and range
- m_low_code <<= 1;
- m_range <<= 1;
-
- // keep low to 16 bits - throw out top bit
- m_low_code &= 0xFFFF;
-
+
+ // Update the statistical context
+ ctx.Update( symbol );
+
+ while ( m_range <= 0x4000 )
+ {
+ if ( ( (m_low_code+m_range-1)^m_low_code)>=0x8000 )
+ {
+ // Straddle condition
+ // We must have an underflow situation with
+ // low = 0x01... and high = 0x10...
+
+ m_low_code ^= 0x4000;
+ m_underflow++;
+
+ }
+ else
+ {
+ // Bits agree - output them
+ m_byteio->WriteBit( m_low_code & 0x8000);
+ for (; m_underflow > 0; m_underflow-- )
+ m_byteio->WriteBit(~m_low_code & 0x8000);
+ }
+
+ // Double low value and range
+ m_low_code <<= 1;
+ m_range <<= 1;
+
+ // keep low to 16 bits - throw out top bit
+ m_low_code &= 0xFFFF;
+
+ }
}
-}
-inline void ArithCodecBase::EncodeUInt(const unsigned int the_int,
- const int bin1, const int max_bin)
-{
- const int value = (the_int + 1);
- const int info_ctx = (max_bin + 1);
- int bin = bin1;
- int top_bit = 1;
- {
- int max_value = 1;
- while(value > max_value)
+ inline void ArithCodecBase::EncodeUInt(const unsigned int the_int,
+ const int bin1, const int max_bin) {
+ const int value = (the_int+1);
+ const int info_ctx = (max_bin+1);
+ int bin = bin1;
+ int top_bit = 1;
{
- top_bit <<= 1;
- max_value <<= 1;
- max_value += 1;
+ int max_value = 1;
+ while (value>max_value) {
+ top_bit <<= 1;
+ max_value <<= 1;
+ max_value += 1;
+ }
}
- }
- bool stop = (top_bit == 1);
- EncodeSymbol(stop, bin);
- while(!stop)
- {
- top_bit >>= 1;
- EncodeSymbol((value & top_bit), info_ctx);
- if(bin < max_bin) bin += 1;
- stop = (top_bit == 1);
+ bool stop = (top_bit==1);
EncodeSymbol(stop, bin);
+ while (!stop) {
+ top_bit >>= 1;
+ EncodeSymbol( (value&top_bit), info_ctx);
+ if ( bin < max_bin) bin+=1;
+ stop = (top_bit==1);
+ EncodeSymbol(stop, bin);
+ }
}
-}
-inline void ArithCodecBase::EncodeSInt(const int value,
- const int bin1, const int max_bin)
-{
- EncodeUInt(std::abs(value), bin1, max_bin);
- if(value != 0)
- {
- EncodeSymbol((value < 0), max_bin + 2);
+ inline void ArithCodecBase::EncodeSInt(const int value,
+ const int bin1, const int max_bin) {
+ EncodeUInt(std::abs(value), bin1, max_bin);
+ if (value != 0) {
+ EncodeSymbol( (value < 0), max_bin+2 );
+ }
}
-}
-
-//! Abstract binary arithmetic coding class
-/*!
- This is an abtract binary arithmetic encoding class, used as the base
- for concrete classes that encode motion vectors and subband residues.
- \param T a container (most probably, or array) type
-*/
-template<class T> //T is container/array type
-class ArithCodec
- : public ArithCodecBase
-{
-public:
-
- //! Constructor for encoding
+ //! Abstract binary arithmetic coding class
/*!
- Creates an ArithCodec object to decode input based on a set of
- parameters.
- \param p_byteio input/output for encoded bits
- \param number_of_contexts the number of contexts used
+ This is an abtract binary arithmetic encoding class, used as the base
+ for concrete classes that encode motion vectors and subband residues.
+ \param T a container (most probably, or array) type
*/
- ArithCodec(ByteIO* p_byteio, size_t number_of_contexts);
-
-
- //! Destructor
- /*!
- Destructor is virtual as this class is abstract.
- */
- virtual ~ArithCodec() {}
-
- //! Compresses the input and returns the number of bits written.
- /*!
- Compress takes a type T object (a container or array) and
- compresses it using the abstract function DoWorkCode() which
- is overridden in subclasses. It returns the number of
- bits written.
- \param in_data the input to be compressed. Non-const,
- since the compression may be lossy.
- */
- int Compress(T & in_data);
-
- //! Decompresses the bitstream and writes into the output.
- /*!
- Decompresses the bitstream, up to the number of bytes
- specified and writes into the output subclasses.
- \param out_data the output into which the decompressed data
- is written.
- \param num_bytes the number of bytes to be read from the
- bitstream.
- */
- void Decompress(T & out_data, const int num_bytes);
-
-protected:
-
- //virtual encode-only functions
- ///////////////////////////////
-
- //! Does the work of actually coding the data
- virtual void DoWorkCode(T & in_data) = 0;
-
- //! virtual decode-only functions
- ///////////////////////////////
- virtual void DoWorkDecode(T & out_data) = 0;
-};
-
-//Implementation - core functions
-/////////////////////////////////
-
-template<class T>
-ArithCodec<T>::ArithCodec(ByteIO* p_byteio, size_t number_of_contexts):
- ArithCodecBase(p_byteio, number_of_contexts) {}
-
+ template<class T> //T is container/array type
+ class ArithCodec
+ : public ArithCodecBase
+ {
+ public:
+
+ //! Constructor for encoding
+ /*!
+ Creates an ArithCodec object to decode input based on a set of
+ parameters.
+ \param p_byteio input/output for encoded bits
+ \param number_of_contexts the number of contexts used
+ */
+ ArithCodec(ByteIO* p_byteio, size_t number_of_contexts);
+
+
+ //! Destructor
+ /*!
+ Destructor is virtual as this class is abstract.
+ */
+ virtual ~ArithCodec() {}
+
+ //! Compresses the input and returns the number of bits written.
+ /*!
+ Compress takes a type T object (a container or array) and
+ compresses it using the abstract function DoWorkCode() which
+ is overridden in subclasses. It returns the number of
+ bits written.
+ \param in_data the input to be compressed. Non-const,
+ since the compression may be lossy.
+ */
+ int Compress(T & in_data);
+
+ //! Decompresses the bitstream and writes into the output.
+ /*!
+ Decompresses the bitstream, up to the number of bytes
+ specified and writes into the output subclasses.
+ \param out_data the output into which the decompressed data
+ is written.
+ \param num_bytes the number of bytes to be read from the
+ bitstream.
+ */
+ void Decompress(T & out_data, const int num_bytes);
+
+ protected:
+
+ //virtual encode-only functions
+ ///////////////////////////////
+
+ //! Does the work of actually coding the data
+ virtual void DoWorkCode(T & in_data) = 0;
+
+ //! virtual decode-only functions
+ ///////////////////////////////
+ virtual void DoWorkDecode(T & out_data)=0;
+ };
+
+ //Implementation - core functions
+ /////////////////////////////////
+
+ template<class T>
+ ArithCodec<T>::ArithCodec(ByteIO* p_byteio, size_t number_of_contexts):
+ ArithCodecBase(p_byteio, number_of_contexts) {}
+
+
+
+ template<class T>
+ int ArithCodec<T>::Compress(T &in_data)
+ {
+ InitEncoder();
+ DoWorkCode(in_data);
+ FlushEncoder();
+ return ByteCount();
+ }
-template<class T>
-int ArithCodec<T>::Compress(T &in_data)
-{
- InitEncoder();
- DoWorkCode(in_data);
- FlushEncoder();
- return ByteCount();
-}
-
-template<class T>
-void ArithCodec<T>::Decompress(T &out_data, const int num_bytes)
-{
- InitDecoder(num_bytes);
- DoWorkDecode(out_data);
-}
+ template<class T>
+ void ArithCodec<T>::Decompress( T &out_data, const int num_bytes )
+ {
+ InitDecoder(num_bytes);
+ DoWorkDecode( out_data );
+ }
-inline bool ArithCodecBase::InputBit()
-{
- if(m_input_bits_left == 0)
+ inline bool ArithCodecBase::InputBit()
{
- m_data_ptr++;
- m_input_bits_left = 8;
+ if (m_input_bits_left == 0)
+ {
+ m_data_ptr++;
+ m_input_bits_left = 8;
+ }
+ m_input_bits_left--;
+ // MSB to LSB
+ return bool( ( (*m_data_ptr) >> m_input_bits_left ) & 1 );
}
- m_input_bits_left--;
- // MSB to LSB
- return bool(((*m_data_ptr) >> m_input_bits_left) & 1);
-}
}// namespace dirac
#endif
diff --git a/src/filters/parser/DiracSplitter/libdirac/libdirac_common/arrays.h b/src/filters/parser/DiracSplitter/libdirac/libdirac_common/arrays.h
index d124654a7..276ba5ef2 100644
--- a/src/filters/parser/DiracSplitter/libdirac/libdirac_common/arrays.h
+++ b/src/filters/parser/DiracSplitter/libdirac/libdirac_common/arrays.h
@@ -20,7 +20,7 @@
* Portions created by the Initial Developer are Copyright (C) 2004.
* All Rights Reserved.
*
-* Contributor(s): Thomas Davies (Original Author),
+* Contributor(s): Thomas Davies (Original Author),
* Peter Meerwald (pmeerw@users.sourceforge.net)
* Mike Ferenduros (mike_ferenzduros@users.sourceforge.net)
* Anuradha Suraparaju
@@ -52,597 +52,544 @@
namespace dirac
{
-//! Range type.
-/*!
- Range type encapsulating a closed range of values [first,last].
- Used to initialies OneDArrays.
- */
-class Range
-{
-public:
- //! Constructor
+ //! Range type.
/*!
- Constructor taking a start and an end point for the range.
+ Range type encapsulating a closed range of values [first,last].
+ Used to initialies OneDArrays.
*/
- Range(int s, int e): m_fst(s), m_lst(e) {}
-
- //! Returns the start of the range.
- int First() const
- {
- return m_fst;
- }
-
- //! Returns the end point of the range.
- int Last() const
+ class Range
{
- return m_lst;
- }
-
-private:
- int m_fst , m_lst;
-};
-
-//////////////////////////////
-//One-Dimensional Array type//
-//////////////////////////////
-
-//! A template class for one-dimensional arrays.
-/*!
- A template class for one-D arrays. Can be used wherever built-in
- arrays are used, and eliminates the need for explicit memory
- (de-)allocation. Also supports arrays not based at zero.
- */
-template <class T> class OneDArray
-{
-public:
- //! Default constructor.
- /*!
- Default constructor produces an empty array.
- */
- OneDArray();
+ public:
+ //! Constructor
+ /*!
+ Constructor taking a start and an end point for the range.
+ */
+ Range(int s, int e): m_fst(s), m_lst(e){}
- //! 'Length' constructor.
- /*!
- Length constructor produces a zero-based array.
- */
- OneDArray(const int len);
+ //! Returns the start of the range.
+ int First() const {return m_fst;}
- //! Range constructor
- /*!
- Range constructor produces an array with values indexed within the
- range parameters.
- \param r a range of indexing values.
- */
- OneDArray(const Range& r);
+ //! Returns the end point of the range.
+ int Last() const {return m_lst;}
- //! Destructor.
- /*!
- Destructor frees the data allocated in the constructors.
- */
- ~OneDArray()
- {
- FreePtr();
- }
+ private:
+ int m_fst ,m_lst;
+ };
- //! Copy constructor.
- /*!
- Copy constructor copies both data and metadata.
- */
- OneDArray(const OneDArray<T>& cpy);
+ //////////////////////////////
+ //One-Dimensional Array type//
+ //////////////////////////////
- //! Assignment=
+ //! A template class for one-dimensional arrays.
/*!
- Assignment= assigns both data and metadata.
+ A template class for one-D arrays. Can be used wherever built-in
+ arrays are used, and eliminates the need for explicit memory
+ (de-)allocation. Also supports arrays not based at zero.
*/
- OneDArray<T>& operator=(const OneDArray<T>& rhs);
+ template <class T> class OneDArray
+ {
+ public:
+ //! Default constructor.
+ /*!
+ Default constructor produces an empty array.
+ */
+ OneDArray();
+
+ //! 'Length' constructor.
+ /*!
+ Length constructor produces a zero-based array.
+ */
+ OneDArray(const int len);
+
+ //! Range constructor
+ /*!
+ Range constructor produces an array with values indexed within the
+ range parameters.
+ \param r a range of indexing values.
+ */
+ OneDArray(const Range& r);
+
+ //! Destructor.
+ /*!
+ Destructor frees the data allocated in the constructors.
+ */
+ ~OneDArray()
+ {
+ FreePtr();
+ }
- //! Resize the array, throwing away the current data.
- void Resize(int l);
+ //! Copy constructor.
+ /*!
+ Copy constructor copies both data and metadata.
+ */
+ OneDArray(const OneDArray<T>& cpy);
- //! Element access.
- T& operator[](const int pos)
- {
- return m_ptr[pos-m_first];
- }
+ //! Assignment=
+ /*!
+ Assignment= assigns both data and metadata.
+ */
+ OneDArray<T>& operator=(const OneDArray<T>& rhs);
- //! Element access.
- const T& operator[](const int pos) const
- {
- return m_ptr[pos-m_first];
- }
+ //! Resize the array, throwing away the current data.
+ void Resize(int l);
- //! Returns the length of the array.
- int Length() const
- {
- return m_length;
- }
+ //! Element access.
+ T& operator[](const int pos){return m_ptr[pos-m_first];}
- //! Returns the index of the first element.
- int First() const
- {
- return m_first;
- }
+ //! Element access.
+ const T& operator[](const int pos) const {return m_ptr[pos-m_first];}
- //! Returns the index of the last element.
- int Last() const
- {
- return m_last;
- }
+ //! Returns the length of the array.
+ int Length() const {return m_length;}
-private:
- void Init(const int len);
+ //! Returns the index of the first element.
+ int First() const {return m_first;}
- void Init(const Range& r);
+ //! Returns the index of the last element.
+ int Last() const {return m_last;}
- void FreePtr();
+ private:
+ void Init(const int len);
- int m_first, m_last;
- int m_length;
- T* m_ptr;
-};
+ void Init(const Range& r);
-//public member functions//
-///////////////////////////
+ void FreePtr();
-template <class T>
-OneDArray<T>::OneDArray()
-{
- Init(0);
-}
+ int m_first, m_last;
+ int m_length;
+ T* m_ptr;
+ };
-template <class T>
-OneDArray<T>::OneDArray(const int len)
-{
- Init(len);
-}
+ //public member functions//
+ ///////////////////////////
-template <class T>
-OneDArray<T>::OneDArray(const Range& r)
-{
- Init(r);
-}
-
-template <class T>
-OneDArray<T>::OneDArray(const OneDArray<T>& cpy)
-{
- m_first = cpy.m_first;
- m_last = cpy.m_last;
- m_length = m_last - m_first + 1;
+ template <class T>
+ OneDArray<T>::OneDArray()
+ {
+ Init(0);
+ }
- if(m_first == 0)
- Init(m_length);
- else
- Init(Range(m_first , m_last));
+ template <class T>
+ OneDArray<T>::OneDArray(const int len)
+ {
+ Init(len);
+ }
- memcpy(m_ptr , cpy.m_ptr , m_length * sizeof(T));
-}
+ template <class T>
+ OneDArray<T>::OneDArray(const Range& r)
+ {
+ Init(r);
+ }
-template <class T>
-OneDArray<T>& OneDArray<T>::operator=(const OneDArray<T>& rhs)
-{
- if(&rhs != this)
+ template <class T>
+ OneDArray<T>::OneDArray(const OneDArray<T>& cpy)
{
- FreePtr();
- m_first = rhs.m_first;
- m_last = rhs.m_last;
- m_length = rhs.m_length;
+ m_first = cpy.m_first;
+ m_last = cpy.m_last;
+ m_length = m_last - m_first + 1;
- if(m_first == 0)
+ if (m_first==0)
Init(m_length);
else
Init(Range(m_first , m_last));
- memcpy(m_ptr , rhs.m_ptr , m_length * sizeof(T));
-
+ memcpy( m_ptr , cpy.m_ptr , m_length * sizeof( T ) );
}
- return *this;
-}
-template <class T>
-void OneDArray<T>::Resize(int l)
-{
- if(l != m_length)
+ template <class T>
+ OneDArray<T>& OneDArray<T>::operator=(const OneDArray<T>& rhs)
{
- FreePtr();
- Init(l);
- }
-}
-
-//private member functions//
-////////////////////////////
-
-template <class T>
-void OneDArray<T>::Init(const int len)
-{
- Range r(0 , len - 1);
+ if (&rhs != this)
+ {
+ FreePtr();
+ m_first = rhs.m_first;
+ m_last = rhs.m_last;
+ m_length = rhs.m_length;
- Init(r);
+ if (m_first == 0)
+ Init(m_length);
+ else
+ Init(Range(m_first , m_last));
-}
+ memcpy( m_ptr , rhs.m_ptr , m_length * sizeof( T ) );
-template <class T>
-void OneDArray<T>::Init(const Range& r)
-{
-
- m_first = r.First();
- m_last = r.Last();
- m_length = m_last - m_first + 1;
+ }
+ return *this;
+ }
- if(m_length > 0)
+ template <class T>
+ void OneDArray<T>::Resize(int l)
{
- m_ptr = new T[ m_length ];
+ if (l != m_length)
+ {
+ FreePtr();
+ Init(l);
+ }
}
- else
+
+ //private member functions//
+ ////////////////////////////
+
+ template <class T>
+ void OneDArray<T>::Init(const int len)
{
- m_length = 0;
- m_first = 0;
- m_last = -1;
- m_ptr = NULL;
- }
-}
+ Range r(0 , len-1);
-template <class T>
-void OneDArray<T>::FreePtr()
-{
- if(m_length > 0)
- delete[] m_ptr;
-}
-
-
-//////////////////////////////
-//Two-Dimensional Array type//
-//////////////////////////////
-
-//! A template class for two-dimensional arrays.
-/*!
- A template class to do two-d arrays, so that explicit memory
- (de-)allocation is not required. Only zero-based arrays are
- currently supported so that access is fast. Accessing elements along
- a row is therefore much faster than accessing them along a column.
- Rows are contiguous in memory, so array[y][x] is equivalent to
- array[0][x+y*LengthX()].
- */
-template <class T> class TwoDArray
-{
- typedef T* element_type;
+ Init(r);
-public:
+ }
- //! Default constructor.
- /*!
- Default constructor creates an empty array.
- */
- TwoDArray()
+ template <class T>
+ void OneDArray<T>::Init(const Range& r)
{
- Init(0, 0);
- }
- //! Constructor.
- /*!
- The constructor creates an array of given width height.
- */
- TwoDArray(const int height , const int width)
- {
- Init(height , width);
- }
+ m_first = r.First();
+ m_last = r.Last();
+ m_length = m_last - m_first + 1;
- //! Constructor.
- /*!
- The constructor creates an array of given width and length height
- and initialises it to a value
- */
- TwoDArray(const int height , const int width , T val);
+ if ( m_length>0 )
+ {
+ m_ptr = new T[ m_length ];
+ }
+ else
+ {
+ m_length = 0;
+ m_first = 0;
+ m_last = -1;
+ m_ptr = NULL;
+ }
+ }
- //! Destructor
- /*!
- Destructor frees the data allocated in the constructor.
- */
- virtual ~TwoDArray()
+ template <class T>
+ void OneDArray<T>::FreePtr()
{
- FreeData();
+ if ( m_length>0 )
+ delete[] m_ptr;
}
- //! Copy constructor.
- /*!
- Copy constructor copies data and metadata.
- */
- TwoDArray(const TwoDArray<T>& Cpy);
- //! Assignment =
- /*!
- Assignement = assigns both data and metadata.
- */
- TwoDArray<T>& operator=(const TwoDArray<T>& rhs);
+ //////////////////////////////
+ //Two-Dimensional Array type//
+ //////////////////////////////
- //! Copy Contents
+ //! A template class for two-dimensional arrays.
/*!
- Copy contents of array into output array retaining the dimensions
- of the output array. If output array is larger that array then
- pad with last true value.
- Return true is copy was successful
+ A template class to do two-d arrays, so that explicit memory
+ (de-)allocation is not required. Only zero-based arrays are
+ currently supported so that access is fast. Accessing elements along
+ a row is therefore much faster than accessing them along a column.
+ Rows are contiguous in memory, so array[y][x] is equivalent to
+ array[0][x+y*LengthX()].
*/
- bool CopyContents(TwoDArray<T>& out) const;
+ template <class T> class TwoDArray
+ {
+ typedef T* element_type;
+
+ public:
+
+ //! Default constructor.
+ /*!
+ Default constructor creates an empty array.
+ */
+ TwoDArray(){ Init(0,0); }
+
+ //! Constructor.
+ /*!
+ The constructor creates an array of given width height.
+ */
+ TwoDArray( const int height , const int width ){Init(height , width);}
+
+ //! Constructor.
+ /*!
+ The constructor creates an array of given width and length height
+ and initialises it to a value
+ */
+ TwoDArray( const int height , const int width , T val);
+
+ //! Destructor
+ /*!
+ Destructor frees the data allocated in the constructor.
+ */
+ virtual ~TwoDArray(){
+ FreeData();
+ }
- //! Fill contents
- /*!
- Initialise the array with the val provided.
- */
- void Fill(T val);
+ //! Copy constructor.
+ /*!
+ Copy constructor copies data and metadata.
+ */
+ TwoDArray(const TwoDArray<T>& Cpy);
- //! Resizes the array, deleting the current data.
- void Resize(const int height, const int width);
+ //! Assignment =
+ /*!
+ Assignement = assigns both data and metadata.
+ */
+ TwoDArray<T>& operator=(const TwoDArray<T>& rhs);
- //! Element access.
- /*!
- Accesses the rows of the arrays, which are returned in the form
- of pointers to the row data NOT OneDArray objects.
- */
- inline element_type& operator[](const int pos)
- {
- return m_array_of_rows[pos];
- }
+ //! Copy Contents
+ /*!
+ Copy contents of array into output array retaining the dimensions
+ of the output array. If output array is larger that array then
+ pad with last true value.
+ Return true is copy was successful
+ */
+ bool CopyContents(TwoDArray<T>& out) const;
- //! Element access.
- /*!
- Accesses the rows of the arrays, which are returned in the form of
- pointers to the row data NOT OneDArray objects.
- */
- inline const element_type& operator[](const int pos) const
- {
- return m_array_of_rows[pos];
- }
+ //! Fill contents
+ /*!
+ Initialise the array with the val provided.
+ */
+ void Fill(T val);
- //! Returns the width
- int LengthX() const
- {
- return m_length_x;
- }
+ //! Resizes the array, deleting the current data.
+ void Resize(const int height, const int width);
- //! Returns the height
- int LengthY() const
- {
- return m_length_y;
- }
+ //! Element access.
+ /*!
+ Accesses the rows of the arrays, which are returned in the form
+ of pointers to the row data NOT OneDArray objects.
+ */
+ inline element_type& operator[](const int pos){return m_array_of_rows[pos];}
- //! Returns the index of the first element of a row
- int FirstX() const
- {
- return m_first_x;
- }
+ //! Element access.
+ /*!
+ Accesses the rows of the arrays, which are returned in the form of
+ pointers to the row data NOT OneDArray objects.
+ */
+ inline const element_type& operator[](const int pos) const {return m_array_of_rows[pos];}
- //! Returns the index of the first element of a column
- int FirstY() const
- {
- return m_first_y;
- }
+ //! Returns the width
+ int LengthX() const { return m_length_x; }
- //! Returns the index of the last element of a row
- int LastX() const
- {
- return m_last_x;
- }
+ //! Returns the height
+ int LengthY() const { return m_length_y; }
- //! Returns the index of the first element of a column
- int LastY() const
- {
- return m_last_y;
- }
+ //! Returns the index of the first element of a row
+ int FirstX() const { return m_first_x; }
-private:
- //! Initialise the array
- void Init(const int height, const int width);
+ //! Returns the index of the first element of a column
+ int FirstY() const { return m_first_y; }
- //! Free all the allocated data
- void FreeData();
+ //! Returns the index of the last element of a row
+ int LastX() const { return m_last_x; }
- int m_first_x;
- int m_first_y;
+ //! Returns the index of the first element of a column
+ int LastY() const { return m_last_y; }
- int m_last_x;
- int m_last_y;
+ private:
+ //! Initialise the array
+ void Init(const int height,const int width);
- int m_length_x;
- int m_length_y;
+ //! Free all the allocated data
+ void FreeData();
- element_type* m_array_of_rows;
-};
+ int m_first_x;
+ int m_first_y;
-//public member functions//
-///////////////////////////
+ int m_last_x;
+ int m_last_y;
-template <class T>
-TwoDArray<T>::TwoDArray(const int height , const int width , const T val)
-{
- Init(height , width);
- std::fill_n(m_array_of_rows[0], m_length_x * m_length_y, val);
-}
+ int m_length_x;
+ int m_length_y;
-template <class T>
-TwoDArray<T>::TwoDArray(const TwoDArray<T>& Cpy)
-{
- m_first_x = Cpy.m_first_x;
- m_first_y = Cpy.m_first_y;
- m_last_x = Cpy.m_last_x;
- m_last_y = Cpy.m_last_y;
+ element_type* m_array_of_rows;
+ };
- m_length_x = m_last_x - m_first_x + 1;
- m_length_y = m_last_y - m_first_y + 1;
+ //public member functions//
+ ///////////////////////////
- if(m_first_x == 0 && m_first_y == 0)
- Init(m_length_y , m_length_x);
- else
+ template <class T>
+ TwoDArray<T>::TwoDArray( const int height , const int width , const T val)
{
- //based 2D arrays not yet supported
- }
-
- memcpy(m_array_of_rows[0] , (Cpy.m_array_of_rows)[0] , m_length_x * m_length_y * sizeof(T));
-
-}
+ Init( height , width );
+ std::fill_n( m_array_of_rows[0], m_length_x*m_length_y, val);
+ }
-template <class T>
-TwoDArray<T>& TwoDArray<T>::operator=(const TwoDArray<T>& rhs)
-{
- if(&rhs != this)
+ template <class T>
+ TwoDArray<T>::TwoDArray(const TwoDArray<T>& Cpy)
{
- FreeData();
-
- m_first_x = rhs.m_first_x;
- m_first_y = rhs.m_first_y;
-
- m_last_x = rhs.m_last_x;
- m_last_y = rhs.m_last_y;
+ m_first_x = Cpy.m_first_x;
+ m_first_y = Cpy.m_first_y;
+ m_last_x = Cpy.m_last_x;
+ m_last_y = Cpy.m_last_y;
m_length_x = m_last_x - m_first_x + 1;
- m_length_y = m_last_y - m_first_y + 1;
+ m_length_y = m_last_y - m_first_y + 1;
- if(m_first_x == 0 && m_first_y == 0)
+ if (m_first_x == 0 && m_first_y == 0)
Init(m_length_y , m_length_x);
- else
- {
- //based 2D arrays not yet supported
+ else{
+ //based 2D arrays not yet supported
}
- memcpy(m_array_of_rows[0], (rhs.m_array_of_rows)[0], m_length_x * m_length_y * sizeof(T));
+ memcpy( m_array_of_rows[0] , (Cpy.m_array_of_rows)[0] , m_length_x * m_length_y * sizeof( T ) );
}
- return *this;
-
-}
-
-template <class T>
-bool TwoDArray<T>::CopyContents(TwoDArray<T>& out) const
-{
- if(&out != this)
+ template <class T>
+ TwoDArray<T>& TwoDArray<T>::operator=(const TwoDArray<T>& rhs)
{
- int rows = std::min(m_length_y, out.m_length_y);
- int cols = std::min(m_length_x, out.m_length_x);
- for(int j = 0; j < rows; ++j)
+ if (&rhs != this)
{
- memcpy(out.m_array_of_rows[j], m_array_of_rows[j], cols * sizeof(T)) ;
- for(int i = cols; i < out.m_length_x; ++i)
- out.m_array_of_rows[j][i] = out.m_array_of_rows[j][cols-1];
+ FreeData();
+
+ m_first_x = rhs.m_first_x;
+ m_first_y = rhs.m_first_y;
+
+ m_last_x = rhs.m_last_x;
+ m_last_y = rhs.m_last_y;
+
+ m_length_x = m_last_x - m_first_x + 1;
+ m_length_y = m_last_y - m_first_y + 1;
+
+ if (m_first_x == 0 && m_first_y == 0)
+ Init(m_length_y , m_length_x);
+ else
+ {
+ //based 2D arrays not yet supported
+ }
+
+ memcpy( m_array_of_rows[0], (rhs.m_array_of_rows)[0], m_length_x * m_length_y * sizeof( T ) );
+
}
- for(int j = rows; j < out.m_length_y; ++j)
+
+ return *this;
+
+ }
+
+ template <class T>
+ bool TwoDArray<T>::CopyContents(TwoDArray<T>& out) const
+ {
+ if (&out != this)
{
- memcpy(out.m_array_of_rows[j], out.m_array_of_rows[rows-1], out.m_length_x * sizeof(T)) ;
+ int rows = std::min (m_length_y, out.m_length_y);
+ int cols = std::min (m_length_x, out.m_length_x);
+ for (int j = 0; j < rows; ++j)
+ {
+ memcpy( out.m_array_of_rows[j], m_array_of_rows[j], cols * sizeof( T )) ;
+ for (int i = cols; i <out.m_length_x; ++i)
+ out.m_array_of_rows[j][i] = out.m_array_of_rows[j][cols-1];
+ }
+ for (int j = rows; j < out.m_length_y; ++j)
+ {
+ memcpy( out.m_array_of_rows[j], out.m_array_of_rows[rows-1], out.m_length_x * sizeof( T )) ;
+ }
}
+ return true;
}
- return true;
-}
-
-template <class T>
-void TwoDArray<T>::Fill(T val)
-{
- if(m_length_x && m_length_y)
- std::fill_n(m_array_of_rows[0], m_length_x * m_length_y, val);
-}
+
+ template <class T>
+ void TwoDArray<T>::Fill( T val)
+ {
+ if (m_length_x && m_length_y)
+ std::fill_n( m_array_of_rows[0], m_length_x*m_length_y, val);
+ }
-template <class T>
-void TwoDArray<T>::Resize(const int height, const int width)
-{
- if(height != m_length_y || width != m_length_x)
+ template <class T>
+ void TwoDArray<T>::Resize(const int height, const int width)
{
- FreeData();
- Init(height , width);
+ if (height != m_length_y || width != m_length_x)
+ {
+ FreeData();
+ Init(height , width);
+ }
}
-}
-
-//private member functions//
-////////////////////////////
-template <class T>
-void TwoDArray<T>::Init(const int height , const int width)
-{
- m_length_x = width;
- m_length_y = height;
- m_first_x = 0;
- m_first_y = 0;
-
- m_last_x = m_length_x - 1;
- m_last_y = m_length_y - 1;
+ //private member functions//
+ ////////////////////////////
- if(m_length_y > 0)
+ template <class T>
+ void TwoDArray<T>::Init(const int height , const int width)
{
- // allocate the array containing ptrs to all the rows
- m_array_of_rows = new element_type[ m_length_y ];
+ m_length_x = width;
+ m_length_y = height;
+ m_first_x = 0;
+ m_first_y = 0;
- if(m_length_x > 0)
- {
- // Allocate the whole thing as a single big block
- m_array_of_rows[0] = new T[ m_length_x * m_length_y ];
+ m_last_x = m_length_x-1;
+ m_last_y = m_length_y-1;
- // Point the pointers
- for(int j = 1 ; j < m_length_y ; ++j)
- m_array_of_rows[j] = m_array_of_rows[0] + j * m_length_x;
+ if (m_length_y>0)
+ {
+ // allocate the array containing ptrs to all the rows
+ m_array_of_rows = new element_type[ m_length_y ];
+
+ if ( m_length_x>0 )
+ {
+ // Allocate the whole thing as a single big block
+ m_array_of_rows[0] = new T[ m_length_x * m_length_y ];
+
+ // Point the pointers
+ for (int j=1 ; j<m_length_y ; ++j)
+ m_array_of_rows[j] = m_array_of_rows[0] + j * m_length_x;
+ }
+ else
+ {
+ m_length_x = 0;
+ m_first_x = 0;
+ m_last_x = -1;
+ }
}
- else
+ else
{
m_length_x = 0;
+ m_length_y = 0;
m_first_x = 0;
+ m_first_y = 0;
m_last_x = -1;
+ m_last_y = -1;
+ m_array_of_rows = NULL;
}
}
- else
- {
- m_length_x = 0;
- m_length_y = 0;
- m_first_x = 0;
- m_first_y = 0;
- m_last_x = -1;
- m_last_y = -1;
- m_array_of_rows = NULL;
- }
-}
-template <class T>
-void TwoDArray<T>::FreeData()
-{
- if(m_length_y > 0)
+ template <class T>
+ void TwoDArray<T>::FreeData()
{
- if(m_length_x > 0)
+ if (m_length_y>0)
{
- delete[] m_array_of_rows[0];
- }
-
- m_length_y = m_length_x = 0;
- // deallocate the array of rows
- delete[] m_array_of_rows;
+ if (m_length_x>0)
+ {
+ delete[] m_array_of_rows[0];
+ }
+
+ m_length_y = m_length_x = 0;
+ // deallocate the array of rows
+ delete[] m_array_of_rows;
+ }
}
-}
-// Related functions
+ // Related functions
-//! A function for extracting array data
-template <class T >
-std::ostream & operator<< (std::ostream & stream, TwoDArray<T> & array)
-{
- for(int j = 0 ; j < array.LengthY() ; ++j)
+ //! A function for extracting array data
+ template <class T >
+ std::ostream & operator<< (std::ostream & stream, TwoDArray<T> & array)
{
- for(int i = 0 ; i < array.LengthX() ; ++i)
+ for (int j=0 ; j<array.LengthY() ; ++j)
{
- stream << array[j][i] << " ";
- }// i
- stream << std::endl;
- }// j
-
- return stream;
-}
+ for (int i=0 ; i<array.LengthX() ; ++i)
+ {
+ stream << array[j][i] << " ";
+ }// i
+ stream << std::endl;
+ }// j
+
+ return stream;
+ }
-//! A function for inserting array data
-template <class T >
-std::istream & operator>> (std::istream & stream, TwoDArray<T> & array)
-{
- for(int j = 0 ; j < array.LengthY() ; ++j)
+ //! A function for inserting array data
+ template <class T >
+ std::istream & operator>> (std::istream & stream, TwoDArray<T> & array)
{
- for(int i = 0 ; i < array.LengthX() ; ++i)
+ for (int j=0 ; j<array.LengthY() ; ++j)
{
- stream >> array[j][i];
- }// i
- }// j
+ for (int i=0 ; i<array.LengthX() ; ++i)
+ {
+ stream >> array[j][i];
+ }// i
+ }// j
- return stream;
-}
+ return stream;
+ }
} //namespace dirac
#endif
diff --git a/src/filters/parser/DiracSplitter/libdirac/libdirac_common/band_codec.cpp b/src/filters/parser/DiracSplitter/libdirac/libdirac_common/band_codec.cpp
index bb751e1f0..fc0e42312 100644
--- a/src/filters/parser/DiracSplitter/libdirac/libdirac_common/band_codec.cpp
+++ b/src/filters/parser/DiracSplitter/libdirac/libdirac_common/band_codec.cpp
@@ -72,25 +72,25 @@ GenericIntraDCBandCodec<ArithCodec<CoeffArray> >::GenericIntraDCBandCodec(
void IntraDCBandCodec::DoWorkCode(CoeffArray& in_data)
{
// Residues after prediction, quantisation and inverse quantisation
- m_dc_pred_res.Resize(m_node.Yl() , m_node.Xl());
- m_dc_pred_res.Fill(0);
+ m_dc_pred_res.Resize( m_node.Yl() , m_node.Xl() );
+ m_dc_pred_res.Fill( 0 );
BandCodec::DoWorkCode(in_data);
}
-void IntraDCBandCodec::CodeCoeff(CoeffArray& in_data, const int xpos, const int ypos)
+void IntraDCBandCodec::CodeCoeff( CoeffArray& in_data, const int xpos, const int ypos)
{
m_nhood_nonzero = false;
- if(ypos > m_node.Yp())
+ if (ypos > m_node.Yp())
m_nhood_nonzero |= bool(m_dc_pred_res[ypos-1][xpos]);
- if(xpos > m_node.Xp())
+ if (xpos > m_node.Xp())
m_nhood_nonzero |= bool(m_dc_pred_res[ypos][xpos-1]);
- if(ypos > m_node.Yp() && xpos > m_node.Xp())
+ if (ypos > m_node.Yp() && xpos > m_node.Xp())
m_nhood_nonzero |= bool(m_dc_pred_res[ypos-1][xpos-1]);
- ValueType prediction = GetPrediction(in_data , xpos , ypos);
+ ValueType prediction = GetPrediction( in_data , xpos , ypos );
ValueType val = in_data[ypos][xpos] - prediction;
- CodeVal(in_data , xpos , ypos , val);
+ CodeVal( in_data , xpos , ypos , val );
m_dc_pred_res[ypos][xpos] = in_data[ypos][xpos];
in_data[ypos][xpos] += prediction;
}
@@ -98,22 +98,22 @@ void IntraDCBandCodec::CodeCoeff(CoeffArray& in_data, const int xpos, const int
void IntraDCBandCodec::DoWorkDecode(CoeffArray& out_data)
{
// Residues after prediction, quantisation and inverse quantisation
- m_dc_pred_res.Resize(m_node.Yl() , m_node.Xl());
- m_dc_pred_res.Fill(0);
+ m_dc_pred_res.Resize( m_node.Yl() , m_node.Xl() );
+ m_dc_pred_res.Fill( 0 );
BandCodec::DoWorkDecode(out_data);
}
-void IntraDCBandCodec::DecodeCoeff(CoeffArray& out_data, const int xpos, const int ypos)
+void IntraDCBandCodec::DecodeCoeff( CoeffArray& out_data, const int xpos, const int ypos)
{
m_nhood_nonzero = false;
- if(ypos > m_node.Yp())
+ if (ypos > m_node.Yp())
m_nhood_nonzero |= bool(m_dc_pred_res[ypos-1][xpos]);
- if(xpos > m_node.Xp())
+ if (xpos > m_node.Xp())
m_nhood_nonzero |= bool(m_dc_pred_res[ypos][xpos-1]);
- if(ypos > m_node.Yp() && xpos > m_node.Xp())
+ if (ypos > m_node.Yp() && xpos > m_node.Xp())
m_nhood_nonzero |= bool(m_dc_pred_res[ypos-1][xpos-1]);
- DecodeVal(out_data , xpos , ypos);
+ DecodeVal( out_data , xpos , ypos );
m_dc_pred_res[ypos][xpos] = out_data[ypos][xpos];
}
diff --git a/src/filters/parser/DiracSplitter/libdirac/libdirac_common/band_codec.h b/src/filters/parser/DiracSplitter/libdirac/libdirac_common/band_codec.h
index e03c75aaa..dfebb2e7f 100644
--- a/src/filters/parser/DiracSplitter/libdirac/libdirac_common/band_codec.h
+++ b/src/filters/parser/DiracSplitter/libdirac/libdirac_common/band_codec.h
@@ -48,201 +48,201 @@
namespace dirac
{
-class SubbandByteIO;
+ class SubbandByteIO;
-//Subclasses the arithmetic codec to produce a coding/decoding tool for subbands
+ //Subclasses the arithmetic codec to produce a coding/decoding tool for subbands
-//! A template class for coding and decoding wavelet subband data.
-template<typename EntropyCodec>
-class GenericBandCodec: public EntropyCodec
-{
-public:
-
- //! Constructor
- /*!
- Creates a BandCodec object to encode subband data
- \param subband_byteio input/output for the encoded bits
- \param number_of_contexts the number of contexts used in the encoding process
- \param band_list the set of all the subbands
- \param band_num the number of the subband being coded
- \param is_intra Flag indicating whether the band comes from an intra picture
- */
- GenericBandCodec(SubbandByteIO* subband_byteio,
- size_t number_of_contexts,
- const SubbandList& band_list,
- int band_num,
- const bool is_intra);
+ //! A template class for coding and decoding wavelet subband data.
+ template<typename EntropyCodec>
+ class GenericBandCodec: public EntropyCodec
+ {
+ public:
-protected:
- //! Code an individual quantised value and perform inverse-quantisation
- inline void CodeVal(CoeffArray& in_data , const int xpos , const int ypos , const CoeffType val);
+ //! Constructor
+ /*!
+ Creates a BandCodec object to encode subband data
+ \param subband_byteio input/output for the encoded bits
+ \param number_of_contexts the number of contexts used in the encoding process
+ \param band_list the set of all the subbands
+ \param band_num the number of the subband being coded
+ \param is_intra Flag indicating whether the band comes from an intra picture
+ */
+ GenericBandCodec(SubbandByteIO* subband_byteio,
+ size_t number_of_contexts,
+ const SubbandList& band_list,
+ int band_num,
+ const bool is_intra);
- //! Decode an individual quantised value and perform inverse-quantisation
- inline void DecodeVal(CoeffArray& out_data , const int xpos , const int ypos);
+ protected:
+ //! Code an individual quantised value and perform inverse-quantisation
+ inline void CodeVal( CoeffArray& in_data , const int xpos , const int ypos , const CoeffType val);
- //! Encode the offset for a code block quantiser
- void CodeQuantIndexOffset(const int offset);
+ //! Decode an individual quantised value and perform inverse-quantisation
+ inline void DecodeVal(CoeffArray& out_data , const int xpos , const int ypos );
- //! Decode the offset for a code block quantiser
- int DecodeQuantIndexOffset();
+ //! Encode the offset for a code block quantiser
+ void CodeQuantIndexOffset( const int offset );
- //! Set a code block area to a given value
- inline void SetToVal(const CodeBlock& code_block , CoeffArray& coeff_data , const CoeffType val);
+ //! Decode the offset for a code block quantiser
+ int DecodeQuantIndexOffset();
- //! Set all block values to 0
- virtual void ClearBlock(const CodeBlock& code_block , CoeffArray& coeff_data);
+ //! Set a code block area to a given value
+ inline void SetToVal( const CodeBlock& code_block , CoeffArray& coeff_data , const CoeffType val);
-protected:
- //functions
- // Overridden from the base class
- virtual void DoWorkCode(CoeffArray& in_data);
- // Ditto
- virtual void DoWorkDecode(CoeffArray& out_data);
+ //! Set all block values to 0
+ virtual void ClearBlock( const CodeBlock& code_block , CoeffArray& coeff_data);
- virtual void CodeCoeffBlock(const CodeBlock& code_block , CoeffArray& in_data);
- virtual void DecodeCoeffBlock(const CodeBlock& code_block , CoeffArray& out_data);
+ protected:
+ //functions
+ // Overridden from the base class
+ virtual void DoWorkCode(CoeffArray& in_data);
+ // Ditto
+ virtual void DoWorkDecode(CoeffArray& out_data);
- virtual void CodeCoeff(CoeffArray& in_data, const int xpos, const int ypos);
+ virtual void CodeCoeffBlock(const CodeBlock& code_block , CoeffArray& in_data);
+ virtual void DecodeCoeffBlock(const CodeBlock& code_block , CoeffArray& out_data);
- virtual void DecodeCoeff(CoeffArray& in_data, const int xpos, const int ypos);
- //! A function for choosing the context for "follow bits"
- inline int ChooseFollowContext(const int bin_number) const;
+ virtual void CodeCoeff(CoeffArray& in_data, const int xpos, const int ypos);
- //! A function for choosing the context for "information bits"
- inline int ChooseInfoContext() const;
+ virtual void DecodeCoeff(CoeffArray& in_data, const int xpos, const int ypos);
+ //! A function for choosing the context for "follow bits"
+ inline int ChooseFollowContext( const int bin_number ) const;
- //! A function for choosing the context for sign bits
- inline int ChooseSignContext(const CoeffArray& data , const int xpos , const int ypos) const;
+ //! A function for choosing the context for "information bits"
+ inline int ChooseInfoContext() const;
-private:
- //! Private, bodyless copy constructor: class should not be copied
- GenericBandCodec(const GenericBandCodec& cpy);
- //! Private, bodyless copy operator=: class should not be assigned
- GenericBandCodec& operator=(const GenericBandCodec& rhs);
+ //! A function for choosing the context for sign bits
+ inline int ChooseSignContext(const CoeffArray& data , const int xpos , const int ypos ) const;
-protected:
+ private:
+ //! Private, bodyless copy constructor: class should not be copied
+ GenericBandCodec(const GenericBandCodec& cpy);
+ //! Private, bodyless copy operator=: class should not be assigned
+ GenericBandCodec& operator=(const GenericBandCodec& rhs);
- //! Flag indicating whether the band comes from an intra picture
- bool m_is_intra;
+ protected:
- //! variables
- int m_bnum;
+ //! Flag indicating whether the band comes from an intra picture
+ bool m_is_intra;
- //! the subband being coded
- const Subband m_node;
+ //! variables
+ int m_bnum;
- //! the quantisation index of the last codeblock
- int m_last_qf_idx;
+ //! the subband being coded
+ const Subband m_node;
- //! quantisation value
- int m_qf;
+ //! the quantisation index of the last codeblock
+ int m_last_qf_idx;
- //! reconstruction point
- CoeffType m_offset;
+ //! quantisation value
+ int m_qf;
- //! True if neighbours non-zero
- bool m_nhood_nonzero;
+ //! reconstruction point
+ CoeffType m_offset;
- //! the parent subband
- Subband m_pnode;
+ //! True if neighbours non-zero
+ bool m_nhood_nonzero;
- //! position of the parent coefficient
- int m_pxpos, m_pypos;
+ //! the parent subband
+ Subband m_pnode;
- //! True if the parent of a coeff is not zero
- bool m_parent_notzero;
+ //! position of the parent coefficient
+ int m_pxpos, m_pypos;
-};
+ //! True if the parent of a coeff is not zero
+ bool m_parent_notzero;
-//! A general class for coding and decoding wavelet subband data.
-/*!
- A general class for coding and decoding wavelet subband data, deriving from the abstract ArithCodec class.
- */
-typedef GenericBandCodec<ArithCodec<CoeffArray> > BandCodec;
-typedef BandCodec LFBandCodec;
+ };
-//////////////////////////////////////////////////////////////////////////////////
-//Finally,special class incorporating prediction for the DC band of intra frames//
-//////////////////////////////////////////////////////////////////////////////////
-
-//! A template class specially for coding the DC subband of Intra frames
-template<typename EntropyCodec>
-class GenericIntraDCBandCodec : public GenericBandCodec<EntropyCodec>
-{
-public:
- //! Constructor
+ //! A general class for coding and decoding wavelet subband data.
/*!
- Creates a IntraDCBandCodec object to encode subband data
- \param subband_byteio input/output for the encoded bits
- \param number_of_contexts the number of contexts used in the encoding process
- \param band_list the set of all the subbands
+ A general class for coding and decoding wavelet subband data, deriving from the abstract ArithCodec class.
*/
- GenericIntraDCBandCodec(SubbandByteIO* subband_byteio,
- size_t number_of_contexts,
- const SubbandList& band_list)
- : GenericBandCodec<EntropyCodec>(subband_byteio, number_of_contexts,
- band_list, band_list.Length(),
- true) {}
-
-protected:
- //! When coding a skipped block, propegate the predicted values for future non skipped blocks
- void ClearBlock(const CodeBlock& code_block , CoeffArray& coeff_data);
-
- //! Prediction of a DC value from its previously coded neighbours
- CoeffType GetPrediction(const CoeffArray& data , const int xpos , const int ypos) const;
-
- //! Decode codeblock of coefficients and perform DC prediction
- void DecodeCoeffBlock(const CodeBlock& code_block , CoeffArray& out_data);
-};
-
-
-//! A class specially for coding the DC subband of Intra frames
-/*!
- A class specially for coding the DC subband of Intra frames, using
- intra-band prediction of coefficients. It uses the abstract ArithCodec
- class
-*/
-class IntraDCBandCodec: public GenericIntraDCBandCodec<ArithCodec<CoeffArray> >
-{
-public:
- //! Constructor
+ typedef GenericBandCodec<ArithCodec<CoeffArray> > BandCodec;
+ typedef BandCodec LFBandCodec;
+
+ //////////////////////////////////////////////////////////////////////////////////
+ //Finally,special class incorporating prediction for the DC band of intra frames//
+ //////////////////////////////////////////////////////////////////////////////////
+
+ //! A template class specially for coding the DC subband of Intra frames
+ template<typename EntropyCodec>
+ class GenericIntraDCBandCodec : public GenericBandCodec<EntropyCodec>
+ {
+ public:
+ //! Constructor
+ /*!
+ Creates a IntraDCBandCodec object to encode subband data
+ \param subband_byteio input/output for the encoded bits
+ \param number_of_contexts the number of contexts used in the encoding process
+ \param band_list the set of all the subbands
+ */
+ GenericIntraDCBandCodec(SubbandByteIO* subband_byteio,
+ size_t number_of_contexts,
+ const SubbandList& band_list)
+ : GenericBandCodec<EntropyCodec>(subband_byteio,number_of_contexts,
+ band_list, band_list.Length(),
+ true){}
+
+ protected:
+ //! When coding a skipped block, propegate the predicted values for future non skipped blocks
+ void ClearBlock( const CodeBlock& code_block , CoeffArray& coeff_data);
+
+ //! Prediction of a DC value from its previously coded neighbours
+ CoeffType GetPrediction(const CoeffArray& data , const int xpos , const int ypos ) const;
+
+ //! Decode codeblock of coefficients and perform DC prediction
+ void DecodeCoeffBlock(const CodeBlock& code_block , CoeffArray& out_data);
+ };
+
+
+ //! A class specially for coding the DC subband of Intra frames
/*!
- Creates a IntraDCBandCodec object to encode subband data, based on parameters
- \param subband_byteio input/output for the encoded bits
- \param number_of_contexts the number of contexts used in the encoding process
- \param band_list the set of all the subbands
- */
- IntraDCBandCodec(SubbandByteIO* subband_byteio,
- size_t number_of_contexts,
- const SubbandList& band_list)
- : GenericIntraDCBandCodec<ArithCodec<CoeffArray> >(subband_byteio,
- number_of_contexts,
- band_list) {}
-
-
-private:
- //! Initialize extra data required for error-feedback DC quantization
- void DoWorkCode(CoeffArray& in_data); //overridden from the base class
-
- //! Ditto
- void DoWorkDecode(CoeffArray& out_data);
-
- //! Encode a single coefficient using error-feedback DC quantization
- void CodeCoeff(CoeffArray& in_data, const int xpos, const int ypos);
-
- //! Decode a single coefficient using error-feedback DC quantization
- void DecodeCoeff(CoeffArray& out_data, const int xpos, const int ypos);
-
- //! Private, bodyless copy constructor: class should not be copied
- IntraDCBandCodec(const IntraDCBandCodec& cpy);
-
- //! Private, bodyless copy operator=: class should not be assigned
- IntraDCBandCodec& operator=(const IntraDCBandCodec& rhs);
-
-private:
- CoeffArray m_dc_pred_res;
-};
+ A class specially for coding the DC subband of Intra frames, using
+ intra-band prediction of coefficients. It uses the abstract ArithCodec
+ class
+ */
+ class IntraDCBandCodec: public GenericIntraDCBandCodec<ArithCodec<CoeffArray> >
+ {
+ public:
+ //! Constructor
+ /*!
+ Creates a IntraDCBandCodec object to encode subband data, based on parameters
+ \param subband_byteio input/output for the encoded bits
+ \param number_of_contexts the number of contexts used in the encoding process
+ \param band_list the set of all the subbands
+ */
+ IntraDCBandCodec(SubbandByteIO* subband_byteio,
+ size_t number_of_contexts,
+ const SubbandList& band_list)
+ : GenericIntraDCBandCodec<ArithCodec<CoeffArray> >(subband_byteio,
+ number_of_contexts,
+ band_list){}
+
+
+ private:
+ //! Initialize extra data required for error-feedback DC quantization
+ void DoWorkCode(CoeffArray& in_data); //overridden from the base class
+
+ //! Ditto
+ void DoWorkDecode(CoeffArray& out_data);
+
+ //! Encode a single coefficient using error-feedback DC quantization
+ void CodeCoeff(CoeffArray& in_data, const int xpos, const int ypos);
+
+ //! Decode a single coefficient using error-feedback DC quantization
+ void DecodeCoeff(CoeffArray& out_data, const int xpos, const int ypos);
+
+ //! Private, bodyless copy constructor: class should not be copied
+ IntraDCBandCodec(const IntraDCBandCodec& cpy);
+
+ //! Private, bodyless copy operator=: class should not be assigned
+ IntraDCBandCodec& operator=(const IntraDCBandCodec& rhs);
+
+ private:
+ CoeffArray m_dc_pred_res;
+ };
}// end namespace dirac
#endif
diff --git a/src/filters/parser/DiracSplitter/libdirac/libdirac_common/band_codec_template.h b/src/filters/parser/DiracSplitter/libdirac/libdirac_common/band_codec_template.h
index b1f924786..8ca94d089 100644
--- a/src/filters/parser/DiracSplitter/libdirac/libdirac_common/band_codec_template.h
+++ b/src/filters/parser/DiracSplitter/libdirac/libdirac_common/band_codec_template.h
@@ -7,18 +7,18 @@ using namespace dirac;
//! Constructor for encoding.
template<typename EntropyCodec>
GenericBandCodec<EntropyCodec>::GenericBandCodec(SubbandByteIO* subband_byteio,
- size_t number_of_contexts,
- const SubbandList & band_list,
- int band_num,
- const bool is_intra):
- EntropyCodec(subband_byteio, number_of_contexts),
+ size_t number_of_contexts,
+ const SubbandList & band_list,
+ int band_num,
+ const bool is_intra):
+ EntropyCodec(subband_byteio,number_of_contexts),
m_is_intra(is_intra),
m_bnum(band_num),
m_node(band_list(band_num)),
m_last_qf_idx(m_node.QuantIndex())
{
- if(m_node.Parent() != 0)
- m_pnode = band_list(m_node.Parent());
+ if (m_node.Parent()!=0)
+ m_pnode=band_list(m_node.Parent());
}
@@ -27,30 +27,30 @@ template<typename EntropyCodec>
void GenericBandCodec<EntropyCodec>::DoWorkCode(CoeffArray& in_data)
{
- const TwoDArray<CodeBlock>& block_list(m_node.GetCodeBlocks());
+ const TwoDArray<CodeBlock>& block_list( m_node.GetCodeBlocks() );
// coeff blocks can be skipped only if SpatialPartitioning is
// enabled i.e. more than one code-block per subband
bool code_skip = (block_list.LengthX() > 1 || block_list.LengthY() > 1);
// Now loop over the blocks and code
- for(int j = block_list.FirstY() ; j <= block_list.LastY() ; ++j)
+ for (int j=block_list.FirstY() ; j<=block_list.LastY() ; ++j)
{
CodeBlock *block = block_list[j];
- for(int i = block_list.FirstX() ; i <= block_list.LastX() ; ++i)
+ for (int i=block_list.FirstX() ; i<=block_list.LastX() ; ++i)
{
- if(code_skip)
- EntropyCodec::EncodeSymbol(block[i].Skipped() , BLOCK_SKIP_CTX);
- if(!block[i].Skipped())
- CodeCoeffBlock(block[i] , in_data);
+ if (code_skip)
+ EntropyCodec::EncodeSymbol(block[i].Skipped() , BLOCK_SKIP_CTX );
+ if ( !block[i].Skipped() )
+ CodeCoeffBlock( block[i] , in_data );
else
- ClearBlock(block[i] , in_data);
+ ClearBlock (block[i] , in_data);
}// i
}// j
}
template<typename EntropyCodec>
-void GenericBandCodec<EntropyCodec>::CodeCoeffBlock(const CodeBlock& code_block , CoeffArray& in_data)
+void GenericBandCodec<EntropyCodec>::CodeCoeffBlock( const CodeBlock& code_block , CoeffArray& in_data )
{
//main coding function, using binarisation
@@ -63,39 +63,39 @@ void GenericBandCodec<EntropyCodec>::CodeCoeffBlock(const CodeBlock& code_block
bool has_parent = m_node.Parent() != 0;
- if(m_node.UsingMultiQuants())
+ if ( m_node.UsingMultiQuants() )
{
- CodeQuantIndexOffset(qf_idx - m_last_qf_idx);
- m_last_qf_idx = qf_idx;
+ CodeQuantIndexOffset( qf_idx - m_last_qf_idx);
+ m_last_qf_idx = qf_idx;
}
- m_qf = dirac_quantiser_lists.QuantFactor4(qf_idx);
- if(m_is_intra)
- m_offset = dirac_quantiser_lists.IntraQuantOffset4(qf_idx);
+ m_qf = dirac_quantiser_lists.QuantFactor4( qf_idx );
+ if (m_is_intra)
+ m_offset = dirac_quantiser_lists.IntraQuantOffset4( qf_idx );
else
- m_offset = dirac_quantiser_lists.InterQuantOffset4(qf_idx);
+ m_offset = dirac_quantiser_lists.InterQuantOffset4( qf_idx );
- for(int ypos = ybeg; ypos < yend ; ++ypos)
+ for ( int ypos=ybeg; ypos<yend ;++ypos)
{
- m_pypos = ((ypos - m_node.Yp()) >> 1) + m_pnode.Yp();
- for(int xpos = xbeg; xpos < xend ; ++xpos)
+ m_pypos=(( ypos-m_node.Yp() )>>1)+m_pnode.Yp();
+ for ( int xpos=xbeg; xpos<xend ;++xpos)
{
- m_pxpos = ((xpos - m_node.Xp()) >> 1) + m_pnode.Xp();
+ m_pxpos=(( xpos-m_node.Xp() )>>1)+m_pnode.Xp();
m_nhood_nonzero = false;
- if(ypos > m_node.Yp())
+ if (ypos > m_node.Yp())
m_nhood_nonzero |= bool(in_data[ypos-1][xpos]);
- if(xpos > m_node.Xp())
+ if (xpos > m_node.Xp())
m_nhood_nonzero |= bool(in_data[ypos][xpos-1]);
- if(ypos > m_node.Yp() && xpos > m_node.Xp())
+ if (ypos > m_node.Yp() && xpos > m_node.Xp())
m_nhood_nonzero |= bool(in_data[ypos-1][xpos-1]);
- if(has_parent)
- m_parent_notzero = static_cast<bool>(in_data[m_pypos][m_pxpos]);
+ if (has_parent)
+ m_parent_notzero = static_cast<bool> ( in_data[m_pypos][m_pxpos] );
else
m_parent_notzero = false;
- CodeCoeff(in_data , xpos , ypos);
+ CodeCoeff( in_data , xpos , ypos );
}// xpos
}// ypos
@@ -103,9 +103,9 @@ void GenericBandCodec<EntropyCodec>::CodeCoeffBlock(const CodeBlock& code_block
}
template<typename EntropyCodec>
-void GenericBandCodec<EntropyCodec>::CodeCoeff(CoeffArray& in_data, const int xpos, const int ypos)
+void GenericBandCodec<EntropyCodec>::CodeCoeff( CoeffArray& in_data, const int xpos, const int ypos)
{
- CodeVal(in_data , xpos , ypos , in_data[ypos][xpos]);
+ CodeVal( in_data , xpos , ypos , in_data[ypos][xpos] );
}
@@ -128,99 +128,99 @@ based on position, and have different contexts from the info bits.
*/
template<typename EntropyCodec>
-inline void GenericBandCodec<EntropyCodec>::CodeVal(CoeffArray& in_data ,
- const int xpos ,
- const int ypos ,
- const CoeffType val)
+inline void GenericBandCodec<EntropyCodec>::CodeVal( CoeffArray& in_data ,
+ const int xpos ,
+ const int ypos ,
+ const CoeffType val )
{
- unsigned int abs_val(std::abs(val));
+ unsigned int abs_val( std::abs(val) );
abs_val <<= 2;
abs_val /= m_qf;
- const int N = abs_val + 1;
- int num_follow_zeroes = 0;
+ const int N = abs_val+1;
+ int num_follow_zeroes=0;
- while(N >= (1 << num_follow_zeroes))
+ while ( N >= (1<<num_follow_zeroes) )
++num_follow_zeroes;
--num_follow_zeroes;
- for(int i = num_follow_zeroes - 1, c = 1; i >= 0; --i, ++c)
+ for ( int i=num_follow_zeroes-1, c=1; i>=0; --i, ++c )
{
- EntropyCodec::EncodeSymbol(0, ChooseFollowContext(c));
- EntropyCodec::EncodeSymbol(N&(1 << i), ChooseInfoContext());
+ EntropyCodec::EncodeSymbol( 0, ChooseFollowContext( c ) );
+ EntropyCodec::EncodeSymbol( N&(1<<i), ChooseInfoContext() );
}
- EntropyCodec::EncodeSymbol(1, ChooseFollowContext(num_follow_zeroes + 1));
+ EntropyCodec::EncodeSymbol( 1, ChooseFollowContext( num_follow_zeroes+1 ) );
- in_data[ypos][xpos] = static_cast<CoeffType>(abs_val);
+ in_data[ypos][xpos] = static_cast<CoeffType>( abs_val );
- if(abs_val)
+ if ( abs_val )
{
// Must code sign bits and reconstruct
in_data[ypos][xpos] *= m_qf;
- in_data[ypos][xpos] += m_offset + 2;
+ in_data[ypos][xpos] += m_offset+2;
in_data[ypos][xpos] >>= 2;
- if(val > 0)
+ if ( val>0 )
{
- EntropyCodec::EncodeSymbol(0 , ChooseSignContext(in_data , xpos , ypos));
+ EntropyCodec::EncodeSymbol( 0 , ChooseSignContext( in_data , xpos , ypos ) );
}
else
{
- EntropyCodec::EncodeSymbol(1 , ChooseSignContext(in_data , xpos , ypos));
+ EntropyCodec::EncodeSymbol( 1 , ChooseSignContext( in_data , xpos , ypos ) );
in_data[ypos][xpos] = -in_data[ypos][xpos];
}
}
}
template<typename EntropyCodec>
-void GenericBandCodec<EntropyCodec>::CodeQuantIndexOffset(const int offset)
+void GenericBandCodec<EntropyCodec>::CodeQuantIndexOffset( const int offset )
{
- const int abs_val = std::abs(offset);
+ const int abs_val = std::abs( offset );
- int N = abs_val + 1;
- int num_follow_zeroes = 0;
+ int N = abs_val+1;
+ int num_follow_zeroes=0;
- while(N >= (1 << num_follow_zeroes))
+ while ( N>= (1<<num_follow_zeroes) )
++num_follow_zeroes;
--num_follow_zeroes;
- for(int i = num_follow_zeroes - 1, c = 1; i >= 0; --i, ++c)
+ for ( int i=num_follow_zeroes-1, c=1; i>=0; --i, ++c )
{
- EntropyCodec::EncodeSymbol(0 , Q_OFFSET_FOLLOW_CTX);
- EntropyCodec::EncodeSymbol(N&(1 << i), Q_OFFSET_INFO_CTX);
+ EntropyCodec::EncodeSymbol( 0 , Q_OFFSET_FOLLOW_CTX );
+ EntropyCodec::EncodeSymbol( N&(1<<i), Q_OFFSET_INFO_CTX );
}
- EntropyCodec::EncodeSymbol(1 , Q_OFFSET_FOLLOW_CTX);
+ EntropyCodec::EncodeSymbol( 1 , Q_OFFSET_FOLLOW_CTX );
- if(abs_val)
+ if ( abs_val )
{
- if(offset > 0)
- EntropyCodec::EncodeSymbol(0 , Q_OFFSET_SIGN_CTX);
+ if ( offset>0 )
+ EntropyCodec::EncodeSymbol( 0 , Q_OFFSET_SIGN_CTX );
else
- EntropyCodec::EncodeSymbol(1 , Q_OFFSET_SIGN_CTX);
+ EntropyCodec::EncodeSymbol( 1 , Q_OFFSET_SIGN_CTX );
}
}
template<typename EntropyCodec>
-void GenericBandCodec<EntropyCodec>::DoWorkDecode(CoeffArray& out_data)
+void GenericBandCodec<EntropyCodec>::DoWorkDecode( CoeffArray& out_data )
{
- const TwoDArray<CodeBlock>& block_list(m_node.GetCodeBlocks());
+ const TwoDArray<CodeBlock>& block_list( m_node.GetCodeBlocks() );
// coeff blocks can be skipped only if SpatialPartitioning is
// enabled i.e. more than one code-block per subband
- bool decode_skip = (block_list.LengthX() > 1 || block_list.LengthY() > 1);
+ bool decode_skip= (block_list.LengthX() > 1 || block_list.LengthY() > 1);
// Now loop over the blocks and decode
- for(int j = block_list.FirstY() ; j <= block_list.LastY() ; ++j)
+ for (int j=block_list.FirstY() ; j<=block_list.LastY() ; ++j)
{
CodeBlock *block = block_list[j];
- for(int i = block_list.FirstX() ; i <= block_list.LastX() ; ++i)
+ for (int i=block_list.FirstX() ; i<=block_list.LastX() ; ++i)
{
- if(decode_skip)
- block[i].SetSkip(EntropyCodec::DecodeSymbol(BLOCK_SKIP_CTX));
- if(!block[i].Skipped())
- DecodeCoeffBlock(block[i] , out_data);
+ if (decode_skip)
+ block[i].SetSkip( EntropyCodec::DecodeSymbol( BLOCK_SKIP_CTX ) );
+ if ( !block[i].Skipped() )
+ DecodeCoeffBlock( block[i] , out_data );
else
- ClearBlock(block[i] , out_data);
+ ClearBlock (block[i] , out_data);
}// i
}// j
@@ -228,7 +228,7 @@ void GenericBandCodec<EntropyCodec>::DoWorkDecode(CoeffArray& out_data)
}
template<typename EntropyCodec>
-void GenericBandCodec<EntropyCodec>::DecodeCoeffBlock(const CodeBlock& code_block , CoeffArray& out_data)
+void GenericBandCodec<EntropyCodec>::DecodeCoeffBlock( const CodeBlock& code_block , CoeffArray& out_data )
{
@@ -241,13 +241,13 @@ void GenericBandCodec<EntropyCodec>::DecodeCoeffBlock(const CodeBlock& code_bloc
bool has_parent = m_node.Parent() != 0;
- if(m_node.UsingMultiQuants())
+ if ( m_node.UsingMultiQuants() )
{
- qf_idx = m_last_qf_idx + DecodeQuantIndexOffset();
+ qf_idx = m_last_qf_idx+DecodeQuantIndexOffset();
m_last_qf_idx = qf_idx;
}
- if(qf_idx > (int)dirac_quantiser_lists.MaxQuantIndex())
+ if (qf_idx > (int)dirac_quantiser_lists.MaxQuantIndex())
{
std::ostringstream errstr;
errstr << "Quantiser index out of range [0.."
@@ -258,54 +258,54 @@ void GenericBandCodec<EntropyCodec>::DecodeCoeffBlock(const CodeBlock& code_bloc
SEVERITY_PICTURE_ERROR);
}
- m_qf = dirac_quantiser_lists.QuantFactor4(qf_idx);
+ m_qf = dirac_quantiser_lists.QuantFactor4( qf_idx );
- if(m_is_intra)
- m_offset = dirac_quantiser_lists.IntraQuantOffset4(qf_idx);
+ if (m_is_intra)
+ m_offset = dirac_quantiser_lists.IntraQuantOffset4( qf_idx );
else
- m_offset = dirac_quantiser_lists.InterQuantOffset4(qf_idx);
+ m_offset = dirac_quantiser_lists.InterQuantOffset4( qf_idx );
//Work
- for(int ypos = ybeg; ypos < yend ; ++ypos)
+ for ( int ypos=ybeg; ypos<yend ;++ypos)
{
- m_pypos = ((ypos - m_node.Yp()) >> 1) + m_pnode.Yp();
+ m_pypos=(( ypos-m_node.Yp() )>>1)+m_pnode.Yp();
CoeffType *p_out_data = NULL;
- if(has_parent)
+ if (has_parent)
p_out_data = out_data[m_pypos];
CoeffType *c_out_data_1 = NULL;
- if(ypos != m_node.Yp())
+ if (ypos!=m_node.Yp())
c_out_data_1 = out_data[ypos-1];
CoeffType *c_out_data_2 = out_data[ypos];
- for(int xpos = xbeg; xpos < xend ; ++xpos)
+ for ( int xpos=xbeg; xpos<xend ;++xpos)
{
- m_pxpos = ((xpos - m_node.Xp()) >> 1) + m_pnode.Xp();
+ m_pxpos=(( xpos-m_node.Xp() )>>1)+m_pnode.Xp();
m_nhood_nonzero = false;
/* c_out_data_1 is the line above the current
* c_out_data_2 is the current line */
- if(ypos > m_node.Yp())
+ if (ypos > m_node.Yp())
m_nhood_nonzero |= bool(c_out_data_1[xpos]);
- if(xpos > m_node.Xp())
+ if (xpos > m_node.Xp())
m_nhood_nonzero |= bool(c_out_data_2[xpos-1]);
- if(ypos > m_node.Yp() && xpos > m_node.Xp())
+ if (ypos > m_node.Yp() && xpos > m_node.Xp())
m_nhood_nonzero |= bool(c_out_data_1[xpos-1]);
- if(has_parent)
- m_parent_notzero = (p_out_data[m_pxpos] != 0);
+ if (has_parent)
+ m_parent_notzero = ( p_out_data[m_pxpos] != 0 );
else
m_parent_notzero = false;
- DecodeCoeff(out_data , xpos , ypos);
+ DecodeCoeff( out_data , xpos , ypos );
}// xpos
}// ypos
}
template<typename EntropyCodec>
-void GenericBandCodec<EntropyCodec>::DecodeCoeff(CoeffArray& in_data, const int xpos, const int ypos)
+void GenericBandCodec<EntropyCodec>::DecodeCoeff( CoeffArray& in_data, const int xpos, const int ypos)
{
- DecodeVal(in_data , xpos , ypos);
+ DecodeVal( in_data , xpos , ypos );
}
@@ -327,80 +327,80 @@ All bits are arithmetically coded. The follow bits have separate contexts
based on position, and have different contexts from the info bits.
*/
template<typename EntropyCodec>
-inline void GenericBandCodec<EntropyCodec>::DecodeVal(CoeffArray& out_data , const int xpos , const int ypos)
+inline void GenericBandCodec<EntropyCodec>::DecodeVal( CoeffArray& out_data , const int xpos , const int ypos )
{
CoeffType& out_pixel = out_data[ypos][xpos];
out_pixel = 1;
- int bit_count = 1;
+ int bit_count=1;
- while(!EntropyCodec::DecodeSymbol(ChooseFollowContext(bit_count)))
+ while ( !EntropyCodec::DecodeSymbol( ChooseFollowContext( bit_count ) ) )
{
out_pixel <<= 1;
- out_pixel |= EntropyCodec::DecodeSymbol(ChooseInfoContext());
+ out_pixel |= EntropyCodec::DecodeSymbol( ChooseInfoContext() );
bit_count++;
};
--out_pixel;
- if(out_pixel)
+ if ( out_pixel )
{
out_pixel *= m_qf;
- out_pixel += m_offset + 2;
+ out_pixel += m_offset+2;
out_pixel >>= 2;
- if(EntropyCodec::DecodeSymbol(ChooseSignContext(out_data, xpos, ypos)))
+ if ( EntropyCodec::DecodeSymbol( ChooseSignContext(out_data, xpos, ypos)) )
out_pixel = -out_pixel;
}
}
template<typename EntropyCodec>
-inline int GenericBandCodec<EntropyCodec>::ChooseFollowContext(const int bin_number) const
+inline int GenericBandCodec<EntropyCodec>::ChooseFollowContext( const int bin_number ) const
{
//condition on neighbouring values and parent values
- if(!m_parent_notzero)
+ if (!m_parent_notzero)
{
- switch(bin_number)
+ switch ( bin_number )
{
- case 1 :
- if(m_nhood_nonzero == false)
- return Z_FBIN1z_CTX;
-
- return Z_FBIN1nz_CTX;
-
- case 2 :
- return Z_FBIN2_CTX;
- case 3 :
- return Z_FBIN3_CTX;
- case 4 :
- return Z_FBIN4_CTX;
- case 5 :
- return Z_FBIN5_CTX;
- default :
- return Z_FBIN6plus_CTX;
+ case 1 :
+ if(m_nhood_nonzero == false)
+ return Z_FBIN1z_CTX;
+
+ return Z_FBIN1nz_CTX;
+
+ case 2 :
+ return Z_FBIN2_CTX;
+ case 3 :
+ return Z_FBIN3_CTX;
+ case 4 :
+ return Z_FBIN4_CTX;
+ case 5 :
+ return Z_FBIN5_CTX;
+ default :
+ return Z_FBIN6plus_CTX;
}
}
else
{
- switch(bin_number)
+ switch ( bin_number )
{
- case 1 :
- if(m_nhood_nonzero == false)
- return NZ_FBIN1z_CTX;
-
- return NZ_FBIN1nz_CTX;
-
- case 2 :
- return NZ_FBIN2_CTX;
- case 3 :
- return NZ_FBIN3_CTX;
- case 4 :
- return NZ_FBIN4_CTX;
- case 5 :
- return NZ_FBIN5_CTX;
- default :
- return NZ_FBIN6plus_CTX;
+ case 1 :
+ if(m_nhood_nonzero == false)
+ return NZ_FBIN1z_CTX;
+
+ return NZ_FBIN1nz_CTX;
+
+ case 2 :
+ return NZ_FBIN2_CTX;
+ case 3 :
+ return NZ_FBIN3_CTX;
+ case 4 :
+ return NZ_FBIN4_CTX;
+ case 5 :
+ return NZ_FBIN5_CTX;
+ default :
+ return NZ_FBIN6plus_CTX;
}
}
@@ -416,33 +416,33 @@ inline int GenericBandCodec<EntropyCodec>::ChooseInfoContext() const
}
template<typename EntropyCodec>
-inline int GenericBandCodec<EntropyCodec>::ChooseSignContext(const CoeffArray& data , const int xpos , const int ypos) const
+inline int GenericBandCodec<EntropyCodec>::ChooseSignContext( const CoeffArray& data , const int xpos , const int ypos ) const
{
- if(m_node.Yp() == 0 && m_node.Xp() != 0)
+ if ( m_node.Yp()==0 && m_node.Xp()!=0 )
{
//we're in a vertically oriented subband
- if(ypos == 0)
+ if (ypos == 0)
return SIGN0_CTX;
else
{
- if(data[ypos-1][xpos] > 0)
+ if (data[ypos-1][xpos]>0)
return SIGN_POS_CTX;
- else if(data[ypos-1][xpos] < 0)
+ else if (data[ypos-1][xpos]<0)
return SIGN_NEG_CTX;
else
return SIGN0_CTX;
}
}
- else if(m_node.Xp() == 0 && m_node.Yp() != 0)
+ else if ( m_node.Xp()==0 && m_node.Yp()!=0 )
{
//we're in a horizontally oriented subband
- if(xpos == 0)
+ if (xpos == 0)
return SIGN0_CTX;
else
{
- if(data[ypos][xpos-1] > 0)
+ if ( data[ypos][xpos-1] > 0 )
return SIGN_POS_CTX;
- else if(data[ypos][xpos-1] < 0)
+ else if ( data[ypos][xpos-1] < 0 )
return SIGN_NEG_CTX;
else
return SIGN0_CTX;
@@ -457,40 +457,40 @@ int GenericBandCodec<EntropyCodec>::DecodeQuantIndexOffset()
{
int offset = 1;
- while(!EntropyCodec::DecodeSymbol(Q_OFFSET_FOLLOW_CTX))
+ while ( !EntropyCodec::DecodeSymbol( Q_OFFSET_FOLLOW_CTX ) )
{
offset <<= 1;
- offset |= EntropyCodec::DecodeSymbol(Q_OFFSET_INFO_CTX);
+ offset |= EntropyCodec::DecodeSymbol( Q_OFFSET_INFO_CTX );
}
--offset;
- if(offset)
+ if ( offset )
{
- if(EntropyCodec::DecodeSymbol(Q_OFFSET_SIGN_CTX))
+ if ( EntropyCodec::DecodeSymbol( Q_OFFSET_SIGN_CTX ) )
offset = -offset;
}
return offset;
}
template<typename EntropyCodec>
-void GenericBandCodec<EntropyCodec>::SetToVal(const CodeBlock& code_block , CoeffArray& pic_data , const CoeffType val)
+void GenericBandCodec<EntropyCodec>::SetToVal( const CodeBlock& code_block , CoeffArray& pic_data , const CoeffType val)
{
- for(int j = code_block.Ystart() ; j < code_block.Yend() ; j++)
+ for (int j=code_block.Ystart() ; j<code_block.Yend() ; j++)
{
- for(int i = code_block.Xstart() ; i < code_block.Xend() ; i++)
- {
+ for (int i=code_block.Xstart() ; i<code_block.Xend() ; i++)
+ {
pic_data[j][i] = val;
- }// i
+ }// i
}// j
}
template<typename EntropyCodec>
-void GenericBandCodec<EntropyCodec>::ClearBlock(const CodeBlock& code_block , CoeffArray& coeff_data)
+void GenericBandCodec<EntropyCodec>::ClearBlock( const CodeBlock& code_block , CoeffArray& coeff_data)
{
- for(int j = code_block.Ystart() ; j < code_block.Yend() ; j++)
+ for (int j=code_block.Ystart() ; j<code_block.Yend() ; j++)
{
CoeffType *pic = &coeff_data[j][code_block.Xstart()];
- memset(pic, 0, (code_block.Xend() - code_block.Xstart())*sizeof(CoeffType));
+ memset (pic, 0, (code_block.Xend()-code_block.Xstart())*sizeof(CoeffType));
}// j
}
@@ -501,11 +501,11 @@ void GenericIntraDCBandCodec<EntropyCodec>::DecodeCoeffBlock(const CodeBlock& co
{
GenericBandCodec<EntropyCodec>::DecodeCoeffBlock(code_block, out_data);
/* do prediction for this block */
- for(int ypos = code_block.Ystart() ; ypos < code_block.Yend() ; ++ypos)
+ for ( int ypos=code_block.Ystart() ; ypos<code_block.Yend() ; ++ypos)
{
- for(int xpos = code_block.Xstart() ; xpos < code_block.Xend() ; ++xpos)
+ for ( int xpos=code_block.Xstart() ; xpos<code_block.Xend() ; ++xpos)
{
- out_data[ypos][xpos] += GetPrediction(out_data , xpos , ypos);
+ out_data[ypos][xpos] += GetPrediction( out_data , xpos , ypos );
}
}
}
@@ -515,41 +515,41 @@ void GenericIntraDCBandCodec<EntropyCodec>::DecodeCoeffBlock(const CodeBlock& co
* predict the values in the next codeblock */
template<typename EntropyCodec>
-void GenericIntraDCBandCodec<EntropyCodec>::ClearBlock(const CodeBlock& code_block , CoeffArray& coeff_data)
+void GenericIntraDCBandCodec<EntropyCodec>::ClearBlock( const CodeBlock& code_block , CoeffArray& coeff_data)
{
- for(int ypos = code_block.Ystart() ; ypos < code_block.Yend() ; ++ypos)
+ for (int ypos=code_block.Ystart() ; ypos<code_block.Yend() ; ++ypos)
{
- for(int xpos = code_block.Xstart() ; xpos < code_block.Xend() ; ++xpos)
+ for (int xpos=code_block.Xstart() ; xpos<code_block.Xend() ; ++xpos)
{
/* NB, it is correct to overwrite the old value */
- coeff_data[ypos][xpos] = GetPrediction(coeff_data , xpos , ypos);
+ coeff_data[ypos][xpos] = GetPrediction( coeff_data , xpos , ypos );
} // i
} // j
}
template<typename EntropyCodec>
-CoeffType GenericIntraDCBandCodec<EntropyCodec>::GetPrediction(const CoeffArray& data , const int xpos , const int ypos) const
+CoeffType GenericIntraDCBandCodec<EntropyCodec>::GetPrediction( const CoeffArray& data , const int xpos , const int ypos ) const
{
/* NB, 4.5.3 integer division
* numbers are rounded down towards -ve infinity, differing from
* C's convention that rounds towards 0
*/
- if(ypos != 0)
+ if (ypos!=0)
{
- if(xpos != 0)
+ if (xpos!=0)
{
- int sum = data[ypos][xpos-1] + data[ypos-1][xpos-1] + data[ypos-1][xpos] + 3 / 2;
- if(sum < 0)
- return (sum - 2) / 3;
+ int sum = data[ypos][xpos-1] + data[ypos-1][xpos-1] + data[ypos-1][xpos] + 3/2;
+ if (sum<0)
+ return (sum-2)/3;
else
- return sum / 3;
+ return sum/3;
}
else
return data[ypos - 1][0];
}
else
{
- if(xpos != 0)
+ if(xpos!=0)
return data[0][xpos - 1];
else
return 0;
diff --git a/src/filters/parser/DiracSplitter/libdirac/libdirac_common/band_vlc.cpp b/src/filters/parser/DiracSplitter/libdirac/libdirac_common/band_vlc.cpp
index 9ea1aa081..b6ddf5337 100644
--- a/src/filters/parser/DiracSplitter/libdirac/libdirac_common/band_vlc.cpp
+++ b/src/filters/parser/DiracSplitter/libdirac/libdirac_common/band_vlc.cpp
@@ -47,8 +47,8 @@
using namespace dirac;
ArithCodecToVLCAdapter::ArithCodecToVLCAdapter(
- SubbandByteIO* subband_byteio,
- size_t /*number_of_contexts*/):
+ SubbandByteIO* subband_byteio,
+ size_t /*number_of_contexts*/):
m_byteio(subband_byteio)
{}
@@ -82,19 +82,19 @@ GenericIntraDCBandCodec<ArithCodecToVLCAdapter>::GenericIntraDCBandCodec(
const SubbandList & band_list);
IntraDCBandVLC::IntraDCBandVLC(SubbandByteIO* subband_byteio,
- const SubbandList& band_list):
+ const SubbandList& band_list):
GenericIntraDCBandCodec<ArithCodecToVLCAdapter>(subband_byteio, 0, band_list)
{}
-void IntraDCBandVLC::CodeCoeff(CoeffArray& in_data ,
- const int xpos ,
- const int ypos)
+void IntraDCBandVLC::CodeCoeff( CoeffArray& in_data ,
+ const int xpos ,
+ const int ypos )
{
CoeffType val, prediction;
- prediction = GetPrediction(in_data, xpos, ypos);
+ prediction = GetPrediction( in_data, xpos, ypos );
val = in_data[ypos][xpos] - prediction;
- CodeVal(in_data , xpos , ypos , val);
+ CodeVal( in_data , xpos , ypos , val );
in_data[ypos][xpos] += prediction;
}
diff --git a/src/filters/parser/DiracSplitter/libdirac/libdirac_common/band_vlc.h b/src/filters/parser/DiracSplitter/libdirac/libdirac_common/band_vlc.h
index 4cde9849c..597802d26 100644
--- a/src/filters/parser/DiracSplitter/libdirac/libdirac_common/band_vlc.h
+++ b/src/filters/parser/DiracSplitter/libdirac/libdirac_common/band_vlc.h
@@ -48,92 +48,92 @@
namespace dirac
{
-class SubbandByteIO;
-class ByteIO;
+ class SubbandByteIO;
+ class ByteIO;
-/*! Abstract VLC entropy codec base class */
-class ArithCodecToVLCAdapter
-{
-public:
- /*! Constructor */
- ArithCodecToVLCAdapter(SubbandByteIO* subband_byteio, size_t number_of_contexts);
+ /*! Abstract VLC entropy codec base class */
+ class ArithCodecToVLCAdapter
+ {
+ public:
+ /*! Constructor */
+ ArithCodecToVLCAdapter(SubbandByteIO* subband_byteio, size_t number_of_contexts);
- /*! Virtual Destructor */
- virtual ~ArithCodecToVLCAdapter() {}
+ /*! Virtual Destructor */
+ virtual ~ArithCodecToVLCAdapter(){}
- /* Compresses the input and returns the number of bits written */
- int Compress(CoeffArray &in_data);
+ /* Compresses the input and returns the number of bits written */
+ int Compress (CoeffArray &in_data);
- /* Decompresses the bitstream */
- void Decompress(CoeffArray& out_data, int num_bytes);
+ /* Decompresses the bitstream */
+ void Decompress (CoeffArray& out_data, int num_bytes);
- /* Encodes a symbol and writes to the output */
- void EncodeSymbol(bool val, int /*context_num*/)
- {
- m_byteio->WriteBit(val);
- }
+ /* Encodes a symbol and writes to the output */
+ void EncodeSymbol(bool val, int /*context_num*/)
+ {
+ m_byteio->WriteBit(val);
+ }
- /* Decodes a symbol */
- bool DecodeSymbol(int /*context_num*/)
- {
- return m_byteio->ReadBoolB();
- }
-
- /*! Purely virtual function that does the actual encoding. Derived classes must define it */
- virtual void DoWorkCode(CoeffArray &in_data) = 0;
-
- /*! Purely virtual function that does the actual decoding. Derived classes must define it */
- virtual void DoWorkDecode(CoeffArray &out_data) = 0;
-
-protected:
- /*! Input/output stream for Dirac-format bytes */
- ByteIO *m_byteio;
-
-private:
- //! Private, bodyless copy constructor: class should not be copied
- ArithCodecToVLCAdapter(const ArithCodecToVLCAdapter& cpy);
- //! Private, bodyless copy operator=: class should not be assigned
- ArithCodecToVLCAdapter& operator=(const ArithCodecToVLCAdapter& rhs);
-};
-
-
-//! A general class for coding and decoding wavelet subband data using variable length coding.
-/*!
- A general class for coding and decoding wavelet subband data using variable length coding,
- */
-typedef GenericBandCodec<ArithCodecToVLCAdapter> BandVLC;
-
-//////////////////////////////////////////////////////////////////////////////////
-//Finally,special class incorporating prediction for the DC band of intra frames//
-//////////////////////////////////////////////////////////////////////////////////
-
-//! A class specially for coding the DC subband of Intra frames
-/*!
- A class specially for coding the DC subband of Intra frames, using intra-band prediction
- of coefficients.
-*/
-class IntraDCBandVLC: public GenericIntraDCBandCodec<ArithCodecToVLCAdapter>
-{
-public:
- //! Constructor
+ /* Decodes a symbol */
+ bool DecodeSymbol(int /*context_num*/)
+ {
+ return m_byteio->ReadBoolB();
+ }
+
+ /*! Purely virtual function that does the actual encoding. Derived classes must define it */
+ virtual void DoWorkCode(CoeffArray &in_data) = 0;
+
+ /*! Purely virtual function that does the actual decoding. Derived classes must define it */
+ virtual void DoWorkDecode(CoeffArray &out_data) = 0;
+
+ protected:
+ /*! Input/output stream for Dirac-format bytes */
+ ByteIO *m_byteio;
+
+ private:
+ //! Private, bodyless copy constructor: class should not be copied
+ ArithCodecToVLCAdapter(const ArithCodecToVLCAdapter& cpy);
+ //! Private, bodyless copy operator=: class should not be assigned
+ ArithCodecToVLCAdapter& operator=(const ArithCodecToVLCAdapter& rhs);
+ };
+
+
+ //! A general class for coding and decoding wavelet subband data using variable length coding.
/*!
- Creates a IntraDCBandVLC object to encode subband data, based on parameters
- \param subband_byteio input/output for the encoded bits
- \param band_list the set of all the subbands
+ A general class for coding and decoding wavelet subband data using variable length coding,
*/
- IntraDCBandVLC(SubbandByteIO* subband_byteio,
- const SubbandList& band_list);
-private:
- //! Encode a single coefficient using error-feedback DC quantization
- void CodeCoeff(CoeffArray& in_data, const int xpos, const int ypos);
-
-private:
- //! Private, bodyless copy constructor: class should not be copied
- IntraDCBandVLC(const IntraDCBandVLC& cpy);
-
- //! Private, bodyless copy operator=: class should not be assigned
- IntraDCBandVLC& operator=(const IntraDCBandVLC& rhs);
-};
+ typedef GenericBandCodec<ArithCodecToVLCAdapter> BandVLC;
+
+ //////////////////////////////////////////////////////////////////////////////////
+ //Finally,special class incorporating prediction for the DC band of intra frames//
+ //////////////////////////////////////////////////////////////////////////////////
+
+ //! A class specially for coding the DC subband of Intra frames
+ /*!
+ A class specially for coding the DC subband of Intra frames, using intra-band prediction
+ of coefficients.
+ */
+ class IntraDCBandVLC: public GenericIntraDCBandCodec<ArithCodecToVLCAdapter>
+ {
+ public:
+ //! Constructor
+ /*!
+ Creates a IntraDCBandVLC object to encode subband data, based on parameters
+ \param subband_byteio input/output for the encoded bits
+ \param band_list the set of all the subbands
+ */
+ IntraDCBandVLC(SubbandByteIO* subband_byteio,
+ const SubbandList& band_list);
+ private:
+ //! Encode a single coefficient using error-feedback DC quantization
+ void CodeCoeff(CoeffArray& in_data, const int xpos, const int ypos);
+
+ private:
+ //! Private, bodyless copy constructor: class should not be copied
+ IntraDCBandVLC (const IntraDCBandVLC& cpy);
+
+ //! Private, bodyless copy operator=: class should not be assigned
+ IntraDCBandVLC& operator=(const IntraDCBandVLC& rhs);
+ };
}// end namespace dirac
diff --git a/src/filters/parser/DiracSplitter/libdirac/libdirac_common/bit_manager.cpp b/src/filters/parser/DiracSplitter/libdirac/libdirac_common/bit_manager.cpp
index 7a3470ad8..aed3d145c 100644
--- a/src/filters/parser/DiracSplitter/libdirac/libdirac_common/bit_manager.cpp
+++ b/src/filters/parser/DiracSplitter/libdirac/libdirac_common/bit_manager.cpp
@@ -49,7 +49,7 @@ using std::vector;
////////////////
//Constructor
-BasicOutputManager::BasicOutputManager(std::ostream* out_data):
+BasicOutputManager::BasicOutputManager(std::ostream* out_data ):
m_num_out_bytes(0),
m_op_ptr(out_data)
{
@@ -59,9 +59,9 @@ BasicOutputManager::BasicOutputManager(std::ostream* out_data):
void BasicOutputManager::InitOutputStream()
{
// Set byte pointer to start of buffer
- m_current_byte = 0;
- // Set output mask to MSB of byte
- m_output_mask = 0x80;
+ m_current_byte = 0;
+ // Set output mask to MSB of byte
+ m_output_mask = 0x80;
// Reset the output buffer
m_buffer.clear();
}
@@ -69,82 +69,82 @@ void BasicOutputManager::InitOutputStream()
void BasicOutputManager::OutputSkipInterpretStartPrefixByte()
{
size_t buf_size = m_buffer.size();
- if(buf_size >= 4 &&
- m_buffer[buf_size-1] == (char)START_CODE_PREFIX_BYTE3 &&
- m_buffer[buf_size-2] == (char)START_CODE_PREFIX_BYTE2 &&
- m_buffer[buf_size-3] == (char)START_CODE_PREFIX_BYTE1 &&
- m_buffer[buf_size-4] == (char)START_CODE_PREFIX_BYTE0)
+ if (buf_size >=4 &&
+ m_buffer[buf_size-1] == (char)START_CODE_PREFIX_BYTE3 &&
+ m_buffer[buf_size-2] == (char)START_CODE_PREFIX_BYTE2 &&
+ m_buffer[buf_size-3] == (char)START_CODE_PREFIX_BYTE1 &&
+ m_buffer[buf_size-4] == (char)START_CODE_PREFIX_BYTE0)
{
m_buffer.push_back((char)NOT_START_CODE);
std::cerr << "Wrote ignore code " << std::endl;
}
}
-void BasicOutputManager::OutputBit(const bool& bit)
+void BasicOutputManager::OutputBit(const bool& bit )
{
- m_current_byte |= (bit ? (m_output_mask) : 0);
+ m_current_byte |= (bit ? (m_output_mask):0);
// Shift mask to next bit in the output byte
- m_output_mask >>= 1;
+ m_output_mask >>= 1;
- if(m_output_mask == 0)
- {
+ if ( m_output_mask == 0 )
+ {
// If a whole byte has been written, write out
m_output_mask = 0x80;
m_buffer.push_back(m_current_byte);
OutputSkipInterpretStartPrefixByte();
m_current_byte = 0;
- }
+ }
}
void BasicOutputManager::OutputBit(const bool& bit, int& count)
{
OutputBit(bit);
- count++;
+ count++;
}
void BasicOutputManager::OutputByte(const char& byte)
{
FlushOutput();
- m_buffer.push_back(byte);
+ m_buffer.push_back( byte );
OutputSkipInterpretStartPrefixByte();
}
-void BasicOutputManager::OutputBytes(char* str_array)
+void BasicOutputManager::OutputBytes( char* str_array )
{
FlushOutput();
- while(*str_array != 0)
+ while ( *str_array != 0 )
{
- m_buffer.push_back(*str_array);
+ m_buffer.push_back( *str_array );
str_array++;
}
}
-void BasicOutputManager::OutputBytes(char* str_array, int num)
+void BasicOutputManager::OutputBytes(char* str_array,int num)
{
FlushOutput();
- for(int i = 0 ; i < num ; ++i)
- m_buffer.push_back(str_array[i]);
+ for ( int i=0 ; i<num ; ++i )
+ m_buffer.push_back( str_array[i] );
}
void BasicOutputManager::WriteToFile()
{
FlushOutput();
- for(vector<char>::iterator it = m_buffer.begin() ; it != m_buffer.end() ; ++it)
+ for ( vector<char>::iterator it=m_buffer.begin() ; it!=m_buffer.end() ; ++it )
{
- m_op_ptr->write(&(*it) , 1);
+ m_op_ptr->write( &( *it ) , 1 );
}
m_num_out_bytes = m_buffer.size();
- InitOutputStream();
+ InitOutputStream();
}
void BasicOutputManager::FlushOutput()
{
// Flush the current byte to output buffer and reset
- if(m_output_mask != 0x80)
+ if ( m_output_mask != 0x80 )
{
- m_buffer.push_back(m_current_byte);
+ m_buffer.push_back( m_current_byte );
m_current_byte = 0;
m_output_mask = 0x80;
}
@@ -152,27 +152,27 @@ void BasicOutputManager::FlushOutput()
size_t BasicOutputManager::Size() const
{
- if(m_output_mask == 0x80)
+ if ( m_output_mask==0x80 )
return m_buffer.size();
else
- return m_buffer.size() + 1;
+ return m_buffer.size()+1;
}
// Unit output - a subband or the MV data, for example //
-UnitOutputManager::UnitOutputManager(std::ostream* out_data):
+UnitOutputManager::UnitOutputManager(std::ostream* out_data ):
m_header(out_data),
m_data(out_data),
m_unit_bytes(0),
m_unit_data_bytes(0),
m_unit_head_bytes(0)
-{}
+ {}
void UnitOutputManager::WriteToFile()
{
m_header.WriteToFile();
m_data.WriteToFile();
-
+
// after writing to file, get the number of unit bytes written
m_unit_data_bytes = m_data.GetNumBytes();
m_unit_head_bytes = m_header.GetNumBytes();
@@ -182,16 +182,16 @@ void UnitOutputManager::WriteToFile()
size_t UnitOutputManager::Size() const
{
- return m_data.Size() + m_header.Size();
+ return m_data.Size()+m_header.Size();
}
-FrameOutputManager::FrameOutputManager(std::ostream* out_data , int num_bands) :
- m_data_array(3 , num_bands),
- m_comp_bytes(3),
- m_comp_hdr_bytes(3),
- m_out_stream(out_data)
+FrameOutputManager::FrameOutputManager( std::ostream* out_data , int num_bands ) :
+ m_data_array( 3 , num_bands ),
+ m_comp_bytes( 3 ),
+ m_comp_hdr_bytes( 3 ),
+ m_out_stream( out_data )
{
- Init(num_bands);
+ Init( num_bands );
}
FrameOutputManager::~FrameOutputManager()
@@ -218,13 +218,13 @@ void FrameOutputManager::WriteToFile()
m_header_bytes += m_mv_hdr_bytes;
// Write out the component data
- for(int c = 0 ; c < 3 ; ++c)
+ for ( int c=0 ; c<3 ; ++c)
{
m_comp_hdr_bytes[c] = 0;
m_comp_bytes[c] = 0;
- for(int b = m_data_array.LastX() ; b >= 0 ; --b)
+ for ( int b=m_data_array.LastX() ; b>=0 ; --b)
{
m_data_array[c][b]->WriteToFile();
// after writing to file, get the number of bytes written
@@ -234,52 +234,52 @@ void FrameOutputManager::WriteToFile()
}// c
- for(int c = 0 ; c < m_data_array.LengthY() ; ++c)
+ for ( int c=0 ; c<m_data_array.LengthY() ; ++c)
{
m_total_bytes += m_comp_bytes[c];
m_header_bytes += m_comp_hdr_bytes[c];
}
}
-UnitOutputManager& FrameOutputManager::BandOutput(const int csort , const int band_num)
+UnitOutputManager& FrameOutputManager::BandOutput( const int csort , const int band_num)
{
- return *(m_data_array[csort][band_num-1]);
+ return *( m_data_array[csort][band_num-1] );
}
-const UnitOutputManager& FrameOutputManager::BandOutput(const int csort , const int band_num) const
+const UnitOutputManager& FrameOutputManager::BandOutput( const int csort , const int band_num) const
{
- return *(m_data_array[csort][band_num-1]);
+ return *( m_data_array[csort][band_num-1] );
}
// Picture stuff
-void FrameOutputManager::Init(int num_bands)
+void FrameOutputManager::Init( int num_bands )
{
// Initialise output for the picture header
- m_frame_header = new BasicOutputManager(m_out_stream);
+ m_frame_header = new BasicOutputManager( m_out_stream );
// Initialise output for the MV data
- m_mv_data = new UnitOutputManager(m_out_stream);
+ m_mv_data = new UnitOutputManager( m_out_stream );
// Initialise subband outputs
- for(int c = 0 ; c < 3 ; ++c)
- for(int b = 0 ; b < num_bands ; ++b)
- m_data_array[c][b] = new UnitOutputManager(m_out_stream);
+ for ( int c=0 ; c<3 ; ++c)
+ for ( int b=0 ; b<num_bands ; ++b)
+ m_data_array[c][b] = new UnitOutputManager( m_out_stream );
}
void FrameOutputManager::Reset()
{
const int num_bands = m_data_array.LengthX();
DeleteAll();
- Init(num_bands);
-}
+ Init( num_bands );
+}
void FrameOutputManager::DeleteAll()
{
// Delete subband outputs
- for(int c = 0 ; c < 3 ; ++c)
- for(int b = 0 ; b < m_data_array.LengthX() ; ++b)
+ for ( int c=0 ; c<3 ; ++c)
+ for ( int b=0 ; b<m_data_array.LengthX() ; ++b )
delete m_data_array[c][b];
// Delete MV data op
@@ -287,7 +287,7 @@ void FrameOutputManager::DeleteAll()
// Delete picture header op
delete m_frame_header;
-}
+}
size_t FrameOutputManager::Size() const
{
@@ -295,9 +295,9 @@ size_t FrameOutputManager::Size() const
size += m_frame_header->Size();
- for(int c = 0 ; c < 3 ; ++c)
+ for ( int c=0 ; c<3 ; ++c)
{
- for(int b = 0 ; b < m_data_array.LengthX() ; ++b)
+ for ( int b=0 ; b<m_data_array.LengthX() ; ++b )
{
size += m_data_array[c][b]->Size();
}
@@ -306,17 +306,17 @@ size_t FrameOutputManager::Size() const
size += m_mv_data->Size();
return size;
-}
+}
// Sequence stuff //
-SequenceOutputManager::SequenceOutputManager(std::ostream* out_data):
- m_frame_op_mgr(out_data),
- m_seq_header(out_data),
- m_seq_end(out_data),
- m_comp_bytes(3),
- m_comp_hdr_bytes(3),
+SequenceOutputManager::SequenceOutputManager( std::ostream* out_data ):
+ m_frame_op_mgr( out_data ),
+ m_seq_header( out_data ),
+ m_seq_end( out_data ),
+ m_comp_bytes( 3 ),
+ m_comp_hdr_bytes( 3 ),
m_mv_hdr_bytes(0),
m_mv_bytes(0),
m_total_bytes(0),
@@ -324,7 +324,7 @@ SequenceOutputManager::SequenceOutputManager(std::ostream* out_data):
m_trailer_bytes(0)
{
- for(int c = 0 ; c < 3 ; ++c)
+ for (int c=0 ; c<3 ; ++c )
{
m_comp_hdr_bytes[c] = 0;
m_comp_bytes[c] = 0;
@@ -334,12 +334,12 @@ SequenceOutputManager::SequenceOutputManager(std::ostream* out_data):
void SequenceOutputManager::WriteFrameData()
{
m_frame_op_mgr.WriteToFile();
-
+
// Keep up with count of component bytes
- for(int c = 0 ; c < m_comp_hdr_bytes.Length(); ++c)
+ for (int c=0 ; c<m_comp_hdr_bytes.Length(); ++c)
{
- m_comp_hdr_bytes[c] += m_frame_op_mgr.ComponentHeadBytes(c);
- m_comp_bytes[c] += m_frame_op_mgr.ComponentBytes(c);
+ m_comp_hdr_bytes[c] += m_frame_op_mgr.ComponentHeadBytes( c );
+ m_comp_bytes[c] += m_frame_op_mgr.ComponentBytes( c );
}// c
// Keep up with count of MV bytes
@@ -371,7 +371,7 @@ void SequenceOutputManager::WriteSeqTrailerToFile()
////////////////
//Constructor
-BitInputManager::BitInputManager(std::istream* in_data):
+BitInputManager::BitInputManager(std::istream* in_data ):
m_ip_ptr(in_data)
{
InitInputStream();
@@ -386,16 +386,16 @@ void BitInputManager::InitInputStream()
bool BitInputManager::InputBit()
{
- //assumes mode errors will be caught by iostream class
+ //assumes mode errors will be caught by iostream class
- if(m_input_bits_left == 0)
+ if (m_input_bits_left == 0)
{
- m_ip_ptr->read(&m_current_byte, 1);
+ m_ip_ptr->read(&m_current_byte,1);
m_input_bits_left = 8;
- if(m_shift == START_CODE_PREFIX && (unsigned char)m_current_byte == NOT_START_CODE)
+ if (m_shift == START_CODE_PREFIX && (unsigned char)m_current_byte == NOT_START_CODE)
{
std::cerr << "Ignoring byte " << std::endl;
- m_ip_ptr->read(&m_current_byte, 1);
+ m_ip_ptr->read(&m_current_byte,1);
m_shift = 0xffffffff;
}
m_shift = (m_shift << 8) | m_current_byte;
@@ -403,7 +403,7 @@ bool BitInputManager::InputBit()
m_input_bits_left--;
- return bool((m_current_byte >> m_input_bits_left) & 1);
+ return bool( ( m_current_byte >> m_input_bits_left ) & 1 );
}
@@ -415,7 +415,7 @@ bool BitInputManager::InputBit(int& count)
bool BitInputManager::InputBit(int& count, const int max_count)
{
- if(count < max_count)
+ if ( count<max_count )
{
count++;
return InputBit();
@@ -426,29 +426,29 @@ bool BitInputManager::InputBit(int& count, const int max_count)
char BitInputManager::InputByte()
{
- // Forget about what's in the current byte
+ // Forget about what's in the current byte
FlushInput();
char byte;
- m_ip_ptr->read(&byte, 1);
+ m_ip_ptr->read(&byte,1);
- return byte;
+ return byte;
}
void BitInputManager::InputBytes(char* cptr, int num)
{
- // Forget about what's in the current byte
+ // Forget about what's in the current byte
FlushInput();
- m_ip_ptr->read(cptr, num);
+ m_ip_ptr->read(cptr,num);
}
void BitInputManager::FlushInput()
{
- m_input_bits_left = 0;
+ m_input_bits_left = 0;
}
-bool BitInputManager::End() const
+bool BitInputManager::End() const
{
- return m_ip_ptr->eof();
+ return m_ip_ptr->eof();
}
diff --git a/src/filters/parser/DiracSplitter/libdirac/libdirac_common/bit_manager.h b/src/filters/parser/DiracSplitter/libdirac/libdirac_common/bit_manager.h
index 194fca1e0..6f75e8004 100644
--- a/src/filters/parser/DiracSplitter/libdirac/libdirac_common/bit_manager.h
+++ b/src/filters/parser/DiracSplitter/libdirac/libdirac_common/bit_manager.h
@@ -48,543 +48,477 @@
namespace dirac
{
-//! Prefix for all start codes
-const unsigned int START_CODE_PREFIX = 0x42424344; //BBCD
-const unsigned int START_CODE_PREFIX_BYTE0 =
- (START_CODE_PREFIX >> 24) & 0xFF;
-const unsigned int START_CODE_PREFIX_BYTE1 =
- (START_CODE_PREFIX >> 16) & 0xFF;
-const unsigned int START_CODE_PREFIX_BYTE2 =
- (START_CODE_PREFIX >> 8) & 0xFF;
-const unsigned int START_CODE_PREFIX_BYTE3 =
- START_CODE_PREFIX & 0xFF;
-
-//! Random Access Point (RAP) Intra Picture start Code
-const unsigned char RAP_START_CODE = 0xD7;
-//! Non-RAP Intra Picture start code
-const unsigned char IFRAME_START_CODE = 0xD6;
-//! L1 Picture start code
-const unsigned char L1FRAME_START_CODE = 0xD4;
-//! L2 Picture start code
-const unsigned char L2FRAME_START_CODE = 0xD5;
-//! Sequence end code
-const unsigned char SEQ_END_CODE = 0xD0;
-//! Not a start code but part of data
-const unsigned char NOT_START_CODE = 0xFF;
-//! Bitstream version
-const unsigned char BITSTREAM_VERSION = 0x05; //0.5
-
-
-////////////////////////////////////////////////
-//--------------Bit output stuff--------------//
-////////////////////////////////////////////////
-
-class UnitOutputManager;
-class FrameOutputManager;
-class SequenceOutputManager;
-
-//! Class for managing bit- and byte-oriented output.
-/*!
- A class for managing bit- and byte-oriented output. Wraps around
- an ostream object but stores data in memory until told told to
- write out in order to support data re-ordering - for example
- writing a header once the subsequent data has been obtained.
- Implementation to be reviewed in future. TJD 13 April 2004.
-*/
-class BasicOutputManager
-{
- // Data cannot be written to file directly, only by other o/p classes
- friend class UnitOutputManager;
- friend class FrameOutputManager;
- friend class SequenceOutputManager;
-
-public:
- //! Constructor
+ //! Prefix for all start codes
+ const unsigned int START_CODE_PREFIX = 0x42424344; //BBCD
+ const unsigned int START_CODE_PREFIX_BYTE0 =
+ (START_CODE_PREFIX >> 24) & 0xFF;
+ const unsigned int START_CODE_PREFIX_BYTE1 =
+ (START_CODE_PREFIX >> 16) & 0xFF;
+ const unsigned int START_CODE_PREFIX_BYTE2 =
+ (START_CODE_PREFIX >> 8) & 0xFF;
+ const unsigned int START_CODE_PREFIX_BYTE3 =
+ START_CODE_PREFIX & 0xFF;
+
+ //! Random Access Point (RAP) Intra Picture start Code
+ const unsigned char RAP_START_CODE = 0xD7;
+ //! Non-RAP Intra Picture start code
+ const unsigned char IFRAME_START_CODE = 0xD6;
+ //! L1 Picture start code
+ const unsigned char L1FRAME_START_CODE = 0xD4;
+ //! L2 Picture start code
+ const unsigned char L2FRAME_START_CODE = 0xD5;
+ //! Sequence end code
+ const unsigned char SEQ_END_CODE = 0xD0;
+ //! Not a start code but part of data
+ const unsigned char NOT_START_CODE = 0xFF;
+ //! Bitstream version
+ const unsigned char BITSTREAM_VERSION = 0x05; //0.5
+
+
+ ////////////////////////////////////////////////
+ //--------------Bit output stuff--------------//
+ ////////////////////////////////////////////////
+
+ class UnitOutputManager;
+ class FrameOutputManager;
+ class SequenceOutputManager;
+
+ //! Class for managing bit- and byte-oriented output.
/*!
- Constructor requires an ostream object pointer.
- \param out_data the output stream object pointer
+ A class for managing bit- and byte-oriented output. Wraps around
+ an ostream object but stores data in memory until told told to
+ write out in order to support data re-ordering - for example
+ writing a header once the subsequent data has been obtained.
+ Implementation to be reviewed in future. TJD 13 April 2004.
*/
- BasicOutputManager(std::ostream* out_data);
-
- //Copy constructor is default shallow copy
-
- //Operator= is default shallow=
-
- //! Destructor
- ~BasicOutputManager() {}
-
- //! Write a bit out.
- /*!
- Write a bit out to the internal data cache.
- */
- void OutputBit(const bool& bit);
-
- //! Write a bit out and increment count
- /*!
- Write a bit out to the internal data cache and increment the
- count of bits written.
- */
- void OutputBit(const bool& bit, int& count);
-
- //! Write a byte out.
- /*!
- Write a byte out to the internal data cache.
- */
- void OutputByte(const char& byte);
-
- //! Write a null-terminated set of bytes out.
- /*!
- Write a null-terminated set of bytes out to the internal data cache.
- */
- void OutputBytes(char* str_array);
-
- //! Write a number of bytes out.
- /*!
- Write a number of bytes out to the internal data cache.
- */
- void OutputBytes(char* str_array, int num);
-
- //! Return the number of bytes last output to file.
- /*!
- Return the number of bytes last output to file.
- */
- size_t GetNumBytes() const
+ class BasicOutputManager
{
- return m_num_out_bytes;
- }
-
- //! Current size of the internal data cache in bytes.
+ // Data cannot be written to file directly, only by other o/p classes
+ friend class UnitOutputManager;
+ friend class FrameOutputManager;
+ friend class SequenceOutputManager;
+
+ public:
+ //! Constructor
+ /*!
+ Constructor requires an ostream object pointer.
+ \param out_data the output stream object pointer
+ */
+ BasicOutputManager(std::ostream* out_data );
+
+ //Copy constructor is default shallow copy
+
+ //Operator= is default shallow=
+
+ //! Destructor
+ ~BasicOutputManager(){}
+
+ //! Write a bit out.
+ /*!
+ Write a bit out to the internal data cache.
+ */
+ void OutputBit(const bool& bit);
+
+ //! Write a bit out and increment count
+ /*!
+ Write a bit out to the internal data cache and increment the
+ count of bits written.
+ */
+ void OutputBit(const bool& bit,int& count);
+
+ //! Write a byte out.
+ /*!
+ Write a byte out to the internal data cache.
+ */
+ void OutputByte(const char& byte);
+
+ //! Write a null-terminated set of bytes out.
+ /*!
+ Write a null-terminated set of bytes out to the internal data cache.
+ */
+ void OutputBytes(char* str_array);
+
+ //! Write a number of bytes out.
+ /*!
+ Write a number of bytes out to the internal data cache.
+ */
+ void OutputBytes(char* str_array,int num);
+
+ //! Return the number of bytes last output to file.
+ /*!
+ Return the number of bytes last output to file.
+ */
+ size_t GetNumBytes() const {return m_num_out_bytes;}
+
+ //! Current size of the internal data cache in bytes.
+ /*!
+ Current size of the internal data cache in bytes.
+ */
+ size_t Size() const;
+
+ private:
+ // Number of output bytes written
+ size_t m_num_out_bytes;
+ std::ostream* m_op_ptr;
+ // Buffer used to store output prior to saving to file
+ std::vector<char> m_buffer;
+ // Char used for temporary storage of op data bits
+ char m_current_byte;
+ // Used to set individual bit within the current header byte
+ int m_output_mask;
+
+ //functions
+
+ //! Write all data to file.
+ /*!
+ Dump the internal data cache to the internal ostream object.
+ */
+ void WriteToFile();
+
+ //Initialise the output stream.
+ void InitOutputStream();
+
+ //Clean out any remaining output bits to the buffer
+ void FlushOutput();
+
+ //! Write an ignore code
+ /*!
+ Write a skip interpret start prefix byte out to the internal data
+ cache.
+ */
+ void OutputSkipInterpretStartPrefixByte();
+ };
+
+ //! A class for handling data output, including headers.
/*!
- Current size of the internal data cache in bytes.
+ A class for handling data output, including headers and reordering.
*/
- size_t Size() const;
-
-private:
- // Number of output bytes written
- size_t m_num_out_bytes;
- std::ostream* m_op_ptr;
- // Buffer used to store output prior to saving to file
- std::vector<char> m_buffer;
- // Char used for temporary storage of op data bits
- char m_current_byte;
- // Used to set individual bit within the current header byte
- int m_output_mask;
-
- //functions
-
- //! Write all data to file.
- /*!
- Dump the internal data cache to the internal ostream object.
- */
- void WriteToFile();
-
- //Initialise the output stream.
- void InitOutputStream();
-
- //Clean out any remaining output bits to the buffer
- void FlushOutput();
-
- //! Write an ignore code
- /*!
- Write a skip interpret start prefix byte out to the internal data
- cache.
- */
- void OutputSkipInterpretStartPrefixByte();
-};
-
-//! A class for handling data output, including headers.
-/*!
-A class for handling data output, including headers and reordering.
-*/
-class UnitOutputManager
-{
- // Only the FrameOutputManager can make this class write data to file
- friend class FrameOutputManager;
-
-public:
- //! Constructor.
- /*!
- Constructor wraps around a pointer to an ostream object, and
- initialises two BasicOutputManager objects for header and data
- */
- UnitOutputManager(std::ostream* out_data);
-
- //Copy constructor is default shallow copy
-
- //Operator= is default shallow=
-
- //! Destructor
- ~UnitOutputManager() {}
-
- //! Handles the header bits.
- /*!
- A BasicOutputManager object for handling the header bits.
- */
- BasicOutputManager& Header()
+ class UnitOutputManager
{
- return m_header;
- }
-
- //! Handles the data bits.
- /*!
- A BasicOutputManager object for handling the data bits.
- */
- BasicOutputManager& Data()
+ // Only the FrameOutputManager can make this class write data to file
+ friend class FrameOutputManager;
+
+ public:
+ //! Constructor.
+ /*!
+ Constructor wraps around a pointer to an ostream object, and
+ initialises two BasicOutputManager objects for header and data
+ */
+ UnitOutputManager(std::ostream* out_data );
+
+ //Copy constructor is default shallow copy
+
+ //Operator= is default shallow=
+
+ //! Destructor
+ ~UnitOutputManager(){}
+
+ //! Handles the header bits.
+ /*!
+ A BasicOutputManager object for handling the header bits.
+ */
+ BasicOutputManager& Header(){return m_header;}
+
+ //! Handles the data bits.
+ /*!
+ A BasicOutputManager object for handling the data bits.
+ */
+ BasicOutputManager& Data(){return m_data;}
+
+ //! Returns the total number of bytes written in the last unit coded.
+ /*!
+ Returns the total number of bytes written in the last unit coded - header + data.
+ */
+ const size_t GetUnitBytes() const {return m_unit_bytes;}
+
+ //! Returns the total number of header bytes written in the last unit coded.
+ const size_t GetUnitHeaderBytes() const {return m_unit_head_bytes;}
+
+ //! Current size of the internal data cache in bytes.
+ /*!
+ Current size of the internal data cache in bytes.
+ */
+ size_t Size() const;
+
+ private:
+ // basic output managers for the header and data
+ BasicOutputManager m_header,m_data;
+
+ // total number of bytes written in the last unit coded
+ size_t m_unit_bytes;
+
+ // number of data bytes for the last unit coded
+ size_t m_unit_data_bytes;
+
+ // number of data bytes for the last unit coded
+ size_t m_unit_head_bytes;
+
+ // functions
+
+ //! Writes the bit caches to file.
+ /*!
+ Writes the header bits to the ostream, followed by the data bits.
+ */
+ void WriteToFile();
+ };
+
+ class FrameOutputManager
{
- return m_data;
- }
+ public:
- //! Returns the total number of bytes written in the last unit coded.
- /*!
- Returns the total number of bytes written in the last unit coded - header + data.
- */
- const size_t GetUnitBytes() const
- {
- return m_unit_bytes;
- }
+ // Only the SequenceOutputManager can make this class write data to file
+ friend class SequenceOutputManager;
- //! Returns the total number of header bytes written in the last unit coded.
- const size_t GetUnitHeaderBytes() const
- {
- return m_unit_head_bytes;
- }
+ //! Constructor
+ /*
+ Constructs a class which manages output for an entire picture.
+ \param out_data pointer to the output stream
+ \param num_bands the number of subbands per component
+ */
+ FrameOutputManager( std::ostream* out_data , const int num_bands=13 );
- //! Current size of the internal data cache in bytes.
- /*!
- Current size of the internal data cache in bytes.
- */
- size_t Size() const;
-
-private:
- // basic output managers for the header and data
- BasicOutputManager m_header, m_data;
-
- // total number of bytes written in the last unit coded
- size_t m_unit_bytes;
-
- // number of data bytes for the last unit coded
- size_t m_unit_data_bytes;
-
- // number of data bytes for the last unit coded
- size_t m_unit_head_bytes;
-
- // functions
-
- //! Writes the bit caches to file.
- /*!
- Writes the header bits to the ostream, followed by the data bits.
- */
- void WriteToFile();
-};
-
-class FrameOutputManager
-{
-public:
-
- // Only the SequenceOutputManager can make this class write data to file
- friend class SequenceOutputManager;
+ //! Destructor
+ ~FrameOutputManager();
- //! Constructor
- /*
- Constructs a class which manages output for an entire picture.
- \param out_data pointer to the output stream
- \param num_bands the number of subbands per component
- */
- FrameOutputManager(std::ostream* out_data , const int num_bands = 13);
-
- //! Destructor
- ~FrameOutputManager();
-
- //! Set the number of bands there will be in a component
- void SetNumBands(const int num_bands);
-
- //! Get an output manager for a subband
- /*!
- Get an output manager for a subband.
- \param csort the component (Y, U or V)
- \param band_num the number of the subband
- */
- UnitOutputManager& BandOutput(const int csort , const int band_num);
+ //! Set the number of bands there will be in a component
+ void SetNumBands( const int num_bands );
- //! Get an output manager for a subband
- /*!
- Get an output manager for a subband.
- \param csort the component (Y, U or V)
- \param band_num the number of the subband
- */
- const UnitOutputManager& BandOutput(const int csort , const int band_num) const;
+ //! Get an output manager for a subband
+ /*!
+ Get an output manager for a subband.
+ \param csort the component (Y, U or V)
+ \param band_num the number of the subband
+ */
+ UnitOutputManager& BandOutput( const int csort , const int band_num );
- //! Get an output manager for MV data
- /*!
- Get an output manager for MV data
- */
- UnitOutputManager& MVOutput()
- {
- return *m_mv_data;
- }
+ //! Get an output manager for a subband
+ /*!
+ Get an output manager for a subband.
+ \param csort the component (Y, U or V)
+ \param band_num the number of the subband
+ */
+ const UnitOutputManager& BandOutput( const int csort , const int band_num ) const;
- //! Get an output manager for MV data
- /*!
- Get an output manager for MV data
- */
- const UnitOutputManager& MVOutput() const
- {
- return *m_mv_data;
- }
+ //! Get an output manager for MV data
+ /*!
+ Get an output manager for MV data
+ */
+ UnitOutputManager& MVOutput(){ return *m_mv_data; }
- //! Get an output manager for the picture header
- BasicOutputManager& HeaderOutput()
- {
- return *m_frame_header;
- }
+ //! Get an output manager for MV data
+ /*!
+ Get an output manager for MV data
+ */
+ const UnitOutputManager& MVOutput() const { return *m_mv_data; }
- //! Return the number of bytes used for each component
- const size_t ComponentBytes(const int comp_num) const
- {
- return m_comp_bytes[comp_num];
- }
+ //! Get an output manager for the picture header
+ BasicOutputManager& HeaderOutput(){ return *m_frame_header; }
- //! Return the number of header bytes used for each component
- const size_t ComponentHeadBytes(const int comp_num) const
- {
- return m_comp_hdr_bytes[comp_num];
- }
+ //! Return the number of bytes used for each component
+ const size_t ComponentBytes( const int comp_num ) const { return m_comp_bytes[comp_num];}
- //! Return the number of motion vector bytes used
- const size_t MVBytes() const
- {
- return m_mv_bytes;
- }
+ //! Return the number of header bytes used for each component
+ const size_t ComponentHeadBytes( const int comp_num ) const { return m_comp_hdr_bytes[comp_num];}
- //! Return the number of motion vector header bytes used
- const size_t MVHeadBytes() const
- {
- return m_mv_hdr_bytes;
- }
+ //! Return the number of motion vector bytes used
+ const size_t MVBytes() const { return m_mv_bytes;}
- //! Return the number of bytes used for the whole picture
- const size_t FrameBytes() const
- {
- return m_total_bytes;
- }
+ //! Return the number of motion vector header bytes used
+ const size_t MVHeadBytes() const { return m_mv_hdr_bytes;}
- //! Return the number of header bytes used throughout the picture
- const size_t FrameHeadBytes() const
- {
- return m_header_bytes;
- }
+ //! Return the number of bytes used for the whole picture
+ const size_t FrameBytes() const { return m_total_bytes;}
- //! Current size of the internal data cache in bytes.
- /*!
- Current size of the internal data cache in bytes.
- */
- size_t Size() const;
+ //! Return the number of header bytes used throughout the picture
+ const size_t FrameHeadBytes() const { return m_header_bytes;}
-private:
+ //! Current size of the internal data cache in bytes.
+ /*!
+ Current size of the internal data cache in bytes.
+ */
+ size_t Size() const;
- // Array of subband outputs, 1 for each component and subband
- TwoDArray< UnitOutputManager* > m_data_array;
+ private:
- // Motion vector output
- UnitOutputManager* m_mv_data;
+ // Array of subband outputs, 1 for each component and subband
+ TwoDArray< UnitOutputManager* > m_data_array;
- // Picture header output
- BasicOutputManager* m_frame_header;
+ // Motion vector output
+ UnitOutputManager* m_mv_data;
- // The total number of picture bytes
- size_t m_total_bytes;
+ // Picture header output
+ BasicOutputManager* m_frame_header;
- // The total number of header bytes
- size_t m_header_bytes;
+ // The total number of picture bytes
+ size_t m_total_bytes;
- // The total number of MV header bytes
- size_t m_mv_hdr_bytes;
+ // The total number of header bytes
+ size_t m_header_bytes;
- // The total number of MV bytes
- size_t m_mv_bytes;
+ // The total number of MV header bytes
+ size_t m_mv_hdr_bytes;
- // The total number of bytes in each component
- OneDArray< size_t > m_comp_bytes;
+ // The total number of MV bytes
+ size_t m_mv_bytes;
- // The total number of header bytes in each component
- OneDArray< size_t > m_comp_hdr_bytes;
+ // The total number of bytes in each component
+ OneDArray< size_t > m_comp_bytes;
- // A copy of a pointer to the output stream
- std::ostream* m_out_stream;
+ // The total number of header bytes in each component
+ OneDArray< size_t > m_comp_hdr_bytes;
- // Functions
+ // A copy of a pointer to the output stream
+ std::ostream* m_out_stream;
- //! Initialise the band data
- void Init(const int num_bands);
+ // Functions
- //! Reset all the data
- void Reset();
+ //! Initialise the band data
+ void Init( const int num_bands );
- //! Delete all the data
- void DeleteAll();
+ //! Reset all the data
+ void Reset();
- //! Write all the picture data to file
- void WriteToFile();
-};
+ //! Delete all the data
+ void DeleteAll();
-class SequenceOutputManager
-{
-public:
- //! Constructor
- SequenceOutputManager(std::ostream* out_data);
+ //! Write all the picture data to file
+ void WriteToFile();
+ };
- //! Return a reference to the output for a single picture
- FrameOutputManager& FrameOutput()
+ class SequenceOutputManager
{
- return m_frame_op_mgr;
- }
+ public:
+ //! Constructor
+ SequenceOutputManager( std::ostream* out_data );
- //! Return a reference to the output for the sequence header
- BasicOutputManager& HeaderOutput()
- {
- return m_seq_header;
- }
+ //! Return a reference to the output for a single picture
+ FrameOutputManager& FrameOutput(){ return m_frame_op_mgr; }
- //! Return a reference to the output for the sequence trailer
- BasicOutputManager& TrailerOutput()
- {
- return m_seq_end;
- }
+ //! Return a reference to the output for the sequence header
+ BasicOutputManager& HeaderOutput(){ return m_seq_header; }
- //! Reset the picture data without outputting
- void ResetFrame()
- {
- m_frame_op_mgr.Reset();
- }
+ //! Return a reference to the output for the sequence trailer
+ BasicOutputManager& TrailerOutput(){ return m_seq_end; }
- //! Write the sequence header
- void WriteSeqHeaderToFile();
+ //! Reset the picture data without outputting
+ void ResetFrame(){ m_frame_op_mgr.Reset(); }
- //! Write all the picture data to file
- void WriteFrameData();
+ //! Write the sequence header
+ void WriteSeqHeaderToFile();
- //! Write the sequence trailer
- void WriteSeqTrailerToFile();
+ //! Write all the picture data to file
+ void WriteFrameData();
- //! Return the total number of bytes used for the sequence
- const size_t SequenceBytes()
- {
- return m_total_bytes;
- }
+ //! Write the sequence trailer
+ void WriteSeqTrailerToFile();
- //! Return the total number of header bytes used throughout the sequence
- const size_t SequenceHeadBytes()
- {
- return m_header_bytes;
- }
+ //! Return the total number of bytes used for the sequence
+ const size_t SequenceBytes() { return m_total_bytes; }
- //! Return the total number bytes used for MVs
- const size_t MVBytes()
- {
- return m_mv_bytes;
- }
+ //! Return the total number of header bytes used throughout the sequence
+ const size_t SequenceHeadBytes() { return m_header_bytes; }
- //! Return the total number bytes used for a component
- const size_t ComponentBytes(const int comp_num)
- {
- return m_comp_bytes[comp_num];
- }
+ //! Return the total number bytes used for MVs
+ const size_t MVBytes() { return m_mv_bytes; }
- //! Reset the picture data
- void ResetFrameData();
+ //! Return the total number bytes used for a component
+ const size_t ComponentBytes( const int comp_num ) { return m_comp_bytes[comp_num]; }
+ //! Reset the picture data
+ void ResetFrameData();
-private:
- // The picture output manager
- FrameOutputManager m_frame_op_mgr;
+ private:
- // Output manager for the sequence header
- BasicOutputManager m_seq_header;
+ // The picture output manager
+ FrameOutputManager m_frame_op_mgr;
- // Output manager for the sequence end
- BasicOutputManager m_seq_end;
+ // Output manager for the sequence header
+ BasicOutputManager m_seq_header;
- // The total number of bytes in each component
- OneDArray< size_t > m_comp_bytes;
+ // Output manager for the sequence end
+ BasicOutputManager m_seq_end;
- // The total number of header bits in each component
- OneDArray< size_t > m_comp_hdr_bytes;
+ // The total number of bytes in each component
+ OneDArray< size_t > m_comp_bytes;
- // The number of MV header bytes
- size_t m_mv_hdr_bytes;
+ // The total number of header bits in each component
+ OneDArray< size_t > m_comp_hdr_bytes;
- // The total number of MV bytes
- size_t m_mv_bytes;
+ // The number of MV header bytes
+ size_t m_mv_hdr_bytes;
- // The total number of bytes written so far
- size_t m_total_bytes;
+ // The total number of MV bytes
+ size_t m_mv_bytes;
- // The total number of header bytes written so far
- size_t m_header_bytes;
+ // The total number of bytes written so far
+ size_t m_total_bytes;
- // The total number of trailer bytes written so far
- size_t m_trailer_bytes;
-};
+ // The total number of header bytes written so far
+ size_t m_header_bytes;
-///////////////////////////////////////////////
-//--------------Bit input stuff--------------//
-///////////////////////////////////////////////
+ // The total number of trailer bytes written so far
+ size_t m_trailer_bytes;
+ };
-//! A class for managing bit-wise and byte-wise input.
-class BitInputManager
-{
+ ///////////////////////////////////////////////
+ //--------------Bit input stuff--------------//
+ ///////////////////////////////////////////////
-public:
- //! Constructor.
- /*!
- Constructor. Wraps around an istream object.
- */
- BitInputManager(std::istream* in_data);
+ //! A class for managing bit-wise and byte-wise input.
+ class BitInputManager
+ {
+
+ public:
+ //! Constructor.
+ /*!
+ Constructor. Wraps around an istream object.
+ */
+ BitInputManager(std::istream* in_data );
- //Copy constructor is default shallow copy
+ //Copy constructor is default shallow copy
- //Operator= is default shallow=
+ //Operator= is default shallow=
- //! Destructor
- ~BitInputManager() {}
+ //! Destructor
+ ~BitInputManager(){}
- //input functions
- //! Obtain the next bit.
- bool InputBit();
+ //input functions
+ //! Obtain the next bit.
+ bool InputBit();
- //! Obtain the next bit, incrementing count.
- bool InputBit(int& count);
+ //! Obtain the next bit, incrementing count.
+ bool InputBit(int& count);
- //! Obtain the next bit, incrementing count, if count<max_count; else return 0 (false).
- bool InputBit(int& count, const int max_count);
+ //! Obtain the next bit, incrementing count, if count<max_count; else return 0 (false).
+ bool InputBit(int& count, const int max_count);
- //! Obtain the next byte.
- char InputByte();
+ //! Obtain the next byte.
+ char InputByte();
- //! Obtain a number of bytes.
- void InputBytes(char* cptr, int num);
+ //! Obtain a number of bytes.
+ void InputBytes(char* cptr,int num);
- //! Move onto the next byte. Needed if a data unit is not an exact number of bytes.
- void FlushInput();
+ //! Move onto the next byte. Needed if a data unit is not an exact number of bytes.
+ void FlushInput();
- //! Returns true if we're at the end of the input, false otherwise
- bool End() const ;
+ //! Returns true if we're at the end of the input, false otherwise
+ bool End() const ;
-private:
+ private:
- std::istream* m_ip_ptr;
- // Char used for temporary storage of ip bits
- char m_current_byte;
- // The number of bits left withint the current input byte being decoded
- int m_input_bits_left;
+ std::istream* m_ip_ptr;
+ // Char used for temporary storage of ip bits
+ char m_current_byte;
+ // The number of bits left withint the current input byte being decoded
+ int m_input_bits_left;
- //used to check if start code is detected
- unsigned int m_shift;
- //functions
- // Initialise the input stream
- void InitInputStream();
-};
+ //used to check if start code is detected
+ unsigned int m_shift;
+ //functions
+ // Initialise the input stream
+ void InitInputStream();
+ };
} // namespace dirac
#endif
diff --git a/src/filters/parser/DiracSplitter/libdirac/libdirac_common/cmd_line.cpp b/src/filters/parser/DiracSplitter/libdirac/libdirac_common/cmd_line.cpp
index 003f6d06b..82abf66b8 100644
--- a/src/filters/parser/DiracSplitter/libdirac/libdirac_common/cmd_line.cpp
+++ b/src/filters/parser/DiracSplitter/libdirac/libdirac_common/cmd_line.cpp
@@ -42,32 +42,32 @@ using namespace dirac;
using namespace std;
CommandLine::CommandLine(int argc, char * argv[], const set<string> & bool_opts)
- : m_options(),
- m_inputs(),
- m_bool_opts(bool_opts)
+ : m_options(),
+ m_inputs(),
+ m_bool_opts(bool_opts)
{
bool option_active = false;
vector<option>::iterator active_option;
- for(int i = 1; i < argc; ++i)
+ for (int i = 1; i < argc; ++i)
{
// is it an option?
- if((strlen(argv[i]) > 1) && (argv[i][0] == '-'))
+ if ((strlen(argv[i]) > 1) && (argv[i][0] == '-'))
{
// store new key
string opt_key = string(&argv[i][1]);
m_options.push_back(option(opt_key));
-
+
// active option is now last in list
active_option = m_options.end();
--active_option;
-
+
// check option list to see if we're looking for an argument
option_active = (m_bool_opts.find(opt_key) == m_bool_opts.end());
}
else
{
- if(option_active)
+ if (option_active)
active_option->m_value = string(argv[i]);
else
m_inputs.push_back(string(argv[i]));
diff --git a/src/filters/parser/DiracSplitter/libdirac/libdirac_common/cmd_line.h b/src/filters/parser/DiracSplitter/libdirac/libdirac_common/cmd_line.h
index 2c5fdf49b..0977c8b27 100644
--- a/src/filters/parser/DiracSplitter/libdirac/libdirac_common/cmd_line.h
+++ b/src/filters/parser/DiracSplitter/libdirac/libdirac_common/cmd_line.h
@@ -45,47 +45,47 @@
namespace dirac
{
-// structure for defining the nature of options
-// a very simple command-line parser
-class CommandLine
-{
-public:
- struct option
- {
- std::string m_name;
- std::string m_value;
-
- option(const std::string & a_name)
- : m_name(a_name), m_value("")
- {
- // nada
- }
- };
+ // structure for defining the nature of options
+ // a very simple command-line parser
+ class CommandLine
+ {
+ public:
+ struct option
+ {
+ std::string m_name;
+ std::string m_value;
- //! Constructor
- CommandLine(int argc, char * argv[], const std::set<std::string> & bool_opts);
+ option(const std::string & a_name)
+ : m_name(a_name), m_value("")
+ {
+ // nada
+ }
+ };
- const std::vector<option> & GetOptions() const
- {
- return m_options;
- }
+ //! Constructor
+ CommandLine(int argc, char * argv[], const std::set<std::string> & bool_opts);
- const std::vector<std::string> & GetInputs() const
- {
- return m_inputs;
- }
+ const std::vector<option> & GetOptions() const
+ {
+ return m_options;
+ }
- // convenience property
- size_t Count() const
- {
- return m_options.size();
- }
+ const std::vector<std::string> & GetInputs() const
+ {
+ return m_inputs;
+ }
+
+ // convenience property
+ size_t Count() const
+ {
+ return m_options.size();
+ }
-private:
- std::vector<option> m_options;
- std::vector<std::string> m_inputs;
- const std::set<std::string> & m_bool_opts;
-};
+ private:
+ std::vector<option> m_options;
+ std::vector<std::string> m_inputs;
+ const std::set<std::string> & m_bool_opts;
+ };
} // namespace dirac
diff --git a/src/filters/parser/DiracSplitter/libdirac/libdirac_common/common.cpp b/src/filters/parser/DiracSplitter/libdirac/libdirac_common/common.cpp
index cda129fe0..35adcc5ef 100644
--- a/src/filters/parser/DiracSplitter/libdirac/libdirac_common/common.cpp
+++ b/src/filters/parser/DiracSplitter/libdirac/libdirac_common/common.cpp
@@ -57,9 +57,9 @@ using namespace dirac;
//EntropyCorrector functions
EntropyCorrector::EntropyCorrector(int depth):
- m_Yfctrs(3 , 3 * depth + 1),
- m_Ufctrs(3 , 3 * depth + 1),
- m_Vfctrs(3 , 3 * depth + 1)
+ m_Yfctrs( 3 , 3*depth+1 ),
+ m_Ufctrs( 3 , 3*depth+1 ),
+ m_Vfctrs( 3 , 3*depth+1 )
{
Init();
}
@@ -68,9 +68,9 @@ float EntropyCorrector::Factor(const int bandnum , const PictureParams& pp ,
const CompSort c) const
{
int idx = pp.PicSort().IsIntra() ? 0 : (pp.IsBPicture() ? 1 : 2);
- if(c == U_COMP)
+ if (c == U_COMP)
return m_Ufctrs[idx][bandnum-1];
- else if(c == V_COMP)
+ else if (c == V_COMP)
return m_Vfctrs[idx][bandnum-1];
else
return m_Yfctrs[idx][bandnum-1];
@@ -80,9 +80,9 @@ void EntropyCorrector::Init()
{
//do I-pictures
- for(int i = 0 ; i < m_Yfctrs.LengthX() ; ++i)
+ for (int i=0 ; i<m_Yfctrs.LengthX() ; ++i )
{
- if(i == m_Yfctrs.LastX())
+ if ( i == m_Yfctrs.LastX() )
{
// Set factor for Intra pictures
m_Yfctrs[0][i] = 1.0f;
@@ -97,7 +97,7 @@ void EntropyCorrector::Init()
m_Ufctrs[2][i] = 0.85f;
m_Vfctrs[2][i] = 0.85f;
}
- else if(i >= m_Yfctrs.LastX() - 3)
+ else if ( i >= m_Yfctrs.LastX()-3 )
{
// Set factor for Intra pictures
m_Yfctrs[0][i] = 0.85f;
@@ -132,20 +132,19 @@ void EntropyCorrector::Init()
}
void EntropyCorrector::Update(int bandnum , const PictureParams& pp ,
- CompSort c , int est_bits , int actual_bits)
-{
+ CompSort c ,int est_bits , int actual_bits){
//updates the factors - note that the estimated bits are assumed to already include the correction factor
float multiplier;
- if(actual_bits != 0 && est_bits != 0)
- multiplier = float(actual_bits) / float(est_bits);
+ if (actual_bits != 0 && est_bits != 0)
+ multiplier = float(actual_bits)/float(est_bits);
else
- multiplier = 1.0;
+ multiplier=1.0;
int idx = pp.PicSort().IsIntra() ? 0 : (pp.IsBPicture() ? 1 : 2);
- if(c == U_COMP)
+ if (c == U_COMP)
m_Ufctrs[idx][bandnum-1] *= multiplier;
- else if(c == V_COMP)
+ else if (c == V_COMP)
m_Vfctrs[idx][bandnum-1] *= multiplier;
else
m_Yfctrs[idx][bandnum-1] *= multiplier;
@@ -158,16 +157,16 @@ OLBParams::OLBParams(const int xblen, int const yblen, int const xbsep, int cons
m_yblen(yblen),
m_xbsep(xbsep),
m_ybsep(ybsep),
- m_xoffset((xblen - xbsep) / 2),
- m_yoffset((yblen - ybsep) / 2)
+ m_xoffset( (xblen-xbsep)/2 ),
+ m_yoffset( (yblen-ybsep)/2 )
{}
bool OLBParams::operator ==(const OLBParams bparams) const
{
- if(bparams.Xblen() != m_xblen ||
- bparams.Yblen() != m_yblen ||
- bparams.Xbsep() != m_xbsep ||
- bparams.Ybsep() != m_ybsep)
+ if (bparams.Xblen() != m_xblen ||
+ bparams.Yblen() != m_yblen ||
+ bparams.Xbsep() != m_xbsep ||
+ bparams.Ybsep() != m_ybsep)
return false;
@@ -214,21 +213,20 @@ void PicturePredParams::SetBlockSizes(const OLBParams& olbparams , const ChromaF
OLBParams tmp_olbparams = olbparams;
// Factors for scaling chroma blocks
- int xcfactor, ycfactor;
+ int xcfactor,ycfactor;
- if(cformat == format420)
+ if (cformat == format420)
{
xcfactor = 2;
ycfactor = 2;
}
- else if(cformat == format422)
+ else if (cformat == format422)
{
xcfactor = 2;
ycfactor = 1;
}
else
- {
- // assume 444
+ {// assume 444
xcfactor = 1;
ycfactor = 1;
}
@@ -237,97 +235,97 @@ void PicturePredParams::SetBlockSizes(const OLBParams& olbparams , const ChromaF
m_lbparams[2] = tmp_olbparams;
// Check separations are all divisible by 4
- int remainder = m_lbparams[2].Xbsep() % 4;
- if(remainder != 0 || m_lbparams[2].Xbsep() == 0)
+ int remainder= m_lbparams[2].Xbsep()%4;
+ if ( remainder!=0 || m_lbparams[2].Xbsep()==0 )
{
- m_lbparams[2].SetXbsep(m_lbparams[2].Xbsep() + (4 - remainder));
- m_lbparams[2].SetXblen(m_lbparams[2].Xbsep() + 4);
+ m_lbparams[2].SetXbsep( m_lbparams[2].Xbsep()+(4-remainder));
+ m_lbparams[2].SetXblen( m_lbparams[2].Xbsep()+4 );
}
- remainder = m_lbparams[2].Ybsep() % 4;
- if(remainder != 0 || m_lbparams[2].Ybsep() == 0)
+ remainder= m_lbparams[2].Ybsep()%4;
+ if ( remainder!=0 || m_lbparams[2].Ybsep()==0 )
{
- m_lbparams[2].SetYbsep(m_lbparams[2].Ybsep() + (4 - remainder));
- m_lbparams[2].SetYblen(m_lbparams[2].Ybsep() + 4);
+ m_lbparams[2].SetYbsep( m_lbparams[2].Ybsep()+(4-remainder));
+ m_lbparams[2].SetYblen( m_lbparams[2].Ybsep()+4 );
}
// Now check lengths are divisible by 4
- remainder = m_lbparams[2].Xblen() % 4;
- if(remainder != 0)
+ remainder= m_lbparams[2].Xblen()%4;
+ if ( remainder!=0 )
{
- m_lbparams[2].SetXblen(m_lbparams[2].Xbsep() + 4);
+ m_lbparams[2].SetXblen( m_lbparams[2].Xbsep()+4);
}
- remainder = m_lbparams[2].Yblen() % 4;
- if(remainder != 0)
+ remainder= m_lbparams[2].Yblen()%4;
+ if ( remainder!=0 )
{
- m_lbparams[2].SetYblen(m_lbparams[2].Ybsep() + 4);
+ m_lbparams[2].SetYblen( m_lbparams[2].Ybsep()+4);
}
// Check there's non-negative overlap,
// XBLEN >= XBSEP, YBLEN >= YBSEP
- if(m_lbparams[2].Xbsep() > m_lbparams[2].Xblen())
+ if (m_lbparams[2].Xbsep()>m_lbparams[2].Xblen())
{
- m_lbparams[2].SetXblen(m_lbparams[2].Xbsep() + 4);
+ m_lbparams[2].SetXblen( m_lbparams[2].Xbsep()+4);
}
- if(m_lbparams[2].Ybsep() > m_lbparams[2].Yblen())
+ if (m_lbparams[2].Ybsep()>m_lbparams[2].Yblen())
{
- m_lbparams[2].SetYblen(m_lbparams[2].Ybsep() + 4);
+ m_lbparams[2].SetYblen( m_lbparams[2].Ybsep()+4);
}
// Check the lengths aren't too big (100% is max roll-off)
// XBLEN <= 2*XBSEP, YBLEN <= 2*YBSEP
- if(2 * m_lbparams[2].Xbsep() < m_lbparams[2].Xblen())
+ if (2*m_lbparams[2].Xbsep()<m_lbparams[2].Xblen())
{
- m_lbparams[2].SetXblen(m_lbparams[2].Xbsep() + 4);
+ m_lbparams[2].SetXblen( m_lbparams[2].Xbsep()+4);
}
- if(2 * m_lbparams[2].Ybsep() < m_lbparams[2].Yblen())
+ if (2*m_lbparams[2].Ybsep()<m_lbparams[2].Yblen())
{
- m_lbparams[2].SetYblen(m_lbparams[2].Ybsep() + 4);
+ m_lbparams[2].SetYblen( m_lbparams[2].Ybsep()+4);
}
// Set the chroma values
- m_cbparams[2].SetXbsep(m_lbparams[2].Xbsep() / xcfactor);
- m_cbparams[2].SetXblen(m_lbparams[2].Xblen() / xcfactor);
- m_cbparams[2].SetYbsep(m_lbparams[2].Ybsep() / ycfactor);
- m_cbparams[2].SetYblen(m_lbparams[2].Yblen() / ycfactor);
+ m_cbparams[2].SetXbsep( m_lbparams[2].Xbsep()/xcfactor );
+ m_cbparams[2].SetXblen( m_lbparams[2].Xblen()/xcfactor );
+ m_cbparams[2].SetYbsep( m_lbparams[2].Ybsep()/ycfactor );
+ m_cbparams[2].SetYblen( m_lbparams[2].Yblen()/ycfactor );
//Now work out the overlaps for splitting levels 1 and 0
- m_lbparams[1].SetXbsep(m_lbparams[2].Xbsep() * 2);
- m_lbparams[1].SetXblen(m_lbparams[2].Xblen() + m_lbparams[2].Xbsep());
- m_lbparams[1].SetYbsep(m_lbparams[2].Ybsep() * 2);
- m_lbparams[1].SetYblen(m_lbparams[2].Yblen() + m_lbparams[2].Xbsep());
-
- m_lbparams[0].SetXbsep(m_lbparams[1].Xbsep() * 2);
- m_lbparams[0].SetXblen(m_lbparams[1].Xblen() + m_lbparams[1].Xbsep());
- m_lbparams[0].SetYbsep(m_lbparams[1].Ybsep() * 2);
- m_lbparams[0].SetYblen(m_lbparams[1].Yblen() + m_lbparams[1].Xbsep());
-
- m_cbparams[1].SetXbsep(m_cbparams[2].Xbsep() * 2);
- m_cbparams[1].SetXblen(m_cbparams[2].Xblen() + m_cbparams[2].Xbsep());
- m_cbparams[1].SetYbsep(m_cbparams[2].Ybsep() * 2);
- m_cbparams[1].SetYblen(m_cbparams[2].Yblen() + m_cbparams[2].Xbsep());
-
- m_cbparams[0].SetXbsep(m_cbparams[1].Xbsep() * 2);
- m_cbparams[0].SetXblen(m_cbparams[1].Xblen() + m_cbparams[1].Xbsep());
- m_cbparams[0].SetYbsep(m_cbparams[1].Ybsep() * 2);
- m_cbparams[0].SetYblen(m_cbparams[1].Yblen() + m_cbparams[1].Xbsep());
-
- if(m_lbparams[2].Xbsep() != olbparams.Xbsep() ||
- m_lbparams[2].Ybsep() != olbparams.Ybsep() ||
- m_lbparams[2].Xblen() != olbparams.Xblen() ||
- m_lbparams[2].Yblen() != olbparams.Yblen())
+ m_lbparams[1].SetXbsep( m_lbparams[2].Xbsep()*2 );
+ m_lbparams[1].SetXblen( m_lbparams[2].Xblen() + m_lbparams[2].Xbsep() );
+ m_lbparams[1].SetYbsep( m_lbparams[2].Ybsep()*2 );
+ m_lbparams[1].SetYblen( m_lbparams[2].Yblen() + m_lbparams[2].Xbsep() );
+
+ m_lbparams[0].SetXbsep( m_lbparams[1].Xbsep()*2 );
+ m_lbparams[0].SetXblen( m_lbparams[1].Xblen() + m_lbparams[1].Xbsep() );
+ m_lbparams[0].SetYbsep( m_lbparams[1].Ybsep()*2 );
+ m_lbparams[0].SetYblen( m_lbparams[1].Yblen() + m_lbparams[1].Xbsep() );
+
+ m_cbparams[1].SetXbsep( m_cbparams[2].Xbsep()*2 );
+ m_cbparams[1].SetXblen( m_cbparams[2].Xblen() + m_cbparams[2].Xbsep() );
+ m_cbparams[1].SetYbsep( m_cbparams[2].Ybsep()*2 );
+ m_cbparams[1].SetYblen( m_cbparams[2].Yblen() + m_cbparams[2].Xbsep() );
+
+ m_cbparams[0].SetXbsep( m_cbparams[1].Xbsep()*2 );
+ m_cbparams[0].SetXblen( m_cbparams[1].Xblen() + m_cbparams[1].Xbsep() );
+ m_cbparams[0].SetYbsep( m_cbparams[1].Ybsep()*2 );
+ m_cbparams[0].SetYblen( m_cbparams[1].Yblen() + m_cbparams[1].Xbsep() );
+
+ if ( m_lbparams[2].Xbsep()!=olbparams.Xbsep() ||
+ m_lbparams[2].Ybsep()!=olbparams.Ybsep() ||
+ m_lbparams[2].Xblen()!=olbparams.Xblen() ||
+ m_lbparams[2].Yblen()!=olbparams.Yblen() )
{
- std::cout << std::endl << "WARNING: block parameters are inconsistent with ";
- std::cout << "specification requirements, which are:";
- std::cout << std::endl << "\t 1. Lengths and separations must be positive multiples of 4";
- std::cout << std::endl << "\t 2. Length can't be more than twice separations";
- std::cout << std::endl << "\t 3. Lengths must be greater than or equal to separations";
- std::cout << std::endl << std::endl << "Instead, using:";
- std::cout << " xblen=" << m_lbparams[2].Xblen();
- std::cout << " yblen=" << m_lbparams[2].Yblen();
- std::cout << " xbsep=" << m_lbparams[2].Xbsep();
- std::cout << " ybsep=" << m_lbparams[2].Ybsep() << std::endl;
+ std::cout<<std::endl<<"WARNING: block parameters are inconsistent with ";
+ std::cout<<"specification requirements, which are:";
+ std::cout<<std::endl<<"\t 1. Lengths and separations must be positive multiples of 4";
+ std::cout<<std::endl<<"\t 2. Length can't be more than twice separations";
+ std::cout<<std::endl<<"\t 3. Lengths must be greater than or equal to separations";
+ std::cout<<std::endl<<std::endl<<"Instead, using:";
+ std::cout<<" xblen="<<m_lbparams[2].Xblen();
+ std::cout<<" yblen="<<m_lbparams[2].Yblen();
+ std::cout<<" xbsep="<<m_lbparams[2].Xbsep();
+ std::cout<<" ybsep="<<m_lbparams[2].Ybsep() << std::endl;
}
}
@@ -335,21 +333,21 @@ void PicturePredParams::SetBlockSizes(const OLBParams& olbparams , const ChromaF
// Codec params functions
CodecParams::CodecParams(const VideoFormat &vd, PictureType ftype, unsigned int num_refs, bool set_defaults):
- m_video_format(vd)
+ m_video_format(vd)
{
- if(set_defaults)
+ if (set_defaults)
SetDefaultCodecParameters(*this, ftype, num_refs);
}
-WltFilter CodecParams::TransformFilter(unsigned int wf_idx)
+WltFilter CodecParams::TransformFilter (unsigned int wf_idx)
{
- if(wf_idx >= filterNK)
+ if (wf_idx >= filterNK)
DIRAC_THROW_EXCEPTION(
ERR_UNSUPPORTED_STREAM_DATA,
"Wavelet filter idx out of range [0-7]",
SEVERITY_PICTURE_ERROR);
- if(wf_idx == FIDELITY)
+ if (wf_idx==FIDELITY)
{
std::ostringstream errstr;
errstr << "Wavelet Filter " << wf_idx << " currently not supported";
@@ -366,18 +364,18 @@ void CodecParams::SetTransformFilter(unsigned int wf_idx)
SetTransformFilter(TransformFilter(wf_idx));
}
-void CodecParams::SetTransformDepth(unsigned int wd)
+void CodecParams::SetTransformDepth (unsigned int wd)
{
m_wlt_depth = wd;
// Resize the code block size array.
- m_cb.Resize(wd + 1);
+ m_cb.Resize(wd+1);
}
-void CodecParams::SetCodeBlocks(unsigned int level,
- unsigned int hblocks,
- unsigned int vblocks)
+void CodecParams::SetCodeBlocks (unsigned int level,
+ unsigned int hblocks,
+ unsigned int vblocks)
{
- if(level > m_wlt_depth)
+ if (level > m_wlt_depth)
{
std::ostringstream errstr;
errstr << "level " << level << " out of range [0-" << m_wlt_depth << "]";
@@ -391,9 +389,9 @@ void CodecParams::SetCodeBlocks(unsigned int level,
m_cb[level].SetVerticalCodeBlocks(vblocks);
}
-const CodeBlocks &CodecParams::GetCodeBlocks(unsigned int level) const
+const CodeBlocks &CodecParams::GetCodeBlocks (unsigned int level) const
{
- if(level > m_wlt_depth)
+ if (level > m_wlt_depth)
{
std::ostringstream errstr;
errstr << "level " << level << " out of range [0-" << m_wlt_depth << "]";
@@ -406,9 +404,9 @@ const CodeBlocks &CodecParams::GetCodeBlocks(unsigned int level) const
return m_cb[level];
}
-void CodecParams::SetCodeBlockMode(unsigned int cb_mode)
+void CodecParams::SetCodeBlockMode (unsigned int cb_mode)
{
- if(cb_mode >= QUANT_UNDEF)
+ if (cb_mode >= QUANT_UNDEF)
{
std::ostringstream errstr;
errstr << "Code Block mode " << cb_mode << " out of supported range [0-" << QUANT_MULTIPLE << "]";
@@ -452,18 +450,18 @@ EncoderParams::EncoderParams(const VideoFormat& video_format,
void EncoderParams::CalcLambdas(const float qf)
{
- if(!m_lossless)
+ if (!m_lossless )
{
- m_I_lambda = std::pow(10.0 , (12.0 - qf) / 2.5) / 16.0;
+ m_I_lambda = std::pow( 10.0 , (12.0-qf )/2.5 )/16.0;
- m_L1_lambda = m_I_lambda * 4.0;
- m_L2_lambda = m_I_lambda * 32.0;
+ m_L1_lambda = m_I_lambda*4.0;
+ m_L2_lambda = m_I_lambda*32.0;
// Set the lambdas for motion estimation
const double me_ratio = 2.0;
// Use the same ME lambda for L1 and L2 pictures
- m_L1_me_lambda = std::sqrt(m_L1_lambda) * me_ratio;
+ m_L1_me_lambda = std::sqrt(m_L1_lambda)*me_ratio;
m_L2_me_lambda = m_L1_me_lambda;
}
else
@@ -487,36 +485,36 @@ void EncoderParams::SetInterTransformFilter(unsigned int wf_idx)
SetInterTransformFilter(TransformFilter(wf_idx));
}
-void EncoderParams::SetUsualCodeBlocks(const PictureType &/*ftype*/)
+void EncoderParams::SetUsualCodeBlocks ( const PictureType &/*ftype*/)
{
// No subband splitting if spatial partitioning if false
// Since this function is common to encoder and decoder we allow the
// setting of code blocks without checking if DefaultSpatialPartition is
// true.
- if(SpatialPartition() == false)
+ if (SpatialPartition() == false)
return;
SetCodeBlocks(0, 1, 1);
int depth = TransformDepth();
- if(depth == 0)
+ if (depth == 0)
return;
- int xl_pad = (Xl() + (1 << depth) - 1) & ~((1 << depth) - 1);
- int yl_pad = (Yl() + (1 << depth) - 1) & ~((1 << depth) - 1);
+ int xl_pad = (Xl() + (1 << depth)-1) & ~((1 << depth)-1);
+ int yl_pad = (Yl() + (1 << depth)-1) & ~((1 << depth)-1);
/* NB, could have different sizes based upon ftype == INTRA_PICTURE */
/* aim for 12x12 codeblocks in each subband, execpt the DC with 4x4 */
- for(int i = 1; i <= depth; i++)
- SetCodeBlocks(depth - i + 1, std::max(1, (xl_pad >> i) / 12), std::max(1, (yl_pad >> i) / 12));
- SetCodeBlocks(0, std::max(1, (xl_pad >> depth) / 4), std::max(1, (yl_pad >> depth) / 4));
+ for (int i = 1; i <= depth; i++)
+ SetCodeBlocks(depth-i+1, std::max(1,(xl_pad >> i) /12), std::max(1, (yl_pad >> i) /12));
+ SetCodeBlocks(0, std::max(1,(xl_pad >> depth) /4), std::max(1,(yl_pad >> depth) /4));
}
int EncoderParams::GOPLength() const
{
- if(m_num_L1 > 0)
- return (m_num_L1 + 1) * m_L1_sep;
+ if (m_num_L1>0)
+ return (m_num_L1+1)*m_L1_sep;
- return ((m_num_L1 == 0) ? 10 : 0);
+ return ((m_num_L1==0) ? 10 : 0);
}
DecoderParams::DecoderParams(const VideoFormat& video_format,
@@ -550,11 +548,11 @@ SourceParams::SourceParams(const VideoFormat& video_format,
int SourceParams::ChromaWidth() const
{
- switch(m_cformat)
+ switch (m_cformat)
{
case format420:
case format422:
- return m_xl / 2;
+ return m_xl/2;
case format444:
default:
@@ -564,10 +562,10 @@ int SourceParams::ChromaWidth() const
int SourceParams::ChromaHeight() const
{
- switch(m_cformat)
+ switch (m_cformat)
{
case format420:
- return m_yl / 2;
+ return m_yl/2;
case format422:
case format444:
@@ -577,10 +575,10 @@ int SourceParams::ChromaHeight() const
}
-void SourceParams::SetFrameRate(FrameRateType fr)
+void SourceParams::SetFrameRate (FrameRateType fr)
{
m_fr_idx = fr;
- switch(fr)
+ switch (fr)
{
case FRAMERATE_23p97_FPS:
m_framerate.m_num = 24000;
@@ -629,11 +627,11 @@ void SourceParams::SetFrameRate(FrameRateType fr)
}
}
-void SourceParams::SetPixelAspectRatio(PixelAspectRatioType pix_asr_idx)
+void SourceParams::SetPixelAspectRatio (PixelAspectRatioType pix_asr_idx)
{
m_pix_asr_idx = pix_asr_idx;
- switch(pix_asr_idx)
+ switch (pix_asr_idx)
{
case PIXEL_ASPECT_RATIO_1_1:
m_pixel_aspect_ratio.m_num = m_pixel_aspect_ratio.m_denom = 1;
@@ -665,10 +663,10 @@ void SourceParams::SetPixelAspectRatio(PixelAspectRatioType pix_asr_idx)
}
}
-void SourceParams::SetSignalRange(SignalRangeType sr)
+void SourceParams::SetSignalRange (SignalRangeType sr)
{
m_sr_idx = sr;
- switch(sr)
+ switch (sr)
{
case SIGNAL_RANGE_8BIT_FULL:
m_luma_offset = 0;
@@ -704,7 +702,7 @@ void SourceParams::SetSignalRange(SignalRangeType sr)
}
}
-void SourceParams::SetColourSpecification(unsigned int cs_idx)
+void SourceParams::SetColourSpecification (unsigned int cs_idx)
{
m_cs_idx = cs_idx;
switch(cs_idx)
@@ -738,30 +736,30 @@ void SourceParams::SetColourSpecification(unsigned int cs_idx)
}
}
-void SourceParams::SetColourPrimariesIndex(unsigned int cp)
+void SourceParams::SetColourPrimariesIndex (unsigned int cp)
{
m_cs_idx = 0;
- if(cp >= CP_UNDEF)
+ if (cp >= CP_UNDEF)
{
//TODO: flag a warning
}
m_col_primary = static_cast<ColourPrimaries>(cp);
}
-void SourceParams::SetColourMatrixIndex(unsigned int cm)
+void SourceParams::SetColourMatrixIndex (unsigned int cm)
{
m_cs_idx = 0;
- if(cm >= CM_UNDEF)
+ if (cm >= CM_UNDEF)
{
//TODO: flag a warning
}
m_col_matrix = static_cast<ColourMatrix>(cm);
}
-void SourceParams::SetTransferFunctionIndex(unsigned int tf)
+void SourceParams::SetTransferFunctionIndex (unsigned int tf)
{
m_cs_idx = 0;
- if(tf >= TF_UNDEF)
+ if (tf >= TF_UNDEF)
{
//TODO: flag a warning
}
@@ -773,21 +771,21 @@ void SourceParams::SetTransferFunctionIndex(unsigned int tf)
// Default constructor
PictureParams::PictureParams():
m_psort(PictureSort::IntraRefPictureSort()),
- m_picture_type(INTRA_PICTURE),
- m_reference_type(REFERENCE_PICTURE),
+ m_picture_type( INTRA_PICTURE ),
+ m_reference_type( REFERENCE_PICTURE ),
m_output(false),
m_using_ac(true)
{}
// Constructor
PictureParams::PictureParams(const ChromaFormat& cf,
- int xlen, int ylen,
- unsigned int luma_depth,
- unsigned int chroma_depth) :
+ int xlen, int ylen,
+ unsigned int luma_depth,
+ unsigned int chroma_depth) :
m_cformat(cf),
m_psort(PictureSort::IntraRefPictureSort()),
- m_picture_type(INTRA_PICTURE),
- m_reference_type(REFERENCE_PICTURE),
+ m_picture_type( INTRA_PICTURE ),
+ m_reference_type( REFERENCE_PICTURE ),
m_output(false),
m_xl(xlen),
m_yl(ylen),
@@ -796,17 +794,17 @@ PictureParams::PictureParams(const ChromaFormat& cf,
m_using_ac(true)
{
m_cxl = m_cyl = 0;
- if(cf == format420)
+ if (cf == format420)
{
- m_cxl = xlen >> 1;
- m_cyl = ylen >> 1;
+ m_cxl = xlen>>1;
+ m_cyl = ylen>>1;
}
- else if(cf == format422)
+ else if (cf == format422)
{
- m_cxl = xlen >> 1;
+ m_cxl = xlen>>1;
m_cyl = ylen;
}
- else if(cf == format444)
+ else if (cf == format444)
{
m_cxl = xlen;
m_cyl = ylen;
@@ -819,14 +817,14 @@ PictureParams::PictureParams(const ChromaFormat& cf, const PictureSort& ps):
m_output(false),
m_using_ac(true)
{
- SetPicSort(ps);
+ SetPicSort( ps );
}
PictureParams::PictureParams(const SourceParams& sparams):
m_cformat(sparams.CFormat()),
m_psort(PictureSort::IntraRefPictureSort()),
- m_picture_type(INTRA_PICTURE),
- m_reference_type(REFERENCE_PICTURE),
+ m_picture_type( INTRA_PICTURE ),
+ m_reference_type( REFERENCE_PICTURE ),
m_output(false),
m_xl(sparams.Xl()),
m_yl(sparams.Yl()),
@@ -834,20 +832,20 @@ PictureParams::PictureParams(const SourceParams& sparams):
m_cyl(sparams.ChromaHeight()),
m_using_ac(true)
{
- if(sparams.SourceSampling() == 1)
+ if (sparams.SourceSampling() == 1)
{
- m_yl = (m_yl >> 1);
- m_cyl = (m_cyl >> 1);
+ m_yl = (m_yl>>1);
+ m_cyl = (m_cyl>>1);
}
m_luma_depth = static_cast<unsigned int>
- (
- std::log((double)sparams.LumaExcursion()) / std::log(2.0) + 1
- );
+ (
+ std::log((double)sparams.LumaExcursion())/std::log(2.0) + 1
+ );
m_chroma_depth = static_cast<unsigned int>
- (
- std::log((double)sparams.ChromaExcursion()) / std::log(2.0) + 1
- );
+ (
+ std::log((double)sparams.ChromaExcursion())/std::log(2.0) + 1
+ );
}
@@ -856,11 +854,11 @@ void PictureParams::SetXl(int xlen)
{
m_xl = xlen;
m_cxl = 0;
- if(m_cformat == format420 || m_cformat == format422)
+ if (m_cformat == format420 || m_cformat == format422)
{
- m_cxl = m_xl >> 1;
+ m_cxl = m_xl>>1;
}
- else if(m_cformat == format444)
+ else if (m_cformat == format444)
{
m_cxl = m_xl;
}
@@ -870,11 +868,11 @@ void PictureParams::SetYl(int ylen)
{
m_yl = ylen;
m_cyl = 0;
- if(m_cformat == format420)
+ if (m_cformat == format420)
{
- m_cyl = m_yl >> 1;
+ m_cyl = m_yl>>1;
}
- else if(m_cformat == format422 || m_cformat == format444)
+ else if (m_cformat == format422 || m_cformat == format444)
{
m_cyl = m_yl;
}
@@ -882,29 +880,29 @@ void PictureParams::SetYl(int ylen)
bool PictureParams::IsBPicture() const
{
- bool is_B_picture(false);
+ bool is_B_picture( false );
- if(m_refs.size() == 2)
+ if ( m_refs.size() == 2 )
{
- if(m_refs[0] < m_fnum && m_refs[1] > m_fnum)
+ if ( m_refs[0] < m_fnum && m_refs[1] > m_fnum )
is_B_picture = true;
- if(m_refs[0] > m_fnum && m_refs[1] < m_fnum)
+ if ( m_refs[0] > m_fnum && m_refs[1] < m_fnum )
is_B_picture = true;
}
return is_B_picture;
}
-void PictureParams::SetPicSort(const PictureSort& ps)
+void PictureParams::SetPicSort( const PictureSort& ps )
{
- m_psort = ps;
- if(ps.IsIntra())
+ m_psort=ps;
+ if ( ps.IsIntra() )
m_picture_type = INTRA_PICTURE;
else
m_picture_type = INTER_PICTURE;
- if(ps.IsRef())
+ if ( ps.IsRef() )
m_reference_type = REFERENCE_PICTURE;
else
m_reference_type = NON_REFERENCE_PICTURE;
@@ -914,7 +912,7 @@ void PictureParams::SetPicSort(const PictureSort& ps)
void PictureParams::SetPictureType(const PictureType ftype)
{
m_picture_type = ftype;
- if(ftype == INTRA_PICTURE)
+ if (ftype == INTRA_PICTURE )
m_psort.SetIntra();
else
m_psort.SetInter();
@@ -923,7 +921,7 @@ void PictureParams::SetPictureType(const PictureType ftype)
void PictureParams::SetReferenceType(const ReferenceType rtype)
{
m_reference_type = rtype;
- if(rtype == REFERENCE_PICTURE)
+ if (rtype == REFERENCE_PICTURE )
m_psort.SetRef();
else
m_psort.SetNonRef();
@@ -931,14 +929,14 @@ void PictureParams::SetReferenceType(const ReferenceType rtype)
QuantiserLists::QuantiserLists()
- :
+:
// FIXME: hardcode m_max_qindex to 119. In future this will depend on level
// As per spec max qf_idx is 127. But for values of qf_idx > 120 we
// will need more than 32 bits. Hence qf_idx is limited to 119.
- m_max_qindex(119),
- m_qflist4(m_max_qindex + 1),
- m_intra_offset4(m_max_qindex + 1),
- m_inter_offset4(m_max_qindex + 1)
+ m_max_qindex( 119 ),
+ m_qflist4( m_max_qindex+1 ),
+ m_intra_offset4( m_max_qindex+1 ),
+ m_inter_offset4( m_max_qindex+1 )
{
m_qflist4[0] = 4;
m_qflist4[1] = 5;
@@ -953,32 +951,32 @@ QuantiserLists::QuantiserLists()
uint64_t base, qfactor;
#endif //_MSC_VER
- for(unsigned int q = 2; q <= m_max_qindex; ++q)
+ for (unsigned int q=2; q<=m_max_qindex; ++q)
{
- base = (1 << (q / 4));
+ base = (1<<(q/4));
- switch(q % 4)
+ switch (q%4)
{
- case 0:
- qfactor = 4 * base;
- break;
- case 1:
- qfactor = (503829 * base + 52958) / 105917;
- break;
- case 2:
- qfactor = (665857 * base + 58854) / 117708;
- break;
- case 3:
- qfactor = (440253 * base + 32722) / 65444;
- break;
- default: //Default case never used
- qfactor = 0;
+ case 0:
+ qfactor = 4*base;
+ break;
+ case 1:
+ qfactor = (503829*base+52958)/105917;
+ break;
+ case 2:
+ qfactor = (665857*base+58854)/117708;
+ break;
+ case 3:
+ qfactor = (440253*base+32722)/65444;
+ break;
+ default: //Default case never used
+ qfactor = 0;
}
- m_qflist4[q] = int(qfactor);
+ m_qflist4[q] = int( qfactor );
- m_intra_offset4[q] = (m_qflist4[q] + 1) >> 1;
- m_inter_offset4[q] = (3 * m_qflist4[q] + 4) >> 3;
+ m_intra_offset4[q] = (m_qflist4[q]+1)>>1;
+ m_inter_offset4[q] = (3*m_qflist4[q]+4)>>3;
}// q
}
@@ -1129,7 +1127,7 @@ MVPrecisionType IntToMVPrecisionType(int mv_prec)
switch(mv_prec)
{
case MV_PRECISION_PIXEL:
- return MV_PRECISION_PIXEL;
+ return MV_PRECISION_PIXEL;
case MV_PRECISION_HALF_PIXEL:
return MV_PRECISION_HALF_PIXEL;
case MV_PRECISION_QUARTER_PIXEL:
diff --git a/src/filters/parser/DiracSplitter/libdirac/libdirac_common/common.h b/src/filters/parser/DiracSplitter/libdirac/libdirac_common/common.h
index 7ee59d81b..0ec2653e3 100644
--- a/src/filters/parser/DiracSplitter/libdirac/libdirac_common/common.h
+++ b/src/filters/parser/DiracSplitter/libdirac/libdirac_common/common.h
@@ -54,2194 +54,1559 @@
#include <cmath>
namespace dirac
{
-/*! \file
- This file contains common classes used throughout the encoder and
- decoder. The main classes are the encoder and decoder parameters for
- controlling the encode and decode processes. These are passed
- throughout the codec. There are also parameter classes for sequences
- and Pictures.
-*/
+ /*! \file
+ This file contains common classes used throughout the encoder and
+ decoder. The main classes are the encoder and decoder parameters for
+ controlling the encode and decode processes. These are passed
+ throughout the codec. There are also parameter classes for sequences
+ and Pictures.
+ */
-//Some basic types used throughout the codec ...//
-//////////////////////////////////////////////////////////////
+ //Some basic types used throughout the codec ...//
+ //////////////////////////////////////////////////////////////
-//! Type of picture data (including motion compensated residuals)
-typedef short ValueType;
+ //! Type of picture data (including motion compensated residuals)
+ typedef short ValueType;
#if !defined(HAVE_MMX)
-//! Type of wavelet coefficient data (should be larger than ValueType)
-typedef int CoeffType;
+ //! Type of wavelet coefficient data (should be larger than ValueType)
+ typedef int CoeffType;
#else
-//! Type of wavelet coefficient data (should be larger than ValueType)
-typedef short CoeffType;
+ //! Type of wavelet coefficient data (should be larger than ValueType)
+ typedef short CoeffType;
#endif
-//! Type for performing calculations on ValueType and CoeffType. Should be >ValueType, >=CoeffType
-typedef int CalcValueType;
-
-//! Prediction modes for blocks
-enum PredMode { INTRA , REF1_ONLY , REF2_ONLY , REF1AND2, UNDEFINED };
-
-//! Types of picture component
-enum CompSort { Y_COMP , U_COMP , V_COMP };
-
-//! Addition or subtraction
-enum AddOrSub { ADD , SUBTRACT };
-
-//! Forward or backward
-enum Direction { FORWARD , BACKWARD };
+ //! Type for performing calculations on ValueType and CoeffType. Should be >ValueType, >=CoeffType
+ typedef int CalcValueType;
+
+ //! Prediction modes for blocks
+ enum PredMode{ INTRA , REF1_ONLY , REF2_ONLY , REF1AND2, UNDEFINED };
+
+ //! Types of picture component
+ enum CompSort{ Y_COMP , U_COMP , V_COMP };
+
+ //! Addition or subtraction
+ enum AddOrSub{ ADD , SUBTRACT };
+
+ //! Forward or backward
+ enum Direction { FORWARD , BACKWARD };
+
+ //! Contexts used for coefficient coding
+ enum CtxAliases
+ {//used for residual coding
+ SIGN0_CTX, // -sign, previous symbol is 0
+ SIGN_POS_CTX, // -sign, previous symbol is +ve
+ SIGN_NEG_CTX, // -sign, previous symbol is -ve
+
+ // Follow bit contexts
+ Z_FBIN1z_CTX, // -bin 1, parent is zero, neighbours zero
+ Z_FBIN1nz_CTX, // -bin 1, parent is zero, neighbours non-zero
+ Z_FBIN2_CTX, // -bin 2, parent is zero
+ Z_FBIN3_CTX, // -bin 3, parent is zero
+ Z_FBIN4_CTX, // -bin 4, parent is zero
+ Z_FBIN5_CTX, // -bin 5, parent is zero
+ Z_FBIN6plus_CTX, // -bins 6 plus, parent is zero
+
+ NZ_FBIN1z_CTX, // -bin 1, parent is non-zero, neighbours zero
+ NZ_FBIN1nz_CTX, // -bin 1, parent is non-zero, neighbours non-zero
+ NZ_FBIN2_CTX, // -bin 2, parent is non-zero
+ NZ_FBIN3_CTX, // -bin 3, parent is non-zero
+ NZ_FBIN4_CTX, // -bin 4, parent is non-zero
+ NZ_FBIN5_CTX, // -bin 5, parent is non-zero
+ NZ_FBIN6plus_CTX, // -bins 6 plus, parent is non-zero
+
+ // Information bit contexts
+ INFO_CTX,
+
+ BLOCK_SKIP_CTX, // - blocks are skipped
+ Q_OFFSET_FOLLOW_CTX, // - code block quantiser offset magnitude
+ Q_OFFSET_INFO_CTX, // - code block quantiser offset info context
+ Q_OFFSET_SIGN_CTX, // - code block quantiser offset sign
+ TOTAL_COEFF_CTXS // The total number of coefficient contexts
+ };
-//! Contexts used for coefficient coding
-enum CtxAliases
-{
- //used for residual coding
- SIGN0_CTX, // -sign, previous symbol is 0
- SIGN_POS_CTX, // -sign, previous symbol is +ve
- SIGN_NEG_CTX, // -sign, previous symbol is -ve
-
- // Follow bit contexts
- Z_FBIN1z_CTX, // -bin 1, parent is zero, neighbours zero
- Z_FBIN1nz_CTX, // -bin 1, parent is zero, neighbours non-zero
- Z_FBIN2_CTX, // -bin 2, parent is zero
- Z_FBIN3_CTX, // -bin 3, parent is zero
- Z_FBIN4_CTX, // -bin 4, parent is zero
- Z_FBIN5_CTX, // -bin 5, parent is zero
- Z_FBIN6plus_CTX, // -bins 6 plus, parent is zero
-
- NZ_FBIN1z_CTX, // -bin 1, parent is non-zero, neighbours zero
- NZ_FBIN1nz_CTX, // -bin 1, parent is non-zero, neighbours non-zero
- NZ_FBIN2_CTX, // -bin 2, parent is non-zero
- NZ_FBIN3_CTX, // -bin 3, parent is non-zero
- NZ_FBIN4_CTX, // -bin 4, parent is non-zero
- NZ_FBIN5_CTX, // -bin 5, parent is non-zero
- NZ_FBIN6plus_CTX, // -bins 6 plus, parent is non-zero
-
- // Information bit contexts
- INFO_CTX,
-
- BLOCK_SKIP_CTX, // - blocks are skipped
- Q_OFFSET_FOLLOW_CTX, // - code block quantiser offset magnitude
- Q_OFFSET_INFO_CTX, // - code block quantiser offset info context
- Q_OFFSET_SIGN_CTX, // - code block quantiser offset sign
- TOTAL_COEFF_CTXS // The total number of coefficient contexts
-};
-
-//! Contexts used for MV data coding
-enum MvCtxAliases
-{
- // DC value contexts //
- ///////////////////////
+ //! Contexts used for MV data coding
+ enum MvCtxAliases
+ {
+ // DC value contexts //
+ ///////////////////////
- DC_FBIN1_CTX,
- DC_FBIN2plus_CTX,
- DC_INFO_CTX,
- DC_SIGN_CTX,
+ DC_FBIN1_CTX,
+ DC_FBIN2plus_CTX,
+ DC_INFO_CTX,
+ DC_SIGN_CTX,
- // Motion vector contexts //
- ////////////////////////////
+ // Motion vector contexts //
+ ////////////////////////////
- MV_FBIN1_CTX,
- MV_FBIN2_CTX,
- MV_FBIN3_CTX,
- MV_FBIN4_CTX,
- MV_FBIN5plus_CTX,
+ MV_FBIN1_CTX,
+ MV_FBIN2_CTX,
+ MV_FBIN3_CTX,
+ MV_FBIN4_CTX,
+ MV_FBIN5plus_CTX,
- MV_INFO_CTX,
+ MV_INFO_CTX,
- MV_SIGN_CTX,
+ MV_SIGN_CTX,
- // Prediction mode contexts
+ // Prediction mode contexts
- PMODE_BIT0_CTX, // -bit 0, prediction mode value
- PMODE_BIT1_CTX, // -bin 1, prediction mode value
+ PMODE_BIT0_CTX, // -bit 0, prediction mode value
+ PMODE_BIT1_CTX, // -bin 1, prediction mode value
- // Macroblock contexts
+ // Macroblock contexts
- SB_SPLIT_BIN1_CTX, // bin 1, SB split mode vals
- SB_SPLIT_BIN2_CTX, // bin 2, SB split mode vals. Bin 3 not required
+ SB_SPLIT_BIN1_CTX, // bin 1, SB split mode vals
+ SB_SPLIT_BIN2_CTX, // bin 2, SB split mode vals. Bin 3 not required
- SB_SPLIT_INFO_CTX, // info context for SB split mode
+ SB_SPLIT_INFO_CTX, // info context for SB split mode
- TOTAL_MV_CTXS // The total number of motion vector contexts
-};
+ TOTAL_MV_CTXS // The total number of motion vector contexts
+ };
-/**
-* Function to convert an integer to a valid VideoFormat
-*@param video_format Integer corresponding to a format
-*@return Valid video-format (returns VIDEO_FORMAT_UNDEFINED if no valid format found)
-*/
-VideoFormat IntToVideoFormat(int video_format);
+ /**
+ * Function to convert an integer to a valid VideoFormat
+ *@param video_format Integer corresponding to a format
+ *@return Valid video-format (returns VIDEO_FORMAT_UNDEFINED if no valid format found)
+ */
+ VideoFormat IntToVideoFormat(int video_format);
-/**
-* Function to convert an integer to a valid VideoFormat
-*@param chroma_format Integer corresponding to a format
-*@return Valid chroma-format (returns formatNK if no valid format found)
-*/
-ChromaFormat IntToChromaFormat(int chroma_format);
+ /**
+ * Function to convert an integer to a valid VideoFormat
+ *@param chroma_format Integer corresponding to a format
+ *@return Valid chroma-format (returns formatNK if no valid format found)
+ */
+ ChromaFormat IntToChromaFormat(int chroma_format);
-/**
+ /**
* Function to convert an integer to a valid FrameRate type
*@param frame_rate_idx Integer corresponding to a frame-rate in the spec table
*@return Valid FrameRateType (returns FRAMERATE_UNDEFINED if no valid frame-rate found)
*/
-FrameRateType IntToFrameRateType(int frame_rate_idx);
-
-/**
-* Function to convert an integer to a valid PixelAspectRatio type
-*@param pix_asr_idx Integer corresponding to a pixel aspect ratio in the spec table
-*@return Valid PixelAspectRatioType (returns PIXEL_ASPECT_RATIO_UNDEFINED if no valid pixel aspect ratio found)
-*/
-PixelAspectRatioType IntToPixelAspectRatioType(int pix_asr_idx);
-
-/**
-* Function to convert an integer to a valid SignalRange type
-*@param signal_range_idx Integer corresponding to a signal-range in the spec table
-*@return Valid SignalRangeType (returns SIGNAL_RANGE_UNDEFINED if no valid signal-ratio found)
-*/
-SignalRangeType IntToSignalRangeType(int signal_range_idx);
-
-/**
+ FrameRateType IntToFrameRateType(int frame_rate_idx);
+
+ /**
+ * Function to convert an integer to a valid PixelAspectRatio type
+ *@param pix_asr_idx Integer corresponding to a pixel aspect ratio in the spec table
+ *@return Valid PixelAspectRatioType (returns PIXEL_ASPECT_RATIO_UNDEFINED if no valid pixel aspect ratio found)
+ */
+ PixelAspectRatioType IntToPixelAspectRatioType(int pix_asr_idx);
+
+ /**
+ * Function to convert an integer to a valid SignalRange type
+ *@param signal_range_idx Integer corresponding to a signal-range in the spec table
+ *@return Valid SignalRangeType (returns SIGNAL_RANGE_UNDEFINED if no valid signal-ratio found)
+ */
+ SignalRangeType IntToSignalRangeType(int signal_range_idx);
+
+ /**
* Function to convert an integer to a valid motion-vector precision type
*@param mv_prec Integer corresponding to a valid motion-vector precision
*@return Valid MVPrecisionType (returns SIGNAL_RANGE_UNDEFINED if no valid precision found)
*/
-MVPrecisionType IntToMVPrecisionType(int mv_prec);
-
-//Classes used throughout the codec//
-/////////////////////////////////////
-
-//! Class defining a rational number
-class Rational
-{
-public:
- //! Numerator
- unsigned int m_num;
- //! Denominator
- unsigned int m_denom;
-};
-
-//! Picture type Class
-class PictureSort
-{
-public:
- PictureSort()
- {
- fs = 0x00; // default intra non-ref
- }
-
- void SetIntra()
- {
- fs &= 0xfe;
- }
- void SetInter()
- {
- fs |= 0x01;
- }
- void SetNonRef()
- {
- fs &= 0xfd;
- }
- void SetRef()
- {
- fs |= 0x02;
- }
-
- bool IsInter() const
- {
- return fs & 0x01;
- }
- bool IsIntra() const
- {
- return !IsInter();
- }
- bool IsRef() const
- {
- return fs & 0x02;
+ MVPrecisionType IntToMVPrecisionType(int mv_prec);
+
+ //Classes used throughout the codec//
+ /////////////////////////////////////
+
+ //! Class defining a rational number
+ class Rational
+ {
+ public:
+ //! Numerator
+ unsigned int m_num;
+ //! Denominator
+ unsigned int m_denom;
};
- bool IsNonRef() const
- {
- return !IsRef();
- }
-
- void SetIntraNonRef()
- {
- SetIntra();
- SetNonRef();
- }
- void SetIntraRef()
- {
- SetIntra();
- SetRef();
- }
- void SetInterNonRef()
- {
- SetInter();
- SetNonRef();
- }
- void SetInterRef()
- {
- SetInter();
- SetRef();
- }
-
- bool IsIntraNonRef() const
- {
- return (fs & 0x03) == 0x00;
- }
- bool IsIntraRef() const
- {
- return (fs & 0x03) == 0x02;
- }
- bool IsInterNonRef() const
- {
- return (fs & 0x03) == 0x01;
- }
- bool IsInterRef() const
- {
- return (fs & 0x03) == 0x03;
- }
-
- void Clear()
- {
- fs = 0x00;
- }
-
- static PictureSort IntraRefPictureSort()
- {
- PictureSort fs;
- fs.SetIntraRef();
- return fs;
- }
-
- static PictureSort InterRefPictureSort()
- {
- PictureSort fs;
- fs.SetInterRef();
- return fs;
- }
-
- static PictureSort IntraNonRefPictureSort()
- {
- PictureSort fs;
- fs.SetIntraNonRef();
- return fs;
- }
- static PictureSort InterNonRefPictureSort()
- {
- PictureSort fs;
- fs.SetInterNonRef();
- return fs;
- }
-
-private:
- unsigned char fs;
-};
-
-//! Parameters relating to the source material being encoded/decoded
-class SourceParams
-{
-public:
- //! default constructor
- SourceParams(const VideoFormat &vf = VIDEO_FORMAT_CUSTOM,
- bool set_defaults = true);
-
- ////////////////////////////////////////////////////////////////////
- //NB: Assume default copy constructor, assignment = and destructor//
- ////////////////////////////////////////////////////////////////////
-
- // Gets
- //! Returns video-format
- VideoFormat GetVideoFormat() const
- {
- return m_video_format;
- }
-
- //! Returns the picture width
- unsigned int Xl() const
- {
- return m_xl;
- }
-
- //! Returns the picture height
- unsigned int Yl() const
- {
- return m_yl;
- }
-
- //! Returns the chroma format of the sequence (420, 422, 444)
- ChromaFormat CFormat() const
- {
- return m_cformat;
- }
-
- //! Returns the chroma width
- int ChromaWidth() const;
-
- //! Returns the chroma height
- int ChromaHeight() const;
+ //! Picture type Class
+ class PictureSort
+ {
+ public:
+ PictureSort() { fs = 0x00; } // default intra non-ref
+
+ void SetIntra() { fs &= 0xfe; }
+ void SetInter() { fs |= 0x01; }
+ void SetNonRef() { fs &= 0xfd; }
+ void SetRef() { fs |= 0x02; }
+
+ bool IsInter () const { return fs & 0x01; }
+ bool IsIntra () const { return !IsInter(); }
+ bool IsRef() const { return fs & 0x02; };
+ bool IsNonRef() const { return !IsRef(); }
+
+ void SetIntraNonRef() { SetIntra(); SetNonRef(); }
+ void SetIntraRef() { SetIntra(); SetRef(); }
+ void SetInterNonRef() { SetInter(); SetNonRef(); }
+ void SetInterRef() { SetInter(); SetRef(); }
+
+ bool IsIntraNonRef() const { return (fs & 0x03) == 0x00; }
+ bool IsIntraRef() const { return (fs & 0x03) == 0x02; }
+ bool IsInterNonRef() const { return (fs & 0x03) == 0x01; }
+ bool IsInterRef() const { return (fs & 0x03) == 0x03; }
+
+ void Clear() { fs=0x00; }
+
+ static PictureSort IntraRefPictureSort()
+ {
+ PictureSort fs;
+ fs.SetIntraRef();
+ return fs;
+ }
+
+ static PictureSort InterRefPictureSort()
+ {
+ PictureSort fs;
+ fs.SetInterRef();
+ return fs;
+ }
+
+ static PictureSort IntraNonRefPictureSort()
+ {
+ PictureSort fs;
+ fs.SetIntraNonRef();
+ return fs;
+ }
+
+ static PictureSort InterNonRefPictureSort()
+ {
+ PictureSort fs;
+ fs.SetInterNonRef();
+ return fs;
+ }
+
+ private:
+ unsigned char fs;
+ };
- //! Returns the source sampling field of the source scan format
- unsigned int SourceSampling() const
+ //! Parameters relating to the source material being encoded/decoded
+ class SourceParams
{
- return m_source_sampling;
- }
+ public:
+ //! default constructor
+ SourceParams (const VideoFormat &vf = VIDEO_FORMAT_CUSTOM,
+ bool set_defaults=true);
- //! Returns true if top field comes first in time
- bool TopFieldFirst() const
- {
- return m_topfieldfirst;
- }
+ ////////////////////////////////////////////////////////////////////
+ //NB: Assume default copy constructor, assignment = and destructor//
+ ////////////////////////////////////////////////////////////////////
- //! Return the number for frames per second
- Rational FrameRate() const
- {
- return m_framerate;
- }
+ // Gets
+ //! Returns video-format
+ VideoFormat GetVideoFormat() const { return m_video_format;}
- //! Return the type from the frame rate table
- FrameRateType FrameRateIndex() const
- {
- return m_fr_idx;
- }
+ //! Returns the picture width
+ unsigned int Xl() const {return m_xl;}
- //! Return the pixel aspect ratio
- Rational PixelAspectRatio() const
- {
- return m_pixel_aspect_ratio;
- }
-
- //! Return the type from the pixel aspect ratio table
- PixelAspectRatioType PixelAspectRatioIndex() const
- {
- return m_pix_asr_idx;
- }
+ //! Returns the picture height
+ unsigned int Yl() const {return m_yl;}
- // Clean area parameters
- //! Return the Clean area width
- unsigned int CleanWidth() const
- {
- return m_clean_width;
- }
- //! Return the Clean area height
- unsigned int CleanHeight() const
- {
- return m_clean_height;
- }
- //! Return the Clean area left offset
- unsigned int LeftOffset() const
- {
- return m_left_offset;
- }
- //! Return the Clean area top offset
- unsigned int TopOffset() const
- {
- return m_top_offset;
- }
+ //! Returns the chroma format of the sequence (420, 422, 444)
+ ChromaFormat CFormat() const {return m_cformat;}
- // Signal Range parameters
+ //! Returns the chroma width
+ int ChromaWidth() const;
- //! Return the type from the signal range table
- SignalRangeType SignalRangeIndex() const
- {
- return m_sr_idx;
- }
+ //! Returns the chroma height
+ int ChromaHeight() const;
- //! Return the luma offset
- unsigned int LumaOffset() const
- {
- return m_luma_offset;
- }
- //! Return the luma excursion
- unsigned int LumaExcursion() const
- {
- return m_luma_excursion;
- }
- //! Return the chroma offset
- unsigned int ChromaOffset() const
- {
- return m_chroma_offset;
- }
- //! Return the chroma excursion
- unsigned int ChromaExcursion() const
- {
- return m_chroma_excursion;
- }
+ //! Returns the source sampling field of the source scan format
+ unsigned int SourceSampling() const { return m_source_sampling; }
- //! Return the index into the colour specification table
- unsigned int ColourSpecificationIndex() const
- {
- return m_cs_idx;
- }
+ //! Returns true if top field comes first in time
+ bool TopFieldFirst() const { return m_topfieldfirst; }
- //! Return the colour primaries index
- ColourPrimaries ColourPrimariesIndex() const
- {
- return m_col_primary;
- }
- //! Return the colour matrix index
- ColourMatrix ColourMatrixIndex() const
- {
- return m_col_matrix;
- }
- //! Return the transfer function index
- TransferFunction TransferFunctionIndex() const
- {
- return m_transfer_func;
- }
+ //! Return the number for frames per second
+ Rational FrameRate() const { return m_framerate; }
- // Sets
+ //! Return the type from the frame rate table
+ FrameRateType FrameRateIndex() const { return m_fr_idx; }
+
+ //! Return the pixel aspect ratio
+ Rational PixelAspectRatio() const { return m_pixel_aspect_ratio; }
+
+ //! Return the type from the pixel aspect ratio table
+ PixelAspectRatioType PixelAspectRatioIndex() const { return m_pix_asr_idx; }
+
+ // Clean area parameters
+ //! Return the Clean area width
+ unsigned int CleanWidth() const { return m_clean_width; }
+ //! Return the Clean area height
+ unsigned int CleanHeight() const { return m_clean_height; }
+ //! Return the Clean area left offset
+ unsigned int LeftOffset() const { return m_left_offset; }
+ //! Return the Clean area top offset
+ unsigned int TopOffset() const { return m_top_offset; }
+
+ // Signal Range parameters
+
+ //! Return the type from the signal range table
+ SignalRangeType SignalRangeIndex() const { return m_sr_idx; }
+
+ //! Return the luma offset
+ unsigned int LumaOffset() const { return m_luma_offset; }
+ //! Return the luma excursion
+ unsigned int LumaExcursion() const { return m_luma_excursion; }
+ //! Return the chroma offset
+ unsigned int ChromaOffset() const { return m_chroma_offset; }
+ //! Return the chroma excursion
+ unsigned int ChromaExcursion() const { return m_chroma_excursion; }
+
+ //! Return the index into the colour specification table
+ unsigned int ColourSpecificationIndex() const { return m_cs_idx; }
+
+ //! Return the colour primaries index
+ ColourPrimaries ColourPrimariesIndex() const { return m_col_primary; }
+ //! Return the colour matrix index
+ ColourMatrix ColourMatrixIndex() const { return m_col_matrix; }
+ //! Return the transfer function index
+ TransferFunction TransferFunctionIndex() const { return m_transfer_func; }
+
+ // Sets
+
+ //! Sets the picture width
+ void SetXl(unsigned int xlen) {m_xl = xlen;}
+
+ //! Sets the picture height
+ void SetYl(unsigned int ylen) {m_yl = ylen;}
+
+ //! Sets the chroma format (Y only, 420, 422 etc)
+ void SetCFormat(ChromaFormat cf) {m_cformat=cf;}
+
+ //! Set if the source sampling field of the scan format
+ void SetSourceSampling(unsigned int source_sampling)
+ { m_source_sampling = source_sampling; }
+
+ //! Set Topfield first. True if top field comes first in time
+ void SetTopFieldFirst(bool tff) { m_topfieldfirst = tff; }
+
+ //! Sets the video format
+ void SetVideoFormat(VideoFormat vf){ m_video_format=vf;}
+
+ //! Set the frame rate
+ void SetFrameRate(const Rational &frate )
+ {
+ m_fr_idx = FRAMERATE_CUSTOM; m_framerate = frate;
+ }
+
+ //! Set the frame rate
+ void SetFrameRate(unsigned int fr_num, unsigned int fr_denom )
+ {
+ m_fr_idx = FRAMERATE_CUSTOM;
+ m_framerate.m_num = fr_num;
+ m_framerate.m_denom = fr_denom;
+ }
- //! Sets the picture width
- void SetXl(unsigned int xlen)
- {
- m_xl = xlen;
- }
+ //! Set the frame rate
+ void SetFrameRate(FrameRateType fr);
- //! Sets the picture height
- void SetYl(unsigned int ylen)
- {
- m_yl = ylen;
- }
+ //! Set the pixel aspect ratio
+ void SetPixelAspectRatio(const Rational &pix_asr)
+ {
+ m_pix_asr_idx = PIXEL_ASPECT_RATIO_CUSTOM;
+ m_pixel_aspect_ratio = pix_asr;
+ }
+
+ //! Set the pixel aspect ratio
+ void SetPixelAspectRatio(unsigned int pix_as_num, unsigned int pix_as_denom )
+ {
+ m_pix_asr_idx = PIXEL_ASPECT_RATIO_CUSTOM;
+ m_pixel_aspect_ratio.m_num = pix_as_num;
+ m_pixel_aspect_ratio.m_denom = pix_as_denom;
+ }
+
+ //! Set the Pixel Aspect Ratio
+ void SetPixelAspectRatio(PixelAspectRatioType pixel_aspect_ratio);
+
+ // Clean area parameters
+ //! Set the Clean area width
+ void SetCleanWidth(unsigned int clean_width) { m_clean_width = clean_width; }
+ //! Set the Clean area height
+ void SetCleanHeight(unsigned int clean_height) { m_clean_height = clean_height; }
+ //! Set the Clean area left offset
+ void SetLeftOffset(unsigned int left_offset) { m_left_offset = left_offset; }
+ //! Set the Clean area top offset
+ void SetTopOffset(unsigned int top_offset) { m_top_offset = top_offset; }
+
+ // Signal Range parameters
+ //! Set the Signal Range parameters
+ void SetSignalRange(SignalRangeType sr);
+
+ //! Set the luma offset
+ void SetLumaOffset(unsigned int luma_offset) { m_sr_idx = SIGNAL_RANGE_CUSTOM; m_luma_offset = luma_offset; }
+ //! Set the luma excursion
+ void SetLumaExcursion(unsigned int luma_exc) { m_sr_idx = SIGNAL_RANGE_CUSTOM; m_luma_excursion = luma_exc; }
+ //! Set the chroma offset
+ void SetChromaOffset(unsigned int chroma_off) { m_sr_idx = SIGNAL_RANGE_CUSTOM; m_chroma_offset = chroma_off; }
+ //! Set the chroma excursion
+ void SetChromaExcursion(unsigned int chroma_exc) { m_sr_idx = SIGNAL_RANGE_CUSTOM; m_chroma_excursion = chroma_exc; }
+
+ //! Set the Colour specification
+ void SetColourSpecification(unsigned int cs_idx);
+ //! Set the colour primaries index
+ void SetColourPrimariesIndex(unsigned int cp);
+ //! Set the colour matrix index
+ void SetColourMatrixIndex(unsigned int cm);
+ //! Set the transfer function index
+ void SetTransferFunctionIndex(unsigned int tf);
+
+ private:
+ //!Video-format
+ VideoFormat m_video_format;
+
+ //! Width of video
+ unsigned int m_xl;
+
+ //! Height of video
+ unsigned int m_yl;
+
+ //! Presence of chroma and/or chroma sampling structure
+ ChromaFormat m_cformat;
+
+ //! Source sampling field : 0 - progressive, 1 - interlaced
+ unsigned int m_source_sampling;
+
+ //! If m_source_sampling=1, true if the top field is first in temporal order
+ bool m_topfieldfirst;
+
+ //! Index into frame rate table
+ FrameRateType m_fr_idx;
+
+ //! Frame Rate i.e number of frames per second
+ Rational m_framerate;
+
+ //! Index into pixel aspect ratio table
+ PixelAspectRatioType m_pix_asr_idx;
+
+ //! Pixel Aspect Ratio
+ Rational m_pixel_aspect_ratio;
+
+ // Clean area parameters
+
+ //! Clean area width
+ unsigned int m_clean_width;
+
+ //! Clean area height
+ unsigned int m_clean_height;
+
+ //! Clean area left offset
+ unsigned int m_left_offset;
+
+ //! Clean area top offset
+ unsigned int m_top_offset;
+
+ // signal range parameters
+
+ //! Index into signal range table
+ SignalRangeType m_sr_idx;
+
+ //! Luma offset
+ unsigned int m_luma_offset;
+ //! Luma excursion
+ unsigned int m_luma_excursion;
+ //! Chroma offset
+ unsigned int m_chroma_offset;
+ //! Chroma excursion
+ unsigned int m_chroma_excursion;
+
+ //! Index into colour spec table
+ unsigned int m_cs_idx;
- //! Sets the chroma format (Y only, 420, 422 etc)
- void SetCFormat(ChromaFormat cf)
- {
- m_cformat = cf;
- }
+ //! Colour Primaries Index
+ ColourPrimaries m_col_primary;
- //! Set if the source sampling field of the scan format
- void SetSourceSampling(unsigned int source_sampling)
- {
- m_source_sampling = source_sampling;
- }
+ // Colour Matrix index
+ ColourMatrix m_col_matrix;
- //! Set Topfield first. True if top field comes first in time
- void SetTopFieldFirst(bool tff)
- {
- m_topfieldfirst = tff;
- }
+ // Transfer function index
+ TransferFunction m_transfer_func;
+ };
- //! Sets the video format
- void SetVideoFormat(VideoFormat vf)
- {
- m_video_format = vf;
- }
- //! Set the frame rate
- void SetFrameRate(const Rational &frate)
+ //! Parameters for initialising picture class objects
+ class PictureParams
{
- m_fr_idx = FRAMERATE_CUSTOM;
- m_framerate = frate;
- }
- //! Set the frame rate
- void SetFrameRate(unsigned int fr_num, unsigned int fr_denom)
- {
- m_fr_idx = FRAMERATE_CUSTOM;
- m_framerate.m_num = fr_num;
- m_framerate.m_denom = fr_denom;
- }
+ public:
+ //! Default constructor
+ PictureParams();
- //! Set the frame rate
- void SetFrameRate(FrameRateType fr);
+ //! Constructor
+ /*!
+ Picture chroma format is set Picture sort defaults to I picture.
+ */
+ PictureParams(const ChromaFormat& cf, int xlen, int ylen,
+ unsigned int luma_depth, unsigned int chroma_depth);
- //! Set the pixel aspect ratio
- void SetPixelAspectRatio(const Rational &pix_asr)
- {
- m_pix_asr_idx = PIXEL_ASPECT_RATIO_CUSTOM;
- m_pixel_aspect_ratio = pix_asr;
- }
+ //! Constructor
+ /*!
+ Picture chroma format and picture sort are set.
+ */
+ PictureParams(const ChromaFormat& cf, const PictureSort& fs);
- //! Set the pixel aspect ratio
- void SetPixelAspectRatio(unsigned int pix_as_num, unsigned int pix_as_denom)
- {
- m_pix_asr_idx = PIXEL_ASPECT_RATIO_CUSTOM;
- m_pixel_aspect_ratio.m_num = pix_as_num;
- m_pixel_aspect_ratio.m_denom = pix_as_denom;
- }
+ //! Constructor
+ /*!
+ Constructor. Parameters are derived from the source parameters
+ */
+ PictureParams(const SourceParams& sparams);
- //! Set the Pixel Aspect Ratio
- void SetPixelAspectRatio(PixelAspectRatioType pixel_aspect_ratio);
+ ////////////////////////////////////////////////////////////////////
+ //NB: Assume default copy constructor, assignment = and destructor//
+ ////////////////////////////////////////////////////////////////////
- // Clean area parameters
- //! Set the Clean area width
- void SetCleanWidth(unsigned int clean_width)
- {
- m_clean_width = clean_width;
- }
- //! Set the Clean area height
- void SetCleanHeight(unsigned int clean_height)
- {
- m_clean_height = clean_height;
- }
- //! Set the Clean area left offset
- void SetLeftOffset(unsigned int left_offset)
- {
- m_left_offset = left_offset;
- }
- //! Set the Clean area top offset
- void SetTopOffset(unsigned int top_offset)
- {
- m_top_offset = top_offset;
- }
+ // Gets ...
- // Signal Range parameters
- //! Set the Signal Range parameters
- void SetSignalRange(SignalRangeType sr);
+ //! Returns the chroma format of the picture
+ const ChromaFormat& CFormat() const{return m_cformat;}
- //! Set the luma offset
- void SetLumaOffset(unsigned int luma_offset)
- {
- m_sr_idx = SIGNAL_RANGE_CUSTOM;
- m_luma_offset = luma_offset;
- }
- //! Set the luma excursion
- void SetLumaExcursion(unsigned int luma_exc)
- {
- m_sr_idx = SIGNAL_RANGE_CUSTOM;
- m_luma_excursion = luma_exc;
- }
- //! Set the chroma offset
- void SetChromaOffset(unsigned int chroma_off)
- {
- m_sr_idx = SIGNAL_RANGE_CUSTOM;
- m_chroma_offset = chroma_off;
- }
- //! Set the chroma excursion
- void SetChromaExcursion(unsigned int chroma_exc)
- {
- m_sr_idx = SIGNAL_RANGE_CUSTOM;
- m_chroma_excursion = chroma_exc;
- }
+ //! Returns the picture width
+ int Xl() const {return m_xl;}
- //! Set the Colour specification
- void SetColourSpecification(unsigned int cs_idx);
- //! Set the colour primaries index
- void SetColourPrimariesIndex(unsigned int cp);
- //! Set the colour matrix index
- void SetColourMatrixIndex(unsigned int cm);
- //! Set the transfer function index
- void SetTransferFunctionIndex(unsigned int tf);
+ //! Returns the picture height
+ int Yl() const {return m_yl;}
-private:
- //!Video-format
- VideoFormat m_video_format;
+ //! Returns the chroma width of the picture
+ int ChromaXl() const{return m_cxl;}
- //! Width of video
- unsigned int m_xl;
+ //! Returns the chroma height of the picture
+ int ChromaYl() const{return m_cyl;}
- //! Height of video
- unsigned int m_yl;
+ //! Returns the luma depth
+ unsigned int LumaDepth() const { return m_luma_depth; }
- //! Presence of chroma and/or chroma sampling structure
- ChromaFormat m_cformat;
+ //! Returns the chroma depth
+ unsigned int ChromaDepth() const { return m_chroma_depth; }
- //! Source sampling field : 0 - progressive, 1 - interlaced
- unsigned int m_source_sampling;
+ //! Returns the type of the picture
+ const PictureSort& PicSort() const {return m_psort;}
- //! If m_source_sampling=1, true if the top field is first in temporal order
- bool m_topfieldfirst;
+ //! Returns the number of the picture (in time order)
+ int PictureNum() const {return m_fnum;}
- //! Index into frame rate table
- FrameRateType m_fr_idx;
+ //! Returns the retired reference picture number
+ int RetiredPictureNum() const {return m_retd_fnum;}
- //! Frame Rate i.e number of frames per second
- Rational m_framerate;
+ //! Returns whether the picture is bi-directionally predicted by checking references
+ bool IsBPicture() const;
- //! Index into pixel aspect ratio table
- PixelAspectRatioType m_pix_asr_idx;
+ //! Returns the number of pictures after the current picture number after which the picture can be discarded
+ int ExpiryTime() const {return m_expiry_time;}
- //! Pixel Aspect Ratio
- Rational m_pixel_aspect_ratio;
+ //! Returns an indication of whether the picture has been output yet
+ bool Output() const {return m_output;}
- // Clean area parameters
+ //! Returns a const C++ reference to the set of reference picture numbers (will be empty if the picture is an I picture)
+ const std::vector<int>& Refs() const {return m_refs;}
- //! Clean area width
- unsigned int m_clean_width;
+ //! Returns non-const C++ referece to the vector of reference pictures, to allow them to be set
+ std::vector<int>& Refs(){return m_refs;}
- //! Clean area height
- unsigned int m_clean_height;
+ //! Return the number of reference pictures
+ unsigned int NumRefs()const {return m_refs.size();}
- //! Clean area left offset
- unsigned int m_left_offset;
+ //! Returns type of picture (see enum)
+ PictureType GetPictureType () const { return m_picture_type; }
- //! Clean area top offset
- unsigned int m_top_offset;
+ //! Returns reference picture type (see enum)
+ ReferenceType GetReferenceType() const { return m_reference_type;}
- // signal range parameters
+ //! Returns true is entropy coding using Arithmetic coding
+ bool UsingAC() const { return m_using_ac; }
- //! Index into signal range table
- SignalRangeType m_sr_idx;
+ // ... Sets
- //! Luma offset
- unsigned int m_luma_offset;
- //! Luma excursion
- unsigned int m_luma_excursion;
- //! Chroma offset
- unsigned int m_chroma_offset;
- //! Chroma excursion
- unsigned int m_chroma_excursion;
+ //! Sets the type of picture
+ void SetPicSort( const PictureSort& ps );
- //! Index into colour spec table
- unsigned int m_cs_idx;
+ //! Sets the picture to be Intra/Inter
+ void SetPictureType(const PictureType ftype);
- //! Colour Primaries Index
- ColourPrimaries m_col_primary;
+ //! Sets the picture to be a reference or not
+ void SetReferenceType(const ReferenceType rtype);
- // Colour Matrix index
- ColourMatrix m_col_matrix;
+ //! Sets the picture number
+ void SetPictureNum( const int fn ){ m_fnum=fn; }
- // Transfer function index
- TransferFunction m_transfer_func;
-};
+ //! Sets how long the picture will stay in the buffer (encoder only)
+ void SetExpiryTime( const int expt ){ m_expiry_time=expt; }
+ //! Sets a flag to indicate that the picture has been output
+ void SetAsOutput(){m_output=true;}
-//! Parameters for initialising picture class objects
-class PictureParams
-{
+ //! Sets the chroma format
+ void SetCFormat(ChromaFormat cf){ m_cformat = cf; }
-public:
- //! Default constructor
- PictureParams();
+ //! Sets the picture width
+ void SetXl(int xlen);
- //! Constructor
- /*!
- Picture chroma format is set Picture sort defaults to I picture.
- */
- PictureParams(const ChromaFormat& cf, int xlen, int ylen,
- unsigned int luma_depth, unsigned int chroma_depth);
+ //! Sets the picture height
+ void SetYl(int ylen);
- //! Constructor
- /*!
- Picture chroma format and picture sort are set.
- */
- PictureParams(const ChromaFormat& cf, const PictureSort& fs);
+ //! Set Luma Depth
+ void SetLumaDepth(unsigned int luma_depth) { m_luma_depth = luma_depth; }
- //! Constructor
- /*!
- Constructor. Parameters are derived from the source parameters
- */
- PictureParams(const SourceParams& sparams);
+ //! Set Chroma Depth
+ void SetChromaDepth(unsigned int chroma_depth) { m_chroma_depth = chroma_depth; }
- ////////////////////////////////////////////////////////////////////
- //NB: Assume default copy constructor, assignment = and destructor//
- ////////////////////////////////////////////////////////////////////
+ //! Sets the retired reference picture number
+ void SetRetiredPictureNum(int retd_fnum) {m_retd_fnum = retd_fnum;}
- // Gets ...
+ //! Sets the arithmetic coding flag
+ void SetUsingAC(bool using_ac) { m_using_ac = using_ac; }
- //! Returns the chroma format of the picture
- const ChromaFormat& CFormat() const
- {
- return m_cformat;
- }
+ private:
- //! Returns the picture width
- int Xl() const
- {
- return m_xl;
- }
+ //! The chroma format
+ ChromaFormat m_cformat;
- //! Returns the picture height
- int Yl() const
- {
- return m_yl;
- }
+ //! The picture sort
+ PictureSort m_psort;
- //! Returns the chroma width of the picture
- int ChromaXl() const
- {
- return m_cxl;
- }
+ //! The set of picture numbers of reference pictures
+ std::vector<int> m_refs;
- //! Returns the chroma height of the picture
- int ChromaYl() const
- {
- return m_cyl;
- }
+ //! The number of pictures, after the current picture number, after the (de)coding of which the picture can be deleted
+ int m_expiry_time;
- //! Returns the luma depth
- unsigned int LumaDepth() const
- {
- return m_luma_depth;
- }
+ //! The picture number, in temporal order
+ int m_fnum;
- //! Returns the chroma depth
- unsigned int ChromaDepth() const
- {
- return m_chroma_depth;
- }
+ //! Picture type
+ PictureType m_picture_type;
- //! Returns the type of the picture
- const PictureSort& PicSort() const
- {
- return m_psort;
- }
+ //! Reference type
+ ReferenceType m_reference_type;
- //! Returns the number of the picture (in time order)
- int PictureNum() const
- {
- return m_fnum;
- }
+ //! True if the picture has been output, false if not
+ bool m_output;
- //! Returns the retired reference picture number
- int RetiredPictureNum() const
- {
- return m_retd_fnum;
- }
+ //! The picture number of the retired picture
+ mutable int m_retd_fnum;
- //! Returns whether the picture is bi-directionally predicted by checking references
- bool IsBPicture() const;
+ //! Picture luma width
+ int m_xl;
- //! Returns the number of pictures after the current picture number after which the picture can be discarded
- int ExpiryTime() const
- {
- return m_expiry_time;
- }
+ //! Picture luma height
+ int m_yl;
- //! Returns an indication of whether the picture has been output yet
- bool Output() const
- {
- return m_output;
- }
+ //! Picture chroma width
+ int m_cxl;
- //! Returns a const C++ reference to the set of reference picture numbers (will be empty if the picture is an I picture)
- const std::vector<int>& Refs() const
- {
- return m_refs;
- }
+ //! Picture chroma height
+ int m_cyl;
- //! Returns non-const C++ referece to the vector of reference pictures, to allow them to be set
- std::vector<int>& Refs()
- {
- return m_refs;
- }
+ //! Luma depth - number of bits required for lumz
+ unsigned int m_luma_depth;
- //! Return the number of reference pictures
- unsigned int NumRefs()const
- {
- return m_refs.size();
- }
+ //! chroma depth - number of bits required for luma
+ unsigned int m_chroma_depth;
- //! Returns type of picture (see enum)
- PictureType GetPictureType() const
- {
- return m_picture_type;
- }
+ //! arithmetic coding flag
+ bool m_using_ac;
+ };
- //! Returns reference picture type (see enum)
- ReferenceType GetReferenceType() const
- {
- return m_reference_type;
- }
- //! Returns true is entropy coding using Arithmetic coding
- bool UsingAC() const
+ //! A class for picture component data.
+ /*!
+ A class for encapsulating picture data, derived from TwoDArray.
+ */
+ class PicArray: public TwoDArray<ValueType>
{
- return m_using_ac;
- }
+ public:
+ //! Default constructor
+ /*!
+ Default constructor creates an empty array.
+ */
+ PicArray(): TwoDArray<ValueType>(){}
- // ... Sets
+ //! Constructor.
+ /*!
+ Contructor creates a two-D array, with specified size and colour
+ format.
+ */
+ PicArray(int height, int width, CompSort cs=Y_COMP):
+ TwoDArray<ValueType>(height, width), m_csort(cs){}
- //! Sets the type of picture
- void SetPicSort(const PictureSort& ps);
+ //copy constructor and assignment= derived by inheritance
- //! Sets the picture to be Intra/Inter
- void SetPictureType(const PictureType ftype);
+ //! Destructor
+ ~PicArray(){}
- //! Sets the picture to be a reference or not
- void SetReferenceType(const ReferenceType rtype);
+ //! Return which component is stored
+ const CompSort& CSort() const {return m_csort;}
+
+ //! Set the type of component being stored
+ void SetCSort(const CompSort cs){ m_csort = cs; }
- //! Sets the picture number
- void SetPictureNum(const int fn)
- {
- m_fnum = fn;
- }
+ private:
- //! Sets how long the picture will stay in the buffer (encoder only)
- void SetExpiryTime(const int expt)
- {
- m_expiry_time = expt;
- }
+ CompSort m_csort;
+ };
- //! Sets a flag to indicate that the picture has been output
- void SetAsOutput()
- {
- m_output = true;
- }
- //! Sets the chroma format
- void SetCFormat(ChromaFormat cf)
+ //! A structure for recording costs, particularly in quantisation.
+ class CostType
{
- m_cformat = cf;
- }
+ public:
+ //! The error (MSE or 4th power)
+ double Error;
- //! Sets the picture width
- void SetXl(int xlen);
+ //! The entropy in bits per symbol.
+ double ENTROPY;
- //! Sets the picture height
- void SetYl(int ylen);
+ //! The Lagrangian combination of MSE+lambda*entropy
+ double TOTAL;
+ };
- //! Set Luma Depth
- void SetLumaDepth(unsigned int luma_depth)
- {
- m_luma_depth = luma_depth;
- }
- //! Set Chroma Depth
- void SetChromaDepth(unsigned int chroma_depth)
- {
- m_chroma_depth = chroma_depth;
- }
+ //! A class used for correcting estimates of entropy.
+ /*!
+ A class used by the encoder for correcting estimates of entropy. Used
+ for selecting quantisers in subband coefficient coding. Factors can be
+ adjusted in the light of previous experience.
+ */
+ class EntropyCorrector
+ {
+ public:
+ //! Constructor.
+ /*!
+ Constructs arrays of correction factors of size.
+ \param depth the depth of the wavelet transform.
+ */
+ EntropyCorrector(int depth);
+
+ ////////////////////////////////////////////////////////////////////
+ //NB: Assume default copy constructor, assignment = and destructor//
+ ////////////////////////////////////////////////////////////////////
+
+ //! Returns the correction factor.
+ /*!
+ Returns the correction factor for the band given also the type of
+ picture and component.
+ */
+ float Factor(const int bandnum, const PictureParams& pp,
+ const CompSort c) const;
+
+ //! Update the correction factors.
+ /*!
+ Update the factors for a given subband, component and picture type.
+ \param bandnum the number of the subband to update
+ \param pp picture parameters
+ \param c component type
+ \param est_bits the number of bits it was estimated would be used
+ \param actual_bits the number of bits that actually were used
+ */
+ void Update(int bandnum, const PictureParams& pp,
+ CompSort c,int est_bits,int actual_bits);
+
+ private:
+ //! Initialises the correction factors
+ void Init();
+
+ TwoDArray<float> m_Yfctrs;
+ TwoDArray<float> m_Ufctrs;
+ TwoDArray<float> m_Vfctrs;
+ };
- //! Sets the retired reference picture number
- void SetRetiredPictureNum(int retd_fnum)
+ //! Parameters for overlapped block motion compensation
+ class OLBParams
{
- m_retd_fnum = retd_fnum;
- }
- //! Sets the arithmetic coding flag
- void SetUsingAC(bool using_ac)
- {
- m_using_ac = using_ac;
- }
+ public:
-private:
+ //! Default constructor does nothing
+ OLBParams(){}
- //! The chroma format
- ChromaFormat m_cformat;
+ //! Constructor
+ /*
+ Constructor rationalises proposed parameters to allow suitable
+ overlap and fit in with chroma format
+ \param xblen the horizontal block length
+ \param yblen the vertical block length
+ \param xblen the horizontal block separation
+ \param yblen the vertical block separation
- //! The picture sort
- PictureSort m_psort;
+ */
+ OLBParams(const int xblen, const int yblen,
+ const int xbsep, const int ybsep);
- //! The set of picture numbers of reference pictures
- std::vector<int> m_refs;
+ // Gets ...
- //! The number of pictures, after the current picture number, after the (de)coding of which the picture can be deleted
- int m_expiry_time;
+ //! Returns the horizontal block length
+ int Xblen() const {return m_xblen;}
- //! The picture number, in temporal order
- int m_fnum;
+ //! Returns the vertical block length
+ int Yblen() const {return m_yblen;}
- //! Picture type
- PictureType m_picture_type;
+ //! Returns the horizontal block separation
+ int Xbsep() const {return m_xbsep;}
- //! Reference type
- ReferenceType m_reference_type;
+ //! Returns the vertical block separation
+ int Ybsep() const {return m_ybsep;}
- //! True if the picture has been output, false if not
- bool m_output;
+ //! The offset in the horizontal start of the block caused by overlap,=(XBLEN-XBSEP)/2
+ int Xoffset() const {return m_xoffset;}
- //! The picture number of the retired picture
- mutable int m_retd_fnum;
+ //! The offset in the vertical start of the block caused by overlap,=(YBLEN-YBSEP)/2
+ int Yoffset() const {return m_yoffset;}
- //! Picture luma width
- int m_xl;
+ // ... and sets
- //! Picture luma height
- int m_yl;
+ //! Sets the block width
+ void SetXblen( int xblen ){ m_xblen = xblen; m_xoffset = (m_xblen-m_xbsep)/2;}
- //! Picture chroma width
- int m_cxl;
+ //! Sets the block height
+ void SetYblen( int yblen ){ m_yblen = yblen; m_yoffset = (m_yblen-m_ybsep)/2;}
- //! Picture chroma height
- int m_cyl;
+ //! Sets the block horizontal separation
+ void SetXbsep( int xbsep ){ m_xbsep = xbsep; m_xoffset = (m_xblen-m_xbsep)/2;}
- //! Luma depth - number of bits required for lumz
- unsigned int m_luma_depth;
+ //! Sets the block vertical separation
+ void SetYbsep( int ybsep ){ m_ybsep = ybsep; m_yoffset = (m_yblen-m_ybsep)/2;}
- //! chroma depth - number of bits required for luma
- unsigned int m_chroma_depth;
+ bool operator == (const OLBParams bparams) const;
- //! arithmetic coding flag
- bool m_using_ac;
-};
+ // overloaded stream operators
+ friend std::ostream & operator<< (std::ostream &, OLBParams &);
+ friend std::istream & operator>> (std::istream &, OLBParams &);
-//! A class for picture component data.
-/*!
- A class for encapsulating picture data, derived from TwoDArray.
- */
-class PicArray: public TwoDArray<ValueType>
-{
-public:
- //! Default constructor
- /*!
- Default constructor creates an empty array.
- */
- PicArray(): TwoDArray<ValueType>() {}
-
- //! Constructor.
- /*!
- Contructor creates a two-D array, with specified size and colour
- format.
- */
- PicArray(int height, int width, CompSort cs = Y_COMP):
- TwoDArray<ValueType>(height, width), m_csort(cs) {}
+ private:
- //copy constructor and assignment= derived by inheritance
-
- //! Destructor
- ~PicArray() {}
-
- //! Return which component is stored
- const CompSort& CSort() const
- {
- return m_csort;
- }
+ int m_xblen;
+ int m_yblen;
+ int m_xbsep;
+ int m_ybsep;
+ int m_xoffset;
+ int m_yoffset;
+ };
- //! Set the type of component being stored
- void SetCSort(const CompSort cs)
+ //! Parameters relating to the complexity of encoder/decoder
+ class ParseParams
{
- m_csort = cs;
- }
-
-private:
-
- CompSort m_csort;
-};
-
-
-//! A structure for recording costs, particularly in quantisation.
-class CostType
-{
-public:
- //! The error (MSE or 4th power)
- double Error;
-
- //! The entropy in bits per symbol.
- double ENTROPY;
+ public:
+ //! Default constructor
+ ParseParams();
- //! The Lagrangian combination of MSE+lambda*entropy
- double TOTAL;
-};
+ // Gets
+ //! Get the major version
+ unsigned int MajorVersion() const { return m_major_ver; }
-//! A class used for correcting estimates of entropy.
-/*!
- A class used by the encoder for correcting estimates of entropy. Used
- for selecting quantisers in subband coefficient coding. Factors can be
- adjusted in the light of previous experience.
- */
-class EntropyCorrector
-{
-public:
- //! Constructor.
- /*!
- Constructs arrays of correction factors of size.
- \param depth the depth of the wavelet transform.
- */
- EntropyCorrector(int depth);
-
- ////////////////////////////////////////////////////////////////////
- //NB: Assume default copy constructor, assignment = and destructor//
- ////////////////////////////////////////////////////////////////////
-
- //! Returns the correction factor.
- /*!
- Returns the correction factor for the band given also the type of
- picture and component.
- */
- float Factor(const int bandnum, const PictureParams& pp,
- const CompSort c) const;
-
- //! Update the correction factors.
- /*!
- Update the factors for a given subband, component and picture type.
- \param bandnum the number of the subband to update
- \param pp picture parameters
- \param c component type
- \param est_bits the number of bits it was estimated would be used
- \param actual_bits the number of bits that actually were used
- */
- void Update(int bandnum, const PictureParams& pp,
- CompSort c, int est_bits, int actual_bits);
+ //! Get the minor version
+ unsigned int MinorVersion() const { return m_minor_ver; }
-private:
- //! Initialises the correction factors
- void Init();
+ //! Get the Profile
+ unsigned int Profile() const { return m_profile; }
- TwoDArray<float> m_Yfctrs;
- TwoDArray<float> m_Ufctrs;
- TwoDArray<float> m_Vfctrs;
-};
+ //! Get the Level
+ unsigned int Level() const { return m_level; }
-//! Parameters for overlapped block motion compensation
-class OLBParams
-{
+ // Sets
-public:
+ //! Set the major version
+ void SetMajorVersion(unsigned int major_ver) {m_major_ver = major_ver; }
- //! Default constructor does nothing
- OLBParams() {}
+ //! Set the minor version
+ void SetMinorVersion(unsigned int minor_ver) { m_minor_ver = minor_ver; }
- //! Constructor
- /*
- Constructor rationalises proposed parameters to allow suitable
- overlap and fit in with chroma format
- \param xblen the horizontal block length
- \param yblen the vertical block length
- \param xblen the horizontal block separation
- \param yblen the vertical block separation
+ //! Set the Profile
+ void SetProfile(unsigned int profile) { m_profile = profile; }
- */
- OLBParams(const int xblen, const int yblen,
- const int xbsep, const int ybsep);
+ //! Set the Level
+ void SetLevel(unsigned int level) { m_level = level; }
- // Gets ...
-
- //! Returns the horizontal block length
- int Xblen() const
- {
- return m_xblen;
- }
-
- //! Returns the vertical block length
- int Yblen() const
- {
- return m_yblen;
- }
-
- //! Returns the horizontal block separation
- int Xbsep() const
- {
- return m_xbsep;
- }
-
- //! Returns the vertical block separation
- int Ybsep() const
- {
- return m_ybsep;
- }
-
- //! The offset in the horizontal start of the block caused by overlap,=(XBLEN-XBSEP)/2
- int Xoffset() const
- {
- return m_xoffset;
- }
-
- //! The offset in the vertical start of the block caused by overlap,=(YBLEN-YBSEP)/2
- int Yoffset() const
- {
- return m_yoffset;
- }
-
- // ... and sets
-
- //! Sets the block width
- void SetXblen(int xblen)
- {
- m_xblen = xblen;
- m_xoffset = (m_xblen - m_xbsep) / 2;
- }
+ private:
+ //! Major Version
+ unsigned int m_major_ver;
+ //! Minor Version
+ unsigned int m_minor_ver;
+ //! Profile
+ unsigned int m_profile;
+ //! Level
+ unsigned int m_level;
+ };
- //! Sets the block height
- void SetYblen(int yblen)
- {
- m_yblen = yblen;
- m_yoffset = (m_yblen - m_ybsep) / 2;
- }
+ //! Structure to hold code block sizes when spatial partitioning is used
+ class CodeBlocks
+ {
+ public:
+ //! Default Constructor
+ CodeBlocks () : m_hblocks(1), m_vblocks(1)
+ {}
+
+ //! Constructor
+ CodeBlocks (unsigned int hblocks, unsigned int vblocks) :
+ m_hblocks(hblocks),
+ m_vblocks(vblocks)
+ {}
+
+ // Gets
+ //! Return the number of horizontal code blocks
+ unsigned int HorizontalCodeBlocks() const { return m_hblocks; }
+ //! Return the number of vertical code blocks
+ unsigned int VerticalCodeBlocks() const { return m_vblocks; }
+ // Sets
+ //! Set the number of horizontal code blocks
+ void SetHorizontalCodeBlocks(unsigned int hblocks) { m_hblocks = hblocks; }
+ //! Set the number of vertical code blocks
+ void SetVerticalCodeBlocks(unsigned int vblocks) { m_vblocks = vblocks; }
+ private:
+ //! Number of Horizontal code blocks
+ unsigned int m_hblocks;
+ //! Number of Vertical code blocks
+ unsigned int m_vblocks;
+ };
- //! Sets the block horizontal separation
- void SetXbsep(int xbsep)
+ //! Structure to hold motion parameters when motion comp is used
+ class PicturePredParams
{
- m_xbsep = xbsep;
- m_xoffset = (m_xblen - m_xbsep) / 2;
- }
+ public:
+ PicturePredParams():
+ m_lbparams(3),
+ m_cbparams(3) {}
- //! Sets the block vertical separation
- void SetYbsep(int ybsep)
- {
- m_ybsep = ybsep;
- m_yoffset = (m_yblen - m_ybsep) / 2;
- }
+ //! Return the global motion flag used for encoding/decoding
+ bool UsingGlobalMotion() const { return m_use_global_motion; }
- bool operator == (const OLBParams bparams) const;
+ //! Return the number of picture weight precision bits
+ unsigned int PictureWeightsBits() const { return m_picture_weights_bits; }
- // overloaded stream operators
- friend std::ostream & operator<< (std::ostream &, OLBParams &);
- friend std::istream & operator>> (std::istream &, OLBParams &);
+ //! Return the Ref1 weight
+ int Ref1Weight() const { return m_ref1_weight; }
+ //! Return the Ref2 weight
+ int Ref2Weight() const { return m_ref2_weight; }
-private:
+ bool CustomRefWeights()
+ {
+ return (m_picture_weights_bits != 1 ||
+ m_ref1_weight != 1 ||
+ m_ref2_weight != 1);
+ }
- int m_xblen;
- int m_yblen;
- int m_xbsep;
- int m_ybsep;
- int m_xoffset;
- int m_yoffset;
-};
+ //! Return the number of superblocks horizontally
+ int XNumSB() const {return m_x_num_sb;}
-//! Parameters relating to the complexity of encoder/decoder
-class ParseParams
-{
-public:
- //! Default constructor
- ParseParams();
+ //! Return the number of superblocks vertically
+ int YNumSB() const {return m_y_num_sb;}
- // Gets
+ //! Return the number of blocks horizontally
+ int XNumBlocks() const {return m_x_num_blocks;}
- //! Get the major version
- unsigned int MajorVersion() const
- {
- return m_major_ver;
- }
+ //! Returns the number of blocks vertically
+ int YNumBlocks() const {return m_y_num_blocks;}
- //! Get the minor version
- unsigned int MinorVersion() const
- {
- return m_minor_ver;
- }
+ //! Return the Luma block parameters for each macroblock splitting level
+ const OLBParams& LumaBParams(int n) const {return m_lbparams[n];}
- //! Get the Profile
- unsigned int Profile() const
- {
- return m_profile;
- }
+ //! Return the Chroma block parameters for each macroblock splitting level
+ const OLBParams& ChromaBParams(int n) const {return m_cbparams[n];}
- //! Get the Level
- unsigned int Level() const
- {
- return m_level;
- }
+ //! Return the number of accuracy bits used for motion vectors
+ MVPrecisionType MVPrecision() const { return m_mv_precision; }
- // Sets
+ //! Set how many SBs there are horizontally
+ void SetXNumSB(const int xn){m_x_num_sb=xn;}
- //! Set the major version
- void SetMajorVersion(unsigned int major_ver)
- {
- m_major_ver = major_ver;
- }
+ //! Set how many SBs there are vertically
+ void SetYNumSB(const int yn){m_y_num_sb=yn;}
- //! Set the minor version
- void SetMinorVersion(unsigned int minor_ver)
- {
- m_minor_ver = minor_ver;
- }
+ //! Set how many blocks there are horizontally
+ void SetXNumBlocks(const int xn){m_x_num_blocks=xn;}
- //! Set the Profile
- void SetProfile(unsigned int profile)
- {
- m_profile = profile;
- }
+ //! Set how many blocks there are vertically
+ void SetYNumBlocks(const int yn){m_y_num_blocks=yn;}
- //! Set the Level
- void SetLevel(unsigned int level)
- {
- m_level = level;
- }
+ //! Set the block sizes for all SB splitting levels given these prototype block sizes for level=2
+ void SetBlockSizes(const OLBParams& olbparams , const ChromaFormat cformat);
-private:
- //! Major Version
- unsigned int m_major_ver;
- //! Minor Version
- unsigned int m_minor_ver;
- //! Profile
- unsigned int m_profile;
- //! Level
- unsigned int m_level;
-};
-
-//! Structure to hold code block sizes when spatial partitioning is used
-class CodeBlocks
-{
-public:
- //! Default Constructor
- CodeBlocks() : m_hblocks(1), m_vblocks(1)
- {}
-
- //! Constructor
- CodeBlocks(unsigned int hblocks, unsigned int vblocks) :
- m_hblocks(hblocks),
- m_vblocks(vblocks)
- {}
-
- // Gets
- //! Return the number of horizontal code blocks
- unsigned int HorizontalCodeBlocks() const
- {
- return m_hblocks;
- }
- //! Return the number of vertical code blocks
- unsigned int VerticalCodeBlocks() const
- {
- return m_vblocks;
- }
- // Sets
- //! Set the number of horizontal code blocks
- void SetHorizontalCodeBlocks(unsigned int hblocks)
- {
- m_hblocks = hblocks;
- }
- //! Set the number of vertical code blocks
- void SetVerticalCodeBlocks(unsigned int vblocks)
- {
- m_vblocks = vblocks;
- }
-private:
- //! Number of Horizontal code blocks
- unsigned int m_hblocks;
- //! Number of Vertical code blocks
- unsigned int m_vblocks;
-};
-
-//! Structure to hold motion parameters when motion comp is used
-class PicturePredParams
-{
-public:
- PicturePredParams():
- m_lbparams(3),
- m_cbparams(3) {}
+ //! Set block level luma params
+ void SetLumaBlockParams(const OLBParams& olbparams) {m_lbparams[2] = olbparams;}
- //! Return the global motion flag used for encoding/decoding
- bool UsingGlobalMotion() const
- {
- return m_use_global_motion;
- }
+ //! Set the number of accuracy bits for motion vectors
+ void SetMVPrecision(const MVPrecisionType p)
+ {
+ // Assert in debug mode. Maybe we should throw an exception???
+ TESTM((p >=0 && p <=3), "Motion precision value in range 0..3");
+ m_mv_precision = p;
+ }
- //! Return the number of picture weight precision bits
- unsigned int PictureWeightsBits() const
- {
- return m_picture_weights_bits;
- }
+ void SetMVPrecision(const MVPrecisionType p) const
+ {
+ // Assert in debug mode. Maybe we should throw an exception???
+ TESTM((p >=0 && p <=3), "Motion precision value in range 0..3");
+ m_mv_precision = p;
+ }
- //! Return the Ref1 weight
- int Ref1Weight() const
- {
- return m_ref1_weight;
- }
+ //! Set the wavelet filter used for picture (de)coding
+ void SetUsingGlobalMotion(bool gm) { m_use_global_motion=gm; }
- //! Return the Ref2 weight
- int Ref2Weight() const
- {
- return m_ref2_weight;
- }
+ //! Set the picture weight precision bits used for (de)coding
+ void SetPictureWeightsPrecision(unsigned int wt_prec) { m_picture_weights_bits=wt_prec; }
- bool CustomRefWeights()
- {
- return (m_picture_weights_bits != 1 ||
- m_ref1_weight != 1 ||
- m_ref2_weight != 1);
- }
+ //! Set the ref 1 picture weight
+ void SetRef1Weight(int wt) { m_ref1_weight=wt; }
- //! Return the number of superblocks horizontally
- int XNumSB() const
- {
- return m_x_num_sb;
- }
+ //! Set the ref 2 picture weight
+ void SetRef2Weight(int wt) { m_ref2_weight=wt; }
- //! Return the number of superblocks vertically
- int YNumSB() const
- {
- return m_y_num_sb;
- }
+ private:
- //! Return the number of blocks horizontally
- int XNumBlocks() const
- {
- return m_x_num_blocks;
- }
+ //! The number of superblocks horizontally
+ int m_x_num_sb;
- //! Returns the number of blocks vertically
- int YNumBlocks() const
- {
- return m_y_num_blocks;
- }
+ //! The number of superblocks verticaly
+ int m_y_num_sb;
- //! Return the Luma block parameters for each macroblock splitting level
- const OLBParams& LumaBParams(int n) const
- {
- return m_lbparams[n];
- }
+ //! The number of blocks horizontally
+ int m_x_num_blocks;
- //! Return the Chroma block parameters for each macroblock splitting level
- const OLBParams& ChromaBParams(int n) const
- {
- return m_cbparams[n];
- }
+ //! The number of blocks vertically
+ int m_y_num_blocks;
- //! Return the number of accuracy bits used for motion vectors
- MVPrecisionType MVPrecision() const
- {
- return m_mv_precision;
- }
+ OneDArray<OLBParams> m_lbparams;
- //! Set how many SBs there are horizontally
- void SetXNumSB(const int xn)
- {
- m_x_num_sb = xn;
- }
+ OneDArray<OLBParams> m_cbparams;
- //! Set how many SBs there are vertically
- void SetYNumSB(const int yn)
- {
- m_y_num_sb = yn;
- }
+ //! The precision of motion vectors (number of accuracy bits eg 1=half-pel accuracy)
+ mutable MVPrecisionType m_mv_precision;
- //! Set how many blocks there are horizontally
- void SetXNumBlocks(const int xn)
- {
- m_x_num_blocks = xn;
- }
+ //! picture predicion parameters - precision
+ unsigned int m_picture_weights_bits;
- //! Set how many blocks there are vertically
- void SetYNumBlocks(const int yn)
- {
- m_y_num_blocks = yn;
- }
+ //! picture predicion parameters - reference picture 1 weight
+ int m_ref1_weight;
- //! Set the block sizes for all SB splitting levels given these prototype block sizes for level=2
- void SetBlockSizes(const OLBParams& olbparams , const ChromaFormat cformat);
+ //! picture predicion parameters - reference picture 2 weight
+ int m_ref2_weight;
- //! Set block level luma params
- void SetLumaBlockParams(const OLBParams& olbparams)
- {
- m_lbparams[2] = olbparams;
- }
+ //! Global motion fields
+ bool m_use_global_motion;
- //! Set the number of accuracy bits for motion vectors
- void SetMVPrecision(const MVPrecisionType p)
- {
- // Assert in debug mode. Maybe we should throw an exception???
- TESTM((p >= 0 && p <= 3), "Motion precision value in range 0..3");
- m_mv_precision = p;
- }
+ };
- void SetMVPrecision(const MVPrecisionType p) const
+ //! Parameters common to coder and decoder operation
+ /*!
+ Parameters used throughout both the encoder and the decoder
+ */
+ class CodecParams
{
- // Assert in debug mode. Maybe we should throw an exception???
- TESTM((p >= 0 && p <= 3), "Motion precision value in range 0..3");
- m_mv_precision = p;
- }
+ public:
- //! Set the wavelet filter used for picture (de)coding
- void SetUsingGlobalMotion(bool gm)
- {
- m_use_global_motion = gm;
- }
+ //! Default constructor
+ CodecParams (const VideoFormat& video_format = VIDEO_FORMAT_CUSTOM,
+ PictureType ftype = INTRA_PICTURE,
+ unsigned int num_refs = 0,
+ bool set_defaults=true);
- //! Set the picture weight precision bits used for (de)coding
- void SetPictureWeightsPrecision(unsigned int wt_prec)
- {
- m_picture_weights_bits = wt_prec;
- }
+ ////////////////////////////////////////////////////////////////////
+ //NB: Assume default copy constructor, assignment = and destructor//
+ ////////////////////////////////////////////////////////////////////
- //! Set the ref 1 picture weight
- void SetRef1Weight(int wt)
- {
- m_ref1_weight = wt;
- }
+ // Gets ...
- //! Set the ref 2 picture weight
- void SetRef2Weight(int wt)
- {
- m_ref2_weight = wt;
- }
+ //! Returns the picture coding mode (independent of source format)
+ /*! Returns the picture coding mode (independent of source format)
+ * 0 = Frame coding (no quincunx)
+ * 1 = Field coding (no quincunx)
+ */
+ int PictureCodingMode() const {return m_pic_coding_mode;}
-private:
+ //! Returns true if the pictures are being coded as fields (mode 1 or 3)
+ bool FieldCoding() const { return (m_pic_coding_mode==1); }
- //! The number of superblocks horizontally
- int m_x_num_sb;
+ //! Returns true if the topmost field comes first in time when coding
+ bool TopFieldFirst() const {return m_topfieldfirst;}
- //! The number of superblocks verticaly
- int m_y_num_sb;
+ //! Return the picture/field luma width
+ int Xl() const {return m_xl;}
- //! The number of blocks horizontally
- int m_x_num_blocks;
+ //! Return the picture/field luma height
+ int Yl() const {return m_yl;}
- //! The number of blocks vertically
- int m_y_num_blocks;
+ //! Return the picture/field chroma width
+ int ChromaXl() const {return m_cxl;}
- OneDArray<OLBParams> m_lbparams;
+ //! Return the picture/field chroma height
+ int ChromaYl() const {return m_cyl;}
- OneDArray<OLBParams> m_cbparams;
+ //! Returns the luma depth
+ unsigned int LumaDepth() const { return m_luma_depth; }
- //! The precision of motion vectors (number of accuracy bits eg 1=half-pel accuracy)
- mutable MVPrecisionType m_mv_precision;
+ //! Returns the chroma depth
+ unsigned int ChromaDepth() const { return m_chroma_depth; }
- //! picture predicion parameters - precision
- unsigned int m_picture_weights_bits;
+ //! Return zero transform flag being used for picture (de)coding
+ bool ZeroTransform() const { return m_zero_transform; }
- //! picture predicion parameters - reference picture 1 weight
- int m_ref1_weight;
+ //! Return the wavelet filter currently being used for picture (de)coding
+ WltFilter TransformFilter() const { return m_wlt_filter; }
- //! picture predicion parameters - reference picture 2 weight
- int m_ref2_weight;
+ //! Return the transform depth being used for picture (de)coding
+ unsigned int TransformDepth() const { return m_wlt_depth; }
- //! Global motion fields
- bool m_use_global_motion;
+ //! Return multiple quantisers flag being used for picture (de)coding
+ CodeBlockMode GetCodeBlockMode() const { return m_cb_mode; }
-};
+ //! Return the spatial partitioning flag being used for picture (de)coding
+ bool SpatialPartition() const { return m_spatial_partition; }
-//! Parameters common to coder and decoder operation
-/*!
- Parameters used throughout both the encoder and the decoder
-*/
-class CodecParams
-{
-public:
+ //! Return the code blocks for a particular level
+ const CodeBlocks &GetCodeBlocks(unsigned int level) const;
- //! Default constructor
- CodecParams(const VideoFormat& video_format = VIDEO_FORMAT_CUSTOM,
- PictureType ftype = INTRA_PICTURE,
- unsigned int num_refs = 0,
- bool set_defaults = true);
+ //! Return the video format currently being used for picture (de)coding
+ VideoFormat GetVideoFormat() const { return m_video_format; }
- ////////////////////////////////////////////////////////////////////
- //NB: Assume default copy constructor, assignment = and destructor//
- ////////////////////////////////////////////////////////////////////
+ //! Return the picture prediction params
+ PicturePredParams& GetPicPredParams(){return m_picpredparams;}
- // Gets ...
+ //! Return the picture prediction params
+ const PicturePredParams& GetPicPredParams() const {return m_picpredparams;}
- //! Returns the picture coding mode (independent of source format)
- /*! Returns the picture coding mode (independent of source format)
- * 0 = Frame coding (no quincunx)
- * 1 = Field coding (no quincunx)
- */
- int PictureCodingMode() const
- {
- return m_pic_coding_mode;
- }
+ // ... and Sets
+ //! Sets whether input is coded as fields or quincunxially
+ void SetPictureCodingMode(int pic_coding){m_pic_coding_mode=pic_coding;}
- //! Returns true if the pictures are being coded as fields (mode 1 or 3)
- bool FieldCoding() const
- {
- return (m_pic_coding_mode == 1);
- }
+ //! Sets whether the topmost field comes first in time [NB: TBD since this duplicates metadata in the sequence header]
+ void SetTopFieldFirst(bool topf){m_topfieldfirst=topf;}
- //! Returns true if the topmost field comes first in time when coding
- bool TopFieldFirst() const
- {
- return m_topfieldfirst;
- }
+ //! Set the picture/field luma width
+ void SetXl(const int x){m_xl=x;}
- //! Return the picture/field luma width
- int Xl() const
- {
- return m_xl;
- }
+ //! Set the picture/field luma height
+ void SetYl(const int y){m_yl=y;}
- //! Return the picture/field luma height
- int Yl() const
- {
- return m_yl;
- }
+ //! Set the frame/field chroma width
+ void SetChromaXl(const int x){m_cxl=x;}
- //! Return the picture/field chroma width
- int ChromaXl() const
- {
- return m_cxl;
- }
+ //! Set the frame/field chroma height
+ void SetChromaYl(const int y){m_cyl=y;}
- //! Return the picture/field chroma height
- int ChromaYl() const
- {
- return m_cyl;
- }
+ //! Set Luma Depth
+ void SetLumaDepth(unsigned int luma_depth) { m_luma_depth = luma_depth; }
- //! Returns the luma depth
- unsigned int LumaDepth() const
- {
- return m_luma_depth;
- }
+ //! Set Chroma Depth
+ void SetChromaDepth(unsigned int chroma_depth) { m_chroma_depth = chroma_depth; }
- //! Returns the chroma depth
- unsigned int ChromaDepth() const
- {
- return m_chroma_depth;
- }
+ //! Set the zero transform flag being used for picture (de)coding
+ void SetZeroTransform(bool zero_transform) { m_zero_transform = zero_transform; }
- //! Return zero transform flag being used for picture (de)coding
- bool ZeroTransform() const
- {
- return m_zero_transform;
- }
+ //! Set the wavelet filter used for picture (de)coding
+ void SetTransformFilter(const WltFilter wf) { m_wlt_filter=wf; }
- //! Return the wavelet filter currently being used for picture (de)coding
- WltFilter TransformFilter() const
- {
- return m_wlt_filter;
- }
+ //! Set the wavelet filter used for picture (de)coding
+ void SetTransformFilter(unsigned int wf_idx);
- //! Return the transform depth being used for picture (de)coding
- unsigned int TransformDepth() const
- {
- return m_wlt_depth;
- }
+ //! Set the transform depth used for picture (de)coding and allocate for the code blocks array
+ void SetTransformDepth(unsigned int wd);
- //! Return multiple quantisers flag being used for picture (de)coding
- CodeBlockMode GetCodeBlockMode() const
- {
- return m_cb_mode;
- }
+ //! Set the multiple quantisers flag usedto picture (de)coding
+ void SetCodeBlockMode(unsigned int cb_mode);
- //! Return the spatial partitioning flag being used for picture (de)coding
- bool SpatialPartition() const
- {
- return m_spatial_partition;
- }
+ //! Set the spatial partition flag usedto picture (de)coding
+ void SetSpatialPartition(bool spatial_partition) { m_spatial_partition=spatial_partition; }
- //! Return the code blocks for a particular level
- const CodeBlocks &GetCodeBlocks(unsigned int level) const;
+ //! Set the number of code blocks for a particular level
+ void SetCodeBlocks(unsigned int level, unsigned int hblocks, unsigned int vblocks);
- //! Return the video format currently being used for picture (de)coding
- VideoFormat GetVideoFormat() const
- {
- return m_video_format;
- }
+ //! Set the video format used for picture (de)coding
+ void SetVideoFormat(const VideoFormat vd) { m_video_format=vd; }
- //! Return the picture prediction params
- PicturePredParams& GetPicPredParams()
- {
- return m_picpredparams;
- }
+ protected:
+ //! Return the Wavelet filter associated with the wavelet index
+ WltFilter TransformFilter (unsigned int wf_idx);
+ private:
- //! Return the picture prediction params
- const PicturePredParams& GetPicPredParams() const
- {
- return m_picpredparams;
- }
+ //! The picture prediction parameters
+ PicturePredParams m_picpredparams;
- // ... and Sets
- //! Sets whether input is coded as fields or quincunxially
- void SetPictureCodingMode(int pic_coding)
- {
- m_pic_coding_mode = pic_coding;
- }
+ //! The picture coding mode
+ int m_pic_coding_mode;
- //! Sets whether the topmost field comes first in time [NB: TBD since this duplicates metadata in the sequence header]
- void SetTopFieldFirst(bool topf)
- {
- m_topfieldfirst = topf;
- }
+ //! True if interlaced and top field is first in temporal order
+ bool m_topfieldfirst;
- //! Set the picture/field luma width
- void SetXl(const int x)
- {
- m_xl = x;
- }
+ //! The frame/field luma width
+ int m_xl;
- //! Set the picture/field luma height
- void SetYl(const int y)
- {
- m_yl = y;
- }
+ //! The frame/field luma height
+ int m_yl;
- //! Set the frame/field chroma width
- void SetChromaXl(const int x)
- {
- m_cxl = x;
- }
+ //! The frame/field chroma width
+ int m_cxl;
- //! Set the frame/field chroma height
- void SetChromaYl(const int y)
- {
- m_cyl = y;
- }
+ //! The frame/field chroma height
+ int m_cyl;
- //! Set Luma Depth
- void SetLumaDepth(unsigned int luma_depth)
- {
- m_luma_depth = luma_depth;
- }
+ //! Luma depth - number of bits required for lumz
+ unsigned int m_luma_depth;
- //! Set Chroma Depth
- void SetChromaDepth(unsigned int chroma_depth)
- {
- m_chroma_depth = chroma_depth;
- }
+ //! chroma depth - number of bits required for luma
+ unsigned int m_chroma_depth;
- //! Set the zero transform flag being used for picture (de)coding
- void SetZeroTransform(bool zero_transform)
- {
- m_zero_transform = zero_transform;
- }
+ //! The video format being used
+ VideoFormat m_video_format;
- //! Set the wavelet filter used for picture (de)coding
- void SetTransformFilter(const WltFilter wf)
- {
- m_wlt_filter = wf;
- }
+ //! Zero transform flag
+ bool m_zero_transform;
- //! Set the wavelet filter used for picture (de)coding
- void SetTransformFilter(unsigned int wf_idx);
+ //! The wavelet filter being used
+ WltFilter m_wlt_filter;
- //! Set the transform depth used for picture (de)coding and allocate for the code blocks array
- void SetTransformDepth(unsigned int wd);
+ //! Wavelet depth
+ unsigned int m_wlt_depth;
- //! Set the multiple quantisers flag usedto picture (de)coding
- void SetCodeBlockMode(unsigned int cb_mode);
+ //! Code block mode
+ CodeBlockMode m_cb_mode;
- //! Set the spatial partition flag usedto picture (de)coding
- void SetSpatialPartition(bool spatial_partition)
- {
- m_spatial_partition = spatial_partition;
- }
+ //! Spatial partitioning flag
+ bool m_spatial_partition;
- //! Set the number of code blocks for a particular level
- void SetCodeBlocks(unsigned int level, unsigned int hblocks, unsigned int vblocks);
+ //! Code block array. Number of entries is m_wlt_depth+1
+ OneDArray<CodeBlocks> m_cb;
+ };
- //! Set the video format used for picture (de)coding
- void SetVideoFormat(const VideoFormat vd)
+ //! Parameters for the encoding process
+ /*!
+ Parameters for the encoding process, derived from CodecParams.
+ */
+ class EncoderParams: public CodecParams
{
- m_video_format = vd;
- }
+ //codec params plus parameters relating solely to the operation of the encoder
-protected:
- //! Return the Wavelet filter associated with the wavelet index
- WltFilter TransformFilter(unsigned int wf_idx);
-private:
+ public:
+ //! Default constructor
+ EncoderParams(const VideoFormat& video_format,
+ PictureType ftype = INTER_PICTURE,
+ unsigned int num_refs = 2,
+ bool set_defaults=true);
- //! The picture prediction parameters
- PicturePredParams m_picpredparams;
+ ////////////////////////////////////////////////////////////////////
+ //NB: Assume default copy constructor, assignment = and destructor//
+ //This means pointers are copied, not the objects they point to.////
+ ////////////////////////////////////////////////////////////////////
- //! The picture coding mode
- int m_pic_coding_mode;
+ // Gets ...
- //! True if interlaced and top field is first in temporal order
- bool m_topfieldfirst;
- //! The frame/field luma width
- int m_xl;
+ //! Returns true if we're operating verbosely, false otherwise
+ bool Verbose() const {return m_verbose;}
- //! The frame/field luma height
- int m_yl;
+ //! Returns a flag indicating that we're doing local decoding
+ bool LocalDecode() const {return m_loc_decode;}
- //! The frame/field chroma width
- int m_cxl;
+ //! Get whether we're doing lossless coding
+ bool Lossless() const {return m_lossless;}
- //! The frame/field chroma height
- int m_cyl;
+ //! Get whether we're doing full-search motion estimation
+ bool FullSearch() const {return m_full_search; }
- //! Luma depth - number of bits required for lumz
- unsigned int m_luma_depth;
+ //! Get the horizontal search range for full-search motion estimation
+ int XRangeME() const {return m_x_range_me;}
- //! chroma depth - number of bits required for luma
- unsigned int m_chroma_depth;
+ //! Get the vertical search range for full-search motion estimation
+ int YRangeME() const {return m_y_range_me;}
- //! The video format being used
- VideoFormat m_video_format;
+ //! Get whether we're doing combined component motion estimation
+ bool CombinedME() const {return m_combined_me; }
- //! Zero transform flag
- bool m_zero_transform;
+ //! Get the quality factor
+ float Qf() const {return m_qf;}
- //! The wavelet filter being used
- WltFilter m_wlt_filter;
+ //! Return the nominal number of L1 pictures before the next I picture
+ /*!
+ Return the nominal number of L1 pictures before the next I picture. Can be
+ overridden by I-picture insertion
- //! Wavelet depth
- unsigned int m_wlt_depth;
+ */
+ int NumL1() const {return m_num_L1;}
- //! Code block mode
- CodeBlockMode m_cb_mode;
+ //! Return the separation between L1 pictures (and between L1 and I pictures)
+ int L1Sep() const {return m_L1_sep;}
- //! Spatial partitioning flag
- bool m_spatial_partition;
+ //! Return the amount we're weighting noise in the U component
+ float UFactor() const {return m_ufactor;}
- //! Code block array. Number of entries is m_wlt_depth+1
- OneDArray<CodeBlocks> m_cb;
-};
+ //! Return the amount we're weighting noise in the V component
+ float VFactor() const {return m_vfactor;}
-//! Parameters for the encoding process
-/*!
- Parameters for the encoding process, derived from CodecParams.
- */
-class EncoderParams: public CodecParams
-{
- //codec params plus parameters relating solely to the operation of the encoder
+ //! Return the number of cycles per degree at the nominal viewing distance for the raster
+ float CPD() const {return m_cpd;}
-public:
- //! Default constructor
- EncoderParams(const VideoFormat& video_format,
- PictureType ftype = INTER_PICTURE,
- unsigned int num_refs = 2,
- bool set_defaults = true);
+ //! Return what prefiltering is in place
+ PrefilterType Prefilter() const {return m_prefilter;}
- ////////////////////////////////////////////////////////////////////
- //NB: Assume default copy constructor, assignment = and destructor//
- //This means pointers are copied, not the objects they point to.////
- ////////////////////////////////////////////////////////////////////
+ //! Return the prefiltering strength
+ int PrefilterStrength() const {return m_prefilter_strength;}
- // Gets ...
+ //! Return the Lagrangian parameter to be used for I pictures
+ float ILambda() const {return m_I_lambda;}
+ //! Return the Lagrangian parameter to be used for L1 pictures
+ float L1Lambda() const {return m_L1_lambda;}
- //! Returns true if we're operating verbosely, false otherwise
- bool Verbose() const
- {
- return m_verbose;
- }
+ //! Return the Lagrangian parameter to be used for L2 pictures
+ float L2Lambda() const {return m_L2_lambda;}
- //! Returns a flag indicating that we're doing local decoding
- bool LocalDecode() const
- {
- return m_loc_decode;
- }
+ //! Return the Lagrangian ME parameter to be used for L1 pictures
+ float L1MELambda() const {return m_L1_me_lambda;}
- //! Get whether we're doing lossless coding
- bool Lossless() const
- {
- return m_lossless;
- }
+ //! Return the Lagrangian ME parameter to be used for L2 pictures
+ float L2MELambda() const {return m_L2_me_lambda;}
- //! Get whether we're doing full-search motion estimation
- bool FullSearch() const
- {
- return m_full_search;
- }
+ //! Return the size of the GOP
+ int GOPLength() const;
- //! Get the horizontal search range for full-search motion estimation
- int XRangeME() const
- {
- return m_x_range_me;
- }
+ //! Return the output path to be used for storing diagnositic data
+ char * OutputPath() const {return ( char* ) m_output_path.c_str();}
- //! Get the vertical search range for full-search motion estimation
- int YRangeME() const
- {
- return m_y_range_me;
- }
+ //! Return a reference to the entropy factors
+ const EntropyCorrector& EntropyFactors() const {return *m_ent_correct;}
- //! Get whether we're doing combined component motion estimation
- bool CombinedME() const
- {
- return m_combined_me;
- }
+ //! Return a reference to the entropy factors - we need to be able to change the values of the entropy factors in situ
+ EntropyCorrector& EntropyFactors() {return *m_ent_correct;}
- //! Get the quality factor
- float Qf() const
- {
- return m_qf;
- }
+ //! Return the Wavelet filter to be used for intra pictures
+ WltFilter IntraTransformFilter() { return m_intra_wltfilter; }
- //! Return the nominal number of L1 pictures before the next I picture
- /*!
- Return the nominal number of L1 pictures before the next I picture. Can be
- overridden by I-picture insertion
+ //! Return the Wavelet filter to be used for Inter pictures
+ WltFilter InterTransformFilter() { return m_inter_wltfilter; }
- */
- int NumL1() const
- {
- return m_num_L1;
- }
+ //! Return the Target Bit Rate in kbps
+ int TargetRate() {return m_target_rate;}
- //! Return the separation between L1 pictures (and between L1 and I pictures)
- int L1Sep() const
- {
- return m_L1_sep;
- }
+ //! Return true if using Arithmetic coding
+ bool UsingAC() const {return m_using_ac;}
- //! Return the amount we're weighting noise in the U component
- float UFactor() const
- {
- return m_ufactor;
- }
+ // ... and Sets
- //! Return the amount we're weighting noise in the V component
- float VFactor() const
- {
- return m_vfactor;
- }
+ //! Sets verbosity on or off
+ void SetVerbose(bool v){m_verbose=v;}
- //! Return the number of cycles per degree at the nominal viewing distance for the raster
- float CPD() const
- {
- return m_cpd;
- }
+ //! Sets a flag indicating that we're producing a locally decoded o/p
+ void SetLocalDecode( const bool decode ){m_loc_decode=decode;}
- //! Return what prefiltering is in place
- PrefilterType Prefilter() const
- {
- return m_prefilter;
- }
+ //! Set whether we're doing lossless coding
+ void SetLossless(const bool l){m_lossless = l;}
- //! Return the prefiltering strength
- int PrefilterStrength() const
- {
- return m_prefilter_strength;
- }
+ //! Set whether we're doing full-search motion estimation
+ void SetFullSearch(const bool fs){m_full_search = fs;}
- //! Return the Lagrangian parameter to be used for I pictures
- float ILambda() const
- {
- return m_I_lambda;
- }
+ //! Set whether we're doing combined component motion estimation
+ void SetCombinedME(const bool cme){m_combined_me = cme;}
- //! Return the Lagrangian parameter to be used for L1 pictures
- float L1Lambda() const
- {
- return m_L1_lambda;
- }
+ //! Set the horizontal search range for full-search motion estimation
+ void SetXRangeME(const int xr){m_x_range_me = xr;}
- //! Return the Lagrangian parameter to be used for L2 pictures
- float L2Lambda() const
- {
- return m_L2_lambda;
- }
+ //! Set the vertical search range for full-search motion estimation
+ void SetYRangeME(const int yr){m_y_range_me = yr;}
- //! Return the Lagrangian ME parameter to be used for L1 pictures
- float L1MELambda() const
- {
- return m_L1_me_lambda;
- }
+ //! Set the quality factor
+ void SetQf(const float qfac){ m_qf=qfac; CalcLambdas(m_qf); }
- //! Return the Lagrangian ME parameter to be used for L2 pictures
- float L2MELambda() const
- {
- return m_L2_me_lambda;
- }
+ //! Set the nominal number of L1 pictures between I pictures
+ void SetNumL1(const int nl){m_num_L1=nl;}
- //! Return the size of the GOP
- int GOPLength() const;
+ //! Set the separation between L1 pictures
+ void SetL1Sep(const int lsep){m_L1_sep=lsep;}
- //! Return the output path to be used for storing diagnositic data
- char * OutputPath() const
- {
- return (char*) m_output_path.c_str();
- }
+ //! Set the amount to weight noise in the U component
+ void SetUFactor(const float uf){m_ufactor=uf;}
- //! Return a reference to the entropy factors
- const EntropyCorrector& EntropyFactors() const
- {
- return *m_ent_correct;
- }
+ //! Set the amount to weight noise in the V component
+ void SetVFactor(const float vf){m_vfactor=vf;}
- //! Return a reference to the entropy factors - we need to be able to change the values of the entropy factors in situ
- EntropyCorrector& EntropyFactors()
- {
- return *m_ent_correct;
- }
+ //! Set the number of cycles per degree at the nominal viewing distance
+ void SetCPD(const float cpd){m_cpd=cpd;}
- //! Return the Wavelet filter to be used for intra pictures
- WltFilter IntraTransformFilter()
- {
- return m_intra_wltfilter;
- }
+ //! Set denoising value - true or false
+ void SetPrefilter(const PrefilterType pf, const int str){m_prefilter=pf;
+ m_prefilter_strength=str;}
- //! Return the Wavelet filter to be used for Inter pictures
- WltFilter InterTransformFilter()
- {
- return m_inter_wltfilter;
- }
+ //! Set the output path to be used for diagnostic data
+ void SetOutputPath(const char * op){ m_output_path = op; }
- //! Return the Target Bit Rate in kbps
- int TargetRate()
- {
- return m_target_rate;
- }
+ //! Sets the entropy factors - TBD: set this up in a constructor and pass encoder params around entirely by reference
+ void SetEntropyFactors(EntropyCorrector* entcorrect){m_ent_correct=entcorrect;}
+ //! Set the Wavelet filter to be used for intra pictures
+ void SetIntraTransformFilter(unsigned int wf_idx);
- //! Return true if using Arithmetic coding
- bool UsingAC() const
- {
- return m_using_ac;
- }
+ //! Set the Wavelet filter to be used for inter pictures
+ void SetInterTransformFilter(unsigned int wf_idx);
- // ... and Sets
+ //! Set the Wavelet filter to be used for intra pictures
+ void SetIntraTransformFilter(WltFilter wf) { m_intra_wltfilter = wf; }
+
+ //! Set the number of code blocks for all levels
+ void SetUsualCodeBlocks(const PictureType& ftype);
- //! Sets verbosity on or off
- void SetVerbose(bool v)
- {
- m_verbose = v;
- }
+ //! Set the Wavelet filter to be used for inter pictures
+ void SetInterTransformFilter(WltFilter wf) { m_inter_wltfilter = wf; }
- //! Sets a flag indicating that we're producing a locally decoded o/p
- void SetLocalDecode(const bool decode)
- {
- m_loc_decode = decode;
- }
+ //! Set the target bit rate
+ void SetTargetRate(const int rate){m_target_rate = rate;}
- //! Set whether we're doing lossless coding
- void SetLossless(const bool l)
- {
- m_lossless = l;
- }
+ //! Set the arithmetic coding flag
+ void SetUsingAC(bool using_ac) {m_using_ac = using_ac;}
+ private:
- //! Set whether we're doing full-search motion estimation
- void SetFullSearch(const bool fs)
- {
- m_full_search = fs;
- }
+ //! Calculate the Lagrangian parameters from the quality factor
+ void CalcLambdas(const float qf);
- //! Set whether we're doing combined component motion estimation
- void SetCombinedME(const bool cme)
- {
- m_combined_me = cme;
- }
+ private:
- //! Set the horizontal search range for full-search motion estimation
- void SetXRangeME(const int xr)
- {
- m_x_range_me = xr;
- }
+ //! Code/decode with commentary if true
+ bool m_verbose;
- //! Set the vertical search range for full-search motion estimation
- void SetYRangeME(const int yr)
- {
- m_y_range_me = yr;
- }
+ //! Flag indicating we're doing local decoding
+ bool m_loc_decode;
- //! Set the quality factor
- void SetQf(const float qfac)
- {
- m_qf = qfac;
- CalcLambdas(m_qf);
- }
+ //! A flag indicating we're doing lossless coding
+ bool m_lossless;
- //! Set the nominal number of L1 pictures between I pictures
- void SetNumL1(const int nl)
- {
- m_num_L1 = nl;
- }
+ //! A flag indicating whether we're doing full-search block matching
+ bool m_full_search;
- //! Set the separation between L1 pictures
- void SetL1Sep(const int lsep)
- {
- m_L1_sep = lsep;
- }
+ //! A flag indicating whether we're doing combined component motion estimation
+ bool m_combined_me;
- //! Set the amount to weight noise in the U component
- void SetUFactor(const float uf)
- {
- m_ufactor = uf;
- }
+ //! The horizontal range for full-search block matching
+ int m_x_range_me;
- //! Set the amount to weight noise in the V component
- void SetVFactor(const float vf)
- {
- m_vfactor = vf;
- }
+ //! The vertical range for full-search block matching
+ int m_y_range_me;
- //! Set the number of cycles per degree at the nominal viewing distance
- void SetCPD(const float cpd)
- {
- m_cpd = cpd;
- }
+ //! Quality factor
+ float m_qf;
- //! Set denoising value - true or false
- void SetPrefilter(const PrefilterType pf, const int str)
- {
- m_prefilter = pf;
- m_prefilter_strength = str;
- }
+ //! Number of L1 pictures before next I picture
+ int m_num_L1;
- //! Set the output path to be used for diagnostic data
- void SetOutputPath(const char * op)
- {
- m_output_path = op;
- }
+ //! Separation between L1 pictures
+ int m_L1_sep;
- //! Sets the entropy factors - TBD: set this up in a constructor and pass encoder params around entirely by reference
- void SetEntropyFactors(EntropyCorrector* entcorrect)
- {
- m_ent_correct = entcorrect;
- }
- //! Set the Wavelet filter to be used for intra pictures
- void SetIntraTransformFilter(unsigned int wf_idx);
-
- //! Set the Wavelet filter to be used for inter pictures
- void SetInterTransformFilter(unsigned int wf_idx);
+ //! factor for weighting U component quantisation errors
+ float m_ufactor;
- //! Set the Wavelet filter to be used for intra pictures
- void SetIntraTransformFilter(WltFilter wf)
- {
- m_intra_wltfilter = wf;
- }
+ //! factor for weighting V component quantisation errors
+ float m_vfactor;
- //! Set the number of code blocks for all levels
- void SetUsualCodeBlocks(const PictureType& ftype);
+ //! Cycles per degree assumed for viewing the video
+ float m_cpd;
- //! Set the Wavelet filter to be used for inter pictures
- void SetInterTransformFilter(WltFilter wf)
- {
- m_inter_wltfilter = wf;
- }
-
- //! Set the target bit rate
- void SetTargetRate(const int rate)
- {
- m_target_rate = rate;
- }
-
- //! Set the arithmetic coding flag
- void SetUsingAC(bool using_ac)
- {
- m_using_ac = using_ac;
- }
-private:
+ //! Indicator for prefiltering
+ PrefilterType m_prefilter;
- //! Calculate the Lagrangian parameters from the quality factor
- void CalcLambdas(const float qf);
+ //! Prefiltering strength
+ int m_prefilter_strength;
-private:
+ //! Lagrangian parameter for Intra picture coding
+ float m_I_lambda;
- //! Code/decode with commentary if true
- bool m_verbose;
+ //! Lagrangian parameter for L1 picture coding
+ float m_L1_lambda;
- //! Flag indicating we're doing local decoding
- bool m_loc_decode;
+ //! Lagrangian parameter for L2 picture coding
+ float m_L2_lambda;
- //! A flag indicating we're doing lossless coding
- bool m_lossless;
+ //! Lagrangian param for L1 motion estimation
+ float m_L1_me_lambda;
- //! A flag indicating whether we're doing full-search block matching
- bool m_full_search;
+ //! Lagrangian param for L2 motion estimation
+ float m_L2_me_lambda;
- //! A flag indicating whether we're doing combined component motion estimation
- bool m_combined_me;
+ //! Correction factors for quantiser selection
+ EntropyCorrector* m_ent_correct;
- //! The horizontal range for full-search block matching
- int m_x_range_me;
+ //! Output file path
+ std::string m_output_path;
- //! The vertical range for full-search block matching
- int m_y_range_me;
+ //! Wavelet filter for Intra pictures
+ WltFilter m_intra_wltfilter;
- //! Quality factor
- float m_qf;
+ //! Wavelet filter for Inter pictures
+ WltFilter m_inter_wltfilter;
- //! Number of L1 pictures before next I picture
- int m_num_L1;
+ //! Target bit rate
+ int m_target_rate;
- //! Separation between L1 pictures
- int m_L1_sep;
+ //! Arithmetic coding flag
+ bool m_using_ac;
- //! factor for weighting U component quantisation errors
- float m_ufactor;
-
- //! factor for weighting V component quantisation errors
- float m_vfactor;
-
- //! Cycles per degree assumed for viewing the video
- float m_cpd;
-
- //! Indicator for prefiltering
- PrefilterType m_prefilter;
-
- //! Prefiltering strength
- int m_prefilter_strength;
-
- //! Lagrangian parameter for Intra picture coding
- float m_I_lambda;
-
- //! Lagrangian parameter for L1 picture coding
- float m_L1_lambda;
-
- //! Lagrangian parameter for L2 picture coding
- float m_L2_lambda;
-
- //! Lagrangian param for L1 motion estimation
- float m_L1_me_lambda;
-
- //! Lagrangian param for L2 motion estimation
- float m_L2_me_lambda;
+ };
- //! Correction factors for quantiser selection
- EntropyCorrector* m_ent_correct;
+ //! Parameters for the decoding process
+ /*!
+ Parameters for the decoding process. Derived from CodecParams.
+ */
+ class DecoderParams: public CodecParams
+ {
+ public:
+ //! Default constructor
+ DecoderParams(const VideoFormat& video_format = VIDEO_FORMAT_CIF, PictureType ftype=INTRA_PICTURE, unsigned int num_refs = 0, bool set_defaults = false);
- //! Output file path
- std::string m_output_path;
+ //! Returns true if we're operating verbosely, false otherwise
+ bool Verbose() const {return m_verbose;}
- //! Wavelet filter for Intra pictures
- WltFilter m_intra_wltfilter;
+ //! Sets verbosity on or off
+ void SetVerbose(bool v){m_verbose=v;}
- //! Wavelet filter for Inter pictures
- WltFilter m_inter_wltfilter;
+ ////////////////////////////////////////////////////////////////////
+ //NB: Assume default copy constructor, assignment = and destructor//
+ //This means pointers are copied, not the objects they point to.////
+ ////////////////////////////////////////////////////////////////////
- //! Target bit rate
- int m_target_rate;
- //! Arithmetic coding flag
- bool m_using_ac;
+ private:
-};
+ //! Code/decode with commentary if true
+ bool m_verbose;
-//! Parameters for the decoding process
-/*!
- Parameters for the decoding process. Derived from CodecParams.
- */
-class DecoderParams: public CodecParams
-{
-public:
- //! Default constructor
- DecoderParams(const VideoFormat& video_format = VIDEO_FORMAT_CIF, PictureType ftype = INTRA_PICTURE, unsigned int num_refs = 0, bool set_defaults = false);
+ };
- //! Returns true if we're operating verbosely, false otherwise
- bool Verbose() const
+ //! A simple bounds checking function, very useful in a number of places
+ inline ValueType BChk(const ValueType &num, const ValueType &max)
{
- return m_verbose;
+ if(num < 0) return 0;
+ else if(num >= max) return max-1;
+ else return num;
}
- //! Sets verbosity on or off
- void SetVerbose(bool v)
+ //! Class for encapsulating quantiser data
+ class QuantiserLists
{
- m_verbose = v;
- }
-
- ////////////////////////////////////////////////////////////////////
- //NB: Assume default copy constructor, assignment = and destructor//
- //This means pointers are copied, not the objects they point to.////
- ////////////////////////////////////////////////////////////////////
+ public:
+ //! Default constructor
+ QuantiserLists();
+ //! Returns 4 times the quantisation factor
+ inline int QuantFactor4( const int index ) const {return m_qflist4[index]; }
-private:
+ //! Returns the intra Picture quantisation offset for non-zero values
+ inline int IntraQuantOffset4( const int index ) const {return m_intra_offset4[index]; }
+ //! Returns the inter Picture quantisation offset for non-zero values
+ inline int InterQuantOffset4( const int index ) const {return m_inter_offset4[index]; }
- //! Code/decode with commentary if true
- bool m_verbose;
+ //! Returns the maximum quantiser index supported
+ inline int MaxQuantIndex() const {return m_max_qindex; }
-};
-//! A simple bounds checking function, very useful in a number of places
-inline ValueType BChk(const ValueType &num, const ValueType &max)
-{
- if(num < 0) return 0;
- else if(num >= max) return max - 1;
- else return num;
-}
-
-//! Class for encapsulating quantiser data
-class QuantiserLists
-{
-public:
- //! Default constructor
- QuantiserLists();
+ private:
+ unsigned int m_max_qindex;
+ OneDArray<int> m_qflist4;
+ OneDArray<int> m_intra_offset4;
+ OneDArray<int> m_inter_offset4;
- //! Returns 4 times the quantisation factor
- inline int QuantFactor4(const int index) const
- {
- return m_qflist4[index];
- }
-
- //! Returns the intra Picture quantisation offset for non-zero values
- inline int IntraQuantOffset4(const int index) const
- {
- return m_intra_offset4[index];
- }
- //! Returns the inter Picture quantisation offset for non-zero values
- inline int InterQuantOffset4(const int index) const
- {
- return m_inter_offset4[index];
- }
-
- //! Returns the maximum quantiser index supported
- inline int MaxQuantIndex() const
- {
- return m_max_qindex;
- }
-
-
-private:
- unsigned int m_max_qindex;
- OneDArray<int> m_qflist4;
- OneDArray<int> m_intra_offset4;
- OneDArray<int> m_inter_offset4;
-
-};
+ };
-//! A constant list of the quantisers being used in Dirac
-static const QuantiserLists dirac_quantiser_lists;
+ //! A constant list of the quantisers being used in Dirac
+ static const QuantiserLists dirac_quantiser_lists;
} // namespace dirac
diff --git a/src/filters/parser/DiracSplitter/libdirac/libdirac_common/common_types.h b/src/filters/parser/DiracSplitter/libdirac/libdirac_common/common_types.h
index ab4fd8998..ef7d7a4a6 100644
--- a/src/filters/parser/DiracSplitter/libdirac/libdirac_common/common_types.h
+++ b/src/filters/parser/DiracSplitter/libdirac/libdirac_common/common_types.h
@@ -50,59 +50,53 @@
#ifdef __cplusplus
extern "C" {
#endif
- /*
- * Some basic enumeration types used throughout the codec and by end user ...//
- */
-
- /*! Types of chroma formatting (formatNK=format not known) */
- typedef enum {
- format444, format422, format420, formatNK
- }
- ChromaFormat;
-
- /*! Types of Wavelet filters supported. filterNK - not known) */
- typedef enum
- {
- DD9_7 = 0, /* Deslauriers-Dubuc (9,7) */
- LEGALL5_3, /* LeGall (5,3) */
- DD13_7, /* Deslauriers-Dubuc (13,7) */
- HAAR0, /* Haar, no shift per level*/
- HAAR1, /* Haar, one shift per level*/
- FIDELITY, /* Fidelity wavelet */
- DAUB9_7, /* Integer approximation to Daubechies 97 */
- filterNK
- } WltFilter;
-
- /*! Enumerated type that defines prefiltering types supported by the
- encoder. */
- typedef enum
- {
- NO_PF = 0,
- DIAGLP,
- RECTLP,
- CWM
- } PrefilterType;
-
- static const int NUM_WLT_FILTERS = 8;
-
- /*! Types of picture */
- typedef enum
- {
- INTRA_PICTURE = 0,
+/*
+* Some basic enumeration types used throughout the codec and by end user ...//
+*/
+
+/*! Types of chroma formatting (formatNK=format not known) */
+typedef enum { format444, format422, format420, formatNK } ChromaFormat;
+
+/*! Types of Wavelet filters supported. filterNK - not known) */
+typedef enum
+{
+ DD9_7=0, /* Deslauriers-Dubuc (9,7) */
+ LEGALL5_3, /* LeGall (5,3) */
+ DD13_7, /* Deslauriers-Dubuc (13,7) */
+ HAAR0, /* Haar, no shift per level*/
+ HAAR1, /* Haar, one shift per level*/
+ FIDELITY, /* Fidelity wavelet */
+ DAUB9_7, /* Integer approximation to Daubechies 97 */
+ filterNK
+} WltFilter;
+
+/*! Enumerated type that defines prefiltering types supported by the
+ encoder. */
+typedef enum
+{
+ NO_PF = 0,
+ DIAGLP,
+ RECTLP,
+ CWM
+} PrefilterType;
+
+static const int NUM_WLT_FILTERS = 8;
+
+/*! Types of picture */
+typedef enum {
+ INTRA_PICTURE=0,
INTER_PICTURE
} PictureType;
- /*! Types of referencing */
- typedef enum
- {
- REFERENCE_PICTURE = 0,
+/*! Types of referencing */
+typedef enum {
+ REFERENCE_PICTURE=0,
NON_REFERENCE_PICTURE
- } ReferenceType;
+} ReferenceType;
- /*! Types for video-format */
- typedef enum
- {
- VIDEO_FORMAT_CUSTOM = 0,
+/*! Types for video-format */
+typedef enum {
+ VIDEO_FORMAT_CUSTOM=0,
VIDEO_FORMAT_QSIF525,
VIDEO_FORMAT_QCIF,
VIDEO_FORMAT_SIF525,
@@ -124,96 +118,89 @@ extern "C" {
VIDEO_FORMAT_UHDTV_8K60,
VIDEO_FORMAT_UHDTV_8K50,
VIDEO_FORMAT_UNDEFINED
- } VideoFormat;
-
- /*! Types of Colour primaries */
- typedef enum
- {
- CP_HDTV_COMP_INTERNET = 0,
- CP_SDTV_525,
- CP_SDTV_625,
- CP_DCINEMA,
- CP_UNDEF
- } ColourPrimaries;
-
- /*! Types of Colour Matrices */
- typedef enum
- {
- CM_HDTV_COMP_INTERNET = 0,
- CM_SDTV,
- CM_REVERSIBLE,
- CM_UNDEF
- } ColourMatrix;
-
- /*! Types of Transfer functions */
- typedef enum
- {
- TF_TV = 0,
- TF_EXT_GAMUT,
- TF_LINEAR,
- TF_DCINEMA,
- TF_UNDEF
- } TransferFunction;
-
- /*! Types of Picture-rate */
- typedef enum
- {
- FRAMERATE_CUSTOM = 0,
- FRAMERATE_23p97_FPS,
- FRAMERATE_24_FPS,
- FRAMERATE_25_FPS,
- FRAMERATE_29p97_FPS,
- FRAMERATE_30_FPS,
- FRAMERATE_50_FPS,
- FRAMERATE_59p94_FPS,
- FRAMERATE_60_FPS,
- FRAMERATE_14p98_FPS,
- FRAMERATE_12p5_FPS,
- FRAMERATE_UNDEFINED
- } FrameRateType;
-
- /*! Types of Aspect Ratio */
- typedef enum
- {
- PIXEL_ASPECT_RATIO_CUSTOM = 0,
- PIXEL_ASPECT_RATIO_1_1,
- PIXEL_ASPECT_RATIO_10_11,
- PIXEL_ASPECT_RATIO_12_11,
- PIXEL_ASPECT_RATIO_40_33,
- PIXEL_ASPECT_RATIO_16_11,
- PIXEL_ASPECT_RATIO_4_3,
- PIXEL_ASPECT_RATIO_UNDEFINED
- } PixelAspectRatioType;
-
-
- /*! Types of signal range */
- typedef enum
- {
- SIGNAL_RANGE_CUSTOM = 0,
- SIGNAL_RANGE_8BIT_FULL,
- SIGNAL_RANGE_8BIT_VIDEO,
- SIGNAL_RANGE_10BIT_VIDEO,
- SIGNAL_RANGE_12BIT_VIDEO,
- SIGNAL_RANGE_UNDEFINED
- } SignalRangeType;
-
- /*! Types of motion-vector precision */
- typedef enum
- {
- MV_PRECISION_PIXEL = 0,
- MV_PRECISION_HALF_PIXEL,
- MV_PRECISION_QUARTER_PIXEL,
- MV_PRECISION_EIGHTH_PIXEL,
- MV_PRECISION_UNDEFINED
- } MVPrecisionType;
-
- /*! Type of quantiser modes when spatial partitioning is enabled */
- typedef enum
- {
- QUANT_SINGLE,
- QUANT_MULTIPLE,
- QUANT_UNDEF
- } CodeBlockMode;
+} VideoFormat;
+
+/*! Types of Colour primaries */
+typedef enum {
+ CP_HDTV_COMP_INTERNET=0,
+ CP_SDTV_525,
+ CP_SDTV_625,
+ CP_DCINEMA,
+ CP_UNDEF
+}ColourPrimaries;
+
+/*! Types of Colour Matrices */
+typedef enum {
+ CM_HDTV_COMP_INTERNET=0,
+ CM_SDTV,
+ CM_REVERSIBLE,
+ CM_UNDEF
+}ColourMatrix;
+
+/*! Types of Transfer functions */
+typedef enum {
+ TF_TV=0,
+ TF_EXT_GAMUT,
+ TF_LINEAR,
+ TF_DCINEMA,
+ TF_UNDEF
+} TransferFunction;
+
+/*! Types of Picture-rate */
+typedef enum {
+ FRAMERATE_CUSTOM=0,
+ FRAMERATE_23p97_FPS,
+ FRAMERATE_24_FPS,
+ FRAMERATE_25_FPS,
+ FRAMERATE_29p97_FPS,
+ FRAMERATE_30_FPS,
+ FRAMERATE_50_FPS,
+ FRAMERATE_59p94_FPS,
+ FRAMERATE_60_FPS,
+ FRAMERATE_14p98_FPS,
+ FRAMERATE_12p5_FPS,
+ FRAMERATE_UNDEFINED
+} FrameRateType;
+
+/*! Types of Aspect Ratio */
+typedef enum {
+ PIXEL_ASPECT_RATIO_CUSTOM=0,
+ PIXEL_ASPECT_RATIO_1_1,
+ PIXEL_ASPECT_RATIO_10_11,
+ PIXEL_ASPECT_RATIO_12_11,
+ PIXEL_ASPECT_RATIO_40_33,
+ PIXEL_ASPECT_RATIO_16_11,
+ PIXEL_ASPECT_RATIO_4_3,
+ PIXEL_ASPECT_RATIO_UNDEFINED
+} PixelAspectRatioType;
+
+
+/*! Types of signal range */
+typedef enum {
+ SIGNAL_RANGE_CUSTOM=0,
+ SIGNAL_RANGE_8BIT_FULL,
+ SIGNAL_RANGE_8BIT_VIDEO,
+ SIGNAL_RANGE_10BIT_VIDEO,
+ SIGNAL_RANGE_12BIT_VIDEO,
+ SIGNAL_RANGE_UNDEFINED
+} SignalRangeType;
+
+/*! Types of motion-vector precision */
+typedef enum {
+ MV_PRECISION_PIXEL=0,
+ MV_PRECISION_HALF_PIXEL,
+ MV_PRECISION_QUARTER_PIXEL,
+ MV_PRECISION_EIGHTH_PIXEL,
+ MV_PRECISION_UNDEFINED
+} MVPrecisionType;
+
+/*! Type of quantiser modes when spatial partitioning is enabled */
+typedef enum
+{
+ QUANT_SINGLE,
+ QUANT_MULTIPLE,
+ QUANT_UNDEF
+} CodeBlockMode;
#ifdef __cplusplus
}
diff --git a/src/filters/parser/DiracSplitter/libdirac/libdirac_common/dirac_assertions.cpp b/src/filters/parser/DiracSplitter/libdirac/libdirac_common/dirac_assertions.cpp
index 9e0b320f5..747c64998 100644
--- a/src/filters/parser/DiracSplitter/libdirac/libdirac_common/dirac_assertions.cpp
+++ b/src/filters/parser/DiracSplitter/libdirac/libdirac_common/dirac_assertions.cpp
@@ -44,19 +44,19 @@ using namespace dirac;
namespace dirac
{
-void dirac_assert(const char *p_fname, int line_number, const char *p_mess)
+void dirac_assert( const char *p_fname, int line_number, const char *p_mess )
{
- dirac_report(p_fname, line_number, p_mess);
+ dirac_report( p_fname, line_number, p_mess );
// dump core
- abort();
+ abort ();
}
-void dirac_report(const char *p_fname, int line_number, const char *p_mess)
+void dirac_report( const char *p_fname, int line_number, const char *p_mess )
{
std::string errMess("Assertion ");
-
- if(p_mess)
- errMess = errMess + "^ " + std::string(p_mess) + " ^" + " failed";
+
+ if ( p_mess )
+ errMess = errMess + "^ " + std::string(p_mess) + " ^" +" failed";
else
errMess += " failure";
diff --git a/src/filters/parser/DiracSplitter/libdirac/libdirac_common/dirac_assertions.h b/src/filters/parser/DiracSplitter/libdirac/libdirac_common/dirac_assertions.h
index f773fa3e7..209447e84 100644
--- a/src/filters/parser/DiracSplitter/libdirac/libdirac_common/dirac_assertions.h
+++ b/src/filters/parser/DiracSplitter/libdirac/libdirac_common/dirac_assertions.h
@@ -70,10 +70,10 @@ namespace dirac
/*! Print a message to standard error and abort if in debug mode */
-void dirac_assert(const char *p_fname, int line_number, const char *p_mess);
+void dirac_assert( const char *p_fname, int line_number, const char *p_mess);
/*! Print a message to standard error */
-void dirac_report(const char *p_fname, int line_number, const char *p_mess);
+void dirac_report( const char *p_fname, int line_number, const char *p_mess);
} // namespace dirac
diff --git a/src/filters/parser/DiracSplitter/libdirac/libdirac_common/dirac_exception.cpp b/src/filters/parser/DiracSplitter/libdirac/libdirac_common/dirac_exception.cpp
index c1741799d..b42e42748 100644
--- a/src/filters/parser/DiracSplitter/libdirac/libdirac_common/dirac_exception.cpp
+++ b/src/filters/parser/DiracSplitter/libdirac/libdirac_common/dirac_exception.cpp
@@ -50,20 +50,20 @@ DiracException::DiracException(
const DiracErrorCode& errorCode,
const string& errorMessage,
const DiracSeverityCode& severityCode)
- : mErrorCode(errorCode),
- mSeverityCode(severityCode),
- mErrorMessage(errorMessage)
+: mErrorCode(errorCode),
+ mSeverityCode(severityCode),
+ mErrorMessage(errorMessage)
{
}
DiracException::DiracException(
const DiracException& src)
- : mErrorCode(src.mErrorCode)
- , mSeverityCode(src.mSeverityCode)
- , mErrorMessage(src.mErrorMessage)
+: mErrorCode(src.mErrorCode)
+, mSeverityCode(src.mSeverityCode)
+, mErrorMessage(src.mErrorMessage)
{
-
+
}
DiracException::~DiracException()
@@ -78,7 +78,7 @@ DiracErrorCode DiracException::GetErrorCode() const
return mErrorCode;
}
-DiracSeverityCode DiracException::GetSeverityCode() const
+ DiracSeverityCode DiracException::GetSeverityCode() const
{
return mSeverityCode;
}
diff --git a/src/filters/parser/DiracSplitter/libdirac/libdirac_common/dirac_exception.h b/src/filters/parser/DiracSplitter/libdirac/libdirac_common/dirac_exception.h
index 9f417d2b9..44c54cb0d 100644
--- a/src/filters/parser/DiracSplitter/libdirac/libdirac_common/dirac_exception.h
+++ b/src/filters/parser/DiracSplitter/libdirac/libdirac_common/dirac_exception.h
@@ -48,41 +48,38 @@
#include <iostream> // has an ostringstream
-namespace dirac
-{
+namespace dirac {
-/**
- * Enumeration of Dirac-defined error codes.
- *
- *
- */
-enum DiracErrorCode
-{
- ERR_UNSUPPORTED_STREAM_DATA = 0,
- ERR_END_OF_STREAM,
- ERR_INVALID_VIDEO_FORMAT,
- ERR_INVALID_CHROMA_FORMAT,
- ERR_INVALID_PICTURE_RATE,
- ERR_INVALID_SIGNAL_RANGE,
- ERR_INVALID_PIXEL_ASPECT_RATIO,
- ERR_INVALID_VIDEO_DEPTH,
- ERR_INVALID_MOTION_VECTOR_PRECISION,
- ERR_INVALID_INIT_DATA
-
-};
+ /**
+ * Enumeration of Dirac-defined error codes.
+ *
+ *
+ */
+ enum DiracErrorCode {
+ ERR_UNSUPPORTED_STREAM_DATA=0,
+ ERR_END_OF_STREAM,
+ ERR_INVALID_VIDEO_FORMAT,
+ ERR_INVALID_CHROMA_FORMAT,
+ ERR_INVALID_PICTURE_RATE,
+ ERR_INVALID_SIGNAL_RANGE,
+ ERR_INVALID_PIXEL_ASPECT_RATIO,
+ ERR_INVALID_VIDEO_DEPTH,
+ ERR_INVALID_MOTION_VECTOR_PRECISION,
+ ERR_INVALID_INIT_DATA
+
+ };
-/**
-* Error-severity states
-*/
-enum DiracSeverityCode
-{
- SEVERITY_NO_ERROR = 0,
- SEVERITY_WARNING,
- SEVERITY_PICTURE_ERROR,
- SEVERITY_ACCESSUNIT_ERROR,
- SEVERITY_SEQUENCE_ERROR,
- SEVERITY_TERMINATE
-};
+ /**
+ * Error-severity states
+ */
+ enum DiracSeverityCode {
+ SEVERITY_NO_ERROR=0,
+ SEVERITY_WARNING,
+ SEVERITY_PICTURE_ERROR,
+ SEVERITY_ACCESSUNIT_ERROR,
+ SEVERITY_SEQUENCE_ERROR,
+ SEVERITY_TERMINATE
+ };
/**
* DiracException is the class which should be used for all exceptions
@@ -164,7 +161,7 @@ private:
*/
std::string mErrorMessage;
-
+
// UNIMPLEMENTED METHODS
DiracException& operator=(const DiracException&);
diff --git a/src/filters/parser/DiracSplitter/libdirac/libdirac_common/dirac_types.h b/src/filters/parser/DiracSplitter/libdirac/libdirac_common/dirac_types.h
index d9fd2952b..cc7cd7f54 100644
--- a/src/filters/parser/DiracSplitter/libdirac/libdirac_common/dirac_types.h
+++ b/src/filters/parser/DiracSplitter/libdirac/libdirac_common/dirac_types.h
@@ -41,7 +41,7 @@
#include <libdirac_common/common_types.h>
-/*! This file contains common enumerated types used throughout
+/*! This file contains common enumerated types used throughout
the end user interfaces to the encoder and decoder
*/
@@ -55,13 +55,13 @@ extern "C" {
#define DllExport
#endif
- /*
- * Major version corresponds to major version of the software.
- * Minor version corresponds to minor version of the software. Bump
- * this up by one whenever there are major feature changes to the software.
- * Patch version corresponds to changes in the API. It should be
- * bumped up by 1 for every committed change to the API
- */
+/*
+* Major version corresponds to major version of the software.
+* Minor version corresponds to minor version of the software. Bump
+* this up by one whenever there are major feature changes to the software.
+* Patch version corresponds to changes in the API. It should be
+* bumped up by 1 for every committed change to the API
+*/
#define DIRAC_RESEARCH_MAJOR_VERSION 1 /* 0..255 */
#define DIRAC_RESEARCH_MINOR_VERSION 0 /* 0..255 */
#define DIRAC_RESEARCH_PATCH_VERSION 2 /* 0..255 */
@@ -77,122 +77,122 @@ extern "C" {
#define DIRAC_RESEARCH_VERSION_ATLEAST(X, Y, Z) \
(DIRAC_RESEARCH_CURVERSION >= DIRAC_RESEARCH_VERSION(X, Y, Z))
- /*
- * Some basic enumeration types used by end user encoder and decoder ...//
- */
- typedef ChromaFormat dirac_chroma_t;
- typedef PictureType dirac_picture_type_t;
- typedef ReferenceType dirac_reference_type_t;
- typedef WltFilter dirac_wlt_filter_t;
-
- typedef struct
- {
- int numerator;
- int denominator;
- } dirac_rational_t;
-
- typedef dirac_rational_t dirac_frame_rate_t;
- typedef dirac_rational_t dirac_pix_asr_t;
-
- /*! Structure that holds the parase parameters */
- typedef struct
- {
- //! Major version
- unsigned int major_ver;
- //! Minor version
- unsigned int minor_ver;
- //! Profile
- unsigned int profile;
- //! level
- unsigned int level;
- } dirac_parseparams_t;
-
- typedef struct
- {
- unsigned int width;
- unsigned int height;
- unsigned int left_offset;
- unsigned int top_offset;
- } dirac_clean_area_t;
-
- typedef struct
- {
- unsigned int luma_offset;
- unsigned int luma_excursion;
- unsigned int chroma_offset;
- unsigned int chroma_excursion;
- } dirac_signal_range_t;
-
- typedef struct
- {
- float kr;
- float kb;
- } dirac_col_matrix_t;
-
- typedef ColourPrimaries dirac_col_primaries_t;
- typedef TransferFunction dirac_transfer_func_t;
-
- typedef struct
- {
- dirac_col_primaries_t col_primary;
- dirac_col_matrix_t col_matrix;
- dirac_transfer_func_t trans_func;
- } dirac_colour_spec_t;
-
- /*! Structure that holds the source parameters */
- typedef struct
- {
- /*! numper of pixels per line */
- unsigned int width;
- /*! number of lines per frame */
- unsigned int height;
- /*! chroma type */
- dirac_chroma_t chroma;
- /*! numper of pixels of chroma per line */
- unsigned int chroma_width;
- /*! number of lines of chroma per frame */
- unsigned int chroma_height;
- /*! source sampling field: 0 - progressive; 1 - interlaced */
- unsigned int source_sampling;
- /*! top field comes first : 0 - false; 1 - true. Set by Dirac library. */
- int topfieldfirst;
- /*! frame rate */
- dirac_frame_rate_t frame_rate;
- /*! pixel aspect ratio */
- dirac_pix_asr_t pix_asr;
- /* clean area*/
- dirac_clean_area_t clean_area;
- /* signal range*/
- dirac_signal_range_t signal_range;
- /* colour specification*/
- dirac_colour_spec_t colour_spec;
-
- } dirac_sourceparams_t;
-
- /*! Structure that holds the picture parameters */
- typedef struct
- {
- /*! picture type */
- dirac_picture_type_t ptype;
- /*! reference type */
- dirac_reference_type_t rtype;
- /*! picture number in decoded order */
- int pnum;
- } dirac_picparams_t;
-
-
- /*! Structure that holds the frame buffers into which data is written
- (NB we have frame-oriented IO even though we code pictures)*/
- typedef struct
- {
- /*! buffers to hold the luma and chroma data */
- unsigned char *buf[3];
- /*! user data */
- void *id;
- } dirac_framebuf_t;
+/*
+* Some basic enumeration types used by end user encoder and decoder ...//
+*/
+typedef ChromaFormat dirac_chroma_t;
+typedef PictureType dirac_picture_type_t;
+typedef ReferenceType dirac_reference_type_t;
+typedef WltFilter dirac_wlt_filter_t;
+
+typedef struct
+{
+ int numerator;
+ int denominator;
+} dirac_rational_t;
+
+typedef dirac_rational_t dirac_frame_rate_t;
+typedef dirac_rational_t dirac_pix_asr_t;
+
+/*! Structure that holds the parase parameters */
+typedef struct
+{
+ //! Major version
+ unsigned int major_ver;
+ //! Minor version
+ unsigned int minor_ver;
+ //! Profile
+ unsigned int profile;
+ //! level
+ unsigned int level;
+} dirac_parseparams_t;
+
+typedef struct
+{
+ unsigned int width;
+ unsigned int height;
+ unsigned int left_offset;
+ unsigned int top_offset;
+} dirac_clean_area_t;
+
+typedef struct
+{
+ unsigned int luma_offset;
+ unsigned int luma_excursion;
+ unsigned int chroma_offset;
+ unsigned int chroma_excursion;
+} dirac_signal_range_t;
+
+typedef struct
+{
+ float kr;
+ float kb;
+} dirac_col_matrix_t;
+
+typedef ColourPrimaries dirac_col_primaries_t;
+typedef TransferFunction dirac_transfer_func_t;
+
+typedef struct
+{
+ dirac_col_primaries_t col_primary;
+ dirac_col_matrix_t col_matrix;
+ dirac_transfer_func_t trans_func;
+} dirac_colour_spec_t;
+
+/*! Structure that holds the source parameters */
+typedef struct
+{
+ /*! numper of pixels per line */
+ unsigned int width;
+ /*! number of lines per frame */
+ unsigned int height;
+ /*! chroma type */
+ dirac_chroma_t chroma;
+ /*! numper of pixels of chroma per line */
+ unsigned int chroma_width;
+ /*! number of lines of chroma per frame */
+ unsigned int chroma_height;
+ /*! source sampling field: 0 - progressive; 1 - interlaced */
+ unsigned int source_sampling;
+ /*! top field comes first : 0 - false; 1 - true. Set by Dirac library. */
+ int topfieldfirst;
+ /*! frame rate */
+ dirac_frame_rate_t frame_rate;
+ /*! pixel aspect ratio */
+ dirac_pix_asr_t pix_asr;
+ /* clean area*/
+ dirac_clean_area_t clean_area;
+ /* signal range*/
+ dirac_signal_range_t signal_range;
+ /* colour specification*/
+ dirac_colour_spec_t colour_spec;
+
+} dirac_sourceparams_t;
+
+/*! Structure that holds the picture parameters */
+typedef struct
+{
+ /*! picture type */
+ dirac_picture_type_t ptype;
+ /*! reference type */
+ dirac_reference_type_t rtype;
+ /*! picture number in decoded order */
+ int pnum;
+} dirac_picparams_t;
+
+
+/*! Structure that holds the frame buffers into which data is written
+(NB we have frame-oriented IO even though we code pictures)*/
+typedef struct
+{
+ /*! buffers to hold the luma and chroma data */
+ unsigned char *buf[3];
+ /*! user data */
+ void *id;
+} dirac_framebuf_t;
#ifdef __cplusplus
}
#endif
-#endif
+#endif
diff --git a/src/filters/parser/DiracSplitter/libdirac/libdirac_common/mot_comp.cpp b/src/filters/parser/DiracSplitter/libdirac/libdirac_common/mot_comp.cpp
index 10fb53229..7fe5515c9 100644
--- a/src/filters/parser/DiracSplitter/libdirac/libdirac_common/mot_comp.cpp
+++ b/src/filters/parser/DiracSplitter/libdirac/libdirac_common/mot_comp.cpp
@@ -61,36 +61,36 @@ using std::vector;
// MV precision value in the PicturePredParams to instantiate the
// appropriate MotionCompensation sub-class.
void MotionCompensator::CompensatePicture(const PicturePredParams &ppp,
- const AddOrSub direction ,
- const MvData& mv_data,
- Picture* in_pic ,
- Picture* refsptr[2])
+ const AddOrSub direction ,
+ const MvData& mv_data,
+ Picture* in_pic ,
+ Picture* refsptr[2])
{
- switch(ppp.MVPrecision())
+ switch (ppp.MVPrecision())
{
case MV_PRECISION_EIGHTH_PIXEL:
{
MotionCompensator_EighthPixel my_comp(ppp);
- my_comp.CompensatePicture(direction , mv_data, in_pic, refsptr);
+ my_comp.CompensatePicture( direction , mv_data, in_pic, refsptr);
break;
}
case MV_PRECISION_HALF_PIXEL:
{
MotionCompensator_HalfPixel my_comp(ppp);
- my_comp.CompensatePicture(direction , mv_data, in_pic, refsptr);
+ my_comp.CompensatePicture( direction , mv_data, in_pic, refsptr);
break;
}
case MV_PRECISION_PIXEL:
{
MotionCompensator_Pixel my_comp(ppp);
- my_comp.CompensatePicture(direction , mv_data, in_pic, refsptr);
+ my_comp.CompensatePicture( direction , mv_data, in_pic, refsptr);
break;
}
case MV_PRECISION_QUARTER_PIXEL:
default:
{
MotionCompensator_QuarterPixel my_comp(ppp);
- my_comp.CompensatePicture(direction , mv_data, in_pic, refsptr);
+ my_comp.CompensatePicture( direction , mv_data, in_pic, refsptr);
break;
}
}
@@ -103,7 +103,7 @@ void MotionCompensator::CompensatePicture(const PicturePredParams &ppp,
// motion compensation. Creates the necessary arithmetic objects and
// calls ReConfig to create weighting blocks to fit the values within
// m_predparams.
-MotionCompensator::MotionCompensator(const PicturePredParams &ppp):
+MotionCompensator::MotionCompensator( const PicturePredParams &ppp ):
m_predparams(ppp),
luma_or_chroma(true)
{
@@ -128,62 +128,61 @@ MotionCompensator::~MotionCompensator()
}
//Called to perform motion compensated addition/subtraction on an entire picture.
-void MotionCompensator::CompensatePicture(const AddOrSub direction ,
- const MvData& mv_data,
- Picture* my_picture ,
- Picture* refsptr[2])
+void MotionCompensator::CompensatePicture( const AddOrSub direction ,
+ const MvData& mv_data,
+ Picture* my_picture ,
+ Picture* refsptr[2])
{
- m_add_or_sub = direction;
-
- const PictureSort& psort = my_picture->GetPparams().PicSort();
-
- m_cformat = my_picture->GetPparams().CFormat();
-
- if(psort.IsInter())
- {
- //we can motion compensate
-
- const std::vector<int>& refs = my_picture->GetPparams().Refs();
-
- // Now check that references are marked correctly
- if(!refsptr[0]->GetPparams().PicSort().IsRef())
- {
- std::cout << std::endl << "WARNING! Reference picture (number " << refs[0];
- std::cout << ") being used is not marked as a reference. Incorrect output is likely.";
- }
- if(refsptr[0]->GetPparams().PictureNum() != refs[0])
- {
- std::cout << std::endl << "WARNING! Reference picture number 0 ";
- std::cout << "does not agree(" << refsptr[0]->GetPparams().PictureNum() << " and ";
- std::cout << refs[0] << "). Incorrect output is likely.";
- }
-
-
- if(refs.size() > 1)
- {
- if(!refsptr[1]->GetPparams().PicSort().IsRef())
- {
- std::cout << std::endl << "WARNING! Reference picture (number ";
- std::cout << refs[1] << ") being used is not marked as a reference. Incorrect output is likely.";
- }
- if(refsptr[1]->GetPparams().PictureNum() != refs[1])
- {
- std::cout << std::endl << "WARNING! Reference picture number 1 ";
- std::cout << "does not agree(" << refsptr[1]->GetPparams().PictureNum() << " and ";
- std::cout << refs[1] << "). Incorrect output is likely.";
- }
- }
- else
- refsptr[1] = refsptr[0];
-
- luma_or_chroma = true;
- //now do all the components
- CompensateComponent(my_picture , refsptr, mv_data , Y_COMP);
-
- luma_or_chroma = false;
- CompensateComponent(my_picture , refsptr, mv_data , U_COMP);
- CompensateComponent(my_picture , refsptr, mv_data , V_COMP);
- }
+ m_add_or_sub = direction;
+
+ const PictureSort& psort=my_picture->GetPparams().PicSort();
+
+ m_cformat = my_picture->GetPparams().CFormat();
+
+ if (psort.IsInter())
+ {//we can motion compensate
+
+ const std::vector<int>& refs=my_picture->GetPparams().Refs();
+
+ // Now check that references are marked correctly
+ if ( !refsptr[0]->GetPparams().PicSort().IsRef() )
+ {
+ std::cout<<std::endl<<"WARNING! Reference picture (number "<<refs[0];
+ std::cout<<") being used is not marked as a reference. Incorrect output is likely.";
+ }
+ if ( refsptr[0]->GetPparams().PictureNum() != refs[0] )
+ {
+ std::cout<<std::endl<<"WARNING! Reference picture number 0 ";
+ std::cout<<"does not agree("<<refsptr[0]->GetPparams().PictureNum()<<" and ";
+ std::cout<<refs[0]<<"). Incorrect output is likely.";
+ }
+
+
+ if ( refs.size()>1 )
+ {
+ if ( !refsptr[1]->GetPparams().PicSort().IsRef() )
+ {
+ std::cout<<std::endl<<"WARNING! Reference picture (number ";
+ std::cout<<refs[1]<<") being used is not marked as a reference. Incorrect output is likely.";
+ }
+ if ( refsptr[1]->GetPparams().PictureNum() != refs[1])
+ {
+ std::cout<<std::endl<<"WARNING! Reference picture number 1 ";
+ std::cout<<"does not agree("<<refsptr[1]->GetPparams().PictureNum()<<" and ";
+ std::cout<<refs[1]<<"). Incorrect output is likely.";
+ }
+ }
+ else
+ refsptr[1] = refsptr[0];
+
+ luma_or_chroma = true;
+ //now do all the components
+ CompensateComponent( my_picture , refsptr, mv_data , Y_COMP );
+
+ luma_or_chroma = false;
+ CompensateComponent( my_picture , refsptr, mv_data , U_COMP);
+ CompensateComponent( my_picture , refsptr, mv_data , V_COMP);
+ }
}
//--private member functions--//
@@ -195,7 +194,7 @@ void MotionCompensator::CompensatePicture(const AddOrSub direction ,
//blocks.
void MotionCompensator::ReConfig()
{
- if(luma_or_chroma)
+ if (luma_or_chroma)
m_bparams = m_predparams.LumaBParams(2);
else
m_bparams = m_predparams.ChromaBParams(2);
@@ -205,65 +204,65 @@ void MotionCompensator::ReConfig()
// Total shift = shift assuming equal picture weights +
// picture weights precision
- int blocks_per_mb_row = m_predparams.XNumBlocks() / m_predparams.XNumSB();
- int blocks_per_sb_row = blocks_per_mb_row >> 1;
- int mb_xlen = m_bparams.Xblen() * blocks_per_mb_row - (m_bparams.Xblen() - m_bparams.Xbsep()) * (blocks_per_mb_row - 1);
+ int blocks_per_mb_row = m_predparams.XNumBlocks()/m_predparams.XNumSB();
+ int blocks_per_sb_row = blocks_per_mb_row>>1;
+ int mb_xlen = m_bparams.Xblen()*blocks_per_mb_row - (m_bparams.Xblen()-m_bparams.Xbsep())*(blocks_per_mb_row-1);
int mb_ylen = m_bparams.Yblen();
- int mb_xsep = mb_xlen - (m_bparams.Xblen() - m_bparams.Xbsep());
+ int mb_xsep = mb_xlen - (m_bparams.Xblen()-m_bparams.Xbsep());
int mb_ysep = m_bparams.Ybsep();
- int sb_xlen = m_bparams.Xblen() * blocks_per_sb_row - (m_bparams.Xblen() - m_bparams.Xbsep()) * (blocks_per_sb_row - 1);
+ int sb_xlen = m_bparams.Xblen()*blocks_per_sb_row - (m_bparams.Xblen()-m_bparams.Xbsep())*(blocks_per_sb_row-1);
int sb_ylen = m_bparams.Yblen();
int sb_xsep = sb_xlen - (m_bparams.Xblen() - m_bparams.Xbsep());
int sb_ysep = m_bparams.Ybsep();
for(int i = 0; i < 9; i++)
{
- m_block_weights[i].Resize(m_bparams.Yblen() , m_bparams.Xblen());
- m_macro_block_weights[i].Resize(mb_ylen , mb_xlen);
- m_sub_block_weights[i].Resize(sb_ylen , sb_xlen);
+ m_block_weights[i].Resize( m_bparams.Yblen() , m_bparams.Xblen() );
+ m_macro_block_weights[i].Resize( mb_ylen , mb_xlen );
+ m_sub_block_weights[i].Resize( sb_ylen , sb_xlen );
}
// Firstly calculate the non-weighted Weighting blocks. i,e, assuming that
// the picture_weight for each reference picture is 1.
// Calculate non-weighted Block Weights
- CalculateWeights(m_bparams.Xbsep(), m_bparams.Ybsep(), m_block_weights);
+ CalculateWeights( m_bparams.Xbsep(), m_bparams.Ybsep(), m_block_weights );
// Calculate non-weighted "macro" Block Weights
- CalculateWeights(mb_xsep, mb_ysep , m_macro_block_weights);
+ CalculateWeights( mb_xsep, mb_ysep , m_macro_block_weights );
// Calculate non-weighted superblock Weights
- CalculateWeights(sb_xsep, sb_ysep , m_sub_block_weights);
+ CalculateWeights( sb_xsep, sb_ysep , m_sub_block_weights );
}
-void MotionCompensator::CompensateComponent(Picture* pic ,
- Picture* refsptr[2] ,
- const MvData& mv_data ,
- const CompSort cs)
+void MotionCompensator::CompensateComponent( Picture* pic ,
+ Picture* refsptr[2] ,
+ const MvData& mv_data ,
+ const CompSort cs )
{
// Set up references to pictures and references
- PicArray& pic_data_out = pic->Data(cs);
+ PicArray& pic_data_out = pic->Data( cs );
// Size of picture component being motion compensated
- const PicArray& ref1up = refsptr[0]->UpData(cs);
- const PicArray& ref2up = refsptr[1]->UpData(cs);
+ const PicArray& ref1up = refsptr[0]->UpData( cs );
+ const PicArray& ref2up = refsptr[1]->UpData( cs );
// Set up a row of blocks which will contain the MC data, which
// we'll add or subtract to pic_data_out
- TwoDArray<ValueType> pic_data(m_bparams.Yblen(), pic_data_out.LengthX(), 0);
+ TwoDArray<ValueType> pic_data(m_bparams.Yblen(), pic_data_out.LengthX(), 0 );
// Factors to compensate for subsampling of chroma
int xscale_shift = 0;
int yscale_shift = 0;
- if(cs != Y_COMP)
+ if ( cs != Y_COMP )
{
- if(m_cformat == format420)
+ if (m_cformat == format420)
{
xscale_shift = 1;
yscale_shift = 1;
}
- else if(m_cformat == format422)
+ else if (m_cformat == format422)
{
xscale_shift = 1;
yscale_shift = 0;
@@ -271,7 +270,7 @@ void MotionCompensator::CompensateComponent(Picture* pic ,
}
ImageCoords pic_size(pic->GetPparams().Xl(), pic->GetPparams().Yl());
- if(cs != Y_COMP)
+ if ( cs != Y_COMP )
{
pic_size.x = pic->GetPparams().ChromaXl();
pic_size.y = pic->GetPparams().ChromaYl();
@@ -279,14 +278,14 @@ void MotionCompensator::CompensateComponent(Picture* pic ,
// Reference to the relevant DC array
- const TwoDArray<ValueType>& dcarray = mv_data.DC(cs);
+ const TwoDArray<ValueType>& dcarray = mv_data.DC( cs );
// Set up references to the vectors
const int num_refs = pic->GetPparams().Refs().size();
const MvArray* mv_array1;
const MvArray* mv_array2;
mv_array1 = &mv_data.Vectors(1);
- if(num_refs == 2)
+ if (num_refs ==2 )
mv_array2 = &mv_data.Vectors(2);
else
mv_array2 = &mv_data.Vectors(1);
@@ -294,7 +293,7 @@ void MotionCompensator::CompensateComponent(Picture* pic ,
ReConfig();//set all the weighting blocks up
//Blocks are listed left to right, line by line.
- MVector mv1, mv2;
+ MVector mv1,mv2;
PredMode block_mode;
//Coords of the top-left corner of a block
@@ -305,24 +304,24 @@ void MotionCompensator::CompensateComponent(Picture* pic ,
//and add the compensated pixels to the image pointed to by pic_data.
size_t wgt_idx;
- int save_from_row = m_bparams.Ybsep() - m_bparams.Yoffset();
+ int save_from_row = m_bparams.Ybsep()-m_bparams.Yoffset();
bool row_overlap = ((m_bparams.Yblen() - m_bparams.Ybsep()) > 0);
// unpadded picture dimensions
- const int x_end_data = pic_data_out.FirstX() + std::min(pic_data_out.LengthX(), pic_size.x);
- const int y_end_data = pic_data_out.FirstY() + std::min(pic_data_out.LengthY(), pic_size.y);
+ const int x_end_data = pic_data_out.FirstX() + std::min(pic_data_out.LengthX(), pic_size.x );
+ const int y_end_data = pic_data_out.FirstY() + std::min(pic_data_out.LengthY(), pic_size.y );
- const int blocks_per_mb_row = m_predparams.XNumBlocks() / m_predparams.XNumSB();
- const int blocks_per_sb_row = blocks_per_mb_row >> 1;
+ const int blocks_per_mb_row = m_predparams.XNumBlocks()/m_predparams.XNumSB();
+ const int blocks_per_sb_row = blocks_per_mb_row>>1;
// The picture does not contain integral number of blocks. So not all
// blocks need to be processed. Compute the relevant blocks to be
- // processed
- int y_num_blocks = std::min((NUM_USED_BLKS(pic_size.y, m_bparams.Ybsep(), m_bparams.Yblen())),
- m_predparams.YNumBlocks());
- int x_num_blocks = std::min((NUM_USED_BLKS(pic_size.x, m_bparams.Xbsep(), m_bparams.Xblen())),
- m_predparams.XNumBlocks());
+ // processed
+ int y_num_blocks = std::min((NUM_USED_BLKS(pic_size.y,m_bparams.Ybsep(),m_bparams.Yblen())),
+ m_predparams.YNumBlocks());
+ int x_num_blocks = std::min((NUM_USED_BLKS(pic_size.x,m_bparams.Xbsep(),m_bparams.Xblen())),
+ m_predparams.XNumBlocks());
//Loop over all the block rows
pos.y = -m_bparams.Yoffset();
@@ -331,13 +330,13 @@ void MotionCompensator::CompensateComponent(Picture* pic ,
pos.x = -m_bparams.Xoffset();
int xincr, xb_incr = 0;
//loop over all the blocks in a row
- for(int xblock = 0 ; xblock < x_num_blocks; xblock += xb_incr)
+ for(int xblock = 0 ; xblock < x_num_blocks; xblock+=xb_incr)
{
int split_mode = mv_data.SBSplit()[yblock/blocks_per_mb_row][xblock/blocks_per_mb_row];
int blk_x, blk_y = 1;
- switch(split_mode)
+ switch (split_mode)
{
case 0: // processing superblock
blk_x = blocks_per_mb_row;
@@ -352,22 +351,22 @@ void MotionCompensator::CompensateComponent(Picture* pic ,
}
//Decide which weights to use.
- if(pos.x >= 0 && (xblock + blk_x) < x_num_blocks)
+ if (pos.x >=0 && (xblock+blk_x) < x_num_blocks)
{
// block is entirely within picture in x direction
- if(pos.y < 0)
+ if (pos.y < 0)
wgt_idx = 1;
- else if((yblock + blk_y) < y_num_blocks)
+ else if ((yblock+blk_y) < y_num_blocks)
wgt_idx = 4;
else
wgt_idx = 7;
}
- else if(pos.x < 0)
+ else if (pos.x < 0)
{
// left edge of block is outside picture in x direction
- if(pos.y < 0)
+ if (pos.y < 0)
wgt_idx = 0;
- else if((yblock + blk_y) < y_num_blocks)
+ else if ((yblock+blk_y) < y_num_blocks)
wgt_idx = 3;
else
wgt_idx = 6;
@@ -375,9 +374,9 @@ void MotionCompensator::CompensateComponent(Picture* pic ,
else
{
// right edge of block is outside picture in x direction
- if(pos.y < 0)
+ if (pos.y < 0)
wgt_idx = 2;
- else if((yblock + blk_y) < y_num_blocks)
+ else if ((yblock+blk_y) < y_num_blocks)
wgt_idx = 5;
else
wgt_idx = 8;
@@ -388,12 +387,12 @@ void MotionCompensator::CompensateComponent(Picture* pic ,
TwoDArray<ValueType> *wt;
- if(split_mode == 0) //Block part of a MacroBlock
+ if (split_mode == 0) //Block part of a MacroBlock
{
wt = &m_macro_block_weights[wgt_idx];
xb_incr = blocks_per_mb_row;
}
- else if(split_mode == 1) //Block part of a SubBlock
+ else if (split_mode == 1) //Block part of a SubBlock
{
wt = &m_sub_block_weights[wgt_idx];
xb_incr = blocks_per_sb_row;
@@ -424,27 +423,27 @@ void MotionCompensator::CompensateComponent(Picture* pic ,
// Use only the first Ybsep rows since the remaining rows are
// needed for the next row of blocks since we are using overlapped
// blocks motion compensation
- if(m_add_or_sub == SUBTRACT)
+ if (m_add_or_sub == SUBTRACT)
{
int start_y = std::max(pic_data_out.FirstY() , pos.y) ;
- int end_y = std::min(pic_data_out.FirstY() + pos.y + m_bparams.Ybsep() , y_end_data);
+ int end_y = std::min (pic_data_out.FirstY() + pos.y + m_bparams.Ybsep() , y_end_data);
- if(yblock == y_num_blocks - 1)
+ if (yblock == y_num_blocks - 1)
{
end_y = pic_data_out.LengthY();
- if(end_y > y_end_data)
+ if (end_y > y_end_data)
end_y = y_end_data;
}
- for(int i = start_y, pos_y = 0; i < end_y; i++, pos_y++)
+ for ( int i = start_y, pos_y = 0; i < end_y; i++, pos_y++)
{
ValueType *pic_row = pic_data[pos_y];
ValueType *out_row = pic_data_out[i];
- for(int j = pic_data_out.FirstX(); j < x_end_data; ++j)
+ for ( int j =pic_data_out.FirstX(); j < x_end_data; ++j)
{
- out_row[j] -= static_cast<ValueType>((pic_row[j] + 32) >> 6);
+ out_row[j] -= static_cast<ValueType>( (pic_row[j] + 32) >> 6 );
}
// Okay, we've done all the actual blocks. Now if the picture is further padded
@@ -452,7 +451,7 @@ void MotionCompensator::CompensateComponent(Picture* pic ,
// for all the picture lines in the block row. Need only do this when we're
// subtracting.
- for(int j = pic_size.x; j < pic_data_out.LengthX() ; ++j)
+ for (int j=pic_size.x; j<pic_data_out.LengthX() ; ++j )
{
out_row[pic_data_out.FirstX()+j] = 0;
}
@@ -461,28 +460,28 @@ void MotionCompensator::CompensateComponent(Picture* pic ,
else // (m_add_or_sub == ADD)
{
int start_y = std::max(pic_data_out.FirstY() , pos.y) ;
- int end_y = std::min(pic_data_out.FirstY() + pos.y + m_bparams.Ybsep() , pic_data_out.FirstY() + pic_data_out.LengthY());
- if(yblock == (y_num_blocks - 1))
+ int end_y = std::min (pic_data_out.FirstY() + pos.y + m_bparams.Ybsep() , pic_data_out.FirstY() + pic_data_out.LengthY());
+ if (yblock == (y_num_blocks - 1))
{
- end_y += (m_bparams.Yblen() - m_bparams.Ybsep());
- if(end_y > pic_size.y)
+ end_y += (m_bparams.Yblen()-m_bparams.Ybsep());
+ if (end_y > pic_size.y)
end_y = pic_size.y;
}
#if defined (HAVE_MMX)
- CompensateComponentAddAndShift_mmx(start_y, end_y, 6, pic_size,
- pic_data, pic_data_out);
+ CompensateComponentAddAndShift_mmx (start_y, end_y, 6, pic_size,
+ pic_data, pic_data_out);
#else
- for(int i = start_y, pic_y = 0; i < end_y; i++, pic_y++)
+ for ( int i = start_y, pic_y = 0; i < end_y; i++, pic_y++)
{
ValueType *pic_row = pic_data[pic_y];
ValueType *out_row = pic_data_out[i];
- for(int j = 0; j < pic_size.x; j++)
+ for ( int j =0; j < pic_size.x; j++)
{
- out_row[j] += static_cast<ValueType>((pic_row[j] + 32) >> 6);
+ out_row[j] += static_cast<ValueType>( (pic_row[j] + 32) >> 6 );
}
// Pad the remaining pixels of the row with last truepic pixel val
- for(int j = pic_size.x; j < pic_data.LengthX(); j++)
+ for ( int j = pic_size.x; j < pic_data.LengthX(); j++)
{
out_row[j] = out_row[pic_size.x-1];
}
@@ -492,45 +491,45 @@ void MotionCompensator::CompensateComponent(Picture* pic ,
//Increment the block vertical position
pos.y += m_bparams.Ybsep();
- if(row_overlap)
+ if (row_overlap)
{
- // Copy the rows required to motion compensate the next row of
+ // Copy the rows required to motion compensate the next row of
// blocks. This is usually Yblen-Ybsep rows.
- memmove(pic_data[0], pic_data[save_from_row], (m_bparams.Yblen() - save_from_row)*pic_data.LengthX()*sizeof(ValueType));
- memset(pic_data[m_bparams.Yblen() - save_from_row], 0, save_from_row * pic_data.LengthX()*sizeof(ValueType));
+ memmove (pic_data[0], pic_data[save_from_row], (m_bparams.Yblen() - save_from_row)*pic_data.LengthX()*sizeof(ValueType));
+ memset( pic_data[m_bparams.Yblen() - save_from_row], 0, save_from_row*pic_data.LengthX()*sizeof(ValueType) );
save_from_row = m_bparams.Ybsep();
}
else
{
// no row overlap. So reset pic_data to 0.
- memset(pic_data[0], 0, m_bparams.Yblen()*pic_data.LengthX()*sizeof(ValueType));
+ memset( pic_data[0], 0, m_bparams.Yblen()*pic_data.LengthX()*sizeof(ValueType) );
}
}//yblock
- if(m_add_or_sub == SUBTRACT)
+ if ( m_add_or_sub == SUBTRACT)
{
- // Finally, now we've done all the blocks, we must set all padded lines
+ // Finally, now we've done all the blocks, we must set all padded lines
// below the last row equal to 0, if we're subtracting
- for(int y = pic_size.y ; y < pic_data_out.LengthY() ; ++y)
+ for ( int y=pic_size.y ; y<pic_data_out.LengthY() ; ++y )
{
ValueType *out_row = pic_data_out[y];
- for(int x = 0 ; x < pic_data_out.LengthX() ; ++x)
+ for ( int x=0 ; x<pic_data_out.LengthX() ; ++x )
{
out_row[x] = 0;
}
}
}
- else if(m_add_or_sub == ADD)
+ else if ( m_add_or_sub == ADD)
{
// Edge extension
- // Finally, now we've done all the blocks, we must set all padded lines
+ // Finally, now we've done all the blocks, we must set all padded lines
// below the last row equal to same as last row, if we're adding
ValueType *last_row = &pic_data_out[pic_size.y-1][0];
- for(int y = pic_size.y ; y < pic_data_out.LengthY() ; ++y)
+ for ( int y=pic_size.y ; y<pic_data_out.LengthY() ; ++y )
{
ValueType *out_row = pic_data_out[y];
- for(int x = 0 ; x < pic_data_out.LengthX() ; ++x)
+ for ( int x=0 ; x<pic_data_out.LengthX() ; ++x )
{
out_row[x] = last_row[x];
}
@@ -540,34 +539,34 @@ void MotionCompensator::CompensateComponent(Picture* pic ,
}
void MotionCompensator::CompensateBlock(
- TwoDArray<ValueType> &pic_data ,
- const ImageCoords& pos ,
- const ImageCoords& pic_size ,
- PredMode block_mode,
- ValueType dc,
- const PicArray &ref1up_data ,
- const MVector &mv1 ,
- const PicArray &ref2up_data ,
- const MVector &mv2 ,
- const TwoDArray<ValueType>& wt_array)
+ TwoDArray<ValueType> &pic_data ,
+ const ImageCoords& pos ,
+ const ImageCoords& pic_size ,
+ PredMode block_mode,
+ ValueType dc,
+ const PicArray &ref1up_data ,
+ const MVector &mv1 ,
+ const PicArray &ref2up_data ,
+ const MVector &mv2 ,
+ const TwoDArray<ValueType>& wt_array)
{
//Coordinates in the image being written to.
- const ImageCoords start_pos(std::max(pos.x, 0) , std::max(pos.y, 0));
- const ImageCoords end_pos(std::min(pos.x + wt_array.LengthX() , pic_size.x) ,
- std::min(pos.y + wt_array.LengthY() , pic_size.y));
+ const ImageCoords start_pos( std::max(pos.x,0) , std::max(pos.y,0) );
+ const ImageCoords end_pos( std::min( pos.x + wt_array.LengthX() , pic_size.x ) ,
+ std::min( pos.y + wt_array.LengthY() , pic_size.y ) );
// Check if we are within original picture bounds
- if(start_pos.x >= end_pos.x || start_pos.y >= end_pos.y)
+ if (start_pos.x >= end_pos.x || start_pos.y >= end_pos.y)
return;
- TwoDArray<ValueType> val1(end_pos.y - start_pos.y, end_pos.x - start_pos.x);
- TwoDArray<ValueType> val2(end_pos.y - start_pos.y, end_pos.x - start_pos.x);
+ TwoDArray<ValueType> val1(end_pos.y - start_pos.y, end_pos.x-start_pos.x);
+ TwoDArray<ValueType> val2(end_pos.y - start_pos.y, end_pos.x-start_pos.x);
if(block_mode == REF1_ONLY)
{
BlockPixelPred(val1, pos, pic_size, ref1up_data, mv1);
}
- else if(block_mode == REF2_ONLY)
+ else if (block_mode == REF2_ONLY)
{
BlockPixelPred(val1, pos, pic_size, ref2up_data, mv2);
}
@@ -577,8 +576,7 @@ void MotionCompensator::CompensateBlock(
BlockPixelPred(val2, pos, pic_size, ref2up_data, mv2);
}
else
- {
- //we have a DC block.
+ {//we have a DC block.
DCBlock(val1, dc);
}
/*
@@ -592,9 +590,9 @@ void MotionCompensator::CompensateBlock(
AdjustBlockBySpatialWeights(val1, pos, wt_array);
#if !defined (HAVE_MMX)
- for(int y = 0, py = 0; y < val1.LengthY(); ++y, ++py)
+ for (int y = 0, py=0; y < val1.LengthY(); ++y, ++py)
{
- for(int x = 0, px = start_pos.x; x < val1.LengthX(); ++x, ++px)
+ for (int x = 0, px=start_pos.x; x < val1.LengthX(); ++x, ++px)
{
pic_data[py][px] += val1[y][x];
}
@@ -604,53 +602,53 @@ void MotionCompensator::CompensateBlock(
#endif
}
-void MotionCompensator::DCBlock(TwoDArray<ValueType> &block_data ,
- const ValueType dc)
+void MotionCompensator::DCBlock( TwoDArray<ValueType> &block_data ,
+ const ValueType dc)
{
//Quick process where we can just copy from the double size image.
ValueType *block_curr = &block_data[0][0];
for(int y = 0; y < block_data.LengthY(); ++y)
{
- for(int x = 0; x < block_data.LengthX(); ++x, ++block_curr)
+ for(int x=0; x < block_data.LengthX(); ++x, ++block_curr)
{
*block_curr = dc;
}
}
}
-void MotionCompensator::AdjustBlockByRefWeights(
- TwoDArray<ValueType>& val1_block,
- TwoDArray<ValueType>& val2_block,
- PredMode block_mode)
+void MotionCompensator::AdjustBlockByRefWeights (
+ TwoDArray<ValueType>& val1_block,
+ TwoDArray<ValueType>& val2_block,
+ PredMode block_mode)
{
// No need to multiply by reference weights if DC block
- if(block_mode == INTRA)
+ if (block_mode == INTRA)
return;
- if(m_predparams.CustomRefWeights())
+ if (m_predparams.CustomRefWeights())
{
int ref_wt_prec_bias = 1;
- for(int i = m_predparams.PictureWeightsBits() - 1; i > 0; --i)
+ for (int i = m_predparams.PictureWeightsBits()-1; i > 0; --i)
{
ref_wt_prec_bias <<= 1;
}
- if(block_mode != REF1AND2)
+ if (block_mode != REF1AND2)
{
- for(int y = 0; y < val1_block.LengthY(); ++y)
+ for (int y = 0; y < val1_block.LengthY(); ++y)
{
- for(int x = 0; x < val1_block.LengthX(); ++x)
+ for (int x = 0; x < val1_block.LengthX(); ++x)
{
val1_block[y][x] *= (m_predparams.Ref1Weight() +
- m_predparams.Ref2Weight());
+ m_predparams.Ref2Weight());
}
}
}
else
{
- for(int y = 0; y < val1_block.LengthY(); ++y)
+ for (int y = 0; y < val1_block.LengthY(); ++y)
{
- for(int x = 0; x < val1_block.LengthX(); ++x)
+ for (int x = 0; x < val1_block.LengthX(); ++x)
{
val1_block[y][x] *= m_predparams.Ref1Weight();
val2_block[y][x] *= m_predparams.Ref2Weight();
@@ -658,9 +656,9 @@ void MotionCompensator::AdjustBlockByRefWeights(
}
}
}
- for(int y = 0; y < val1_block.LengthY(); ++y)
+ for (int y = 0; y < val1_block.LengthY(); ++y)
{
- for(int x = 0; x < val1_block.LengthX(); ++x)
+ for (int x = 0; x < val1_block.LengthX(); ++x)
{
val1_block[y][x] = (val1_block[y][x] + ref_wt_prec_bias) >> m_predparams.PictureWeightsBits();
}
@@ -669,13 +667,13 @@ void MotionCompensator::AdjustBlockByRefWeights(
else
{
// Default weights
- if(block_mode == REF1AND2)
+ if (block_mode == REF1AND2)
{
- for(int y = 0; y < val1_block.LengthY(); ++y)
+ for (int y = 0; y < val1_block.LengthY(); ++y)
{
- for(int x = 0; x < val1_block.LengthX(); ++x)
+ for (int x = 0; x < val1_block.LengthX(); ++x)
{
- val1_block[y][x] = (val1_block[y][x] + val2_block[y][x] + 1) >> 1;
+ val1_block[y][x] = (val1_block[y][x] + val2_block[y][x] + 1)>>1;
}
}
}
@@ -684,17 +682,17 @@ void MotionCompensator::AdjustBlockByRefWeights(
}
#if !defined (HAVE_MMX)
-void MotionCompensator::AdjustBlockBySpatialWeights(
- TwoDArray<ValueType>& val_block,
- const ImageCoords &pos,
- const TwoDArray<ValueType> &wt_array)
+void MotionCompensator::AdjustBlockBySpatialWeights (
+ TwoDArray<ValueType>& val_block,
+ const ImageCoords &pos,
+ const TwoDArray<ValueType> &wt_array)
{
- ImageCoords start_pos(std::max(0, pos.x), std::max(0, pos.y));
- ImageCoords wt_start(start_pos.x - pos.x, start_pos.y - pos.y);
+ ImageCoords start_pos (std::max(0, pos.x), std::max(0, pos.y));
+ ImageCoords wt_start (start_pos.x - pos.x, start_pos.y - pos.y);
- for(int y = 0, wt_y = wt_start.y; y < val_block.LengthY(); ++y, ++wt_y)
+ for (int y = 0, wt_y=wt_start.y; y < val_block.LengthY(); ++y, ++wt_y)
{
- for(int x = 0, wt_x = wt_start.x; x < val_block.LengthX(); ++x, ++wt_x)
+ for (int x = 0, wt_x=wt_start.x; x < val_block.LengthX(); ++x, ++wt_x)
{
val_block[y][x] *= wt_array[wt_y][wt_x];
}
@@ -702,24 +700,24 @@ void MotionCompensator::AdjustBlockBySpatialWeights(
}
#endif
-void MotionCompensator::CalculateWeights(int xbsep, int ybsep,
- TwoDArray<ValueType>* wts_array)
+void MotionCompensator::CalculateWeights( int xbsep, int ybsep,
+ TwoDArray<ValueType>* wts_array)
{
// Firstly calculate the non-weighted Weighting blocks. i,e, assuming that
// the picture_weight for each reference picture is 1.
// We can create all nine weighting blocks by calculating values
// for four blocks and mirroring them to generate the others.
- CreateBlock(xbsep, ybsep, false , false , wts_array[0]);
- CreateBlock(xbsep, ybsep, false , true , wts_array[3]);
- CreateBlock(xbsep, ybsep, true , false , wts_array[1]);
- CreateBlock(xbsep, ybsep, true , true , wts_array[4]);
+ CreateBlock( xbsep, ybsep, false , false , wts_array[0] );
+ CreateBlock( xbsep, ybsep, false , true , wts_array[3] );
+ CreateBlock( xbsep, ybsep, true , false , wts_array[1] );
+ CreateBlock( xbsep, ybsep, true , true , wts_array[4] );
// Note order of flipping is important.
- FlipX(wts_array[3] , wts_array[5]);
- FlipX(wts_array[0] , wts_array[2]);
- FlipY(wts_array[0] , wts_array[6]);
- FlipX(wts_array[6] , wts_array[8]);
- FlipY(wts_array[1] , wts_array[7]);
+ FlipX( wts_array[3] , wts_array[5] );
+ FlipX( wts_array[0] , wts_array[2] );
+ FlipY( wts_array[0] , wts_array[6] );
+ FlipX( wts_array[6] , wts_array[8] );
+ FlipY( wts_array[1] , wts_array[7] );
}
// Calculates a weighting block.
@@ -734,64 +732,64 @@ void MotionCompensator::CalculateWeights(int xbsep, int ybsep,
// * * *
// * * *
//* * *
-void MotionCompensator::CreateBlock(int xbsep, int ybsep,
- bool FullX , bool FullY ,
- TwoDArray<ValueType>& WeightArray)
+void MotionCompensator::CreateBlock( int xbsep, int ybsep,
+ bool FullX , bool FullY ,
+ TwoDArray<ValueType>& WeightArray)
{
// Create temporary arrays
int xblen = WeightArray.LengthX();
int yblen = WeightArray.LengthY();
- OneDArray<ValueType> HWts(xblen);
- OneDArray<ValueType> VWts(yblen);
+ OneDArray<ValueType> HWts( xblen );
+ OneDArray<ValueType> VWts( yblen );
// Window in the x direction
- int xoffset = (xblen - xbsep) / 2;
- if(xoffset != 1)
+ int xoffset = (xblen - xbsep)/2;
+ if ( xoffset != 1 )
{
- for(int x = 0; x < 2 * xoffset; ++x)
+ for(int x = 0; x < 2*xoffset; ++x)
{
- HWts[x] = 1 + (6 * x + xoffset - 1) / (2 * xoffset - 1);
+ HWts[x] = 1 + (6*x + xoffset-1)/(2*xoffset-1);
HWts[x+xbsep] = 8 - HWts[x];
}// x
}
else
{
- HWts[0] = HWts[1+xbsep] = 3;
- HWts[1] = HWts[xbsep] = 5;
+ HWts[0]=HWts[1+xbsep]=3;
+ HWts[1]=HWts[xbsep]=5;
}
- for(int x = 2 * xoffset; x < xbsep; ++x)
- HWts[x] = 8;
+ for (int x = 2*xoffset; x < xbsep; ++x)
+ HWts[x] = 8;
// Window in the y direction
- int yoffset = (yblen - ybsep) / 2;
- if(yoffset != 1)
+ int yoffset = (yblen - ybsep)/2;
+ if ( yoffset != 1 )
{
- for(int y = 0; y < 2 * yoffset; ++y)
+ for(int y = 0; y < 2*yoffset; ++y)
{
- VWts[y] = 1 + (6 * y + yoffset - 1) / (2 * yoffset - 1);
+ VWts[y] = 1 + (6 *y + yoffset-1)/(2*yoffset-1);
VWts[y+ybsep] = 8 - VWts[y];
}// y
}
else
{
- VWts[0] = VWts[1+ybsep] = 3;
- VWts[1] = VWts[ybsep] = 5;
+ VWts[0]=VWts[1+ybsep]=3;
+ VWts[1]=VWts[ybsep]=5;
}
- for(int y = 2 * yoffset; y < ybsep; ++y)
- VWts[y] = 8;
+ for (int y = 2*yoffset; y < ybsep; ++y)
+ VWts[y] = 8;
// Now reflect or pad, as appropriate
- if(!FullX)
+ if (!FullX)
{
- for(int x = 0; x < 2 * xoffset; ++x)
+ for( int x = 0; x < 2*xoffset; ++x)
HWts[x] = 8;
}
// Reflect or pad, as appropriate
- if(!FullY)
+ if (!FullY)
{
- for(int y = 0 ; y < 2 * yoffset; ++y)
+ for( int y = 0 ; y < 2*yoffset; ++y)
VWts[y] = 8;
}
@@ -805,8 +803,8 @@ void MotionCompensator::CreateBlock(int xbsep, int ybsep,
}
// Flips the values in an array in the x direction.
-void MotionCompensator::FlipX(const TwoDArray<ValueType>& Original ,
- TwoDArray<ValueType>& Flipped)
+void MotionCompensator::FlipX( const TwoDArray<ValueType>& Original ,
+ TwoDArray<ValueType>& Flipped)
{
int yblen = Original.LengthY();
int xblen = Original.LengthX();
@@ -820,8 +818,8 @@ void MotionCompensator::FlipX(const TwoDArray<ValueType>& Original ,
}
// Flips the values in an array in the y direction.
-void MotionCompensator::FlipY(const TwoDArray<ValueType>& Original ,
- TwoDArray<ValueType>& Flipped)
+void MotionCompensator::FlipY( const TwoDArray<ValueType>& Original ,
+ TwoDArray<ValueType>& Flipped)
{
int yblen = Original.LengthY();
int xblen = Original.LengthX();
@@ -841,22 +839,22 @@ void MotionCompensator::FlipY(const TwoDArray<ValueType>& Original ,
// Motion Compesation class that provides pixel precision compensation
-MotionCompensator_Pixel::MotionCompensator_Pixel(const PicturePredParams &ppp) :
- MotionCompensator(ppp)
+MotionCompensator_Pixel::MotionCompensator_Pixel( const PicturePredParams &ppp ) :
+ MotionCompensator( ppp )
{}
void MotionCompensator_Pixel::BlockPixelPred(
- TwoDArray<ValueType> &block_data ,
- const ImageCoords& pos,
- const ImageCoords& pic_size ,
- const PicArray &refup_data ,
- const MVector &mv)
+ TwoDArray<ValueType> &block_data ,
+ const ImageCoords& pos,
+ const ImageCoords& pic_size ,
+ const PicArray &refup_data ,
+ const MVector &mv)
{
//Coordinates in the image being written to.
- const ImageCoords start_pos(std::max(pos.x, 0) , std::max(pos.y, 0));
+ const ImageCoords start_pos( std::max(pos.x,0) , std::max(pos.y,0) );
//Where to start in the upconverted image - scaled since ref is upconverted
- const ImageCoords ref_start((start_pos.x + mv.x) << 1 , (start_pos.y + mv.y) << 1);
+ const ImageCoords ref_start( (start_pos.x + mv.x)<<1 , (start_pos.y + mv.y)<<1 );
//An additional stage to make sure the block to be copied does not fall outside
//the reference image.
@@ -868,23 +866,23 @@ void MotionCompensator_Pixel::BlockPixelPred(
//Check if there are going to be any problems copying the block from
//the upvconverted reference image.
- if(ref_start.x < 0)
+ if( ref_start.x < 0 )
do_bounds_checking = true;
- else if(ref_start.x + ((block_data.LengthX() - 1) << 1) >= trueRefXlen)
+ else if( ref_start.x + ((block_data.LengthX() - 1)<<1 ) >= trueRefXlen )
do_bounds_checking = true;
- if(ref_start.y < 0)
+ if( ref_start.y < 0 )
do_bounds_checking = true;
- else if(ref_start.y + ((block_data.LengthY() - 1) << 1) >= trueRefYlen)
+ else if( ref_start.y + ((block_data.LengthY() - 1)<<1 ) >= trueRefYlen)
do_bounds_checking = true;
ValueType *block_curr = &block_data[0][0];
- if(!do_bounds_checking)
+ if( !do_bounds_checking )
{
ValueType *refup_curr = &refup_data[ref_start.y][ref_start.x];
- const int refup_next(2 *(refXlen - block_data.LengthX())); // - go down a row and back up
- for(int y = 0; y < block_data.LengthY(); ++y, refup_curr += refup_next)
+ const int refup_next( 2*(refXlen - block_data.LengthX()) ); // - go down a row and back up
+ for( int y=0; y < block_data.LengthY(); ++y, refup_curr+=refup_next )
{
- for(int x = 0; x < block_data.LengthX(); ++x, ++block_curr, refup_curr += 2)
+ for( int x=0; x < block_data.LengthX(); ++x, ++block_curr, refup_curr+=2 )
{
*block_curr = *refup_curr;
}// x
@@ -894,14 +892,14 @@ void MotionCompensator_Pixel::BlockPixelPred(
{
// We're doing bounds checking because we'll fall off the edge of the reference otherwise.
- for(int y = 0, ry = ref_start.y, by = BChk(ry, trueRefYlen);
- y < block_data.LengthY(); ++y, ry += 2 , by = BChk(ry, trueRefYlen))
+ for( int y=0, ry=ref_start.y, by=BChk(ry,trueRefYlen);
+ y < block_data.LengthY(); ++y, ry+=2 , by=BChk(ry,trueRefYlen) )
{
- for(int x = 0 , rx = ref_start.x , bx = BChk(rx, trueRefXlen);
- x < block_data.LengthX() ; ++x, ++block_curr, rx += 2 , bx = BChk(rx, trueRefXlen))
- {
- *block_curr = refup_data[by][bx];
- }// x
+ for( int x=0 , rx=ref_start.x , bx=BChk(rx,trueRefXlen);
+ x <block_data.LengthX() ; ++x, ++block_curr, rx+=2 , bx=BChk(rx,trueRefXlen) )
+ {
+ *block_curr = refup_data[by][bx];
+ }// x
}// y
}
@@ -909,21 +907,21 @@ void MotionCompensator_Pixel::BlockPixelPred(
// Motion Compesation class that provides half-pixel precision compensation
-MotionCompensator_HalfPixel::MotionCompensator_HalfPixel(const PicturePredParams &ppp) :
- MotionCompensator(ppp)
+MotionCompensator_HalfPixel::MotionCompensator_HalfPixel( const PicturePredParams &ppp ) :
+ MotionCompensator( ppp )
{}
#if !defined (HAVE_MMX)
void MotionCompensator_HalfPixel::BlockPixelPred(
- TwoDArray<ValueType> &block_data ,
- const ImageCoords& pos ,
- const ImageCoords& pic_size ,
- const PicArray &refup_data ,
- const MVector &mv)
+ TwoDArray<ValueType> &block_data ,
+ const ImageCoords& pos ,
+ const ImageCoords& pic_size ,
+ const PicArray &refup_data ,
+ const MVector &mv)
{
//Where to start in the upconverted image
- const ImageCoords start_pos(std::max(pos.x, 0) , std::max(pos.y, 0));
- const ImageCoords ref_start((start_pos.x << 1) + mv.x , (start_pos.y << 1) + mv.y);
+ const ImageCoords start_pos( std::max(pos.x,0) , std::max(pos.y,0) );
+ const ImageCoords ref_start( ( start_pos.x<<1 ) + mv.x ,( start_pos.y<<1 ) + mv.y );
//An additional stage to make sure the block to be copied does not fall
//outsidethe reference image.
@@ -937,25 +935,25 @@ void MotionCompensator_HalfPixel::BlockPixelPred(
//Check if there are going to be any problems copying the block from
//the upvconverted reference image.
- if(ref_start.x < 0)
+ if( ref_start.x < 0 )
do_bounds_checking = true;
- else if(ref_start.x + ((block_data.LengthX() - 1) << 1) >= trueRefXlen)
+ else if( ref_start.x + ((block_data.LengthX() -1 )<<1 ) >= trueRefXlen )
do_bounds_checking = true;
- if(ref_start.y < 0)
+ if( ref_start.y < 0 )
do_bounds_checking = true;
- else if(ref_start.y + ((block_data.LengthY() - 1) << 1) >= trueRefYlen)
+ else if( ref_start.y + ((block_data.LengthY() - 1 )<<1 ) >= trueRefYlen)
do_bounds_checking = true;
ValueType *block_curr = &block_data[0][0];
- if(!do_bounds_checking)
+ if( !do_bounds_checking )
{
ValueType *refup_curr = &refup_data[ref_start.y][ref_start.x];
- const int refup_next((refXlen - block_data.LengthX()) * 2);// go down 2 rows and back up
+ const int refup_next( (refXlen - block_data.LengthX())*2 );// go down 2 rows and back up
- for(int y = 0; y < block_data.LengthY(); ++y, refup_curr += refup_next)
+ for( int y=0; y < block_data.LengthY(); ++y, refup_curr+=refup_next )
{
- for(int x = 0; x < block_data.LengthX(); ++x, ++block_curr, refup_curr += 2)
+ for( int x=0; x < block_data.LengthX(); ++x, ++block_curr, refup_curr+=2 )
{
*block_curr = refup_curr[0];
}
@@ -964,108 +962,108 @@ void MotionCompensator_HalfPixel::BlockPixelPred(
else
{
// We're doing bounds checking because we'll fall off the edge of the reference otherwise.
- for(int y = 0, ry = ref_start.y, by = BChk(ry, trueRefYlen);
- y < block_data.LengthY(); ++y, ry += 2 , by = BChk(ry, trueRefYlen))
+ for( int y=0, ry=ref_start.y, by=BChk(ry,trueRefYlen);
+ y<block_data.LengthY(); ++y, ry+=2 , by=BChk(ry,trueRefYlen))
{
- for(int x = 0 , rx = ref_start.x , bx = BChk(rx, trueRefXlen);
- x < block_data.LengthX() ;
- ++x, ++block_curr, rx += 2 , bx = BChk(rx, trueRefXlen))
- {
- *block_curr = refup_data[by][bx];
- }// x
+ for( int x=0 , rx=ref_start.x , bx=BChk(rx,trueRefXlen);
+ x<block_data.LengthX() ;
+ ++x, ++block_curr, rx+=2 , bx=BChk(rx,trueRefXlen))
+ {
+ *block_curr = refup_data[by][bx];
+ }// x
}// y
}
}
#endif
// Motion Compesation class that provides quarter-pixel precision compensation
-MotionCompensator_QuarterPixel::MotionCompensator_QuarterPixel(const PicturePredParams &ppp) :
- MotionCompensator(ppp)
+MotionCompensator_QuarterPixel::MotionCompensator_QuarterPixel( const PicturePredParams &ppp ) :
+ MotionCompensator( ppp )
{}
#if !defined (HAVE_MMX)
void MotionCompensator_QuarterPixel::BlockPixelPred(
- TwoDArray<ValueType> &block_data ,
- const ImageCoords& pos ,
- const ImageCoords& pic_size ,
- const PicArray &refup_data ,
- const MVector &mv)
+ TwoDArray<ValueType> &block_data ,
+ const ImageCoords& pos ,
+ const ImageCoords& pic_size ,
+ const PicArray &refup_data ,
+ const MVector &mv)
{
// Set up the start point in the reference image by rounding the motion vector
// to 1/2 pel accuracy.NB: bit shift rounds negative values DOWN, as required
- const MVector roundvec(mv.x >> 1 , mv.y >> 1);
+ const MVector roundvec( mv.x>>1 , mv.y>>1 );
//Get the remainder after rounding. NB rmdr values always 0 or 1
- const MVector rmdr(mv.x & 1 , mv.y & 1);
+ const MVector rmdr( mv.x & 1 , mv.y & 1 );
//Where to start in the upconverted image
- const ImageCoords start_pos(std::max(pos.x, 0) , std::max(pos.y, 0));
- const ImageCoords ref_start((start_pos.x << 1) + roundvec.x , (start_pos.y << 1) + roundvec.y);
+ const ImageCoords start_pos( std::max(pos.x,0) , std::max(pos.y,0) );
+ const ImageCoords ref_start( ( start_pos.x<<1 ) + roundvec.x ,( start_pos.y<<1 ) + roundvec.y );
//An additional stage to make sure the block to be copied does not fall outside
//the reference image.
const int refXlen = refup_data.LengthX();
//const int refYlen = refup_data.LengthY();
- const int trueRefXlen = (pic_size.x << 1) - 1;
- const int trueRefYlen = (pic_size.y << 1) - 1;
+ const int trueRefXlen = (pic_size.x<<1) - 1;
+ const int trueRefYlen = (pic_size.y<<1) - 1;
ValueType *block_curr = &block_data[0][0];
bool do_bounds_checking = false;
//Check if there are going to be any problems copying the block from
//the upvconverted reference image.
- if(ref_start.x < 0)
+ if( ref_start.x < 0 )
do_bounds_checking = true;
- else if(ref_start.x + (block_data.LengthX() << 1) >= trueRefXlen)
+ else if( ref_start.x + (block_data.LengthX()<<1 ) >= trueRefXlen )
do_bounds_checking = true;
- if(ref_start.y < 0)
+ if( ref_start.y < 0 )
do_bounds_checking = true;
- else if(ref_start.y + (block_data.LengthY() << 1) >= trueRefYlen)
+ else if( ref_start.y + (block_data.LengthY()<<1 ) >= trueRefYlen )
do_bounds_checking = true;
- if(!do_bounds_checking)
+ if( !do_bounds_checking )
{
ValueType *refup_curr = &refup_data[ref_start.y][ref_start.x];
- const int refup_next((refXlen - block_data.LengthX()) * 2); //go down 2 rows and back to beginning of block line
- if(rmdr.x == 0 && rmdr.y == 0)
+ const int refup_next( ( refXlen - block_data.LengthX() )*2 ); //go down 2 rows and back to beginning of block line
+ if( rmdr.x == 0 && rmdr.y == 0 )
{
- for(int y = 0; y < block_data.LengthY(); ++y, refup_curr += refup_next)
+ for( int y=0; y < block_data.LengthY(); ++y, refup_curr+=refup_next )
{
- for(int x = 0; x < block_data.LengthX(); ++x, ++block_curr, refup_curr += 2)
+ for( int x=0; x < block_data.LengthX(); ++x, ++block_curr, refup_curr+=2 )
{
*block_curr = refup_curr[0];
}
}
}
- else if(rmdr.y == 0)
+ else if( rmdr.y == 0 )
{
- for(int y = 0; y < block_data.LengthY(); ++y, refup_curr += refup_next)
+ for( int y=0; y < block_data.LengthY(); ++y, refup_curr+=refup_next )
{
- for(int x = 0; x < block_data.LengthX(); ++x, ++block_curr, refup_curr += 2)
+ for( int x=0; x < block_data.LengthX(); ++x, ++block_curr, refup_curr+=2 )
{
*block_curr = (refup_curr[0] + refup_curr[1] + 1) >> 1;
}
}
}
- else if(rmdr.x == 0)
+ else if( rmdr.x == 0 )
{
- for(int y = 0; y < block_data.LengthY(); ++y, refup_curr += refup_next)
+ for( int y=0; y < block_data.LengthY(); ++y, refup_curr+=refup_next )
{
- for(int x = 0; x < block_data.LengthX(); ++x, ++block_curr, refup_curr += 2)
+ for( int x=0; x < block_data.LengthX(); ++x, ++block_curr, refup_curr+=2 )
{
- *block_curr = (refup_curr[0] + refup_curr[refXlen] + 1) >> 1;
+ *block_curr = ( refup_curr[0] + refup_curr[refXlen] + 1 ) >> 1;
}
}
}
else
{
- for(int y = 0; y < block_data.LengthY(); ++y, refup_curr += refup_next)
+ for( int y=0; y < block_data.LengthY(); ++y, refup_curr+=refup_next )
{
- for(int x = 0; x < block_data.LengthX(); ++x, ++block_curr, refup_curr += 2)
+ for( int x=0; x < block_data.LengthX(); ++x, ++block_curr, refup_curr+=2 )
{
- *block_curr = (refup_curr[0] + refup_curr[1] +
- refup_curr[refXlen+0] +
- refup_curr[refXlen+1] + 2) >> 2;
+ *block_curr = ( refup_curr[0] + refup_curr[1] +
+ refup_curr[refXlen+0] +
+ refup_curr[refXlen+1] + 2 ) >> 2;
}
}
}
@@ -1075,28 +1073,27 @@ void MotionCompensator_QuarterPixel::BlockPixelPred(
// We're doing bounds checking because we'll fall off the edge of the reference otherwise.
//weights for doing linear interpolation, calculated from the remainder values
- const ValueType linear_wts[4] = { (2 - rmdr.x) *(2 - rmdr.y), //tl
- rmdr.x *(2 - rmdr.y), //tr
+ const ValueType linear_wts[4] = { (2 - rmdr.x) * (2 - rmdr.y), //tl
+ rmdr.x * (2 - rmdr.y), //tr
(2 - rmdr.x) * rmdr.y, //bl
- rmdr.x * rmdr.y
- }; //br
+ rmdr.x * rmdr.y }; //br
- for(int c = 0, uY = ref_start.y, BuY = BChk(uY, trueRefYlen), BuY1 = BChk(uY + 1, trueRefYlen);
- c < block_data.LengthY(); ++c, uY += 2, BuY = BChk(uY, trueRefYlen), BuY1 = BChk(uY + 1, trueRefYlen))
- {
- for(int l = 0, uX = ref_start.x, BuX = BChk(uX, trueRefXlen), BuX1 = BChk(uX + 1, trueRefXlen);
- l < block_data.LengthX(); ++l, uX += 2, BuX = BChk(uX, trueRefXlen), BuX1 = BChk(uX + 1, trueRefXlen))
- {
+ for(int c = 0, uY = ref_start.y,BuY=BChk(uY,trueRefYlen),BuY1=BChk(uY+1,trueRefYlen);
+ c < block_data.LengthY(); ++c, uY += 2,BuY=BChk(uY,trueRefYlen),BuY1=BChk(uY+1,trueRefYlen))
+ {
+ for(int l = 0, uX = ref_start.x,BuX=BChk(uX,trueRefXlen),BuX1=BChk(uX+1,trueRefXlen);
+ l < block_data.LengthX(); ++l, uX += 2,BuX=BChk(uX,trueRefXlen),BuX1=BChk(uX+1,trueRefXlen))
+ {
- block_data[c][l] = (linear_wts[0] * refup_data[BuY][BuX] +
- linear_wts[1] * refup_data[BuY][BuX1] +
- linear_wts[2] * refup_data[BuY1][BuX] +
- linear_wts[3] * refup_data[BuY1][BuX1] +
- 2
+ block_data[c][l] = ( linear_wts[0] * refup_data[BuY][BuX] +
+ linear_wts[1] * refup_data[BuY][BuX1] +
+ linear_wts[2] * refup_data[BuY1][BuX] +
+ linear_wts[3] * refup_data[BuY1][BuX1] +
+ 2
) >> 2;
- }//l
- }//c
+ }//l
+ }//c
}
}
@@ -1104,35 +1101,34 @@ void MotionCompensator_QuarterPixel::BlockPixelPred(
// Motion Compesation class that provides one eighth-pixel precision
// compensation
-MotionCompensator_EighthPixel::MotionCompensator_EighthPixel(const PicturePredParams &ppp) :
- MotionCompensator(ppp)
+MotionCompensator_EighthPixel::MotionCompensator_EighthPixel( const PicturePredParams &ppp ) :
+ MotionCompensator( ppp )
{}
void MotionCompensator_EighthPixel::BlockPixelPred(
- TwoDArray<ValueType> &block_data ,
- const ImageCoords& pos ,
- const ImageCoords& pic_size ,
- const PicArray &refup_data ,
- const MVector &mv)
+ TwoDArray<ValueType> &block_data ,
+ const ImageCoords& pos ,
+ const ImageCoords& pic_size ,
+ const PicArray &refup_data ,
+ const MVector &mv)
{
//Set up the start point in the reference image by rounding the motion vector
//NB: bit shift rounds negative values DOWN, as required
- const MVector roundvec(mv.x >> 2 , mv.y >> 2);
+ const MVector roundvec( mv.x>>2 , mv.y>>2 );
//Get the remainder after rounding. NB rmdr values always 0,1,2 or 3
- const MVector rmdr(mv.x & 3 , mv.y & 3);
+ const MVector rmdr( mv.x & 3 , mv.y & 3 );
//Where to start in the upconverted image
- const ImageCoords start_pos(std::max(pos.x, 0) , std::max(pos.y, 0));
- const ImageCoords ref_start((start_pos.x << 1) + roundvec.x , (start_pos.y << 1) + roundvec.y);
+ const ImageCoords start_pos( std::max(pos.x,0) , std::max(pos.y,0) );
+ const ImageCoords ref_start( ( start_pos.x<<1 ) + roundvec.x ,( start_pos.y<<1 ) + roundvec.y );
//weights for doing linear interpolation, calculated from the remainder values
- const ValueType linear_wts[4] = { (4 - rmdr.x) *(4 - rmdr.y), //tl
- rmdr.x *(4 - rmdr.y), //tr
- (4 - rmdr.x) * rmdr.y, //bl
- rmdr.x * rmdr.y
- }; //br
+ const ValueType linear_wts[4] = { (4 - rmdr.x) * (4 - rmdr.y), //tl
+ rmdr.x * (4 - rmdr.y), //tr
+ (4 - rmdr.x) * rmdr.y, //bl
+ rmdr.x * rmdr.y }; //br
//An additional stage to make sure the block to be copied does not fall outside
//the reference image.
@@ -1144,74 +1140,74 @@ void MotionCompensator_EighthPixel::BlockPixelPred(
//Check if there are going to be any problems copying the block from
//the upvconverted reference image.
- if(ref_start.x < 0)
+ if( ref_start.x < 0 )
do_bounds_checking = true;
- else if(ref_start.x + (block_data.LengthX() << 1) >= trueRefXlen)
+ else if( ref_start.x + (block_data.LengthX()<<1 ) >= trueRefXlen )
do_bounds_checking = true;
- if(ref_start.y < 0)
+ if( ref_start.y < 0 )
do_bounds_checking = true;
- else if(ref_start.y + (block_data.LengthY() << 1) >= trueRefYlen)
+ else if( ref_start.y + (block_data.LengthY()<<1 ) >= trueRefYlen)
do_bounds_checking = true;
- if(!do_bounds_checking)
+ if( !do_bounds_checking )
{
ValueType *block_curr = &block_data[0][0];
ValueType *refup_curr = &refup_data[ref_start.y][ref_start.x];
- const int refup_next = (refup_data.LengthX() - block_data.LengthX()) * 2; //go down 2 rows and back up
+ const int refup_next = (refup_data.LengthX() - block_data.LengthX() )*2; //go down 2 rows and back up
- if(rmdr.x == 0 && rmdr.y == 0)
+ if( rmdr.x == 0 && rmdr.y == 0 )
{
- for(int y = 0; y < block_data.LengthY(); ++y, refup_curr += refup_next)
+ for( int y=0; y < block_data.LengthY(); ++y, refup_curr+=refup_next )
{
- for(int x = 0; x < block_data.LengthX(); ++x, ++block_curr, refup_curr += 2)
+ for( int x=0; x < block_data.LengthX(); ++x, ++block_curr, refup_curr+=2 )
{
*block_curr = refup_curr[0];
}
}
}
- else if(rmdr.y == 0)
+ else if( rmdr.y == 0 )
{
- for(int y = 0; y < block_data.LengthY(); ++y, refup_curr += refup_next)
+ for( int y=0; y < block_data.LengthY(); ++y, refup_curr+=refup_next )
{
- for(int x = 0; x < block_data.LengthX(); ++x, ++block_curr, refup_curr += 2)
+ for( int x=0; x < block_data.LengthX(); ++x, ++block_curr, refup_curr+=2 )
{
- *block_curr = (
+ *block_curr = (
linear_wts[0] * refup_curr[0] +
linear_wts[1] * refup_curr[1] +
- 8
- ) >> 4;
+ 8
+ ) >> 4;
}
}
}
- else if(rmdr.x == 0)
+ else if( rmdr.x == 0 )
{
- for(int y = 0; y < block_data.LengthY(); ++y, refup_curr += refup_next)
+ for( int y=0; y < block_data.LengthY(); ++y, refup_curr+=refup_next )
{
- for(int x = 0; x < block_data.LengthX(); ++x, ++block_curr, refup_curr += 2)
+ for( int x=0; x < block_data.LengthX(); ++x, ++block_curr, refup_curr+=2 )
{
- *block_curr = (
- linear_wts[0] * refup_curr[0] +
- linear_wts[2] * refup_curr[refXlen+0] +
- 8
- ) >> 4;
+ *block_curr = (
+ linear_wts[0] * refup_curr[0] +
+ linear_wts[2] * refup_curr[refXlen+0] +
+ 8
+ ) >> 4;
}
}
}
else
{
- for(int y = 0; y < block_data.LengthY(); ++y, refup_curr += refup_next)
+ for( int y=0; y < block_data.LengthY(); ++y, refup_curr+=refup_next )
{
- for(int x = 0; x < block_data.LengthX(); ++x, ++block_curr, refup_curr += 2)
+ for( int x=0; x < block_data.LengthX(); ++x, ++block_curr, refup_curr+=2 )
{
- *block_curr = (
+ *block_curr = (
linear_wts[0] * refup_curr[0] +
linear_wts[1] * refup_curr[1] +
linear_wts[2] * refup_curr[refXlen+0] +
linear_wts[3] * refup_curr[refXlen+1] +
8
- ) >> 4;
+ ) >> 4;
}
}
}
@@ -1220,12 +1216,12 @@ void MotionCompensator_EighthPixel::BlockPixelPred(
{
// We're doing bounds checking because we'll fall off the edge of the reference otherwise.
- for(int c = 0, uY = ref_start.y, BuY = BChk(uY, trueRefYlen), BuY1 = BChk(uY + 1, trueRefYlen);
- c < block_data.LengthY(); ++c, uY += 2, BuY = BChk(uY, trueRefYlen), BuY1 = BChk(uY + 1, trueRefYlen))
+ for(int c = 0, uY = ref_start.y,BuY=BChk(uY,trueRefYlen),BuY1=BChk(uY+1,trueRefYlen);
+ c < block_data.LengthY(); ++c, uY += 2,BuY=BChk(uY,trueRefYlen),BuY1=BChk(uY+1,trueRefYlen))
{
- for(int l = 0, uX = ref_start.x, BuX = BChk(uX, trueRefXlen), BuX1 = BChk(uX + 1, trueRefXlen);
- l < block_data.LengthX();
- ++l, uX += 2, BuX = BChk(uX, trueRefXlen), BuX1 = BChk(uX + 1, trueRefXlen))
+ for(int l = 0, uX = ref_start.x,BuX=BChk(uX,trueRefXlen),BuX1=BChk(uX+1,trueRefXlen);
+ l < block_data.LengthX();
+ ++l, uX += 2,BuX=BChk(uX,trueRefXlen),BuX1=BChk(uX+1,trueRefXlen))
{
block_data[c][l] = (
diff --git a/src/filters/parser/DiracSplitter/libdirac/libdirac_common/mot_comp.h b/src/filters/parser/DiracSplitter/libdirac/libdirac_common/mot_comp.h
index d69675abf..7974cc1db 100644
--- a/src/filters/parser/DiracSplitter/libdirac/libdirac_common/mot_comp.h
+++ b/src/filters/parser/DiracSplitter/libdirac/libdirac_common/mot_comp.h
@@ -57,243 +57,243 @@
namespace dirac
{
-class PictureBuffer;
-class Picture;
-
-//! Abstract Motion compensator class.
-/*!
- Motion compensator class, for doing motion compensation with two
- references and overlapped blocks, using raised-cosine roll-off.
- This is an abstract class. It must be sub-classed and the
- BlockPixelPred must be defined in the sub-classes.
-*/
-class MotionCompensator
-{
-
-public:
- //! Constructor.
- /*!
- Constructor initialises using codec parameters.
- */
- MotionCompensator(const PicturePredParams &ppp);
- //! Destructor
- virtual ~MotionCompensator();
+ class PictureBuffer;
+ class Picture;
- //! Convenience function to perform motion compensation on a picture
- /*!
- Static function that motion compensates a picture. It uses the
- MV precision value in the PicturePredParams to instantiate the
- appropriate MotionCompensation sub-class.
- \param ppp Picture prediction parameters
- \param direction whether we're subtracting or adding
- \param mv_data the motion vector data
- \param in_pic Pointer to picture being motion compensated
- \param refptr Array of pointers to reference pictures.
- */
- static void CompensatePicture(const PicturePredParams &ppp,
- const AddOrSub direction ,
- const MvData& mv_data,
- Picture* in_pic ,
- Picture* refptr[2]);
-
- //! Compensate a picture
+ //! Abstract Motion compensator class.
/*!
- Perform motion compensated addition/subtraction on a picture using
- parameters
- \param direction whether we're subtracting or adding
- ` \param mv_data the motion vector data
- \param in_pic Pointer to picture being motion compensated
- \param refsptr Array of pointers to reference pictures.
- */
- void CompensatePicture(const AddOrSub direction ,
- const MvData& mv_data,
- Picture* in_pic ,
- Picture* refsptr[2]);
-
-private:
- //private, body-less copy constructor: this class should not be copied
- MotionCompensator(const MotionCompensator& cpy);
- //private, body-less assignment=: this class should not be assigned
- MotionCompensator& operator=(const MotionCompensator& rhs);
-
- //functions
-
- //! Motion-compensate a component
- void CompensateComponent(Picture* pic ,
- Picture* refsptr[2] ,
- const MvData& mv_data , const CompSort cs);
-
- //! Recalculate the weight matrix and store other key block related parameters.
- //! DC-compensate an individual block
- void DCBlock(TwoDArray<ValueType> &block_data ,
- const ValueType dc);
- void ReConfig();
-
- // Calculates a weighting arrays blocks.
- void CalculateWeights(int xbsep, int ybsep, TwoDArray<ValueType>* wt_array);
-
- //! Calculates a weighting block.
- /*!
- Params defines the block parameters so the relevant weighting
- arrays can be created. FullX and FullY refer to whether the
- weight should be adjusted for the edge of an image. eg. 1D
- Weighting shapes in x direction
- FullX true FullX false
- *** ********
- * * *
- * * *
- * * *
- */
- void CreateBlock(int xbsep, int ybsep, bool FullX, bool FullY, TwoDArray<ValueType>& WeightArray);
-
- //! Flips the values in an array in the x direction
- void FlipX(const TwoDArray<ValueType>& Original, TwoDArray<ValueType>& Flipped);
-
- //! Flips the values in an array in the y direction.
- void FlipY(const TwoDArray<ValueType>& Original, TwoDArray<ValueType>& Flipped);
-
- virtual void CompensateBlock(TwoDArray<ValueType>& pic_data ,
- const ImageCoords& pos ,
- const ImageCoords &orig_pic_size,
- PredMode block_mode,
- ValueType dc,
- const PicArray& ref1up_data ,
- const MVector& mv1 ,
- const PicArray& ref2up_data ,
- const MVector& mv2 ,
- const TwoDArray<ValueType>& Weights);
- //! Predict pixels in a block. Pure virtual. SubClasses need to define it
- virtual void BlockPixelPred(TwoDArray<ValueType>& block_data ,
- const ImageCoords& pos,
- const ImageCoords &orig_pic_size,
- const PicArray& refup_data ,
- const MVector& mv) = 0;
-
- // Adjust the block value based on reference weights
- /*
- * Adjust the block value based on reference weights of each
- * reference picture.
- * val1_block - Block predicted from a single reference picture
- * val2_block - Block predicted from second reference picture
- * mode is REF1AND2
- * block_mode - Block prediction mode.
- *
- * On return, val1_block will contain the weight reference weight
- * adjusted block values
+ Motion compensator class, for doing motion compensation with two
+ references and overlapped blocks, using raised-cosine roll-off.
+ This is an abstract class. It must be sub-classed and the
+ BlockPixelPred must be defined in the sub-classes.
*/
- void AdjustBlockByRefWeights(TwoDArray<ValueType>& val1_block,
- TwoDArray<ValueType>& val2_block,
- PredMode block_mode);
-
- // Adjust the block value based spatial weighting matrix
- /*
- * Adjust the block value based on spatial weighting matrix
- * val_block - Predicted block
- * pos - position of top lef corner of block in picture
- * wt_array - spatial weighting matrix
- *
- * On return, val_block will contain the spatial weight adjusted block
- * values
- */
- void AdjustBlockBySpatialWeights(TwoDArray<ValueType>& val_block,
- const ImageCoords &pos,
- const TwoDArray<ValueType> &wt_array);
-protected:
- //variables
-
- //! The codec parameters
- PicturePredParams m_predparams;
-
- //! The chroma format
- ChromaFormat m_cformat;
- bool luma_or_chroma; //true if we're doing luma, false if we're coding chroma
-
- // A marker saying whether we're doing MC addition or subtraction
- AddOrSub m_add_or_sub;
-
- // Block information
- OLBParams m_bparams;
- // Arrays of block weights
- TwoDArray<ValueType>* m_block_weights;
- // Arrays of super block weights
- TwoDArray<ValueType>* m_macro_block_weights;
- // Arrays of sub super block weights
- TwoDArray<ValueType>* m_sub_block_weights;
-};
-
-//! Pixel precision Motion compensator class.
-class MotionCompensator_Pixel : public MotionCompensator
-{
-
-public:
- //! Constructor.
- /*!
- Constructor initialises using codec parameters.
- */
- MotionCompensator_Pixel(const PicturePredParams &ppp);
-
-private:
- //! Motion-compensate a block.
- virtual void BlockPixelPred(TwoDArray<ValueType>& block_data ,
- const ImageCoords& pos,
- const ImageCoords &orig_pic_size,
- const PicArray& refup_data ,
- const MVector& mv);
-};
-
-//! Half Pixel precision Motion compensator class.
-class MotionCompensator_HalfPixel : public MotionCompensator
-{
-public:
- //! Constructor.
- /*!
- Constructor initialises using codec parameters.
- */
- MotionCompensator_HalfPixel(const PicturePredParams &ppp);
-private:
- //! Motion-compensate a block.
- virtual void BlockPixelPred(TwoDArray<ValueType>& block_data ,
- const ImageCoords& pos,
- const ImageCoords &orig_pic_size,
- const PicArray& refup_data ,
- const MVector& mv);
-};
-
-//! Quarter Pixel precision Motion compensator class.
-class MotionCompensator_QuarterPixel : public MotionCompensator
-{
-public:
- //! Constructor.
- /*!
- Constructor initialises using codec parameters.
- */
- MotionCompensator_QuarterPixel(const PicturePredParams &ppp);
-private:
- //! Motion-compensate a block.
- virtual void BlockPixelPred(TwoDArray<ValueType>& block_data ,
- const ImageCoords& pos,
- const ImageCoords &orig_pic_size,
- const PicArray& refup_data ,
- const MVector& mv);
-};
-
-//! Eighth Pixel precision Motion compensator class.
-class MotionCompensator_EighthPixel : public MotionCompensator
-{
-public:
- //! Constructor.
- /*!
- Constructor initialises using codec parameters.
- */
- MotionCompensator_EighthPixel(const PicturePredParams &ppp);
-private:
- //! Motion-compensate a block.
- virtual void BlockPixelPred(TwoDArray<ValueType>& block_data ,
- const ImageCoords& pos,
- const ImageCoords &orig_pic_size,
- const PicArray& refup_data ,
- const MVector& mv);
-};
+ class MotionCompensator
+ {
+
+ public:
+ //! Constructor.
+ /*!
+ Constructor initialises using codec parameters.
+ */
+ MotionCompensator( const PicturePredParams &ppp );
+ //! Destructor
+ virtual ~MotionCompensator();
+
+ //! Convenience function to perform motion compensation on a picture
+ /*!
+ Static function that motion compensates a picture. It uses the
+ MV precision value in the PicturePredParams to instantiate the
+ appropriate MotionCompensation sub-class.
+ \param ppp Picture prediction parameters
+ \param direction whether we're subtracting or adding
+ \param mv_data the motion vector data
+ \param in_pic Pointer to picture being motion compensated
+ \param refptr Array of pointers to reference pictures.
+ */
+ static void CompensatePicture ( const PicturePredParams &ppp,
+ const AddOrSub direction ,
+ const MvData& mv_data,
+ Picture* in_pic ,
+ Picture* refptr[2]);
+
+ //! Compensate a picture
+ /*!
+ Perform motion compensated addition/subtraction on a picture using
+ parameters
+ \param direction whether we're subtracting or adding
+ ` \param mv_data the motion vector data
+ \param in_pic Pointer to picture being motion compensated
+ \param refsptr Array of pointers to reference pictures.
+ */
+ void CompensatePicture( const AddOrSub direction ,
+ const MvData& mv_data,
+ Picture* in_pic ,
+ Picture* refsptr[2] );
+
+ private:
+ //private, body-less copy constructor: this class should not be copied
+ MotionCompensator( const MotionCompensator& cpy );
+ //private, body-less assignment=: this class should not be assigned
+ MotionCompensator& operator=( const MotionCompensator& rhs );
+
+ //functions
+
+ //! Motion-compensate a component
+ void CompensateComponent( Picture* pic ,
+ Picture* refsptr[2] ,
+ const MvData& mv_data , const CompSort cs);
+
+ //! Recalculate the weight matrix and store other key block related parameters.
+ //! DC-compensate an individual block
+ void DCBlock( TwoDArray<ValueType> &block_data ,
+ const ValueType dc);
+ void ReConfig();
+
+ // Calculates a weighting arrays blocks.
+ void CalculateWeights(int xbsep, int ybsep, TwoDArray<ValueType>* wt_array);
+
+ //! Calculates a weighting block.
+ /*!
+ Params defines the block parameters so the relevant weighting
+ arrays can be created. FullX and FullY refer to whether the
+ weight should be adjusted for the edge of an image. eg. 1D
+ Weighting shapes in x direction
+ FullX true FullX false
+ *** ********
+ * * *
+ * * *
+ * * *
+ */
+ void CreateBlock(int xbsep, int ybsep, bool FullX, bool FullY, TwoDArray<ValueType>& WeightArray);
+
+ //! Flips the values in an array in the x direction
+ void FlipX(const TwoDArray<ValueType>& Original, TwoDArray<ValueType>& Flipped);
+
+ //! Flips the values in an array in the y direction.
+ void FlipY(const TwoDArray<ValueType>& Original, TwoDArray<ValueType>& Flipped);
+
+ virtual void CompensateBlock( TwoDArray<ValueType>& pic_data ,
+ const ImageCoords& pos ,
+ const ImageCoords &orig_pic_size,
+ PredMode block_mode,
+ ValueType dc,
+ const PicArray& ref1up_data ,
+ const MVector& mv1 ,
+ const PicArray& ref2up_data ,
+ const MVector& mv2 ,
+ const TwoDArray<ValueType>& Weights );
+ //! Predict pixels in a block. Pure virtual. SubClasses need to define it
+ virtual void BlockPixelPred( TwoDArray<ValueType>& block_data ,
+ const ImageCoords& pos,
+ const ImageCoords &orig_pic_size,
+ const PicArray& refup_data ,
+ const MVector& mv) = 0;
+
+ // Adjust the block value based on reference weights
+ /*
+ * Adjust the block value based on reference weights of each
+ * reference picture.
+ * val1_block - Block predicted from a single reference picture
+ * val2_block - Block predicted from second reference picture
+ * mode is REF1AND2
+ * block_mode - Block prediction mode.
+ *
+ * On return, val1_block will contain the weight reference weight
+ * adjusted block values
+ */
+ void AdjustBlockByRefWeights (TwoDArray<ValueType>& val1_block,
+ TwoDArray<ValueType>& val2_block,
+ PredMode block_mode);
+
+ // Adjust the block value based spatial weighting matrix
+ /*
+ * Adjust the block value based on spatial weighting matrix
+ * val_block - Predicted block
+ * pos - position of top lef corner of block in picture
+ * wt_array - spatial weighting matrix
+ *
+ * On return, val_block will contain the spatial weight adjusted block
+ * values
+ */
+ void AdjustBlockBySpatialWeights (TwoDArray<ValueType>& val_block,
+ const ImageCoords &pos,
+ const TwoDArray<ValueType> &wt_array);
+ protected:
+ //variables
+
+ //! The codec parameters
+ PicturePredParams m_predparams;
+
+ //! The chroma format
+ ChromaFormat m_cformat;
+ bool luma_or_chroma; //true if we're doing luma, false if we're coding chroma
+
+ // A marker saying whether we're doing MC addition or subtraction
+ AddOrSub m_add_or_sub;
+
+ // Block information
+ OLBParams m_bparams;
+ // Arrays of block weights
+ TwoDArray<ValueType>* m_block_weights;
+ // Arrays of super block weights
+ TwoDArray<ValueType>* m_macro_block_weights;
+ // Arrays of sub super block weights
+ TwoDArray<ValueType>* m_sub_block_weights;
+ };
+
+ //! Pixel precision Motion compensator class.
+ class MotionCompensator_Pixel : public MotionCompensator
+ {
+
+ public:
+ //! Constructor.
+ /*!
+ Constructor initialises using codec parameters.
+ */
+ MotionCompensator_Pixel (const PicturePredParams &ppp);
+
+ private:
+ //! Motion-compensate a block.
+ virtual void BlockPixelPred( TwoDArray<ValueType>& block_data ,
+ const ImageCoords& pos,
+ const ImageCoords &orig_pic_size,
+ const PicArray& refup_data ,
+ const MVector& mv);
+ };
+
+ //! Half Pixel precision Motion compensator class.
+ class MotionCompensator_HalfPixel : public MotionCompensator
+ {
+ public:
+ //! Constructor.
+ /*!
+ Constructor initialises using codec parameters.
+ */
+ MotionCompensator_HalfPixel (const PicturePredParams &ppp);
+ private:
+ //! Motion-compensate a block.
+ virtual void BlockPixelPred( TwoDArray<ValueType>& block_data ,
+ const ImageCoords& pos,
+ const ImageCoords &orig_pic_size,
+ const PicArray& refup_data ,
+ const MVector& mv);
+ };
+
+ //! Quarter Pixel precision Motion compensator class.
+ class MotionCompensator_QuarterPixel : public MotionCompensator
+ {
+ public:
+ //! Constructor.
+ /*!
+ Constructor initialises using codec parameters.
+ */
+ MotionCompensator_QuarterPixel (const PicturePredParams &ppp);
+ private:
+ //! Motion-compensate a block.
+ virtual void BlockPixelPred( TwoDArray<ValueType>& block_data ,
+ const ImageCoords& pos,
+ const ImageCoords &orig_pic_size,
+ const PicArray& refup_data ,
+ const MVector& mv);
+ };
+
+ //! Eighth Pixel precision Motion compensator class.
+ class MotionCompensator_EighthPixel : public MotionCompensator
+ {
+ public:
+ //! Constructor.
+ /*!
+ Constructor initialises using codec parameters.
+ */
+ MotionCompensator_EighthPixel (const PicturePredParams &ppp);
+ private:
+ //! Motion-compensate a block.
+ virtual void BlockPixelPred( TwoDArray<ValueType>& block_data ,
+ const ImageCoords& pos,
+ const ImageCoords &orig_pic_size,
+ const PicArray& refup_data ,
+ const MVector& mv);
+ };
} // namespace dirac
diff --git a/src/filters/parser/DiracSplitter/libdirac/libdirac_common/mot_comp_mmx.cpp b/src/filters/parser/DiracSplitter/libdirac/libdirac_common/mot_comp_mmx.cpp
index e56226a0b..8c1cd0fa7 100644
--- a/src/filters/parser/DiracSplitter/libdirac/libdirac_common/mot_comp_mmx.cpp
+++ b/src/filters/parser/DiracSplitter/libdirac/libdirac_common/mot_comp_mmx.cpp
@@ -44,49 +44,48 @@
using namespace dirac;
inline void check_active_columns(
- int x, int xmax, ValueType act_cols1[4],
- ValueType act_cols2[4], ValueType *row1, ValueType *row2)
+ int x, int xmax, ValueType act_cols1[4],
+ ValueType act_cols2[4], ValueType *row1, ValueType *row2)
{
// check if we need any clipping
- if(x >= 0 && (x + 3) < xmax)
- {
+ if (x >= 0 && (x+3) < xmax) {
// special case, nothing to do
memcpy(act_cols1, &row1[x], 4 * sizeof(ValueType));
memcpy(act_cols2, &row2[x], 4 * sizeof(ValueType));
}
else
{
- act_cols1[0] = row1[BChk(x, xmax)];
- act_cols2[0] = row2[BChk(x, xmax)];
- act_cols1[1] = row1[BChk(x+1, xmax)];
- act_cols2[1] = row2[BChk(x+1, xmax)];
- act_cols1[2] = row1[BChk(x+2, xmax)];
- act_cols2[2] = row2[BChk(x+2, xmax)];
- act_cols1[3] = row1[BChk(x+3, xmax)];
- act_cols2[3] = row2[BChk(x+3, xmax)];
+ act_cols1[0] = row1[BChk(x,xmax)];
+ act_cols2[0] = row2[BChk(x,xmax)];
+ act_cols1[1] = row1[BChk(x+1,xmax)];
+ act_cols2[1] = row2[BChk(x+1,xmax)];
+ act_cols1[2] = row1[BChk(x+2,xmax)];
+ act_cols2[2] = row2[BChk(x+2,xmax)];
+ act_cols1[3] = row1[BChk(x+3,xmax)];
+ act_cols2[3] = row2[BChk(x+3,xmax)];
}
}
-void MotionCompensator_QuarterPixel::BlockPixelPred(
- TwoDArray<ValueType> &block_data ,
- const ImageCoords& pos ,
- const ImageCoords& orig_pic_size ,
- const PicArray &refup_data ,
- const MVector &mv)
+void MotionCompensator_QuarterPixel::BlockPixelPred(
+ TwoDArray<ValueType> &block_data ,
+ const ImageCoords& pos ,
+ const ImageCoords& orig_pic_size ,
+ const PicArray &refup_data ,
+ const MVector &mv)
{
// Set up the start point in the reference image by rounding the motion vector
// to 1/2 pel accuracy.NB: bit shift rounds negative values DOWN, as required
- const MVector roundvec(mv.x >> 1 , mv.y >> 1);
+ const MVector roundvec( mv.x>>1 , mv.y>>1 );
//Get the remainder after rounding. NB rmdr values always 0 or 1
- const MVector rmdr(mv.x & 1 , mv.y & 1);
+ const MVector rmdr( mv.x & 1 , mv.y & 1 );
//Where to start in the upconverted image
- const ImageCoords start_pos(std::max(pos.x, 0) , std::max(pos.y, 0));
+ const ImageCoords start_pos( std::max(pos.x,0) , std::max(pos.y,0) );
// check that we are doing MC within true pic boundaries
- if(start_pos.x >= orig_pic_size.x || start_pos.y >= orig_pic_size.y)
+ if (start_pos.x >= orig_pic_size.x || start_pos.y >= orig_pic_size.y)
return;
- const ImageCoords ref_start((start_pos.x << 1) + roundvec.x , (start_pos.y << 1) + roundvec.y);
+ const ImageCoords ref_start( ( start_pos.x<<1 ) + roundvec.x ,( start_pos.y<<1 ) + roundvec.y );
//An additional stage to make sure the block to be copied does not fall outside
//the reference image.
@@ -99,142 +98,142 @@ void MotionCompensator_QuarterPixel::BlockPixelPred(
bool do_bounds_checking = false;
//Check if there are going to be any problems copying the block from
//the upvconverted reference image.
- if(ref_start.x < 0)
+ if( ref_start.x < 0 )
do_bounds_checking = true;
- else if(ref_start.x + (block_data.LengthX() << 1) >= trueRefXlen)
+ else if( ref_start.x + (block_data.LengthX()<<1 ) >= trueRefXlen )
do_bounds_checking = true;
- if(ref_start.y < 0)
+ if( ref_start.y < 0 )
do_bounds_checking = true;
- else if(ref_start.y + (block_data.LengthY() << 1) >= trueRefYlen)
+ else if( ref_start.y + (block_data.LengthY()<<1 ) >= trueRefYlen)
do_bounds_checking = true;
- if(!do_bounds_checking)
+ if( !do_bounds_checking )
{
- int stopX = (block_data.LengthX() >> 2) << 2;
+ int stopX = (block_data.LengthX()>>2)<<2;
ValueType *refup_curr = &refup_data[ref_start.y][ref_start.x];
- const int refup_next((refXlen - block_data.LengthX()) * 2); //go down 2 rows and back to beginning of block line
- if(rmdr.x == 0 && rmdr.y == 0)
+ const int refup_next( ( refXlen - block_data.LengthX() )*2 ); //go down 2 rows and back to beginning of block line
+ if( rmdr.x == 0 && rmdr.y == 0 )
{
__m64 m1, m2;
- for(int y = 0; y < block_data.LengthY(); ++y, refup_curr += refup_next)
+ for( int y=0; y < block_data.LengthY(); ++y, refup_curr+=refup_next )
{
int x;
- for(x = 0; x < stopX; x += 4, block_curr += 4, refup_curr += 8)
+ for( x=0; x < stopX; x+=4, block_curr+=4, refup_curr+=8 )
{
- m1 = _mm_unpacklo_pi16(*(__m64 *)refup_curr, *(__m64 *)(refup_curr + 4));
- m2 = _mm_unpackhi_pi16(*(__m64 *)refup_curr, *(__m64 *)(refup_curr + 4));
+ m1 = _mm_unpacklo_pi16 (*(__m64 *)refup_curr, *(__m64 *)(refup_curr+4));
+ m2 = _mm_unpackhi_pi16 (*(__m64 *)refup_curr, *(__m64 *)(refup_curr+4));
// *block_curr = refup_curr[0]
- *(__m64 *)block_curr = _mm_unpacklo_pi16(m1, m2);
+ *(__m64 *)block_curr = _mm_unpacklo_pi16 (m1, m2);
}
// Mopup the last value
- for(x = stopX ; x < block_data.LengthX(); ++x)
+ for ( x=stopX ; x < block_data.LengthX(); ++x)
{
*block_curr = *refup_curr;
++block_curr;
- refup_curr += 2;
+ refup_curr+=2;
}
}
_mm_empty();
}
- else if(rmdr.y == 0)
+ else if( rmdr.y == 0 )
{
- __m64 round = _mm_set_pi16(1, 1, 1, 1);
+ __m64 round = _mm_set_pi16 (1, 1, 1, 1);
__m64 m1, m2, m3;
- for(int y = 0; y < block_data.LengthY(); ++y, refup_curr += refup_next)
+ for( int y=0; y < block_data.LengthY(); ++y, refup_curr+=refup_next )
{
int x;
- for(x = 0; x < stopX; x += 4, block_curr += 4, refup_curr += 8)
+ for( x=0; x < stopX; x+=4, block_curr+=4, refup_curr+=8 )
{
- m1 = _mm_unpacklo_pi16(*(__m64 *)refup_curr, *(__m64 *)(refup_curr + 4));
- m3 = _mm_unpackhi_pi16(*(__m64 *)refup_curr, *(__m64 *)(refup_curr + 4));
- m2 = _mm_unpackhi_pi16(m1, m3);
- m1 = _mm_unpacklo_pi16(m1, m3);
+ m1 = _mm_unpacklo_pi16 (*(__m64 *)refup_curr, *(__m64 *)(refup_curr+4));
+ m3 = _mm_unpackhi_pi16 (*(__m64 *)refup_curr, *(__m64 *)(refup_curr+4));
+ m2 = _mm_unpackhi_pi16 (m1, m3);
+ m1 = _mm_unpacklo_pi16 (m1, m3);
// (refup_curr[0] + refup_curr[1] + 1)>>1
- m1 = _mm_add_pi16(m1, m2);
- m1 = _mm_add_pi16(m1, round);
- *(__m64 *)block_curr = _mm_srai_pi16(m1, 1);
+ m1 = _mm_add_pi16 (m1, m2);
+ m1 = _mm_add_pi16 (m1, round);
+ *(__m64 *)block_curr = _mm_srai_pi16 (m1, 1);
}
// Mopup the last value
- for(x = stopX; x < block_data.LengthX(); ++x)
+ for ( x=stopX; x < block_data.LengthX(); ++x)
{
- *block_curr = ((*refup_curr +
- *(refup_curr + 1) + 1
- ) >> 1);
+ *block_curr = (( *refup_curr +
+ *(refup_curr+1) + 1
+ ) >> 1);
++block_curr;
- refup_curr += 2;
+ refup_curr+=2;
}
}
_mm_empty();
}
- else if(rmdr.x == 0)
+ else if( rmdr.x == 0 )
{
- __m64 round = _mm_set_pi16(1, 1, 1, 1);
+ __m64 round = _mm_set_pi16 (1, 1, 1, 1);
__m64 m1, m2, m3;
- for(int y = 0; y < block_data.LengthY(); ++y, refup_curr += refup_next)
+ for( int y=0; y < block_data.LengthY(); ++y, refup_curr+=refup_next )
{
int x;
- for(x = 0; x < stopX; x += 4, block_curr += 4, refup_curr += 8)
+ for( x = 0; x < stopX; x+=4, block_curr+=4, refup_curr+=8 )
{
- m1 = _mm_unpacklo_pi16(*(__m64 *)refup_curr, *(__m64 *)(refup_curr + 4));
- m2 = _mm_unpackhi_pi16(*(__m64 *)refup_curr, *(__m64 *)(refup_curr + 4));
+ m1 = _mm_unpacklo_pi16 (*(__m64 *)refup_curr, *(__m64 *)(refup_curr+4));
+ m2 = _mm_unpackhi_pi16 (*(__m64 *)refup_curr, *(__m64 *)(refup_curr+4));
// m1 now contains r00 r02 r04 r06
- m1 = _mm_unpacklo_pi16(m1, m2);
+ m1 = _mm_unpacklo_pi16 (m1, m2);
- m3 = _mm_unpacklo_pi16(*(__m64 *)(refup_curr + refXlen), *(__m64 *)(refup_curr + refXlen + 4));
- m2 = _mm_unpackhi_pi16(*(__m64 *)(refup_curr + refXlen), *(__m64 *)(refup_curr + refXlen + 4));
+ m3 = _mm_unpacklo_pi16 (*(__m64 *)(refup_curr+refXlen), *(__m64 *)(refup_curr+refXlen+4));
+ m2 = _mm_unpackhi_pi16 (*(__m64 *)(refup_curr+refXlen), *(__m64 *)(refup_curr+refXlen+4));
// m1 now contains r10 r12 r14 r16
- m2 = _mm_unpacklo_pi16(m3, m2);
+ m2 = _mm_unpacklo_pi16 (m3, m2);
- // (refup_curr[0] + (refup_curr+refXlen)[0] + 1)>>1
- m1 = _mm_add_pi16(m1, m2);
- m1 = _mm_add_pi16(m1, round);
- *(__m64 *)block_curr = _mm_srai_pi16(m1, 1);
+ // (refup_curr[0] + (refup_curr+refXlen)[0] + 1)>>1
+ m1 = _mm_add_pi16 (m1, m2);
+ m1 = _mm_add_pi16 (m1, round);
+ *(__m64 *)block_curr = _mm_srai_pi16 (m1, 1);
}
- for(x = stopX; x < block_data.LengthX(); ++x)
+ for ( x=stopX; x < block_data.LengthX(); ++x)
{
- *block_curr = ((*refup_curr + *(refup_curr + refXlen) +
- 1
+ *block_curr = (( *refup_curr + *(refup_curr+refXlen) +
+ 1
) >> 1);
++block_curr;
- refup_curr += 2;
+ refup_curr+=2;
}
}
_mm_empty();
}
else
{
- __m64 round = _mm_set_pi16(2, 2, 2, 2);
+ __m64 round = _mm_set_pi16 (2, 2, 2, 2);
__m64 m1, m2, m3;
- for(int y = 0; y < block_data.LengthY(); ++y, refup_curr += refup_next)
+ for( int y=0; y < block_data.LengthY(); ++y, refup_curr+=refup_next )
{
int x;
- for(x = 0; x < stopX; x += 4, block_curr += 4, refup_curr += 8)
+ for( x = 0; x < stopX; x+=4, block_curr+=4, refup_curr+=8 )
{
- m1 = _mm_add_pi16(*(__m64 *)refup_curr, *(__m64 *)(refup_curr + refXlen));
- m2 = _mm_add_pi16(*(__m64 *)(refup_curr + 4), *(__m64 *)(refup_curr + refXlen + 4));
- m3 = _mm_unpacklo_pi16(m1, m2);
- m1 = _mm_unpackhi_pi16(m1, m2);
+ m1 = _mm_add_pi16 (*(__m64 *)refup_curr, *(__m64 *)(refup_curr+refXlen));
+ m2 = _mm_add_pi16 (*(__m64 *)(refup_curr+4), *(__m64 *)(refup_curr+refXlen+4));
+ m3 = _mm_unpacklo_pi16 (m1, m2);
+ m1 = _mm_unpackhi_pi16 (m1, m2);
- m2 = _mm_unpackhi_pi16(m3, m1);
- m1 = _mm_unpacklo_pi16(m3, m1);
+ m2 = _mm_unpackhi_pi16 (m3, m1);
+ m1 = _mm_unpacklo_pi16 (m3, m1);
- m1 = _mm_add_pi16(m1, m2);
- m1 = _mm_add_pi16(m1, round);
- *(__m64 *)block_curr = _mm_srai_pi16(m1, 2);
+ m1 = _mm_add_pi16 (m1, m2);
+ m1 = _mm_add_pi16 (m1, round);
+ *(__m64 *)block_curr = _mm_srai_pi16 (m1, 2);
}
- for(x = stopX; x < block_data.LengthX(); ++x)
+ for ( x=stopX; x < block_data.LengthX(); ++x)
{
- *block_curr = ((*refup_curr +
- *(refup_curr + 1) +
- *(refup_curr + refXlen) +
- *(refup_curr + refXlen + 1) +
- 2
+ *block_curr = (( *refup_curr +
+ *(refup_curr+1) +
+ *(refup_curr+refXlen) +
+ *(refup_curr+refXlen+1) +
+ 2
) >> 2);
++block_curr;
- refup_curr += 2;
+ refup_curr+=2;
}
}
_mm_empty();
@@ -245,41 +244,40 @@ void MotionCompensator_QuarterPixel::BlockPixelPred(
// We're 2doing bounds checking because we'll fall off the edge of the reference otherwise.
//weights for doing linear interpolation, calculated from the remainder values
- const ValueType linear_wts[4] = { (2 - rmdr.x) *(2 - rmdr.y), //tl
- rmdr.x *(2 - rmdr.y), //tr
+ const ValueType linear_wts[4] = { (2 - rmdr.x) * (2 - rmdr.y), //tl
+ rmdr.x * (2 - rmdr.y), //tr
(2 - rmdr.x) * rmdr.y, //bl
- rmdr.x * rmdr.y
- }; //br
+ rmdr.x * rmdr.y }; //br
ValueType act_cols1[4], act_cols2[4];
int uX, uY, c, l;
- for(c = 0, uY = ref_start.y; c < block_data.LengthY(); ++c, uY += 2)
- {
- for(l = 0, uX = ref_start.x; l < block_data.LengthX(); ++l, ++block_curr, uX += 2)
- {
- check_active_columns(uX, trueRefXlen, act_cols1, act_cols2, refup_data[BChk(uY, trueRefYlen)], refup_data[BChk(uY+1, trueRefYlen)]);
-
- *block_curr = ((linear_wts[0] * act_cols1[0] +
- linear_wts[1] * act_cols1[1] +
- linear_wts[2] * act_cols2[0] +
- linear_wts[3] * act_cols2[1] +
- 2
+ for(c = 0, uY = ref_start.y; c < block_data.LengthY(); ++c, uY += 2)
+ {
+ for(l = 0, uX=ref_start.x; l < block_data.LengthX(); ++l, ++block_curr, uX += 2)
+ {
+ check_active_columns(uX, trueRefXlen, act_cols1, act_cols2, refup_data[BChk(uY, trueRefYlen)], refup_data[BChk(uY+1, trueRefYlen)]);
+
+ *block_curr = (( linear_wts[0] * act_cols1[0] +
+ linear_wts[1] * act_cols1[1] +
+ linear_wts[2] * act_cols2[0] +
+ linear_wts[3] * act_cols2[1] +
+ 2
) >> 2);
- }//l
- }//c
+ }//l
+ }//c
}
}
-void MotionCompensator_HalfPixel::BlockPixelPred(
- TwoDArray<ValueType> &block_data ,
- const ImageCoords& pos ,
- const ImageCoords& orig_pic_size ,
- const PicArray &refup_data ,
- const MVector &mv)
+void MotionCompensator_HalfPixel::BlockPixelPred(
+ TwoDArray<ValueType> &block_data ,
+ const ImageCoords& pos ,
+ const ImageCoords& orig_pic_size ,
+ const PicArray &refup_data ,
+ const MVector &mv)
{
//Where to start in the upconverted image
- const ImageCoords start_pos(std::max(pos.x, 0) , std::max(pos.y, 0));
- const ImageCoords ref_start((start_pos.x << 1) + mv.x , (start_pos.y << 1) + mv.y);
+ const ImageCoords start_pos( std::max(pos.x,0) , std::max(pos.y,0) );
+ const ImageCoords ref_start( ( start_pos.x<<1 ) + mv.x ,( start_pos.y<<1 ) + mv.y );
//An additional stage to make sure the block to be copied does not fall outside
//the reference image.
@@ -293,50 +291,50 @@ void MotionCompensator_HalfPixel::BlockPixelPred(
//Check if there are going to be any problems copying the block from
//the upvconverted reference image.
- if(ref_start.x < 0)
+ if( ref_start.x < 0 )
do_bounds_checking = true;
- else if(ref_start.x + ((block_data.LengthX() - 1) << 1) >= trueRefXlen)
+ else if( ref_start.x + ((block_data.LengthX() - 1 )<<1 ) >= trueRefXlen )
do_bounds_checking = true;
- if(ref_start.y < 0)
+ if( ref_start.y < 0 )
do_bounds_checking = true;
- else if(ref_start.y + ((block_data.LengthY() - 1) << 1) >= trueRefYlen)
+ else if( ref_start.y + ((block_data.LengthY() - 1 )<<1 ) >= trueRefYlen)
do_bounds_checking = true;
ValueType *block_curr = &block_data[0][0];
-
- if(!do_bounds_checking)
- {
+
+ if( !do_bounds_checking )
+ {
ValueType *refup_curr = &refup_data[ref_start.y][ref_start.x];
- const int refup_next((refXlen - block_data.LengthX()) * 2);// go down 2 rows and back up
+ const int refup_next( (refXlen - block_data.LengthX())*2 );// go down 2 rows and back up
#if 1
- int stopX = (block_data.LengthX() >> 2) << 2;
+ int stopX = (block_data.LengthX()>>2)<<2;
{
__m64 m1, m2;
- for(int y = 0; y < block_data.LengthY(); ++y, refup_curr += refup_next)
+ for( int y=0; y < block_data.LengthY(); ++y, refup_curr+=refup_next )
{
int x;
- for(x = 0; x < stopX; x += 4, block_curr += 4, refup_curr += 8)
+ for( x=0; x < stopX; x+=4, block_curr+=4, refup_curr+=8 )
{
- m1 = _mm_unpacklo_pi16(*(__m64 *)refup_curr, *(__m64 *)(refup_curr + 4));
- m2 = _mm_unpackhi_pi16(*(__m64 *)refup_curr, *(__m64 *)(refup_curr + 4));
- *(__m64 *)block_curr = _mm_unpacklo_pi16(m1, m2);
+ m1 = _mm_unpacklo_pi16 (*(__m64 *)refup_curr, *(__m64 *)(refup_curr+4));
+ m2 = _mm_unpackhi_pi16 (*(__m64 *)refup_curr, *(__m64 *)(refup_curr+4));
+ *(__m64 *)block_curr = _mm_unpacklo_pi16 (m1, m2);
}
// Mopup the last value
- for(x = stopX ; x < block_data.LengthX(); ++x)
+ for ( x=stopX ; x < block_data.LengthX(); ++x)
{
*block_curr = *refup_curr;
++block_curr;
- refup_curr += 2;
+ refup_curr+=2;
}
}
_mm_empty();
}
#else
- for(int y = 0; y < block_data.LengthY(); ++y, refup_curr += refup_next)
+ for( int y=0; y < block_data.LengthY(); ++y, refup_curr+=refup_next )
{
- for(int x = 0; x < block_data.LengthX(); ++x, ++block_curr, refup_curr += 2)
+ for( int x=0; x < block_data.LengthX(); ++x, ++block_curr, refup_curr+=2 )
{
*block_curr = refup_curr[0];
}
@@ -346,27 +344,27 @@ void MotionCompensator_HalfPixel::BlockPixelPred(
else
{
// We're doing bounds checking because we'll fall off the edge of the reference otherwise.
- for(int y = 0, ry = ref_start.y, by = BChk(ry, trueRefYlen);
- y < block_data.LengthY();
- ++y, ry += 2, by = BChk(ry, trueRefYlen))
+ for( int y=0, ry=ref_start.y, by=BChk(ry,trueRefYlen);
+ y<block_data.LengthY();
+ ++y, ry+=2,by=BChk(ry,trueRefYlen))
{
- for(int x = 0 , rx = ref_start.x , bx = BChk(rx, trueRefXlen);
- x < block_data.LengthX() ;
- ++x, ++block_curr, rx += 2 , bx = BChk(rx, trueRefXlen))
- {
- *block_curr = refup_data[by][bx];
- }// x
+ for( int x=0 , rx=ref_start.x , bx=BChk(rx,trueRefXlen);
+ x<block_data.LengthX() ;
+ ++x, ++block_curr, rx+=2 , bx=BChk(rx,trueRefXlen))
+ {
+ *block_curr = refup_data[by][bx];
+ }// x
}// y
}
}
-void MotionCompensator::AdjustBlockBySpatialWeights(
- TwoDArray<ValueType>& val_block,
- const ImageCoords &pos,
- const TwoDArray<ValueType> &wt_array)
+void MotionCompensator::AdjustBlockBySpatialWeights (
+ TwoDArray<ValueType>& val_block,
+ const ImageCoords &pos,
+ const TwoDArray<ValueType> &wt_array)
{
- ImageCoords start_pos(std::max(0, pos.x), std::max(0, pos.y));
- ImageCoords wt_start(start_pos.x - pos.x, start_pos.y - pos.y);
+ ImageCoords start_pos (std::max(0, pos.x), std::max(0, pos.y));
+ ImageCoords wt_start (start_pos.x - pos.x, start_pos.y - pos.y);
ValueType *val_curr = &val_block[0][0];
ValueType *wt_curr = &wt_array[wt_start.y][wt_start.x];
@@ -374,21 +372,21 @@ void MotionCompensator::AdjustBlockBySpatialWeights(
// go down at row and back to beginning of weights line
const int wt_next = wt_array.LengthX() - val_block.LengthX();
- const int stopX = (val_block.LengthX() >> 2) << 2;
-
- for(int j = 0; j < val_block.LengthY(); ++j, wt_curr += wt_next)
+ const int stopX = (val_block.LengthX()>>2)<<2;
+
+ for ( int j = 0; j < val_block.LengthY(); ++j, wt_curr += wt_next)
{
- for(int i = 0; i < stopX; i += 4, val_curr += 4, wt_curr += 4)
+ for ( int i = 0; i < stopX; i+=4, val_curr+=4, wt_curr+=4)
{
/*
* NOTE: Using only the low 16 bits of the result of multiplication
* by weights because the result is supposed to fit in 16 bit
* words. For some weights could result in overflow and errors
*/
- __m64 *out = (__m64 *)val_curr;
- *out = _mm_mullo_pi16(*(__m64 *)val_curr, *(__m64 *)wt_curr);
+ __m64 *out = (__m64 *)val_curr;
+ *out = _mm_mullo_pi16 (*(__m64 *)val_curr, *(__m64 *)wt_curr);
}
- for(int i = stopX; i < val_block.LengthX(); ++i, ++val_curr, ++wt_curr)
+ for (int i = stopX; i < val_block.LengthX(); ++i, ++val_curr, ++wt_curr)
{
*val_curr = *val_curr * *wt_curr;
}
@@ -398,75 +396,75 @@ void MotionCompensator::AdjustBlockBySpatialWeights(
namespace dirac
{
-void CompensateComponentAddAndShift_mmx(int start_y, int end_y,
- int weight_bits,
- const ImageCoords& orig_pic_size,
- TwoDArray<ValueType> &comp_data,
- PicArray &pic_data_out)
-{
- if(start_y >= end_y)
- return;
- const int round_val = 1 << (weight_bits - 1);
- int stopX = pic_data_out.FirstX() + ((orig_pic_size.x >> 2) << 2);
- int x_end_truepic_data = pic_data_out.FirstX() + orig_pic_size.x;
- int x_end_data = pic_data_out.FirstX() + pic_data_out.LengthX();
- __m64 mround_val = _mm_set_pi16(round_val, round_val, round_val, round_val);
- ValueType *pic_row = &comp_data[0][comp_data.FirstX()];
- ValueType *out_row = &pic_data_out[start_y][pic_data_out.FirstX()];
- for(int i = start_y; i < end_y; i++)
+ void CompensateComponentAddAndShift_mmx (int start_y, int end_y,
+ int weight_bits,
+ const ImageCoords& orig_pic_size,
+ TwoDArray<ValueType> &comp_data,
+ PicArray &pic_data_out)
{
- for(int j = pic_data_out.FirstX(); j < stopX; j += 4)
- {
- __m64 in1 = _mm_add_pi16(*(__m64 *)pic_row, mround_val);
- in1 = _mm_srai_pi16(in1, weight_bits);
- __m64 *out = (__m64 *)out_row;
- *out = _mm_add_pi16(in1, *out);
- pic_row += 4;
- out_row += 4;
- }
- for(int j = stopX; j < x_end_truepic_data; j++)
+ if (start_y >= end_y)
+ return;
+ const int round_val = 1<<(weight_bits-1);
+ int stopX = pic_data_out.FirstX() + ((orig_pic_size.x>>2)<<2);
+ int x_end_truepic_data = pic_data_out.FirstX() + orig_pic_size.x;
+ int x_end_data = pic_data_out.FirstX() + pic_data_out.LengthX();
+ __m64 mround_val = _mm_set_pi16 (round_val, round_val, round_val, round_val);
+ ValueType *pic_row = &comp_data[0][comp_data.FirstX()];
+ ValueType *out_row = &pic_data_out[start_y][pic_data_out.FirstX()];
+ for ( int i = start_y; i < end_y; i++)
{
- *out_row += static_cast<ValueType>((*pic_row + round_val) >> weight_bits);
- ++out_row;
- ++pic_row;
- }
- // Now pad past the true picture with the last true pic val in
- // current row
- ValueType last_true_val = *(out_row - 1);
- for(int j = x_end_truepic_data; j < x_end_data; ++j)
- {
- *out_row = last_true_val;
- ++out_row;
- ++pic_row;
- }
+ for ( int j = pic_data_out.FirstX(); j < stopX; j+=4)
+ {
+ __m64 in1 = _mm_add_pi16 (*(__m64 *)pic_row, mround_val);
+ in1 = _mm_srai_pi16 (in1, weight_bits);
+ __m64 *out = (__m64 *)out_row;
+ *out = _mm_add_pi16 (in1, *out);
+ pic_row += 4;
+ out_row += 4;
+ }
+ for ( int j =stopX; j < x_end_truepic_data; j++)
+ {
+ *out_row += static_cast<ValueType>( (*pic_row + round_val) >> weight_bits );
+ ++out_row;
+ ++pic_row;
+ }
+ // Now pad past the true picture with the last true pic val in
+ // current row
+ ValueType last_true_val = *(out_row - 1);
+ for ( int j = x_end_truepic_data; j < x_end_data; ++j)
+ {
+ *out_row = last_true_val;
+ ++out_row;
+ ++pic_row;
+ }
+ }
+ _mm_empty();
}
- _mm_empty();
-}
-void AddMCBlock_mmx(const ImageCoords& start_pos,
- TwoDArray<ValueType> &comp_strip,
- TwoDArray<ValueType>& block_data)
-{
- const int stopX = (block_data.LengthX() >> 2) << 2;
+ void AddMCBlock_mmx (const ImageCoords& start_pos,
+ TwoDArray<ValueType> &comp_strip,
+ TwoDArray<ValueType>& block_data)
+ {
+ const int stopX = (block_data.LengthX()>>2)<<2;
- const int comp_next = comp_strip.LengthX() - block_data.LengthX();
- ValueType *comp_curr = &comp_strip[start_pos.y][start_pos.x];
- ValueType *block_curr = &block_data[0][0];
+ const int comp_next = comp_strip.LengthX()-block_data.LengthX();
+ ValueType *comp_curr = &comp_strip[start_pos.y][start_pos.x];
+ ValueType *block_curr = &block_data[0][0];
- for(int j = 0; j < block_data.LengthY(); ++j, comp_curr += comp_next)
- {
- for(int i = 0; i < stopX; i += 4, comp_curr += 4, block_curr += 4)
- {
- __m64 *out = (__m64 *)comp_curr;
- // mc_tmp[y][x] += val
- *out = _mm_add_pi16(*(__m64 *)comp_curr, *(__m64 *)block_curr);
- }
- for(int i = stopX; i < block_data.LengthX(); ++i, ++comp_curr, ++block_curr)
+ for (int j = 0; j < block_data.LengthY(); ++j, comp_curr += comp_next)
{
- *comp_curr += *block_curr;
+ for (int i = 0; i < stopX; i+=4, comp_curr+=4, block_curr+=4)
+ {
+ __m64 *out = (__m64 *)comp_curr;
+ // mc_tmp[y][x] += val
+ *out = _mm_add_pi16 (*(__m64 *)comp_curr, *(__m64 *)block_curr);
+ }
+ for (int i = stopX; i < block_data.LengthX(); ++i, ++comp_curr, ++block_curr)
+ {
+ *comp_curr += *block_curr;
+ }
}
+ _mm_empty();
}
- _mm_empty();
-}
}
#endif
diff --git a/src/filters/parser/DiracSplitter/libdirac/libdirac_common/mot_comp_mmx.h b/src/filters/parser/DiracSplitter/libdirac/libdirac_common/mot_comp_mmx.h
index dcc7f19b9..4be009c61 100644
--- a/src/filters/parser/DiracSplitter/libdirac/libdirac_common/mot_comp_mmx.h
+++ b/src/filters/parser/DiracSplitter/libdirac/libdirac_common/mot_comp_mmx.h
@@ -50,13 +50,13 @@
namespace dirac
{
-void CompensateComponentAddAndShift_mmx(int start_y, int end_y,
- int weight_bits,
- const ImageCoords& orig_pic_size,
- TwoDArray<ValueType> &comp_data,
- PicArray &pic_data_out);
-
-void AddMCBlock_mmx(const ImageCoords& start_pos, TwoDArray<ValueType> &comp_strip, TwoDArray<ValueType>& block_data);
+ void CompensateComponentAddAndShift_mmx (int start_y, int end_y,
+ int weight_bits,
+ const ImageCoords& orig_pic_size,
+ TwoDArray<ValueType> &comp_data,
+ PicArray &pic_data_out);
+
+ void AddMCBlock_mmx (const ImageCoords& start_pos, TwoDArray<ValueType> &comp_strip, TwoDArray<ValueType>& block_data);
}
#endif // HAVE_MMX
diff --git a/src/filters/parser/DiracSplitter/libdirac/libdirac_common/motion.cpp b/src/filters/parser/DiracSplitter/libdirac/libdirac_common/motion.cpp
index 3e1a60fcc..cb48bdbb3 100644
--- a/src/filters/parser/DiracSplitter/libdirac/libdirac_common/motion.cpp
+++ b/src/filters/parser/DiracSplitter/libdirac/libdirac_common/motion.cpp
@@ -52,14 +52,14 @@ using namespace std;
//Motion vector and Motion Estimation structures//
//////////////////////////////////////////////////
-MvData::MvData(const PicturePredParams& predparams , const int num_refs):
- m_predparams(predparams),
- m_vectors(Range(1 , num_refs)),
- m_gm_vectors(Range(1 , num_refs)),
- m_modes(predparams.YNumBlocks() , predparams.XNumBlocks()),
- m_dc(3),
- m_sb_split(predparams.YNumSB() , predparams.XNumSB()),
- m_gm_params(Range(1 , num_refs)) //,
+MvData::MvData( const PicturePredParams& predparams , const int num_refs ):
+ m_predparams( predparams ),
+ m_vectors( Range(1 , num_refs) ),
+ m_gm_vectors( Range(1 , num_refs) ),
+ m_modes( predparams.YNumBlocks() , predparams.XNumBlocks() ),
+ m_dc( 3 ),
+ m_sb_split( predparams.YNumSB() , predparams.XNumSB() ),
+ m_gm_params( Range(1 , num_refs) )//,
// m_num_refs(num_refs)
{
InitMvData();
@@ -68,144 +68,140 @@ MvData::MvData(const PicturePredParams& predparams , const int num_refs):
void MvData::InitMvData()
{
// Create the arrays of vectors
- for(int i = m_vectors.First() ; i <= m_vectors.Last() ; ++i)
- {
- m_vectors[i] = new MvArray(Mode().LengthY() , Mode().LengthX());
- m_gm_vectors[i] = new MvArray(Mode().LengthY() , Mode().LengthX());
- }
+ for ( int i=m_vectors.First() ; i<=m_vectors.Last() ; ++i ){
+ m_vectors[i] = new MvArray( Mode().LengthY() , Mode().LengthX() );
+ m_gm_vectors[i] = new MvArray( Mode().LengthY() , Mode().LengthX() );
+ }
// create global motion parameter arrays
- for(int i = m_gm_params.First() ; i <= m_gm_params.Last() ; ++i)
- {
- m_gm_params[i] = new OneDArray<float> (8);
+ for ( int i=m_gm_params.First() ; i<=m_gm_params.Last() ; ++i ){
+ m_gm_params[i] = new OneDArray<float> ( 8 );
}
- // Create the arrays of dc values
- for(int i = 0 ; i < 3 ; ++i)
- m_dc[i] = new TwoDArray<ValueType>(Mode().LengthY() , Mode().LengthX() , 0);
+ // Create the arrays of dc values
+ for ( int i=0 ; i<3 ; ++i )
+ m_dc[i] = new TwoDArray<ValueType>( Mode().LengthY() , Mode().LengthX() , 0);
}
MvData::~MvData()
{
- // Delete the arrays of vectors
- for(int i = m_vectors.First() ; i <= m_vectors.Last() ; ++i)
- {
+ // Delete the arrays of vectors
+ for ( int i=m_vectors.First() ; i<=m_vectors.Last() ; ++i ){
delete m_vectors[i];
delete m_gm_vectors[i];
}
- // delete array of global motion parameters
- for(int i = m_gm_params.First() ; i <= m_gm_params.Last() ; ++i)
- {
- delete m_gm_params[i];
- }
+ // delete array of global motion parameters
+ for ( int i=m_gm_params.First() ; i<=m_gm_params.Last() ; ++i ){
+ delete m_gm_params[i];
+ }
- // Delete the arrays of dc values
- for(int i = 0 ; i < 3 ; ++i)
- delete m_dc[i];
+ // Delete the arrays of dc values
+ for ( int i=0 ; i<3 ; ++i )
+ delete m_dc[i];
}
-MEData::MEData(const PicturePredParams& predparams , const int num_refs):
- MvData(predparams , num_refs),
- m_pred_costs(Range(1 , num_refs)),
- m_intra_costs(predparams.YNumBlocks() , predparams.XNumBlocks(), 0),
- m_bipred_costs(predparams.YNumBlocks() , predparams.XNumBlocks()),
- m_SB_costs(predparams.YNumSB() , predparams.XNumSB()),
- m_lambda_map(predparams.YNumBlocks() , predparams.XNumBlocks()),
- m_inliers(Range(1 , num_refs)),
- m_intra_block_ratio(0.0)
+MEData::MEData(const PicturePredParams& predparams , const int num_refs ):
+ MvData( predparams , num_refs ),
+ m_pred_costs( Range( 1 , num_refs ) ),
+ m_intra_costs( predparams.YNumBlocks() , predparams.XNumBlocks(), 0 ),
+ m_bipred_costs( predparams.YNumBlocks() , predparams.XNumBlocks() ),
+ m_SB_costs( predparams.YNumSB() , predparams.XNumSB() ),
+ m_lambda_map( predparams.YNumBlocks() , predparams.XNumBlocks() ),
+ m_inliers( Range( 1 , num_refs ) ),
+ m_intra_block_ratio(0.0)
{
InitMEData();
}
void MEData::InitMEData()
{
- // Create the arrays of prediction costs
- for(int i = m_pred_costs.First() ; i <= m_pred_costs.Last() ; ++i)
- m_pred_costs[i] = new TwoDArray<MvCostData>(Mode().LengthY() , Mode().LengthX());
+ // Create the arrays of prediction costs
+ for ( int i=m_pred_costs.First() ; i<=m_pred_costs.Last() ; ++i )
+ m_pred_costs[i] = new TwoDArray<MvCostData>( Mode().LengthY() , Mode().LengthX() );
// Create the arrays of vectors
- for(int i = m_inliers.First() ; i <= m_inliers.Last() ; ++i)
- m_inliers[i] = new TwoDArray<int>(Mode().LengthY() , Mode().LengthX());
+ for ( int i=m_inliers.First() ; i<=m_inliers.Last() ; ++i )
+ m_inliers[i] = new TwoDArray<int>( Mode().LengthY() , Mode().LengthX() );
}
-void MEData::SetLambdaMap(const int num_refs , const float lambda)
+void MEData::SetLambdaMap( const int num_refs , const float lambda )
{
- TwoDArray<bool> transition_map1(Mode().LengthY() , Mode().LengthX());
- TwoDArray<bool> transition_map2(Mode().LengthY() , Mode().LengthX());
+ TwoDArray<bool> transition_map1( Mode().LengthY() , Mode().LengthX() );
+ TwoDArray<bool> transition_map2( Mode().LengthY() , Mode().LengthX() );
- FindTransitions(transition_map1 , 1);
+ FindTransitions( transition_map1 , 1 );
- if(num_refs == 1)
+ if ( num_refs==1 )
{
- for(int j = 0 ; j < m_lambda_map.LengthY() ; j++)
+ for ( int j=0 ; j<m_lambda_map.LengthY() ; j++)
{
- for(int i = 0 ; i < m_lambda_map.LengthX() ; i++)
+ for ( int i=0 ; i<m_lambda_map.LengthX() ; i++)
{
- if(transition_map1[j][i])
+ if ( transition_map1[j][i] )
m_lambda_map[j][i] = 0.0;
else
m_lambda_map[j][i] = lambda;
- if(i < 4 || j < 4)
- m_lambda_map[j][i] /= 5.0;
+ if ( i<4 || j<4 )
+ m_lambda_map[j][i] /= 5.0;
}// i
}// j
}
- else if(num_refs > 1)
+ else if ( num_refs > 1 )
{
- FindTransitions(transition_map2 , 2);
+ FindTransitions( transition_map2 , 2 );
- for(int j = 0 ; j < m_lambda_map.LengthY() ; j++)
+ for ( int j=0 ; j<m_lambda_map.LengthY() ; j++)
{
- for(int i = 0 ; i < m_lambda_map.LengthX() ; i++)
+ for ( int i=0 ; i<m_lambda_map.LengthX() ; i++)
{
- if(transition_map1[j][i] && transition_map2[j][i])
+ if ( transition_map1[j][i] && transition_map2[j][i] )
m_lambda_map[j][i] = 0.0;
- else if(transition_map1[j][i] || transition_map2[j][i])
- m_lambda_map[j][i] = lambda / 4.0;
+ else if (transition_map1[j][i] || transition_map2[j][i] )
+ m_lambda_map[j][i] = lambda/4.0;
else
m_lambda_map[j][i] = lambda;
- if(i < 4 || j < 4)
- m_lambda_map[j][i] /= 5.0;
+ if ( i<4 || j<4 )
+ m_lambda_map[j][i] /= 5.0;
}// i
}// j
}
}
-void MEData::SetLambdaMap(const int level , const TwoDArray<float>& l_map , const float wt)
+void MEData::SetLambdaMap( const int level , const TwoDArray<float>& l_map , const float wt )
{
- const int factor = 1 << (2 - level);
+ const int factor = 1<<(2-level);
int xstart , xend , ystart , yend;
-
- for(int j = 0 ; j < m_lambda_map.LengthY() ; ++j)
+
+ for (int j = 0 ; j<m_lambda_map.LengthY() ; ++j )
{
- for(int i = 0 ; i < m_lambda_map.LengthX() ; ++i)
+ for (int i = 0 ; i<m_lambda_map.LengthX() ; ++i )
{
xstart = factor * i;
ystart = factor * j;
- xend = factor * (i + 1);
- yend = factor * (j + 1);
+ xend = factor * ( i + 1 );
+ yend = factor * ( j + 1 );
m_lambda_map[j][i] = l_map[ystart][xstart];
- for(int q = ystart ; q < yend ; ++q)
- for(int p = xstart ; p < xend ; ++p)
- m_lambda_map[j][i] = std::max(l_map[q][p] , m_lambda_map[j][i]);
+ for (int q = ystart ; q<yend ; ++q )
+ for (int p = xstart ; p<xend ; ++p )
+ m_lambda_map[j][i] = std::max( l_map[q][p] , m_lambda_map[j][i] );
- m_lambda_map[j][i] *= wt;
+ m_lambda_map[j][i] *= wt;
}// i
}// j
}
-void MEData::FindTransitions(TwoDArray<bool>& trans_map , const int ref_num)
+void MEData::FindTransitions( TwoDArray<bool>& trans_map , const int ref_num )
{
- const MvArray& mv_array = Vectors(ref_num);
+ const MvArray& mv_array = Vectors( ref_num );
// Start with a statistical approach - determine thresholds later
@@ -219,20 +215,20 @@ void MEData::FindTransitions(TwoDArray<bool>& trans_map , const int ref_num)
double threshold;
// first, mean
- for(int j = 0 ; j < mv_array.LengthY() ; ++j)
- for(int i = 0 ; i < mv_array.LengthX() ; ++i)
- total_cost += PredCosts(ref_num)[j][i].SAD;
+ for ( int j=0 ; j<mv_array.LengthY() ; ++j )
+ for ( int i=0 ; i<mv_array.LengthX() ; ++i )
+ total_cost += PredCosts( ref_num )[j][i].SAD;
- mean_cost = total_cost /
- static_cast<long double>(mv_array.LengthX() * mv_array.LengthY());
+ mean_cost = total_cost /
+ static_cast<long double>( mv_array.LengthX()*mv_array.LengthY() );
// next , Standard Deviation
-
- for(int j = 0 ; j < mv_array.LengthY() ; ++j)
+
+ for ( int j=0 ; j<mv_array.LengthY() ; ++j )
{
- for(int i = 0 ; i < mv_array.LengthX() ; ++i)
+ for ( int i=0 ; i<mv_array.LengthX() ; ++i )
{
- diff = PredCosts(ref_num)[j][i].SAD - mean_cost;
+ diff = PredCosts( ref_num )[j][i].SAD - mean_cost;
diff *= diff;
sd_cost += diff;
@@ -240,40 +236,40 @@ void MEData::FindTransitions(TwoDArray<bool>& trans_map , const int ref_num)
}// j
// Get the variance ...
- sd_cost /= static_cast<long double>(mv_array.LengthX() * mv_array.LengthY());
+ sd_cost /= static_cast<long double>( mv_array.LengthX()*mv_array.LengthY() );
// ... and then the SD
- sd_cost = std::sqrt(sd_cost);
+ sd_cost = std::sqrt( sd_cost );
- threshold = mean_cost + 3 * sd_cost;
+ threshold = mean_cost + 3*sd_cost;
// now go through and mark those that go above the threshold
- for(int j = 0 ; j < mv_array.LengthY() ; ++j)
- for(int i = 0 ; i < mv_array.LengthX() ; ++i)
- trans_map[j][i] = (PredCosts(ref_num)[j][i].SAD >= threshold) ? true : false;
+ for ( int j=0 ; j<mv_array.LengthY() ; ++j )
+ for ( int i=0 ; i<mv_array.LengthX() ; ++i )
+ trans_map[j][i] = ( PredCosts( ref_num )[j][i].SAD >= threshold )? true : false;
// Next look at motion-vector costs
- TwoDArray<double> val_array(mv_array.LengthY() , mv_array.LengthX());
+ TwoDArray<double> val_array( mv_array.LengthY() , mv_array.LengthX() );
// first, mean
total_cost = 0.0;
- for(int i = 0 ; i < mv_array.LengthX() ; ++i)
+ for ( int i=0 ; i<mv_array.LengthX() ; ++i )
{
val_array[0][i] = 0.0;
val_array[val_array.LastY()][i] = 0.0;
}// i
- for(int j = 1 ; j < mv_array.LengthY() - 1 ; ++j)
+ for ( int j=1 ; j<mv_array.LengthY()-1 ; ++j )
{
val_array[j][0] = 0.0;
val_array[j][val_array.LastX()] = 0.0;
- for(int i = 1 ; i < mv_array.LengthX() - 1 ; ++i)
+ for ( int i=1 ; i<mv_array.LengthX()-1 ; ++i )
{
- val_array[j][i] = 0.0;
- for(int q = -1 ; q <= 1 ; ++q)
- for(int p = -1 ; p <= 1 ; ++p)
- val_array[j][i] = std::max(val_array[j][i] , (double)Norm1(mv_array[j+q][i+p] - mv_array[j][i]));
+ val_array[j][i] =0.0;
+ for (int q=-1 ; q<=1 ; ++q)
+ for (int p=-1 ; p<=1 ; ++p)
+ val_array[j][i] = std::max( val_array[j][i] , (double)Norm1( mv_array[j+q][i+p] - mv_array[j][i] ) );
total_cost += val_array[j][i];
@@ -281,15 +277,15 @@ void MEData::FindTransitions(TwoDArray<bool>& trans_map , const int ref_num)
}// j
- mean_cost = total_cost /
- static_cast<long double>(mv_array.LengthX() * mv_array.LengthY());
+ mean_cost = total_cost /
+ static_cast<long double>( mv_array.LengthX()*mv_array.LengthY() );
// next , Standard Deviation
sd_cost = 0.0;
-
- for(int j = 1 ; j < mv_array.LengthY() - 1 ; ++j)
+
+ for ( int j=1 ; j<mv_array.LengthY()-1 ; ++j )
{
- for(int i = 1 ; i < mv_array.LengthX() - 1 ; ++i)
+ for ( int i=1 ; i<mv_array.LengthX()-1 ; ++i )
{
diff = val_array[j][i] - mean_cost;
diff *= diff;
@@ -300,39 +296,39 @@ void MEData::FindTransitions(TwoDArray<bool>& trans_map , const int ref_num)
}// j
// Get the variance ...
- sd_cost /= static_cast<long double>(mv_array.LengthX() * mv_array.LengthY());
+ sd_cost /= static_cast<long double>( mv_array.LengthX()*mv_array.LengthY() );
// ... and then the SD
- sd_cost = std::sqrt(sd_cost);
+ sd_cost = std::sqrt( sd_cost );
- threshold = mean_cost + 3 * sd_cost;
+ threshold = mean_cost + 3*sd_cost;
// now go through and mark those that go above the threshold
- for(int j = 0 ; j < mv_array.LengthY() ; ++j)
- for(int i = 0 ; i < mv_array.LengthX() ; ++i)
- trans_map[j][i] = (val_array[j][i] >= threshold) ? true : false;
-
- bool contains_trans;
-
- for(int j = 0 ; j < mv_array.LengthY() / 4 ; ++j)
- {
- for(int i = 0 ; i < mv_array.LengthX() / 4 ; ++i)
- {
- contains_trans = false;
- for(int q = 4 * j ; q < 4 *(j + 1) ; ++q)
- {
- for(int p = 4 * i ; p < 4 *(i + 1) ; ++p)
- {
- if(trans_map[q][p])
- contains_trans = true;
- }// p
- }// q
- for(int q = 4 * j ; q < 4 *(j + 1) ; ++q)
- for(int p = 4 * i ; p < 4 *(i + 1) ; ++p)
- trans_map[q][p] = contains_trans;
-
- }// i
- }// j
+ for ( int j=0 ; j<mv_array.LengthY() ; ++j )
+ for ( int i=0 ; i<mv_array.LengthX() ; ++i )
+ trans_map[j][i] = ( val_array[j][i] >= threshold )? true : false;
+
+ bool contains_trans;
+
+ for ( int j=0 ; j<mv_array.LengthY()/4 ; ++j )
+ {
+ for ( int i=0 ; i<mv_array.LengthX()/4 ; ++i )
+ {
+ contains_trans = false;
+ for ( int q=4*j ; q<4*(j+1) ; ++q )
+ {
+ for ( int p=4*i ; p<4*(i+1) ; ++p )
+ {
+ if (trans_map[q][p])
+ contains_trans = true;
+ }// p
+ }// q
+ for ( int q=4*j ; q<4*(j+1) ; ++q )
+ for ( int p=4*i ; p<4*(i+1) ; ++p )
+ trans_map[q][p] = contains_trans;
+
+ }// i
+ }// j
}
@@ -340,41 +336,39 @@ void MEData::FindTransitions(TwoDArray<bool>& trans_map , const int ref_num)
MEData::~MEData()
{
// Delete the arrays of prediction costs
- for(int i = m_pred_costs.First() ; i <= m_pred_costs.Last() ; ++i)
- delete m_pred_costs[i];
+ for ( int i=m_pred_costs.First() ; i<=m_pred_costs.Last() ; ++i )
+ delete m_pred_costs[i];
- for(int i = m_inliers.First() ; i <= m_inliers.Last() ; ++i)
+ for ( int i=m_inliers.First() ; i<=m_inliers.Last() ; ++i )
delete m_inliers[i];
}
-void MEData::DropRef(const int rindex)
-{
+void MEData::DropRef( const int rindex ){
- if(rindex == 2) {}
- else if(rindex == 1)
- {
- // Swap data for reference 1 and reference 2
- // so that reference 2 becomes the new reference 1
+ if (rindex==2){}
+ else if (rindex==1){
+ // Swap data for reference 1 and reference 2
+ // so that reference 2 becomes the new reference 1
- MvArray* ptr = m_vectors[1];
- m_vectors[1] = m_vectors[2];
- m_vectors[2] = ptr;
+ MvArray* ptr = m_vectors[1];
+ m_vectors[1] = m_vectors[2];
+ m_vectors[2] = ptr;
- ptr = m_gm_vectors[1];
- m_gm_vectors[1] = m_gm_vectors[2];
- m_gm_vectors[2] = ptr;
+ ptr = m_gm_vectors[1];
+ m_gm_vectors[1] = m_gm_vectors[2];
+ m_gm_vectors[2] = ptr;
- OneDArray<float>* ptr2 = m_gm_params[1];
- m_gm_params[1] = m_gm_params[2];
- m_gm_params[2] = ptr2;
+ OneDArray<float>* ptr2 = m_gm_params[1];
+ m_gm_params[1] = m_gm_params[2];
+ m_gm_params[2] = ptr2;
- TwoDArray<MvCostData>* ptr3 = m_pred_costs[1];
- m_pred_costs[1] = m_pred_costs[2];
- m_pred_costs[2] = ptr3;
+ TwoDArray<MvCostData>* ptr3 = m_pred_costs[1];
+ m_pred_costs[1] = m_pred_costs[2];
+ m_pred_costs[2] = ptr3;
- TwoDArray<int>* ptr4 = m_inliers[1];
- m_inliers[1] = m_inliers[2];
- m_inliers[2] = ptr4;
+ TwoDArray<int>* ptr4 = m_inliers[1];
+ m_inliers[1] = m_inliers[2];
+ m_inliers[2] = ptr4;
}
}
@@ -420,29 +414,29 @@ istream & operator>> (istream & stream, PredMode & mode)
istream &operator>> (istream & stream, MEData & me_data)
{
stream.ignore(1000, '\n');
-
+
// input reference-independent information
stream >> me_data.SBSplit();
stream >> me_data.SBCosts();
stream >> me_data.Mode();
stream >> me_data.IntraCosts();
- if(me_data.m_pred_costs.Length() > 1)
+ if (me_data.m_pred_costs.Length() > 1)
stream >> me_data.BiPredCosts();
- if(me_data.DC().Length() == 1)
+ if (me_data.DC().Length() == 1)
{
- stream >> me_data.DC(Y_COMP);
+ stream >> me_data.DC( Y_COMP );
}
- else if(me_data.DC().Length() == 3)
+ else if (me_data.DC().Length() == 3)
{
- stream >> me_data.DC(Y_COMP);
- stream >> me_data.DC(U_COMP);
- stream >> me_data.DC(V_COMP);
+ stream >> me_data.DC( Y_COMP );
+ stream >> me_data.DC( U_COMP );
+ stream >> me_data.DC( V_COMP );
}
// input reference information
- for(int i = 1; i <= me_data.m_pred_costs.Length(); ++i)
+ for (int i=1; i<=me_data.m_pred_costs.Length(); ++i)
{
stream >> me_data.Vectors(i);
stream >> me_data.PredCosts(i);
@@ -463,23 +457,23 @@ ostream &operator<< (ostream & stream, MEData & me_data)
stream << endl << me_data.Mode();
stream << endl << me_data.IntraCosts() << endl;
- if(me_data.m_pred_costs.Length() > 1)
+ if (me_data.m_pred_costs.Length() > 1)
stream << me_data.BiPredCosts();
// output component DC values
- if(me_data.DC().Length() == 1)
+ if (me_data.DC().Length() == 1)
{
- stream << endl << me_data.DC(Y_COMP);
+ stream << endl << me_data.DC( Y_COMP );
}
- else if(me_data.DC().Length() == 3)
+ else if (me_data.DC().Length() == 3)
{
- stream << endl << me_data.DC(Y_COMP);
- stream << endl << me_data.DC(U_COMP);
- stream << endl << me_data.DC(V_COMP);
+ stream << endl << me_data.DC( Y_COMP );
+ stream << endl << me_data.DC( U_COMP );
+ stream << endl << me_data.DC( V_COMP );
}
// output reference information
- for(int i = 1; i <= me_data.m_pred_costs.Length(); ++i)
+ for (int i=1; i<=me_data.m_pred_costs.Length(); ++i)
{
stream << endl << me_data.Vectors(i);
stream << endl << me_data.PredCosts(i) << endl;
@@ -487,194 +481,180 @@ ostream &operator<< (ostream & stream, MEData & me_data)
//stream << endl << me_data.GlobalMotionVectors(i) << endl;
//stream << endl << me_data.GlobalMotionInliers(i) << endl;
}
-
+
return stream;
}
-int Median(const int val1, const int val2, const int val3)
+int Median( const int val1, const int val2, const int val3)
{
int tmp;
- tmp = val1;
- tmp += val2;
- tmp += val3;
-
- tmp -= std::max(std::max(val1 , val2) , val3);
- tmp -= std::min(std::min(val1 , val2) , val3);
+ tmp=val1;
+ tmp+=val2;
+ tmp+=val3;
+ tmp -= std::max( std::max( val1 , val2 ) , val3 );
+ tmp -= std::min( std::min( val1 , val2 ) , val3 );
+
return tmp;
}
-MVector MvMedian(const MVector& mv1, const MVector& mv2, const MVector& mv3)
-{
- //takes median of each vector component
+MVector MvMedian(const MVector& mv1,const MVector& mv2,const MVector& mv3) {
+ //takes median of each vector component
MVector tmp_mv;
- tmp_mv.x = mv1.x;
- tmp_mv.x += mv2.x;
- tmp_mv.x += mv3.x;
+ tmp_mv.x=mv1.x;
+ tmp_mv.x+=mv2.x;
+ tmp_mv.x+=mv3.x;
- tmp_mv.x -= std::max(std::max(mv1.x, mv2.x), mv3.x);
- tmp_mv.x -= std::min(std::min(mv1.x, mv2.x), mv3.x);
+ tmp_mv.x-=std::max(std::max(mv1.x,mv2.x),mv3.x);
+ tmp_mv.x-=std::min(std::min(mv1.x,mv2.x),mv3.x);
- tmp_mv.y = mv1.y;
- tmp_mv.y += mv2.y;
- tmp_mv.y += mv3.y;
+ tmp_mv.y=mv1.y;
+ tmp_mv.y+=mv2.y;
+ tmp_mv.y+=mv3.y;
- tmp_mv.y -= std::max(std::max(mv1.y, mv2.y), mv3.y);
- tmp_mv.y -= std::min(std::min(mv1.y, mv2.y), mv3.y);
+ tmp_mv.y-=std::max(std::max(mv1.y,mv2.y),mv3.y);
+ tmp_mv.y-=std::min(std::min(mv1.y,mv2.y),mv3.y);
return tmp_mv;
}
int Median(const std::vector<int>& val_list)
-{
+{
// take the median of up to 4 elements
- switch(val_list.size())
- {
- case 1 :
-
- return val_list[0];
- case 2 : // return the mean
- return ((val_list[0] + val_list[1] + 1) >> 1);
- case 3 :
- return Median(val_list[0], val_list[1], val_list[2]);
- case 4 :
+ switch (val_list.size() )
{
- int med_val(0);
- int max_val(val_list[0]);
- int min_val(val_list[0]);
-
- for(int i = 0; i < 4; ++i)
- {
- med_val += val_list[i];
- max_val = std::max(max_val , val_list[i]);
- min_val = std::min(min_val , val_list[i]);
-
- }// i
+ case 1 :
+
+ return val_list[0];
+ case 2 : // return the mean
+ return ( ( val_list[0] + val_list[1] + 1 )>>1 );
+ case 3 :
+ return Median(val_list[0], val_list[1], val_list[2] );
+ case 4 :
+ {
+ int med_val(0);
+ int max_val(val_list[0]);
+ int min_val(val_list[0]);
- med_val -= (max_val + min_val);
+ for (int i=0; i<4; ++i )
+ {
+ med_val += val_list[i];
+ max_val = std::max( max_val , val_list[i] );
+ min_val = std::min( min_val , val_list[i] );
- return ((med_val + 1) >> 1);
- }
- default :
- return 0;
+ }// i
+
+ med_val -= ( max_val + min_val );
+
+ return ( (med_val + 1)>>1 );
+ }
+ default :
+ return 0;
}
}
-MVector MvMedian(const std::vector<MVector>& vect_list)
-{
+MVector MvMedian(const std::vector<MVector>& vect_list){
//median of 0-4 vectors
-
- if(vect_list.size() == 0)
+
+ if ( vect_list.size() == 0 )
return 0;
- else if(vect_list.size() == 1)
+ else if ( vect_list.size() == 1 )
return vect_list[0];
- else if(vect_list.size() == 2)
- return MvMean(vect_list[0], vect_list[1]);
- else if(vect_list.size() == 3)
- return MvMedian(vect_list[0], vect_list[1], vect_list[2]);
- else if(vect_list.size() == 4)
+ else if ( vect_list.size() == 2 )
+ return MvMean( vect_list[0], vect_list[1] );
+ else if ( vect_list.size() == 3 )
+ return MvMedian(vect_list[0], vect_list[1], vect_list[2] );
+ else if ( vect_list.size() == 4 )
{
- MVector tmp_mv(0);
- MVector max_mv(vect_list[0]);
- MVector min_mv(vect_list[0]);
- for(int i = 0; i < 4; ++i)
- {
- tmp_mv.x += vect_list[i].x;
- max_mv.x = std::max(max_mv.x, vect_list[i].x);
- min_mv.x = std::min(min_mv.x, vect_list[i].x);
-
- tmp_mv.y += vect_list[i].y;
- max_mv.y = std::max(max_mv.y, vect_list[i].y);
- min_mv.y = std::min(min_mv.y, vect_list[i].y);
-
- }// i
-
- tmp_mv.x -= (max_mv.x + min_mv.x);
- tmp_mv.y -= (max_mv.y + min_mv.y);
-
- tmp_mv.x = (tmp_mv.x + 1) >> 1;
- tmp_mv.y = (tmp_mv.y + 1) >> 1;
-
- return tmp_mv;
-
+ MVector tmp_mv(0);
+ MVector max_mv(vect_list[0]);
+ MVector min_mv(vect_list[0]);
+ for (int i=0; i<4; ++i )
+ {
+ tmp_mv.x += vect_list[i].x;
+ max_mv.x=std::max(max_mv.x, vect_list[i].x);
+ min_mv.x=std::min(min_mv.x, vect_list[i].x);
+
+ tmp_mv.y += vect_list[i].y;
+ max_mv.y=std::max(max_mv.y, vect_list[i].y);
+ min_mv.y=std::min(min_mv.y, vect_list[i].y);
+
+ }// i
+
+ tmp_mv.x -= (max_mv.x+min_mv.x);
+ tmp_mv.y -= (max_mv.y+min_mv.y);
+
+ tmp_mv.x = (tmp_mv.x+1)>>1;
+ tmp_mv.y = (tmp_mv.y+1)>>1;
+
+ return tmp_mv;
+
}
else
- {
+ {
MVector median;
- int num_vals = int(vect_list.size());
- if(num_vals > 0)
- {
- int pos = 0;
+ int num_vals=int(vect_list.size());
+ if (num_vals>0) {
+ int pos=0;
std::vector<int> ordered_vals(vect_list.size());
//do x first
- ordered_vals[0] = vect_list[0].x;
- for(int I = 1; I < num_vals; ++I)
- {
- for(int K = 0; K < I; ++K)
- {
- if(vect_list[I].x < ordered_vals[K])
- {
- pos = K;
+ ordered_vals[0]=vect_list[0].x;
+ for (int I=1;I<num_vals;++I){
+ for (int K=0;K<I;++K){
+ if (vect_list[I].x<ordered_vals[K]){
+ pos=K;
break;
}
else
- pos = K + 1;
+ pos=K+1;
}//K
- if(pos == I)
- ordered_vals[I] = vect_list[I].x;
- else
- {
- for(int K = I - 1; K >= pos; --K)
- {
- ordered_vals[K+1] = ordered_vals[K];
+ if (pos==I)
+ ordered_vals[I]=vect_list[I].x;
+ else{
+ for (int K=I-1;K>=pos;--K){
+ ordered_vals[K+1]=ordered_vals[K];
}
- ordered_vals[pos] = vect_list[I].x;
+ ordered_vals[pos]=vect_list[I].x;
}
}//I
- if(vect_list.size() % 2 != 0)
- median.x = ordered_vals[(num_vals-1)/2];
+ if (vect_list.size()%2!=0)
+ median.x=ordered_vals[(num_vals-1)/2];
else
- median.x = (ordered_vals[(num_vals/2)-1] + ordered_vals[num_vals/2] + 1) >> 1;
+ median.x=(ordered_vals[(num_vals/2)-1]+ordered_vals[num_vals/2]+1)>>1;
//now do y
- ordered_vals[0] = vect_list[0].y;
- for(int I = 1; I < num_vals; ++I)
- {
- for(int K = 0; K < I; ++K)
- {
- if(vect_list[I].y < ordered_vals[K])
- {
- pos = K;
+ ordered_vals[0]=vect_list[0].y;
+ for (int I=1;I<num_vals;++I){
+ for (int K=0;K<I;++K){
+ if (vect_list[I].y<ordered_vals[K]){
+ pos=K;
break;
}
else
- pos = K + 1;
+ pos=K+1;
}//K
- if(pos == I)
- ordered_vals[I] = vect_list[I].y;
- else
- {
- for(int K = I - 1; K >= pos; --K)
- {
- ordered_vals[K+1] = ordered_vals[K];
+ if (pos==I)
+ ordered_vals[I]=vect_list[I].y;
+ else{
+ for (int K=I-1;K>=pos;--K){
+ ordered_vals[K+1]=ordered_vals[K];
}
- ordered_vals[pos] = vect_list[I].y;
+ ordered_vals[pos]=vect_list[I].y;
}
}//I
- if(num_vals % 2 != 0)
- median.y = ordered_vals[(num_vals-1)/2];
+ if (num_vals%2!=0)
+ median.y=ordered_vals[(num_vals-1)/2];
else
- median.y = (ordered_vals[(num_vals/2)-1] + ordered_vals[num_vals/2] + 1) >> 1;
+ median.y=(ordered_vals[(num_vals/2)-1]+ordered_vals[num_vals/2]+1)>>1;
}
- else
- {
- median.x = 0;
- median.y = 0;
+ else{
+ median.x=0;
+ median.y=0;
}
return median;
@@ -686,15 +666,15 @@ MVector MvMedian(const std::vector<MVector>& vect_list)
//! Return the unbiased mean of two motion vectors
MVector MvMean(const MVector& mv1, const MVector& mv2)
{
- //takes mean of each vector component
+ //takes mean of each vector component
MVector tmp_mv;
tmp_mv.x = mv1.x;
- tmp_mv.x += mv2.x + 1;
+ tmp_mv.x += mv2.x+1;
tmp_mv.x >>= 1;
tmp_mv.y = mv1.y;
- tmp_mv.y += mv2.y + 1;
+ tmp_mv.y += mv2.y+1;
tmp_mv.y >>= 1;
return tmp_mv;
@@ -703,12 +683,12 @@ MVector MvMean(const MVector& mv1, const MVector& mv2)
//! Return the mean of a set of unsigned integer values
unsigned int GetUMean(std::vector<unsigned int>& values)
{
- unsigned int sum = 0;
- for(unsigned int I = 0; I < values.size(); ++I)
- sum += values[I];
+ unsigned int sum=0;
+ for (unsigned int I=0;I<values.size();++I)
+ sum+=values[I];
- sum += (values.size() >> 1);
- sum /= values.size();
+ sum+=(values.size()>>1);
+ sum/=values.size();
return sum;
}
@@ -716,23 +696,23 @@ unsigned int GetUMean(std::vector<unsigned int>& values)
//! Return the mean of a set of signed integer values
int GetSMean(std::vector<int>& values)
{
- if(values.size() == 0)
+ if (values.size()==0)
return 0;
- int sum = 0;
- for(unsigned int i = 0; i < values.size(); ++i)
- sum += values[i];
- if(sum >= 0)
+ int sum=0;
+ for (unsigned int i=0;i<values.size();++i)
+ sum+=values[i];
+ if ( sum>=0 )
{
- sum += (values.size() >> 1);
- sum /= values.size();
+ sum+=(values.size()>>1);
+ sum/=values.size();
}
else
{
int old_sum = sum;
- sum -= values.size() * old_sum;
- sum += (values.size() >> 1);
- sum /= values.size();
+ sum -= values.size()*old_sum;
+ sum+=(values.size()>>1);
+ sum/=values.size();
sum += old_sum;
}
diff --git a/src/filters/parser/DiracSplitter/libdirac/libdirac_common/motion.h b/src/filters/parser/DiracSplitter/libdirac/libdirac_common/motion.h
index db402cef1..a985bdbd7 100644
--- a/src/filters/parser/DiracSplitter/libdirac/libdirac_common/motion.h
+++ b/src/filters/parser/DiracSplitter/libdirac/libdirac_common/motion.h
@@ -44,499 +44,404 @@
namespace dirac
{
-////////////////////////////////////////////////////////////////
-//classes and functions for motion estimation and compensation//
-////////////////////////////////////////////////////////////////
+ ////////////////////////////////////////////////////////////////
+ //classes and functions for motion estimation and compensation//
+ ////////////////////////////////////////////////////////////////
-//classes
+ //classes
-//! Horizontal or vertical
-enum MvElement { HORIZONTAL , VERTICAL };
+ //! Horizontal or vertical
+ enum MvElement { HORIZONTAL , VERTICAL };
-//! Motion vector class - just a pair
-template <class T>
-class MotionVector
-{
-public:
+ //! Motion vector class - just a pair
+ template <class T>
+ class MotionVector
+ {
+ public:
- //! Constructor
- MotionVector<T>(T a, T b) : x(a), y(b) {};
- //! Default construct - sets components to 0
- MotionVector<T>() : x(0), y(0) {};
- //! Constructor
- MotionVector<T>(T a) : x(a), y(a) {};
+ //! Constructor
+ MotionVector<T>(T a, T b) : x(a), y(b) {};
+ //! Default construct - sets components to 0
+ MotionVector<T>() : x(0), y(0) {};
+ //! Constructor
+ MotionVector<T>(T a) : x(a), y(a) {};
- //! Addition
- inline MotionVector<T> operator+(const MotionVector<T>& argument) const;
+ //! Addition
+ inline MotionVector<T> operator+(const MotionVector<T>& argument) const;
- //! Subtraction
- inline MotionVector<T> operator-(const MotionVector<T>& argument) const;
+ //! Subtraction
+ inline MotionVector<T> operator-(const MotionVector<T>& argument) const;
- //! Scalar multiplication
- inline MotionVector<T> operator*(const float argument) const;
+ //! Scalar multiplication
+ inline MotionVector<T> operator*(const float argument) const;
- //! Scalar multiplication
- inline MotionVector<T> operator*(const int argument) const;
+ //! Scalar multiplication
+ inline MotionVector<T> operator*(const int argument) const;
- //! Bitshift of each component
- inline MotionVector<T> operator<<(const int argument) const;
+ //! Bitshift of each component
+ inline MotionVector<T> operator<<(const int argument) const;
- //! Bitshift of each component
- inline MotionVector<T> operator>>(const int argument) const;
+ //! Bitshift of each component
+ inline MotionVector<T> operator>>(const int argument) const;
+
+ //! Array-style element access
+ T& operator[](const int pos){return ( ( pos==0) ? x : y );}
- //! Array-style element access
- T& operator[](const int pos)
- {
- return ((pos == 0) ? x : y);
- }
-
- //! Array-style element access.
- const T& operator[](const int pos) const
- {
- return ((pos == 0) ? x : y);
- }
+ //! Array-style element access.
+ const T& operator[](const int pos) const {return ( ( pos==0) ? x : y );}
- //! x and y components
- T x, y;
+ //! x and y components
+ T x,y;
-};
+ };
-template <class T>
-inline MotionVector<T> MotionVector<T>::operator+(const MotionVector<T>& argument) const
-{
- MotionVector<T> temp;
- temp.x = x + argument.x;
- temp.y = y + argument.y;
+ template <class T>
+ inline MotionVector<T> MotionVector<T>::operator+(const MotionVector<T>& argument) const
+ {
+ MotionVector<T> temp;
+ temp.x = x + argument.x;
+ temp.y = y + argument.y;
- return temp;
-}
+ return temp;
+ }
-template <class T>
-inline MotionVector<T> MotionVector<T>::operator-(const MotionVector<T>& argument) const
-{
- MotionVector<T> temp;
- temp.x = x - argument.x;
- temp.y = y - argument.y;
+ template <class T>
+ inline MotionVector<T> MotionVector<T>::operator-(const MotionVector<T>& argument) const
+ {
+ MotionVector<T> temp;
+ temp.x = x-argument.x;
+ temp.y = y-argument.y;
- return temp;
-}
+ return temp;
+ }
-template <class T>
-inline MotionVector<T> MotionVector<T>::operator*(const float argument) const
-{
- MotionVector<T> temp;
- temp.x = x * argument;
- temp.y = y * argument;
+ template <class T>
+ inline MotionVector<T> MotionVector<T>::operator*(const float argument) const
+ {
+ MotionVector<T> temp;
+ temp.x = x*argument;
+ temp.y = y*argument;
- return temp;
-}
+ return temp;
+ }
-template <class T>
-inline MotionVector<T> MotionVector<T>::operator*(const int argument) const
-{
- MotionVector<T> temp;
- temp.x = x * argument;
- temp.y = y * argument;
+ template <class T>
+ inline MotionVector<T> MotionVector<T>::operator*(const int argument) const
+ {
+ MotionVector<T> temp;
+ temp.x = x*argument;
+ temp.y = y*argument;
- return temp;
-}
+ return temp;
+ }
-template <class T>
-inline MotionVector<T> MotionVector<T>::operator<<(const int argument) const
-{
- MotionVector<T> temp;
- temp.x = x << argument;
- temp.y = y << argument;
+ template <class T>
+ inline MotionVector<T> MotionVector<T>::operator<<(const int argument) const
+ {
+ MotionVector<T> temp;
+ temp.x = x<<argument;
+ temp.y = y<<argument;
- return temp;
-}
+ return temp;
+ }
-template <class T>
-inline MotionVector<T> MotionVector<T>::operator>>(const int argument) const
-{
- MotionVector<T> temp;
- temp.x = x >> argument;
- temp.y = y >> argument;
+ template <class T>
+ inline MotionVector<T> MotionVector<T>::operator>>(const int argument) const
+ {
+ MotionVector<T> temp;
+ temp.x = x>>argument;
+ temp.y = y>>argument;
- return temp;
-}
+ return temp;
+ }
-//! Overloaded operator<< for MotionVector class for output to stream
-template <class T>
-std::ostream & operator<< (std::ostream & stream, MotionVector<T> & mv)
-{
- stream << mv.x << " " << mv.y;
+ //! Overloaded operator<< for MotionVector class for output to stream
+ template <class T>
+ std::ostream & operator<< (std::ostream & stream, MotionVector<T> & mv)
+ {
+ stream << mv.x << " " << mv.y;
- return stream;
-}
+ return stream;
+ }
-//! Overloaded operator>> for MotionVector class for input from stream
-template <class T>
-std::istream & operator>> (std::istream & stream, MotionVector<T> & mv)
-{
- stream >> mv.x;
- stream >> mv.y;
+ //! Overloaded operator>> for MotionVector class for input from stream
+ template <class T>
+ std::istream & operator>> (std::istream & stream, MotionVector<T> & mv)
+ {
+ stream >> mv.x;
+ stream >> mv.y;
- return stream;
-}
+ return stream;
+ }
-//! MVector class is a vector of ints
-typedef MotionVector<int> MVector;
+ //! MVector class is a vector of ints
+ typedef MotionVector<int> MVector;
-//! ImageCoords class is a vector of ints
-typedef MotionVector<int> ImageCoords;
+ //! ImageCoords class is a vector of ints
+ typedef MotionVector<int> ImageCoords;
-//! MvArray is a two-D array of MVectors
-typedef TwoDArray<MVector> MvArray;
+ //! MvArray is a two-D array of MVectors
+ typedef TwoDArray<MVector> MvArray;
-//! An array of float-based motion vectors for doing global motion calcs
-typedef TwoDArray< MotionVector<float> > MvFloatArray;
+ //! An array of float-based motion vectors for doing global motion calcs
+ typedef TwoDArray< MotionVector<float> > MvFloatArray;
-//! Class for recording costs derived in motion estimation
-class MvCostData
-{
-public:
- //! Constructor
- MvCostData():
+ //! Class for recording costs derived in motion estimation
+ class MvCostData
+ {
+ public:
+ //! Constructor
+ MvCostData():
SAD(0.0),
mvcost(0.0),
- total(0.0) {}
+ total(0.0){}
- void SetTotal(const float lambda)
- {
- total = SAD + lambda * mvcost;
- }
+ void SetTotal( const float lambda ){total = SAD + lambda*mvcost;}
- //! The Sum of Absolute Differences - easier to compute than Sum-Squared Differences
- float SAD;
+ //! The Sum of Absolute Differences - easier to compute than Sum-Squared Differences
+ float SAD;
- //! The (Lagrangian-weighted) motion vector cost - the difference of a motion vector from its neighbouring vectors
- float mvcost;
+ //! The (Lagrangian-weighted) motion vector cost - the difference of a motion vector from its neighbouring vectors
+ float mvcost;
- //! Total=SAD+mvcost
- float total;
-};
+ //! Total=SAD+mvcost
+ float total;
+ };
-//! Class for all the motion vector data
-/*!
- Motion vector data: the motion vectors themselves, the blocks
- and macroblock modes.
-*/
-class MvData
-{
-public:
- //! Constructor
+ //! Class for all the motion vector data
/*!
- Constructor takes:
- \param predparams Picture prediction parameters
- \param num_refs the number of references being used for the picture
+ Motion vector data: the motion vectors themselves, the blocks
+ and macroblock modes.
*/
- MvData(const PicturePredParams& predparams , const int num_refs);
+ class MvData
+ {
+ public:
+ //! Constructor
+ /*!
+ Constructor takes:
+ \param predparams Picture prediction parameters
+ \param num_refs the number of references being used for the picture
+ */
+ MvData( const PicturePredParams& predparams , const int num_refs);
- //! Destructor
- ~MvData();
+ //! Destructor
+ ~MvData();
- //! Return a reference to the local picture prediction params
- PicturePredParams& GetPicPredParams()
- {
- return m_predparams;
- }
+ //! Return a reference to the local picture prediction params
+ PicturePredParams& GetPicPredParams(){return m_predparams;}
- //! Return a reference to the local picture prediction params
- const PicturePredParams& GetPicPredParams() const
- {
- return m_predparams;
- }
+ //! Return a reference to the local picture prediction params
+ const PicturePredParams& GetPicPredParams() const{return m_predparams;}
- //! Get the MVs for a reference
- MvArray& Vectors(const int ref_id)
- {
- return *(m_vectors[ref_id]);
- }
+ //! Get the MVs for a reference
+ MvArray& Vectors(const int ref_id){return *( m_vectors[ref_id] );}
- //! Get the MVs for a reference
- const MvArray& Vectors(const int ref_id) const
- {
- return *(m_vectors[ref_id]);
- }
+ //! Get the MVs for a reference
+ const MvArray& Vectors(const int ref_id) const {return *( m_vectors[ref_id] );}
- //! Get the global MVs for a reference
- MvArray& GlobalMotionVectors(const int ref_id)
- {
- return *(m_gm_vectors[ref_id]);
- }
+ //! Get the global MVs for a reference
+ MvArray& GlobalMotionVectors(const int ref_id){return *( m_gm_vectors[ref_id] );}
- //! Get the global MVs for a reference
- const MvArray& GlobalMotionVectors(const int ref_id) const
- {
- return *(m_gm_vectors[ref_id]);
- }
+ //! Get the global MVs for a reference
+ const MvArray& GlobalMotionVectors(const int ref_id) const {return *( m_gm_vectors[ref_id] );}
- //! Get the DC values for each component
- TwoDArray<ValueType>& DC(CompSort cs)
- {
- return *(m_dc[cs]);
- }
+ //! Get the DC values for each component
+ TwoDArray<ValueType>& DC(CompSort cs){return *( m_dc[cs] );}
- //! Get the DC values for each component
- const TwoDArray<ValueType>& DC(CompSort cs) const
- {
- return *(m_dc[cs]);
- }
+ //! Get the DC values for each component
+ const TwoDArray<ValueType>& DC(CompSort cs) const {return *( m_dc[cs] );}
- //! Get a reference to the vector holding component DC values
- const OneDArray< TwoDArray<ValueType>* >& DC() const
- {
- return m_dc;
- }
+ //! Get a reference to the vector holding component DC values
+ const OneDArray< TwoDArray<ValueType>* >& DC() const {return m_dc;}
- //! Get the block prediction modes
- TwoDArray<PredMode>& Mode()
- {
- return m_modes;
- }
+ //! Get the block prediction modes
+ TwoDArray<PredMode>& Mode(){return m_modes;}
- //! Get the block prediction modes
- const TwoDArray<PredMode>& Mode() const
- {
- return m_modes;
- }
+ //! Get the block prediction modes
+ const TwoDArray<PredMode>& Mode() const {return m_modes;}
- //! Get the SB split level
- TwoDArray<int>& SBSplit()
- {
- return m_sb_split;
- }
+ //! Get the SB split level
+ TwoDArray<int>& SBSplit(){return m_sb_split;}
- //! Get the SB split level
- const TwoDArray<int>& SBSplit() const
- {
- return m_sb_split;
- }
+ //! Get the SB split level
+ const TwoDArray<int>& SBSplit() const{return m_sb_split;}
- //! Get the global motion model parameters
- OneDArray<float>& GlobalMotionParameters(const int ref_id)
- {
- return *(m_gm_params[ref_id]);
- }
+ //! Get the global motion model parameters
+ OneDArray<float>& GlobalMotionParameters(const int ref_id) { return *( m_gm_params[ref_id] ); }
- //! Get the global motion model parameters
- const OneDArray<float>& GlobalMotionParameters(const int ref_id) const
- {
- return *(m_gm_params[ref_id]);
- }
+ //! Get the global motion model parameters
+ const OneDArray<float>& GlobalMotionParameters(const int ref_id) const { return *( m_gm_params[ref_id] ); }
-protected:
- // A local copy of the picture prediction parameters
- PicturePredParams m_predparams;
+ protected:
+ // A local copy of the picture prediction parameters
+ PicturePredParams m_predparams;
- // Initialises the arrays of data
- void InitMvData();
+ // Initialises the arrays of data
+ void InitMvData();
- // The motion vectors
- OneDArray<MvArray*> m_vectors;
+ // The motion vectors
+ OneDArray<MvArray*> m_vectors;
- // The global motion vectors
- OneDArray<MvArray*> m_gm_vectors;
+ // The global motion vectors
+ OneDArray<MvArray*> m_gm_vectors;
- // The block modes
- TwoDArray<PredMode> m_modes;
+ // The block modes
+ TwoDArray<PredMode> m_modes;
- // The DC values
- OneDArray< TwoDArray<ValueType>* > m_dc;
+ // The DC values
+ OneDArray< TwoDArray<ValueType>* > m_dc;
- // The SB split levels
- TwoDArray<int> m_sb_split;
+ // The SB split levels
+ TwoDArray<int> m_sb_split;
- // Global motion model parameters
- OneDArray< OneDArray<float>* > m_gm_params;
+ // Global motion model parameters
+ OneDArray< OneDArray<float>* > m_gm_params;
// // Number of reference frames
// unsigned int m_num_refs;
-};
-
-//! Class for all the motion estimation data
-/*!
- Motion estimation data: derived from MvData class, also
- incorporates costs for blocks and macroblocks
-*/
-
-class MEData: public MvData
-{
-public:
+ };
- //! Constructor
+ //! Class for all the motion estimation data
/*!
- Constructor takes:
- \param predparams the picture prediction parameters
- \param num_refs the number of references being used for the picture
+ Motion estimation data: derived from MvData class, also
+ incorporates costs for blocks and macroblocks
*/
- MEData(const PicturePredParams& predparams , const int num_refs = 2);
- //! Destructor
- ~MEData();
-
- //! drop the data relating to one reference
- void DropRef(int ref_index);
-
- //! Get the block cost structures for each reference
- TwoDArray<MvCostData>& PredCosts(const int ref_id)
+ class MEData: public MvData
{
- return *(m_pred_costs[ref_id]);
- }
+ public:
- //! Get the block cost structures for each reference
- const TwoDArray<MvCostData>& PredCosts(const int ref_id) const
- {
- return *(m_pred_costs[ref_id]);
- }
+ //! Constructor
+ /*!
+ Constructor takes:
+ \param predparams the picture prediction parameters
+ \param num_refs the number of references being used for the picture
+ */
+ MEData( const PicturePredParams& predparams , const int num_refs = 2);
- //! Get the intra costs
- TwoDArray<float>& IntraCosts()
- {
- return m_intra_costs;
- }
+ //! Destructor
+ ~MEData();
+
+ //! drop the data relating to one reference
+ void DropRef( int ref_index );
- //! Get the intra costs
- const TwoDArray<float>& IntraCosts() const
- {
- return m_intra_costs;
- }
+ //! Get the block cost structures for each reference
+ TwoDArray<MvCostData>& PredCosts(const int ref_id){ return *( m_pred_costs[ref_id] ); }
- //! Get the bipred costs
- TwoDArray<MvCostData>& BiPredCosts()
- {
- return m_bipred_costs;
- }
+ //! Get the block cost structures for each reference
+ const TwoDArray<MvCostData>& PredCosts(const int ref_id) const { return *( m_pred_costs[ref_id] ); }
- //! Get the bipred costs
- const TwoDArray<MvCostData>& BiPredCosts() const
- {
- return m_bipred_costs;
- }
+ //! Get the intra costs
+ TwoDArray<float>& IntraCosts(){ return m_intra_costs; }
- //! Get the SB costs
- TwoDArray<float>& SBCosts()
- {
- return m_SB_costs;
- }
+ //! Get the intra costs
+ const TwoDArray<float>& IntraCosts() const { return m_intra_costs; }
- //! Get the SB costs
- const TwoDArray<float>& SBCosts() const
- {
- return m_SB_costs;
- }
+ //! Get the bipred costs
+ TwoDArray<MvCostData>& BiPredCosts(){ return m_bipred_costs; }
- //! Get the proportion of intra blocks
- float IntraBlockRatio() const
- {
- return m_intra_block_ratio;
- }
+ //! Get the bipred costs
+ const TwoDArray<MvCostData>& BiPredCosts() const { return m_bipred_costs; }
- //! Set the intra block ratio
- void SetIntraBlockRatio(const float r)
- {
- m_intra_block_ratio = r;
- }
+ //! Get the SB costs
+ TwoDArray<float>& SBCosts(){ return m_SB_costs; }
- //! Set up the lambda map by detecting motion discontinuities
- void SetLambdaMap(const int num_refs , const float lambda);
+ //! Get the SB costs
+ const TwoDArray<float>& SBCosts() const { return m_SB_costs; }
- //! Set up the lambda map by averaging the lambda map from a lower level
- void SetLambdaMap(const int level , const TwoDArray<float>& l_map , const float wt);
+ //! Get the proportion of intra blocks
+ float IntraBlockRatio() const {return m_intra_block_ratio; }
- //! Get a lambda value for a given block and level
- const TwoDArray<float>& LambdaMap() const
- {
- return m_lambda_map;
- }
+ //! Set the intra block ratio
+ void SetIntraBlockRatio(const float r){ m_intra_block_ratio = r; }
- //! Get the inliers for each reference
- TwoDArray<int>& GlobalMotionInliers(const int ref_id)
- {
- return *(m_inliers[ref_id]);
- }
+ //! Set up the lambda map by detecting motion discontinuities
+ void SetLambdaMap( const int num_refs , const float lambda );
- //! Get the inliers for each reference
- const TwoDArray<int>& GlobalMotionInliers(const int ref_id) const
- {
- return *(m_inliers[ref_id]);
- }
+ //! Set up the lambda map by averaging the lambda map from a lower level
+ void SetLambdaMap( const int level , const TwoDArray<float>& l_map , const float wt );
- //! Overloaded operator<< for outputing to (file) stream
- friend std::ostream &operator<< (std::ostream & stream, MEData & me_data);
+ //! Get a lambda value for a given block and level
+ const TwoDArray<float>& LambdaMap() const { return m_lambda_map; }
- //! Overloaded operator>> for input of data from (file) stream
- friend std::istream &operator>> (std::istream & stream, MEData & me_data);
+ //! Get the inliers for each reference
+ TwoDArray<int>& GlobalMotionInliers(const int ref_id){ return *( m_inliers[ref_id] ); }
-private:
- // Initialises the arrays of data
- void InitMEData();
+ //! Get the inliers for each reference
+ const TwoDArray<int>& GlobalMotionInliers(const int ref_id) const { return *( m_inliers[ref_id] ); }
- // Finds transitions in the motion vectors
- void FindTransitions(TwoDArray<bool>& trans_map , const int ref_num);
+ //! Overloaded operator<< for outputing to (file) stream
+ friend std::ostream &operator<< (std::ostream & stream, MEData & me_data);
- // The costs of predicting each block, for each reference
- OneDArray< TwoDArray<MvCostData>* > m_pred_costs;
+ //! Overloaded operator>> for input of data from (file) stream
+ friend std::istream &operator>> (std::istream & stream, MEData & me_data);
- // The costs of predicting each block by DC
- TwoDArray<float> m_intra_costs;
+ private:
+ // Initialises the arrays of data
+ void InitMEData();
- // The costs of predicting each block bidirectionally
- TwoDArray<MvCostData> m_bipred_costs;
+ // Finds transitions in the motion vectors
+ void FindTransitions( TwoDArray<bool>& trans_map , const int ref_num );
- // The costs for each macroblock as a whole
- TwoDArray<float> m_SB_costs;
+ // The costs of predicting each block, for each reference
+ OneDArray< TwoDArray<MvCostData>* > m_pred_costs;
- // A map of the lambda values to use
- TwoDArray<float> m_lambda_map;
+ // The costs of predicting each block by DC
+ TwoDArray<float> m_intra_costs;
- // Global motion inliers
- OneDArray< TwoDArray<int>* > m_inliers;
+ // The costs of predicting each block bidirectionally
+ TwoDArray<MvCostData> m_bipred_costs;
- // Intra block ratio
- float m_intra_block_ratio;
+ // The costs for each macroblock as a whole
+ TwoDArray<float> m_SB_costs;
-};
+ // A map of the lambda values to use
+ TwoDArray<float> m_lambda_map;
-//motion estimation and coding stuff
+ // Global motion inliers
+ OneDArray< TwoDArray<int>* > m_inliers;
-//! Return the median of 3 integers
-int Median(const int val1, const int val2, const int val3);
+ // Intra block ratio
+ float m_intra_block_ratio;
-//! Return the median of three motion vectors
-MVector MvMedian(const MVector& mv1, const MVector& mv2, const MVector& mv3);
+ };
+ //motion estimation and coding stuff
+
+ //! Return the median of 3 integers
+ int Median( const int val1, const int val2, const int val3);
-//! Return the median of a set of integers
-int Median(const std::vector<int>& val_list);
+ //! Return the median of three motion vectors
+ MVector MvMedian(const MVector& mv1,const MVector& mv2,const MVector& mv3);
-//! Return the median of a set of (up to 4) motion vectors
-MVector MvMedian(const std::vector<MVector>& vect_list);
-//! Return the mean of two motion vectors
-MVector MvMean(const MVector& mv1, const MVector& mv2);
+ //! Return the median of a set of integers
+ int Median(const std::vector<int>& val_list);
-//! Return the squared length of a motion vector
-inline int Norm2(const MVector& mv) //L^2 norm of a motion vector
-{
- return mv.x * mv.x + mv.y * mv.y;
-}
+ //! Return the median of a set of (up to 4) motion vectors
+ MVector MvMedian(const std::vector<MVector>& vect_list);
-//! Return the sum of the lengths of a motion vector's componets
-inline int Norm1(const MVector& mv) //L^1 norm of a motion vector
-{
- return abs(mv.x) + abs(mv.y);
-}
+ //! Return the mean of two motion vectors
+ MVector MvMean(const MVector& mv1, const MVector& mv2);
-//! Return the mean of a set of unsigned integer values
-unsigned int GetUMean(std::vector<unsigned int>& values);
+ //! Return the squared length of a motion vector
+ inline int Norm2(const MVector& mv){//L^2 norm of a motion vector
+ return mv.x*mv.x+mv.y*mv.y;
+ }
-//! Return the mean of a set of signed integer values
-int GetSMean(std::vector<int>& values);
+ //! Return the sum of the lengths of a motion vector's componets
+ inline int Norm1(const MVector& mv){//L^1 norm of a motion vector
+ return abs(mv.x)+abs(mv.y);
+ }
+
+ //! Return the mean of a set of unsigned integer values
+ unsigned int GetUMean(std::vector<unsigned int>& values);
+
+ //! Return the mean of a set of signed integer values
+ int GetSMean(std::vector<int>& values);
} // namespace dirac
diff --git a/src/filters/parser/DiracSplitter/libdirac/libdirac_common/mv_codec.cpp b/src/filters/parser/DiracSplitter/libdirac/libdirac_common/mv_codec.cpp
index 6de2418dd..d576d6e12 100644
--- a/src/filters/parser/DiracSplitter/libdirac/libdirac_common/mv_codec.cpp
+++ b/src/filters/parser/DiracSplitter/libdirac/libdirac_common/mv_codec.cpp
@@ -45,42 +45,42 @@ using namespace dirac;
//public functions//
////////////////////
-// Constructor
+// Constructor
SplitModeCodec::SplitModeCodec(ByteIO* p_byteio,
- size_t number_of_contexts)
- : ArithCodec <MvData> (p_byteio, number_of_contexts)
-{}
+ size_t number_of_contexts)
+ : ArithCodec <MvData> (p_byteio,number_of_contexts)
+{}
-void SplitModeCodec::InitContexts()
-{
+void SplitModeCodec::InitContexts()
+{
}
// Main code function
-void SplitModeCodec::DoWorkCode(MvData& in_data)
+void SplitModeCodec::DoWorkCode( MvData& in_data )
{
- for(m_sb_yp = 0; m_sb_yp < in_data.SBSplit().LengthY(); ++m_sb_yp)
+ for (m_sb_yp = 0; m_sb_yp < in_data.SBSplit().LengthY(); ++m_sb_yp)
{
- for(m_sb_xp = 0; m_sb_xp < in_data.SBSplit().LengthX(); ++m_sb_xp)
+ for (m_sb_xp = 0; m_sb_xp < in_data.SBSplit().LengthX(); ++m_sb_xp)
{
CodeVal(in_data);
}//m_sb_xp
}//m_sb_yp
-}
+}
// Main decode function
-void SplitModeCodec::DoWorkDecode(MvData& out_data)
+void SplitModeCodec::DoWorkDecode( MvData& out_data)
{
- for(m_sb_yp = 0; m_sb_yp < out_data.SBSplit().LengthY(); ++m_sb_yp)
+ for (m_sb_yp = 0; m_sb_yp < out_data.SBSplit().LengthY(); ++m_sb_yp)
{
- for(m_sb_xp = 0; m_sb_xp < out_data.SBSplit().LengthX(); ++m_sb_xp)
+ for (m_sb_xp = 0; m_sb_xp < out_data.SBSplit().LengthX(); ++m_sb_xp)
{
- DecodeVal(out_data);
+ DecodeVal( out_data );
}//m_sb_xp
}//m_sb_yp
-}
+}
//protected functions//
///////////////////////
@@ -94,34 +94,34 @@ void SplitModeCodec::ResetAll()
//prediction functions
-unsigned int SplitModeCodec::Prediction(const TwoDArray<int> & split_data) const
-{
+unsigned int SplitModeCodec::Prediction(const TwoDArray<int> & split_data ) const
+{
int result = 0;
-
+
std::vector < unsigned int > nbrs;
-
- if(m_sb_xp > 0 && m_sb_yp > 0)
+
+ if (m_sb_xp > 0 && m_sb_yp > 0)
{
- nbrs.push_back(split_data[m_sb_yp-1][m_sb_xp]);
- nbrs.push_back(split_data[m_sb_yp-1][m_sb_xp-1]);
- nbrs.push_back(split_data[m_sb_yp][m_sb_xp-1]);
+ nbrs.push_back( split_data[m_sb_yp-1][m_sb_xp] );
+ nbrs.push_back( split_data[m_sb_yp-1][m_sb_xp-1] );
+ nbrs.push_back( split_data[m_sb_yp][m_sb_xp-1] );
- result = GetUMean(nbrs);
+ result = GetUMean(nbrs);
}
- else if(m_sb_xp > 0 && m_sb_yp == 0)
- result = split_data[m_sb_yp][m_sb_xp-1];
- else if(m_sb_xp == 0 && m_sb_yp > 0)
- result = split_data[m_sb_yp-1][m_sb_xp];
+ else if (m_sb_xp > 0 && m_sb_yp == 0)
+ result = split_data[m_sb_yp][m_sb_xp-1];
+ else if (m_sb_xp == 0 && m_sb_yp > 0)
+ result = split_data[m_sb_yp-1][m_sb_xp];
- return result;
+ return result;
}
void SplitModeCodec::CodeVal(const MvData& in_data)
{
- int val = in_data.SBSplit()[m_sb_yp][m_sb_xp] - Prediction(in_data.SBSplit());
-
- if(val < 0) val += 3; //produce prediction mod 3
+ int val = in_data.SBSplit()[m_sb_yp][m_sb_xp] - Prediction( in_data.SBSplit() );
+
+ if (val < 0) val+=3; //produce prediction mod 3
EncodeUInt(val, SB_SPLIT_BIN1_CTX, SB_SPLIT_BIN2_CTX);
}
@@ -134,96 +134,96 @@ void SplitModeCodec::CodeVal(const MvData& in_data)
void SplitModeCodec::DecodeVal(MvData& out_data)
{
out_data.SBSplit()[m_sb_yp][m_sb_xp] =
- (DecodeUInt(SB_SPLIT_BIN1_CTX, SB_SPLIT_BIN2_CTX) +
- Prediction(out_data.SBSplit())) % 3;
+ (DecodeUInt(SB_SPLIT_BIN1_CTX, SB_SPLIT_BIN2_CTX) +
+ Prediction(out_data.SBSplit())) % 3;
}
/******************************************************************************/
//public functions//
////////////////////
-// Constructor
+// Constructor
PredModeCodec::PredModeCodec(ByteIO* p_byteio,
- size_t number_of_contexts,
- int num_refs)
- : ArithCodec <MvData> (p_byteio, number_of_contexts),
- m_num_refs(num_refs)
-{}
+ size_t number_of_contexts,
+ int num_refs)
+ : ArithCodec <MvData> (p_byteio,number_of_contexts),
+ m_num_refs(num_refs)
+{}
-void PredModeCodec::InitContexts()
-{
+void PredModeCodec::InitContexts()
+{
}
// Main code function
-void PredModeCodec::DoWorkCode(MvData& in_data)
+void PredModeCodec::DoWorkCode( MvData& in_data )
{
- int step, max;
- int split_depth;
+ int step,max;
+ int split_depth;
- for(m_sb_yp = 0, m_sb_tlb_y = 0; m_sb_yp < in_data.SBSplit().LengthY(); ++m_sb_yp, m_sb_tlb_y += 4)
+ for (m_sb_yp = 0, m_sb_tlb_y = 0; m_sb_yp < in_data.SBSplit().LengthY(); ++m_sb_yp, m_sb_tlb_y += 4)
{
- for(m_sb_xp = 0, m_sb_tlb_x = 0; m_sb_xp < in_data.SBSplit().LengthX(); ++m_sb_xp, m_sb_tlb_x += 4)
+ for (m_sb_xp = 0,m_sb_tlb_x = 0; m_sb_xp < in_data.SBSplit().LengthX(); ++m_sb_xp,m_sb_tlb_x += 4)
{
- split_depth = in_data.SBSplit()[m_sb_yp][m_sb_xp];
+ split_depth = in_data.SBSplit()[m_sb_yp][m_sb_xp];
- step = 4 >> (split_depth);
- max = (1 << split_depth);
-
- //now do all the block modes and mvs in the mb
- for(m_b_yp = m_sb_tlb_y; m_b_yp < m_sb_tlb_y + 4; m_b_yp += step)
+ step = 4 >> (split_depth);
+ max = (1 << split_depth);
+
+ //now do all the block modes and mvs in the mb
+ for (m_b_yp = m_sb_tlb_y; m_b_yp < m_sb_tlb_y+4; m_b_yp += step)
{
- for(m_b_xp = m_sb_tlb_x; m_b_xp < m_sb_tlb_x + 4; m_b_xp += step)
+ for (m_b_xp = m_sb_tlb_x; m_b_xp < m_sb_tlb_x+4; m_b_xp += step)
{
CodeVal(in_data);
}//m_b_xp
- }//m_b_yp
-
+ }//m_b_yp
+
}//m_sb_xp
- }//m_sb_yp
-}
+ }//m_sb_yp
+}
// Main decode function
-void PredModeCodec::DoWorkDecode(MvData& out_data)
+void PredModeCodec::DoWorkDecode( MvData& out_data)
{
- int step, max;
- int split_depth;
- int xstart, ystart;
+ int step,max;
+ int split_depth;
+ int xstart,ystart;
// Then the prediction mode
- for(m_sb_yp = 0, m_sb_tlb_y = 0; m_sb_yp < out_data.SBSplit().LengthY(); ++m_sb_yp, m_sb_tlb_y += 4)
+ for (m_sb_yp = 0,m_sb_tlb_y = 0; m_sb_yp < out_data.SBSplit().LengthY(); ++m_sb_yp,m_sb_tlb_y += 4)
{
- for(m_sb_xp = 0, m_sb_tlb_x = 0; m_sb_xp < out_data.SBSplit().LengthX(); ++m_sb_xp, m_sb_tlb_x += 4)
+ for (m_sb_xp = 0,m_sb_tlb_x = 0; m_sb_xp < out_data.SBSplit().LengthX(); ++m_sb_xp,m_sb_tlb_x += 4)
{
- split_depth = out_data.SBSplit()[m_sb_yp][m_sb_xp];
- step = 4 >> (split_depth);
- max = (1 << split_depth);
+ split_depth = out_data.SBSplit()[m_sb_yp][m_sb_xp];
+ step = 4 >> (split_depth);
+ max = (1 << split_depth);
//now do all the block mvs in the mb
- for(int j = 0; j < max; ++j)
- {
- for(int i = 0; i < max; ++i)
+ for (int j = 0; j < max; ++j)
+ {
+ for (int i = 0; i < max; ++i)
{
- xstart = m_b_xp = m_sb_tlb_x + i * step;
- ystart = m_b_yp = m_sb_tlb_y + j * step;
-
- DecodeVal(out_data);
+ xstart = m_b_xp = m_sb_tlb_x + i * step;
+ ystart = m_b_yp = m_sb_tlb_y + j * step;
+
+ DecodeVal(out_data);
- // propagate throughout SB
- for(m_b_yp = ystart; m_b_yp < ystart + step; m_b_yp++)
+ // propagate throughout SB
+ for (m_b_yp = ystart; m_b_yp < ystart+step; m_b_yp++)
{
- for(m_b_xp = xstart; m_b_xp < xstart + step; m_b_xp++)
- {
- out_data.Mode()[m_b_yp][m_b_xp] = out_data.Mode()[ystart][xstart];
+ for (m_b_xp = xstart; m_b_xp < xstart+step; m_b_xp++)
+ {
+ out_data.Mode()[m_b_yp][m_b_xp] = out_data.Mode()[ystart][xstart];
}//m_b_xp
}//m_b_yp
- }//i
+ }//i
}//j
}//m_sb_xp
}//m_sb_yp
-}
+}
//protected functions//
///////////////////////
@@ -240,30 +240,30 @@ void PredModeCodec::ResetAll()
unsigned int PredModeCodec::Prediction(const TwoDArray < PredMode > & preddata) const
{
unsigned int result = (unsigned int)(INTRA);
- unsigned int num_ref1_nbrs(0);
- unsigned int num_ref2_nbrs(0);
-
- if(m_b_xp > 0 && m_b_yp > 0)
+ unsigned int num_ref1_nbrs( 0 );
+ unsigned int num_ref2_nbrs( 0 );
+
+ if (m_b_xp > 0 && m_b_yp > 0)
{
- num_ref1_nbrs += ((unsigned int)(preddata[m_b_yp-1][m_b_xp])) & 1;
- num_ref1_nbrs += ((unsigned int)(preddata[m_b_yp-1][m_b_xp-1])) & 1;
- num_ref1_nbrs += ((unsigned int)(preddata[m_b_yp][m_b_xp-1])) & 1;
+ num_ref1_nbrs += ((unsigned int)( preddata[m_b_yp-1][m_b_xp] ) ) & 1;
+ num_ref1_nbrs += ((unsigned int)( preddata[m_b_yp-1][m_b_xp-1] ) ) & 1;
+ num_ref1_nbrs += ((unsigned int)( preddata[m_b_yp][m_b_xp-1] ) ) & 1;
- result = num_ref1_nbrs >> 1;
+ result = num_ref1_nbrs>>1;
- if(m_num_refs == 2)
+ if ( m_num_refs==2)
{
- num_ref2_nbrs += ((unsigned int)(preddata[m_b_yp-1][m_b_xp])) & 2;
- num_ref2_nbrs += ((unsigned int)(preddata[m_b_yp-1][m_b_xp-1])) & 2;
- num_ref2_nbrs += ((unsigned int)(preddata[m_b_yp][m_b_xp-1])) & 2;
+ num_ref2_nbrs += ((unsigned int)( preddata[m_b_yp-1][m_b_xp] ) ) & 2;
+ num_ref2_nbrs += ((unsigned int)( preddata[m_b_yp-1][m_b_xp-1] ) ) & 2;
+ num_ref2_nbrs += ((unsigned int)( preddata[m_b_yp][m_b_xp-1] ) ) & 2;
num_ref2_nbrs >>= 1;
- result ^= ((num_ref2_nbrs >> 1) << 1);
+ result ^= ( (num_ref2_nbrs>>1)<<1 );
}
}
- else if(m_b_xp > 0 && m_b_yp == 0)
- result = (unsigned int)(preddata[0][m_b_xp-1]);
- else if(m_b_xp == 0 && m_b_yp > 0)
- result = (unsigned int)(preddata[m_b_yp-1][0]);
+ else if (m_b_xp > 0 && m_b_yp == 0)
+ result = (unsigned int)( preddata[0][m_b_xp-1] );
+ else if (m_b_xp == 0 && m_b_yp > 0)
+ result = (unsigned int)( preddata[m_b_yp-1][0] );
return result;
}
@@ -273,15 +273,15 @@ void PredModeCodec::CodeVal(const MvData& in_data)
// Xor with the prediction so we predict whether REF1 is used or REF2 is
// used, separately
unsigned int residue = in_data.Mode()[m_b_yp][m_b_xp] ^
- Prediction(in_data.Mode());
+ Prediction( in_data.Mode() );
// Code REF1 part of the prediction residue (ie the first bit)
- EncodeSymbol(residue & 1 , PMODE_BIT0_CTX);
+ EncodeSymbol( residue & 1 , PMODE_BIT0_CTX );
// Code REF2 part of the prediction residue (ie the second bit)
- if(m_num_refs == 2)
+ if (m_num_refs==2)
{
- EncodeSymbol(residue & 2 , PMODE_BIT1_CTX);
+ EncodeSymbol( residue & 2 , PMODE_BIT1_CTX );
}
}
@@ -289,7 +289,7 @@ void PredModeCodec::CodeVal(const MvData& in_data)
//decoding functions//
//////////////////////
-void PredModeCodec::DecodeVal(MvData& out_data)
+void PredModeCodec::DecodeVal( MvData& out_data )
{
// Xor with the prediction so we predict whether REF1 is used or REF2 is
// used, separately
@@ -297,18 +297,18 @@ void PredModeCodec::DecodeVal(MvData& out_data)
// Decode REF1 part of the prediction residue (ie the first bit)
bool bit;
- bit = DecodeSymbol(PMODE_BIT0_CTX);
+ bit = DecodeSymbol( PMODE_BIT0_CTX );
residue = (unsigned int) bit;
// Decode REF2 part of the prediction residue (ie the second bit)
- if(m_num_refs == 2)
+ if (m_num_refs==2)
{
- bit = DecodeSymbol(PMODE_BIT1_CTX);
- residue |= ((unsigned int) bit) << 1;
+ bit = DecodeSymbol( PMODE_BIT1_CTX );
+ residue |= ( (unsigned int) bit ) << 1;
}
out_data.Mode()[m_b_yp][m_b_xp] =
- PredMode(Prediction(out_data.Mode()) ^ residue);
+ PredMode( Prediction( out_data.Mode() ) ^ residue );
}
/******************************************************************************/
@@ -321,9 +321,9 @@ VectorElementCodec::VectorElementCodec(ByteIO* p_byteio,
int ref_id,
MvElement horvert,
size_t number_of_contexts)
- : ArithCodec <MvData> (p_byteio, number_of_contexts),
- m_ref(ref_id),
- m_hv(horvert)
+ : ArithCodec <MvData> (p_byteio,number_of_contexts),
+ m_ref(ref_id),
+ m_hv(horvert)
{}
@@ -332,80 +332,80 @@ void VectorElementCodec::InitContexts()
{}
// Main code function
-void VectorElementCodec::DoWorkCode(MvData& in_data)
+void VectorElementCodec::DoWorkCode( MvData& in_data )
{
- int step, max;
+ int step,max;
int split_depth;
- for(m_sb_yp = 0, m_sb_tlb_y = 0; m_sb_yp < in_data.SBSplit().LengthY(); ++m_sb_yp, m_sb_tlb_y += 4)
+ for (m_sb_yp = 0, m_sb_tlb_y = 0; m_sb_yp < in_data.SBSplit().LengthY(); ++m_sb_yp, m_sb_tlb_y += 4)
{
- for(m_sb_xp = 0, m_sb_tlb_x = 0; m_sb_xp < in_data.SBSplit().LengthX(); ++m_sb_xp, m_sb_tlb_x += 4)
+ for (m_sb_xp = 0,m_sb_tlb_x = 0; m_sb_xp < in_data.SBSplit().LengthX(); ++m_sb_xp,m_sb_tlb_x += 4)
{
split_depth = in_data.SBSplit()[m_sb_yp][m_sb_xp];
- step = 4 >> (split_depth);
+ step = 4 >> (split_depth);
max = (1 << split_depth);
-
- //now do all the block modes and mvs in the mb
- for(m_b_yp = m_sb_tlb_y; m_b_yp < m_sb_tlb_y + 4; m_b_yp += step)
+
+ //now do all the block modes and mvs in the mb
+ for (m_b_yp = m_sb_tlb_y; m_b_yp < m_sb_tlb_y+4; m_b_yp += step)
{
- for(m_b_xp = m_sb_tlb_x; m_b_xp < m_sb_tlb_x + 4; m_b_xp += step)
+ for (m_b_xp = m_sb_tlb_x; m_b_xp < m_sb_tlb_x+4; m_b_xp += step)
{
- if(in_data.Mode()[m_b_yp][m_b_xp] & m_ref)
+ if ( in_data.Mode()[m_b_yp][m_b_xp] & m_ref )
{
CodeVal(in_data);
- }
+ }
}//m_b_xp
- }//m_b_yp
-
+ }//m_b_yp
+
}//m_sb_xp
}//m_sb_yp
-}
+}
// Main decode function
-void VectorElementCodec::DoWorkDecode(MvData& out_data)
+void VectorElementCodec::DoWorkDecode( MvData& out_data)
{
- int step, max;
- int split_depth;
- int xstart, ystart;
+ int step,max;
+ int split_depth;
+ int xstart,ystart;
- for(m_sb_yp = 0, m_sb_tlb_y = 0; m_sb_yp < out_data.SBSplit().LengthY(); ++m_sb_yp, m_sb_tlb_y += 4)
+ for (m_sb_yp = 0,m_sb_tlb_y = 0; m_sb_yp < out_data.SBSplit().LengthY(); ++m_sb_yp,m_sb_tlb_y += 4)
{
- for(m_sb_xp = 0, m_sb_tlb_x = 0; m_sb_xp < out_data.SBSplit().LengthX(); ++m_sb_xp, m_sb_tlb_x += 4)
+ for (m_sb_xp = 0,m_sb_tlb_x = 0; m_sb_xp < out_data.SBSplit().LengthX(); ++m_sb_xp,m_sb_tlb_x += 4)
{
- split_depth = out_data.SBSplit()[m_sb_yp][m_sb_xp];
- step = 4 >> (split_depth);
- max = (1 << split_depth);
+ split_depth = out_data.SBSplit()[m_sb_yp][m_sb_xp];
+ step = 4 >> (split_depth);
+ max = (1 << split_depth);
//now do all the block mvs in the mb
- for(int j = 0; j < max; ++j)
- {
- for(int i = 0; i < max; ++i)
+ for (int j = 0; j < max; ++j)
+ {
+ for (int i = 0; i < max; ++i)
{
- xstart = m_b_xp = m_sb_tlb_x + i * step;
- ystart = m_b_yp = m_sb_tlb_y + j * step;
-
- if(out_data.Mode()[m_b_yp][m_b_xp] & m_ref)
+ xstart = m_b_xp = m_sb_tlb_x + i * step;
+ ystart = m_b_yp = m_sb_tlb_y + j * step;
+
+ if (out_data.Mode()[m_b_yp][m_b_xp] & m_ref)
{
- DecodeVal(out_data);
+ DecodeVal( out_data );
}
-
- // propagate throughout SB
- for(m_b_yp = ystart; m_b_yp < ystart + step; m_b_yp++)
+
+ // propagate throughout SB
+ for (m_b_yp = ystart; m_b_yp < ystart+step; m_b_yp++)
{
- for(m_b_xp = xstart; m_b_xp < xstart + step; m_b_xp++)
- {
- out_data.Vectors(m_ref)[m_b_yp][m_b_xp][m_hv] =
- out_data.Vectors(m_ref)[ystart][xstart][m_hv];
+ for (m_b_xp = xstart; m_b_xp < xstart+step; m_b_xp++)
+ {
+ out_data.Vectors(m_ref)[m_b_yp][m_b_xp][m_hv] =
+ out_data.Vectors(m_ref)[ystart][xstart][m_hv];
}//m_b_xp
}//m_b_yp
- }//i
+ }//i
}//j
}//m_sb_xp
}//m_sb_yp
-}
+}
//protected functions//
///////////////////////
@@ -420,48 +420,48 @@ void VectorElementCodec::ResetAll()
//prediction functions
int VectorElementCodec::Prediction(const MvArray& mvarray,
- const TwoDArray < PredMode > & preddata) const
+ const TwoDArray < PredMode > & preddata) const
{
- std::vector <int> nbrs;
- PredMode pmode;
- int result(0);
-
- if(m_b_xp > 0 && m_b_yp > 0)
+ std::vector <int> nbrs;
+ PredMode pmode;
+ int result( 0 );
+
+ if (m_b_xp > 0 && m_b_yp > 0)
{
- pmode = preddata[m_b_yp-1][m_b_xp];
- if(pmode & m_ref)
- nbrs.push_back(mvarray[m_b_yp-1][m_b_xp][m_hv]);
-
- pmode = preddata[m_b_yp-1][m_b_xp-1];
- if(pmode & m_ref)
- nbrs.push_back(mvarray[m_b_yp-1][m_b_xp-1][m_hv]);
-
- pmode = preddata[m_b_yp][m_b_xp-1];
- if(pmode & m_ref)
+ pmode = preddata[m_b_yp-1][m_b_xp];
+ if (pmode & m_ref)
+ nbrs.push_back(mvarray[m_b_yp-1][m_b_xp][m_hv]);
+
+ pmode = preddata[m_b_yp-1][m_b_xp-1];
+ if (pmode & m_ref)
+ nbrs.push_back(mvarray[m_b_yp-1][m_b_xp-1][m_hv]);
+
+ pmode = preddata[m_b_yp][m_b_xp-1];
+ if (pmode & m_ref)
nbrs.push_back(mvarray[m_b_yp][m_b_xp-1][m_hv]);
-
- if(nbrs.size() > 0)
- result = Median(nbrs);
+
+ if (nbrs.size() > 0)
+ result = Median(nbrs);
}
- else if(m_b_xp > 0 && m_b_yp == 0)
+ else if (m_b_xp > 0 && m_b_yp == 0)
{
- pmode = preddata[0][m_b_xp-1];
- if(pmode & m_ref)
- result = mvarray[0][m_b_xp-1][m_hv];
+ pmode = preddata[0][m_b_xp-1];
+ if (pmode & m_ref)
+ result = mvarray[0][m_b_xp-1][m_hv];
}
- else if(m_b_xp == 0 && m_b_yp > 0)
+ else if (m_b_xp == 0 && m_b_yp > 0)
{
- pmode = preddata[m_b_yp-1][0];
- if(pmode & m_ref)
+ pmode = preddata[m_b_yp-1][0];
+ if (pmode & m_ref)
result = mvarray[m_b_yp-1][0][m_hv];
}
- return result;
+ return result;
}
-void VectorElementCodec::CodeVal(const MvData& in_data)
+void VectorElementCodec::CodeVal(const MvData& in_data )
{
const MvArray& mv_array = in_data.Vectors(m_ref);
- const int pred = Prediction(mv_array , in_data.Mode());
+ const int pred = Prediction( mv_array , in_data.Mode() );
const int val = mv_array[m_b_yp][m_b_xp][m_hv] - pred;
EncodeSInt(val, MV_FBIN1_CTX, MV_FBIN5plus_CTX);
@@ -471,11 +471,11 @@ void VectorElementCodec::CodeVal(const MvData& in_data)
//////////////////////
-void VectorElementCodec::DecodeVal(MvData& out_data)
+void VectorElementCodec::DecodeVal( MvData& out_data )
{
- MvArray& mv_array = out_data.Vectors(m_ref);
- int pred = Prediction(mv_array , out_data.Mode());
- mv_array[m_b_yp][m_b_xp][m_hv] = pred +
+ MvArray& mv_array = out_data.Vectors(m_ref);
+ int pred = Prediction( mv_array , out_data.Mode() );
+ mv_array[m_b_yp][m_b_xp][m_hv] = pred +
DecodeSInt(MV_FBIN1_CTX, MV_FBIN5plus_CTX);
}
@@ -483,95 +483,95 @@ void VectorElementCodec::DecodeVal(MvData& out_data)
/******************************************************************************/
//public functions//
////////////////////
-// Constructor
+// Constructor
DCCodec::DCCodec(ByteIO* p_byteio,
- const CompSort csort,
- size_t number_of_contexts):
- ArithCodec <MvData> (p_byteio, number_of_contexts),
- m_csort(csort)
-{}
+ const CompSort csort,
+ size_t number_of_contexts):
+ArithCodec <MvData> (p_byteio,number_of_contexts),
+m_csort( csort )
+{}
-void DCCodec::InitContexts()
-{
+void DCCodec::InitContexts()
+{
}
// Main code function
-void DCCodec::DoWorkCode(MvData& in_data)
+void DCCodec::DoWorkCode( MvData& in_data )
{
- int step, max;
- int split_depth;
-
- for(m_sb_yp = 0, m_sb_tlb_y = 0; m_sb_yp < in_data.SBSplit().LengthY(); ++m_sb_yp, m_sb_tlb_y += 4)
+ int step,max;
+ int split_depth;
+
+ for (m_sb_yp = 0, m_sb_tlb_y = 0; m_sb_yp < in_data.SBSplit().LengthY(); ++m_sb_yp, m_sb_tlb_y += 4)
{
- for(m_sb_xp = 0, m_sb_tlb_x = 0; m_sb_xp < in_data.SBSplit().LengthX(); ++m_sb_xp, m_sb_tlb_x += 4)
+ for (m_sb_xp = 0,m_sb_tlb_x = 0; m_sb_xp < in_data.SBSplit().LengthX(); ++m_sb_xp,m_sb_tlb_x += 4)
{
- split_depth = in_data.SBSplit()[m_sb_yp][m_sb_xp];
-
- step = 4 >> (split_depth);
- max = (1 << split_depth);
+ split_depth = in_data.SBSplit()[m_sb_yp][m_sb_xp];
- //now do all the block modes and mvs in the mb
- for(m_b_yp = m_sb_tlb_y; m_b_yp < m_sb_tlb_y + 4; m_b_yp += step)
+ step = 4 >> (split_depth);
+ max = (1 << split_depth);
+
+ //now do all the block modes and mvs in the mb
+ for (m_b_yp = m_sb_tlb_y; m_b_yp < m_sb_tlb_y+4; m_b_yp += step)
{
- for(m_b_xp = m_sb_tlb_x; m_b_xp < m_sb_tlb_x + 4; m_b_xp += step)
+ for (m_b_xp = m_sb_tlb_x; m_b_xp < m_sb_tlb_x+4; m_b_xp += step)
{
if(in_data.Mode()[m_b_yp][m_b_xp] == INTRA)
{
CodeVal(in_data);
}
}//m_b_xp
- }//m_b_yp
-
+ }//m_b_yp
+
}//m_sb_xp
}//m_sb_yp
-}
+}
// Main decode function
-void DCCodec::DoWorkDecode(MvData& out_data)
+void DCCodec::DoWorkDecode( MvData& out_data)
{
- int step, max;
- int split_depth;
- int xstart, ystart;
+ int step,max;
+ int split_depth;
+ int xstart,ystart;
- for(m_sb_yp = 0, m_sb_tlb_y = 0; m_sb_yp < out_data.SBSplit().LengthY(); ++m_sb_yp, m_sb_tlb_y += 4)
+ for (m_sb_yp = 0,m_sb_tlb_y = 0; m_sb_yp < out_data.SBSplit().LengthY(); ++m_sb_yp,m_sb_tlb_y += 4)
{
- for(m_sb_xp = 0, m_sb_tlb_x = 0; m_sb_xp < out_data.SBSplit().LengthX(); ++m_sb_xp, m_sb_tlb_x += 4)
+ for (m_sb_xp = 0,m_sb_tlb_x = 0; m_sb_xp < out_data.SBSplit().LengthX(); ++m_sb_xp,m_sb_tlb_x += 4)
{
- //start with split mode
- split_depth = out_data.SBSplit()[m_sb_yp][m_sb_xp];
- step = 4 >> (split_depth);
- max = (1 << split_depth);
+ //start with split mode
+ split_depth = out_data.SBSplit()[m_sb_yp][m_sb_xp];
+ step = 4 >> (split_depth);
+ max = (1 << split_depth);
//now do all the block mvs in the mb
- for(int j = 0; j < max; ++j)
- {
- for(int i = 0; i < max; ++i)
+ for (int j = 0; j < max; ++j)
+ {
+ for (int i = 0; i < max; ++i)
{
- xstart = m_b_xp = m_sb_tlb_x + i * step;
- ystart = m_b_yp = m_sb_tlb_y + j * step;
-
+ xstart = m_b_xp = m_sb_tlb_x + i * step;
+ ystart = m_b_yp = m_sb_tlb_y + j * step;
+
if(out_data.Mode()[m_b_yp][m_b_xp] == INTRA)
{
- DecodeVal(out_data);
+ DecodeVal( out_data );
}
-
- // propagate throughout SB
- for(m_b_yp = ystart; m_b_yp < ystart + step; m_b_yp++)
+
+ // propagate throughout SB
+ for (m_b_yp = ystart; m_b_yp < ystart+step; m_b_yp++)
{
- for(m_b_xp = xstart; m_b_xp < xstart + step; m_b_xp++)
- {
- out_data.DC(m_csort)[m_b_yp][m_b_xp] = out_data.DC(m_csort)[ystart][xstart];
+ for (m_b_xp = xstart; m_b_xp < xstart+step; m_b_xp++)
+ {
+ out_data.DC( m_csort )[m_b_yp][m_b_xp] = out_data.DC( m_csort )[ystart][xstart];
}//m_b_xp
}//m_b_yp
- }//i
+ }//i
}//j
}//m_sb_xp
}//m_sb_yp
-}
+}
//protected functions//
///////////////////////
@@ -586,56 +586,56 @@ void DCCodec::ResetAll()
//prediction functions
ValueType DCCodec::Prediction(const TwoDArray < ValueType > & dcdata,
- const TwoDArray < PredMode > & preddata) const
+ const TwoDArray < PredMode > & preddata) const
{
- std::vector < int > nbrs;
+ std::vector < int > nbrs;
PredMode pmode;
- ValueType result = 0;
-
- if(m_b_xp > 0 && m_b_yp > 0)
+ ValueType result = 0;
+
+ if (m_b_xp > 0 && m_b_yp > 0)
{
- pmode = preddata[m_b_yp-1][m_b_xp];
- if(pmode == INTRA)
- nbrs.push_back((int) dcdata[m_b_yp-1][m_b_xp]);
-
- pmode = preddata[m_b_yp-1][m_b_xp-1];
- if(pmode == INTRA)
- nbrs.push_back((int)dcdata[m_b_yp-1][m_b_xp-1]);
-
- pmode = preddata[m_b_yp][m_b_xp-1];
- if(pmode == INTRA)
- nbrs.push_back((int) dcdata[m_b_yp][m_b_xp-1]);
-
- if(nbrs.size() > 0)
- result = ValueType(GetSMean(nbrs));
+ pmode = preddata[m_b_yp-1][m_b_xp];
+ if (pmode == INTRA)
+ nbrs.push_back( (int) dcdata[m_b_yp-1][m_b_xp] );
+
+ pmode = preddata[m_b_yp-1][m_b_xp-1];
+ if (pmode == INTRA)
+ nbrs.push_back((int)dcdata[m_b_yp-1][m_b_xp-1] );
+
+ pmode = preddata[m_b_yp][m_b_xp-1];
+ if (pmode == INTRA)
+ nbrs.push_back( (int) dcdata[m_b_yp][m_b_xp-1] );
+
+ if (nbrs.size() > 0)
+ result = ValueType(GetSMean(nbrs));
}
- else if(m_b_xp > 0 && m_b_yp == 0)
+ else if (m_b_xp > 0 && m_b_yp == 0)
{
- pmode = preddata[0][m_b_xp-1];
- if(pmode == INTRA)
- result = dcdata[0][m_b_xp-1];
+ pmode = preddata[0][m_b_xp-1];
+ if (pmode == INTRA)
+ result = dcdata[0][m_b_xp-1];
}
- else if(m_b_xp == 0 && m_b_yp > 0)
+ else if (m_b_xp == 0 && m_b_yp > 0)
{
- pmode = preddata[m_b_yp-1][0];
- if(pmode == INTRA)
- result = dcdata[m_b_yp-1][0];
+ pmode = preddata[m_b_yp-1][0];
+ if (pmode == INTRA)
+ result = dcdata[m_b_yp-1][0];
}
return result;
}
void DCCodec::CodeVal(const MvData& in_data)
-{
- const int val = in_data.DC(m_csort)[m_b_yp][m_b_xp] -
- Prediction(in_data.DC(m_csort) , in_data.Mode());
+{
+ const int val = in_data.DC( m_csort )[m_b_yp][m_b_xp] -
+ Prediction( in_data.DC(m_csort) , in_data.Mode() );
EncodeSInt(val, DC_FBIN1_CTX, DC_FBIN2plus_CTX);
}
//decoding functions//
//////////////////////
-void DCCodec::DecodeVal(MvData& out_data)
+void DCCodec::DecodeVal( MvData& out_data )
{
- out_data.DC(m_csort)[m_b_yp][m_b_xp] = DecodeSInt(DC_FBIN1_CTX, DC_FBIN2plus_CTX) +
- Prediction(out_data.DC(m_csort), out_data.Mode());
+ out_data.DC( m_csort )[m_b_yp][m_b_xp] = DecodeSInt(DC_FBIN1_CTX, DC_FBIN2plus_CTX) +
+ Prediction(out_data.DC( m_csort ), out_data.Mode());
}
diff --git a/src/filters/parser/DiracSplitter/libdirac/libdirac_common/mv_codec.h b/src/filters/parser/DiracSplitter/libdirac/libdirac_common/mv_codec.h
index 9e3ce1d47..ed76ac92a 100644
--- a/src/filters/parser/DiracSplitter/libdirac/libdirac_common/mv_codec.h
+++ b/src/filters/parser/DiracSplitter/libdirac/libdirac_common/mv_codec.h
@@ -54,246 +54,246 @@
namespace dirac
{
-//! Codes and decodes the split mode
-/*!
- Derived from the ArithCodec class, this codes and decodes the split mode
- */
-class SplitModeCodec: public ArithCodec<MvData>
-{
-public:
- //! Constructor
+ //! Codes and decodes the split mode
/*!
- Creates a MvDataCodec object to encode MV data, based on parameters
- \param p_byteio Input/output for the encoded bits
- \param number_of_contexts the number of contexts used
- */
- SplitModeCodec(ByteIO* p_byteio, size_t number_of_contexts);
-
-
+ Derived from the ArithCodec class, this codes and decodes the split mode
+ */
+ class SplitModeCodec: public ArithCodec<MvData>
+ {
+ public:
+ //! Constructor
+ /*!
+ Creates a MvDataCodec object to encode MV data, based on parameters
+ \param p_byteio Input/output for the encoded bits
+ \param number_of_contexts the number of contexts used
+ */
+ SplitModeCodec(ByteIO* p_byteio, size_t number_of_contexts);
- //! Initialises the contexts
- void InitContexts();
+
-private:
+ //! Initialises the contexts
+ void InitContexts();
+
+ private:
- // Position of current SB
- int m_sb_xp, m_sb_yp;
+ // Position of current SB
+ int m_sb_xp, m_sb_yp;
-private:
+ private:
- // functions
- //! Private, bodyless copy constructor: class should not be copied
- SplitModeCodec(const SplitModeCodec& cpy);
- //! Private, bodyless copy operator=: class should not be assigned
- SplitModeCodec& operator=(const SplitModeCodec& rhs);
+ // functions
+ //! Private, bodyless copy constructor: class should not be copied
+ SplitModeCodec(const SplitModeCodec& cpy);
+ //! Private, bodyless copy operator=: class should not be assigned
+ SplitModeCodec& operator=(const SplitModeCodec& rhs);
- // coding functions
- // Code the SB splitting mode
- void CodeVal(const MvData& in_data);
+ // coding functions
+ // Code the SB splitting mode
+ void CodeVal(const MvData& in_data);
- // decoding functions
- // Decode the SB splitting mode
- void DecodeVal(MvData& out_data);
+ // decoding functions
+ // Decode the SB splitting mode
+ void DecodeVal( MvData& out_data);
- void DoWorkCode(MvData& in_data);
- void DoWorkDecode(MvData& out_data);
+ void DoWorkCode( MvData& in_data );
+ void DoWorkDecode(MvData& out_data);
- // Context stuff
- void ResetAll();
+ // Context stuff
+ void ResetAll();
- //prediction stuff
- unsigned int Prediction(const TwoDArray<int>& mbdata) const;
+ //prediction stuff
+ unsigned int Prediction(const TwoDArray<int>& mbdata) const;
-};
+ };
/******************************************************************************/
-//! Codes and decodes the prediction modes
-/*!
- Derived from the ArithCodec class, this codes and decodes the prediction mode.
- */
-class PredModeCodec: public ArithCodec<MvData>
-{
-public:
- //! Constructor
+ //! Codes and decodes the prediction modes
/*!
- Creates a MvDataCodec object to encode MV data, based on parameters
- \param p_byteio Input/output for the encoded bits
- \param number_of_contexts the number of contexts used
- \param num_refs Number of references
- */
- PredModeCodec(ByteIO* p_byteio, size_t number_of_contexts, const int num_refs);
-
- //! Initialises the contexts
- void InitContexts();
-
-private:
-
- // Position of current block
- int m_b_xp, m_b_yp;
- // Position of current SB
- int m_sb_xp, m_sb_yp;
- // Position of top-left block of current SB
- int m_sb_tlb_x, m_sb_tlb_y;
- // Number of reference pictures
- int m_num_refs;
-
-private:
-
- // functions
- //! Private, bodyless copy constructor: class should not be copied
- PredModeCodec(const PredModeCodec& cpy);
- //! Private, bodyless copy operator=: class should not be assigned
- PredModeCodec& operator=(const PredModeCodec& rhs);
-
- // coding functions
- // Code the block prediction mode
- void CodeVal(const MvData& in_data);
-
- // decoding functions
- // Decode the block prediction mode
- void DecodeVal(MvData& out_data);
-
- void DoWorkCode(MvData& in_data);
- void DoWorkDecode(MvData& out_data);
-
- // Context stuff
- void ResetAll();
-
- //prediction stuff
- unsigned int Prediction(const TwoDArray<PredMode>& preddata) const;
-
-};
+ Derived from the ArithCodec class, this codes and decodes the prediction mode.
+ */
+ class PredModeCodec: public ArithCodec<MvData>
+ {
+ public:
+ //! Constructor
+ /*!
+ Creates a MvDataCodec object to encode MV data, based on parameters
+ \param p_byteio Input/output for the encoded bits
+ \param number_of_contexts the number of contexts used
+ \param num_refs Number of references
+ */
+ PredModeCodec(ByteIO* p_byteio, size_t number_of_contexts, const int num_refs);
+
+ //! Initialises the contexts
+ void InitContexts();
+
+ private:
+
+ // Position of current block
+ int m_b_xp, m_b_yp;
+ // Position of current SB
+ int m_sb_xp, m_sb_yp;
+ // Position of top-left block of current SB
+ int m_sb_tlb_x, m_sb_tlb_y;
+ // Number of reference pictures
+ int m_num_refs;
+
+ private:
+
+ // functions
+ //! Private, bodyless copy constructor: class should not be copied
+ PredModeCodec(const PredModeCodec& cpy);
+ //! Private, bodyless copy operator=: class should not be assigned
+ PredModeCodec& operator=(const PredModeCodec& rhs);
+
+ // coding functions
+ // Code the block prediction mode
+ void CodeVal(const MvData& in_data);
+
+ // decoding functions
+ // Decode the block prediction mode
+ void DecodeVal(MvData& out_data);
+
+ void DoWorkCode( MvData& in_data );
+ void DoWorkDecode(MvData& out_data);
+
+ // Context stuff
+ void ResetAll();
+
+ //prediction stuff
+ unsigned int Prediction(const TwoDArray<PredMode>& preddata) const;
+
+ };
/******************************************************************************/
-//! Codes and decodes an array of motion vectors
-/*!
- Derived from the ArithCodec class, this codes and decodes a motion vector
- element (vertical or horizontal)
- */
-class VectorElementCodec: public ArithCodec<MvData>
-{
-public:
- //! Constructor
+ //! Codes and decodes an array of motion vectors
/*!
- Creates a MvDataCodec object to encode MV data, based on parameters
- \param p_byteio Input/output for the encoded bits
- \param ref_id The identity of the reference (1 or 2)
- \param horvert The identity of the vector element (horizontal or vertical)
- \param number_of_contexts the number of contexts used
- */
- VectorElementCodec(ByteIO* p_byteio, int ref_id, MvElement horvert,
- size_t number_of_contexts);
-
-
- //! Initialises the contexts
- void InitContexts();
-
-private:
-
- // Position of current block
- int m_b_xp, m_b_yp;
-
- // Position of current SB
- int m_sb_xp, m_sb_yp;
-
- // Position of top-left block of current SB
- int m_sb_tlb_x, m_sb_tlb_y;
-
- // The identity of the reference (1 or 2)
- const int m_ref;
-
- // Whether it's the vertical or horizontal MV element
- const MvElement m_hv;
-
-private:
-
- // functions
- //! Private, bodyless copy constructor: class should not be copied
- VectorElementCodec(const VectorElementCodec& cpy);
- //! Private, bodyless copy operator=: class should not be assigned
- VectorElementCodec& operator=(const VectorElementCodec& rhs);
-
- // coding functions
- // Code the motion vector element
- void CodeVal(const MvData& in_data);
-
- // decoding functions
- // Decode the motion vector element
- void DecodeVal(MvData& out_data);
-
- void DoWorkCode(MvData& in_data);
- void DoWorkDecode(MvData& out_data);
-
- // Context stuff
- void ResetAll();
-
- //prediction stuff
- int Prediction(const MvArray& mvarray,
- const TwoDArray<PredMode>& preddata) const;
-
-};
+ Derived from the ArithCodec class, this codes and decodes a motion vector
+ element (vertical or horizontal)
+ */
+ class VectorElementCodec: public ArithCodec<MvData>
+ {
+ public:
+ //! Constructor
+ /*!
+ Creates a MvDataCodec object to encode MV data, based on parameters
+ \param p_byteio Input/output for the encoded bits
+ \param ref_id The identity of the reference (1 or 2)
+ \param horvert The identity of the vector element (horizontal or vertical)
+ \param number_of_contexts the number of contexts used
+ */
+ VectorElementCodec(ByteIO* p_byteio, int ref_id, MvElement horvert,
+ size_t number_of_contexts);
+
+
+ //! Initialises the contexts
+ void InitContexts();
+
+ private:
+
+ // Position of current block
+ int m_b_xp, m_b_yp;
+
+ // Position of current SB
+ int m_sb_xp, m_sb_yp;
+
+ // Position of top-left block of current SB
+ int m_sb_tlb_x, m_sb_tlb_y;
+
+ // The identity of the reference (1 or 2)
+ const int m_ref;
+
+ // Whether it's the vertical or horizontal MV element
+ const MvElement m_hv;
+
+ private:
+
+ // functions
+ //! Private, bodyless copy constructor: class should not be copied
+ VectorElementCodec(const VectorElementCodec& cpy);
+ //! Private, bodyless copy operator=: class should not be assigned
+ VectorElementCodec& operator=(const VectorElementCodec& rhs);
+
+ // coding functions
+ // Code the motion vector element
+ void CodeVal(const MvData& in_data);
+
+ // decoding functions
+ // Decode the motion vector element
+ void DecodeVal( MvData& out_data);
+
+ void DoWorkCode( MvData& in_data );
+ void DoWorkDecode(MvData& out_data);
+
+ // Context stuff
+ void ResetAll();
+
+ //prediction stuff
+ int Prediction( const MvArray& mvarray,
+ const TwoDArray<PredMode>& preddata) const;
+
+ };
/******************************************************************************/
-//! Codes and decodes a set of DC values
-/*!
- Derived from the ArithCodec class, this codes and decodes all the DC
- values for a component
- */
-class DCCodec: public ArithCodec<MvData>
-{
-public:
- //! Constructor
+ //! Codes and decodes a set of DC values
/*!
- Creates a MvDataCodec object to encode MV data, based on parameters
- \param p_byteio Input/output for the encoded bits
- \param csort The identity of the component (Y, U or V)
- \param number_of_contexts the number of contexts used
- */
- DCCodec(ByteIO* p_byteio, const CompSort csort, size_t number_of_contexts);
-
- //! Initialises the contexts
- void InitContexts();
-
-private:
-
- // The component being coded
- const CompSort m_csort;
- // Position of current block
- int m_b_xp, m_b_yp;
- // Position of current SB
- int m_sb_xp, m_sb_yp;
- // Position of top-left block of current SB
- int m_sb_tlb_x, m_sb_tlb_y;
-
-private:
-
- // functions
- //! Private, bodyless copy constructor: class should not be copied
- DCCodec(const DCCodec& cpy);
- //! Private, bodyless copy operator=: class should not be assigned
- DCCodec& operator=(const DCCodec& rhs);
-
- // coding functions
- // Code the dc value of intra blocks
- void CodeVal(const MvData& in_data);
-
- // decoding functions
- // Decode the dc value of intra blocks
- void DecodeVal(MvData& out_data);
-
- void DoWorkCode(MvData& in_data);
- void DoWorkDecode(MvData& out_data);
-
- // Context stuff
- void ResetAll();
-
- //prediction stuff
- ValueType Prediction(const TwoDArray<ValueType>& dcdata,
- const TwoDArray<PredMode>& preddata) const;
-};
-
+ Derived from the ArithCodec class, this codes and decodes all the DC
+ values for a component
+ */
+ class DCCodec: public ArithCodec<MvData>
+ {
+ public:
+ //! Constructor
+ /*!
+ Creates a MvDataCodec object to encode MV data, based on parameters
+ \param p_byteio Input/output for the encoded bits
+ \param csort The identity of the component (Y, U or V)
+ \param number_of_contexts the number of contexts used
+ */
+ DCCodec(ByteIO* p_byteio, const CompSort csort, size_t number_of_contexts);
+
+ //! Initialises the contexts
+ void InitContexts();
+
+ private:
+
+ // The component being coded
+ const CompSort m_csort;
+ // Position of current block
+ int m_b_xp, m_b_yp;
+ // Position of current SB
+ int m_sb_xp, m_sb_yp;
+ // Position of top-left block of current SB
+ int m_sb_tlb_x, m_sb_tlb_y;
+
+ private:
+
+ // functions
+ //! Private, bodyless copy constructor: class should not be copied
+ DCCodec(const DCCodec& cpy);
+ //! Private, bodyless copy operator=: class should not be assigned
+ DCCodec& operator=(const DCCodec& rhs);
+
+ // coding functions
+ // Code the dc value of intra blocks
+ void CodeVal(const MvData& in_data);
+
+ // decoding functions
+ // Decode the dc value of intra blocks
+ void DecodeVal( MvData& out_data);
+
+ void DoWorkCode( MvData& in_data );
+ void DoWorkDecode(MvData& out_data);
+
+ // Context stuff
+ void ResetAll();
+
+ //prediction stuff
+ ValueType Prediction( const TwoDArray<ValueType>& dcdata,
+ const TwoDArray<PredMode>& preddata) const;
+ };
+
}// end namepace dirac
diff --git a/src/filters/parser/DiracSplitter/libdirac/libdirac_common/pic_io.cpp b/src/filters/parser/DiracSplitter/libdirac/libdirac_common/pic_io.cpp
index fff71999f..b6e56ebc3 100644
--- a/src/filters/parser/DiracSplitter/libdirac/libdirac_common/pic_io.cpp
+++ b/src/filters/parser/DiracSplitter/libdirac/libdirac_common/pic_io.cpp
@@ -48,7 +48,7 @@ StreamPicOutput::~StreamPicOutput()
{
}
-StreamPicOutput::StreamPicOutput(std::ostream *op_ptr, const SourceParams& sp) :
+StreamPicOutput::StreamPicOutput (std::ostream *op_ptr, const SourceParams& sp) :
m_sparams(sp),
m_op_pic_ptr(op_ptr)
{
@@ -56,37 +56,37 @@ StreamPicOutput::StreamPicOutput(std::ostream *op_ptr, const SourceParams& sp) :
StreamFrameOutput::StreamFrameOutput(std::ostream *op_str,
const SourceParams& sp) :
- StreamPicOutput(op_str, sp)
+ StreamPicOutput (op_str, sp)
{}
StreamFrameOutput::~StreamFrameOutput()
{
}
-bool StreamFrameOutput::WriteToNextFrame(const Picture& myframe)
+bool StreamFrameOutput::WriteToNextFrame( const Picture& myframe )
{
bool ret_val;
- ret_val = WriteFrameComponent(myframe.Data(Y_COMP), Y_COMP);
- ret_val &= WriteFrameComponent(myframe.Data(U_COMP), U_COMP);
- ret_val &= WriteFrameComponent(myframe.Data(V_COMP), V_COMP);
+ ret_val=WriteFrameComponent(myframe.Data(Y_COMP), Y_COMP );
+ ret_val&=WriteFrameComponent( myframe.Data(U_COMP), U_COMP );
+ ret_val&=WriteFrameComponent( myframe.Data(V_COMP), V_COMP );
return ret_val;
}
-bool StreamFrameOutput::WriteFrameComponent(const PicArray& pic_data , const CompSort& cs)
+bool StreamFrameOutput::WriteFrameComponent( const PicArray& pic_data , const CompSort& cs)
{
- if(!m_op_pic_ptr)
+ if (!m_op_pic_ptr)
{
- std::cerr << std::endl << "Can't open picture data file for writing";
+ std::cerr<<std::endl<<"Can't open picture data file for writing";
return false;
}
//initially set up for 10-bit data input, rounded to 8 bits on file output
//This will throw out any padding to the right and bottom of a frame
- int xl, yl;
- if(cs == Y_COMP)
+ int xl,yl;
+ if (cs == Y_COMP)
{
xl = m_sparams.Xl();
yl = m_sparams.Yl();
@@ -97,18 +97,18 @@ bool StreamFrameOutput::WriteFrameComponent(const PicArray& pic_data , const Com
yl = m_sparams.ChromaHeight();
}
- unsigned char* tempc = new unsigned char[xl];
+ unsigned char* tempc=new unsigned char[xl];
- if(m_op_pic_ptr)
+ if (m_op_pic_ptr)
{
- for(int j = 0 ; j < yl ; ++j)
+ for (int j=0 ; j<yl ;++j)
{
- for(int i = 0 ; i < xl ; ++i)
+ for (int i=0 ; i<xl ; ++i)
{
- tempc[i] = (unsigned char)(pic_data[j][i] + 128);
+ tempc[i] = (unsigned char) ( pic_data[j][i] + 128 );
}//I
- m_op_pic_ptr->write((char*) tempc, xl);
+ m_op_pic_ptr->write((char*) tempc,xl);
}//J
}
@@ -121,43 +121,43 @@ bool StreamFrameOutput::WriteFrameComponent(const PicArray& pic_data , const Com
}
StreamFieldOutput::StreamFieldOutput(std::ostream *op_str,
- const SourceParams& sp) :
+ const SourceParams& sp) :
StreamPicOutput(op_str, sp),
m_frame_store(NULL)
{
int frame_size = (m_sparams.Xl() * m_sparams.Yl()) +
- 2 * (m_sparams.ChromaWidth() * m_sparams.ChromaHeight());
+ 2 * (m_sparams.ChromaWidth() * m_sparams.ChromaHeight());
m_frame_store = new unsigned char[frame_size];
}
StreamFieldOutput::~StreamFieldOutput()
{
- if(m_frame_store)
+ if (m_frame_store)
delete [] m_frame_store;
}
-bool StreamFieldOutput::WriteToNextFrame(const Picture& myfield)
+bool StreamFieldOutput::WriteToNextFrame( const Picture& myfield )
{
bool ret_val;
- ret_val = WriteFieldComponent(myfield.Data(Y_COMP) , myfield.GetPparams().PictureNum(), Y_COMP);
- ret_val &= WriteFieldComponent(myfield.Data(U_COMP) , myfield.GetPparams().PictureNum(), U_COMP);
- ret_val &= WriteFieldComponent(myfield.Data(V_COMP) , myfield.GetPparams().PictureNum(), V_COMP);
+ ret_val=WriteFieldComponent(myfield.Data(Y_COMP) , myfield.GetPparams().PictureNum(), Y_COMP );
+ ret_val&=WriteFieldComponent(myfield.Data(U_COMP) , myfield.GetPparams().PictureNum(), U_COMP );
+ ret_val&=WriteFieldComponent(myfield.Data(V_COMP) , myfield.GetPparams().PictureNum(), V_COMP );
return ret_val;
}
-bool StreamFieldOutput::WriteFieldComponent(const PicArray& pic_data , int field_num, const CompSort& cs)
+bool StreamFieldOutput::WriteFieldComponent( const PicArray& pic_data , int field_num, const CompSort& cs)
{
- if(!m_op_pic_ptr)
+ if (!m_op_pic_ptr)
{
- std::cerr << std::endl << "Can't open picture data file for writing";
+ std::cerr<<std::endl<<"Can't open picture data file for writing";
return false;
}
unsigned char *comp;
- int xl, yl;
- if(cs == Y_COMP)
+ int xl,yl;
+ if (cs == Y_COMP)
{
xl = m_sparams.Xl();
yl = m_sparams.Yl();
@@ -167,13 +167,13 @@ bool StreamFieldOutput::WriteFieldComponent(const PicArray& pic_data , int field
{
xl = m_sparams.ChromaWidth();
yl = m_sparams.ChromaHeight();
- if(cs == U_COMP)
+ if (cs == U_COMP)
{
comp = m_frame_store + (m_sparams.Xl() * m_sparams.Yl());
}
else
{
- comp = m_frame_store + (m_sparams.Xl() * m_sparams.Yl()) + (xl * yl);
+ comp = m_frame_store + (m_sparams.Xl() * m_sparams.Yl()) + (xl*yl);
}
}
@@ -184,19 +184,19 @@ bool StreamFieldOutput::WriteFieldComponent(const PicArray& pic_data , int field
// Seek offset after writing field to file
int end = 0;
- bool top_field = m_sparams.TopFieldFirst() ? (!(field_num % 2)) :
- (field_num % 2);
+ bool top_field = m_sparams.TopFieldFirst() ? (!(field_num%2)) :
+ (field_num%2);
bool write_to_file = (m_sparams.TopFieldFirst() && !top_field) ||
(!m_sparams.TopFieldFirst() && top_field);
- if(m_sparams.TopFieldFirst())
+ if (m_sparams.TopFieldFirst())
{
- if(top_field)
+ if (top_field)
{
start = 0;
skip = 2 * xl * sizeof(char);
- end = -(xl * yl);
+ end = -(xl*yl);
}
else
{
@@ -207,11 +207,11 @@ bool StreamFieldOutput::WriteFieldComponent(const PicArray& pic_data , int field
}
else
{
- if(!top_field) // i.e. bottom field
+ if (!top_field) // i.e. bottom field
{
start = xl;
skip = 2 * xl * sizeof(char);
- end = -(xl * yl);
+ end = -(xl*yl);
}
else // top field
{
@@ -223,21 +223,21 @@ bool StreamFieldOutput::WriteFieldComponent(const PicArray& pic_data , int field
unsigned char *tempc = comp + start;
- int field_yl = yl >> 1;
+ int field_yl = yl>>1;
int field_xl = xl;
- for(int j = 0 ; j < field_yl ; ++j)
+ for (int j=0 ; j<field_yl ;++j)
{
- for(int i = 0 ; i < field_xl ; ++i)
+ for (int i=0 ; i<field_xl ; ++i)
{
- tempc[i] = (unsigned char)(pic_data[j][i] + 128);
+ tempc[i] = (unsigned char) (pic_data[j][i]+128);
}//I
tempc += skip;
}//J
tempc += end;
- if(write_to_file)
+ if (write_to_file)
{
- m_op_pic_ptr->write((char*) comp, xl * yl);
+ m_op_pic_ptr->write((char*) comp,xl*yl);
m_op_pic_ptr->flush();
return true;
}
@@ -251,7 +251,7 @@ MemoryStreamOutput::MemoryStreamOutput(SourceParams &sp, bool interlace)
m_op_pic_ptr =
new std::ostream(&m_membuf);
- if(interlace)
+ if (interlace)
m_op_pic_str = new StreamFieldOutput(m_op_pic_ptr, sp);
else
m_op_pic_str = new StreamFrameOutput(m_op_pic_ptr, sp);
@@ -263,27 +263,27 @@ MemoryStreamOutput::~MemoryStreamOutput()
delete m_op_pic_ptr;
}
-void MemoryStreamOutput::SetMembufReference(unsigned char *buf, int buf_size)
+void MemoryStreamOutput::SetMembufReference (unsigned char *buf, int buf_size)
{
m_membuf.SetMembufReference(buf, buf_size);
}
FileStreamOutput::FileStreamOutput(const char* output_name,
- const SourceParams& sp, bool interlace)
+ const SourceParams& sp, bool interlace)
{
//picture output
m_op_pic_ptr =
- new std::ofstream(output_name, std::ios::out | std::ios::binary);
+ new std::ofstream(output_name,std::ios::out | std::ios::binary);
- if(!(*m_op_pic_ptr))
+ if (!(*m_op_pic_ptr))
{
std::cerr << std::endl <<
- "Can't open output picture data file for output: " <<
- output_name << std::endl;
+ "Can't open output picture data file for output: " <<
+ output_name<<std::endl;
return;
}
- if(interlace)
+ if (interlace)
m_op_pic_str = new StreamFieldOutput(m_op_pic_ptr, sp);
else
m_op_pic_str = new StreamFrameOutput(m_op_pic_ptr, sp);
@@ -291,7 +291,7 @@ FileStreamOutput::FileStreamOutput(const char* output_name,
FileStreamOutput::~FileStreamOutput()
{
- if(m_op_pic_ptr && *m_op_pic_ptr)
+ if (m_op_pic_ptr && *m_op_pic_ptr)
{
static_cast<std::ofstream *>(m_op_pic_ptr)->close();
delete m_op_pic_ptr;
@@ -303,14 +303,14 @@ FileStreamOutput::~FileStreamOutput()
/**************************************Input***********************************/
-StreamPicInput::StreamPicInput(std::istream *ip_pic_ptr,
- const SourceParams &sparams) :
+StreamPicInput::StreamPicInput (std::istream *ip_pic_ptr,
+ const SourceParams &sparams) :
m_sparams(sparams),
m_ip_pic_ptr(ip_pic_ptr)
{}
-StreamPicInput::~StreamPicInput()
+StreamPicInput::~StreamPicInput ()
{}
bool StreamPicInput::End() const
@@ -318,29 +318,29 @@ bool StreamPicInput::End() const
return m_ip_pic_ptr->eof();
}
-StreamFrameInput::StreamFrameInput(std::istream *ip_pic_ptr,
- const SourceParams &sparams) :
+StreamFrameInput::StreamFrameInput (std::istream *ip_pic_ptr,
+ const SourceParams &sparams) :
StreamPicInput(ip_pic_ptr, sparams)
{}
-StreamFrameInput::~StreamFrameInput()
+StreamFrameInput::~StreamFrameInput ()
{}
void StreamFrameInput::Skip(const int num)
{
- const int num_pels = m_sparams.Xl() * m_sparams.Yl();
+ const int num_pels = m_sparams.Xl()*m_sparams.Yl();
int num_bytes;
const ChromaFormat cf = m_sparams.CFormat();
- if(cf == format420)
- num_bytes = (num_pels * 3) / 2;
- else if(cf == format422)
- num_bytes = num_pels * 2;
+ if ( cf == format420 )
+ num_bytes = (num_pels*3)/2;
+ else if ( cf == format422 )
+ num_bytes = num_pels*2;
else
- num_bytes = num_pels * 3;
+ num_bytes = num_pels*3;
- m_ip_pic_ptr->seekg(num * num_bytes , std::ios::cur);
+ m_ip_pic_ptr->seekg( num*num_bytes , std::ios::cur );
}
bool StreamFrameInput::ReadNextPicture(Picture& myframe)
@@ -350,9 +350,9 @@ bool StreamFrameInput::ReadNextPicture(Picture& myframe)
bool ret_val;
- ret_val = ReadFrameComponent(myframe.Data(Y_COMP) , Y_COMP);
- ret_val &= ReadFrameComponent(myframe.Data(U_COMP) , U_COMP);
- ret_val &= ReadFrameComponent(myframe.Data(V_COMP) , V_COMP);
+ ret_val=ReadFrameComponent( myframe.Data(Y_COMP) , Y_COMP);
+ ret_val&=ReadFrameComponent(myframe.Data(U_COMP) , U_COMP);
+ ret_val&=ReadFrameComponent(myframe.Data(V_COMP) , V_COMP);
return ret_val;
}
@@ -360,29 +360,26 @@ bool StreamFrameInput::ReadNextPicture(Picture& myframe)
bool StreamFrameInput::ReadFrameComponent(PicArray& pic_data, const CompSort& cs)
{
- if(! *m_ip_pic_ptr)
+ if (! *m_ip_pic_ptr)
return false;
- int xl, yl;
- if(cs == Y_COMP)
- {
+ int xl,yl;
+ if (cs == Y_COMP){
xl = m_sparams.Xl();
yl = m_sparams.Yl();
}
- else
- {
- if(m_sparams.CFormat() == format420)
+ else{
+ if (m_sparams.CFormat()==format420)
{
- xl = m_sparams.Xl() / 2;
- yl = m_sparams.Yl() / 2;
+ xl = m_sparams.Xl()/2;
+ yl = m_sparams.Yl()/2;
}
- else if(m_sparams.CFormat() == format422)
+ else if (m_sparams.CFormat() == format422)
{
- xl = m_sparams.Xl() / 2;
+ xl = m_sparams.Xl()/2;
yl = m_sparams.Yl();
}
- else
- {
+ else{
xl = m_sparams.Xl();
yl = m_sparams.Yl();
}
@@ -390,23 +387,22 @@ bool StreamFrameInput::ReadFrameComponent(PicArray& pic_data, const CompSort& cs
unsigned char * temp = new unsigned char[xl];//array big enough for one line
- for(int j = 0 ; j < yl ; ++j)
+ for (int j=0 ; j<yl ; ++j)
{
m_ip_pic_ptr->read((char*) temp, xl);
- for(int i = 0 ; i < xl ; ++i)
+ for (int i=0 ; i<xl ; ++i)
{
pic_data[j][i] = (ValueType) temp[i];
}//I
- for(int i = 0 ; i < xl ; ++i)
+ for (int i=0 ; i<xl ; ++i)
{
pic_data[j][i] -= 128;
}//I
//pad the columns on the rhs using the edge value
- for(int i = xl ; i < pic_data.LengthX() ; ++i)
- {
+ for (int i=xl ; i<pic_data.LengthX() ; ++i ){
pic_data[j][i] = pic_data[j][xl-1];
}//I
@@ -415,9 +411,9 @@ bool StreamFrameInput::ReadFrameComponent(PicArray& pic_data, const CompSort& cs
delete [] temp;
//now do the padded lines, using the last true line
- for(int j = yl ; j < pic_data.LengthY() ; ++j)
+ for (int j=yl ; j<pic_data.LengthY() ; ++j )
{
- for(int i = 0 ; i < pic_data.LengthX() ; ++i)
+ for (int i=0 ; i<pic_data.LengthX() ; ++i )
{
pic_data[j][i] = pic_data[yl-1][i];
}//I
@@ -426,17 +422,17 @@ bool StreamFrameInput::ReadFrameComponent(PicArray& pic_data, const CompSort& cs
return true;
}
-StreamFieldInput::StreamFieldInput(std::istream *ip_pic_ptr,
- const SourceParams &sparams) :
+StreamFieldInput::StreamFieldInput (std::istream *ip_pic_ptr,
+ const SourceParams &sparams) :
StreamPicInput(ip_pic_ptr, sparams)
{}
-StreamFieldInput::~StreamFieldInput()
+StreamFieldInput::~StreamFieldInput ()
{}
void StreamFieldInput::Skip(const int num)
{
- REPORTM(num && false, "StreamFieldInput::Skip - Reached unimplemented function");
+ REPORTM (num && false, "StreamFieldInput::Skip - Reached unimplemented function");
}
bool StreamFieldInput::ReadNextPicture(Picture& mypic)
@@ -448,18 +444,18 @@ bool StreamFieldInput::ReadNextPicture(Picture& mypic)
bool ret_val;
- bool is_field1 = ((mypic.GetPparams().PictureNum() % 2) == 0);
- ret_val = ReadFieldComponent(is_field1, mypic.Data(Y_COMP), Y_COMP);
- ret_val &= ReadFieldComponent(is_field1, mypic.Data(U_COMP), U_COMP);
- ret_val &= ReadFieldComponent(is_field1, mypic.Data(V_COMP), V_COMP);
+ bool is_field1 = ((mypic.GetPparams().PictureNum()%2) == 0);
+ ret_val=ReadFieldComponent( is_field1, mypic.Data(Y_COMP), Y_COMP);
+ ret_val&=ReadFieldComponent(is_field1, mypic.Data(U_COMP), U_COMP);
+ ret_val&=ReadFieldComponent(is_field1, mypic.Data(V_COMP), V_COMP);
- int picture_size = m_sparams.Xl() * m_sparams.Yl() +
- 2 * m_sparams.ChromaWidth() * m_sparams.ChromaHeight();
- if(is_field1)
+ int picture_size = m_sparams.Xl()*m_sparams.Yl() +
+ 2*m_sparams.ChromaWidth()*m_sparams.ChromaHeight();
+ if (is_field1)
{
//Seek back to the beginning of frame so that the next field
//from the frame can be read
- m_ip_pic_ptr->seekg(-picture_size, std::ios::cur);
+ m_ip_pic_ptr->seekg (-picture_size, std::ios::cur);
}
return ret_val;
@@ -472,42 +468,39 @@ bool StreamFieldInput::ReadNextFrame(Picture& field1, Picture& field2)
bool ret_val = false;
- ret_val = ReadFieldComponent(field1.Data(Y_COMP), field2.Data(Y_COMP), Y_COMP);
- ret_val &= ReadFieldComponent(field1.Data(U_COMP), field2.Data(U_COMP), U_COMP);
- ret_val &= ReadFieldComponent(field1.Data(V_COMP), field2.Data(V_COMP), V_COMP);
-
+ ret_val=ReadFieldComponent( field1.Data(Y_COMP), field2.Data(Y_COMP), Y_COMP);
+ ret_val&=ReadFieldComponent(field1.Data(U_COMP), field2.Data(U_COMP), U_COMP);
+ ret_val&=ReadFieldComponent(field1.Data(V_COMP), field2.Data(V_COMP), V_COMP);
+
return ret_val;
}
bool StreamFieldInput::ReadFieldComponent(PicArray& pic_data1,
- PicArray& pic_data2,
- const CompSort& cs)
+ PicArray& pic_data2,
+ const CompSort& cs)
{
- if(! *m_ip_pic_ptr)
+ if (! *m_ip_pic_ptr)
return false;
//initially set up for 8-bit file input expanded to 10 bits for array output
- int xl, yl;
- if(cs == Y_COMP)
- {
+ int xl,yl;
+ if (cs == Y_COMP){
xl = m_sparams.Xl();
yl = m_sparams.Yl();
}
- else
- {
- if(m_sparams.CFormat() == format420)
+ else{
+ if (m_sparams.CFormat()==format420)
{
- xl = m_sparams.Xl() / 2;
- yl = m_sparams.Yl() / 2;
+ xl = m_sparams.Xl()/2;
+ yl = m_sparams.Yl()/2;
}
- else if(m_sparams.CFormat() == format422)
+ else if (m_sparams.CFormat() == format422)
{
- xl = m_sparams.Xl() / 2;
+ xl = m_sparams.Xl()/2;
yl = m_sparams.Yl();
}
- else
- {
+ else{
xl = m_sparams.Xl();
yl = m_sparams.Yl();
}
@@ -516,32 +509,31 @@ bool StreamFieldInput::ReadFieldComponent(PicArray& pic_data1,
unsigned char * temp = new unsigned char[xl];//array big enough for one line
ValueType *pic;
- for(int j = 0 ; j < yl ; j++)
+ for (int j=0 ; j<yl ; j++)
{
m_ip_pic_ptr->read((char*) temp, xl);
- if(j % 2 == 0)
+ if (j % 2 == 0)
{
pic = m_sparams.TopFieldFirst() ?
- &pic_data1[j/2][0] : &pic_data2[j/2][0];
+ &pic_data1[j/2][0] : &pic_data2[j/2][0];
}
else
{
pic = m_sparams.TopFieldFirst() ?
- &pic_data2[j/2][0] : &pic_data1[j/2][0];
+ &pic_data2[j/2][0] : &pic_data1[j/2][0];
}
- for(int i = 0 ; i < xl ; ++i)
+ for (int i=0 ; i<xl ; ++i)
{
pic[i] = (ValueType) temp[i];
}//I
- for(int i = 0 ; i < xl ; ++i)
+ for (int i=0 ; i<xl ; ++i)
{
pic[i] -= 128;
}//I
//pad the columns on the rhs using the edge value
- for(int i = xl ; i < pic_data1.LengthX() ; ++i)
- {
+ for (int i=xl ; i<pic_data1.LengthX() ; ++i ){
pic[i] = pic[xl-1];
}//I
@@ -550,9 +542,9 @@ bool StreamFieldInput::ReadFieldComponent(PicArray& pic_data1,
delete [] temp;
//now do the padded lines, using the last true line
- for(int j = yl / 2 ; j < pic_data1.LengthY() ; ++j)
+ for (int j=yl/2 ; j<pic_data1.LengthY() ; ++j )
{
- for(int i = 0 ; i < pic_data1.LengthX() ; ++i)
+ for (int i=0 ; i<pic_data1.LengthX() ; ++i )
{
pic_data1[j][i] = pic_data1[yl/2-1][i];
pic_data2[j][i] = pic_data2[yl/2-1][i];
@@ -563,51 +555,48 @@ bool StreamFieldInput::ReadFieldComponent(PicArray& pic_data1,
}
bool StreamFieldInput::ReadFieldComponent(bool is_field1,
- PicArray& pic_data,
- const CompSort& cs)
+ PicArray& pic_data,
+ const CompSort& cs)
{
- if(! *m_ip_pic_ptr)
+ if (! *m_ip_pic_ptr)
return false;
//initially set up for 8-bit file input expanded to 10 bits for array output
- int xl, yl;
- if(cs == Y_COMP)
- {
+ int xl,yl;
+ if (cs == Y_COMP){
xl = m_sparams.Xl();
- yl = m_sparams.Yl() >> 1;
+ yl = m_sparams.Yl()>>1;
}
- else
- {
+ else{
xl = m_sparams.ChromaWidth();
- yl = m_sparams.ChromaHeight() >> 1;
+ yl = m_sparams.ChromaHeight()>>1;
}
unsigned char * pic = new unsigned char[2*xl];//array big enough for two lines - one for each field
int start = 0;
- if((is_field1 && !m_sparams.TopFieldFirst()) ||
- (!is_field1 && m_sparams.TopFieldFirst()))
+ if ((is_field1 && !m_sparams.TopFieldFirst()) ||
+ (!is_field1 && m_sparams.TopFieldFirst()))
{
start = xl;
}
- for(int j = 0 ; j < yl ; j++)
+ for (int j=0 ; j<yl ; j++)
{
- m_ip_pic_ptr->read((char*) pic, 2 * xl);
+ m_ip_pic_ptr->read((char*) pic, 2*xl);
// skip to the start of the field
unsigned char *field = pic + start;
- for(int i = 0 ; i < xl ; ++i)
+ for (int i=0 ; i<xl ; ++i)
{
pic_data[j][i] = (ValueType) field[i];
}//I
- for(int i = 0 ; i < xl ; ++i)
+ for (int i=0 ; i<xl ; ++i)
{
pic_data[j][i] -= 128;
}
//pad the columns on the rhs using the edge value
- for(int i = xl ; i < pic_data.LengthX() ; ++i)
- {
+ for (int i=xl ; i<pic_data.LengthX() ; ++i ){
pic_data[j][i] = pic_data[j][xl-1];
}//I
@@ -615,9 +604,9 @@ bool StreamFieldInput::ReadFieldComponent(bool is_field1,
delete [] pic;
//now do the padded lines, using the last true line
- for(int j = yl ; j < pic_data.LengthY() ; ++j)
+ for (int j=yl ; j<pic_data.LengthY() ; ++j )
{
- for(int i = 0 ; i < pic_data.LengthX() ; ++i)
+ for (int i=0 ; i<pic_data.LengthX() ; ++i )
{
pic_data[j][i] = pic_data[yl-1][i];
}//I
@@ -632,7 +621,7 @@ MemoryStreamInput::MemoryStreamInput(SourceParams& sparams, bool field_input)
m_ip_pic_ptr =
new std::istream(&m_membuf);
- if(field_input)
+ if (field_input)
m_inp_str = new StreamFieldInput(m_ip_pic_ptr, sparams);
else
m_inp_str = new StreamFrameInput(m_ip_pic_ptr, sparams);
@@ -644,7 +633,7 @@ MemoryStreamInput::~MemoryStreamInput()
delete m_inp_str;
}
-void MemoryStreamInput::SetMembufReference(unsigned char *buf, int buf_size)
+void MemoryStreamInput::SetMembufReference (unsigned char *buf, int buf_size)
{
m_membuf.SetMembufReference(buf, buf_size);
}
@@ -661,14 +650,14 @@ FileStreamInput::FileStreamInput(const char* input_name,
//picture input
m_ip_pic_ptr =
- new std::ifstream(input_name_yuv, std::ios::in | std::ios::binary);
+ new std::ifstream(input_name_yuv,std::ios::in | std::ios::binary);
- if(!(*m_ip_pic_ptr))
- std::cerr << std::endl <<
- "Can't open input picture data file: " <<
- input_name_yuv << std::endl;
+ if (!(*m_ip_pic_ptr))
+ std::cerr << std::endl<<
+ "Can't open input picture data file: " <<
+ input_name_yuv << std::endl;
- if(interlace)
+ if (interlace)
m_inp_str = new StreamFieldInput(m_ip_pic_ptr, sparams);
else
m_inp_str = new StreamFrameInput(m_ip_pic_ptr, sparams);
diff --git a/src/filters/parser/DiracSplitter/libdirac/libdirac_common/pic_io.h b/src/filters/parser/DiracSplitter/libdirac/libdirac_common/pic_io.h
index 02bb5f678..375b4c033 100644
--- a/src/filters/parser/DiracSplitter/libdirac/libdirac_common/pic_io.h
+++ b/src/filters/parser/DiracSplitter/libdirac/libdirac_common/pic_io.h
@@ -52,500 +52,476 @@
namespace dirac
{
-//////////////////////////////////////////
-//--------------------------------------//
-//- -//
-//-Uncompressed picture file IO wrapper-//
-//- -//
-//--------------------------------------//
-//////////////////////////////////////////
+ //////////////////////////////////////////
+ //--------------------------------------//
+ //- -//
+ //-Uncompressed picture file IO wrapper-//
+ //- -//
+ //--------------------------------------//
+ //////////////////////////////////////////
-// Stream classes for writing/reading frames of uncompressed/decoded data
-// to stream. Streams currently supported are Memory based streams and
-// File based streams. These classes need further restructuring.
-// Anu - 19-11-2004
+ // Stream classes for writing/reading frames of uncompressed/decoded data
+ // to stream. Streams currently supported are Memory based streams and
+ // File based streams. These classes need further restructuring.
+ // Anu - 19-11-2004
-// Subclass these to provide functionality for different file formats and
-// for streaming.
+ // Subclass these to provide functionality for different file formats and
+ // for streaming.
-//! Class for outputting pictures
+ //! Class for outputting pictures
-/*!
- Abstract base class for classes that output frames to stream
-*/
-class StreamPicOutput
-{
-public:
- //! Constructor
/*!
- Constructor, takes
- \param op_ptr the output stream object
- \param sp the source parameters
- */
- StreamPicOutput(std::ostream* op_ptr, const SourceParams& sp);
-
- //! virtual Destructor
- virtual ~StreamPicOutput();
-
- //! Write a picture to the next frame to be output
- virtual bool WriteToNextFrame(const Picture& myframe) = 0;
-
- //! Get the source parameters
- SourceParams& GetSourceParams()
+ Abstract base class for classes that output frames to stream
+ */
+ class StreamPicOutput
{
- return m_sparams;
- }
+ public:
+ //! Constructor
+ /*!
+ Constructor, takes
+ \param op_ptr the output stream object
+ \param sp the source parameters
+ */
+ StreamPicOutput( std::ostream* op_ptr, const SourceParams& sp);
+
+ //! virtual Destructor
+ virtual ~StreamPicOutput();
+
+ //! Write a picture to the next frame to be output
+ virtual bool WriteToNextFrame(const Picture& myframe) = 0;
+
+ //! Get the source parameters
+ SourceParams& GetSourceParams() {return m_sparams;}
+
+ protected:
+ //! Source parameters
+ SourceParams m_sparams;
+ //! Output stream
+ std::ostream* m_op_pic_ptr;
+
+ //! Body-less default Constructor
+ StreamPicOutput();
+ private:
-protected:
- //! Source parameters
- SourceParams m_sparams;
- //! Output stream
- std::ostream* m_op_pic_ptr;
-
- //! Body-less default Constructor
- StreamPicOutput();
-private:
+ };
-};
+ class StreamFrameOutput : public StreamPicOutput
+ {
+ public:
+
+ /*!
+ Constructor, takes
+ \param op_ptr the output stream object
+ \param sp the source parameters
+ */
+ StreamFrameOutput( std::ostream *op_ptr, const SourceParams& sp);
+
+ //! virtual Destructor
+ virtual ~StreamFrameOutput();
+
+ //! Write the next frame to the output
+ bool WriteToNextFrame(const Picture& myframe);
+
+ protected:
+ //! Write a frame component to file
+ bool WriteFrameComponent(const PicArray& pic_data,
+ const CompSort& cs);
+ private:
+ //! Body-less Default Constructor
+ StreamFrameOutput();
+ };
-class StreamFrameOutput : public StreamPicOutput
-{
-public:
+ class StreamFieldOutput : public StreamPicOutput
+ {
+ public:
+ //! Constructor
+ /*!
+ Constructor, takes
+ \param op_ptr the output stream object
+ \param sp the source parameters
+ */
+ StreamFieldOutput( std::ostream *op_ptr, const SourceParams& sp);
+
+ //! virtual Destructor
+ virtual ~StreamFieldOutput();
+
+ //! Write a field to the next frame to be output
+ bool WriteToNextFrame(const Picture& myfield);
+
+ protected:
+ //! Write a field component to file
+ bool WriteFieldComponent(const PicArray& pic_data,
+ int field_num,
+ const CompSort& cs);
+
+ private:
+ //! Body-less Default Constructor
+ StreamFieldOutput();
+ unsigned char *m_frame_store;
+ };
/*!
- Constructor, takes
- \param op_ptr the output stream object
- \param sp the source parameters
- */
- StreamFrameOutput(std::ostream *op_ptr, const SourceParams& sp);
-
- //! virtual Destructor
- virtual ~StreamFrameOutput();
+ Outputs pictures to a memory buffer
+ */
+ class MemoryStreamOutput
+ {
+ public:
+ //! Constructor
+ MemoryStreamOutput(SourceParams &sparams, bool interlace);
- //! Write the next frame to the output
- bool WriteToNextFrame(const Picture& myframe);
+ //! Destructor
+ ~MemoryStreamOutput();
-protected:
- //! Write a frame component to file
- bool WriteFrameComponent(const PicArray& pic_data,
- const CompSort& cs);
-private:
- //! Body-less Default Constructor
- StreamFrameOutput();
-};
+ //! Get source parameters
+ SourceParams& GetSourceParams()
+ { return m_op_pic_str->GetSourceParams();}
-class StreamFieldOutput : public StreamPicOutput
-{
-public:
- //! Constructor
- /*!
- Constructor, takes
- \param op_ptr the output stream object
- \param sp the source parameters
- */
- StreamFieldOutput(std::ostream *op_ptr, const SourceParams& sp);
-
- //! virtual Destructor
- virtual ~StreamFieldOutput();
-
- //! Write a field to the next frame to be output
- bool WriteToNextFrame(const Picture& myfield);
-
-protected:
- //! Write a field component to file
- bool WriteFieldComponent(const PicArray& pic_data,
- int field_num,
- const CompSort& cs);
-
-private:
- //! Body-less Default Constructor
- StreamFieldOutput();
- unsigned char *m_frame_store;
-};
-
-/*!
- Outputs pictures to a memory buffer
-*/
-class MemoryStreamOutput
-{
-public:
- //! Constructor
- MemoryStreamOutput(SourceParams &sparams, bool interlace);
+ StreamPicOutput *GetStream() { return m_op_pic_str; }
+ //! Set the memory buffer to write the data to
+ void SetMembufReference (unsigned char *buf, int buf_size);
- //! Destructor
- ~MemoryStreamOutput();
+ protected:
+ //! Body-less default Constructor
+ MemoryStreamOutput();
+ //! Body-less copy constructor
+ MemoryStreamOutput(const MemoryStreamOutput&);
+ //! Body-less assignment operator
+ MemoryStreamOutput & operator =(const MemoryStreamOutput&);
- //! Get source parameters
- SourceParams& GetSourceParams()
- {
- return m_op_pic_str->GetSourceParams();
- }
+ protected:
- StreamPicOutput *GetStream()
- {
- return m_op_pic_str;
- }
- //! Set the memory buffer to write the data to
- void SetMembufReference(unsigned char *buf, int buf_size);
-
-protected:
- //! Body-less default Constructor
- MemoryStreamOutput();
- //! Body-less copy constructor
- MemoryStreamOutput(const MemoryStreamOutput&);
- //! Body-less assignment operator
- MemoryStreamOutput & operator =(const MemoryStreamOutput&);
-
-protected:
-
- //! local memory buffer
- class OutputMemoryBuffer : public std::streambuf
- {
- public:
- //! Memory buffer constructor
- OutputMemoryBuffer() :
- m_op_buf(0),
- m_op_buf_size(0),
- m_op_idx(0)
- {}
-
- //! Set the buffer variables
- /*! Set the memory buffer variables
- \param buffer buffer to write data to
- \param buffer_size size of output buffer
- */
- void SetMembufReference(unsigned char *buffer, int buffer_size)
- {
- m_op_buf = buffer;
- m_op_buf_size = buffer_size;
- m_op_idx = 0;
- }
-
- protected:
- //! Memory buffer to write data to
- unsigned char *m_op_buf;
- //! Memory buffer size
- int m_op_buf_size;
- //! Index of first available byte in buffer
- int m_op_idx;
-
- //! Write Overflow method to write one char at a time
- virtual int overflow(int c)
- {
- if(c != EOF)
+ //! local memory buffer
+ class OutputMemoryBuffer : public std::streambuf
{
- if(m_op_idx == m_op_buf_size)
- return EOF;
-
- m_op_buf[m_op_idx] = (char)c;
- m_op_idx++;
- }
- return c;
- }
-
- //! xsputn method to write one multiple chars at a time to buffer
- virtual std::streamsize xsputn(const char *s,
- std::streamsize num)
- {
- std::streamsize bytes_left = m_op_buf_size - m_op_idx;
- std::streamsize bytes_written = bytes_left > num
- ? num : bytes_left;
- memcpy(&m_op_buf[m_op_idx], (unsigned char *)s,
- bytes_written);
- m_op_idx += bytes_written;
- return bytes_written;
- }
-
- private:
- //! Body-less copy constructor
- OutputMemoryBuffer(const OutputMemoryBuffer&);
- //! Body-less assignment operator
- OutputMemoryBuffer& operator =(const OutputMemoryBuffer&);
+ public:
+ //! Memory buffer constructor
+ OutputMemoryBuffer () :
+ m_op_buf(0),
+ m_op_buf_size(0),
+ m_op_idx(0)
+ {}
+
+ //! Set the buffer variables
+ /*! Set the memory buffer variables
+ \param buffer buffer to write data to
+ \param buffer_size size of output buffer
+ */
+ void SetMembufReference (unsigned char *buffer, int buffer_size)
+ {
+ m_op_buf = buffer;
+ m_op_buf_size = buffer_size;
+ m_op_idx = 0;
+ }
+
+ protected:
+ //! Memory buffer to write data to
+ unsigned char *m_op_buf;
+ //! Memory buffer size
+ int m_op_buf_size;
+ //! Index of first available byte in buffer
+ int m_op_idx;
+
+ //! Write Overflow method to write one char at a time
+ virtual int overflow (int c)
+ {
+ if ( c != EOF)
+ {
+ if (m_op_idx == m_op_buf_size)
+ return EOF;
+
+ m_op_buf[m_op_idx] = (char)c;
+ m_op_idx++;
+ }
+ return c;
+ }
+
+ //! xsputn method to write one multiple chars at a time to buffer
+ virtual std::streamsize xsputn (const char *s,
+ std::streamsize num)
+ {
+ std::streamsize bytes_left = m_op_buf_size - m_op_idx;
+ std::streamsize bytes_written = bytes_left > num
+ ? num : bytes_left;
+ memcpy (&m_op_buf[m_op_idx], (unsigned char *)s,
+ bytes_written);
+ m_op_idx += bytes_written;
+ return bytes_written;
+ }
+
+ private:
+ //! Body-less copy constructor
+ OutputMemoryBuffer(const OutputMemoryBuffer&);
+ //! Body-less assignment operator
+ OutputMemoryBuffer& operator =(const OutputMemoryBuffer&);
+ };
+
+ private:
+ //! Output stream Memory buffer
+ OutputMemoryBuffer m_membuf;
+ //! Physical Output stream
+ std::ostream* m_op_pic_ptr;
+ //! Pic output Stream
+ StreamPicOutput *m_op_pic_str;
};
-private:
- //! Output stream Memory buffer
- OutputMemoryBuffer m_membuf;
- //! Physical Output stream
- std::ostream* m_op_pic_ptr;
- //! Pic output Stream
- StreamPicOutput *m_op_pic_str;
-};
-
-/*!
- Outputs pictures to a file
-*/
-class FileStreamOutput
-{
-public:
-
- //! Constructor
/*!
- Constructor, takes
- \param output_name the name of the output file
- \param sp the source parameters
- \param interlace the output is interlaced
- */
- FileStreamOutput(const char* output_name,
- const SourceParams& sp, bool interlace);
-
- //! Destructor
- virtual ~FileStreamOutput();
-
- StreamPicOutput *GetStream()
+ Outputs pictures to a file
+ */
+ class FileStreamOutput
{
- return m_op_pic_str;
- }
-private:
- //! Physical Output stream
- std::ostream* m_op_pic_ptr;
- //! Pic output Stream
- StreamPicOutput *m_op_pic_str;
-};
-
-//! Picture input class
-/*!
- Abstract Class for reading picture data from a stream.
- */
-
-class StreamPicInput
-{
-public:
+ public:
+
+ //! Constructor
+ /*!
+ Constructor, takes
+ \param output_name the name of the output file
+ \param sp the source parameters
+ \param interlace the output is interlaced
+ */
+ FileStreamOutput (const char* output_name,
+ const SourceParams& sp, bool interlace);
+
+ //! Destructor
+ virtual ~FileStreamOutput ();
+
+ StreamPicOutput *GetStream() { return m_op_pic_str; }
+ private:
+ //! Physical Output stream
+ std::ostream* m_op_pic_ptr;
+ //! Pic output Stream
+ StreamPicOutput *m_op_pic_str;
+ };
- //! Default Constructor
- StreamPicInput();
- //! Constructor
+ //! Picture input class
/*!
- Constructor, takes
- \param ip_pic_ptr input stream to read from
- \param sparams Source parameters
+ Abstract Class for reading picture data from a stream.
*/
- StreamPicInput(std::istream *ip_pic_ptr, const SourceParams& sparams);
-
- //! Destructor
- virtual ~StreamPicInput();
-
- //! Skip n frames of input
- virtual void Skip(const int n) = 0;
-
- //! Read the next picture frame/field from the file
- virtual bool ReadNextPicture(Picture& mypic) = 0;
- //! Get the source parameters
- SourceParams& GetSourceParams() const
+ class StreamPicInput
{
- return m_sparams;
- }
+ public:
- //! Returns true if we're at the end of the input, false otherwise
- bool End() const ;
+ //! Default Constructor
+ StreamPicInput();
+ //! Constructor
+ /*!
+ Constructor, takes
+ \param ip_pic_ptr input stream to read from
+ \param sparams Source parameters
+ */
+ StreamPicInput(std::istream *ip_pic_ptr, const SourceParams& sparams);
-protected:
+ //! Destructor
+ virtual ~StreamPicInput();
- //! Source parameters
- mutable SourceParams m_sparams;
+ //! Skip n frames of input
+ virtual void Skip( const int n)= 0;
- //! Input stream
- std::istream* m_ip_pic_ptr;
+ //! Read the next picture frame/field from the file
+ virtual bool ReadNextPicture(Picture& mypic) = 0;
-};
+ //! Get the source parameters
+ SourceParams& GetSourceParams() const {return m_sparams;}
-class StreamFrameInput : public StreamPicInput
-{
-public:
+ //! Returns true if we're at the end of the input, false otherwise
+ bool End() const ;
- //! Default Constructor
- StreamFrameInput();
- //! Constructor
- /*!
- Constructor, takes
- \param ip_pic_ptr input stream to read from
- \param sparams Source parameters
- */
- StreamFrameInput(std::istream *ip_pic_ptr, const SourceParams& sparams);
+ protected:
- //! Destructor
- virtual ~StreamFrameInput();
+ //! Source parameters
+ mutable SourceParams m_sparams;
- //! Skip n frames of input
- virtual void Skip(const int n);
+ //! Input stream
+ std::istream* m_ip_pic_ptr;
- //! Read the next frame from the file
- virtual bool ReadNextPicture(Picture& myframe);
+ };
-private:
+ class StreamFrameInput : public StreamPicInput
+ {
+ public:
- //! Read a Frame component from the file
- bool ReadFrameComponent(PicArray& pic_data, const CompSort& cs);
+ //! Default Constructor
+ StreamFrameInput();
+ //! Constructor
+ /*!
+ Constructor, takes
+ \param ip_pic_ptr input stream to read from
+ \param sparams Source parameters
+ */
+ StreamFrameInput(std::istream *ip_pic_ptr, const SourceParams& sparams);
-};
+ //! Destructor
+ virtual ~StreamFrameInput();
-class StreamFieldInput : public StreamPicInput
-{
-public:
+ //! Skip n frames of input
+ virtual void Skip( const int n);
- //! Default Constructor
- StreamFieldInput();
- //! Constructor
- /*!
- Constructor, takes
- \param ip_pic_ptr input stream to read from
- \param sparams Source parameters
- */
- StreamFieldInput(std::istream *ip_pic_ptr, const SourceParams& sparams);
-
- //! Destructor
- virtual ~StreamFieldInput();
-
- //! Skip n frames of input
- virtual void Skip(const int n);
-
- //! Read the next field from the file
- virtual bool ReadNextPicture(Picture& myfield);
-
- //! Read the next frame from the file
- bool ReadNextFrame(Picture& field1, Picture& field2);
-
-protected:
- //! Read both Field components from the file
- bool ReadFieldComponent(PicArray& pic_data1,
- PicArray& pic_data2,
- const CompSort& cs);
-
- //! Read one Field component from the file
- bool ReadFieldComponent(bool is_field1, PicArray& pic_data,
- const CompSort& cs);
-};
-/*!
- Class for reading picture data from memory
- */
-class MemoryStreamInput
-{
-public:
- //! Constructor
- /*! Create a MemoryStreamInput object
- \param sparams Source parameters
- \param field_input Treat input as fields, not frames
- */
- MemoryStreamInput(SourceParams& sparams, bool field_input);
+ //! Read the next frame from the file
+ virtual bool ReadNextPicture(Picture& myframe);
- //! Destructor
- ~MemoryStreamInput();
+ private:
- SourceParams& GetSourceParams()
- {
- return m_inp_str->GetSourceParams();
- }
+ //! Read a Frame component from the file
+ bool ReadFrameComponent(PicArray& pic_data,const CompSort& cs);
- //! Set Memory buffer
- /*! Set the input memory buffer variables
- \param buf Input Buffer to read data from
- \param buf_size Input buffer size
- */
- void SetMembufReference(unsigned char *buf, int buf_size);
+ };
- //! Return the input stream
- StreamPicInput *GetStream()
+ class StreamFieldInput : public StreamPicInput
{
- return m_inp_str;
- }
-protected:
- //! Body-less copy constructor
- MemoryStreamInput(const MemoryStreamInput&);
- //! Body-less assignment operator
- MemoryStreamInput & operator =(const MemoryStreamInput&);
-
-protected:
- //! Class that defines the Input Stream Memory Buffer
- class InputMemoryBuffer : public std::streambuf
+ public:
+
+ //! Default Constructor
+ StreamFieldInput();
+ //! Constructor
+ /*!
+ Constructor, takes
+ \param ip_pic_ptr input stream to read from
+ \param sparams Source parameters
+ */
+ StreamFieldInput(std::istream *ip_pic_ptr, const SourceParams& sparams);
+
+ //! Destructor
+ virtual ~StreamFieldInput();
+
+ //! Skip n frames of input
+ virtual void Skip( const int n);
+
+ //! Read the next field from the file
+ virtual bool ReadNextPicture(Picture& myfield);
+
+ //! Read the next frame from the file
+ bool ReadNextFrame(Picture& field1, Picture& field2);
+
+ protected:
+ //! Read both Field components from the file
+ bool ReadFieldComponent(PicArray& pic_data1,
+ PicArray& pic_data2,
+ const CompSort& cs);
+
+ //! Read one Field component from the file
+ bool ReadFieldComponent(bool is_field1, PicArray& pic_data,
+ const CompSort& cs);
+ };
+ /*!
+ Class for reading picture data from memory
+ */
+ class MemoryStreamInput
{
- public:
- //! Constructor
- InputMemoryBuffer() : m_buffer(0), m_buffer_size(0)
- {
- setg((char *)m_buffer, (char *)m_buffer, (char *)m_buffer);
- }
-
- //! Destructor
- ~InputMemoryBuffer() {}
-
- //! Set Input Memory buffer variables
- /*! Initialises the input memory buffer vars
- \param buffer Input memory buffer
- \param buffer_size Input memory buffer size
- */
- void SetMembufReference(unsigned char *buffer, int buffer_size)
- {
- m_buffer = buffer;
- m_buffer_size = buffer_size;
-
- setg((char *)m_buffer, (char *)m_buffer,
- (char *)(m_buffer + buffer_size));
- }
-
- private:
- //! Body-less copy constructor
- InputMemoryBuffer(const InputMemoryBuffer& inbuf);
- //! Body-less assignment operator
- InputMemoryBuffer& operator = (const InputMemoryBuffer& inbuf);
-
- //! Input memory buffer
- unsigned char *m_buffer;
- //! Input memory buffer size
- int m_buffer_size;
+ public:
+ //! Constructor
+ /*! Create a MemoryStreamInput object
+ \param sparams Source parameters
+ \param field_input Treat input as fields, not frames
+ */
+ MemoryStreamInput(SourceParams& sparams, bool field_input);
+
+ //! Destructor
+ ~MemoryStreamInput();
+
+ SourceParams& GetSourceParams ( )
+ { return m_inp_str->GetSourceParams(); }
+
+ //! Set Memory buffer
+ /*! Set the input memory buffer variables
+ \param buf Input Buffer to read data from
+ \param buf_size Input buffer size
+ */
+ void SetMembufReference (unsigned char *buf, int buf_size);
+
+ //! Return the input stream
+ StreamPicInput *GetStream() { return m_inp_str; }
+ protected:
+ //! Body-less copy constructor
+ MemoryStreamInput(const MemoryStreamInput&);
+ //! Body-less assignment operator
+ MemoryStreamInput & operator =(const MemoryStreamInput&);
+
+ protected:
+ //! Class that defines the Input Stream Memory Buffer
+ class InputMemoryBuffer : public std::streambuf
+ {
+ public:
+ //! Constructor
+ InputMemoryBuffer() : m_buffer(0), m_buffer_size(0)
+ {
+ setg ((char *)m_buffer, (char *)m_buffer, (char *)m_buffer);
+ }
+
+ //! Destructor
+ ~InputMemoryBuffer(){}
+
+ //! Set Input Memory buffer variables
+ /*! Initialises the input memory buffer vars
+ \param buffer Input memory buffer
+ \param buffer_size Input memory buffer size
+ */
+ void SetMembufReference (unsigned char *buffer, int buffer_size)
+ {
+ m_buffer = buffer;
+ m_buffer_size = buffer_size;
+
+ setg ((char *)m_buffer, (char *)m_buffer,
+ (char *)(m_buffer + buffer_size));
+ }
+
+ private:
+ //! Body-less copy constructor
+ InputMemoryBuffer (const InputMemoryBuffer& inbuf);
+ //! Body-less assignment operator
+ InputMemoryBuffer& operator = (const InputMemoryBuffer& inbuf);
+
+ //! Input memory buffer
+ unsigned char *m_buffer;
+ //! Input memory buffer size
+ int m_buffer_size;
+ };
+
+ private:
+ //! Input stream buffer
+ InputMemoryBuffer m_membuf;
+
+ //! Input Stream Object
+ StreamPicInput *m_inp_str;
+
+ //! Input stream
+ std::istream* m_ip_pic_ptr;
};
-private:
- //! Input stream buffer
- InputMemoryBuffer m_membuf;
-
- //! Input Stream Object
- StreamPicInput *m_inp_str;
-
- //! Input stream
- std::istream* m_ip_pic_ptr;
-};
-
-//! Picture input class
-/*!
- Class for reading picture data from a file.
- */
-class FileStreamInput
-{
-public:
-
- //! Constructor
+ //! Picture input class
/*!
- Constructor, takes
- \param input_name the name of the input picture file
- \param sparams the source parameters
- \param interlace input is treated as interlaced
+ Class for reading picture data from a file.
*/
- FileStreamInput(const char* input_name, const SourceParams &sparams, bool interlace);
+ class FileStreamInput
+ {
+ public:
- //! Destructor
- virtual ~FileStreamInput();
+ //! Constructor
+ /*!
+ Constructor, takes
+ \param input_name the name of the input picture file
+ \param sparams the source parameters
+ \param interlace input is treated as interlaced
+ */
+ FileStreamInput (const char* input_name, const SourceParams &sparams, bool interlace);
- SourceParams& GetSourceParams()
- {
- return m_inp_str->GetSourceParams();
- }
+ //! Destructor
+ virtual ~FileStreamInput ();
- //! Return the input stream
- StreamPicInput *GetStream()
- {
- return m_inp_str;
- }
+ SourceParams& GetSourceParams ( )
+ { return m_inp_str->GetSourceParams(); }
+
+ //! Return the input stream
+ StreamPicInput *GetStream() { return m_inp_str; }
-private:
- StreamPicInput *m_inp_str;
+ private:
+ StreamPicInput *m_inp_str;
- //! Input stream
- std::istream* m_ip_pic_ptr;
+ //! Input stream
+ std::istream* m_ip_pic_ptr;
-};
+ };
} // namespace dirac
diff --git a/src/filters/parser/DiracSplitter/libdirac/libdirac_common/picture.cpp b/src/filters/parser/DiracSplitter/libdirac/libdirac_common/picture.cpp
index ba39343a8..ee3da95a3 100644
--- a/src/filters/parser/DiracSplitter/libdirac/libdirac_common/picture.cpp
+++ b/src/filters/parser/DiracSplitter/libdirac/libdirac_common/picture.cpp
@@ -50,62 +50,58 @@ using namespace dirac;
//---Picture---//
///////////////
-Picture::Picture(const PictureParams& pp):
+Picture::Picture(const PictureParams& pp):
m_pparams(pp)
{
- for(int c = 0; c < 3; ++c)
- {
+ for (int c=0;c<3;++c){
m_pic_data[c] = NULL;
- m_up_pic_data[c] = NULL;
+ m_up_pic_data[c] = NULL;
}
Init();
}
-Picture::Picture(const Picture& cpy):
+Picture::Picture( const Picture& cpy ):
m_pparams(cpy.m_pparams)
{
//delete data to be overwritten
- for(int c = 0; c < 3; ++c)
- {
+ for (int c=0;c<3;++c){
m_pic_data[c] = NULL;
- m_up_pic_data[c] = NULL;
+ m_up_pic_data[c] = NULL;
}
//now copy the data across
- for(int c = 0; c < 3; ++c)
- {
- m_pic_data[c] = new PicArray(*(cpy.m_pic_data[c]));
- if(cpy.m_up_pic_data[c] != NULL)
- m_up_pic_data[c] = new PicArray(*(cpy.m_up_pic_data[c]));
+ for (int c=0; c<3; ++c ){
+ m_pic_data[c] = new PicArray( *(cpy.m_pic_data[c]) );
+ if (cpy.m_up_pic_data[c] != NULL)
+ m_up_pic_data[c] = new PicArray( *(cpy.m_up_pic_data[c]) );
}
-
+
}
Picture::~Picture()
{
- ClearData();
+ ClearData();
}
Picture& Picture::operator=(const Picture& rhs)
{
- if(&rhs != this)
+ if ( &rhs != this)
{
- m_pparams = rhs.m_pparams;
+ m_pparams=rhs.m_pparams;
// Delete current data
ClearData();
// Copy the data across
- for(int c = 0; c < 3; ++c)
- {
- m_pic_data[c] = new PicArray(*(rhs.m_pic_data[c]));
-
- if(rhs.m_up_pic_data[c] != NULL)
- m_up_pic_data[c] = new PicArray(*(rhs.m_up_pic_data[c]));
- }
+ for (int c=0; c<3; ++c ){
+ m_pic_data[c] = new PicArray( *(rhs.m_pic_data[c]) );
+
+ if (rhs.m_up_pic_data[c] != NULL)
+ m_up_pic_data[c] = new PicArray( *(rhs.m_up_pic_data[c]) );
+ }
}
return *this;
@@ -114,11 +110,10 @@ Picture& Picture::operator=(const Picture& rhs)
void Picture::Fill(ValueType val)
{
- for(int c = 0; c < 3; ++c)
- {
+ for (int c=0; c<3; ++c ){
m_pic_data[c]->Fill(val);
- if(m_up_pic_data[c] != NULL)
- delete m_up_pic_data[c];
+ if (m_up_pic_data[c] != NULL )
+ delete m_up_pic_data[c];
}
}
@@ -131,43 +126,42 @@ void Picture::Init()
//first delete data if we need to
ClearData();
- m_pic_data[0] = new PicArray(m_pparams.Yl() , m_pparams.Xl());
- m_pic_data[0]->SetCSort(Y_COMP);
+ m_pic_data[0]=new PicArray( m_pparams.Yl() , m_pparams.Xl());
+ m_pic_data[0]->SetCSort( Y_COMP );
- m_pic_data[1] = new PicArray(m_pparams.ChromaYl() ,
- m_pparams.ChromaXl());
- m_pic_data[1]->SetCSort(U_COMP);
+ m_pic_data[1] = new PicArray( m_pparams.ChromaYl() ,
+ m_pparams.ChromaXl() );
+ m_pic_data[1]->SetCSort( U_COMP );
- m_pic_data[2] = new PicArray(m_pparams.ChromaYl() ,
- m_pparams.ChromaXl());
- m_pic_data[2]->SetCSort(V_COMP);
+ m_pic_data[2] = new PicArray( m_pparams.ChromaYl() ,
+ m_pparams.ChromaXl() );
+ m_pic_data[2]->SetCSort( V_COMP );
}
PicArray& Picture::UpData(CompSort cs)
{
const int c = (int) cs;
- if(m_up_pic_data[c] != NULL)
+ if (m_up_pic_data[c] != NULL )
return *(m_up_pic_data[c]);
else
- {
- //we have to do the upconversion
-
- m_up_pic_data[c] = new PicArray(2 * m_pic_data[c]->LengthY(),
- 2 * m_pic_data[c]->LengthX());
+ {//we have to do the upconversion
+
+ m_up_pic_data[c] = new PicArray( 2*m_pic_data[c]->LengthY(),
+ 2*m_pic_data[c]->LengthX() );
UpConverter* myupconv;
- if(c > 0)
- myupconv = new UpConverter(-(1 << (m_pparams.ChromaDepth() - 1)),
- (1 << (m_pparams.ChromaDepth() - 1)) - 1,
- m_pparams.ChromaXl(), m_pparams.ChromaYl());
+ if (c>0)
+ myupconv = new UpConverter(-(1 << (m_pparams.ChromaDepth()-1)),
+ (1 << (m_pparams.ChromaDepth()-1))-1,
+ m_pparams.ChromaXl(), m_pparams.ChromaYl());
else
- myupconv = new UpConverter(-(1 << (m_pparams.LumaDepth() - 1)),
- (1 << (m_pparams.LumaDepth() - 1)) - 1,
- m_pparams.Xl(), m_pparams.Yl());
+ myupconv = new UpConverter(-(1 << (m_pparams.LumaDepth()-1)),
+ (1 << (m_pparams.LumaDepth()-1))-1,
+ m_pparams.Xl(), m_pparams.Yl());
- myupconv->DoUpConverter(*(m_pic_data[c]) , *(m_up_pic_data[c]));
+ myupconv->DoUpConverter( *(m_pic_data[c]) , *(m_up_pic_data[c]) );
- delete myupconv;
+ delete myupconv;
return *(m_up_pic_data[c]);
@@ -178,50 +172,48 @@ const PicArray& Picture::UpData(CompSort cs) const
{
const int c = (int) cs;
- if(m_up_pic_data[c] != NULL)
+ if (m_up_pic_data[c] != NULL)
return *(m_up_pic_data[c]);
else
- {
- //we have to do the upconversion
-
- m_up_pic_data[c] = new PicArray(2 * m_pic_data[c]->LengthY(),
- 2 * m_pic_data[c]->LengthX());
+ {//we have to do the upconversion
+
+ m_up_pic_data[c] = new PicArray( 2*m_pic_data[c]->LengthY(),
+ 2*m_pic_data[c]->LengthX() );
UpConverter* myupconv;
- if(c > 0)
- myupconv = new UpConverter(-(1 << (m_pparams.ChromaDepth() - 1)),
- (1 << (m_pparams.ChromaDepth() - 1)) - 1,
- m_pparams.ChromaXl(), m_pparams.ChromaYl());
+ if (c>0)
+ myupconv = new UpConverter(-(1 << (m_pparams.ChromaDepth()-1)),
+ (1 << (m_pparams.ChromaDepth()-1))-1,
+ m_pparams.ChromaXl(), m_pparams.ChromaYl());
else
- myupconv = new UpConverter(-(1 << (m_pparams.LumaDepth() - 1)),
- (1 << (m_pparams.LumaDepth() - 1)) - 1,
- m_pparams.Xl(), m_pparams.Yl());
+ myupconv = new UpConverter(-(1 << (m_pparams.LumaDepth()-1)),
+ (1 << (m_pparams.LumaDepth()-1))-1,
+ m_pparams.Xl(), m_pparams.Yl());
- myupconv->DoUpConverter(*(m_pic_data[c]) , *(m_up_pic_data[c]));
+ myupconv->DoUpConverter( *(m_pic_data[c]) , *(m_up_pic_data[c]) );
- delete myupconv;
+ delete myupconv;
return *(m_up_pic_data[c]);
}
}
-void Picture::InitWltData(const int transform_depth)
+void Picture::InitWltData( const int transform_depth )
{
int xpad_len, ypad_len;
- int tx_mul = 1 << transform_depth;
+ int tx_mul = 1<<transform_depth;
- for(int c = 0; c < 3; ++c)
- {
+ for (int c=0; c<3; ++c){
xpad_len = m_pic_data[c]->LengthX();
ypad_len = m_pic_data[c]->LengthY();
- if(xpad_len % tx_mul != 0)
- xpad_len = ((xpad_len / tx_mul) + 1) * tx_mul;
- if(ypad_len % tx_mul != 0)
- ypad_len = ((ypad_len / tx_mul) + 1) * tx_mul;
+ if ( xpad_len%tx_mul != 0 )
+ xpad_len = ( (xpad_len/tx_mul)+1 ) *tx_mul;
+ if ( ypad_len%tx_mul != 0 )
+ ypad_len = ( (ypad_len/tx_mul)+1 ) * tx_mul;
- m_wlt_data[c].Resize(ypad_len, xpad_len);
+ m_wlt_data[c].Resize( ypad_len, xpad_len );
}
}
@@ -233,47 +225,47 @@ void Picture::ClipComponent(PicArray& pic_data, CompSort cs) const
ValueType min_val;
ValueType max_val;
-
+
min_val = (cs == Y_COMP) ?
- -(1 << (m_pparams.LumaDepth() - 1)) :
- -(1 << (m_pparams.ChromaDepth() - 1));
+ -(1 << (m_pparams.LumaDepth()-1) ) :
+ -(1 << (m_pparams.ChromaDepth()-1) );
max_val = (cs == Y_COMP) ?
- (1 << (m_pparams.LumaDepth() - 1)) - 1 :
- (1 << (m_pparams.ChromaDepth() - 1)) - 1;
+ (1 << (m_pparams.LumaDepth()-1) )-1 :
+ (1 << (m_pparams.ChromaDepth()-1) )-1;
#if defined (HAVE_MMX)
{
int qcount = count >> 2;
count = count & 3;
-
+
//__m64 pack_usmax = _mm_set_pi16 (0xffff, 0xffff, 0xffff, 0xffff);
//__m64 pack_smin = _mm_set_pi16 (0x8000, 0x8000, 0x8000, 0x8000);
- __m64 pack_usmax = _mm_set_pi16(-1, -1, -1, -1);
- __m64 pack_smin = _mm_set_pi16(-32768, -32768, -32768, -32768);
- __m64 high_val = _mm_set_pi16(max_val, max_val, max_val, max_val);
- __m64 lo_val = _mm_set_pi16(min_val, min_val, min_val, min_val);
-
- __m64 clip_max = _mm_add_pi16(pack_smin, high_val);
- __m64 clip_min = _mm_add_pi16(pack_smin, lo_val);
-
- __m64 tmp1 = _mm_subs_pu16(pack_usmax, clip_max);
- __m64 tmp2 = _mm_adds_pu16(clip_min, tmp1);
-
- while(qcount--)
+ __m64 pack_usmax = _mm_set_pi16 (-1, -1, -1, -1);
+ __m64 pack_smin = _mm_set_pi16 (-32768, -32768, -32768, -32768);
+ __m64 high_val = _mm_set_pi16 (max_val, max_val, max_val, max_val);
+ __m64 lo_val = _mm_set_pi16 (min_val, min_val, min_val, min_val);
+
+ __m64 clip_max = _mm_add_pi16 (pack_smin, high_val);
+ __m64 clip_min = _mm_add_pi16 (pack_smin, lo_val);
+
+ __m64 tmp1 = _mm_subs_pu16 ( pack_usmax, clip_max);
+ __m64 tmp2 = _mm_adds_pu16 ( clip_min, tmp1 );
+
+ while (qcount--)
{
ValueType *p1 = pic;
- *(__m64 *)p1 = _mm_add_pi16(pack_smin, *(__m64 *)p1);
- *(__m64 *)p1 = _mm_adds_pu16(*(__m64 *)p1, tmp1);
- *(__m64 *)p1 = _mm_subs_pu16(*(__m64 *)p1, tmp2);
- *(__m64 *)p1 = _mm_add_pi16(lo_val, *(__m64 *)p1);
+ *(__m64 *)p1 = _mm_add_pi16 (pack_smin, *(__m64 *)p1);
+ *(__m64 *)p1 = _mm_adds_pu16 (*(__m64 *)p1, tmp1);
+ *(__m64 *)p1 = _mm_subs_pu16 (*(__m64 *)p1, tmp2);
+ *(__m64 *)p1 = _mm_add_pi16 (lo_val, *(__m64 *)p1);
pic += 4;
}
//Mop up remaining pixels
- while(count--)
+ while( count-- )
{
- *pic = std::max(min_val, std::min(max_val , *pic)
- );
+ *pic = std::max( min_val, std::min( max_val , *pic )
+ );
pic++;
}
@@ -283,9 +275,9 @@ void Picture::ClipComponent(PicArray& pic_data, CompSort cs) const
#endif
// NOTE: depending on a contigous chunk of memory being allocated
- while(count--)
+ while (count--)
{
- *pic = std::max(min_val, std::min(max_val, *pic));
+ *pic = std::max( min_val, std::min( max_val, *pic ));
pic++;
}
}
@@ -293,35 +285,31 @@ void Picture::ClipComponent(PicArray& pic_data, CompSort cs) const
void Picture::Clip()
{
//just clips the straight picture data, not the upconverted data
-
- for(int c = 0; c < 3; ++c)
- ClipComponent(*(m_pic_data[c]), (CompSort) c);
+
+ for (int c=0; c<3; ++c)
+ ClipComponent( *(m_pic_data[c]), (CompSort) c);
}
void Picture::ClipUpData()
{
//just clips the upconverted data
- for(int c = 0; c < 3; ++c)
- {
- if(m_up_pic_data[c])
- ClipComponent(*(m_up_pic_data[c]), (CompSort) c);
+ for (int c=0; c<3; ++c){
+ if (m_up_pic_data[c])
+ ClipComponent( *(m_up_pic_data[c]), (CompSort) c );
}
}
void Picture::ClearData()
{
- for(int c = 0; c < 3; ++c)
- {
- if(m_pic_data[c] != NULL)
- {
+ for (int c=0;c<3;++c){
+ if (m_pic_data[c] != NULL){
delete m_pic_data[c];
m_pic_data[c] = NULL;
}
- if(m_up_pic_data[c] != NULL)
- {
+ if (m_up_pic_data[c] != NULL){
delete m_up_pic_data[c];
m_up_pic_data[c] = NULL;
}
@@ -329,16 +317,16 @@ void Picture::ClearData()
}
-void Picture::ReconfigPicture(const PictureParams &pp)
+void Picture::ReconfigPicture(const PictureParams &pp )
{
PictureParams old_pp = m_pparams;
m_pparams = pp;
// HAve picture dimensions or Chroma format changed ?
- if(m_pparams.Xl() == old_pp.Xl() &&
- m_pparams.Yl() == old_pp.Yl() &&
- m_pparams.CFormat() == old_pp.CFormat())
+ if (m_pparams.Xl() == old_pp.Xl() &&
+ m_pparams.Yl() == old_pp.Yl() &&
+ m_pparams.CFormat() == old_pp.CFormat())
return;
// Picture dimensions have changed. Re-initialise
diff --git a/src/filters/parser/DiracSplitter/libdirac/libdirac_common/picture.h b/src/filters/parser/DiracSplitter/libdirac/libdirac_common/picture.h
index efc2b2d03..face2d15d 100644
--- a/src/filters/parser/DiracSplitter/libdirac/libdirac_common/picture.h
+++ b/src/filters/parser/DiracSplitter/libdirac/libdirac_common/picture.h
@@ -43,129 +43,105 @@
namespace dirac
{
-//! A class for encapsulating all the data relating to a picture.
-/*!
- A class for encapsulating all the data relating to a picture - all the
- component data, including upconverted data.
- */
-class Picture
-{
-
-public:
-
- //! Constructor
+ //! A class for encapsulating all the data relating to a picture.
/*!
- Constructor initialises the picture parameters and the data
+ A class for encapsulating all the data relating to a picture - all the
+ component data, including upconverted data.
*/
- Picture(const PictureParams& pp);
+ class Picture
+ {
- //! Copy constructor. Private as not currently used [may want to implement reference counting later.]
- Picture(const Picture& cpy);
+ public:
- //! Destructor
- virtual ~Picture();
+ //! Constructor
+ /*!
+ Constructor initialises the picture parameters and the data
+ */
+ Picture( const PictureParams& pp );
- //! Assignment =. Private as not currently used [may want to implement reference counting later.]
- Picture& operator=(const Picture& rhs);
+ //! Copy constructor. Private as not currently used [may want to implement reference counting later.]
+ Picture(const Picture& cpy);
- //! Picture Fill
- /*!
- Initialise contents of picture with value provided
- */
- void Fill(ValueType val);
+ //! Destructor
+ virtual ~Picture();
- //gets and sets
- //! Gets the picture parameters
- PictureParams& GetPparams() const
- {
- return m_pparams;
- }
+ //! Assignment =. Private as not currently used [may want to implement reference counting later.]
+ Picture& operator=( const Picture& rhs );
- //! Sets the picture sort
- void SetPictureSort(const PictureSort ps)
- {
- m_pparams.SetPicSort(ps);
- }
+ //! Picture Fill
+ /*!
+ Initialise contents of picture with value provided
+ */
+ void Fill(ValueType val );
- //! Sets the picture type
- void SetPictureType(const PictureType ftype)
- {
- m_pparams.SetPictureType(ftype);
- }
+ //gets and sets
+ //! Gets the picture parameters
+ PictureParams& GetPparams() const {return m_pparams;}
- //! Sets the picture type
- void SetReferenceType(const ReferenceType rtype)
- {
- m_pparams.SetReferenceType(rtype);
- }
+ //! Sets the picture sort
+ void SetPictureSort( const PictureSort ps ){m_pparams.SetPicSort( ps ); }
- //! Reconfigures to the new parameters.
- void ReconfigPicture(const PictureParams &pp);
+ //! Sets the picture type
+ void SetPictureType( const PictureType ftype ){m_pparams.SetPictureType( ftype ); }
- //! Returns a given component
- PicArray& Data(CompSort cs)
- {
- return *m_pic_data[(int) cs];
- }
+ //! Sets the picture type
+ void SetReferenceType( const ReferenceType rtype ){m_pparams.SetReferenceType( rtype ); }
- //! Returns a given component
- const PicArray& Data(CompSort cs) const
- {
- return *m_pic_data[(int) cs];
- }
+ //! Reconfigures to the new parameters.
+ void ReconfigPicture( const PictureParams &pp );
- //! Returns a given upconverted component
- PicArray& UpData(CompSort cs);
+ //! Returns a given component
+ PicArray& Data(CompSort cs){return *m_pic_data[(int) cs];}
- //! Returns a given upconverted component
- const PicArray& UpData(CompSort cs) const;
+ //! Returns a given component
+ const PicArray& Data(CompSort cs) const{return *m_pic_data[(int) cs];}
- //! Returns the wavelet coefficient data
- const CoeffArray& WltData(CompSort c) const
- {
- return m_wlt_data[(int) c];
- }
+ //! Returns a given upconverted component
+ PicArray& UpData(CompSort cs);
- //! Returns the wavelet coefficient data
- CoeffArray& WltData(CompSort c)
- {
- return m_wlt_data[(int) c];
- }
+ //! Returns a given upconverted component
+ const PicArray& UpData(CompSort cs) const;
- //! Initialises the wavelet coefficient data arrays;
- void InitWltData(const int transform_depth);
+ //! Returns the wavelet coefficient data
+ const CoeffArray& WltData( CompSort c ) const { return m_wlt_data[(int) c]; }
- //! Clip the data to prevent overshoot
- /*!
- Clips the data to lie between 0 and (1<<video_depth)-1
- */
- void Clip();
+ //! Returns the wavelet coefficient data
+ CoeffArray& WltData( CompSort c ) { return m_wlt_data[(int) c]; }
- //! Clip the upconverted data to prevent overshoot
- /*!
- Clips the upconverted data to lie between 0 and (1<<video_depth)-1
- */
- void ClipUpData();
+ //! Initialises the wavelet coefficient data arrays;
+ void InitWltData( const int transform_depth );
+
+ //! Clip the data to prevent overshoot
+ /*!
+ Clips the data to lie between 0 and (1<<video_depth)-1
+ */
+ void Clip();
+
+ //! Clip the upconverted data to prevent overshoot
+ /*!
+ Clips the upconverted data to lie between 0 and (1<<video_depth)-1
+ */
+ void ClipUpData();
-protected:
- mutable PictureParams m_pparams;
- PicArray* m_pic_data[3];//the picture data
- mutable PicArray* m_up_pic_data[3];//upconverted data. Mutable because we
- //create them on the fly even in const
- //functions.
+ protected:
+ mutable PictureParams m_pparams;
+ PicArray* m_pic_data[3];//the picture data
+ mutable PicArray* m_up_pic_data[3];//upconverted data. Mutable because we
+ //create them on the fly even in const
+ //functions.
- CoeffArray m_wlt_data[3];// the wavelet coefficient data
+ CoeffArray m_wlt_data[3];// the wavelet coefficient data
- //! Initialises the picture once the picture parameters have been set
- virtual void Init();
+ //! Initialises the picture once the picture parameters have been set
+ virtual void Init();
- //! Delete all the data
- virtual void ClearData();
+ //! Delete all the data
+ virtual void ClearData();
- //! Clip an individual component
- void ClipComponent(PicArray& pic_data, CompSort cs) const;
+ //! Clip an individual component
+ void ClipComponent(PicArray& pic_data, CompSort cs) const;
-};
+ };
} // namespace dirac
diff --git a/src/filters/parser/DiracSplitter/libdirac/libdirac_common/picture_buffer.cpp b/src/filters/parser/DiracSplitter/libdirac/libdirac_common/picture_buffer.cpp
index 084b5e258..cbd311003 100644
--- a/src/filters/parser/DiracSplitter/libdirac/libdirac_common/picture_buffer.cpp
+++ b/src/filters/parser/DiracSplitter/libdirac/libdirac_common/picture_buffer.cpp
@@ -42,22 +42,21 @@
using namespace dirac;
//Simple constructor for decoder operation
-PictureBuffer::PictureBuffer() {}
+PictureBuffer::PictureBuffer(){}
//Copy constructor. Why anyone would need this I don't know.
PictureBuffer::PictureBuffer(const PictureBuffer& cpy)
-{
+ {
// first delete all frames in the current buffer
- for(size_t i = 0 ; i < m_pic_data.size() ; ++i)
+ for (size_t i=0 ; i<m_pic_data.size() ; ++i)
{
delete m_pic_data[i];
}//i
// next create new arrays, copying from the initialising buffer
m_pic_data.resize(cpy.m_pic_data.size());
- for(size_t i = 0 ; i < m_pic_data.size() ; ++i)
- {
- m_pic_data[i] = new Picture(*(cpy.m_pic_data[i]));
+ for (size_t i=0 ; i<m_pic_data.size() ; ++i){
+ m_pic_data[i] = new Picture( *(cpy.m_pic_data[i]) );
}//i
// now copy the map
@@ -69,21 +68,20 @@ PictureBuffer::PictureBuffer(const PictureBuffer& cpy)
}
//Assignment=. Not sure why this would be used either.
-PictureBuffer& PictureBuffer::operator=(const PictureBuffer& rhs)
-{
- if(&rhs != this)
+PictureBuffer& PictureBuffer::operator=(const PictureBuffer& rhs){
+ if (&rhs!=this)
{
// delete all the frames in the lhs buffer
- for(size_t i = 0 ; i < m_pic_data.size() ; ++i)
+ for (size_t i=0 ; i<m_pic_data.size() ; ++i)
{
delete m_pic_data[i];
}//i
// next create new arrays, copying from the rhs
m_pic_data.resize(rhs.m_pic_data.size());
- for(size_t i = 0 ; i < m_pic_data.size() ; ++i)
+ for (size_t i=0 ; i<m_pic_data.size() ; ++i)
{
- m_pic_data[i] = new Picture(*(rhs.m_pic_data[i]));
+ m_pic_data[i] = new Picture( *(rhs.m_pic_data[i]) );
}//i
// now copy the map
@@ -99,80 +97,76 @@ PictureBuffer& PictureBuffer::operator=(const PictureBuffer& rhs)
//Destructor
PictureBuffer::~PictureBuffer()
{
- for(size_t i = 0 ; i < m_pic_data.size() ; ++i)
+ for (size_t i=0 ; i<m_pic_data.size() ;++i)
delete m_pic_data[i];
}
-Picture& PictureBuffer::GetPicture(const unsigned int pnum)
-{
- //get picture with a given picture number, NOT with a given position in the buffer.
-//If the picture number does not occur, the first picture in the buffer is returned.
+Picture& PictureBuffer::GetPicture( const unsigned int pnum )
+{//get picture with a given picture number, NOT with a given position in the buffer.
+ //If the picture number does not occur, the first picture in the buffer is returned.
- std::map<unsigned int, unsigned int>::iterator it = m_pnum_map.find(pnum);
+ std::map<unsigned int,unsigned int>::iterator it = m_pnum_map.find(pnum);
unsigned int pos = 0;
- if(it != m_pnum_map.end())
+ if (it != m_pnum_map.end())
pos = it->second;
return *(m_pic_data[pos]);
}
-const Picture& PictureBuffer::GetPicture(const unsigned int pnum) const
-{
- //as above, but const version
+const Picture& PictureBuffer::GetPicture( const unsigned int pnum ) const
+{ //as above, but const version
- std::map<unsigned int, unsigned int>::const_iterator it = m_pnum_map.find(pnum);
+ std::map<unsigned int,unsigned int>::const_iterator it = m_pnum_map.find(pnum);
- unsigned int pos = 0;
- if(it != m_pnum_map.end())
+ unsigned int pos=0;
+ if (it != m_pnum_map.end())
pos = it->second;
return *(m_pic_data[pos]);
}
-Picture& PictureBuffer::GetPicture(const unsigned int pnum, bool& is_present)
-{
- //get picture with a given picture number, NOT with a given position in the buffer.
-//If the picture number does not occur, the first picture in the buffer is returned.
+Picture& PictureBuffer::GetPicture( const unsigned int pnum, bool& is_present )
+{//get picture with a given picture number, NOT with a given position in the buffer.
+ //If the picture number does not occur, the first picture in the buffer is returned.
- std::map<unsigned int, unsigned int>::iterator it = m_pnum_map.find(pnum);
+ std::map<unsigned int,unsigned int>::iterator it = m_pnum_map.find(pnum);
unsigned int pos = 0;
- if(it != m_pnum_map.end())
+ if (it != m_pnum_map.end())
{
is_present = true;
pos = it->second;
}
else
- is_present = false;
+ is_present=false;
return *(m_pic_data[pos]);
}
-const Picture& PictureBuffer::GetPicture(const unsigned int pnum, bool& is_present) const
-{
- //as above, but const version
+const Picture& PictureBuffer::GetPicture( const unsigned int pnum, bool& is_present ) const
+{ //as above, but const version
- std::map<unsigned int, unsigned int>::const_iterator it = m_pnum_map.find(pnum);
+ std::map<unsigned int,unsigned int>::const_iterator it = m_pnum_map.find(pnum);
- unsigned int pos = 0;
- if(it != m_pnum_map.end())
+ unsigned int pos=0;
+ if (it != m_pnum_map.end())
{
is_present = true;
pos = it->second;
}
else
- is_present = false;
+ is_present=false;
return *(m_pic_data[pos]);
}
-bool PictureBuffer::IsPictureAvail(const unsigned int pnum) const
+bool PictureBuffer::IsPictureAvail( const unsigned int pnum ) const
{
- std::map<unsigned int, unsigned int>::const_iterator it = m_pnum_map.find(pnum);
+ std::map<unsigned int,unsigned int>::const_iterator it = m_pnum_map.find(pnum);
- if(it != m_pnum_map.end())
+ if (it != m_pnum_map.end())
return true;
else
return false;
@@ -180,22 +174,21 @@ bool PictureBuffer::IsPictureAvail(const unsigned int pnum) const
std::vector<int> PictureBuffer::Members() const
{
- std::vector<int> members(0);
- for(unsigned int i = 0; i < m_pic_data.size(); ++i)
+ std::vector<int> members( 0 );
+ for (unsigned int i=0; i<m_pic_data.size(); ++i )
{
const PictureParams& pparams = m_pic_data[i]->GetPparams();
- members.push_back(pparams.PictureNum());
+ members.push_back( pparams.PictureNum() );
}// i
return members;
}
-void PictureBuffer::PushPicture(const PictureParams& pp)
-{
- // Put a new picture onto the top of the stack
+void PictureBuffer::PushPicture( const PictureParams& pp )
+{// Put a new picture onto the top of the stack
// if picture is present - return
- if(IsPictureAvail(pp.PictureNum()))
+ if (IsPictureAvail(pp.PictureNum()))
return;
// if ( pp.PicSort().IsRef() )
@@ -204,19 +197,19 @@ void PictureBuffer::PushPicture(const PictureParams& pp)
Picture* pptr = new Picture(pp);
// add the picture to the buffer
m_pic_data.push_back(pptr);
-
+
// put the picture number into the index table
- std::pair<unsigned int, unsigned int> temp_pair(pp.PictureNum() , m_pic_data.size() - 1);
+ std::pair<unsigned int,unsigned int> temp_pair(pp.PictureNum() , m_pic_data.size()-1 );
m_pnum_map.insert(temp_pair);
}
-void PictureBuffer::CopyPicture(const Picture& picture)
+void PictureBuffer::CopyPicture( const Picture& picture )
{
PushPicture(picture.GetPparams());
bool is_present;
- Picture & p = GetPicture(picture.GetPparams().PictureNum(), is_present);
+ Picture & p= GetPicture(picture.GetPparams().PictureNum(), is_present);
if(is_present)
p = picture;
}
@@ -225,18 +218,18 @@ void PictureBuffer::ClearSlot(const unsigned int pos)
{
// Clear a slot corresponding to position pos to take more data
- std::pair<unsigned int, unsigned int>* tmp_pair;
+ std::pair<unsigned int,unsigned int>* tmp_pair;
- if(pos < m_pic_data.size())
+ if (pos<m_pic_data.size())
{
delete m_pic_data[pos];
- m_pic_data.erase(m_pic_data.begin() + pos);
+ m_pic_data.erase( m_pic_data.begin()+pos );
- //make a new map
+ //make a new map
m_pnum_map.clear();
- for(size_t i = 0 ; i < m_pic_data.size() ; ++i)
+ for (size_t i=0 ; i<m_pic_data.size() ; ++i)
{
- tmp_pair = new std::pair<unsigned int, unsigned int>(m_pic_data[i]->GetPparams().PictureNum() , i);
+ tmp_pair = new std::pair<unsigned int,unsigned int>( m_pic_data[i]->GetPparams().PictureNum() , i);
m_pnum_map.insert(*tmp_pair);
delete tmp_pair;
}//i
@@ -246,17 +239,15 @@ void PictureBuffer::ClearSlot(const unsigned int pos)
void PictureBuffer::SetRetiredPictureNum(const int show_pnum, const int current_coded_pnum)
{
- if(IsPictureAvail(current_coded_pnum))
+ if ( IsPictureAvail(current_coded_pnum))
{
PictureParams &pparams = GetPicture(current_coded_pnum).GetPparams();
pparams.SetRetiredPictureNum(-1);
- for(size_t i = 0 ; i < m_pic_data.size() ; ++i)
+ for (size_t i=0 ; i<m_pic_data.size() ; ++i)
{
- if(m_pic_data[i]->GetPparams().PicSort().IsRef())
- {
- if((m_pic_data[i]->GetPparams().PictureNum() + m_pic_data[i]->GetPparams().ExpiryTime()) <= show_pnum)
- {
- pparams.SetRetiredPictureNum(m_pic_data[i]->GetPparams().PictureNum());
+ if (m_pic_data[i]->GetPparams().PicSort().IsRef() ){
+ if ( (m_pic_data[i]->GetPparams().PictureNum() + m_pic_data[i]->GetPparams().ExpiryTime() ) <= show_pnum){
+ pparams.SetRetiredPictureNum(m_pic_data[i]->GetPparams().PictureNum());
break;
}
}
@@ -266,9 +257,8 @@ void PictureBuffer::SetRetiredPictureNum(const int show_pnum, const int current_
void PictureBuffer::Remove(const int pnum)
{
- for(size_t i = 0 ; i < m_pic_data.size() ; ++i)
- {
- if(m_pic_data[i]->GetPparams().PictureNum() == pnum)
+ for (size_t i=0 ; i<m_pic_data.size() ; ++i){
+ if ( m_pic_data[i]->GetPparams().PictureNum() == pnum)
ClearSlot(i);
}//i
}
diff --git a/src/filters/parser/DiracSplitter/libdirac/libdirac_common/picture_buffer.h b/src/filters/parser/DiracSplitter/libdirac/libdirac_common/picture_buffer.h
index 70c2e4ab2..86613720e 100644
--- a/src/filters/parser/DiracSplitter/libdirac/libdirac_common/picture_buffer.h
+++ b/src/filters/parser/DiracSplitter/libdirac/libdirac_common/picture_buffer.h
@@ -46,153 +46,152 @@
namespace dirac
{
-//! Holds pictures both for reference and to overcome reordering delay
-/*!
- The buffer holds pictures in a stack to overcome both reordering due to
- bi-directional prediction and use as references for subsequence motion
- estimation. Pictures, and components of pictures, can be accessed by their
- picture numbers. GOP parameters can be included in the constructors so
- that pictures can be given types (I picture, L1 picture or L2 picture) on
- being pushed onto the stack; alternatively, these parameters can be
- overridden.
-*/
-class PictureBuffer
-{
-public:
- //! Default Constructor
- PictureBuffer();
-
- //! Constructor
- /*!
- Creates a PictureBuffer using the chroma format. Suitable for
- compressing when there are no L2 pictures, or when the temporal
- prediction structure is to be determined on the fly.
-
- \param cf the Chroma format of pictures in the buffer
- \param xlen the luma width of pictures in the buffer
- \param ylen the luma height of pictures in the buffer
- \param luma_depth the video depth of the luma comp in the buffer
- \param chroma_depth the video depth of the chroma comp in the buffer
- \param using_ac True if using Arithmetic coding to code coefficient data
-
- */
- PictureBuffer(ChromaFormat cf,
- const int xlen,
- const int ylen,
- const unsigned int luma_depth,
- const unsigned int chroma_depth,
- bool using_ac);
-
- //! Constructor
- /*!
- Creates a PictureBuffer using the chroma format, the number of L1
- pictures between I pictures and the separation in pictures between L1
- pictures. Suitable for compressing when there is a full GOP structure
- or when the temporal prediction structure is to be determined on
- the fly.
-
- \param cf the Chroma format of pictures in the buffer
- \param numL1 the number of Layer 1 pictures before the next I picture. 0 means that there is only one I picture.
- \param L1sep the number of Layer 2 pictures between Layer 1 pictures
- \param xlen the luma width of pictures in the buffer
- \param ylen the luma height of pictures in the buffer
- \param luma_depth the video depth of the luma comp in the buffer
- \param chroma_depth the video depth of the chroma comp in the buffer
- \param interlace Set true if material is being coded in interlaced mode
- \param using_ac True if using Arithmetic coding to code coefficient data
- */
- PictureBuffer(ChromaFormat cf,
- const int numL1,
- const int L1sep,
- const int xlen,
- const int ylen,
- const unsigned int luma_depth,
- const unsigned int chroma_depth,
- bool interlace,
- bool using_ac);
-
- //! Copy constructor
- /*!
- Copy constructor. Removes the current contents of the pictureture buffer
- and copies in the contents of the initialising buffer.
- */
- PictureBuffer(const PictureBuffer& cpy);
-
- //! Operator=.
- /*!
- Operator=. Assigns all elements of the rhs to the lhs.
- */
- PictureBuffer& operator=(const PictureBuffer& rhs);
-
- //! Destructor
- ~PictureBuffer();
-
- //! Get picture with a given picture number (NOT with a given position in the buffer)
- Picture& GetPicture(const unsigned int pnum);
-
- //! Get picture with a given picture number (NOT with a given position in the buffer)
- const Picture& GetPicture(const unsigned int pnum) const;
-
- //! Get picture with a given picture number, setting a flag to true if it's there
- Picture& GetPicture(const unsigned int pnum, bool& is_present);
-
- //! Get picture with a given picture number, setting a flag to true if it's there
- const Picture& GetPicture(const unsigned int pnum, bool& is_present) const;
-
- //! Return true if picture with the particular picture number is available else return false
- bool IsPictureAvail(const unsigned int pnum) const;
-
- //! Returns a list of member pictures
- std::vector<int> Members() const;
-
- //! Put a new picture into the top of the buffer
- /*!
- Put a new picture into the top of the buffer. Picture parameters
- associated with the picture will be as given by the picture parameter
- object.
- */
- void PushPicture(const PictureParams& pp);
-
- //! Put a copy of a new picture into the buffer
- /*!
- Put a copy of a new picture into the buffer.
- */
- void CopyPicture(const Picture& picture);
-
- //! Sets the reference picture number that will be cleaned
- /*!
- Indicate which picture which has been output and which is no longer
- required for reference. Expiry times are set in each picture's
- picture parameters.
- \param show_pnum picture number in display order that can be output
- \param current_coded_pnum picture number in display order of picture currently being coded
- */
- void SetRetiredPictureNum(const int show_pnum, const int current_coded_pnum);
-
- //! Delete picture
- /*!
- Delete picture.
- \param pnum picture number in display order to be deleted from picture buffer
- */
- void Remove(int pnum);
-
-private:
- //! Clear internal data slot number pos
+ //! Holds pictures both for reference and to overcome reordering delay
/*!
- Clear internal data slot number pos
+ The buffer holds pictures in a stack to overcome both reordering due to
+ bi-directional prediction and use as references for subsequence motion
+ estimation. Pictures, and components of pictures, can be accessed by their
+ picture numbers. GOP parameters can be included in the constructors so
+ that pictures can be given types (I picture, L1 picture or L2 picture) on
+ being pushed onto the stack; alternatively, these parameters can be
+ overridden.
*/
- void ClearSlot(const unsigned int pos);
+ class PictureBuffer{
+ public:
+ //! Default Constructor
+ PictureBuffer();
+
+ //! Constructor
+ /*!
+ Creates a PictureBuffer using the chroma format. Suitable for
+ compressing when there are no L2 pictures, or when the temporal
+ prediction structure is to be determined on the fly.
+
+ \param cf the Chroma format of pictures in the buffer
+ \param xlen the luma width of pictures in the buffer
+ \param ylen the luma height of pictures in the buffer
+ \param luma_depth the video depth of the luma comp in the buffer
+ \param chroma_depth the video depth of the chroma comp in the buffer
+ \param using_ac True if using Arithmetic coding to code coefficient data
+
+ */
+ PictureBuffer(ChromaFormat cf,
+ const int xlen,
+ const int ylen,
+ const unsigned int luma_depth,
+ const unsigned int chroma_depth,
+ bool using_ac);
+
+ //! Constructor
+ /*!
+ Creates a PictureBuffer using the chroma format, the number of L1
+ pictures between I pictures and the separation in pictures between L1
+ pictures. Suitable for compressing when there is a full GOP structure
+ or when the temporal prediction structure is to be determined on
+ the fly.
+
+ \param cf the Chroma format of pictures in the buffer
+ \param numL1 the number of Layer 1 pictures before the next I picture. 0 means that there is only one I picture.
+ \param L1sep the number of Layer 2 pictures between Layer 1 pictures
+ \param xlen the luma width of pictures in the buffer
+ \param ylen the luma height of pictures in the buffer
+ \param luma_depth the video depth of the luma comp in the buffer
+ \param chroma_depth the video depth of the chroma comp in the buffer
+ \param interlace Set true if material is being coded in interlaced mode
+ \param using_ac True if using Arithmetic coding to code coefficient data
+ */
+ PictureBuffer(ChromaFormat cf,
+ const int numL1,
+ const int L1sep,
+ const int xlen,
+ const int ylen,
+ const unsigned int luma_depth,
+ const unsigned int chroma_depth,
+ bool interlace,
+ bool using_ac);
+
+ //! Copy constructor
+ /*!
+ Copy constructor. Removes the current contents of the pictureture buffer
+ and copies in the contents of the initialising buffer.
+ */
+ PictureBuffer(const PictureBuffer& cpy);
+
+ //! Operator=.
+ /*!
+ Operator=. Assigns all elements of the rhs to the lhs.
+ */
+ PictureBuffer& operator=(const PictureBuffer& rhs);
+
+ //! Destructor
+ ~PictureBuffer();
+
+ //! Get picture with a given picture number (NOT with a given position in the buffer)
+ Picture& GetPicture(const unsigned int pnum );
+
+ //! Get picture with a given picture number (NOT with a given position in the buffer)
+ const Picture& GetPicture(const unsigned int pnum) const;
+
+ //! Get picture with a given picture number, setting a flag to true if it's there
+ Picture& GetPicture(const unsigned int pnum, bool& is_present);
+
+ //! Get picture with a given picture number, setting a flag to true if it's there
+ const Picture& GetPicture(const unsigned int pnum, bool& is_present) const;
+
+ //! Return true if picture with the particular picture number is available else return false
+ bool IsPictureAvail(const unsigned int pnum) const;
+
+ //! Returns a list of member pictures
+ std::vector<int> Members() const;
+
+ //! Put a new picture into the top of the buffer
+ /*!
+ Put a new picture into the top of the buffer. Picture parameters
+ associated with the picture will be as given by the picture parameter
+ object.
+ */
+ void PushPicture(const PictureParams& pp);
+
+ //! Put a copy of a new picture into the buffer
+ /*!
+ Put a copy of a new picture into the buffer.
+ */
+ void CopyPicture( const Picture& picture );
+
+ //! Sets the reference picture number that will be cleaned
+ /*!
+ Indicate which picture which has been output and which is no longer
+ required for reference. Expiry times are set in each picture's
+ picture parameters.
+ \param show_pnum picture number in display order that can be output
+ \param current_coded_pnum picture number in display order of picture currently being coded
+ */
+ void SetRetiredPictureNum(const int show_pnum, const int current_coded_pnum);
+
+ //! Delete picture
+ /*!
+ Delete picture.
+ \param pnum picture number in display order to be deleted from picture buffer
+ */
+ void Remove(int pnum);
+
+ private:
+ //! Clear internal data slot number pos
+ /*!
+ Clear internal data slot number pos
+ */
+ void ClearSlot(const unsigned int pos);
// //! the count of the number of reference pictures in the buffer
// int m_ref_count;
- //! the buffer storing all the values
- std::vector<Picture*> m_pic_data;
+ //! the buffer storing all the values
+ std::vector<Picture*> m_pic_data;
- //!the map from picture numbers to position in the buffer
- std::map<unsigned int, unsigned int> m_pnum_map;
+ //!the map from picture numbers to position in the buffer
+ std::map<unsigned int,unsigned int> m_pnum_map;
-};
+ };
} // namespace dirac
diff --git a/src/filters/parser/DiracSplitter/libdirac/libdirac_common/upconvert.cpp b/src/filters/parser/DiracSplitter/libdirac/libdirac_common/upconvert.cpp
index c905b794d..5535a66da 100644
--- a/src/filters/parser/DiracSplitter/libdirac/libdirac_common/upconvert.cpp
+++ b/src/filters/parser/DiracSplitter/libdirac/libdirac_common/upconvert.cpp
@@ -44,7 +44,7 @@ using namespace dirac;
#define MIN(a,b) (((a) < (b)) ? (a) : (b))
#define CLIP(x,min,max) MAX(MIN(x,max),min)
-UpConverter::UpConverter(int min_val, int max_val, int orig_xlen, int orig_ylen) :
+UpConverter::UpConverter (int min_val, int max_val, int orig_xlen, int orig_ylen) :
m_min_val(min_val),
m_max_val(max_val),
m_orig_xl(orig_xlen),
@@ -55,23 +55,23 @@ UpConverter::UpConverter(int min_val, int max_val, int orig_xlen, int orig_ylen)
void UpConverter::DoUpConverter(const PicArray& pic_data, PicArray& up_data)
{
- m_width_old = std::min(pic_data.LengthX(), m_orig_xl);
- m_height_old = std::min(pic_data.LengthY(), m_orig_yl);
- m_width_new = std::min(2 * m_width_old, up_data.LengthX());
- m_height_new = std::min(2 * m_height_old, up_data.LengthY());
+ m_width_old = std::min (pic_data.LengthX(), m_orig_xl);
+ m_height_old = std::min (pic_data.LengthY(), m_orig_yl);
+ m_width_new = std::min(2*m_width_old, up_data.LengthX());
+ m_height_new = std::min(2*m_height_old, up_data.LengthY());
// Filter params
const int filter_size = 4;
const int filter_shift = 5;
- const short taps[4] = {21, -7, 3, -1};
+ const short taps[4] = {21,-7,3,-1};
//Variables that will be used by the filter calculations
ValueType sum;
int ypos(0);
+
-
- //There are three y loops to cope with the leading edge, middle
+ //There are three y loops to cope with the leading edge, middle
//and trailing edge of each column.
for(int y = 0 ; y < filter_size; ++y , ypos += 2)
@@ -81,14 +81,14 @@ void UpConverter::DoUpConverter(const PicArray& pic_data, PicArray& up_data)
//This means our main loop is in the x direction and
//there is a much greater chance the data we need will
//be in the cache.
- for(int x = 0 , xpos = 0; x < m_width_old; x++ , xpos += 2)
+ for(int x = 0 , xpos = 0; x < m_width_old; x++ , xpos+=2 )
{
// Copy a Pixel from the original image in each even position
up_data[ypos][xpos] = pic_data[y][x];
//Work out the next pixel from filtered values.
//Excuse the complicated ternary stuff but it sorts out the edge
- sum = 1 << (filter_shift - 1);
+ sum = 1 << (filter_shift-1);
sum += (pic_data[y][x] + pic_data[y+1][x]) * taps[0];
sum += (pic_data[(y>=1)?(y-1):0][x] + pic_data[y+2][x]) * taps[1];
sum += (pic_data[(y>=2)?(y-2):0][x] + pic_data[y+3][x]) * taps[2];
@@ -99,38 +99,38 @@ void UpConverter::DoUpConverter(const PicArray& pic_data, PicArray& up_data)
}// x, xpos
// The row loop.
- RowLoop(up_data , ypos, filter_size, filter_shift, taps);
+ RowLoop( up_data , ypos, filter_size, filter_shift, taps );
}// y, ypos
// This loop is like the last one but it deals with the centre
// section of the image and so the ternary operations are dropped
// from the filter section.
for(int y = filter_size; y < m_height_old - filter_size; ++y , ypos += 2)
{
- for(int x = 0 , xpos = 0; x < m_width_old; x++ , xpos += 2)
+ for(int x = 0 , xpos=0; x < m_width_old; x++ , xpos+=2 )
{
up_data[ypos][xpos] = pic_data[y][x];
- sum = 1 << (filter_shift - 1);
-
- for(int t = 0; t < filter_size; ++t)
+ sum = 1 << (filter_shift-1);
+
+ for (int t=0; t<filter_size; ++t)
sum += (pic_data[y-t][x] + pic_data[y+1+t][x]) * taps[t];
sum >>= filter_shift;
up_data[ypos+1][xpos] = CLIP(sum, m_min_val, m_max_val);
}// x,xpos
- RowLoop(up_data , ypos, filter_size, filter_shift, taps);
+ RowLoop( up_data , ypos, filter_size, filter_shift, taps );
- }// y, ypos
+ }// y, ypos
// Another similar loop! - this time we are dealing with
// the trailing edge so the ternary stuff is back in the
- // filter calcs but in the second parameter.
- for(int y = m_height_old - filter_size; y < m_height_old; ++y , ypos += 2)
+ // filter calcs but in the second parameter.
+ for(int y = m_height_old - filter_size; y < m_height_old; ++y , ypos+=2)
{
- for(int x = 0 , xpos = 0 ; x < m_width_old; x++ , xpos += 2)
+ for(int x = 0 , xpos=0 ; x < m_width_old; x++ , xpos+=2)
{
- up_data[ypos][xpos] = pic_data[y][x];
+ up_data[ypos][xpos]=pic_data[y][x];
- sum = 1 << (filter_shift - 1);
+ sum = 1 << (filter_shift-1);
sum += (pic_data[y][x] + pic_data[((y+1)<m_height_old)?(y+1):(m_height_old-1)][x]) * taps[0];
sum += (pic_data[y - 1][x] + pic_data[((y+2)<m_height_old)?(y+2):(m_height_old-1)][x]) * taps[1];
sum += (pic_data[y - 2][x] + pic_data[((y+3)<m_height_old)?(y+3):(m_height_old-1)][x]) * taps[2];
@@ -139,19 +139,19 @@ void UpConverter::DoUpConverter(const PicArray& pic_data, PicArray& up_data)
sum >>= filter_shift;
up_data[ypos+1][xpos] = CLIP(sum, m_min_val, m_max_val);
}//x,xpos
- RowLoop(up_data , ypos, filter_size, filter_shift, taps);
+ RowLoop( up_data , ypos, filter_size, filter_shift, taps );
}//y,ypos
}
-void UpConverter::RowLoop(PicArray&up_data, const int row_num,
- const int filter_size, const int filter_shift, const short taps[4])
+void UpConverter::RowLoop(PicArray&up_data, const int row_num,
+const int filter_size, const int filter_shift, const short taps[4] )
{
- const int dble_size(filter_size << 1);
+ const int dble_size( filter_size<<1 );
//Calculation variable
ValueType sum;
- int ypos;
+ int ypos;
//Leading row Edge
//Note the factor of two difference as we only want to fill in every other
@@ -160,9 +160,9 @@ void UpConverter::RowLoop(PicArray&up_data, const int row_num,
{
ypos = row_num + j;
- for(int x = 0; x < dble_size ; x += 2)
+ for(int x = 0; x < dble_size ; x+=2)
{
- sum = 1 << (filter_shift - 1);
+ sum = 1 << (filter_shift-1);
sum += (up_data[ypos][x] + up_data[ypos][x+2]) * taps[0];
sum += (up_data[ypos][(x>=2)?(x-2):0] + up_data[ypos][x+4]) * taps[1];
sum += (up_data[ypos][(x>=4)?(x-4):0] + up_data[ypos][x+6]) * taps[2];
@@ -173,11 +173,11 @@ void UpConverter::RowLoop(PicArray&up_data, const int row_num,
up_data[ypos][x+1] = CLIP(sum, m_min_val, m_max_val);
}// x
//Middle of row
- for(int x = dble_size; x < m_width_new - dble_size ; x += 2)
+ for(int x = dble_size; x<m_width_new-dble_size ; x+=2 )
{
- sum = 1 << (filter_shift - 1);
-
- for(int t = 0; t < filter_size; ++t)
+ sum = 1 << (filter_shift-1);
+
+ for (int t=0; t<filter_size; ++t)
sum += (up_data[ypos][x-2*t] + up_data[ypos][x+2+2*t]) * taps[t];
@@ -185,9 +185,9 @@ void UpConverter::RowLoop(PicArray&up_data, const int row_num,
up_data[ypos][x+1] = CLIP(sum, m_min_val, m_max_val);
}// x
//Trailing row edge
- for(int x = m_width_new - dble_size ; x < m_width_new ; x += 2)
+ for(int x = m_width_new - dble_size ; x<m_width_new ; x+=2)
{
- sum = 1 << (filter_shift - 1);
+ sum = 1 << (filter_shift-1);
sum += (up_data[ypos][x] + up_data[ypos][(((x+2)<m_width_new)?(x+2):(m_width_new-2))]) * taps[0];
sum += (up_data[ypos][x-2] + up_data[ypos][(((x+4)<m_width_new)?(x+4):(m_width_new-2))]) * taps[1];
sum += (up_data[ypos][x-4] + up_data[ypos][(((x+6)<m_width_new)?(x+6):(m_width_new-2))]) * taps[2];
diff --git a/src/filters/parser/DiracSplitter/libdirac/libdirac_common/upconvert.h b/src/filters/parser/DiracSplitter/libdirac/libdirac_common/upconvert.h
index c250692e0..94d81026e 100644
--- a/src/filters/parser/DiracSplitter/libdirac/libdirac_common/upconvert.h
+++ b/src/filters/parser/DiracSplitter/libdirac/libdirac_common/upconvert.h
@@ -42,56 +42,56 @@
namespace dirac
{
-//Optimised upconversion class - no array resizes.
-//Uses integer math - no floats!
-//
-
-//! Upconversion class
-/*!
- Class to upconvert data by a factor of 2 in both dimensions
- */
-class UpConverter
-{
+ //Optimised upconversion class - no array resizes.
+ //Uses integer math - no floats!
+ //
+
+ //! Upconversion class
+ /*!
+ Class to upconvert data by a factor of 2 in both dimensions
+ */
+ class UpConverter
+ {
-public:
+ public:
- //! Constructor
- UpConverter(int min_val, int max_val, int orig_xlen, int orig_ylen);
+ //! Constructor
+ UpConverter(int min_val, int max_val, int orig_xlen, int orig_ylen);
- //! Destructor
- ~UpConverter() {};
+ //! Destructor
+ ~UpConverter() {};
- //! Upconvert the picture data
- /*!
- Upconvert the picture data, where the parameters are
- \param pic_data is the original data
- \param up_data is the upconverted data
- */
- void DoUpConverter(const PicArray& pic_data, PicArray& up_data);
+ //! Upconvert the picture data
+ /*!
+ Upconvert the picture data, where the parameters are
+ \param pic_data is the original data
+ \param up_data is the upconverted data
+ */
+ void DoUpConverter(const PicArray& pic_data, PicArray& up_data);
-private:
- //! Private body-less copy constructor: class should not be copied
- UpConverter(const UpConverter& cpy);
+ private:
+ //! Private body-less copy constructor: class should not be copied
+ UpConverter(const UpConverter& cpy);
- //! Private body-less assignment: class should not be assigned
- UpConverter& operator=(const UpConverter& rhs);
+ //! Private body-less assignment: class should not be assigned
+ UpConverter& operator=(const UpConverter& rhs);
- //! Applies the filter to a row and its successor
- void RowLoop(PicArray& up_data, const int row_num,
- const int filter_size, const int filter_shift, const short taps[4]);
+ //! Applies the filter to a row and its successor
+ void RowLoop(PicArray& up_data, const int row_num,
+ const int filter_size, const int filter_shift, const short taps[4] );
-private:
- //Variable to keep the loops in check
- int m_width_old, m_height_old;
- int m_width_new, m_height_new;
+ private:
+ //Variable to keep the loops in check
+ int m_width_old, m_height_old;
+ int m_width_new, m_height_new;
- const int m_min_val;
- const int m_max_val;
+ const int m_min_val;
+ const int m_max_val;
- const int m_orig_xl;
- const int m_orig_yl;
-};
+ const int m_orig_xl;
+ const int m_orig_yl;
+ };
} // namespace dirac
diff --git a/src/filters/parser/DiracSplitter/libdirac/libdirac_common/video_format_defaults.cpp b/src/filters/parser/DiracSplitter/libdirac/libdirac_common/video_format_defaults.cpp
index 6cbf61ad7..683fd3065 100644
--- a/src/filters/parser/DiracSplitter/libdirac/libdirac_common/video_format_defaults.cpp
+++ b/src/filters/parser/DiracSplitter/libdirac/libdirac_common/video_format_defaults.cpp
@@ -63,7 +63,7 @@ void SetDefaultCodecParameters(CodecParams &cparams,
// Overridden from command line of encoder or in bytestream for decoder.
cparams.SetPictureCodingMode(0);
cparams.SetTopFieldFirst(true);
- switch(cparams.GetVideoFormat())
+ switch (cparams.GetVideoFormat())
{
case VIDEO_FORMAT_QSIF525:
case VIDEO_FORMAT_QCIF:
@@ -98,11 +98,11 @@ void SetDefaultCodecParameters(CodecParams &cparams,
break;
}
- if(ptype == INTER_PICTURE)
+ if (ptype == INTER_PICTURE)
{
- ASSERTM(num_refs > 0 && num_refs < 3, "Number of reference frames should be 1 or 2 fo INTER frames");
+ ASSERTM (num_refs > 0 && num_refs < 3, "Number of reference frames should be 1 or 2 fo INTER frames" );
OLBParams bparams;
- PicturePredParams& predparams = cparams.GetPicPredParams();
+ PicturePredParams& predparams = cparams.GetPicPredParams();
predparams.SetUsingGlobalMotion(false);
SetDefaultBlockParameters(bparams, cparams.GetVideoFormat());
predparams.SetLumaBlockParams(bparams);
@@ -128,7 +128,7 @@ void SetDefaultSourceParameters(const VideoFormat &vf, SourceParams& sparams)
sparams.SetTopOffset(0);
sparams.SetColourSpecification(1);
- switch(vf)
+ switch (vf)
{
case VIDEO_FORMAT_CUSTOM:
sparams.SetXl(640);
@@ -228,7 +228,7 @@ void SetDefaultSourceParameters(const VideoFormat &vf, SourceParams& sparams)
sparams.SetXl(1280);
sparams.SetYl(720);
sparams.SetCFormat(format422);
- if(vf == VIDEO_FORMAT_HD_720P50)
+ if (vf == VIDEO_FORMAT_HD_720P50)
sparams.SetFrameRate(FRAMERATE_50_FPS);
else
sparams.SetFrameRate(FRAMERATE_59p94_FPS);
@@ -244,7 +244,7 @@ void SetDefaultSourceParameters(const VideoFormat &vf, SourceParams& sparams)
sparams.SetXl(1920);
sparams.SetYl(1080);
sparams.SetCFormat(format422);
- switch(vf)
+ switch (vf)
{
case VIDEO_FORMAT_HD_1080I60:
sparams.SetSourceSampling(1);
@@ -294,7 +294,7 @@ void SetDefaultSourceParameters(const VideoFormat &vf, SourceParams& sparams)
sparams.SetYl(2160);
sparams.SetCFormat(format422);
sparams.SetSourceSampling(0);
- switch(vf)
+ switch (vf)
{
case VIDEO_FORMAT_UHDTV_4K60:
sparams.SetFrameRate(FRAMERATE_59p94_FPS);
@@ -316,7 +316,7 @@ void SetDefaultSourceParameters(const VideoFormat &vf, SourceParams& sparams)
sparams.SetYl(4320);
sparams.SetCFormat(format422);
sparams.SetSourceSampling(0);
- switch(vf)
+ switch (vf)
{
case VIDEO_FORMAT_UHDTV_8K60:
sparams.SetFrameRate(FRAMERATE_59p94_FPS);
@@ -332,7 +332,7 @@ void SetDefaultSourceParameters(const VideoFormat &vf, SourceParams& sparams)
sparams.SetCleanHeight(4320);
sparams.SetColourSpecification(3);
break;
- default:
+ default:
errstr << "Unsupported video format " << sparams.GetVideoFormat()
<< std::endl;
DIRAC_THROW_EXCEPTION(
@@ -350,7 +350,7 @@ void SetDefaultEncoderParameters(EncoderParams& encparams)
encparams.GetPicPredParams().SetMVPrecision(MV_PRECISION_HALF_PIXEL);
encparams.SetUsingAC(true);
- switch(encparams.GetVideoFormat())
+ switch (encparams.GetVideoFormat())
{
case VIDEO_FORMAT_4SIF525:
case VIDEO_FORMAT_4CIF:
@@ -397,7 +397,7 @@ void SetDefaultEncoderParameters(EncoderParams& encparams)
void SetDefaultBlockParameters(OLBParams& bparams,
const VideoFormat& video_format)
{
- switch(video_format)
+ switch (video_format)
{
case VIDEO_FORMAT_QCIF:
case VIDEO_FORMAT_QSIF525:
@@ -453,7 +453,7 @@ void SetDefaultBlockParameters(OLBParams& bparams,
void SetDefaultBlockParameters(OLBParams& bparams, int pidx)
{
- switch(pidx)
+ switch (pidx)
{
case 0: // custom - so undefined values
return;
@@ -478,20 +478,20 @@ void SetDefaultBlockParameters(OLBParams& bparams, int pidx)
}
}
-unsigned int BlockParametersIndex(const OLBParams& bparams)
+unsigned int BlockParametersIndex (const OLBParams& bparams)
{
OLBParams bparams_1(8, 8, 4, 4);
OLBParams bparams_2(12, 12, 8, 8);
OLBParams bparams_3(16, 16, 12, 12);
OLBParams bparams_4(24, 24, 16, 16);
- if(bparams == bparams_1)
+ if (bparams == bparams_1)
return 1;
- else if(bparams == bparams_2)
+ else if (bparams == bparams_2)
return 2;
- else if(bparams == bparams_3)
+ else if (bparams == bparams_3)
return 3;
- else if(bparams == bparams_4)
+ else if (bparams == bparams_4)
return 4;
else
return 0;
@@ -500,7 +500,7 @@ unsigned int BlockParametersIndex(const OLBParams& bparams)
void SetDefaultTransformFilter(const PictureType ptype, const VideoFormat video_format,
WltFilter &wf)
{
- switch(video_format)
+ switch (video_format)
{
case VIDEO_FORMAT_QCIF:
case VIDEO_FORMAT_QSIF525:
@@ -524,7 +524,7 @@ void SetDefaultTransformFilter(const PictureType ptype, const VideoFormat video_
case VIDEO_FORMAT_UHDTV_8K60:
case VIDEO_FORMAT_UHDTV_8K50:
default:
- if(ptype == INTRA_PICTURE)
+ if (ptype == INTRA_PICTURE)
wf = DD13_7;
else
wf = DD13_7;
diff --git a/src/filters/parser/DiracSplitter/libdirac/libdirac_common/video_format_defaults.h b/src/filters/parser/DiracSplitter/libdirac/libdirac_common/video_format_defaults.h
index dde834389..97426a833 100644
--- a/src/filters/parser/DiracSplitter/libdirac/libdirac_common/video_format_defaults.h
+++ b/src/filters/parser/DiracSplitter/libdirac/libdirac_common/video_format_defaults.h
@@ -47,56 +47,56 @@
namespace dirac
{
-/**
-* Sets default codec parameters - common to encoder and decoder
-*@param cparams Codec Params objects for setting defaults
-*@param ptype Picture type i,e, INTRA or INTER
-*@param num_refs Number of reference frames
-*/
-void SetDefaultCodecParameters(CodecParams &cparams, PictureType ptype, unsigned int num_refs);
-
-/**
-* Sets default encoder parameters
-*@param encparams Params objects for setting defaults
-*/
-void SetDefaultEncoderParameters(EncoderParams& encparams);
-
-/**
-* Sets default Source parameters
-*@param vf Video Format
-*@param sparams Params object for setting defaults
-*/
-void SetDefaultSourceParameters(const VideoFormat &vf, SourceParams& sparams);
+ /**
+ * Sets default codec parameters - common to encoder and decoder
+ *@param cparams Codec Params objects for setting defaults
+ *@param ptype Picture type i,e, INTRA or INTER
+ *@param num_refs Number of reference frames
+ */
+ void SetDefaultCodecParameters (CodecParams &cparams, PictureType ptype, unsigned int num_refs);
+
+ /**
+ * Sets default encoder parameters
+ *@param encparams Params objects for setting defaults
+ */
+ void SetDefaultEncoderParameters(EncoderParams& encparams);
-/**
-* Sets default block parameters
-*@param bparams Params object for setting defaults
-*@param video_format Video format
-*/
-void SetDefaultBlockParameters(OLBParams& bparams,
- const VideoFormat& video_format);
+ /**
+ * Sets default Source parameters
+ *@param vf Video Format
+ *@param sparams Params object for setting defaults
+ */
+ void SetDefaultSourceParameters(const VideoFormat &vf, SourceParams& sparams);
-/**
-* Sets default block parameters
-*@param bparams Params object for setting defaults
-*@param pidx Index into Block Parameters table
-*/
-void SetDefaultBlockParameters(OLBParams& bparams,
- int pidx);
-/**
-* Returns index of block parameters in Defaults table
-*@param bparams Params object for getting index
-*/
-unsigned int BlockParametersIndex(const OLBParams& bparams);
+ /**
+ * Sets default block parameters
+ *@param bparams Params object for setting defaults
+ *@param video_format Video format
+ */
+ void SetDefaultBlockParameters(OLBParams& bparams,
+ const VideoFormat& video_format);
-/**
-* Sets the default Transform filter depending on picture type
-*@param ptype Picture type i.e. intra or inter
-*@param video_format The video format
-*@param wf WltFilter object for getting the default wavelet filter
-*/
-void SetDefaultTransformFilter(const PictureType ptype, const VideoFormat video_format,
- WltFilter &wf);
+ /**
+ * Sets default block parameters
+ *@param bparams Params object for setting defaults
+ *@param pidx Index into Block Parameters table
+ */
+ void SetDefaultBlockParameters(OLBParams& bparams,
+ int pidx);
+ /**
+ * Returns index of block parameters in Defaults table
+ *@param bparams Params object for getting index
+ */
+ unsigned int BlockParametersIndex(const OLBParams& bparams);
+
+ /**
+ * Sets the default Transform filter depending on picture type
+ *@param ptype Picture type i.e. intra or inter
+ *@param video_format The video format
+ *@param wf WltFilter object for getting the default wavelet filter
+ */
+ void SetDefaultTransformFilter( const PictureType ptype, const VideoFormat video_format,
+ WltFilter &wf);
} // namespace dirac
#endif
diff --git a/src/filters/parser/DiracSplitter/libdirac/libdirac_common/wavelet_utils.cpp b/src/filters/parser/DiracSplitter/libdirac/libdirac_common/wavelet_utils.cpp
index c4cf6081e..3a946d9c6 100644
--- a/src/filters/parser/DiracSplitter/libdirac/libdirac_common/wavelet_utils.cpp
+++ b/src/filters/parser/DiracSplitter/libdirac/libdirac_common/wavelet_utils.cpp
@@ -45,33 +45,31 @@ using namespace dirac;
// Default constructor
CodeBlock::CodeBlock()
- :
- m_skipped(false)
-{
- Init(0 , 0 , 0 , 0);
+:
+ m_skipped( false ){
+ Init( 0 , 0 , 0 , 0 );
}
// Constructor
-CodeBlock::CodeBlock(const int xstart ,
- const int ystart ,
- const int xend ,
- const int yend)
- :
- m_skipped(false)
+CodeBlock::CodeBlock( const int xstart ,
+ const int ystart ,
+ const int xend ,
+ const int yend)
+:
+ m_skipped( false )
{
- Init(xstart , ystart , xend , yend);
+ Init( xstart , ystart , xend , yend );
}
// Initialises the code block
-void CodeBlock::Init(const int xstart ,
- const int ystart ,
- const int xend ,
- const int yend)
-{
+void CodeBlock::Init( const int xstart ,
+ const int ystart ,
+ const int xend ,
+ const int yend ){
m_xstart = xstart;
m_xend = xend;
m_ystart = ystart;
- m_yend = yend;
+ m_yend= yend;
m_xl = xend - xstart;
m_yl = yend - ystart;
@@ -79,134 +77,127 @@ void CodeBlock::Init(const int xstart ,
// Default constructor
-Subband::Subband()
-{
+Subband::Subband(){
// this space intentionally left blank
}
// Constructor
-Subband::Subband(int xpos, int ypos, int xlen, int ylen):
- m_xp(xpos),
- m_yp(ypos),
- m_xl(xlen),
- m_yl(ylen),
- m_wt(1.0),
+Subband::Subband(int xpos,int ypos, int xlen, int ylen):
+ m_xp( xpos ),
+ m_yp( ypos ),
+ m_xl( xlen ),
+ m_yl( ylen ),
+ m_wt( 1.0 ),
m_code_block_array(),
- m_skipped(false)
-{
- SetNumBlocks(1 , 1);
+ m_skipped( false ){
+ SetNumBlocks( 1 , 1 );
}
// Constructor
-Subband::Subband(int xpos, int ypos, int xlen, int ylen, int d)
- :
- m_xp(xpos),
- m_yp(ypos),
- m_xl(xlen),
- m_yl(ylen),
- m_wt(1.0),
- m_depth(d),
+Subband::Subband(int xpos,int ypos, int xlen, int ylen, int d)
+ :
+ m_xp( xpos ),
+ m_yp( ypos ),
+ m_xl( xlen ),
+ m_yl( ylen ),
+ m_wt( 1.0 ),
+ m_depth( d ),
m_code_block_array(),
- m_skipped(false)
+ m_skipped( false )
{
- SetNumBlocks(1 , 1);
+ SetNumBlocks( 1 , 1 );
}
-void Subband::SetWt(const float w)
+void Subband::SetWt( const float w )
{
m_wt = w;
}
-void Subband::SetNumBlocks(const int ynum , const int xnum)
-{
- m_code_block_array.Resize(ynum , xnum);
+void Subband::SetNumBlocks( const int ynum , const int xnum){
+ m_code_block_array.Resize( ynum , xnum );
- OneDArray<int> xbounds(xnum + 1);
- OneDArray<int> ybounds(ynum + 1);
+ OneDArray<int> xbounds( xnum + 1 );
+ OneDArray<int> ybounds( ynum + 1 );
- for(int i = 0; i <= xnum ; ++i)
+ for (int i=0; i<=xnum ; ++i)
{
- xbounds[i] = (i * m_xl) / xnum + m_xp;
+ xbounds[i] = ( i * m_xl )/xnum + m_xp;
}// i
- for(int j = 0; j <= ynum ; ++j)
+ for (int j=0; j<=ynum ; ++j)
{
- ybounds[j] = (j * m_yl) / ynum + m_yp;
+ ybounds[j] = ( j * m_yl )/ynum + m_yp;
}// j
- for(int j = 0; j < m_code_block_array.LengthY() ; ++j)
- for(int i = 0; i < m_code_block_array.LengthX() ; ++i)
- m_code_block_array[j][i].Init(xbounds[i] , ybounds[j] ,
- xbounds[i+1] , ybounds[j+1]);
+ for (int j=0; j<m_code_block_array.LengthY() ; ++j)
+ for (int i=0; i<m_code_block_array.LengthX() ; ++i)
+ m_code_block_array[j][i].Init( xbounds[i] , ybounds[j] ,
+ xbounds[i+1] , ybounds[j+1] );
}
//! Destructor
-Subband::~Subband() {}
+Subband::~Subband(){}
//subband list methods
-void SubbandList::Init(const int depth, const int xlen, const int ylen)
-{
- int xl = xlen;
- int yl = ylen;
+void SubbandList::Init(const int depth,const int xlen,const int ylen){
+ int xl=xlen;
+ int yl=ylen;
Clear();
Subband* tmp;
- for(int level = 1; level <= depth; ++level)
- {
- xl /= 2;
- yl /= 2;
+ for (int level = 1; level <= depth; ++level){
+ xl/=2;
+ yl/=2;
/* HH */
- tmp = new Subband(xl , yl , xl , yl , level);
- AddBand(*tmp);
+ tmp=new Subband( xl , yl , xl , yl , level);
+ AddBand( *tmp );
delete tmp;
/* LH */
- tmp = new Subband(0 , yl , xl , yl , level);
- AddBand(*tmp);
+ tmp=new Subband( 0 , yl , xl , yl , level);
+ AddBand( *tmp );
delete tmp;
/* HL */
- tmp = new Subband(xl , 0 , xl , yl , level);
- AddBand(*tmp);
+ tmp=new Subband(xl , 0 , xl , yl , level);
+ AddBand( *tmp );
delete tmp;
- if(level == depth)
- {
+ if (level == depth){
/* LL */
- tmp = new Subband(0 , 0 , xl , yl , level);
- AddBand(*tmp);
+ tmp=new Subband( 0 , 0 , xl , yl , level);
+ AddBand( *tmp );
delete tmp;
}
}
//now set the parent-child relationships
int len = bands.size();
(*this)(len).SetParent(0);
- (*this)(len - 3).SetParent(0);
- (*this)(len - 2).SetParent(0);
- (*this)(len - 1).SetParent(0);
-
- for(int level = 2; level <= depth; ++level)
- {
- //do parent-child relationship for other bands
- (*this)(len - 3 *(level)).SetParent(len - 3 *(level - 1));
- (*this)(len - 3 *(level) + 1).SetParent(len - 3 *(level - 1) + 1);
- (*this)(len - 3 *(level) + 2).SetParent(len - 3 *(level - 1) + 2);
+ (*this)(len-3).SetParent(0);
+ (*this)(len-2).SetParent(0);
+ (*this)(len-1).SetParent(0);
+
+ for (int level = 2; level <= depth; ++level){
+ //do parent-child relationship for other bands
+ (*this)( len-3*(level) ).SetParent( len-3*(level-1) );
+ (*this)(len-3*(level)+1).SetParent(len-3*(level-1)+1);
+ (*this)(len-3*(level)+2).SetParent(len-3*(level-1)+2);
}// level
}
-void CoeffArray::SetBandWeights(const EncoderParams& encparams,
- const PictureParams& pparams,
- const CompSort csort,
- const float cpd_scale_factor)
+void CoeffArray::SetBandWeights (const EncoderParams& encparams,
+ const PictureParams& pparams,
+ const CompSort csort,
+ const float cpd_scale_factor)
{
const WltFilter wltfilter = encparams.TransformFilter();
const bool field_coding = encparams.FieldCoding();
const ChromaFormat cformat = pparams.CFormat();
- const float cpd = encparams.CPD() * cpd_scale_factor;
+ const float cpd = encparams.CPD()*cpd_scale_factor;
const PictureSort psort = pparams.PicSort();
int xlen, ylen, xl, yl, xp, yp;
@@ -217,14 +208,14 @@ void CoeffArray::SetBandWeights(const EncoderParams& encparams,
float chroma_xfac(1.0);
float chroma_yfac(1.0);
- if(csort != Y_COMP)
+ if( csort != Y_COMP)
{
- if(cformat == format422)
+ if( cformat == format422)
{
chroma_xfac = 2.0;
chroma_yfac = 1.0;
}
- else if(cformat == format420)
+ else if( cformat == format420 )
{
chroma_xfac = 2.0;
chroma_yfac = 2.0;
@@ -235,9 +226,9 @@ void CoeffArray::SetBandWeights(const EncoderParams& encparams,
xlen = 2 * m_band_list(1).Xl();
ylen = 2 * m_band_list(1).Yl();
- if(cpd != 0.0)
+ if (cpd != 0.0)
{
- for(int i = 1; i <= m_band_list.Length() ; i++)
+ for( int i = 1; i<=m_band_list.Length() ; i++ )
{
xp = m_band_list(i).Xp();
yp = m_band_list(i).Yp();
@@ -245,50 +236,49 @@ void CoeffArray::SetBandWeights(const EncoderParams& encparams,
yl = m_band_list(i).Yl();
- xfreq = cpd * (float(xp) + (float(xl) / 2.0)) / float(xlen);
- yfreq = cpd * (float(yp) + (float(yl) / 2.0)) / float(ylen);
+ xfreq = cpd * ( float(xp) + (float(xl)/2.0) ) / float(xlen);
+ yfreq = cpd * ( float(yp) + (float(yl)/2.0) ) / float(ylen);
if(field_coding)
- yfreq /= 2.0;
+ yfreq/=2.0;
- temp = PerceptualWeight(xfreq / chroma_xfac , yfreq / chroma_yfac , csort);
+ temp = PerceptualWeight( xfreq/chroma_xfac , yfreq/chroma_yfac , csort );
m_band_list(i).SetWt(temp);
}// i
// Make sure dc is always the lowest weight
- float min_weight = m_band_list(m_band_list.Length()).Wt();
+ float min_weight=m_band_list(m_band_list.Length()).Wt();
- for(int b = 1 ; b <= m_band_list.Length() - 1 ; b++)
- min_weight = ((min_weight > m_band_list(b).Wt()) ? m_band_list(b).Wt() : min_weight);
+ for( int b=1 ; b<=m_band_list.Length()-1 ; b++ )
+ min_weight = ((min_weight>m_band_list(b).Wt()) ? m_band_list(b).Wt() : min_weight);
- m_band_list(m_band_list.Length()).SetWt(min_weight);
+ m_band_list( m_band_list.Length() ).SetWt( min_weight );
// Now normalize weights so that white noise is always weighted the same
// Overall factor to ensure that white noise ends up with the same RMS, whatever the weight
- double overall_factor = 0.0;
+ double overall_factor=0.0;
//fraction of the total number of samples belonging to each subband
double subband_fraction;
- for(int i = 1 ; i <= m_band_list.Length() ; i++)
+ for( int i=1 ; i<=m_band_list.Length() ; i++ )
{
- subband_fraction = 1.0 / ((double) m_band_list(i).Scale() * m_band_list(i).Scale());
- overall_factor += subband_fraction / (m_band_list(i).Wt() * m_band_list(i).Wt());
+ subband_fraction = 1.0/((double) m_band_list(i).Scale() * m_band_list(i).Scale());
+ overall_factor += subband_fraction/( m_band_list(i).Wt() * m_band_list(i).Wt() );
}
- overall_factor = std::sqrt(overall_factor);
+ overall_factor = std::sqrt( overall_factor );
//go through and normalise
- for(int i = m_band_list.Length() ; i > 0 ; i--)
- m_band_list(i).SetWt(m_band_list(i).Wt() * overall_factor);
+ for( int i=m_band_list.Length() ; i>0 ; i-- )
+ m_band_list(i).SetWt( m_band_list(i).Wt() * overall_factor );
}
else
- {
- //cpd=0 so set all weights to 1
+ {//cpd=0 so set all weights to 1
- for(int i = 1 ; i <= m_band_list.Length() ; i++)
- m_band_list(i).SetWt(1.0);
+ for( int i=1 ; i<=m_band_list.Length() ; i++ )
+ m_band_list(i).SetWt( 1.0 );
}
@@ -298,93 +288,92 @@ void CoeffArray::SetBandWeights(const EncoderParams& encparams,
double hfac;
int filt_shift;
- switch(wltfilter)
- {
- case DD9_7 :
- lfac = 1.218660804;
- hfac = 0.780720058;
- filt_shift = 1;
-
- break;
-
- case LEGALL5_3 :
- lfac = 1.179535649;
- hfac = 0.81649658;
- filt_shift = 1;
-
- break;
-
- case DD13_7 :
- lfac = 1.235705971;
- hfac = 0.780719354;
- filt_shift = 1;
-
- break;
-
- case HAAR0 :
- lfac = 1.414213562;
- hfac = 0.707106781;
- filt_shift = 0;
-
- break;
-
- case HAAR1 :
- lfac = 1.414213562;
- hfac = 0.707106781;
- filt_shift = 1;
-
- break;
-
- case DAUB9_7 :
- lfac = 1.149604398;
- hfac = 0.869864452;
- filt_shift = 1;
-
- break;
-
- default:
- lfac = 1.0;
- hfac = 1.0;
- filt_shift = 0;
+ switch (wltfilter){
+ case DD9_7 :
+ lfac = 1.218660804;
+ hfac = 0.780720058;
+ filt_shift = 1;
+
+ break;
+
+ case LEGALL5_3 :
+ lfac = 1.179535649;
+ hfac = 0.81649658;
+ filt_shift = 1;
+
+ break;
+
+ case DD13_7 :
+ lfac = 1.235705971;
+ hfac = 0.780719354;
+ filt_shift = 1;
+
+ break;
+
+ case HAAR0 :
+ lfac = 1.414213562;
+ hfac = 0.707106781;
+ filt_shift = 0;
+
+ break;
+
+ case HAAR1 :
+ lfac = 1.414213562;
+ hfac = 0.707106781;
+ filt_shift = 1;
+
+ break;
+
+ case DAUB9_7 :
+ lfac = 1.149604398;
+ hfac = 0.869864452;
+ filt_shift = 1;
+
+ break;
+
+ default:
+ lfac = 1.0;
+ hfac = 1.0;
+ filt_shift = 0;
}
int idx;
int shift;
- int depth = (m_band_list.Length() - 1) / 3;
+ int depth = (m_band_list.Length()-1)/3;
// Do the DC subband
idx = m_band_list.Length();
- double cf = (1 << (depth * filt_shift)) / std::pow(lfac, 2 * depth) ;
+ double cf = (1<<(depth*filt_shift)) / std::pow(lfac,2*depth ) ;
- m_band_list(idx).SetWt(m_band_list(idx).Wt()*cf);
+ m_band_list(idx).SetWt( m_band_list(idx).Wt()*cf);
// Do the non-DC subbands
- for(int level = 1; level <= depth; level++)
+ for (int level=1; level<=depth; level++)
{
- shift = (depth - level + 1) * filt_shift;
- for(int orient = 3; orient >= 1; --orient)
+ shift = (depth-level+1)*filt_shift;
+ for ( int orient=3;orient>=1; --orient )
{
- idx = 3 * (depth - level) + orient;
+ idx = 3*(depth-level)+orient;
// index into the subband list
- idx = 3 * (depth - level) + orient;
+ idx = 3*(depth-level)+orient;
// Divide through by the weight for the LF subband that was decomposed
// to create this level
- cf = 1.0 / std::pow(lfac, 2 * (depth - level));
+ cf = 1.0/ std::pow(lfac,2*(depth-level) );
- if(m_band_list(idx).Xp() != 0 && m_band_list(idx).Yp() != 0)
+ if ( m_band_list(idx).Xp() != 0 && m_band_list(idx).Yp() != 0)
// HH subband
cf /= (hfac * hfac);
else
// LH or HL subband
cf /= (lfac * hfac);
- cf *= double(1 << shift);
+ cf *= double(1<<shift);
- m_band_list(idx).SetWt(m_band_list(idx).Wt()*cf);
+ m_band_list(idx).SetWt( m_band_list(idx).Wt()*cf );
}// orient
}//level
@@ -394,16 +383,16 @@ void CoeffArray::SetBandWeights(const EncoderParams& encparams,
// Returns a perceptual noise weighting based on extending CCIR 959 values
// assuming a two-d isotropic response. Also has a fudge factor of 20% for chroma
-float CoeffArray::PerceptualWeight(const float xf ,
- const float yf ,
- const CompSort cs)
+float CoeffArray::PerceptualWeight( const float xf ,
+ const float yf ,
+ const CompSort cs )
{
- double freq_sqd(xf * xf + yf * yf);
+ double freq_sqd( xf*xf + yf*yf );
- if(cs != Y_COMP)
+ if ( cs != Y_COMP )
freq_sqd *= 1.2;
- return 0.255 * std::pow(1.0 + 0.2561 * freq_sqd , 0.75) ;
+ return 0.255 * std::pow( 1.0 + 0.2561*freq_sqd , 0.75) ;
}
@@ -415,11 +404,10 @@ float CoeffArray::PerceptualWeight(const float xf ,
//public methods
WaveletTransform::WaveletTransform(int d, WltFilter f)
- : m_depth(d),
- m_filt_sort(f)
+ : m_depth(d),
+ m_filt_sort(f)
{
- switch(m_filt_sort)
- {
+ switch( m_filt_sort ){
case DD9_7 :
m_vhfilter = new VHFilterDD9_7;
@@ -447,61 +435,50 @@ WaveletTransform::WaveletTransform(int d, WltFilter f)
}
//! Destructor
-WaveletTransform::~WaveletTransform()
-{
- delete m_vhfilter;
-}
+WaveletTransform::~WaveletTransform(){ delete m_vhfilter; }
-void WaveletTransform::Transform(const Direction d, PicArray& pic_data, CoeffArray& coeff_data)
-{
+void WaveletTransform::Transform(const Direction d, PicArray& pic_data, CoeffArray& coeff_data) {
- int xl, yl;
+ int xl,yl;
SubbandList& bands = coeff_data.BandList();
- if(d == FORWARD)
- {
- xl = coeff_data.LengthX();
- yl = coeff_data.LengthY();
+ if (d == FORWARD){
+ xl=coeff_data.LengthX();
+ yl=coeff_data.LengthY();
// First copy picture data into coeff_data and pad
- for(int j = 0; j < pic_data.LengthY(); ++j)
- {
- for(int i = 0; i < pic_data.LengthX(); ++i)
- coeff_data[j][i] = CoeffType(pic_data[j][i]);
- for(int i = pic_data.LengthX(); i < coeff_data.LengthX(); ++i)
+ for ( int j=0; j<pic_data.LengthY(); ++j){
+ for ( int i=0; i<pic_data.LengthX(); ++i)
+ coeff_data[j][i] = CoeffType( pic_data[j][i] );
+ for ( int i=pic_data.LengthX(); i<coeff_data.LengthX(); ++i)
coeff_data[j][i] = coeff_data[j][pic_data.LastX()];
}// j
- for(int j = pic_data.LengthY(); j < coeff_data.LengthY(); ++j)
- {
- for(int i = 0; i < coeff_data.LengthX(); ++i)
+ for ( int j=pic_data.LengthY(); j<coeff_data.LengthY(); ++j){
+ for ( int i=0; i<coeff_data.LengthX(); ++i)
coeff_data[j][i] = coeff_data[pic_data.LastY()][i];
}
- for(int l = 1; l <= m_depth; ++l , xl >>= 1 , yl >>= 1)
- {
- m_vhfilter->Split(0, 0, xl, yl, coeff_data);
+ for (int l = 1; l <= m_depth; ++l , xl>>=1 , yl>>=1){
+ m_vhfilter->Split(0,0,xl,yl,coeff_data);
}
- bands.Init(m_depth , coeff_data.LengthX() , coeff_data.LengthY());
+ bands.Init( m_depth , coeff_data.LengthX() , coeff_data.LengthY() );
}
- else
- {
- xl = coeff_data.LengthX() / (1 << (m_depth - 1));
- yl = coeff_data.LengthY() / (1 << (m_depth - 1));
-
- for(int l = 1; l <= m_depth; ++l, xl <<= 1 , yl <<= 1)
- m_vhfilter->Synth(0, 0, xl, yl, coeff_data);
+ else{
+ xl = coeff_data.LengthX()/(1<<(m_depth-1));
+ yl = coeff_data.LengthY()/(1<<(m_depth-1));
+ for (int l = 1; l <= m_depth; ++l, xl<<=1 , yl<<=1 )
+ m_vhfilter->Synth(0,0,xl,yl,coeff_data);
+
//band list now inaccurate, so clear
bands.Clear();
- // Lastly, copy coeff_data back into picture data
- for(int j = 0; j < pic_data.LengthY(); ++j)
- {
- for(int i = 0; i < pic_data.LengthX(); ++i)
- {
- pic_data[j][i] = ValueType(coeff_data[j][i]);
+ // Lastly, copy coeff_data back into picture data
+ for ( int j=0; j<pic_data.LengthY(); ++j){
+ for ( int i=0; i<pic_data.LengthX(); ++i){
+ pic_data[j][i] = ValueType( coeff_data[j][i] );
}// i
}// j
}
@@ -511,35 +488,35 @@ void WaveletTransform::Transform(const Direction d, PicArray& pic_data, CoeffArr
///////////////////////
// NOTEL MMX version is defined in wavelet_utils_mmx.cpp
// the corresponding changes are made in wavelet_utils_mmx.cpp as well
-void VHFilter::Interleave(const int xp ,
- const int yp ,
- const int xl ,
- const int yl ,
- CoeffArray& coeff_data)
+void VHFilter::Interleave( const int xp ,
+ const int yp ,
+ const int xl ,
+ const int yl ,
+ CoeffArray& coeff_data)
{
- TwoDArray<CoeffType> temp_data(yl , xl);
- const int xl2(xl >> 1);
- const int yl2(yl >> 1);
- const int yend(yp + yl);
+ TwoDArray<CoeffType> temp_data( yl , xl );
+ const int xl2( xl>>1);
+ const int yl2( yl>>1);
+ const int yend( yp + yl );
// Make a temporary copy of the subband
- for(int j = yp; j < yend ; j++)
- memcpy(temp_data[j-yp] , coeff_data[j] + xp , xl * sizeof(CoeffType));
+ for (int j = yp; j<yend ; j++ )
+ memcpy( temp_data[j-yp] , coeff_data[j]+xp , xl * sizeof( CoeffType ) );
// Re-order to interleave
- for(int j = 0, s = yp; j < yl2 ; j++, s += 2)
+ for (int j = 0, s=yp; j<yl2 ; j++, s+=2)
{
- for(int i = 0 , r = xp ; i < xl2 ; i++ , r += 2)
+ for (int i = 0 , r=xp ; i<xl2 ; i++ , r += 2)
coeff_data[s][r] = temp_data[j][i];
- for(int i = xl2, r = xp + 1; i < xl ; i++ , r += 2)
+ for (int i = xl2, r=xp+1; i<xl ; i++ , r += 2)
coeff_data[s][r] = temp_data[j][i];
}// j
- for(int j = yl2, s = yp + 1 ; j < yl ; j++ , s += 2)
+ for (int j = yl2, s=yp+1 ; j<yl ; j++ , s += 2)
{
- for(int i = 0 , r = xp ; i < xl2 ; i++ , r += 2)
+ for (int i = 0 , r=xp ; i<xl2 ; i++ , r += 2)
coeff_data[s][r] = temp_data[j][i];
- for(int i = xl2, r = xp + 1; i < xl ; i++ , r += 2)
+ for (int i = xl2, r=xp+1; i<xl ; i++ , r += 2)
coeff_data[s][r] = temp_data[j][i];
}// j
@@ -548,67 +525,67 @@ void VHFilter::Interleave(const int xp ,
#if !defined(HAVE_MMX)
void VHFilter::ShiftRowLeft(CoeffType *row, int length, int shift)
{
- for(int i = 0; i < length; ++i)
+ for (int i = 0; i < length; ++i)
row[i] <<= shift;
}
void VHFilter::ShiftRowRight(CoeffType *row, int length, int shift)
{
- const CoeffType halfway(1 << (shift - 1));
- for(int i = 0; i < length; ++i)
- row[i] = ((row[i] + halfway) >> shift);
+ const CoeffType halfway( 1<<(shift-1) );
+ for (int i = 0; i < length; ++i)
+ row[i] = ((row[i]+halfway)>>shift);
}
#endif
-void VHFilter::DeInterleave(const int xp ,
- const int yp ,
- const int xl ,
- const int yl ,
- CoeffArray& coeff_data)
+void VHFilter::DeInterleave( const int xp ,
+ const int yp ,
+ const int xl ,
+ const int yl ,
+ CoeffArray& coeff_data)
{
- TwoDArray<CoeffType> temp_data(yl , xl);
- const int xl2(xl >> 1);
- const int yl2(yl >> 1);
- const int xend(xp + xl);
- const int yend(yp + yl);
+ TwoDArray<CoeffType> temp_data( yl , xl );
+ const int xl2( xl>>1);
+ const int yl2( yl>>1);
+ const int xend( xp + xl );
+ const int yend( yp + yl );
// Make a temporary copy of the subband
- for(int j = yp; j < yend ; j++)
- memcpy(temp_data[j-yp] , coeff_data[j] + xp , xl * sizeof(CoeffType));
+ for (int j = yp; j<yend ; j++ )
+ memcpy( temp_data[j-yp] , coeff_data[j]+xp , xl * sizeof( CoeffType ) );
// Re-order to de-interleave
- for(int j = yp, s = 0; j < yp + yl2 ; j++, s += 2)
+ for (int j = yp, s=0; j<yp+yl2 ; j++, s+=2)
{
- for(int i = xp , r = 0 ; i < xp + xl2 ; i++ , r += 2)
+ for (int i = xp , r=0 ; i<xp+xl2 ; i++ , r += 2)
coeff_data[j][i] = temp_data[s][r];
- for(int i = xp + xl2, r = 1; i < xend ; i++ , r += 2)
+ for (int i = xp+xl2, r=1; i<xend ; i++ , r += 2)
coeff_data[j][i] = temp_data[s][r];
}// j
- for(int j = yp + yl2, s = 1 ; j < yend ; j++ , s += 2)
+ for (int j = yp+yl2, s=1 ; j<yend ; j++ , s += 2)
{
- for(int i = xp , r = 0 ; i < xp + xl2 ; i++ , r += 2)
+ for (int i = xp , r=0 ; i<xp+xl2 ; i++ , r += 2)
coeff_data[j][i] = temp_data[s][r];
- for(int i = xp + xl2, r = 1; i < xend ; i++ , r += 2)
+ for (int i = xp+xl2, r=1; i<xend ; i++ , r += 2)
coeff_data[j][i] = temp_data[s][r];
}// j
}
-void VHFilterDAUB9_7::Split(const int xp ,
- const int yp ,
- const int xl ,
- const int yl ,
- CoeffArray& coeff_data)
+void VHFilterDAUB9_7::Split (const int xp ,
+ const int yp ,
+ const int xl ,
+ const int yl ,
+ CoeffArray& coeff_data)
{
- const int xend = xp + xl;
- const int yend = yp + yl;
+ const int xend=xp+xl;
+ const int yend=yp+yl;
CoeffType* line_data;
// Positional variables
- int i, j, k;
+ int i,j,k;
// Objects to do lifting stages
// (in revese order and type from synthesis)
@@ -617,41 +594,41 @@ void VHFilterDAUB9_7::Split(const int xp ,
const UpdateStep97< 3616 > updateA;
const UpdateStep97< 1817 > updateB;
- //first do horizontal
+ //first do horizontal
- for(j = yp; j < yend; ++j)
+ for (j = yp; j < yend; ++j)
{
// First lifting stage
line_data = coeff_data[j];
// Shift left by one bit to give us more accuracy
ShiftRowLeft(line_data, xl, 1);
- predictA.Filter(line_data[xp+1] , line_data[xp+2] , line_data[xp]);
- predictB.Filter(line_data[xp] , line_data[xp+1] , line_data[xp+1]);
+ predictA.Filter( line_data[xp+1] , line_data[xp+2] , line_data[xp] );
+ predictB.Filter( line_data[xp] , line_data[xp+1] , line_data[xp+1] );
- for(k = xp + 3; k < xend - 1; k += 2)
+ for ( k = xp+3; k < xend-1; k+=2)
{
- predictA.Filter(line_data[k] , line_data[k+1] , line_data[k-1]);
- predictB.Filter(line_data[k-1] , line_data[k-2] , line_data[k]);
+ predictA.Filter( line_data[k] , line_data[k+1] , line_data[k-1] );
+ predictB.Filter( line_data[k-1] , line_data[k-2] , line_data[k] );
}// i
- predictA.Filter(line_data[xend-1] , line_data[xend-2] , line_data[xend-2]);
- predictB.Filter(line_data[xend-2] , line_data[xend-3] , line_data[xend-1]);
+ predictA.Filter( line_data[xend-1] , line_data[xend-2] , line_data[xend-2] );
+ predictB.Filter( line_data[xend-2] , line_data[xend-3] , line_data[xend-1] );
- //second lifting stage
+ //second lifting stage
- updateA.Filter(line_data[xp+1] , line_data[xp+2] , line_data[xp]);
- updateB.Filter(line_data[xp] , line_data[xp+1] , line_data[xp+1]);
+ updateA.Filter( line_data[xp+1] , line_data[xp+2] , line_data[xp] );
+ updateB.Filter( line_data[xp] , line_data[xp+1] , line_data[xp+1] );
- for(k = xp + 3; k < xend - 1; k += 2)
+ for ( k = xp+3; k < xend-1; k+=2)
{
- updateA.Filter(line_data[k] , line_data[k+1] , line_data[k-1]);
- updateB.Filter(line_data[k-1] , line_data[k-2] , line_data[k]);
+ updateA.Filter( line_data[k] , line_data[k+1] , line_data[k-1] );
+ updateB.Filter( line_data[k-1] , line_data[k-2] , line_data[k] );
}// i
- updateA.Filter(line_data[xend-1] , line_data[xend-2] , line_data[xend-2]);
- updateB.Filter(line_data[xend-2] , line_data[xend-3] , line_data[xend-1]);
+ updateA.Filter( line_data[xend-1] , line_data[xend-2] , line_data[xend-2] );
+ updateB.Filter( line_data[xend-2] , line_data[xend-3] , line_data[xend-1] );
}// j
@@ -660,69 +637,69 @@ void VHFilterDAUB9_7::Split(const int xp ,
// First lifting stage
// top edge - j=xp
- for(i = xp ; i < xend ; ++ i)
+ for ( i = xp ; i<xend ; ++ i)
{
- predictA.Filter(coeff_data[yp+1][i] , coeff_data[yp+2][i] , coeff_data[yp][i]);
- predictB.Filter(coeff_data[yp][i] , coeff_data[yp+1][i] , coeff_data[yp+1][i]);
+ predictA.Filter( coeff_data[yp+1][i] , coeff_data[yp+2][i] , coeff_data[yp][i] );
+ predictB.Filter( coeff_data[yp][i] , coeff_data[yp+1][i] , coeff_data[yp+1][i] );
}// i
// middle bit
- for(k = yp + 3 ; k < yend - 1 ; k += 2)
+ for ( k = yp+3 ; k<yend-1 ; k+=2)
{
- for(i = xp ; i < xend ; ++ i)
+ for ( i = xp ; i<xend ; ++ i)
{
- predictA.Filter(coeff_data[k][i] , coeff_data[k+1][i] , coeff_data[k-1][i]);
- predictB.Filter(coeff_data[k-1][i] , coeff_data[k-2][i] , coeff_data[k][i]);
+ predictA.Filter( coeff_data[k][i] , coeff_data[k+1][i] , coeff_data[k-1][i] );
+ predictB.Filter( coeff_data[k-1][i] , coeff_data[k-2][i] , coeff_data[k][i] );
}// i
}// j
// bottom edge
- for(i = xp ; i < xend ; ++ i)
+ for ( i = xp ; i<xend ; ++ i)
{
- predictA.Filter(coeff_data[yend-1][i] , coeff_data[yend-2][i] , coeff_data[yend-2][i]);
- predictB.Filter(coeff_data[yend-2][i] , coeff_data[yend-3][i] , coeff_data[yend-1][i]);
+ predictA.Filter( coeff_data[yend-1][i] , coeff_data[yend-2][i] , coeff_data[yend-2][i] );
+ predictB.Filter( coeff_data[yend-2][i] , coeff_data[yend-3][i] , coeff_data[yend-1][i] );
}// i
// Second lifting stage
// top edge - j=xp
- for(i = xp ; i < xend ; ++ i)
+ for ( i = xp ; i<xend ; ++ i)
{
- updateA.Filter(coeff_data[yp+1][i] , coeff_data[yp+2][i] , coeff_data[yp][i]);
- updateB.Filter(coeff_data[yp][i] , coeff_data[yp+1][i] , coeff_data[yp+1][i]);
+ updateA.Filter( coeff_data[yp+1][i] , coeff_data[yp+2][i] , coeff_data[yp][i] );
+ updateB.Filter( coeff_data[yp][i] , coeff_data[yp+1][i] , coeff_data[yp+1][i] );
}// i
// middle bit
- for(k = yp + 3 ; k < yend - 1 ; k += 2)
+ for ( k = yp+3 ; k<yend-1 ; k+=2)
{
- for(i = xp ; i < xend ; ++ i)
+ for ( i = xp ; i<xend ; ++ i)
{
- updateA.Filter(coeff_data[k][i] , coeff_data[k+1][i] , coeff_data[k-1][i]);
- updateB.Filter(coeff_data[k-1][i] , coeff_data[k-2][i] , coeff_data[k][i]);
+ updateA.Filter( coeff_data[k][i] , coeff_data[k+1][i] , coeff_data[k-1][i] );
+ updateB.Filter( coeff_data[k-1][i] , coeff_data[k-2][i] , coeff_data[k][i] );
}// i
}// j
// bottom edge
- for(i = xp ; i < xend ; ++ i)
+ for ( i = xp ; i<xend ; ++ i)
{
- updateA.Filter(coeff_data[yend-1][i] , coeff_data[yend-2][i] , coeff_data[yend-2][i]);
- updateB.Filter(coeff_data[yend-2][i] , coeff_data[yend-3][i] , coeff_data[yend-1][i]);
+ updateA.Filter( coeff_data[yend-1][i] , coeff_data[yend-2][i] , coeff_data[yend-2][i] );
+ updateB.Filter( coeff_data[yend-2][i] , coeff_data[yend-3][i] , coeff_data[yend-1][i] );
}// i
// Lastly, have to reorder so that subbands are no longer interleaved
- DeInterleave(xp , yp , xl , yl , coeff_data);
+ DeInterleave( xp ,yp ,xl ,yl , coeff_data );
}
-void VHFilterDAUB9_7::Synth(const int xp ,
- const int yp ,
- const int xl ,
- const int yl ,
- CoeffArray& coeff_data)
+void VHFilterDAUB9_7::Synth (const int xp ,
+ const int yp ,
+ const int xl ,
+ const int yl ,
+ CoeffArray& coeff_data)
{
- int i, j, k;
+ int i,j,k;
- const int xend(xp + xl);
- const int yend(yp + yl);
+ const int xend( xp+xl );
+ const int yend( yp+yl );
const PredictStep97< 1817 > predictB;
const PredictStep97< 3616 > predictA;
@@ -732,89 +709,89 @@ void VHFilterDAUB9_7::Synth(const int xp ,
CoeffType* line_data;
// Firstly reorder to interleave subbands, so that subsequent calculations can be in-place
- Interleave(xp , yp , xl , yl , coeff_data);
+ Interleave( xp , yp , xl , yl , coeff_data );
// Next, do the vertical synthesis
// First lifting stage
// Begin with the bottom edge
- for(i = xend - 1 ; i >= xp ; --i)
+ for ( i = xend-1 ; i>=xp ; --i)
{
- predictB.Filter(coeff_data[yend-2][i] , coeff_data[yend-3][i] , coeff_data[yend-1][i]);
- predictA.Filter(coeff_data[yend-1][i] , coeff_data[yend-2][i] , coeff_data[yend-2][i]);
+ predictB.Filter( coeff_data[yend-2][i] , coeff_data[yend-3][i] , coeff_data[yend-1][i] );
+ predictA.Filter( coeff_data[yend-1][i] , coeff_data[yend-2][i] , coeff_data[yend-2][i] );
}// i
// Next, do the middle bit
- for(k = yend - 3 ; k > yp + 1 ; k -= 2)
+ for ( k = yend-3 ; k>yp+1 ; k-=2)
{
- for(i = xend - 1 ; i >= xp ; --i)
+ for ( i = xend-1 ; i>=xp ; --i)
{
- predictB.Filter(coeff_data[k-1][i] , coeff_data[k-2][i] , coeff_data[k][i]);
- predictA.Filter(coeff_data[k][i] , coeff_data[k+1][i] , coeff_data[k-1][i]);
+ predictB.Filter( coeff_data[k-1][i] , coeff_data[k-2][i] , coeff_data[k][i] );
+ predictA.Filter( coeff_data[k][i] , coeff_data[k+1][i] , coeff_data[k-1][i] );
}// i
}// j
// Then do the top edge
- for(i = xend - 1 ; i >= xp ; --i)
+ for ( i = xend-1 ; i>=xp ; --i)
{
- predictB.Filter(coeff_data[yp][i] , coeff_data[yp+1][i] , coeff_data[yp+1][i]);
- predictA.Filter(coeff_data[yp+1][i] , coeff_data[yp+2][i] , coeff_data[yp][i]);
+ predictB.Filter( coeff_data[yp][i] , coeff_data[yp+1][i] , coeff_data[yp+1][i] );
+ predictA.Filter( coeff_data[yp+1][i] , coeff_data[yp+2][i] , coeff_data[yp][i] );
}// i
// Second lifting stage
// Begin with the bottom edge
- for(i = xend - 1 ; i >= xp ; --i)
+ for ( i = xend-1 ; i>=xp ; --i)
{
- updateB.Filter(coeff_data[yend-2][i] , coeff_data[yend-3][i] , coeff_data[yend-1][i]);
- updateA.Filter(coeff_data[yend-1][i] , coeff_data[yend-2][i] , coeff_data[yend-2][i]);
+ updateB.Filter( coeff_data[yend-2][i] , coeff_data[yend-3][i] , coeff_data[yend-1][i] );
+ updateA.Filter( coeff_data[yend-1][i] , coeff_data[yend-2][i] , coeff_data[yend-2][i] );
}// i
// Next, do the middle bit
- for(k = yend - 3 ; k > yp + 1 ; k -= 2)
+ for ( k = yend-3 ; k>yp+1 ; k-=2)
{
- for(i = xend - 1 ; i >= xp ; --i)
+ for ( i = xend-1 ; i>=xp ; --i)
{
- updateB.Filter(coeff_data[k-1][i] , coeff_data[k-2][i] , coeff_data[k][i]);
- updateA.Filter(coeff_data[k][i] , coeff_data[k+1][i] , coeff_data[k-1][i]);
+ updateB.Filter( coeff_data[k-1][i] , coeff_data[k-2][i] , coeff_data[k][i] );
+ updateA.Filter( coeff_data[k][i] , coeff_data[k+1][i] , coeff_data[k-1][i] );
}// i
}// j
// Then do the top edge
- for(i = xend - 1 ; i >= xp ; --i)
+ for ( i = xend-1 ; i>=xp ; --i)
{
- updateB.Filter(coeff_data[yp][i] , coeff_data[yp+1][i] , coeff_data[yp+1][i]);
- updateA.Filter(coeff_data[yp+1][i] , coeff_data[yp+2][i] , coeff_data[yp][i]);
+ updateB.Filter( coeff_data[yp][i] , coeff_data[yp+1][i] , coeff_data[yp+1][i] );
+ updateA.Filter( coeff_data[yp+1][i] , coeff_data[yp+2][i] , coeff_data[yp][i] );
}// i
// Next do the horizontal synthesis
- for(j = yend - 1; j >= yp ; --j)
+ for (j = yend-1; j >= yp ; --j)
{
// First lifting stage
line_data = coeff_data[j];
- predictB.Filter(line_data[xend-2] , line_data[xend-3] , line_data[xend-1]);
- predictA.Filter(line_data[xend-1] , line_data[xend-2] , line_data[xend-2]);
+ predictB.Filter( line_data[xend-2] , line_data[xend-3] , line_data[xend-1] );
+ predictA.Filter( line_data[xend-1] , line_data[xend-2] , line_data[xend-2] );
- for(k = xend - 3; k > xp + 1; k -= 2)
+ for ( k = xend-3; k > xp+1; k-=2)
{
- predictB.Filter(line_data[k-1] , line_data[k-2] , line_data[k]);
- predictA.Filter(line_data[k] , line_data[k+1] , line_data[k-1]);
+ predictB.Filter( line_data[k-1] , line_data[k-2] , line_data[k] );
+ predictA.Filter( line_data[k] , line_data[k+1] , line_data[k-1] );
}// i
- predictB.Filter(line_data[xp] , line_data[xp+1] , line_data[xp+1]);
- predictA.Filter(line_data[xp+1] , line_data[xp+2] , line_data[xp]);
+ predictB.Filter( line_data[xp] , line_data[xp+1] , line_data[xp+1] );
+ predictA.Filter( line_data[xp+1] , line_data[xp+2] , line_data[xp] );
// Second lifting stage
- updateB.Filter(line_data[xend-2] , line_data[xend-3] , line_data[xend-1]);
- updateA.Filter(line_data[xend-1] , line_data[xend-2] , line_data[xend-2]);
+ updateB.Filter( line_data[xend-2] , line_data[xend-3] , line_data[xend-1] );
+ updateA.Filter( line_data[xend-1] , line_data[xend-2] , line_data[xend-2] );
- for(k = xend - 3; k > xp + 1; k -= 2)
+ for ( k = xend-3; k > xp+1; k-=2)
{
- updateB.Filter(line_data[k-1] , line_data[k-2] , line_data[k]);
- updateA.Filter(line_data[k] , line_data[k+1] , line_data[k-1]);
+ updateB.Filter( line_data[k-1] , line_data[k-2] , line_data[k] );
+ updateA.Filter( line_data[k] , line_data[k+1] , line_data[k-1] );
}// i
- updateB.Filter(line_data[xp] , line_data[xp+1] , line_data[xp+1]);
- updateA.Filter(line_data[xp+1] , line_data[xp+2] , line_data[xp]);
+ updateB.Filter( line_data[xp] , line_data[xp+1] , line_data[xp+1] );
+ updateA.Filter( line_data[xp+1] , line_data[xp+2] , line_data[xp] );
// Shift right by one bit to counter the shift in the analysis stage
ShiftRowRight(line_data, xl, 1);
@@ -826,45 +803,45 @@ void VHFilterDAUB9_7::Synth(const int xp ,
// NOTE: MMX version is defined in wavelet_utils_mmx.cpp
// the corresponding changes are made in wavelet_utils_mmx.cpp as well
void VHFilterLEGALL5_3::Split(const int xp ,
- const int yp ,
- const int xl ,
- const int yl ,
- CoeffArray& coeff_data)
+ const int yp ,
+ const int xl ,
+ const int yl ,
+ CoeffArray& coeff_data)
{
- const int xend = xp + xl;
- const int yend = yp + yl;
+ const int xend=xp+xl;
+ const int yend=yp+yl;
CoeffType* line_data;
// Positional variables
- int i, j, k;
+ int i,j,k;
// Objects to do lifting stages
// (in revese order and type from synthesis)
const PredictStepShift< 1 > predict;
const UpdateStepShift< 2 > update;
- //first do horizontal
+ //first do horizontal
- for(j = yp; j < yend; ++j)
+ for (j = yp; j < yend; ++j)
{
// First lifting stage
line_data = &coeff_data[j][xp];
// Shift left by one bit to give us more accuracy
ShiftRowLeft(line_data, xl, 1);
- predict.Filter(line_data[1] , line_data[2] , line_data[0]);
- update.Filter(line_data[0] , line_data[1] , line_data[1]);
+ predict.Filter( line_data[1] , line_data[2] , line_data[0] );
+ update.Filter( line_data[0] , line_data[1] , line_data[1] );
- for(k = 3; k < xl - 1; k += 2)
+ for (k = 3; k < xl-1; k+=2)
{
- predict.Filter(line_data[k] , line_data[k+1] , line_data[k-1]);
- update.Filter(line_data[k-1] , line_data[k-2] , line_data[k]);
+ predict.Filter( line_data[k] , line_data[k+1] , line_data[k-1] );
+ update.Filter( line_data[k-1] , line_data[k-2] , line_data[k] );
}// i
- predict.Filter(line_data[xl-1] , line_data[xl-2] , line_data[xl-2]);
- update.Filter(line_data[xl-2] , line_data[xl-3] , line_data[xl-1]);
+ predict.Filter( line_data[xl-1] , line_data[xl-2] , line_data[xl-2] );
+ update.Filter( line_data[xl-2] , line_data[xl-3] , line_data[xl-1] );
}// j
@@ -873,45 +850,45 @@ void VHFilterLEGALL5_3::Split(const int xp ,
// First lifting stage
// top edge - j=xp
- for(i = xp ; i < xend ; ++ i)
+ for ( i = xp ; i<xend ; ++ i)
{
- predict.Filter(coeff_data[yp+1][i] , coeff_data[yp+2][i] , coeff_data[yp][i]);
- update.Filter(coeff_data[yp][i] , coeff_data[yp+1][i] , coeff_data[yp+1][i]);
+ predict.Filter( coeff_data[yp+1][i] , coeff_data[yp+2][i] , coeff_data[yp][i] );
+ update.Filter( coeff_data[yp][i] , coeff_data[yp+1][i] , coeff_data[yp+1][i] );
}// i
// middle bit
- for(k = yp + 3 ; k < yend - 1 ; k += 2)
+ for (k = yp+3 ; k<yend-1 ; k+=2)
{
- for(i = xp ; i < xend ; ++ i)
+ for ( i = xp ; i<xend ; ++ i)
{
- predict.Filter(coeff_data[k][i] , coeff_data[k+1][i] , coeff_data[k-1][i]);
- update.Filter(coeff_data[k-1][i] , coeff_data[k-2][i] , coeff_data[k][i]);
+ predict.Filter( coeff_data[k][i] , coeff_data[k+1][i] , coeff_data[k-1][i] );
+ update.Filter( coeff_data[k-1][i] , coeff_data[k-2][i] , coeff_data[k][i] );
}// i
}// j
// bottom edge
- for(i = xp ; i < xend ; ++ i)
+ for ( i = xp ; i<xend ; ++ i)
{
- predict.Filter(coeff_data[yend-1][i] , coeff_data[yend-2][i] , coeff_data[yend-2][i]);
- update.Filter(coeff_data[yend-2][i] , coeff_data[yend-3][i] , coeff_data[yend-1][i]);
+ predict.Filter( coeff_data[yend-1][i] , coeff_data[yend-2][i] , coeff_data[yend-2][i] );
+ update.Filter( coeff_data[yend-2][i] , coeff_data[yend-3][i] , coeff_data[yend-1][i] );
}// i
// Lastly, have to reorder so that subbands are no longer interleaved
- DeInterleave(xp , yp , xl , yl , coeff_data);
+ DeInterleave( xp , yp , xl , yl , coeff_data );
}
// NOTE: MMX version is defined in wavelet_utils_mmx.cpp
// the corresponding changes are made in wavelet_utils_mmx.cpp as well
void VHFilterLEGALL5_3::Synth(const int xp ,
- const int yp ,
- const int xl ,
- const int yl ,
- CoeffArray& coeff_data)
+ const int yp ,
+ const int xl ,
+ const int yl ,
+ CoeffArray& coeff_data)
{
- int i, j, k;
+ int i,j,k;
- const int xend(xp + xl);
- const int yend(yp + yl);
+ const int xend( xp+xl );
+ const int yend( yp+yl );
const PredictStepShift< 2 > predict;
const UpdateStepShift< 1 > update;
@@ -919,50 +896,50 @@ void VHFilterLEGALL5_3::Synth(const int xp ,
CoeffType* line_data;
// Firstly reorder to interleave subbands, so that subsequent calculations can be in-place
- Interleave(xp , yp , xl , yl , coeff_data);
+ Interleave( xp , yp , xl , yl , coeff_data );
// Next, do the vertical synthesis
// First lifting stage
// Begin with the bottom edge
- for(i = xend - 1 ; i >= xp ; --i)
+ for ( i = xend-1 ; i>=xp ; --i)
{
- predict.Filter(coeff_data[yend-2][i] , coeff_data[yend-3][i] , coeff_data[yend-1][i]);
- update.Filter(coeff_data[yend-1][i] , coeff_data[yend-2][i] , coeff_data[yend-2][i]);
+ predict.Filter( coeff_data[yend-2][i] , coeff_data[yend-3][i] , coeff_data[yend-1][i] );
+ update.Filter( coeff_data[yend-1][i] , coeff_data[yend-2][i] , coeff_data[yend-2][i] );
}// i
// Next, do the middle bit
- for(k = yend - 3 ; k > yp + 1 ; k -= 2)
+ for ( k = yend-3 ; k>yp+1 ; k-=2)
{
- for(i = xend - 1 ; i >= xp ; --i)
+ for ( i = xend-1 ; i>=xp ; --i)
{
- predict.Filter(coeff_data[k-1][i] , coeff_data[k-2][i] , coeff_data[k][i]);
- update.Filter(coeff_data[k][i] , coeff_data[k+1][i] , coeff_data[k-1][i]);
+ predict.Filter( coeff_data[k-1][i] , coeff_data[k-2][i] , coeff_data[k][i] );
+ update.Filter( coeff_data[k][i] , coeff_data[k+1][i] , coeff_data[k-1][i] );
}// i
}// j
// Then do the top edge
- for(i = xend - 1 ; i >= xp ; --i)
+ for ( i = xend-1 ; i>=xp ; --i)
{
- predict.Filter(coeff_data[yp][i] , coeff_data[yp+1][i] , coeff_data[yp+1][i]);
- update.Filter(coeff_data[yp+1][i] , coeff_data[yp+2][i] , coeff_data[yp][i]);
+ predict.Filter( coeff_data[yp][i] , coeff_data[yp+1][i] , coeff_data[yp+1][i] );
+ update.Filter( coeff_data[yp+1][i] , coeff_data[yp+2][i] , coeff_data[yp][i] );
}// i
// Next do the horizontal synthesis
- for(j = yend - 1; j >= yp ; --j)
+ for (j = yend-1; j >= yp ; --j)
{
// First lifting stage
line_data = &coeff_data[j][xp];
- predict.Filter(line_data[xl-2] , line_data[xl-3] , line_data[xl-1]);
- update.Filter(line_data[xl-1] , line_data[xl-2] , line_data[xl-2]);
+ predict.Filter( line_data[xl-2] , line_data[xl-3] , line_data[xl-1] );
+ update.Filter( line_data[xl-1] , line_data[xl-2] , line_data[xl-2] );
- for(k = xl - 3; k > 1; k -= 2)
+ for ( k = xl-3; k > 1; k-=2)
{
- predict.Filter(line_data[k-1] , line_data[k-2] , line_data[k]);
- update.Filter(line_data[k] , line_data[k+1] , line_data[k-1]);
+ predict.Filter( line_data[k-1] , line_data[k-2] , line_data[k] );
+ update.Filter( line_data[k] , line_data[k+1] , line_data[k-1] );
}// i
- predict.Filter(line_data[0] , line_data[1] , line_data[1]);
- update.Filter(line_data[1] , line_data[2] , line_data[0]);
+ predict.Filter( line_data[0] , line_data[1] , line_data[1] );
+ update.Filter( line_data[1] , line_data[2] , line_data[0] );
// Shift right by one bit to counter the shift in the analysis stage
ShiftRowRight(line_data, xl, 1);
@@ -973,92 +950,92 @@ void VHFilterLEGALL5_3::Synth(const int xp ,
#endif
void VHFilterDD9_7::Split(const int xp ,
- const int yp ,
- const int xl ,
- const int yl ,
- CoeffArray& coeff_data)
+ const int yp ,
+ const int xl ,
+ const int yl ,
+ CoeffArray& coeff_data)
{
- const int xend = xp + xl;
- const int yend = yp + yl;
+ const int xend=xp+xl;
+ const int yend=yp+yl;
CoeffType* line_data;
// Positional variables
- int i, j, k;
+ int i,j,k;
- PredictStepFourTap < 4 , 9 , -1 > predict;
+ PredictStepFourTap< 4 , 9 , -1 > predict;
UpdateStepShift< 2 > update;
//first do horizontal
- for(j = yp; j < yend; ++j)
+ for (j = yp; j < yend; ++j)
{
line_data = &coeff_data[j][xp];
// Shift left by one bit to give us more accuracy
ShiftRowLeft(line_data, xl, 1);
// First lifting stage
- predict.Filter(line_data[1] , line_data[0] , line_data[2] , line_data[0] , line_data[4]);
- for(k = 3 ; k < xl - 3 ; k += 2)
+ predict.Filter( line_data[1] , line_data[0] , line_data[2] , line_data[0] , line_data[4] );
+ for (k=3 ; k<xl-3 ; k+=2)
{
- predict.Filter(line_data[k] , line_data[k-1] , line_data[k+1] , line_data[k-3] , line_data[k+3]);
+ predict.Filter( line_data[k] , line_data[k-1] , line_data[k+1] , line_data[k-3] , line_data[k+3] );
}// i
- predict.Filter(line_data[xl-3] , line_data[xl-4] , line_data[xl-2] , line_data[xl-6] , line_data[xl-2]);
- predict.Filter(line_data[xl-1] , line_data[xl-2] , line_data[xl-2] , line_data[xl-4] , line_data[xl-2]);
+ predict.Filter( line_data[xl-3] , line_data[xl-4] , line_data[xl-2] , line_data[xl-6] , line_data[xl-2] );
+ predict.Filter( line_data[xl-1] , line_data[xl-2] , line_data[xl-2] , line_data[xl-4] , line_data[xl-2] );
//Second lifting stage
- update.Filter(line_data[0] , line_data[1] , line_data[1]);
- for(i = 2 ; i < xl - 1 ; i += 2)
+ update.Filter( line_data[0] , line_data[1] , line_data[1] );
+ for (i=2 ; i<xl-1 ; i+=2 )
{
- update.Filter(line_data[i] , line_data[i-1] , line_data[i+1]);
+ update.Filter( line_data[i] , line_data[i-1] , line_data[i+1] );
}// i
- }// j
+ }// j
// next do vertical
// First lifting stage
// top line
- for(i = xp ; i < xend ; ++ i)
+ for ( i = xp ; i<xend ; ++ i)
{
- predict.Filter(coeff_data[yp+1][i] , coeff_data[yp][i] , coeff_data[yp+2][i] , coeff_data[yp][i] , coeff_data[yp+4][i]);
+ predict.Filter( coeff_data[yp+1][i] , coeff_data[yp][i] , coeff_data[yp+2][i] , coeff_data[yp][i] , coeff_data[yp+4][i] );
}// i
// middle bit
- for(k = yp + 3 ; k < yend - 3 ; k += 2)
+ for ( k = yp+3 ; k<yend-3 ; k+=2)
{
- for(i = xp ; i < xend ; ++i)
+ for ( i = xp ; i<xend ; ++i)
{
- predict.Filter(coeff_data[k][i] , coeff_data[k-1][i] , coeff_data[k+1][i] , coeff_data[k-3][i] , coeff_data[k+3][i]);
+ predict.Filter( coeff_data[k][i] , coeff_data[k-1][i] , coeff_data[k+1][i] , coeff_data[k-3][i] , coeff_data[k+3][i] );
}// i
}// j
// bottom lines
- for(i = xp ; i < xend ; ++ i)
+ for ( i = xp ; i<xend ; ++ i)
{
- predict.Filter(coeff_data[yend-3][i] , coeff_data[yend-4][i] , coeff_data[yend-2][i] , coeff_data[yend-6][i] , coeff_data[yend-2][i]);
- predict.Filter(coeff_data[yend-1][i] , coeff_data[yend-2][i] , coeff_data[yend-2][i] , coeff_data[yend-4][i] , coeff_data[yend-2][i]);
+ predict.Filter( coeff_data[yend-3][i] , coeff_data[yend-4][i] , coeff_data[yend-2][i] , coeff_data[yend-6][i] , coeff_data[yend-2][i] );
+ predict.Filter( coeff_data[yend-1][i] , coeff_data[yend-2][i] , coeff_data[yend-2][i] , coeff_data[yend-4][i] , coeff_data[yend-2][i] );
}// i
//Second lifting stage
- for(i = xp ; i < xend ; ++ i)
+ for ( i = xp ; i<xend ; ++ i)
{
- update.Filter(coeff_data[yp][i] , coeff_data[yp+1][i] , coeff_data[yp+1][i]);
+ update.Filter( coeff_data[yp][i] , coeff_data[yp+1][i] , coeff_data[yp+1][i] );
}// i
// middle bit
- for(j = yp + 2 ; j < yend - 1 ; j += 2 , k += 2)
+ for ( j = yp+2 ; j<yend-1 ; j+=2 , k+=2)
{
- for(i = xp ; i < xend ; ++i)
+ for ( i = xp ; i<xend ; ++i)
{
- update.Filter(coeff_data[j][i] , coeff_data[j-1][i] , coeff_data[j+1][i]);
+ update.Filter( coeff_data[j][i] , coeff_data[j-1][i] , coeff_data[j+1][i] );
}// i
}// j
// Lastly, have to reorder so that subbands are no longer interleaved
- DeInterleave(xp , yp , xl , yl , coeff_data);
+ DeInterleave( xp , yp , xl , yl , coeff_data );
@@ -1068,85 +1045,85 @@ void VHFilterDD9_7::Split(const int xp ,
// NOTE: MMX version is defined in wavelet_utils_mmx.cpp
// the corresponding changes are made in wavelet_utils_mmx.cpp as well
void VHFilterDD9_7::Synth(const int xp ,
- const int yp ,
- const int xl ,
- const int yl ,
- CoeffArray& coeff_data)
+ const int yp ,
+ const int xl ,
+ const int yl ,
+ CoeffArray& coeff_data)
{
- int i, j;
+ int i,j;
- const int xend(xp + xl);
- const int yend(yp + yl);
+ const int xend( xp+xl );
+ const int yend( yp+yl );
PredictStepShift<2> predict;
- UpdateStepFourTap < 4 , 9 , -1 > update;
+ UpdateStepFourTap< 4 , 9 , -1> update;
CoeffType* line_data;
// Firstly reorder to interleave subbands, so that subsequent calculations can be in-place
- Interleave(xp , yp , xl , yl , coeff_data);
+ Interleave( xp , yp , xl ,yl , coeff_data );
// First, do the vertical synthesis
// First lifting stage
// Middle bit
- for(j = yend - 2 ; j >= yp + 2 ; j -= 2)
+ for ( j=yend-2 ; j>=yp+2 ; j-=2 )
{
- for(i = xend - 1 ; i >= xp ; --i)
+ for ( i = xend-1 ; i>=xp ; --i)
{
- predict.Filter(coeff_data[j][i] , coeff_data[j-1][i] , coeff_data[j+1][i]);
+ predict.Filter( coeff_data[j][i] , coeff_data[j-1][i] , coeff_data[j+1][i] );
}// i
}// j
// top line
- for(i = xend - 1 ; i >= xp ; --i)
+ for ( i = xend-1 ; i>=xp ; --i)
{
- predict.Filter(coeff_data[yp][i] , coeff_data[yp+1][i] , coeff_data[yp+1][i]);
+ predict.Filter( coeff_data[yp][i] , coeff_data[yp+1][i] , coeff_data[yp+1][i] );
}// i
// Second lifting stage
- for(i = xend - 1 ; i >= xp ; --i)
+ for ( i = xend-1 ; i>=xp ; --i)
{
- update.Filter(coeff_data[yend-1][i] , coeff_data[yend-2][i] , coeff_data[yend-2][i] , coeff_data[yend-4][i] , coeff_data[yend-2][i]);
- update.Filter(coeff_data[yend-3][i] , coeff_data[yend-4][i] , coeff_data[yend-2][i] , coeff_data[yend-6][i] , coeff_data[yend-2][i]);
+ update.Filter( coeff_data[yend-1][i] , coeff_data[yend-2][i] , coeff_data[yend-2][i] , coeff_data[yend-4][i] , coeff_data[yend-2][i] );
+ update.Filter( coeff_data[yend-3][i] , coeff_data[yend-4][i] , coeff_data[yend-2][i] , coeff_data[yend-6][i] , coeff_data[yend-2][i] );
}// i
// middle bit
- for(j = yend - 5 ; j >= yp + 3 ; j -= 2)
+ for ( j=yend-5 ; j>=yp+3 ; j-=2)
{
- for(i = xend - 1 ; i >= xp ; --i)
+ for ( i = xend-1 ; i>=xp ; --i)
{
- update.Filter(coeff_data[j][i] , coeff_data[j-1][i] , coeff_data[j+1][i] , coeff_data[j-3][i] , coeff_data[j+3][i]);
+ update.Filter( coeff_data[j][i] , coeff_data[j-1][i] , coeff_data[j+1][i] , coeff_data[j-3][i] , coeff_data[j+3][i] );
}// i
}// k
- for(i = xend - 1 ; i >= xp ; --i)
+ for ( i = xend-1 ; i>=xp ; --i)
{
- update.Filter(coeff_data[yp+1][i] , coeff_data[yp][i] , coeff_data[yp+2][i] , coeff_data[yp][i] , coeff_data[yp+4][i]);
+ update.Filter( coeff_data[yp+1][i] , coeff_data[yp][i] , coeff_data[yp+2][i] , coeff_data[yp][i] , coeff_data[yp+4][i] );
}// i
// Next do the horizontal synthesis
- for(j = yend - 1; j >= yp; --j)
+ for (j = yend-1; j >= yp; --j)
{
line_data = &coeff_data[j][xp];
// First lifting stage
- for(i = xl - 2 ; i >= 2 ; i -= 2)
+ for (i=xl-2 ; i>=2 ; i-=2)
{
- predict.Filter(line_data[i] , line_data[i-1] , line_data[i+1]);
+ predict.Filter( line_data[i] , line_data[i-1] , line_data[i+1] );
}// i
- predict.Filter(line_data[0] , line_data[1] , line_data[1]);
+ predict.Filter( line_data[0] , line_data[1] , line_data[1] );
// Second lifting stage
- update.Filter(line_data[xl-1] , line_data[xl-2] , line_data[xl-2] , line_data[xl-4] , line_data[xl-2]);
- update.Filter(line_data[xl-3] , line_data[xl-4] , line_data[xl-2] , line_data[xl-6] , line_data[xl-2]);
- for(i = xl - 5 ; i >= 3 ; i -= 2)
+ update.Filter( line_data[xl-1] , line_data[xl-2] , line_data[xl-2] , line_data[xl-4] , line_data[xl-2] );
+ update.Filter( line_data[xl-3] , line_data[xl-4] , line_data[xl-2] , line_data[xl-6] , line_data[xl-2] );
+ for (i=xl-5 ; i>=3 ; i-=2)
{
- update.Filter(line_data[i] , line_data[i-1] , line_data[i+1] , line_data[i-3] , line_data[i+3]);
+ update.Filter( line_data[i] , line_data[i-1] , line_data[i+1] , line_data[i-3] , line_data[i+3] );
}// i
- update.Filter(line_data[1] , line_data[0] , line_data[2] , line_data[0] , line_data[4]);
+ update.Filter( line_data[1] , line_data[0] , line_data[2] , line_data[0] , line_data[4] );
// Shift right by one bit to counter the shift in the analysis stage
ShiftRowRight(line_data, xl, 1);
@@ -1157,50 +1134,50 @@ void VHFilterDD9_7::Synth(const int xp ,
#endif
void VHFilterDD13_7::Split(const int xp ,
- const int yp ,
- const int xl ,
- const int yl ,
- CoeffArray& coeff_data)
+ const int yp ,
+ const int xl ,
+ const int yl ,
+ CoeffArray& coeff_data)
{
- const int xend = xp + xl;
- const int yend = yp + yl;
+ const int xend=xp+xl;
+ const int yend=yp+yl;
- PredictStepFourTap < 4 , 9 , -1 > predict;
- UpdateStepFourTap < 5 , 9 , -1 > update;
+ PredictStepFourTap< 4 , 9 , -1 > predict;
+ UpdateStepFourTap< 5 , 9 , -1> update;
CoeffType* line_data;
// Positional variables
- int i, j, k;
+ int i,j,k;
- //first do horizontal
+ //first do horizontal
- for(j = yp; j < yend; ++j)
+ for (j = yp; j < yend; ++j)
{
line_data = &coeff_data[j][xp];
// Shift left by one bit to give us more accuracy
ShiftRowLeft(line_data, xl, 1);
// First lifting stage
- predict.Filter(line_data[1] , line_data[0] , line_data[2] , line_data[0] , line_data[4]);
- for(k = 3 ; k < xl - 3 ; k += 2)
+ predict.Filter( line_data[1] , line_data[0] ,line_data[2] , line_data[0] , line_data[4] );
+ for (k=3 ; k<xl-3 ; k+=2)
{
- predict.Filter(line_data[k] , line_data[k-1] , line_data[k+1] , line_data[k-3] , line_data[k+3]);
+ predict.Filter( line_data[k] , line_data[k-1] , line_data[k+1] , line_data[k-3] , line_data[k+3] );
}// i
- predict.Filter(line_data[xl-3] , line_data[xl-4] , line_data[xl-2] , line_data[xl-6] , line_data[xl-2]);
- predict.Filter(line_data[xl-1] , line_data[xl-2] , line_data[xl-2] , line_data[xl-4] , line_data[xl-2]);
+ predict.Filter( line_data[xl-3] , line_data[xl-4] , line_data[xl-2] , line_data[xl-6] , line_data[xl-2] );
+ predict.Filter( line_data[xl-1] , line_data[xl-2] , line_data[xl-2] , line_data[xl-4] , line_data[xl-2] );
- //second lifting stage
- update.Filter(line_data[0] , line_data[1] , line_data[1] , line_data[3] , line_data[1]);
- update.Filter(line_data[2] , line_data[1] , line_data[3] , line_data[5] , line_data[1]);
- for(k = 4 ; k < xl - 3 ; k += 2)
+ //second lifting stage
+ update.Filter( line_data[0] , line_data[1] , line_data[1] , line_data[3] , line_data[1] );
+ update.Filter( line_data[2] , line_data[1] , line_data[3] , line_data[5] , line_data[1] );
+ for (k=4 ; k<xl-3 ; k+=2)
{
- update.Filter(line_data[k] , line_data[k-1] , line_data[k+1] , line_data[k-3] , line_data[k+3]);
+ update.Filter( line_data[k] , line_data[k-1] , line_data[k+1] , line_data[k-3] , line_data[k+3] );
}// i
- update.Filter(line_data[xl-2] , line_data[xl-3] , line_data[xl-1] , line_data[xl-5] , line_data[xl-1]);
+ update.Filter( line_data[xl-2] , line_data[xl-3] , line_data[xl-1] , line_data[xl-5] , line_data[xl-1] );
}// j
// next do vertical
@@ -1208,153 +1185,153 @@ void VHFilterDD13_7::Split(const int xp ,
// First lifting stage
// top edge - j=xp
- for(i = xp ; i < xend ; ++ i)
+ for ( i = xp ; i<xend ; ++ i)
{
- predict.Filter(coeff_data[yp+1][i] , coeff_data[yp][i] , coeff_data[yp+2][i] , coeff_data[yp][i] , coeff_data[yp+4][i]);
+ predict.Filter( coeff_data[yp+1][i] , coeff_data[yp][i] , coeff_data[yp+2][i] , coeff_data[yp][i] , coeff_data[yp+4][i] );
}// i
// middle bit
- for(k = yp + 3 ; k < yend - 3 ; k += 2)
+ for ( k = yp+3 ; k<yend-3 ; k+=2)
{
- for(i = xp ; i < xend ; ++ i)
+ for ( i = xp ; i<xend ; ++ i)
{
- predict.Filter(coeff_data[k][i] , coeff_data[k-1][i] , coeff_data[k+1][i] , coeff_data[k-3][i] , coeff_data[k+3][i]);
+ predict.Filter( coeff_data[k][i] , coeff_data[k-1][i] , coeff_data[k+1][i] , coeff_data[k-3][i] , coeff_data[k+3][i] );
}// i
}// j
// bottom edge
- for(i = xp ; i < xend ; ++ i)
+ for ( i = xp ; i<xend ; ++ i)
{
- predict.Filter(coeff_data[yend-3][i] , coeff_data[yend-4][i] , coeff_data[yend-2][i] , coeff_data[yend-6][i] , coeff_data[yend-2][i]);
- predict.Filter(coeff_data[yend-1][i] , coeff_data[yend-2][i] , coeff_data[yend-2][i] , coeff_data[yend-4][i] , coeff_data[yend-2][i]);
+ predict.Filter( coeff_data[yend-3][i] , coeff_data[yend-4][i] , coeff_data[yend-2][i] , coeff_data[yend-6][i] , coeff_data[yend-2][i] );
+ predict.Filter( coeff_data[yend-1][i] , coeff_data[yend-2][i] , coeff_data[yend-2][i] , coeff_data[yend-4][i] , coeff_data[yend-2][i] );
}// i
// Second lifting stage
// top edge - j=xp
- for(i = xp ; i < xend ; ++ i)
+ for ( i = xp ; i<xend ; ++ i)
{
- update.Filter(coeff_data[yp][i] , coeff_data[yp+1][i] , coeff_data[yp+1][i] , coeff_data[yp+3][i] , coeff_data[yp+1][i]);
- update.Filter(coeff_data[yp+2][i] , coeff_data[yp+1][i] , coeff_data[yp+3][i] , coeff_data[yp+5][i] , coeff_data[yp+1][i]);
+ update.Filter( coeff_data[yp][i] , coeff_data[yp+1][i] , coeff_data[yp+1][i] , coeff_data[yp+3][i] , coeff_data[yp+1][i] );
+ update.Filter( coeff_data[yp+2][i] , coeff_data[yp+1][i] , coeff_data[yp+3][i] , coeff_data[yp+5][i] , coeff_data[yp+1][i] );
}// i
// middle bit
- for(k = yp + 4 ; k < yend - 3 ; k += 2)
+ for ( k = yp+4 ; k<yend-3 ; k+=2)
{
- for(i = xp ; i < xend ; ++ i)
+ for ( i = xp ; i<xend ; ++ i)
{
- update.Filter(coeff_data[k][i] , coeff_data[k-1][i] , coeff_data[k+1][i] , coeff_data[k-3][i] , coeff_data[k+3][i]);
+ update.Filter( coeff_data[k][i] , coeff_data[k-1][i] , coeff_data[k+1][i] , coeff_data[k-3][i] , coeff_data[k+3][i] );
}// i
}// j
// bottom edge
- for(i = xp ; i < xend ; ++ i)
+ for ( i = xp ; i<xend ; ++ i)
{
- update.Filter(coeff_data[yend-2][i] , coeff_data[yend-3][i] , coeff_data[yend-1][i] , coeff_data[yend-5][i] , coeff_data[yend-1][i]);
+ update.Filter( coeff_data[yend-2][i] , coeff_data[yend-3][i] , coeff_data[yend-1][i] , coeff_data[yend-5][i] , coeff_data[yend-1][i] );
}// i
// Lastly, have to reorder so that subbands are no longer interleaved
- DeInterleave(xp , yp , xl , yl , coeff_data);
+ DeInterleave( xp , yp , xl , yl , coeff_data );
}
#if !defined(HAVE_MMX)
// NOTE: MMX version is defined in wavelet_utils_mmx.cpp
// the corresponding changes are made in wavelet_utils_mmx.cpp as well
void VHFilterDD13_7::Synth(const int xp ,
- const int yp ,
- const int xl ,
- const int yl ,
- CoeffArray& coeff_data)
+ const int yp ,
+ const int xl ,
+ const int yl ,
+ CoeffArray& coeff_data)
{
- int i, j, k;
+ int i,j,k;
- const int xend(xp + xl);
- const int yend(yp + yl);
+ const int xend( xp+xl );
+ const int yend( yp+yl );
- PredictStepFourTap < 5 , 9 , -1 > predict;
- UpdateStepFourTap < 4 , 9 , -1 > update;
+ PredictStepFourTap< 5 , 9 , -1 > predict;
+ UpdateStepFourTap< 4 , 9 , -1> update;
// Firstly reorder to interleave subbands, so that subsequent calculations can be in-place
- Interleave(xp , yp , xl , yl , coeff_data);
+ Interleave( xp , yp , xl , yl , coeff_data );
// Next, do the vertical synthesis
// First lifting stage
// bottom edge
- for(i = xp ; i < xend ; ++ i)
+ for ( i = xp ; i<xend ; ++ i)
{
- predict.Filter(coeff_data[yend-2][i] , coeff_data[yend-3][i] , coeff_data[yend-1][i] , coeff_data[yend-5][i] , coeff_data[yend-1][i]);
+ predict.Filter( coeff_data[yend-2][i] , coeff_data[yend-3][i] , coeff_data[yend-1][i] , coeff_data[yend-5][i] , coeff_data[yend-1][i] );
}// i
// middle bit
- for(k = yend - 4 ; k >= yp + 4 ; k -= 2)
+ for ( k = yend-4 ; k>=yp+4 ; k-=2)
{
- for(i = xp ; i < xend ; ++ i)
+ for ( i = xp ; i<xend ; ++ i)
{
- predict.Filter(coeff_data[k][i] , coeff_data[k-1][i] , coeff_data[k+1][i] , coeff_data[k-3][i] , coeff_data[k+3][i]);
+ predict.Filter( coeff_data[k][i] , coeff_data[k-1][i] , coeff_data[k+1][i] , coeff_data[k-3][i] , coeff_data[k+3][i] );
}// i
}// j
// top edge - j=xp
- for(i = xp ; i < xend ; ++ i)
+ for ( i = xp ; i<xend ; ++ i)
{
- predict.Filter(coeff_data[yp+2][i] , coeff_data[yp+1][i] , coeff_data[yp+3][i] , coeff_data[yp+5][i] , coeff_data[yp+1][i]);
- predict.Filter(coeff_data[yp][i] , coeff_data[yp+1][i] , coeff_data[yp+1][i] , coeff_data[yp+3][i] , coeff_data[yp+1][i]);
+ predict.Filter( coeff_data[yp+2][i] , coeff_data[yp+1][i] , coeff_data[yp+3][i] , coeff_data[yp+5][i] , coeff_data[yp+1][i] );
+ predict.Filter( coeff_data[yp][i] , coeff_data[yp+1][i] , coeff_data[yp+1][i] , coeff_data[yp+3][i] , coeff_data[yp+1][i] );
}// i
// Second lifting stage
// bottom edge
- for(i = xp ; i < xend ; ++ i)
+ for ( i = xp ; i<xend ; ++ i)
{
- update.Filter(coeff_data[yend-1][i] , coeff_data[yend-2][i] , coeff_data[yend-2][i] , coeff_data[yend-4][i] , coeff_data[yend-2][i]);
- update.Filter(coeff_data[yend-3][i] , coeff_data[yend-4][i] , coeff_data[yend-2][i] , coeff_data[yend-6][i] , coeff_data[yend-2][i]);
+ update.Filter( coeff_data[yend-1][i] , coeff_data[yend-2][i] , coeff_data[yend-2][i] , coeff_data[yend-4][i] , coeff_data[yend-2][i] );
+ update.Filter( coeff_data[yend-3][i] , coeff_data[yend-4][i] , coeff_data[yend-2][i] , coeff_data[yend-6][i] , coeff_data[yend-2][i] );
}// i
// middle bit
- for(k = yend - 5 ; k >= yp + 3 ; k -= 2)
+ for ( k = yend-5 ; k>=yp+3 ; k-=2)
{
- for(i = xp ; i < xend ; ++ i)
+ for ( i = xp ; i<xend ; ++ i)
{
- update.Filter(coeff_data[k][i] , coeff_data[k-1][i] , coeff_data[k+1][i] , coeff_data[k-3][i] , coeff_data[k+3][i]);
+ update.Filter( coeff_data[k][i] , coeff_data[k-1][i] , coeff_data[k+1][i] , coeff_data[k-3][i] , coeff_data[k+3][i] );
}// i
}// j
// top edge - j=xp
- for(i = xp ; i < xend ; ++ i)
+ for ( i = xp ; i<xend ; ++ i)
{
- update.Filter(coeff_data[yp+1][i] , coeff_data[yp][i] , coeff_data[yp+2][i] , coeff_data[yp][i] , coeff_data[yp+4][i]);
+ update.Filter( coeff_data[yp+1][i] , coeff_data[yp][i] , coeff_data[yp+2][i] , coeff_data[yp][i] , coeff_data[yp+4][i] );
}// i
// Next do the horizontal synthesis
CoeffType* line_data;
- for(j = yend - 1; j >= yp ; --j)
+ for (j = yend-1; j >= yp ; --j)
{
line_data = &coeff_data[j][xp];
// First lifting stage
- predict.Filter(line_data[xl-2] , line_data[xl-3] , line_data[xl-1] , line_data[xl-5] , line_data[xl-1]);
+ predict.Filter( line_data[xl-2] , line_data[xl-3] , line_data[xl-1] , line_data[xl-5] , line_data[xl-1] );
- for(k = xl - 4 ; k >= 4 ; k -= 2)
+ for (k=xl-4 ; k>=4 ; k-=2)
{
- predict.Filter(line_data[k] , line_data[k-1] , line_data[k+1] , line_data[k-3] , line_data[k+3]);
+ predict.Filter( line_data[k] , line_data[k-1] , line_data[k+1] , line_data[k-3] , line_data[k+3] );
}// i
- predict.Filter(line_data[2] , line_data[1] , line_data[3] , line_data[5] , line_data[1]);
- predict.Filter(line_data[0] , line_data[1] , line_data[1] , line_data[3] , line_data[1]);
+ predict.Filter( line_data[2] , line_data[1] , line_data[3] , line_data[5] , line_data[1] );
+ predict.Filter( line_data[0] , line_data[1] , line_data[1] , line_data[3] , line_data[1] );
- //second lifting stage
- update.Filter(line_data[xl-1] , line_data[xl-2] , line_data[xl-2] , line_data[xl-4] , line_data[xl-2]);
- update.Filter(line_data[xl-3] , line_data[xl-4] , line_data[xl-2] , line_data[xl-6] , line_data[xl-2]);
+ //second lifting stage
+ update.Filter( line_data[xl-1] , line_data[xl-2] , line_data[xl-2] , line_data[xl-4] , line_data[xl-2] );
+ update.Filter( line_data[xl-3] , line_data[xl-4] , line_data[xl-2] , line_data[xl-6] , line_data[xl-2] );
- for(k = xl - 5 ; k >= 3 ; k -= 2)
+ for (k=xl-5 ; k>=3 ; k-=2)
{
- update.Filter(line_data[k] , line_data[k-1] , line_data[k+1] , line_data[k-3] , line_data[k+3]);
+ update.Filter( line_data[k] , line_data[k-1] , line_data[k+1] , line_data[k-3] , line_data[k+3] );
}// i
- update.Filter(line_data[1] , line_data[0] , line_data[2] , line_data[0] , line_data[4]);
+ update.Filter( line_data[1] , line_data[0] , line_data[2] , line_data[0] , line_data[4] );
// Shift right by one bit to counter the shift in the analysis stage
ShiftRowRight(line_data, xl, 1);
@@ -1363,147 +1340,147 @@ void VHFilterDD13_7::Synth(const int xp ,
#endif
void VHFilterHAAR0::Split(const int xp ,
- const int yp ,
- const int xl ,
- const int yl ,
- CoeffArray& coeff_data)
+ const int yp ,
+ const int xl ,
+ const int yl ,
+ CoeffArray& coeff_data)
{
- const int xend = xp + xl;
- const int yend = yp + yl;
+ const int xend=xp+xl;
+ const int yend=yp+yl;
// first do Horizontal
- for(int j = yp; j < yend; ++j)
+ for (int j = yp; j < yend; ++j)
{
- for(int i = xp + 1; i < xend; i += 2)
+ for (int i = xp+1; i < xend; i+=2)
{
// odd sample
// x(2n+1) -= x(2n)
coeff_data[j][i] -= coeff_data[j][i-1];
// even sample
// x(2n) += x(2n+1)/2
- coeff_data[j][i-1] += ((coeff_data[j][i] + 1) >> 1);
+ coeff_data[j][i-1] += ((coeff_data[j][i]+1)>>1);
}
}
// next do vertical
- for(int j = yp + 1; j < yend; j += 2)
+ for (int j = yp+1; j < yend; j+=2)
{
- for(int i = xp; i < xend; ++i)
+ for (int i = xp; i < xend; ++i)
{
coeff_data[j][i] -= coeff_data[j-1][i];
- coeff_data[j-1][i] += ((coeff_data[j][i] + 1) >> 1);
+ coeff_data[j-1][i] += ((coeff_data[j][i]+1)>>1);
}
}
// Lastly, have to reorder so that subbands are no longer interleaved
- DeInterleave(xp , yp , xl , yl , coeff_data);
+ DeInterleave( xp , yp , xl , yl , coeff_data );
}
void VHFilterHAAR0::Synth(const int xp ,
- const int yp ,
- const int xl ,
- const int yl ,
- CoeffArray& coeff_data)
+ const int yp ,
+ const int xl ,
+ const int yl ,
+ CoeffArray& coeff_data)
{
- const int xend(xp + xl);
- const int yend(yp + yl);
+ const int xend( xp+xl );
+ const int yend( yp+yl );
// Firstly reorder to interleave subbands, so that subsequent calculations can be in-place
- Interleave(xp , yp , xl , yl , coeff_data);
+ Interleave( xp , yp , xl , yl , coeff_data );
// First do the vertical
- for(int j = yp + 1; j < yend; j += 2)
+ for (int j = yp+1; j < yend; j+=2)
{
- for(int i = xp; i < xend; ++i)
+ for (int i = xp; i < xend; ++i)
{
- coeff_data[j-1][i] -= ((coeff_data[j][i] + 1) >> 1);
+ coeff_data[j-1][i] -= ((coeff_data[j][i]+1)>>1);
coeff_data[j][i] += coeff_data[j-1][i];
}
}
// Next do the horizontal
- for(int j = yp; j < yend; ++j)
+ for (int j = yp; j < yend; ++j)
{
- for(int i = xp + 1; i < xend; i += 2)
+ for (int i = xp+1; i < xend; i+=2)
{
- coeff_data[j][i-1] -= ((coeff_data[j][i] + 1) >> 1);
+ coeff_data[j][i-1] -= ((coeff_data[j][i]+1)>>1);
coeff_data[j][i] += coeff_data[j][i-1];
}
}
}
void VHFilterHAAR1::Split(const int xp ,
- const int yp ,
- const int xl ,
- const int yl ,
- CoeffArray& coeff_data)
+ const int yp ,
+ const int xl ,
+ const int yl ,
+ CoeffArray& coeff_data)
{
- const int xend = xp + xl;
- const int yend = yp + yl;
+ const int xend=xp+xl;
+ const int yend=yp+yl;
CoeffType* line_data;
// first do Horizontal
- for(int j = yp; j < yend; ++j)
+ for (int j = yp; j < yend; ++j)
{
line_data = &(coeff_data[j][xp]);
ShiftRowLeft(line_data, xl, 1);
- for(int i = xp + 1; i < xend; i += 2)
+ for (int i = xp+1; i < xend; i+=2)
{
// odd sample
// x(2n+1) -= x(2n)
coeff_data[j][i] -= coeff_data[j][i-1];
// even sample
// x(2n) += x(2n+1)/2
- coeff_data[j][i-1] += ((coeff_data[j][i] + 1) >> 1);
+ coeff_data[j][i-1] += ((coeff_data[j][i]+1)>>1);
}
}
// next do vertical
- for(int j = yp + 1; j < yend; j += 2)
+ for (int j = yp+1; j < yend; j+=2)
{
- for(int i = xp; i < xend; ++i)
+ for (int i = xp; i < xend; ++i)
{
coeff_data[j][i] -= coeff_data[j-1][i];
- coeff_data[j-1][i] += ((coeff_data[j][i] + 1) >> 1);
+ coeff_data[j-1][i] += ((coeff_data[j][i]+1)>>1);
}
}
// Lastly, have to reorder so that subbands are no longer interleaved
- DeInterleave(xp , yp , xl , yl , coeff_data);
+ DeInterleave( xp , yp , xl , yl , coeff_data );
}
void VHFilterHAAR1::Synth(const int xp ,
- const int yp ,
- const int xl ,
- const int yl ,
- CoeffArray& coeff_data)
+ const int yp ,
+ const int xl ,
+ const int yl ,
+ CoeffArray& coeff_data)
{
- const int xend(xp + xl);
- const int yend(yp + yl);
+ const int xend( xp+xl );
+ const int yend( yp+yl );
CoeffType* line_data;
// Firstly reorder to interleave subbands, so that subsequent calculations can be in-place
- Interleave(xp , yp , xl , yl , coeff_data);
+ Interleave( xp , yp , xl , yl , coeff_data );
// First do the vertical
- for(int j = yp + 1; j < yend; j += 2)
+ for (int j = yp+1; j < yend; j+=2)
{
- for(int i = xp; i < xend; ++i)
+ for (int i = xp; i < xend; ++i)
{
- coeff_data[j-1][i] -= ((coeff_data[j][i] + 1) >> 1);
+ coeff_data[j-1][i] -= ((coeff_data[j][i]+1)>>1);
coeff_data[j][i] += coeff_data[j-1][i];
}
}
// Next do the horizontal
- for(int j = yp; j < yend; ++j)
+ for (int j = yp; j < yend; ++j)
{
- for(int i = xp + 1; i < xend; i += 2)
+ for (int i = xp+1; i < xend; i+=2)
{
- coeff_data[j][i-1] -= ((coeff_data[j][i] + 1) >> 1);
+ coeff_data[j][i-1] -= ((coeff_data[j][i]+1)>>1);
coeff_data[j][i] += coeff_data[j][i-1];
}
line_data = &coeff_data[j][xp];
@@ -1512,76 +1489,76 @@ void VHFilterHAAR1::Synth(const int xp ,
}
void VHFilterHAAR2::Split(const int xp ,
- const int yp ,
- const int xl ,
- const int yl ,
- CoeffArray& coeff_data)
+ const int yp ,
+ const int xl ,
+ const int yl ,
+ CoeffArray& coeff_data)
{
- const int xend = xp + xl;
- const int yend = yp + yl;
+ const int xend=xp+xl;
+ const int yend=yp+yl;
CoeffType* line_data;
// first do Horizontal
- for(int j = yp; j < yend; ++j)
+ for (int j = yp; j < yend; ++j)
{
line_data = &coeff_data[j][xp];
ShiftRowLeft(line_data, xl, 2);
- for(int i = xp + 1; i < xend; i += 2)
+ for (int i = xp+1; i < xend; i+=2)
{
// odd sample
// x(2n+1) -= x(2n)
coeff_data[j][i] -= coeff_data[j][i-1];
// even sample
// x(2n) += x(2n+1)/2
- coeff_data[j][i-1] += ((coeff_data[j][i] + 1) >> 1);
+ coeff_data[j][i-1] += ((coeff_data[j][i]+1)>>1);
}
}
// next do vertical
- for(int j = yp + 1; j < yend; j += 2)
+ for (int j = yp+1; j < yend; j+=2)
{
- for(int i = xp; i < xend; ++i)
+ for (int i = xp; i < xend; ++i)
{
coeff_data[j][i] -= coeff_data[j-1][i];
- coeff_data[j-1][i] += ((coeff_data[j][i] + 1) >> 1);
+ coeff_data[j-1][i] += ((coeff_data[j][i]+1)>>1);
}
}
// Lastly, have to reorder so that subbands are no longer interleaved
- DeInterleave(xp , yp , xl , yl , coeff_data);
+ DeInterleave( xp , yp , xl , yl , coeff_data );
}
void VHFilterHAAR2::Synth(const int xp ,
- const int yp ,
- const int xl ,
- const int yl ,
- CoeffArray& coeff_data)
+ const int yp ,
+ const int xl ,
+ const int yl ,
+ CoeffArray& coeff_data)
{
- const int xend(xp + xl);
- const int yend(yp + yl);
+ const int xend( xp+xl );
+ const int yend( yp+yl );
CoeffType* line_data;
// Firstly reorder to interleave subbands, so that subsequent calculations can be in-place
- Interleave(xp , yp , xl , yl , coeff_data);
+ Interleave( xp , yp , xl , yl , coeff_data );
// First do the vertical
- for(int j = yp + 1; j < yend; j += 2)
+ for (int j = yp+1; j < yend; j+=2)
{
- for(int i = xp; i < xend; ++i)
+ for (int i = xp; i < xend; ++i)
{
- coeff_data[j-1][i] -= ((coeff_data[j][i] + 1) >> 1);
+ coeff_data[j-1][i] -= ((coeff_data[j][i]+1)>>1);
coeff_data[j][i] += coeff_data[j-1][i];
}
}
// Next do the horizontal
- for(int j = yp; j < yend; ++j)
+ for (int j = yp; j < yend; ++j)
{
- for(int i = xp + 1; i < xend; i += 2)
+ for (int i = xp+1; i < xend; i+=2)
{
- coeff_data[j][i-1] -= ((coeff_data[j][i] + 1) >> 1);
+ coeff_data[j][i-1] -= ((coeff_data[j][i]+1)>>1);
coeff_data[j][i] += coeff_data[j][i-1];
}
line_data = &coeff_data[j][xp];
diff --git a/src/filters/parser/DiracSplitter/libdirac/libdirac_common/wavelet_utils.h b/src/filters/parser/DiracSplitter/libdirac/libdirac_common/wavelet_utils.h
index 26378bf81..2ca565f3b 100644
--- a/src/filters/parser/DiracSplitter/libdirac/libdirac_common/wavelet_utils.h
+++ b/src/filters/parser/DiracSplitter/libdirac/libdirac_common/wavelet_utils.h
@@ -52,830 +52,680 @@
namespace dirac
{
-class PicArray;
-class Subband;
+ class PicArray;
+ class Subband;
-//! Class for encapsulating metadata concerning a block of coefficients in a subband
-class CodeBlock
-{
+ //! Class for encapsulating metadata concerning a block of coefficients in a subband
+ class CodeBlock
+ {
friend class Subband;
-public:
- //! Constructor
- /*
- Default constructor - sets all dimensions to zero
- */
- CodeBlock();
-
- //! Constructor
- /*
- Initialise the code block
- \param xstart the x-coord of the first coefficient in the block
- \param xend one past the last coefficient, horizontally
- \param ystart the y-coord of the first coefficient in the block
- \param yend one past the last coefficient, vertically
- */
- CodeBlock(const int xstart , const int ystart , const int xend , const int yend);
+ public:
+ //! Constructor
+ /*
+ Default constructor - sets all dimensions to zero
+ */
+ CodeBlock();
- //! Returns the horizontal start of the block
- int Xstart() const
- {
- return m_xstart;
- }
+ //! Constructor
+ /*
+ Initialise the code block
+ \param xstart the x-coord of the first coefficient in the block
+ \param xend one past the last coefficient, horizontally
+ \param ystart the y-coord of the first coefficient in the block
+ \param yend one past the last coefficient, vertically
+ */
+ CodeBlock( const int xstart , const int ystart , const int xend , const int yend);
- //! Returns the vertical start of the block
- int Ystart() const
- {
- return m_ystart;
- }
+ //! Returns the horizontal start of the block
+ int Xstart() const { return m_xstart; }
- //! Returns one past the last coefficient coord, horizontally
- int Xend() const
- {
- return m_xend;
- }
+ //! Returns the vertical start of the block
+ int Ystart() const { return m_ystart; }
- //! Returns one past the last coefficient coord, vertically
- int Yend() const
- {
- return m_yend;
- }
+ //! Returns one past the last coefficient coord, horizontally
+ int Xend() const { return m_xend; }
- //! Returns the width of the code block
- int Xl() const
- {
- return m_xl;
- }
+ //! Returns one past the last coefficient coord, vertically
+ int Yend() const { return m_yend; }
- //! Returns the height of the code block
- int Yl() const
- {
- return m_yl;
- }
+ //! Returns the width of the code block
+ int Xl() const { return m_xl; }
- //! Returns the quantisation index associated to the code block
- int QuantIndex() const
- {
- return m_quantindex;
- }
+ //! Returns the height of the code block
+ int Yl() const { return m_yl; }
- //! Returns true if the code-block is skipped, false if not
- bool Skipped() const
- {
- return m_skipped;
- }
+ //! Returns the quantisation index associated to the code block
+ int QuantIndex() const{ return m_quantindex; }
- //! Sets the quantisation index
- void SetQuantIndex(const int quantindex)
- {
- m_quantindex = quantindex;
- }
+ //! Returns true if the code-block is skipped, false if not
+ bool Skipped() const { return m_skipped; }
- //! Sets whether the code block is skipped or not
- void SetSkip(bool skip)
- {
- m_skipped = skip;
- }
-
-private:
-
- //! Initialise the code block
- /*
- Initialise the code block
- \param xstart the x-coord of the first coefficient in the block
- \param xend one past the last coefficient, horizontally
- \param ystart the y-coord of the first coefficient in the block
- \param yend one past the last coefficient, vertically
- */
- void Init(const int xstart , const int ystart , const int xend , const int yend);
+ //! Sets the quantisation index
+ void SetQuantIndex( const int quantindex ){ m_quantindex = quantindex; }
-private:
+ //! Sets whether the code block is skipped or not
+ void SetSkip( bool skip ){ m_skipped = skip; }
- int m_xstart;
- int m_ystart;
- int m_xend;
- int m_yend;
- int m_xl;
- int m_yl;
+ private:
- int m_quantindex;
+ //! Initialise the code block
+ /*
+ Initialise the code block
+ \param xstart the x-coord of the first coefficient in the block
+ \param xend one past the last coefficient, horizontally
+ \param ystart the y-coord of the first coefficient in the block
+ \param yend one past the last coefficient, vertically
+ */
+ void Init( const int xstart , const int ystart , const int xend , const int yend );
- bool m_skipped;
-};
+ private:
+ int m_xstart;
+ int m_ystart;
+ int m_xend;
+ int m_yend;
+ int m_xl;
+ int m_yl;
-//! Class encapsulating all the metadata relating to a wavelet subband
-class Subband
-{
-public:
-
- //! Default constructor
- Subband();
-
- //! Constructor
- /*!
- The constructor parameters are
- \param xpos the xposition of the subband when packed into a
- big array with all the others
- \param ypos the xposition of the subband
- \param xlen the width of the subband
- \param ylen the height of the subband
- */
- Subband(int xpos, int ypos, int xlen, int ylen);
-
- //! Constructor
- /*!
- The constructor parameters are
- \param xpos the xposition of the subband when packed into a
- big array with all the others
- \param ypos the xposition of the subband
- \param xlen the width of the subband
- \param ylen the height of the subband
- \param d the depth of the subband in the wavelet transform
- */
- Subband(int xpos, int ypos, int xlen, int ylen, int d);
+ int m_quantindex;
- //! Destructor
- ~Subband();
+ bool m_skipped;
+ };
- //Default (shallow) copy constructor and operator= used
- //! Return the width of the subband
- int Xl() const
+ //! Class encapsulating all the metadata relating to a wavelet subband
+ class Subband
{
- return m_xl;
- }
+ public:
- //! Return the horizontal position of the subband
- int Xp() const
- {
- return m_xp;
- }
+ //! Default constructor
+ Subband();
- //! Return the height of the subband
- int Yl() const
- {
- return m_yl;
- }
+ //! Constructor
+ /*!
+ The constructor parameters are
+ \param xpos the xposition of the subband when packed into a
+ big array with all the others
+ \param ypos the xposition of the subband
+ \param xlen the width of the subband
+ \param ylen the height of the subband
+ */
+ Subband(int xpos, int ypos, int xlen, int ylen);
- //! Return the vertical position of the subband
- int Yp() const
- {
- return m_yp;
- }
+ //! Constructor
+ /*!
+ The constructor parameters are
+ \param xpos the xposition of the subband when packed into a
+ big array with all the others
+ \param ypos the xposition of the subband
+ \param xlen the width of the subband
+ \param ylen the height of the subband
+ \param d the depth of the subband in the wavelet transform
+ */
+ Subband(int xpos, int ypos, int xlen, int ylen, int d);
- //! Return the index of the maximum bit of the largest coefficient
- int Max() const
- {
- return m_max_bit;
- }
+ //! Destructor
+ ~Subband();
- //! Return the subband perceptual weight
- double Wt() const
- {
- return m_wt;
- }
+ //Default (shallow) copy constructor and operator= used
- //! Return the depth of the subband in the transform
- int Depth() const
- {
- return m_depth;
- }
+ //! Return the width of the subband
+ int Xl() const {return m_xl;}
- //! Return the scale of the subband, viewed as a subsampled version of the picture
- int Scale() const
- {
- return (1 << m_depth);
- }
+ //! Return the horizontal position of the subband
+ int Xp() const {return m_xp;}
- //! Return a quantisation index
- int QuantIndex() const
- {
- return m_qindex;
- }
+ //! Return the height of the subband
+ int Yl() const {return m_yl;}
- //! Return a flag indicating whether we have separate quantisers for each code block
- bool UsingMultiQuants() const
- {
- return m_multi_quants;
- }
+ //! Return the vertical position of the subband
+ int Yp() const {return m_yp;}
- //! Return the index of the parent subband
- int Parent() const
- {
- return m_parent;
- }
-
- //! Return the indices of any child subbands
- const std::vector<int>& Children() const
- {
- return m_children;
- }
+ //! Return the index of the maximum bit of the largest coefficient
+ int Max() const {return m_max_bit;}
- //! Return the index of a specific child band
- int Child(const int n) const
- {
- return m_children[n];
- }
+ //! Return the subband perceptual weight
+ double Wt() const {return m_wt;}
- //! Return the code blocks
- TwoDArray<CodeBlock>& GetCodeBlocks()
- {
- return m_code_block_array;
- }
+ //! Return the depth of the subband in the transform
+ int Depth() const {return m_depth;}
- //! Return the code blocks
- const TwoDArray<CodeBlock>& GetCodeBlocks() const
- {
- return m_code_block_array;
- }
+ //! Return the scale of the subband, viewed as a subsampled version of the picture
+ int Scale() const {return ( 1<<m_depth );}
- //! Returns true if subband is skipped, false if not
- bool Skipped() const
- {
- return m_skipped;
- }
+ //! Return a quantisation index
+ int QuantIndex() const {return m_qindex;}
- //! Set the perceptual weight
- void SetWt(const float w);
+ //! Return a flag indicating whether we have separate quantisers for each code block
+ bool UsingMultiQuants() const {return m_multi_quants; }
- //! Set the parent index
- void SetParent(const int p)
- {
- m_parent = p;
- }
+ //! Return the index of the parent subband
+ int Parent() const {return m_parent;}
- //! Set the subband depth
- void SetDepth(const int d)
- {
- m_depth = d;
- }
+ //! Return the indices of any child subbands
+ const std::vector<int>& Children() const {return m_children;}
- //! Set the index of the maximum bit of the largest coefficient
- void SetMax(const int m)
- {
- m_max_bit = m;
- };
+ //! Return the index of a specific child band
+ int Child(const int n) const {return m_children[n];}
- //! Set the number of (spatial) quantisers in the subband. Creates code block structure
- void SetNumBlocks(const int ynum , const int xnum);
+ //! Return the code blocks
+ TwoDArray<CodeBlock>& GetCodeBlocks(){ return m_code_block_array; }
- //! Set the quantisation index
- void SetQuantIndex(const int idx)
- {
- m_qindex = idx;
- }
+ //! Return the code blocks
+ const TwoDArray<CodeBlock>& GetCodeBlocks() const { return m_code_block_array; }
- //! Set the number of (spatial) quantisers in the subband. Creates code block structure
- void SetUsingMultiQuants(const bool multi)
- {
- m_multi_quants = multi;
- }
+ //! Returns true if subband is skipped, false if not
+ bool Skipped() const { return m_skipped; }
- //! Set whether the subband is skipped or not
- void SetSkip(const bool skip)
- {
- m_skipped = skip;
- }
+ //! Set the perceptual weight
+ void SetWt( const float w );
-private:
- // subband bounds
- int m_xp , m_yp , m_xl , m_yl;
+ //! Set the parent index
+ void SetParent( const int p ){ m_parent=p; }
- // perceptual weight for quantisation
- double m_wt;
+ //! Set the subband depth
+ void SetDepth( const int d ){ m_depth=d;}
- // depth in the transform
- int m_depth;
+ //! Set the index of the maximum bit of the largest coefficient
+ void SetMax( const int m ){ m_max_bit=m; };
- // quantiser index
- int m_qindex;
+ //! Set the number of (spatial) quantisers in the subband. Creates code block structure
+ void SetNumBlocks( const int ynum , const int xnum );
- // position of parent in a subband list
- int m_parent;
+ //! Set the quantisation index
+ void SetQuantIndex( const int idx){ m_qindex = idx; }
- // positions of children in the subband list
- std::vector<int> m_children;
+ //! Set the number of (spatial) quantisers in the subband. Creates code block structure
+ void SetUsingMultiQuants( const bool multi){ m_multi_quants = multi; }
- // position of the MSB of the largest absolute value
- int m_max_bit;
+ //! Set whether the subband is skipped or not
+ void SetSkip(const bool skip ){ m_skipped = skip; }
- // The code blocks
- TwoDArray<CodeBlock> m_code_block_array;
+ private:
+ // subband bounds
+ int m_xp , m_yp , m_xl , m_yl;
- // A flag indicating whether we're using one qf for each code block
- bool m_multi_quants;
+ // perceptual weight for quantisation
+ double m_wt;
- // Whether the subband is skipped or not
- bool m_skipped;
-};
+ // depth in the transform
+ int m_depth;
-//! A class encapulating all the subbands produced by a transform
-class SubbandList
-{
-public:
- //! Constructor
- SubbandList() {}
+ // quantiser index
+ int m_qindex;
- //! Destructor
- ~SubbandList() {}
+ // position of parent in a subband list
+ int m_parent;
- //Default (shallow) copy constructor and operator= used
- //! Initialise the list
- void Init(const int depth, const int xlen, const int ylen);
+ // positions of children in the subband list
+ std::vector<int> m_children;
- //! Return the length of the subband list
- int Length() const
- {
- return bands.size();
- }
+ // position of the MSB of the largest absolute value
+ int m_max_bit;
- //! Return the subband at position n (1<=n<=length)
- Subband& operator()(const int n)
- {
- return bands[n-1];
- }
+ // The code blocks
+ TwoDArray<CodeBlock> m_code_block_array;
- //! Return the subband at position n (1<=n<=length)
- const Subband& operator()(const int n) const
- {
- return bands[n-1];
- }
+ // A flag indicating whether we're using one qf for each code block
+ bool m_multi_quants;
- //! Add a band to the list
- void AddBand(const Subband& b)
- {
- bands.push_back(b);
- }
+ // Whether the subband is skipped or not
+ bool m_skipped;
+ };
- //! Remove all the bands from the list
- void Clear()
+ //! A class encapulating all the subbands produced by a transform
+ class SubbandList
{
- bands.clear();
- }
+ public:
+ //! Constructor
+ SubbandList(){}
-private:
+ //! Destructor
+ ~SubbandList(){}
- //! Given x and y spatial frequencies in cycles per degree, returns a weighting value
- float PerceptualWeight(const float xf , const float yf , const CompSort cs);
+ //Default (shallow) copy constructor and operator= used
+ //! Initialise the list
+ void Init(const int depth,const int xlen,const int ylen);
-private:
- std::vector<Subband> bands;
-};
+ //! Return the length of the subband list
+ int Length() const {return bands.size();}
-class CoeffArray;
-//! A virtual parent class to do vertical and horizontal splitting with wavelet filters
-class VHFilter
-{
+ //! Return the subband at position n (1<=n<=length)
+ Subband& operator()(const int n){return bands[n-1];}
-public:
+ //! Return the subband at position n (1<=n<=length)
+ const Subband& operator()(const int n) const {return bands[n-1];}
- VHFilter() {}
+ //! Add a band to the list
+ void AddBand(const Subband& b){bands.push_back(b);}
- virtual ~VHFilter() {}
+ //! Remove all the bands from the list
+ void Clear(){bands.clear();}
- //! Split a subband into 4
- virtual void Split(const int xp, const int yp, const int xl, const int yl, CoeffArray& coeff_data) = 0;
+ private:
- //! Create a single band from 4 quadrant bands
- virtual void Synth(const int xp, const int yp, const int xl, const int yl, CoeffArray& coeff_data) = 0;
+ //! Given x and y spatial frequencies in cycles per degree, returns a weighting value
+ float PerceptualWeight( const float xf , const float yf , const CompSort cs);
- //! Return the value of the additional bitshift
- virtual int GetShift() const = 0;
-
-protected:
+ private:
+ std::vector<Subband> bands;
+ };
+
+ class CoeffArray;
+ //! A virtual parent class to do vertical and horizontal splitting with wavelet filters
+ class VHFilter
+ {
- //! Interleave data from separate subbands into even and odd positions for in-place calculation - called by Synth
- inline void Interleave(const int xp, const int yp, const int xl, const int yl, CoeffArray& coeff_data);
+ public:
+ VHFilter(){}
- //! De-interleave data even and odd positions into separate subbands - called by Split
- inline void DeInterleave(const int xp, const int yp, const int xl, const int yl, CoeffArray& coeff_data);
+ virtual ~VHFilter(){}
- //! Shift all vals in Row by 'shift' bits to the left to increase accuracy by 'shift' bits. Used in Analysis stage of filter
- void ShiftRowLeft(CoeffType *row, int length, int shift);
+ //! Split a subband into 4
+ virtual void Split(const int xp, const int yp, const int xl, const int yl, CoeffArray& coeff_data)=0;
- //! Shift all vals in Row by 'shift' bits to the right to counter the shift in the Analysis stage. This function is used in the Synthesis stage
- void ShiftRowRight(CoeffType *row, int length, int shift);
-};
+ //! Create a single band from 4 quadrant bands
+ virtual void Synth(const int xp, const int yp, const int xl, const int yl, CoeffArray& coeff_data)=0;
-//! Class to do Daubechies (9,7) filtering operations
-class VHFilterDAUB9_7 : public VHFilter
-{
+ //! Return the value of the additional bitshift
+ virtual int GetShift() const =0;
-public:
+ protected:
- //! Split a subband into 4
- void Split(const int xp, const int yp, const int xl, const int yl, CoeffArray& coeff_data);
+ //! Interleave data from separate subbands into even and odd positions for in-place calculation - called by Synth
+ inline void Interleave( const int xp, const int yp, const int xl, const int yl, CoeffArray& coeff_data );
- //! Create a single band from 4 quadrant bands
- void Synth(const int xp, const int yp, const int xl, const int yl, CoeffArray& coeff_data);
- //! Return the value of the additional bitshift
- int GetShift() const
- {
- return 1;
- }
+ //! De-interleave data even and odd positions into separate subbands - called by Split
+ inline void DeInterleave( const int xp, const int yp, const int xl, const int yl, CoeffArray& coeff_data );
+ //! Shift all vals in Row by 'shift' bits to the left to increase accuracy by 'shift' bits. Used in Analysis stage of filter
+ void ShiftRowLeft(CoeffType *row, int length, int shift);
-};
+ //! Shift all vals in Row by 'shift' bits to the right to counter the shift in the Analysis stage. This function is used in the Synthesis stage
+ void ShiftRowRight(CoeffType *row, int length, int shift);
+ };
-//! Class to do (5,3) wavelet filtering operations
-class VHFilterLEGALL5_3 : public VHFilter
-{
+ //! Class to do Daubechies (9,7) filtering operations
+ class VHFilterDAUB9_7 : public VHFilter
+ {
-public:
+ public:
- //! Split a subband into 4
- void Split(const int xp, const int yp, const int xl, const int yl, CoeffArray& coeff_data);
+ //! Split a subband into 4
+ void Split(const int xp, const int yp, const int xl, const int yl, CoeffArray& coeff_data);
- //! Create a single band from 4 quadrant bands
- void Synth(const int xp, const int yp, const int xl, const int yl, CoeffArray& coeff_data);
+ //! Create a single band from 4 quadrant bands
+ void Synth(const int xp, const int yp, const int xl, const int yl, CoeffArray& coeff_data);
- //! Return the value of the additional bitshift
- int GetShift() const
- {
- return 1;
- }
+ //! Return the value of the additional bitshift
+ int GetShift() const {return 1;}
-#ifdef HAVE_MMX
- inline void HorizSynth(int xp, int xl, int ystart, int yend, CoeffArray &coeff_data);
-#endif
+ };
-};
+ //! Class to do (5,3) wavelet filtering operations
+ class VHFilterLEGALL5_3 : public VHFilter
+ {
-//! A short filter that's actually close to Daubechies (9,7) but with just two lifting steps
-class VHFilterDD9_7 : public VHFilter
-{
+ public:
-public:
+ //! Split a subband into 4
+ void Split(const int xp, const int yp, const int xl, const int yl, CoeffArray& coeff_data);
- //! Split a subband into 4
- void Split(const int xp, const int yp, const int xl, const int yl, CoeffArray& coeff_data);
+ //! Create a single band from 4 quadrant bands
+ void Synth(const int xp, const int yp, const int xl, const int yl, CoeffArray& coeff_data);
- //! Create a single band from 4 quadrant bands
- void Synth(const int xp, const int yp, const int xl, const int yl, CoeffArray& coeff_data);
+ //! Return the value of the additional bitshift
+ int GetShift() const {return 1;}
- //! Return the value of the additional bitshift
- int GetShift() const
- {
- return 1;
- }
-};
+#ifdef HAVE_MMX
+ inline void HorizSynth (int xp, int xl, int ystart, int yend, CoeffArray &coeff_data);
+#endif
-//! An extension of DD9_7, with a better low-pass filter but more computation
-class VHFilterDD13_7 : public VHFilter
-{
+ };
-public:
+ //! A short filter that's actually close to Daubechies (9,7) but with just two lifting steps
+ class VHFilterDD9_7 : public VHFilter
+ {
- //! Split a subband into 4
- void Split(const int xp, const int yp, const int xl, const int yl, CoeffArray& coeff_data);
+ public:
- //! Create a single band from 4 quadrant bands
- void Synth(const int xp, const int yp, const int xl, const int yl, CoeffArray& coeff_data);
+ //! Split a subband into 4
+ void Split(const int xp, const int yp, const int xl, const int yl, CoeffArray& coeff_data);
- //! Return the value of the additional bitshift
- int GetShift() const
- {
- return 1;
- }
+ //! Create a single band from 4 quadrant bands
+ void Synth(const int xp, const int yp, const int xl, const int yl, CoeffArray& coeff_data);
-};
+ //! Return the value of the additional bitshift
+ int GetShift() const {return 1;}
+ };
-//! Class to do Haar wavelet filtering operations
-class VHFilterHAAR0 : public VHFilter
-{
-public:
+ //! An extension of DD9_7, with a better low-pass filter but more computation
+ class VHFilterDD13_7 : public VHFilter
+ {
- //! Split a subband into 4
- void Split(const int xp, const int yp, const int xl, const int yl, CoeffArray& coeff_data);
+ public:
- //! Create a single band from 4 quadrant bands
- void Synth(const int xp, const int yp, const int xl, const int yl, CoeffArray& coeff_data);
+ //! Split a subband into 4
+ void Split(const int xp, const int yp, const int xl, const int yl, CoeffArray& coeff_data);
- //! Return the value of the additional bitshift
- int GetShift() const
- {
- return 0;
- }
+ //! Create a single band from 4 quadrant bands
+ void Synth(const int xp, const int yp, const int xl, const int yl, CoeffArray& coeff_data);
+ //! Return the value of the additional bitshift
+ int GetShift() const {return 1;}
-};
+ };
-//! Class to do Haar wavelet filtering operations with a single shift per level
-class VHFilterHAAR1 : public VHFilter
-{
+ //! Class to do Haar wavelet filtering operations
+ class VHFilterHAAR0 : public VHFilter
+ {
-public:
+ public:
- //! Split a subband into 4
- void Split(const int xp, const int yp, const int xl, const int yl, CoeffArray& coeff_data);
+ //! Split a subband into 4
+ void Split(const int xp, const int yp, const int xl, const int yl, CoeffArray& coeff_data);
- //! Create a single band from 4 quadrant bands
- void Synth(const int xp, const int yp, const int xl, const int yl, CoeffArray& coeff_data);
+ //! Create a single band from 4 quadrant bands
+ void Synth(const int xp, const int yp, const int xl, const int yl, CoeffArray& coeff_data);
- //! Return the value of the additional bitshift
- int GetShift() const
- {
- return 1;
- }
+ //! Return the value of the additional bitshift
+ int GetShift() const {return 0;}
-};
+ };
-//! Class to do Haar wavelet filtering operations with a double shift per level
-class VHFilterHAAR2 : public VHFilter
-{
+ //! Class to do Haar wavelet filtering operations with a single shift per level
+ class VHFilterHAAR1 : public VHFilter
+ {
-public:
+ public:
- //! Split a subband into 4
- void Split(const int xp, const int yp, const int xl, const int yl, CoeffArray& coeff_data);
+ //! Split a subband into 4
+ void Split(const int xp, const int yp, const int xl, const int yl, CoeffArray& coeff_data);
- //! Create a single band from 4 quadrant bands
- void Synth(const int xp, const int yp, const int xl, const int yl, CoeffArray& coeff_data);
+ //! Create a single band from 4 quadrant bands
+ void Synth(const int xp, const int yp, const int xl, const int yl, CoeffArray& coeff_data);
- //! Return a correction factor to compensate for non-unity power gain of low-pass filter
- double GetLowFactor() const
- {
- return 1.414213562;
- }
+ //! Return the value of the additional bitshift
+ int GetShift() const {return 1;}
- //! Return a correction factor to compensate for non-unity power gain of high-pass filter
- double GetHighFactor() const
- {
- return 0.707106781;
- }
+ };
- //! Return the value of the additional bitshift
- int GetShift() const
- {
- return 2;
- }
-};
+ //! Class to do Haar wavelet filtering operations with a double shift per level
+ class VHFilterHAAR2 : public VHFilter
+ {
+ public:
+ //! Split a subband into 4
+ void Split(const int xp, const int yp, const int xl, const int yl, CoeffArray& coeff_data);
-// Lifting steps used in the filters
+ //! Create a single band from 4 quadrant bands
+ void Synth(const int xp, const int yp, const int xl, const int yl, CoeffArray& coeff_data);
-//! Class to do two-tap prediction lifting step
-template<int shift>
-class PredictStepShift
-{
+ //! Return a correction factor to compensate for non-unity power gain of low-pass filter
+ double GetLowFactor() const { return 1.414213562;}
-public:
+ //! Return a correction factor to compensate for non-unity power gain of high-pass filter
+ double GetHighFactor() const { return 0.707106781;}
- //! Constructor
- PredictStepShift() {}
+ //! Return the value of the additional bitshift
+ int GetShift() const {return 2;}
- // Assume default copy constructor, assignment= and destructor //
+ };
- //! Do the filtering
- /*
- Do the filtering.
- \param in_val the value being predicted
- \param val1 the first value being used for prediction
- \param val2 the second value being used for prediction
- */
- inline void Filter(CoeffType& in_val, const CoeffType& val1, const CoeffType& val2) const
- {
- in_val -= ((val1 + val2 + (1 << (shift - 1))) >> shift);
- }
-};
-//! Class to do two-tap updating lifting step
-template<int shift>
-class UpdateStepShift
-{
+ // Lifting steps used in the filters
-public:
- //! Constructor
- UpdateStepShift() {}
+ //! Class to do two-tap prediction lifting step
+ template<int shift>
+ class PredictStepShift
+ {
- //! Do the filtering
- /*
- Do the filtering.
- \param in_val the value being updated
- \param val1 the first value being used for updating
- \param val2 the second value being used for updating
- */
- inline void Filter(CoeffType& in_val, const CoeffType& val1, const CoeffType& val2) const
- {
- in_val += ((val1 + val2 + (1 << (shift - 1))) >> shift);
- }
+ public:
-};
+ //! Constructor
+ PredictStepShift(){}
-//! Class to do symmetric four-tap prediction lifting step
-template <int shift , int tap1, int tap2>
-class PredictStepFourTap
-{
-public:
+ // Assume default copy constructor, assignment= and destructor //
- //! Constructor
- PredictStepFourTap() {}
+ //! Do the filtering
+ /*
+ Do the filtering.
+ \param in_val the value being predicted
+ \param val1 the first value being used for prediction
+ \param val2 the second value being used for prediction
+ */
+ inline void Filter(CoeffType& in_val, const CoeffType& val1, const CoeffType& val2) const
+ {
+ in_val -= (( val1 + val2 + (1<<(shift-1)) ) >>shift );
+ }
- // Assume default copy constructor, assignment= and destructor //
+ };
- //! Do the filtering
- inline void Filter(CoeffType& in_val, const CoeffType& val1, const CoeffType& val2 ,
- const CoeffType& val3, const CoeffType& val4) const
- {
- in_val -= (tap1 * (val1 + val2) + tap2 * (val3 + val4) + (1 << (shift - 1))) >> shift;
- }
-};
+ //! Class to do two-tap updating lifting step
+ template<int shift>
+ class UpdateStepShift
+ {
-//! Class to do symmetric four-tap update lifting step
-template <int shift , int tap1 , int tap2>
-class UpdateStepFourTap
-{
+ public:
+ //! Constructor
+ UpdateStepShift(){}
-public:
- //! Constructor
- UpdateStepFourTap() {}
+ //! Do the filtering
+ /*
+ Do the filtering.
+ \param in_val the value being updated
+ \param val1 the first value being used for updating
+ \param val2 the second value being used for updating
+ */
+ inline void Filter(CoeffType& in_val, const CoeffType& val1, const CoeffType& val2) const
+ {
+ in_val += ( ( val1 + val2 + (1<<(shift-1)) ) >>shift );
+ }
+
+ };
- //! Do the filtering
- inline void Filter(CoeffType& in_val, const CoeffType& val1, const CoeffType& val2 ,
- const CoeffType& val3, const CoeffType& val4) const
+ //! Class to do symmetric four-tap prediction lifting step
+ template <int shift , int tap1, int tap2>
+ class PredictStepFourTap
+ {
+ public:
+
+ //! Constructor
+ PredictStepFourTap(){}
+
+ // Assume default copy constructor, assignment= and destructor //
+
+ //! Do the filtering
+ inline void Filter(CoeffType& in_val, const CoeffType& val1, const CoeffType& val2 ,
+ const CoeffType& val3, const CoeffType& val4 ) const
+ {
+ in_val -= ( tap1*( val1 + val2 ) + tap2*( val3 + val4 ) + (1<<(shift-1)))>>shift;
+ }
+ };
+
+ //! Class to do symmetric four-tap update lifting step
+ template <int shift , int tap1 , int tap2>
+ class UpdateStepFourTap
+ {
+
+ public:
+ //! Constructor
+ UpdateStepFourTap(){}
+
+ //! Do the filtering
+ inline void Filter(CoeffType& in_val, const CoeffType& val1, const CoeffType& val2 ,
+ const CoeffType& val3, const CoeffType& val4 ) const
+ {
+ in_val += ( tap1*( val1 + val2 ) + tap2*( val3 + val4 ) + (1<<(shift-1)) )>>shift;
+ }
+ };
+
+ //! Class to do two-tap prediction lifting step for Daubechies (9,7)
+ template <int gain> class PredictStep97
+ {
+ public:
+
+ //! Constructor
+ PredictStep97(){}
+
+ // Assume default copy constructor, assignment= and destructor //
+
+ //! Do the filtering
+ /*
+ Do the filtering.
+ \param in_val the value being predicted
+ \param val1 the first value being used for prediction
+ \param val2 the second value being used for prediction
+ */
+ inline void Filter(CoeffType& in_val, const CoeffType& val1, const CoeffType& val2) const
+ {
+ in_val -= static_cast< CoeffType >( (gain * static_cast< int >( val1 + val2 )) >>12 );
+ }
+ };
+
+ //! Class to do two-tap update lifting step for Daubechies (9,7)
+ template <int gain> class UpdateStep97
+ {
+
+ public:
+ //! Constructor
+ UpdateStep97(){}
+
+ //! Do the filtering
+ /*
+ Do the filtering.
+ \param in_val the value being updated
+ \param val1 the first value being used for updating
+ \param val2 the second value being used for updating
+ */
+ inline void Filter(CoeffType& in_val, const CoeffType& val1, const CoeffType& val2) const
+ {
+ in_val += static_cast< CoeffType >( (gain * static_cast< int >( val1 + val2 )) >>12 );
+ }
+ };
+
+ //! A class for wavelet coefficient data.
+ /*!
+ A class for encapsulating coefficient data, derived from TwoDArray..
+ */
+ class CoeffArray: public TwoDArray<CoeffType>
{
- in_val += (tap1 * (val1 + val2) + tap2 * (val3 + val4) + (1 << (shift - 1))) >> shift;
- }
-};
+ public:
+ //! Default constructor
+ /*!
+ Default constructor creates an empty array.
+ */
+ CoeffArray(): TwoDArray<CoeffType>(){}
-//! Class to do two-tap prediction lifting step for Daubechies (9,7)
-template <int gain> class PredictStep97
-{
-public:
+ //! Constructor.
+ /*!
+ Contructor creates a two-D array, with specified size and colour
+ format.
+ */
+ CoeffArray(int height, int width, CompSort cs=Y_COMP):
+ TwoDArray<CoeffType>(height, width), m_csort(cs){}
- //! Constructor
- PredictStep97() {}
+ //copy constructor and assignment= derived by inheritance
- // Assume default copy constructor, assignment= and destructor //
+ //! Destructor
+ ~CoeffArray(){}
- //! Do the filtering
- /*
- Do the filtering.
- \param in_val the value being predicted
- \param val1 the first value being used for prediction
- \param val2 the second value being used for prediction
- */
- inline void Filter(CoeffType& in_val, const CoeffType& val1, const CoeffType& val2) const
- {
- in_val -= static_cast< CoeffType >((gain * static_cast< int >(val1 + val2)) >> 12);
- }
-};
+ //! Return which component is stored
+ const CompSort& CSort() const {return m_csort;}
-//! Class to do two-tap update lifting step for Daubechies (9,7)
-template <int gain> class UpdateStep97
-{
+ //! Set the type of component being stored
+ void SetCSort(const CompSort cs){ m_csort = cs; }
-public:
- //! Constructor
- UpdateStep97() {}
+ //! Returns the set of subbands
+ SubbandList& BandList(){return m_band_list;}
- //! Do the filtering
- /*
- Do the filtering.
- \param in_val the value being updated
- \param val1 the first value being used for updating
- \param val2 the second value being used for updating
- */
- inline void Filter(CoeffType& in_val, const CoeffType& val1, const CoeffType& val2) const
- {
- in_val += static_cast< CoeffType >((gain * static_cast< int >(val1 + val2)) >> 12);
- }
-};
-
-//! A class for wavelet coefficient data.
-/*!
- A class for encapsulating coefficient data, derived from TwoDArray..
- */
-class CoeffArray: public TwoDArray<CoeffType>
-{
-public:
- //! Default constructor
- /*!
- Default constructor creates an empty array.
- */
- CoeffArray(): TwoDArray<CoeffType>() {}
+ //! Returns the set of subbands
+ const SubbandList& BandList() const {return m_band_list;}
- //! Constructor.
- /*!
- Contructor creates a two-D array, with specified size and colour
- format.
- */
- CoeffArray(int height, int width, CompSort cs = Y_COMP):
- TwoDArray<CoeffType>(height, width), m_csort(cs) {}
+ //! Sets the subband weights
+ /*!
+ Sets perceptual weights for the subbands. Takes into account both perceptual factors
+ (weight noise less at higher spatial frequencies) and the scaling needed for the
+ wavelet transform.
+ */
+ void SetBandWeights (const EncoderParams& encparams,
+ const PictureParams& pparams,
+ const CompSort csort,
+ const float cpd_scale_factor);
- //copy constructor and assignment= derived by inheritance
+ private:
- //! Destructor
- ~CoeffArray() {}
+ CompSort m_csort;
- //! Return which component is stored
- const CompSort& CSort() const
- {
- return m_csort;
- }
+ // The subband list to be used for conventional transform apps
+ SubbandList m_band_list;
- //! Set the type of component being stored
- void SetCSort(const CompSort cs)
- {
- m_csort = cs;
- }
+ private:
- //! Returns the set of subbands
- SubbandList& BandList()
- {
- return m_band_list;
- }
+ //! Given x and y spatial frequencies in cycles per degree, returns a weighting value
+ float PerceptualWeight(float xf,float yf,CompSort cs);
- //! Returns the set of subbands
- const SubbandList& BandList() const
- {
- return m_band_list;
- }
+ };
- //! Sets the subband weights
+ //! A class to do wavelet transforms
/*!
- Sets perceptual weights for the subbands. Takes into account both perceptual factors
- (weight noise less at higher spatial frequencies) and the scaling needed for the
- wavelet transform.
+ A class to do forward and backward wavelet transforms by iteratively splitting or merging the
+ lowest frequency band.
*/
- void SetBandWeights(const EncoderParams& encparams,
- const PictureParams& pparams,
- const CompSort csort,
- const float cpd_scale_factor);
-
-private:
-
- CompSort m_csort;
-
- // The subband list to be used for conventional transform apps
- SubbandList m_band_list;
-
-private:
-
- //! Given x and y spatial frequencies in cycles per degree, returns a weighting value
- float PerceptualWeight(float xf, float yf, CompSort cs);
-
-};
-
-//! A class to do wavelet transforms
-/*!
- A class to do forward and backward wavelet transforms by iteratively splitting or merging the
- lowest frequency band.
-*/
-class WaveletTransform
-{
-public:
- //! Constructor
- WaveletTransform(int d = 4, WltFilter f = DAUB9_7);
+ class WaveletTransform
+ {
+ public:
+ //! Constructor
+ WaveletTransform(int d = 4, WltFilter f = DAUB9_7);
- //! Destructor
- virtual ~WaveletTransform();
+ //! Destructor
+ virtual ~WaveletTransform();
- //! Transforms the data to and from the wavelet domain
- /*!
- Transforms the data to and from the wavelet domain.
- \param d the direction of the transform
- \param pic_data the data to be transformed
- \param coeff_data array that holds the transform coefficient data
- */
- void Transform(const Direction d, PicArray& pic_data, CoeffArray& coeff_data);
+ //! Transforms the data to and from the wavelet domain
+ /*!
+ Transforms the data to and from the wavelet domain.
+ \param d the direction of the transform
+ \param pic_data the data to be transformed
+ \param coeff_data array that holds the transform coefficient data
+ */
+ void Transform(const Direction d, PicArray& pic_data, CoeffArray& coeff_data);
-private:
+ private:
-private:
+ private:
- // Private variables
+ // Private variables
- //! Depth of the transform
- int m_depth;
+ //! Depth of the transform
+ int m_depth;
- //! The (vertical and horizontal) wavelet filter set to be used
- WltFilter m_filt_sort;
+ //! The (vertical and horizontal) wavelet filter set to be used
+ WltFilter m_filt_sort;
- //! A class to do the vertical and horizontal filtering required
- VHFilter* m_vhfilter;
+ //! A class to do the vertical and horizontal filtering required
+ VHFilter* m_vhfilter;
-private:
- // Private functions
- //! Private, bodyless copy constructor: class should not be copied
- WaveletTransform(const WaveletTransform& cpy);
+ private:
+ // Private functions
+ //! Private, bodyless copy constructor: class should not be copied
+ WaveletTransform(const WaveletTransform& cpy);
- //! Private, bodyless copy operator=: class should not be assigned
- WaveletTransform& operator=(const WaveletTransform& rhs);
+ //! Private, bodyless copy operator=: class should not be assigned
+ WaveletTransform& operator=(const WaveletTransform& rhs);
-};
+ };
}// end namespace dirac
#endif
diff --git a/src/filters/parser/DiracSplitter/libdirac/libdirac_common/wavelet_utils_mmx.cpp b/src/filters/parser/DiracSplitter/libdirac/libdirac_common/wavelet_utils_mmx.cpp
index 70d5e511e..0a8953f8d 100644
--- a/src/filters/parser/DiracSplitter/libdirac/libdirac_common/wavelet_utils_mmx.cpp
+++ b/src/filters/parser/DiracSplitter/libdirac/libdirac_common/wavelet_utils_mmx.cpp
@@ -36,7 +36,7 @@
* or the LGPL.
* ***** END LICENSE BLOCK ***** */
-/*!
+/*!
* MMX version of wavelet transform routines. Note that these routines
* assume that wavelet coefficients, of type CoeffType, are in fact
* shorts. This is set in libdirac_common/common.h. Turning MMX on
@@ -55,76 +55,76 @@ static TwoDArray<CoeffType> t_temp_data;
#if 0
//Attempt1
-inline void Interleave_mmx(const int xp ,
- const int yp ,
- const int xl ,
- const int yl ,
- CoeffArray& coeff_data)
+inline void Interleave_mmx( const int xp ,
+ const int yp ,
+ const int xl ,
+ const int yl ,
+ CoeffArray& coeff_data)
{
- const int xl2(xl >> 1);
- const int yl2(yl >> 1);
- const int yend(yp + yl);
+ const int xl2( xl>>1);
+ const int yl2( yl>>1);
+ const int yend( yp + yl );
- if(coeff_data.LengthX() > t_temp_data.LengthX() ||
- coeff_data.LengthY() > t_temp_data.LengthY())
+ if (coeff_data.LengthX() > t_temp_data.LengthX() ||
+ coeff_data.LengthY() > t_temp_data.LengthY())
{
t_temp_data.Resize(coeff_data.LengthY(), coeff_data.LengthX());
}
// Make a temporary copy of the subband
- for(int j = yp; j < yend ; j++)
- memcpy(t_temp_data[j-yp] , coeff_data[j] + xp , xl * sizeof(CoeffType));
+ for (int j = yp; j<yend ; j++ )
+ memcpy( t_temp_data[j-yp] , coeff_data[j]+xp , xl * sizeof( CoeffType ) );
- int stopx = (xl2 >> 2) << 2;
+ int stopx = (xl2>>2)<<2;
// Re-order to interleave
- for(int j = 0, s = yp; j < yl2 ; j++, s += 2)
+ for (int j = 0, s=yp; j<yl2 ; j++, s+=2)
{
CoeffType *tmp1 = &t_temp_data[j][0];
CoeffType *out = &coeff_data[s][xp];
- for(int i = 0 , t = xp ; i < xp + stopx ; i += 4 , t += 8)
+ for (int i = 0 , t = xp ; i<xp+stopx ; i+=4 , t+=8)
{
__m64 m1 = *(__m64 *)tmp1;
- __m64 m2 = *(__m64 *)(tmp1 + xl2);
- *(__m64 *)out = _mm_unpacklo_pi16(m1, m2);
- out += 4;
- *(__m64 *)out = _mm_unpackhi_pi16(m1, m2);
- out += 4;
+ __m64 m2 = *(__m64 *)(tmp1+xl2);
+ *(__m64 *)out = _mm_unpacklo_pi16 (m1, m2);
+ out+=4;
+ *(__m64 *)out = _mm_unpackhi_pi16 (m1, m2);
+ out+=4;
tmp1 += 4;
}
- for(int i = xp + stopx , r = 2 * (xp + stopx) ; i < xl2 ; i++ , r += 2)
+ for (int i = xp+stopx , r=2*(xp+stopx) ; i<xl2 ; i++ , r += 2)
{
*out = *tmp1;
++out;
- *out = *(tmp1 + xl2);
+ *out = *(tmp1+xl2);
++out;
++tmp1;
}
- }// j
-
- for(int j = yl2, s = yp + 1 ; j < yl ; j++ , s += 2)
+ }// j
+
+ for (int j = yl2, s=yp+1 ; j<yl ; j++ , s += 2)
{
CoeffType *tmp1 = &t_temp_data[j][0];
//CoeffType *tmp2 = &t_temp_data[j][xl2];
CoeffType *out = &coeff_data[s][xp];
- for(int i = 0 , t = xp; i < stopx ; i += 4 , t += 8)
+ for (int i = 0 , t=xp; i<stopx ; i+=4 , t += 8)
{
__m64 m1 = *(__m64 *)tmp1;
- __m64 m2 = *(__m64 *)(tmp1 + xl2);
- *(__m64 *)out = _mm_unpacklo_pi16(m1, m2);
- out += 4;
- *(__m64 *)out = _mm_unpackhi_pi16(m1, m2);
- out += 4;
+ __m64 m2 = *(__m64 *)(tmp1+xl2);
+ *(__m64 *)out = _mm_unpacklo_pi16 (m1, m2);
+ out+=4;
+ *(__m64 *)out = _mm_unpackhi_pi16 (m1, m2);
+ out+=4;
tmp1 += 4;
}
- for(int i = stopx , r = 2 * (xp + stopx) ; i < xl2 ; i++ , r += 2)
+ for (int i = stopx , r=2*(xp+stopx) ; i<xl2 ; i++ , r += 2)
{
*out = *tmp1;
++out;
- *out = *(tmp1 + xl2);
+ *out = *(tmp1+xl2);
++out;
++tmp1;
}
- }// j
+ }// j
_mm_empty();
}
@@ -132,13 +132,13 @@ inline void Interleave_mmx(const int xp ,
void VHFilter::ShiftRowLeft(CoeffType *row, int length, int shift)
{
- int xstop = length / 4 * 4;
+ int xstop = length/4*4;
CoeffType *shift_row = row;
- for(int i = 0; i < xstop; i += 4, shift_row += 4)
- * (__m64 *)shift_row = _mm_slli_pi16(*(__m64 *)shift_row, shift);
+ for (int i = 0; i < xstop; i+=4, shift_row+=4)
+ *(__m64 *)shift_row = _mm_slli_pi16 (*(__m64 *)shift_row, shift);
// mopup
- for(int i = xstop; i < length; ++i)
+ for (int i = xstop; i < length; ++i)
row[i] <<= shift;
_mm_empty();
@@ -147,123 +147,123 @@ void VHFilter::ShiftRowLeft(CoeffType *row, int length, int shift)
void VHFilter::ShiftRowRight(CoeffType *row, int length, int shift)
{
CoeffType *shift_row = row;
- int round_val = 1 << (shift - 1);
- __m64 mmx_round = _mm_set_pi16(round_val, round_val, round_val, round_val);
+ int round_val = 1<<(shift-1);
+ __m64 mmx_round = _mm_set_pi16( round_val, round_val, round_val, round_val);
- int xstop = length / 4 * 4;
- for(int i = 0; i < xstop; i += 4, shift_row += 4)
+ int xstop = length/4*4;
+ for (int i = 0; i < xstop; i+=4, shift_row+=4)
{
- __m64 tmp = _mm_add_pi16(*(__m64 *)shift_row, mmx_round);
+ __m64 tmp = _mm_add_pi16 (*(__m64 *)shift_row, mmx_round);
*(__m64 *)shift_row = _mm_srai_pi16(tmp, shift);
}
// mopup
- for(int i = xstop; i < length; ++i)
- row[i] = ((row[i] + round_val) >> shift);
+ for (int i = xstop; i < length; ++i)
+ row[i] = ((row[i]+round_val)>>shift);
_mm_empty();
}
-inline void Interleave_mmx(const int xp ,
- const int yp ,
- const int xl ,
- const int yl ,
- CoeffArray& coeff_data)
+inline void Interleave_mmx( const int xp ,
+ const int yp ,
+ const int xl ,
+ const int yl ,
+ CoeffArray& coeff_data)
{
- const int xl2(xl >> 1);
- const int yl2(yl >> 1);
- const int yend(yp + yl);
+ const int xl2( xl>>1);
+ const int yl2( yl>>1);
+ const int yend( yp + yl );
- if(coeff_data.LengthX() > t_temp_data.LengthX() ||
- coeff_data.LengthY() > t_temp_data.LengthY())
+ if (coeff_data.LengthX() > t_temp_data.LengthX() ||
+ coeff_data.LengthY() > t_temp_data.LengthY())
{
t_temp_data.Resize(coeff_data.LengthY(), coeff_data.LengthX());
}
// Make a temporary copy of the subband. We are doing a vertical
// interleave while copying
- for(int j = yp, s = 0; j < yp + yl2 ; j++, s += 2)
- memcpy(t_temp_data[s] , coeff_data[j] + xp , xl * sizeof(CoeffType));
- for(int j = yp + yl2, s = 1; j < yend ; j++, s += 2)
- memcpy(t_temp_data[s] , coeff_data[j] + xp , xl * sizeof(CoeffType));
+ for (int j = yp, s=0; j<yp+yl2 ; j++, s+=2 )
+ memcpy( t_temp_data[s] , coeff_data[j]+xp , xl * sizeof( CoeffType ) );
+ for (int j = yp+yl2, s=1; j<yend ; j++, s+=2 )
+ memcpy( t_temp_data[s] , coeff_data[j]+xp , xl * sizeof( CoeffType ) );
- int stopx = (xl2 >> 2) << 2;
+ int stopx = (xl2>>2)<<2;
// Re-order to horizontally interleave
- for(int j = 0, s = yp; j < yl ; j++, ++s)
+ for (int j = 0, s=yp; j<yl ; j++, ++s)
{
CoeffType *tmp1 = &t_temp_data[j][0];
CoeffType *out = &coeff_data[s][xp];
- for(int i = 0 , t = xp ; i < xp + stopx ; i += 4 , t += 8)
+ for (int i = 0 , t = xp ; i<xp+stopx ; i+=4 , t+=8)
{
__m64 m1 = *(__m64 *)tmp1;
- __m64 m2 = *(__m64 *)(tmp1 + xl2);
- *(__m64 *)out = _mm_unpacklo_pi16(m1, m2);
- out += 4;
- *(__m64 *)out = _mm_unpackhi_pi16(m1, m2);
- out += 4;
+ __m64 m2 = *(__m64 *)(tmp1+xl2);
+ *(__m64 *)out = _mm_unpacklo_pi16 (m1, m2);
+ out+=4;
+ *(__m64 *)out = _mm_unpackhi_pi16 (m1, m2);
+ out+=4;
tmp1 += 4;
}
- for(int i = xp + stopx , r = 2 * (xp + stopx) ; i < xl2 ; i++ , r += 2)
+ for (int i = xp+stopx , r=2*(xp+stopx) ; i<xl2 ; i++ , r += 2)
{
*out = *tmp1;
++out;
- *out = *(tmp1 + xl2);
+ *out = *(tmp1+xl2);
++out;
++tmp1;
}
- }// j
-
+ }// j
+
_mm_empty();
}
-void VHFilterDD9_7::Synth(const int xp ,
- const int yp ,
- const int xl ,
- const int yl ,
- CoeffArray& coeff_data)
+void VHFilterDD9_7::Synth(const int xp ,
+ const int yp ,
+ const int xl ,
+ const int yl ,
+ CoeffArray& coeff_data)
{
int i, j;
- const int xend(xp + xl);
- const int yend(yp + yl);
- const int ymid = yp + yl / 2;
+ const int xend( xp+xl );
+ const int yend( yp+yl );
+ const int ymid = yp+yl/2;
PredictStepShift<2> predict;
- __m64 pred_round = _mm_set_pi16(1 << (2 - 1), 1 << (2 - 1), 1 << (2 - 1), 1 << (2 - 1));
-
- int xstop = xp + ((xl >> 2) << 2);
+ __m64 pred_round = _mm_set_pi16 (1<<(2-1), 1<<(2-1), 1<<(2-1), 1<<(2-1));
+
+ int xstop = xp + ((xl>>2)<<2);
// First lifting stage
// Top edge
CoeffType *in1 = coeff_data[ymid];
CoeffType *in2 = coeff_data[ymid];
CoeffType *out = coeff_data[yp];
- for(i = xp ; i < xstop ; i += 4)
+ for ( i = xp ; i < xstop ; i+=4 )
{
// tmp = val + val2
- __m64 tmp = _mm_add_pi16(*(__m64 *)in1, *(__m64 *)in2);
+ __m64 tmp = _mm_add_pi16 (*(__m64 *)in1, *(__m64 *)in2);
// unbiased rounding tmp = (tmp + 1<<(shift-1))>>shift
tmp = _mm_add_pi16(tmp, pred_round);
tmp = _mm_srai_pi16(tmp, 2);
// in_val -= tmp;
- *(__m64 *)out = _mm_sub_pi16(*(__m64*)out, tmp);
+ *(__m64 *)out = _mm_sub_pi16 (*(__m64*)out, tmp);
out += 4;
in1 += 4;
in2 += 4;
}
// Middle bit
- for(j = 1 ; j < yl / 2 ; ++j)
+ for ( j=1 ; j < yl/2 ; ++j )
{
in1 = coeff_data[ymid+j-1];
in2 = coeff_data[ymid+j];
out = coeff_data[yp+j];
- for(i = xp ; i < xstop ; i += 4)
+ for ( i = xp ; i < xstop ; i+=4 )
{
// tmp = val + val2
- __m64 tmp = _mm_add_pi16(*(__m64 *)in1, *(__m64 *)in2);
+ __m64 tmp = _mm_add_pi16 (*(__m64 *)in1, *(__m64 *)in2);
// unbiased rounding tmp = (tmp + 1<<(shift-1))>>shift
tmp = _mm_add_pi16(tmp, pred_round);
tmp = _mm_srai_pi16(tmp, 2);
// in_val -= tmp;
- *(__m64 *)out = _mm_sub_pi16(*(__m64*)out, tmp);
+ *(__m64 *)out = _mm_sub_pi16 (*(__m64*)out, tmp);
out += 4;
in1 += 4;
in2 += 4;
@@ -271,261 +271,261 @@ void VHFilterDD9_7::Synth(const int xp ,
}
// Mopup
- if(xstop != xend)
+ if (xstop != xend)
{
- for(i = xstop ; i < xend ; i++)
+ for ( i = xstop ; i < xend ; i++)
{
- predict.Filter(coeff_data[yp][i] , coeff_data[ymid][i] , coeff_data[ymid][i]);
+ predict.Filter( coeff_data[yp][i] , coeff_data[ymid][i] , coeff_data[ymid][i] );
}// i
- for(j = 1 ; j < yl / 2 ; ++j)
+ for ( j=1 ; j < yl/2 ; ++j )
{
- for(i = xstop ; i < xend ; i++)
+ for ( i = xstop ; i < xend ; i++)
{
- predict.Filter(coeff_data[yp+j][i] , coeff_data[ymid+j-1][i] , coeff_data[ymid+j][i]);
+ predict.Filter( coeff_data[yp+j][i] , coeff_data[ymid+j-1][i] , coeff_data[ymid+j][i] );
}// i
}// j
}
-
+
// Second lifting stage
- UpdateStepFourTap < 4 , 9 , -1 > update;
+ UpdateStepFourTap< 4 , 9 , -1> update;
// rounding factor for update step
- __m64 update_round = _mm_set_pi32(1 << (4 - 1), 1 << (4 - 1));
+ __m64 update_round = _mm_set_pi32 (1<<(4-1), 1<<(4-1));
// top edge
in1 = coeff_data[yp];
in2 = coeff_data[yp+1];
CoeffType *in3 = coeff_data[yp];
CoeffType *in4 = coeff_data[yp+2];
out = coeff_data[ymid];
- __m64 tap1 = _mm_set_pi16(9, 9, 9, 9);
- __m64 tap2 = _mm_set_pi16(-1, -1, -1, -1);
-
- for(i = xp ; i < xstop ; i += 4)
+ __m64 tap1 = _mm_set_pi16 (9, 9, 9, 9);
+ __m64 tap2 = _mm_set_pi16 (-1, -1, -1, -1);
+
+ for ( i = xp ; i < xstop ; i+=4 )
{
__m64 val1, val2, val3, val4, tmp1, tmp2;
val1 = _mm_add_pi16(*(__m64*)in1, *(__m64*)in2);
- tmp1 = _mm_mullo_pi16(val1, tap1);
- tmp2 = _mm_mulhi_pi16(val1, tap1);
- val3 = _mm_unpackhi_pi16(tmp1, tmp2);
- val1 = _mm_unpacklo_pi16(tmp1, tmp2);
+ tmp1 = _mm_mullo_pi16 (val1, tap1);
+ tmp2 = _mm_mulhi_pi16 (val1, tap1);
+ val3 = _mm_unpackhi_pi16 (tmp1, tmp2);
+ val1 = _mm_unpacklo_pi16 (tmp1, tmp2);
val2 = _mm_add_pi16(*(__m64*)in3, *(__m64*)in4);
- tmp1 = _mm_mullo_pi16(val2, tap2);
- tmp2 = _mm_mulhi_pi16(val2, tap2);
- val4 = _mm_unpackhi_pi16(tmp1, tmp2);
- val2 = _mm_unpacklo_pi16(tmp1, tmp2);
-
- val1 = _mm_add_pi32(val1, val2);
- val3 = _mm_add_pi32(val3, val4);
- val1 = _mm_add_pi32(val1, update_round);
- val3 = _mm_add_pi32(val3, update_round);
+ tmp1 = _mm_mullo_pi16 (val2, tap2);
+ tmp2 = _mm_mulhi_pi16 (val2, tap2);
+ val4 = _mm_unpackhi_pi16 (tmp1, tmp2);
+ val2 = _mm_unpacklo_pi16 (tmp1, tmp2);
+
+ val1 = _mm_add_pi32 (val1, val2);
+ val3 = _mm_add_pi32 (val3, val4);
+ val1 = _mm_add_pi32 (val1, update_round);
+ val3 = _mm_add_pi32 (val3, update_round);
val1 = _mm_srai_pi32(val1, 4);
val3 = _mm_srai_pi32(val3, 4);
- val1 = _mm_packs_pi32(val1, val3);
-
- *(__m64*)out = _mm_add_pi16(*(__m64*)out, val1);
- in1 += 4;
- in2 += 4;
- in3 += 4;
- in4 += 4;
- out += 4;
+ val1 = _mm_packs_pi32 (val1, val3);
+
+ *(__m64*)out = _mm_add_pi16 (*(__m64*)out,val1);
+ in1 +=4;
+ in2 +=4;
+ in3 +=4;
+ in4 +=4;
+ out +=4;
}
- // middle bit
- for(j = 1 ; j < yl / 2 - 2 ; ++j)
- {
+ // middle bit
+ for ( j=1 ; j < yl/2 - 2 ; ++j)
+ {
in1 = coeff_data[yp+j];
in2 = coeff_data[yp+j+1];
in3 = coeff_data[yp+j-1];
in4 = coeff_data[yp+j+2];
out = coeff_data[ymid+j];
- for(i = xp ; i < xstop ; i += 4)
+ for ( i = xp ; i < xstop ; i+=4)
{
__m64 val1, val2, val3, val4, tmp1, tmp2;
val1 = _mm_add_pi16(*(__m64*)in1, *(__m64*)in2);
- tmp1 = _mm_mullo_pi16(val1, tap1);
- tmp2 = _mm_mulhi_pi16(val1, tap1);
- val3 = _mm_unpackhi_pi16(tmp1, tmp2);
- val1 = _mm_unpacklo_pi16(tmp1, tmp2);
+ tmp1 = _mm_mullo_pi16 (val1, tap1);
+ tmp2 = _mm_mulhi_pi16 (val1, tap1);
+ val3 = _mm_unpackhi_pi16 (tmp1, tmp2);
+ val1 = _mm_unpacklo_pi16 (tmp1, tmp2);
val2 = _mm_add_pi16(*(__m64*)in3, *(__m64*)in4);
- tmp1 = _mm_mullo_pi16(val2, tap2);
- tmp2 = _mm_mulhi_pi16(val2, tap2);
- val4 = _mm_unpackhi_pi16(tmp1, tmp2);
- val2 = _mm_unpacklo_pi16(tmp1, tmp2);
-
- val1 = _mm_add_pi32(val1, val2);
- val3 = _mm_add_pi32(val3, val4);
- val1 = _mm_add_pi32(val1, update_round);
- val3 = _mm_add_pi32(val3, update_round);
+ tmp1 = _mm_mullo_pi16 (val2, tap2);
+ tmp2 = _mm_mulhi_pi16 (val2, tap2);
+ val4 = _mm_unpackhi_pi16 (tmp1, tmp2);
+ val2 = _mm_unpacklo_pi16 (tmp1, tmp2);
+
+ val1 = _mm_add_pi32 (val1, val2);
+ val3 = _mm_add_pi32 (val3, val4);
+ val1 = _mm_add_pi32 (val1, update_round);
+ val3 = _mm_add_pi32 (val3, update_round);
val1 = _mm_srai_pi32(val1, 4);
val3 = _mm_srai_pi32(val3, 4);
- val1 = _mm_packs_pi32(val1, val3);
-
- *(__m64*)out = _mm_add_pi16(*(__m64*)out, val1);
- in1 += 4;
- in2 += 4;
- in3 += 4;
- in4 += 4;
- out += 4;
- }// i
- }// k
-
- // bottom edge
+ val1 = _mm_packs_pi32 (val1, val3);
+
+ *(__m64*)out = _mm_add_pi16 (*(__m64*)out,val1);
+ in1 +=4;
+ in2 +=4;
+ in3 +=4;
+ in4 +=4;
+ out +=4;
+ }// i
+ }// k
+
+ // bottom edge
in1 = coeff_data[ymid-2];
in2 = coeff_data[ymid-1];
in3 = coeff_data[ymid-3];
in4 = coeff_data[ymid-1];
out = coeff_data[yend-2];
- for(i = xp ; i < xstop ; i += 4)
+ for ( i = xp ; i < xstop ; i+=4)
{
__m64 val1, val2, val3, val4, tmp1, tmp2;
val1 = _mm_add_pi16(*(__m64*)in1, *(__m64*)in2);
- tmp1 = _mm_mullo_pi16(val1, tap1);
- tmp2 = _mm_mulhi_pi16(val1, tap1);
- val3 = _mm_unpackhi_pi16(tmp1, tmp2);
- val1 = _mm_unpacklo_pi16(tmp1, tmp2);
+ tmp1 = _mm_mullo_pi16 (val1, tap1);
+ tmp2 = _mm_mulhi_pi16 (val1, tap1);
+ val3 = _mm_unpackhi_pi16 (tmp1, tmp2);
+ val1 = _mm_unpacklo_pi16 (tmp1, tmp2);
val2 = _mm_add_pi16(*(__m64*)in3, *(__m64*)in4);
- tmp1 = _mm_mullo_pi16(val2, tap2);
- tmp2 = _mm_mulhi_pi16(val2, tap2);
- val4 = _mm_unpackhi_pi16(tmp1, tmp2);
- val2 = _mm_unpacklo_pi16(tmp1, tmp2);
-
- val1 = _mm_add_pi32(val1, val2);
- val3 = _mm_add_pi32(val3, val4);
- val1 = _mm_add_pi32(val1, update_round);
- val3 = _mm_add_pi32(val3, update_round);
+ tmp1 = _mm_mullo_pi16 (val2, tap2);
+ tmp2 = _mm_mulhi_pi16 (val2, tap2);
+ val4 = _mm_unpackhi_pi16 (tmp1, tmp2);
+ val2 = _mm_unpacklo_pi16 (tmp1, tmp2);
+
+ val1 = _mm_add_pi32 (val1, val2);
+ val3 = _mm_add_pi32 (val3, val4);
+ val1 = _mm_add_pi32 (val1, update_round);
+ val3 = _mm_add_pi32 (val3, update_round);
val1 = _mm_srai_pi32(val1, 4);
val3 = _mm_srai_pi32(val3, 4);
- val1 = _mm_packs_pi32(val1, val3);
-
- *(__m64*)out = _mm_add_pi16(*(__m64*)out, val1);
- in1 += 4;
- in2 += 4;
- in3 += 4;
- in4 += 4;
- out += 4;
+ val1 = _mm_packs_pi32 (val1, val3);
+
+ *(__m64*)out = _mm_add_pi16 (*(__m64*)out,val1);
+ in1 +=4;
+ in2 +=4;
+ in3 +=4;
+ in4 +=4;
+ out +=4;
}
-
+
in1 = coeff_data[ymid-1];
in2 = coeff_data[ymid-1];
in3 = coeff_data[ymid-2];
in4 = coeff_data[ymid-1];
out = coeff_data[yend-1];
- for(i = xp ; i < xstop ; i += 4)
+ for ( i = xp ; i < xstop ; i+=4)
{
__m64 val1, val2, val3, val4, tmp1, tmp2;
val1 = _mm_add_pi16(*(__m64*)in1, *(__m64*)in2);
- tmp1 = _mm_mullo_pi16(val1, tap1);
- tmp2 = _mm_mulhi_pi16(val1, tap1);
- val3 = _mm_unpackhi_pi16(tmp1, tmp2);
- val1 = _mm_unpacklo_pi16(tmp1, tmp2);
+ tmp1 = _mm_mullo_pi16 (val1, tap1);
+ tmp2 = _mm_mulhi_pi16 (val1, tap1);
+ val3 = _mm_unpackhi_pi16 (tmp1, tmp2);
+ val1 = _mm_unpacklo_pi16 (tmp1, tmp2);
val2 = _mm_add_pi16(*(__m64*)in3, *(__m64*)in4);
- tmp1 = _mm_mullo_pi16(val2, tap2);
- tmp2 = _mm_mulhi_pi16(val2, tap2);
- val4 = _mm_unpackhi_pi16(tmp1, tmp2);
- val2 = _mm_unpacklo_pi16(tmp1, tmp2);
-
- val1 = _mm_add_pi32(val1, val2);
- val3 = _mm_add_pi32(val3, val4);
- val1 = _mm_add_pi32(val1, update_round);
- val3 = _mm_add_pi32(val3, update_round);
+ tmp1 = _mm_mullo_pi16 (val2, tap2);
+ tmp2 = _mm_mulhi_pi16 (val2, tap2);
+ val4 = _mm_unpackhi_pi16 (tmp1, tmp2);
+ val2 = _mm_unpacklo_pi16 (tmp1, tmp2);
+
+ val1 = _mm_add_pi32 (val1, val2);
+ val3 = _mm_add_pi32 (val3, val4);
+ val1 = _mm_add_pi32 (val1, update_round);
+ val3 = _mm_add_pi32 (val3, update_round);
val1 = _mm_srai_pi32(val1, 4);
val3 = _mm_srai_pi32(val3, 4);
- val1 = _mm_packs_pi32(val1, val3);
-
- *(__m64*)out = _mm_add_pi16(*(__m64*)out, val1);
- in1 += 4;
- in2 += 4;
- in3 += 4;
- in4 += 4;
- out += 4;
+ val1 = _mm_packs_pi32 (val1, val3);
+
+ *(__m64*)out = _mm_add_pi16 (*(__m64*)out,val1);
+ in1 +=4;
+ in2 +=4;
+ in3 +=4;
+ in4 +=4;
+ out +=4;
}
-
- if(xstop != xend)
+
+ if (xstop != xend)
{
- for(i = xstop ; i < xend ; i++)
+ for ( i = xstop ; i < xend ; i++)
{
- update.Filter(coeff_data[ymid][i] , coeff_data[yp][i], coeff_data[yp+1][i], coeff_data[yp][i], coeff_data[yp+2][i]);
+ update.Filter( coeff_data[ymid][i] , coeff_data[yp][i], coeff_data[yp+1][i], coeff_data[yp][i],coeff_data[yp+2][i]);
}// i
// middle bit
- for(j = 1 ; j < yl / 2 - 2 ; ++j)
+ for ( j=1 ; j < yl/2 - 2 ; ++j)
{
- for(i = xstop ; i < xend ; i++)
+ for ( i = xstop ; i < xend ; i++)
{
- update.Filter(coeff_data[ymid+j][i] , coeff_data[yp+j][i], coeff_data[yp+j+1][i], coeff_data[yp+j-1][i], coeff_data[yp+j+2][i]);
+ update.Filter( coeff_data[ymid+j][i] , coeff_data[yp+j][i], coeff_data[yp+j+1][i], coeff_data[yp+j-1][i],coeff_data[yp+j+2][i]);
}// i
}// k
-
- for(i = xstop ; i < xend ; i++)
+
+ for ( i = xstop ; i < xend ; i++)
{
- update.Filter(coeff_data[yend - 2][i] , coeff_data[ymid-2][i], coeff_data[ymid-1][i], coeff_data[ymid-3][i], coeff_data[ymid-1][i]);
- update.Filter(coeff_data[yend - 1][i] , coeff_data[ymid-1][i], coeff_data[ymid-1][i], coeff_data[ymid-2][i], coeff_data[ymid-1][i]);
+ update.Filter( coeff_data[yend - 2][i] , coeff_data[ymid-2][i], coeff_data[ymid-1][i], coeff_data[ymid-3][i],coeff_data[ymid-1][i]);
+ update.Filter( coeff_data[yend - 1][i] , coeff_data[ymid-1][i], coeff_data[ymid-1][i], coeff_data[ymid-2][i],coeff_data[ymid-1][i]);
}// i
}
// Horizontal sythesis
+
+ const int xmid = xl/2;
+ xstop = xmid %4 ? ((xmid>>2)<<2) + 1 : xmid -3;
- const int xmid = xl / 2;
- xstop = xmid % 4 ? ((xmid >> 2) << 2) + 1 : xmid - 3;
-
- for(j = yp; j < yend; ++j)
+ for (j = yp; j < yend; ++j)
{
- CoeffType *line_data = &coeff_data[j][xp];
+ CoeffType *line_data = &coeff_data[j][xp];
// First lifting stage acts on even samples i.e. the low pass ones
- predict.Filter(line_data[0] , line_data[xmid] , line_data[xmid]);
- for(i = 1 ; i < xmid ; ++i)
+ predict.Filter( line_data[0] , line_data[xmid] , line_data[xmid] );
+ for (i=1 ; i < xmid ; ++i)
{
- predict.Filter(line_data[i] , line_data[xmid+i-1] , line_data[xmid+i]);
+ predict.Filter( line_data[i] , line_data[xmid+i-1] , line_data[xmid+i] );
}
// Second lifting stage
- update.Filter(line_data[xmid] , line_data[0] , line_data[1] , line_data[0] , line_data[2]);
+ update.Filter( line_data[xmid] , line_data[0] , line_data[1] , line_data[0] , line_data[2] );
- for(i = 1 ; i < xmid - 2; ++i)
+ for (i=1 ; i < xmid - 2; ++i)
{
- update.Filter(line_data[xmid+i] , line_data[i] , line_data[i+1] , line_data[i-1] , line_data[i+2]);
- }// i
- update.Filter(line_data[xl-2] , line_data[xmid-2] , line_data[xmid-1] , line_data[xmid-3] , line_data[xmid-1]);
- update.Filter(line_data[xl-1] , line_data[xmid-1] , line_data[xmid-1] , line_data[xmid-2] , line_data[xmid-1]);
-
+ update.Filter( line_data[xmid+i] , line_data[i] , line_data[i+1] , line_data[i-1] , line_data[i+2] );
+ }// i
+ update.Filter( line_data[xl-2] , line_data[xmid-2] , line_data[xmid-1] , line_data[xmid-3] , line_data[xmid-1] );
+ update.Filter( line_data[xl-1] , line_data[xmid-1] , line_data[xmid-1] , line_data[xmid-2] , line_data[xmid-1] );
+
// Shift right by one bit to counter the shift in the analysis stage
ShiftRowRight(line_data, xl, 1);
}// j
_mm_empty();
- Interleave_mmx(xp , yp , xl , yl , coeff_data);
+ Interleave_mmx( xp , yp , xl ,yl , coeff_data );
}
void VHFilterDD13_7::Synth(const int xp ,
- const int yp ,
- const int xl ,
- const int yl ,
- CoeffArray& coeff_data)
+ const int yp ,
+ const int xl ,
+ const int yl ,
+ CoeffArray& coeff_data)
{
- int i, j, k;
+ int i,j,k;
- const int xend(xp + xl);
- const int yend(yp + yl);
+ const int xend( xp+xl );
+ const int yend( yp+yl );
- PredictStepFourTap < 5 , 9 , -1 > predict;
- __m64 pred_round = _mm_set_pi32(1 << (5 - 1), 1 << (5 - 1));
- UpdateStepFourTap < 4 , 9 , -1 > update;
- __m64 update_round = _mm_set_pi32(1 << (4 - 1), 1 << (4 - 1));
+ PredictStepFourTap< 5 , 9 , -1 > predict;
+ __m64 pred_round = _mm_set_pi32 (1<<(5-1), 1<<(5-1));
+ UpdateStepFourTap< 4 , 9 , -1> update;
+ __m64 update_round = _mm_set_pi32 (1<<(4-1), 1<<(4-1));
// Next, do the vertical synthesis
- int ymid = yp + yl / 2;
+ int ymid = yp + yl/2;
- int xstop = xp + ((xl >> 2) << 2);
+ int xstop = xp + ((xl>>2)<<2);
// First lifting stage - odd samples
// bottom edge
CoeffType *out = coeff_data[ymid-1];
@@ -534,78 +534,78 @@ void VHFilterDD13_7::Synth(const int xp ,
CoeffType *in3 = coeff_data[yend-3];
CoeffType *in4 = coeff_data[yend-1];
- __m64 tap1 = _mm_set_pi16(9, 9, 9, 9);
- __m64 tap2 = _mm_set_pi16(-1, -1, -1, -1);
- for(i = xp ; i < xstop; i += 4)
+ __m64 tap1 = _mm_set_pi16 (9, 9, 9, 9);
+ __m64 tap2 = _mm_set_pi16 (-1, -1, -1, -1);
+ for ( i = xp ; i<xstop; i+=4)
{
__m64 val1, val2, val3, val4, tmp1, tmp2;
val1 = _mm_add_pi16(*(__m64*)in1, *(__m64*)in2);
- tmp1 = _mm_mullo_pi16(val1, tap1);
- tmp2 = _mm_mulhi_pi16(val1, tap1);
- val3 = _mm_unpackhi_pi16(tmp1, tmp2);
- val1 = _mm_unpacklo_pi16(tmp1, tmp2);
+ tmp1 = _mm_mullo_pi16 (val1, tap1);
+ tmp2 = _mm_mulhi_pi16 (val1, tap1);
+ val3 = _mm_unpackhi_pi16 (tmp1, tmp2);
+ val1 = _mm_unpacklo_pi16 (tmp1, tmp2);
val2 = _mm_add_pi16(*(__m64*)in3, *(__m64*)in4);
- tmp1 = _mm_mullo_pi16(val2, tap2);
- tmp2 = _mm_mulhi_pi16(val2, tap2);
- val4 = _mm_unpackhi_pi16(tmp1, tmp2);
- val2 = _mm_unpacklo_pi16(tmp1, tmp2);
-
- val1 = _mm_add_pi32(val1, val2);
- val3 = _mm_add_pi32(val3, val4);
- val1 = _mm_add_pi32(val1, pred_round);
- val3 = _mm_add_pi32(val3, pred_round);
+ tmp1 = _mm_mullo_pi16 (val2, tap2);
+ tmp2 = _mm_mulhi_pi16 (val2, tap2);
+ val4 = _mm_unpackhi_pi16 (tmp1, tmp2);
+ val2 = _mm_unpacklo_pi16 (tmp1, tmp2);
+
+ val1 = _mm_add_pi32 (val1, val2);
+ val3 = _mm_add_pi32 (val3, val4);
+ val1 = _mm_add_pi32 (val1, pred_round);
+ val3 = _mm_add_pi32 (val3, pred_round);
val1 = _mm_srai_pi32(val1, 5);
val3 = _mm_srai_pi32(val3, 5);
- val1 = _mm_packs_pi32(val1, val3);
-
- *(__m64*)out = _mm_sub_pi16(*(__m64*)out, val1);
- in1 += 4;
- in2 += 4;
- in3 += 4;
- in4 += 4;
- out += 4;
+ val1 = _mm_packs_pi32 (val1, val3);
+
+ *(__m64*)out = _mm_sub_pi16 (*(__m64*)out,val1);
+ in1 +=4;
+ in2 +=4;
+ in3 +=4;
+ in4 +=4;
+ out +=4;
}// i
// middle bit
- for(j = 2 ; j < yl / 2 - 1 ; ++j)
+ for ( j = 2 ; j < yl/2 -1 ; ++j)
{
out = coeff_data[yp+j];
in1 = coeff_data[ymid+j-1];
in2 = coeff_data[ymid+j];
in3 = coeff_data[ymid+j-2];
in4 = coeff_data[ymid+j+1];
- for(i = xp ; i < xstop ; i += 4)
+ for ( i = xp ; i<xstop ; i+=4)
{
__m64 val1, val2, val3, val4, tmp1, tmp2;
val1 = _mm_add_pi16(*(__m64*)in1, *(__m64*)in2);
- tmp1 = _mm_mullo_pi16(val1, tap1);
- tmp2 = _mm_mulhi_pi16(val1, tap1);
- val3 = _mm_unpackhi_pi16(tmp1, tmp2);
- val1 = _mm_unpacklo_pi16(tmp1, tmp2);
+ tmp1 = _mm_mullo_pi16 (val1, tap1);
+ tmp2 = _mm_mulhi_pi16 (val1, tap1);
+ val3 = _mm_unpackhi_pi16 (tmp1, tmp2);
+ val1 = _mm_unpacklo_pi16 (tmp1, tmp2);
val2 = _mm_add_pi16(*(__m64*)in3, *(__m64*)in4);
- tmp1 = _mm_mullo_pi16(val2, tap2);
- tmp2 = _mm_mulhi_pi16(val2, tap2);
- val4 = _mm_unpackhi_pi16(tmp1, tmp2);
- val2 = _mm_unpacklo_pi16(tmp1, tmp2);
-
- val1 = _mm_add_pi32(val1, val2);
- val3 = _mm_add_pi32(val3, val4);
- val1 = _mm_add_pi32(val1, pred_round);
- val3 = _mm_add_pi32(val3, pred_round);
+ tmp1 = _mm_mullo_pi16 (val2, tap2);
+ tmp2 = _mm_mulhi_pi16 (val2, tap2);
+ val4 = _mm_unpackhi_pi16 (tmp1, tmp2);
+ val2 = _mm_unpacklo_pi16 (tmp1, tmp2);
+
+ val1 = _mm_add_pi32 (val1, val2);
+ val3 = _mm_add_pi32 (val3, val4);
+ val1 = _mm_add_pi32 (val1, pred_round);
+ val3 = _mm_add_pi32 (val3, pred_round);
val1 = _mm_srai_pi32(val1, 5);
val3 = _mm_srai_pi32(val3, 5);
- val1 = _mm_packs_pi32(val1, val3);
-
- *(__m64*)out = _mm_sub_pi16(*(__m64*)out, val1);
- in1 += 4;
- in2 += 4;
- in3 += 4;
- in4 += 4;
- out += 4;
+ val1 = _mm_packs_pi32 (val1, val3);
+
+ *(__m64*)out = _mm_sub_pi16 (*(__m64*)out,val1);
+ in1 +=4;
+ in2 +=4;
+ in3 +=4;
+ in4 +=4;
+ out +=4;
}// i
}// j
@@ -615,36 +615,36 @@ void VHFilterDD13_7::Synth(const int xp ,
in2 = coeff_data[ymid+1];
in3 = coeff_data[ymid+2];
in4 = coeff_data[ymid];
- for(i = xp ; i < xstop ; i += 4)
+ for ( i = xp ; i<xstop ; i+=4)
{
__m64 val1, val2, val3, val4, tmp1, tmp2;
val1 = _mm_add_pi16(*(__m64*)in1, *(__m64*)in2);
- tmp1 = _mm_mullo_pi16(val1, tap1);
- tmp2 = _mm_mulhi_pi16(val1, tap1);
- val3 = _mm_unpackhi_pi16(tmp1, tmp2);
- val1 = _mm_unpacklo_pi16(tmp1, tmp2);
+ tmp1 = _mm_mullo_pi16 (val1, tap1);
+ tmp2 = _mm_mulhi_pi16 (val1, tap1);
+ val3 = _mm_unpackhi_pi16 (tmp1, tmp2);
+ val1 = _mm_unpacklo_pi16 (tmp1, tmp2);
val2 = _mm_add_pi16(*(__m64*)in3, *(__m64*)in4);
- tmp1 = _mm_mullo_pi16(val2, tap2);
- tmp2 = _mm_mulhi_pi16(val2, tap2);
- val4 = _mm_unpackhi_pi16(tmp1, tmp2);
- val2 = _mm_unpacklo_pi16(tmp1, tmp2);
-
- val1 = _mm_add_pi32(val1, val2);
- val3 = _mm_add_pi32(val3, val4);
- val1 = _mm_add_pi32(val1, pred_round);
- val3 = _mm_add_pi32(val3, pred_round);
+ tmp1 = _mm_mullo_pi16 (val2, tap2);
+ tmp2 = _mm_mulhi_pi16 (val2, tap2);
+ val4 = _mm_unpackhi_pi16 (tmp1, tmp2);
+ val2 = _mm_unpacklo_pi16 (tmp1, tmp2);
+
+ val1 = _mm_add_pi32 (val1, val2);
+ val3 = _mm_add_pi32 (val3, val4);
+ val1 = _mm_add_pi32 (val1, pred_round);
+ val3 = _mm_add_pi32 (val3, pred_round);
val1 = _mm_srai_pi32(val1, 5);
val3 = _mm_srai_pi32(val3, 5);
- val1 = _mm_packs_pi32(val1, val3);
-
- *(__m64*)out = _mm_sub_pi16(*(__m64*)out, val1);
- in1 += 4;
- in2 += 4;
- in3 += 4;
- in4 += 4;
- out += 4;
+ val1 = _mm_packs_pi32 (val1, val3);
+
+ *(__m64*)out = _mm_sub_pi16 (*(__m64*)out,val1);
+ in1 +=4;
+ in2 +=4;
+ in3 +=4;
+ in4 +=4;
+ out +=4;
}
out = coeff_data[yp];
@@ -652,61 +652,61 @@ void VHFilterDD13_7::Synth(const int xp ,
in2 = coeff_data[ymid];
in3 = coeff_data[ymid+1];
in4 = coeff_data[ymid];
- for(i = xp ; i < xstop ; i += 4)
+ for ( i = xp ; i<xstop ; i+=4)
{
__m64 val1, val2, val3, val4, tmp1, tmp2;
val1 = _mm_add_pi16(*(__m64*)in1, *(__m64*)in2);
- tmp1 = _mm_mullo_pi16(val1, tap1);
- tmp2 = _mm_mulhi_pi16(val1, tap1);
- val3 = _mm_unpackhi_pi16(tmp1, tmp2);
- val1 = _mm_unpacklo_pi16(tmp1, tmp2);
+ tmp1 = _mm_mullo_pi16 (val1, tap1);
+ tmp2 = _mm_mulhi_pi16 (val1, tap1);
+ val3 = _mm_unpackhi_pi16 (tmp1, tmp2);
+ val1 = _mm_unpacklo_pi16 (tmp1, tmp2);
val2 = _mm_add_pi16(*(__m64*)in3, *(__m64*)in4);
- tmp1 = _mm_mullo_pi16(val2, tap2);
- tmp2 = _mm_mulhi_pi16(val2, tap2);
- val4 = _mm_unpackhi_pi16(tmp1, tmp2);
- val2 = _mm_unpacklo_pi16(tmp1, tmp2);
-
- val1 = _mm_add_pi32(val1, val2);
- val3 = _mm_add_pi32(val3, val4);
- val1 = _mm_add_pi32(val1, pred_round);
- val3 = _mm_add_pi32(val3, pred_round);
+ tmp1 = _mm_mullo_pi16 (val2, tap2);
+ tmp2 = _mm_mulhi_pi16 (val2, tap2);
+ val4 = _mm_unpackhi_pi16 (tmp1, tmp2);
+ val2 = _mm_unpacklo_pi16 (tmp1, tmp2);
+
+ val1 = _mm_add_pi32 (val1, val2);
+ val3 = _mm_add_pi32 (val3, val4);
+ val1 = _mm_add_pi32 (val1, pred_round);
+ val3 = _mm_add_pi32 (val3, pred_round);
val1 = _mm_srai_pi32(val1, 5);
val3 = _mm_srai_pi32(val3, 5);
- val1 = _mm_packs_pi32(val1, val3);
-
- *(__m64*)out = _mm_sub_pi16(*(__m64*)out, val1);
- in1 += 4;
- in2 += 4;
- in3 += 4;
- in4 += 4;
- out += 4;
+ val1 = _mm_packs_pi32 (val1, val3);
+
+ *(__m64*)out = _mm_sub_pi16 (*(__m64*)out,val1);
+ in1 +=4;
+ in2 +=4;
+ in3 +=4;
+ in4 +=4;
+ out +=4;
}
- // Mopup
- if(xstop != xend)
+ // Mopup
+ if ( xstop != xend)
{
// Mopup bottom edge
- for(i = xstop ; i < xend ; ++ i)
+ for ( i = xstop ; i<xend ; ++ i)
{
- predict.Filter(coeff_data[ymid-1][i] , coeff_data[yend-2][i] , coeff_data[yend-1][i] , coeff_data[yend-3][i] , coeff_data[yend-1][i]);
+ predict.Filter( coeff_data[ymid-1][i] , coeff_data[yend-2][i] , coeff_data[yend-1][i] , coeff_data[yend-3][i] , coeff_data[yend-1][i] );
}// i
// Mopup middle bit
- for(k = 2 ; k < yl / 2 - 1 ; ++k)
+ for ( k = 2 ; k < yl/2 - 1 ; ++k)
{
- for(i = xstop ; i < xend ; ++ i)
+ for ( i = xstop ; i<xend ; ++ i)
{
- predict.Filter(coeff_data[yp+k][i] , coeff_data[ymid+k-1][i] , coeff_data[ymid+k][i] , coeff_data[ymid+k-2][i] , coeff_data[ymid+k+1][i]);
+ predict.Filter( coeff_data[yp+k][i] , coeff_data[ymid+k-1][i] , coeff_data[ymid+k][i] , coeff_data[ymid+k-2][i] , coeff_data[ymid+k+1][i] );
}// i
}// k
//Mopup top edge
- for(i = xstop ; i < xend ; ++ i)
+ for ( i = xstop ; i<xend ; ++ i)
{
- predict.Filter(coeff_data[yp+1][i] , coeff_data[ymid][i] , coeff_data[ymid+1][i] , coeff_data[ymid+2][i] , coeff_data[ymid][i]);
- predict.Filter(coeff_data[yp][i] , coeff_data[ymid][i] , coeff_data[ymid][i] , coeff_data[ymid+1][i] , coeff_data[ymid][i]);
+ predict.Filter( coeff_data[yp+1][i] , coeff_data[ymid][i] , coeff_data[ymid+1][i] , coeff_data[ymid+2][i] , coeff_data[ymid][i] );
+ predict.Filter( coeff_data[yp][i] , coeff_data[ymid][i] , coeff_data[ymid][i] , coeff_data[ymid+1][i] , coeff_data[ymid][i] );
}// i
@@ -719,77 +719,77 @@ void VHFilterDD13_7::Synth(const int xp ,
in2 = coeff_data[yp+1];
in3 = coeff_data[yp];
in4 = coeff_data[yp+2];
- for(i = xp ; i < xstop ; i += 4)
+ for ( i = xp ; i<xstop ; i+=4)
{
__m64 val1, val2, val3, val4, tmp1, tmp2;
val1 = _mm_add_pi16(*(__m64*)in1, *(__m64*)in2);
- tmp1 = _mm_mullo_pi16(val1, tap1);
- tmp2 = _mm_mulhi_pi16(val1, tap1);
- val3 = _mm_unpackhi_pi16(tmp1, tmp2);
- val1 = _mm_unpacklo_pi16(tmp1, tmp2);
+ tmp1 = _mm_mullo_pi16 (val1, tap1);
+ tmp2 = _mm_mulhi_pi16 (val1, tap1);
+ val3 = _mm_unpackhi_pi16 (tmp1, tmp2);
+ val1 = _mm_unpacklo_pi16 (tmp1, tmp2);
val2 = _mm_add_pi16(*(__m64*)in3, *(__m64*)in4);
- tmp1 = _mm_mullo_pi16(val2, tap2);
- tmp2 = _mm_mulhi_pi16(val2, tap2);
- val4 = _mm_unpackhi_pi16(tmp1, tmp2);
- val2 = _mm_unpacklo_pi16(tmp1, tmp2);
-
- val1 = _mm_add_pi32(val1, val2);
- val3 = _mm_add_pi32(val3, val4);
- val1 = _mm_add_pi32(val1, update_round);
- val3 = _mm_add_pi32(val3, update_round);
+ tmp1 = _mm_mullo_pi16 (val2, tap2);
+ tmp2 = _mm_mulhi_pi16 (val2, tap2);
+ val4 = _mm_unpackhi_pi16 (tmp1, tmp2);
+ val2 = _mm_unpacklo_pi16 (tmp1, tmp2);
+
+ val1 = _mm_add_pi32 (val1, val2);
+ val3 = _mm_add_pi32 (val3, val4);
+ val1 = _mm_add_pi32 (val1, update_round);
+ val3 = _mm_add_pi32 (val3, update_round);
val1 = _mm_srai_pi32(val1, 4);
val3 = _mm_srai_pi32(val3, 4);
- val1 = _mm_packs_pi32(val1, val3);
-
- *(__m64*)out = _mm_add_pi16(*(__m64*)out, val1);
- in1 += 4;
- in2 += 4;
- in3 += 4;
- in4 += 4;
- out += 4;
+ val1 = _mm_packs_pi32 (val1, val3);
+
+ *(__m64*)out = _mm_add_pi16 (*(__m64*)out,val1);
+ in1 +=4;
+ in2 +=4;
+ in3 +=4;
+ in4 +=4;
+ out +=4;
}// i
// middle bit
- for(k = 1 ; k < yl / 2 - 2 ; ++k)
+ for ( k = 1 ; k < yl/2 - 2 ; ++k)
{
out = coeff_data[ymid+k];
in1 = coeff_data[k];
in2 = coeff_data[k+1];
in3 = coeff_data[k-1];
in4 = coeff_data[k+2];
- for(i = xp ; i < xstop ; i += 4)
+ for ( i = xp ; i<xstop ; i+=4)
{
__m64 val1, val2, val3, val4, tmp1, tmp2;
val1 = _mm_add_pi16(*(__m64*)in1, *(__m64*)in2);
- tmp1 = _mm_mullo_pi16(val1, tap1);
- tmp2 = _mm_mulhi_pi16(val1, tap1);
- val3 = _mm_unpackhi_pi16(tmp1, tmp2);
- val1 = _mm_unpacklo_pi16(tmp1, tmp2);
+ tmp1 = _mm_mullo_pi16 (val1, tap1);
+ tmp2 = _mm_mulhi_pi16 (val1, tap1);
+ val3 = _mm_unpackhi_pi16 (tmp1, tmp2);
+ val1 = _mm_unpacklo_pi16 (tmp1, tmp2);
val2 = _mm_add_pi16(*(__m64*)in3, *(__m64*)in4);
- tmp1 = _mm_mullo_pi16(val2, tap2);
- tmp2 = _mm_mulhi_pi16(val2, tap2);
- val4 = _mm_unpackhi_pi16(tmp1, tmp2);
- val2 = _mm_unpacklo_pi16(tmp1, tmp2);
-
- val1 = _mm_add_pi32(val1, val2);
- val3 = _mm_add_pi32(val3, val4);
- val1 = _mm_add_pi32(val1, update_round);
- val3 = _mm_add_pi32(val3, update_round);
+ tmp1 = _mm_mullo_pi16 (val2, tap2);
+ tmp2 = _mm_mulhi_pi16 (val2, tap2);
+ val4 = _mm_unpackhi_pi16 (tmp1, tmp2);
+ val2 = _mm_unpacklo_pi16 (tmp1, tmp2);
+
+ val1 = _mm_add_pi32 (val1, val2);
+ val3 = _mm_add_pi32 (val3, val4);
+ val1 = _mm_add_pi32 (val1, update_round);
+ val3 = _mm_add_pi32 (val3, update_round);
val1 = _mm_srai_pi32(val1, 4);
val3 = _mm_srai_pi32(val3, 4);
- val1 = _mm_packs_pi32(val1, val3);
-
- *(__m64*)out = _mm_add_pi16(*(__m64*)out, val1);
- in1 += 4;
- in2 += 4;
- in3 += 4;
- in4 += 4;
- out += 4;
+ val1 = _mm_packs_pi32 (val1, val3);
+
+ *(__m64*)out = _mm_add_pi16 (*(__m64*)out,val1);
+ in1 +=4;
+ in2 +=4;
+ in3 +=4;
+ in4 +=4;
+ out +=4;
}// i
}// k
@@ -799,36 +799,36 @@ void VHFilterDD13_7::Synth(const int xp ,
in2 = coeff_data[ymid-1];
in3 = coeff_data[ymid-3];
in4 = coeff_data[ymid-1];
- for(i = xp ; i < xstop ; i += 4)
+ for ( i = xp ; i<xstop ; i+=4)
{
__m64 val1, val2, val3, val4, tmp1, tmp2;
val1 = _mm_add_pi16(*(__m64*)in1, *(__m64*)in2);
- tmp1 = _mm_mullo_pi16(val1, tap1);
- tmp2 = _mm_mulhi_pi16(val1, tap1);
- val3 = _mm_unpackhi_pi16(tmp1, tmp2);
- val1 = _mm_unpacklo_pi16(tmp1, tmp2);
+ tmp1 = _mm_mullo_pi16 (val1, tap1);
+ tmp2 = _mm_mulhi_pi16 (val1, tap1);
+ val3 = _mm_unpackhi_pi16 (tmp1, tmp2);
+ val1 = _mm_unpacklo_pi16 (tmp1, tmp2);
val2 = _mm_add_pi16(*(__m64*)in3, *(__m64*)in4);
- tmp1 = _mm_mullo_pi16(val2, tap2);
- tmp2 = _mm_mulhi_pi16(val2, tap2);
- val4 = _mm_unpackhi_pi16(tmp1, tmp2);
- val2 = _mm_unpacklo_pi16(tmp1, tmp2);
-
- val1 = _mm_add_pi32(val1, val2);
- val3 = _mm_add_pi32(val3, val4);
- val1 = _mm_add_pi32(val1, update_round);
- val3 = _mm_add_pi32(val3, update_round);
+ tmp1 = _mm_mullo_pi16 (val2, tap2);
+ tmp2 = _mm_mulhi_pi16 (val2, tap2);
+ val4 = _mm_unpackhi_pi16 (tmp1, tmp2);
+ val2 = _mm_unpacklo_pi16 (tmp1, tmp2);
+
+ val1 = _mm_add_pi32 (val1, val2);
+ val3 = _mm_add_pi32 (val3, val4);
+ val1 = _mm_add_pi32 (val1, update_round);
+ val3 = _mm_add_pi32 (val3, update_round);
val1 = _mm_srai_pi32(val1, 4);
val3 = _mm_srai_pi32(val3, 4);
- val1 = _mm_packs_pi32(val1, val3);
-
- *(__m64*)out = _mm_add_pi16(*(__m64*)out, val1);
- in1 += 4;
- in2 += 4;
- in3 += 4;
- in4 += 4;
- out += 4;
+ val1 = _mm_packs_pi32 (val1, val3);
+
+ *(__m64*)out = _mm_add_pi16 (*(__m64*)out,val1);
+ in1 +=4;
+ in2 +=4;
+ in3 +=4;
+ in4 +=4;
+ out +=4;
}// i
out = coeff_data[yend-1];
@@ -836,96 +836,96 @@ void VHFilterDD13_7::Synth(const int xp ,
in2 = coeff_data[ymid-1];
in3 = coeff_data[ymid-2];
in4 = coeff_data[ymid-1];
- for(i = xp ; i < xstop ; i += 4)
+ for ( i = xp ; i<xstop ; i+=4)
{
__m64 val1, val2, val3, val4, tmp1, tmp2;
val1 = _mm_add_pi16(*(__m64*)in1, *(__m64*)in2);
- tmp1 = _mm_mullo_pi16(val1, tap1);
- tmp2 = _mm_mulhi_pi16(val1, tap1);
- val3 = _mm_unpackhi_pi16(tmp1, tmp2);
- val1 = _mm_unpacklo_pi16(tmp1, tmp2);
+ tmp1 = _mm_mullo_pi16 (val1, tap1);
+ tmp2 = _mm_mulhi_pi16 (val1, tap1);
+ val3 = _mm_unpackhi_pi16 (tmp1, tmp2);
+ val1 = _mm_unpacklo_pi16 (tmp1, tmp2);
val2 = _mm_add_pi16(*(__m64*)in3, *(__m64*)in4);
- tmp1 = _mm_mullo_pi16(val2, tap2);
- tmp2 = _mm_mulhi_pi16(val2, tap2);
- val4 = _mm_unpackhi_pi16(tmp1, tmp2);
- val2 = _mm_unpacklo_pi16(tmp1, tmp2);
-
- val1 = _mm_add_pi32(val1, val2);
- val3 = _mm_add_pi32(val3, val4);
- val1 = _mm_add_pi32(val1, update_round);
- val3 = _mm_add_pi32(val3, update_round);
+ tmp1 = _mm_mullo_pi16 (val2, tap2);
+ tmp2 = _mm_mulhi_pi16 (val2, tap2);
+ val4 = _mm_unpackhi_pi16 (tmp1, tmp2);
+ val2 = _mm_unpacklo_pi16 (tmp1, tmp2);
+
+ val1 = _mm_add_pi32 (val1, val2);
+ val3 = _mm_add_pi32 (val3, val4);
+ val1 = _mm_add_pi32 (val1, update_round);
+ val3 = _mm_add_pi32 (val3, update_round);
val1 = _mm_srai_pi32(val1, 4);
val3 = _mm_srai_pi32(val3, 4);
- val1 = _mm_packs_pi32(val1, val3);
-
- *(__m64*)out = _mm_add_pi16(*(__m64*)out, val1);
- in1 += 4;
- in2 += 4;
- in3 += 4;
- in4 += 4;
- out += 4;
+ val1 = _mm_packs_pi32 (val1, val3);
+
+ *(__m64*)out = _mm_add_pi16 (*(__m64*)out,val1);
+ in1 +=4;
+ in2 +=4;
+ in3 +=4;
+ in4 +=4;
+ out +=4;
}// i
+
-
- // Mopup
- if(xstop != xend)
+ // Mopup
+ if ( xstop != xend)
{
// bottom edge
- for(i = xstop ; i < xend ; ++ i)
+ for ( i = xstop ; i<xend ; ++ i)
{
- update.Filter(coeff_data[yend-1][i] , coeff_data[ymid-1][i] , coeff_data[ymid-1][i] , coeff_data[ymid-2][i] , coeff_data[ymid-1][i]);
- update.Filter(coeff_data[yend-2][i] , coeff_data[ymid-2][i] , coeff_data[ymid-1][i] , coeff_data[ymid-3][i] , coeff_data[ymid-1][i]);
+ update.Filter( coeff_data[yend-1][i] , coeff_data[ymid-1][i] , coeff_data[ymid-1][i] , coeff_data[ymid-2][i] , coeff_data[ymid-1][i] );
+ update.Filter( coeff_data[yend-2][i] , coeff_data[ymid-2][i] , coeff_data[ymid-1][i] , coeff_data[ymid-3][i] , coeff_data[ymid-1][i] );
}// i
// middle bit
- for(k = 1 ; k < yl / 2 - 2 ; ++k)
+ for ( k = 1 ; k < yl/2 - 2 ; ++k)
{
- for(i = xstop ; i < xend ; ++ i)
+ for ( i = xstop ; i<xend ; ++ i)
{
- update.Filter(coeff_data[ymid+k][i] , coeff_data[k][i] , coeff_data[k+1][i] , coeff_data[k-1][i] , coeff_data[k+2][i]);
+ update.Filter( coeff_data[ymid+k][i] , coeff_data[k][i] , coeff_data[k+1][i] , coeff_data[k-1][i] , coeff_data[k+2][i] );
}// i
}// j
// top edge - j=xp
- for(i = xstop ; i < xend ; ++ i)
+ for ( i = xstop ; i<xend ; ++ i)
{
- update.Filter(coeff_data[ymid][i] , coeff_data[yp][i] , coeff_data[yp+1][i] , coeff_data[yp][i] , coeff_data[yp+2][i]);
+ update.Filter( coeff_data[ymid][i] , coeff_data[yp][i] , coeff_data[yp+1][i] , coeff_data[yp][i] , coeff_data[yp+2][i] );
}// i
}
// Next do the horizontal synthesis
CoeffType* line_data;
- int xmid = xl / 2;
+ int xmid = xl/2;
- for(j = yp; j < yend ; ++j)
+ for (j = yp; j < yend ; ++j)
{
- line_data = &coeff_data[j][xp];
+ line_data = &coeff_data[j][xp];
// First lifting stage
- predict.Filter(line_data[0] , line_data[xmid] , line_data[xmid] , line_data[xmid+1] , line_data[xmid]);
- predict.Filter(line_data[1] , line_data[xmid] , line_data[xmid+1] , line_data[xmid+2] , line_data[xmid]);
+ predict.Filter( line_data[0] , line_data[xmid] , line_data[xmid] , line_data[xmid+1] , line_data[xmid] );
+ predict.Filter( line_data[1] , line_data[xmid] , line_data[xmid+1] , line_data[xmid+2] , line_data[xmid] );
- for(k = 2 ; k < xmid - 1 ; ++k)
+ for (k=2 ; k < xmid-1 ; ++k)
{
- predict.Filter(line_data[k] , line_data[xmid+k-1] , line_data[xmid+k] , line_data[xmid+k-2] , line_data[xmid+k+1]);
+ predict.Filter( line_data[k] , line_data[xmid+k-1] , line_data[xmid+k] , line_data[xmid+k-2] , line_data[xmid+k+1] );
- }// i
- predict.Filter(line_data[xmid-1] , line_data[xl-2] , line_data[xl-1] , line_data[xl-3] , line_data[xl-1]);
+ }// i
+ predict.Filter( line_data[xmid-1] , line_data[xl-2] , line_data[xl-1] , line_data[xl-3] , line_data[xl-1] );
- //second lifting stage
+ //second lifting stage
- update.Filter(line_data[xmid] , line_data[0] , line_data[1] , line_data[0] , line_data[2]);
- for(k = 1 ; k < xmid - 2 ; ++k)
+ update.Filter( line_data[xmid] , line_data[0] , line_data[1] , line_data[0] , line_data[2] );
+ for (k=1 ; k<xmid-2 ; ++k)
{
- update.Filter(line_data[xmid+k] , line_data[k] , line_data[k+1] , line_data[k-1] , line_data[k+2]);
- }// i
- update.Filter(line_data[xl-2] , line_data[xmid-2] , line_data[xmid-1] , line_data[xmid-3] , line_data[xmid-1]);
- update.Filter(line_data[xl-1] , line_data[xmid-1] , line_data[xmid-1] , line_data[xmid-2] , line_data[xmid-1]);
+ update.Filter( line_data[xmid+k] , line_data[k] , line_data[k+1] , line_data[k-1] , line_data[k+2] );
+ }// i
+ update.Filter( line_data[xl-2] , line_data[xmid-2] , line_data[xmid-1] , line_data[xmid-3] , line_data[xmid-1] );
+ update.Filter( line_data[xl-1] , line_data[xmid-1] , line_data[xmid-1] , line_data[xmid-2] , line_data[xmid-1] );
// Shift right by one bit to counter the shift in the analysis stage
ShiftRowRight(line_data, xl, 1);
@@ -933,74 +933,74 @@ void VHFilterDD13_7::Synth(const int xp ,
}// j
_mm_empty();
- // Interleave subbands
- Interleave_mmx(xp , yp , xl , yl , coeff_data);
+ // Interleave subbands
+ Interleave_mmx( xp , yp , xl , yl , coeff_data );
}
#if 0
//Opts - Attempt1
void VHFilterLEGALL5_3::Synth(const int xp ,
- const int yp ,
- const int xl ,
- const int yl ,
- CoeffArray& coeff_data)
+ const int yp ,
+ const int xl ,
+ const int yl ,
+ CoeffArray& coeff_data)
{
- int i, j, k;
+ int i,j,k;
- const int xend(xp + xl);
- const int yend(yp + yl);
+ const int xend( xp+xl );
+ const int yend( yp+yl );
const PredictStepShift< 2 > predict;
const UpdateStepShift< 1 > update;
CoeffType* line_data;
- // Firstly reorder to interleave subbands, so that subsequent calculations
+ // Firstly reorder to interleave subbands, so that subsequent calculations
// can be in-place
- Interleave_mmx(xp , yp , xl , yl , coeff_data);
+ Interleave_mmx( xp , yp , xl , yl , coeff_data );
// Next, do the vertical synthesis
// First lifting stage
- int xstop = (xend >> 2) << 2;
-
+ int xstop = (xend>>2)<<2;
+
// Begin the top edge
CoeffType *row1, *row2, *row3, *row4;
row1 = &coeff_data[yp][xp];
row2 = &coeff_data[yp+1][xp];
- for(i = xp ; i < xstop ; i += 4)
+ for ( i = xp ; i < xstop ; i+=4)
{
- __m64 tmp = _mm_add_pi16(*(__m64 *)row2, *(__m64 *)row2);
+ __m64 tmp = _mm_add_pi16 (*(__m64 *)row2, *(__m64 *)row2);
tmp = _mm_srai_pi16(tmp, 2);
- *(__m64 *)row1 = _mm_sub_pi16(*(__m64*)row1, tmp);
+ *(__m64 *)row1 = _mm_sub_pi16 (*(__m64*)row1, tmp);
row1 += 4;
row2 += 4;
}
// Mopup
- for(i = xstop ; i < xend ; ++i)
+ for ( i = xstop ; i < xend ; ++i)
{
- predict.Filter(coeff_data[yp][i] , coeff_data[yp+1][i] , coeff_data[yp+1][i]);
+ predict.Filter( coeff_data[yp][i] , coeff_data[yp+1][i] , coeff_data[yp+1][i] );
}// i
// Next, do the middle bit
- for(k = yp + 2 ; k < yend - 2 ; k += 2)
+ for ( k = yp+2 ; k < yend-2 ; k+=2)
{
CoeffType *row1 = &coeff_data[k-2][xp];
CoeffType *row2 = &coeff_data[k-1][xp];
CoeffType *row3 = &coeff_data[k][xp];
CoeffType *row4 = &coeff_data[k+1][xp];
- for(i = xp ; i < xstop ; i += 4)
+ for ( i = xp ; i < xstop ; i+=4)
{
- __m64 tmp = _mm_add_pi16(*(__m64 *)row4, *(__m64 *)row2);
+ __m64 tmp = _mm_add_pi16 (*(__m64 *)row4, *(__m64 *)row2);
tmp = _mm_srai_pi16(tmp, 2);
- *(__m64 *)row3 = _mm_sub_pi16(*(__m64*)row3, tmp);
+ *(__m64 *)row3 = _mm_sub_pi16 (*(__m64*)row3, tmp);
- tmp = _mm_add_pi16(*(__m64 *)row1, *(__m64 *)row3);
+ tmp = _mm_add_pi16 (*(__m64 *)row1, *(__m64 *)row3);
tmp = _mm_srai_pi16(tmp, 1);
- *(__m64 *)row2 = _mm_add_pi16(*(__m64*)row2, tmp);
+ *(__m64 *)row2 = _mm_add_pi16 (*(__m64*)row2, tmp);
row1 += 4;
row2 += 4;
row3 += 4;
@@ -1008,32 +1008,32 @@ void VHFilterLEGALL5_3::Synth(const int xp ,
}// i
//Mopup
- for(i = xstop ; i < xend ; ++i)
+ for ( i = xstop ; i < xend ; ++i)
{
- predict.Filter(coeff_data[k][i] , coeff_data[k+1][i] , coeff_data[k-1][i]);
- update.Filter(coeff_data[k-1][i] , coeff_data[k-2][i] , coeff_data[k][i]);
+ predict.Filter( coeff_data[k][i] , coeff_data[k+1][i] , coeff_data[k-1][i] );
+ update.Filter( coeff_data[k-1][i] , coeff_data[k-2][i] , coeff_data[k][i] );
}// i
}// j
-
+
// Finally with the bottom edge
row1 = &coeff_data[yend-4][xp];
row2 = &coeff_data[yend-3][xp];
row3 = &coeff_data[yend-2][xp];
row4 = &coeff_data[yend-1][xp];
- for(i = xp ; i < xstop ; i += 4)
+ for ( i = xp ; i < xstop ; i+=4)
{
- __m64 tmp = _mm_add_pi16(*(__m64 *)row2, *(__m64 *)row4);
+ __m64 tmp = _mm_add_pi16 (*(__m64 *)row2, *(__m64 *)row4);
tmp = _mm_srai_pi16(tmp, 2);
- *(__m64 *)row3 = _mm_sub_pi16(*(__m64*)row3, tmp);
+ *(__m64 *)row3 = _mm_sub_pi16 (*(__m64*)row3, tmp);
- tmp = _mm_add_pi16(*(__m64 *)row3, *(__m64 *)row1);
+ tmp = _mm_add_pi16 (*(__m64 *)row3, *(__m64 *)row1);
tmp = _mm_srai_pi16(tmp, 1);
- *(__m64 *)row2 = _mm_add_pi16(*(__m64*)row2, tmp);
+ *(__m64 *)row2 = _mm_add_pi16 (*(__m64*)row2, tmp);
- tmp = _mm_add_pi16(*(__m64 *)row3, *(__m64 *)row3);
+ tmp = _mm_add_pi16 (*(__m64 *)row3, *(__m64 *)row3);
tmp = _mm_srai_pi16(tmp, 1);
- *(__m64 *)row4 = _mm_add_pi16(*(__m64*)row4, tmp);
+ *(__m64 *)row4 = _mm_add_pi16 (*(__m64*)row4, tmp);
row1 += 4;
row2 += 4;
@@ -1041,31 +1041,31 @@ void VHFilterLEGALL5_3::Synth(const int xp ,
row4 += 4;
}// i
// mopup
- for(i = xstop ; i < xend ; ++i)
+ for ( i = xstop ; i < xend ; ++i)
{
- predict.Filter(coeff_data[yend-2][i] , coeff_data[yend-3][i] , coeff_data[yend-1][i]);
- update.Filter(coeff_data[yend-3][i] , coeff_data[yend-2][i] , coeff_data[yend-4][i]);
- update.Filter(coeff_data[yend-1][i] , coeff_data[yend-2][i] , coeff_data[yend-2][i]);
+ predict.Filter( coeff_data[yend-2][i] , coeff_data[yend-3][i] , coeff_data[yend-1][i] );
+ update.Filter( coeff_data[yend-3][i] , coeff_data[yend-2][i] , coeff_data[yend-4][i] );
+ update.Filter( coeff_data[yend-1][i] , coeff_data[yend-2][i] , coeff_data[yend-2][i] );
}// i
// Next do the horizontal synthesis
- for(j = yp; j < yend ; ++j)
+ for (j = yp; j < yend ; ++j)
{
- // First lifting stage
+ // First lifting stage
line_data = &coeff_data[j][xp];
- predict.Filter(line_data[0] , line_data[1] , line_data[1]);
+ predict.Filter( line_data[0] , line_data[1] , line_data[1] );
- for(k = 2; k < xl - 2; k += 2)
- {
- predict.Filter(line_data[k] , line_data[k+1] , line_data[k-1]);
- update.Filter(line_data[k-1] , line_data[k-2] , line_data[k]);
+ for ( k = 2; k < xl -2; k+=2)
+ {
+ predict.Filter( line_data[k] , line_data[k+1] , line_data[k-1] );
+ update.Filter( line_data[k-1] , line_data[k-2] , line_data[k] );
}// i
-
- predict.Filter(line_data[xl-2] , line_data[xl-3] , line_data[xl-1]);
- update.Filter(line_data[xl-3] , line_data[xl-2] , line_data[xl-4]);
- update.Filter(line_data[xl-1] , line_data[xl-2] , line_data[xl-2]);
+
+ predict.Filter( line_data[xl-2] , line_data[xl-3] , line_data[xl-1] );
+ update.Filter( line_data[xl-3] , line_data[xl-2] , line_data[xl-4] );
+ update.Filter( line_data[xl-1] , line_data[xl-2] , line_data[xl-2] );
}
_mm_empty();
@@ -1075,16 +1075,16 @@ void VHFilterLEGALL5_3::Synth(const int xp ,
#if 0
//Opts Attempt 2
void VHFilterLEGALL5_3::Synth(const int xp ,
- const int yp ,
- const int xl ,
- const int yl ,
- PicArray& coeff_data)
+ const int yp ,
+ const int xl ,
+ const int yl ,
+ PicArray& coeff_data)
{
- int i, j, k;
- const int yend(yp + yl);
+ int i,j,k;
+ const int yend( yp+yl );
- const int xl2(xl >> 1);
- const int ymid(yp + (yl >> 1));
+ const int xl2 (xl>>1);
+ const int ymid (yp + (yl>>1));
const PredictStepShift< 2 > predict;
const UpdateStepShift< 1 > update;
@@ -1094,57 +1094,57 @@ void VHFilterLEGALL5_3::Synth(const int xp ,
// Next, do the vertical synthesis
// First lifting stage
- int xstop = (xl >> 2) << 2;
+ int xstop = (xl>>2)<<2;
CoeffType *row1, *row2, *row3, *row4;
// First do the top edge
row1 = &coeff_data[yp][xp];
row2 = &coeff_data[ymid][xp];
- for(i = 0 ; i < xstop ; i += 4)
+ for ( i = 0 ; i < xstop ; i+=4)
{
- __m64 tmp = _mm_add_pi16(*(__m64 *)row2, *(__m64 *)row2);
+ __m64 tmp = _mm_add_pi16 (*(__m64 *)row2, *(__m64 *)row2);
tmp = _mm_srai_pi16(tmp, 2);
- *(__m64 *)row1 = _mm_sub_pi16(*(__m64*)row1, tmp);
- row1 += 4;
- row2 += 4;
+ *(__m64 *)row1 = _mm_sub_pi16 (*(__m64*)row1, tmp);
+ row1+=4;
+ row2+=4;
}// i
//mopup
- for(i = xstop ; i < xl ; ++i)
+ for ( i = xstop ; i < xl ; ++i)
{
- predict.Filter(*row1 , *row2 , *row2);
+ predict.Filter( *row1 , *row2 , *row2);
++row1;
++row2;
}// i
// Next, do the middle bit
- for(k = 1 ; k < ymid - 1 ; ++k)
+ for ( k = 1 ; k < ymid-1 ; ++k)
{
row1 = &coeff_data[k-1][xp];
row2 = &coeff_data[k][xp];
row3 = &coeff_data[ymid+k-1][xp];
row4 = &coeff_data[ymid+k][xp];
- for(i = 0 ; i < xstop ; i += 4)
+ for ( i = 0 ; i < xstop ; i+=4)
{
- __m64 tmp = _mm_add_pi16(*(__m64 *)row3, *(__m64 *)row4);
+ __m64 tmp = _mm_add_pi16 (*(__m64 *)row3, *(__m64 *)row4);
tmp = _mm_srai_pi16(tmp, 2);
- *(__m64 *)row2 = _mm_sub_pi16(*(__m64*)row2, tmp);
+ *(__m64 *)row2 = _mm_sub_pi16 (*(__m64*)row2, tmp);
- tmp = _mm_add_pi16(*(__m64 *)row2, *(__m64 *)row1);
+ tmp = _mm_add_pi16 (*(__m64 *)row2, *(__m64 *)row1);
tmp = _mm_srai_pi16(tmp, 1);
- *(__m64 *)row3 = _mm_add_pi16(*(__m64*)row3, tmp);
-
+ *(__m64 *)row3 = _mm_add_pi16 (*(__m64*)row3, tmp);
+
row1 += 4;
row2 += 4;
row3 += 4;
row4 += 4;
}// i
- for(i = xstop ; i < xl ; ++i)
+ for ( i = xstop ; i < xl ; ++i)
{
- predict.Filter(*row2 , *row4 , *row3);
- update.Filter(*row3 , *row2 , *row1);
+ predict.Filter( *row2 , *row4 , *row3 );
+ update.Filter( *row3 , *row2 , *row1 );
++row1;
++row2;
++row3;
@@ -1158,31 +1158,31 @@ void VHFilterLEGALL5_3::Synth(const int xp ,
row2 = &coeff_data[ymid-1][xp];
row3 = &coeff_data[yend-2][xp];
row4 = &coeff_data[yend-1][xp];
- for(i = xp ; i < xstop ; i += 4)
+ for ( i = xp ; i< xstop ; i+=4)
{
- __m64 tmp = _mm_add_pi16(*(__m64 *)row3, *(__m64 *)row4);
+ __m64 tmp = _mm_add_pi16 (*(__m64 *)row3, *(__m64 *)row4);
tmp = _mm_srai_pi16(tmp, 2);
- *(__m64 *)row2 = _mm_sub_pi16(*(__m64*)row2, tmp);
+ *(__m64 *)row2 = _mm_sub_pi16 (*(__m64*)row2, tmp);
- tmp = _mm_add_pi16(*(__m64 *)row2, *(__m64 *)row1);
+ tmp = _mm_add_pi16 (*(__m64 *)row2, *(__m64 *)row1);
tmp = _mm_srai_pi16(tmp, 1);
- *(__m64 *)row3 = _mm_add_pi16(*(__m64*)row3, tmp);
-
- tmp = _mm_add_pi16(*(__m64 *)row2, *(__m64 *)row2);
+ *(__m64 *)row3 = _mm_add_pi16 (*(__m64*)row3, tmp);
+
+ tmp = _mm_add_pi16 (*(__m64 *)row2, *(__m64 *)row2);
tmp = _mm_srai_pi16(tmp, 1);
- *(__m64 *)row4 = _mm_add_pi16(*(__m64*)row4, tmp);
-
+ *(__m64 *)row4 = _mm_add_pi16 (*(__m64*)row4, tmp);
+
row1 += 4;
row2 += 4;
row3 += 4;
row4 += 4;
}// i
// mopup
- for(i = xstop ; i < xl ; ++i)
+ for ( i = xstop ; i< xl ; ++i)
{
- predict.Filter(*row2 , *row3 , *row4);
- update.Filter(*row3 , *row1 , *row2);
- update.Filter(*row4 , *row2 , *row2);
+ predict.Filter( *row2 , *row3 , *row4 );
+ update.Filter( *row3 , *row1 , *row2 );
+ update.Filter( *row4 , *row2 , *row2 );
++row1;
++row2;
++row3;
@@ -1190,26 +1190,26 @@ void VHFilterLEGALL5_3::Synth(const int xp ,
}// i
// Next do the horizontal synthesis
- xstop = (((xl2 - 2) >> 2) << 2) + 1;
+ xstop = (((xl2 - 2)>>2)<<2) + 1;
//xstop = 1;
- for(j = yp; j < yend ; ++j)
+ for (j = yp; j < yend ; ++j)
{
- // First lifting stage
+ // First lifting stage
line_data = &coeff_data[j][xp];
- predict.Filter(line_data[0] , line_data[xl2] , line_data[xl2]);
+ predict.Filter( line_data[0] , line_data[xl2] , line_data[xl2] );
- for(k = 1; k < xstop; k += 4)
- {
+ for ( k = 1; k < xstop; k+=4)
+ {
//predict.Filter( line_data[k] , line_data[xl2+k] , line_data[xl2+k-1] );
- __m64 m1 = _mm_add_pi16(*(__m64 *)(line_data + xl2 + k), *(__m64 *)(line_data + xl2 + k - 1));
- m1 = _mm_srai_pi16(m1, 2);
- *(__m64 *)(line_data + k) = _mm_sub_pi16(*(__m64 *)(line_data + k), m1);
+ __m64 m1 = _mm_add_pi16 (*(__m64 *)(line_data+xl2+k), *(__m64 *)(line_data+xl2+k-1));
+ m1 = _mm_srai_pi16 (m1, 2);
+ *(__m64 *)(line_data+k) = _mm_sub_pi16 (*(__m64 *)(line_data+k), m1);
//update.Filter( line_data[xl2+k-1] , line_data[k] , line_data[k-1] );
- m1 = _mm_add_pi16(*(__m64 *)(line_data + k), *(__m64 *)(line_data + k - 1));
+ m1 = _mm_add_pi16 (*(__m64 *)(line_data+k), *(__m64 *)(line_data+k-1));
m1 = _mm_srai_pi16(m1, 1);
- *(__m64 *)(line_data + xl2 + k - 1) = _mm_add_pi16(*(__m64*)(line_data + xl2 + k - 1), m1);
-
+ *(__m64 *)(line_data+xl2+k-1) = _mm_add_pi16 (*(__m64*)(line_data+xl2+k-1), m1);
+
row1 += 4;
row2 += 4;
row3 += 4;
@@ -1217,122 +1217,122 @@ void VHFilterLEGALL5_3::Synth(const int xp ,
}// i
- for(k = xstop; k < xl2 - 1; ++k)
- {
- predict.Filter(line_data[k] , line_data[xl2+k] , line_data[xl2+k-1]);
- update.Filter(line_data[xl2+k-1] , line_data[k] , line_data[k-1]);
+ for ( k = xstop; k < xl2-1; ++k)
+ {
+ predict.Filter( line_data[k] , line_data[xl2+k] , line_data[xl2+k-1] );
+ update.Filter( line_data[xl2+k-1] , line_data[k] , line_data[k-1] );
}// i
- predict.Filter(line_data[xl2-1] , line_data[xl-2] , line_data[xl-1]);
- update.Filter(line_data[xl-2] , line_data[xl2-2] , line_data[xl2-1]);
- update.Filter(line_data[xl-1] , line_data[xl2-1] , line_data[xl2-1]);
+ predict.Filter( line_data[xl2-1] , line_data[xl-2] , line_data[xl-1] );
+ update.Filter( line_data[xl-2] , line_data[xl2-2] , line_data[xl2-1] );
+ update.Filter( line_data[xl-1] , line_data[xl2-1] , line_data[xl2-1] );
}
_mm_empty();
-
+
// Finally interleave subbands
- Interleave_mmx(xp , yp , xl , yl , coeff_data);
+ Interleave_mmx( xp , yp , xl , yl , coeff_data );
}
#endif
//Attempt 3
-inline void VHFilterLEGALL5_3::HorizSynth(int xp, int xl, int ystart, int yend, CoeffArray &coeff_data)
+inline void VHFilterLEGALL5_3::HorizSynth (int xp, int xl, int ystart, int yend, CoeffArray &coeff_data)
{
static const PredictStepShift< 2 > predict;
static const UpdateStepShift< 1 > update;
int j, k;
// Next do the horizontal synthesis
- for(j = ystart; j <= yend ; ++j)
+ for (j = ystart; j <= yend ; ++j)
{
- // First lifting stage
+ // First lifting stage
CoeffType *line_data = &coeff_data[j][xp];
- predict.Filter(line_data[0] , line_data[1] , line_data[1]);
+ predict.Filter( line_data[0] , line_data[1] , line_data[1] );
- for(k = 2; k < xl - 2; k += 2)
- {
- predict.Filter(line_data[k] , line_data[k+1] , line_data[k-1]);
- update.Filter(line_data[k-1] , line_data[k-2] , line_data[k]);
+ for ( k = 2; k < xl -2; k+=2)
+ {
+ predict.Filter( line_data[k] , line_data[k+1] , line_data[k-1] );
+ update.Filter( line_data[k-1] , line_data[k-2] , line_data[k] );
}// i
-
- predict.Filter(line_data[xl-2] , line_data[xl-3] , line_data[xl-1]);
- update.Filter(line_data[xl-3] , line_data[xl-2] , line_data[xl-4]);
- update.Filter(line_data[xl-1] , line_data[xl-2] , line_data[xl-2]);
+
+ predict.Filter( line_data[xl-2] , line_data[xl-3] , line_data[xl-1] );
+ update.Filter( line_data[xl-3] , line_data[xl-2] , line_data[xl-4] );
+ update.Filter( line_data[xl-1] , line_data[xl-2] , line_data[xl-2] );
// Shift right by one bit to counter the shift in the analysis stage
ShiftRowRight(line_data, xl, 1);
}
}
void VHFilterLEGALL5_3::Synth(const int xp ,
- const int yp ,
- const int xl ,
- const int yl ,
- CoeffArray &coeff_data)
+ const int yp ,
+ const int xl ,
+ const int yl ,
+ CoeffArray &coeff_data)
{
int i, k;
- const int xend(xp + xl);
- const int yend(yp + yl);
+ const int xend( xp+xl );
+ const int yend( yp+yl );
const PredictStepShift< 2 > predict;
- __m64 pred_round = _mm_set_pi16(1 << (2 - 1), 1 << (2 - 1), 1 << (2 - 1), 1 << (2 - 1));
+ __m64 pred_round = _mm_set_pi16 (1<<(2-1), 1<<(2-1), 1<<(2-1), 1<<(2-1));
const UpdateStepShift< 1 > update;
- __m64 update_round = _mm_set_pi16(1, 1, 1, 1);
+ __m64 update_round = _mm_set_pi16 (1, 1, 1, 1);
int horiz_start = 0;
int horiz_end = 0;
- // Firstly reorder to interleave subbands, so that subsequent calculations
+ // Firstly reorder to interleave subbands, so that subsequent calculations
// can be in-place
- Interleave_mmx(xp , yp , xl , yl , coeff_data);
+ Interleave_mmx( xp , yp , xl , yl , coeff_data );
// Next, do the vertical synthesis
// First lifting stage
- int xstop = (xend >> 2) << 2;
-
+ int xstop = (xend>>2)<<2;
+
// Begin the top edge
CoeffType *row1, *row2, *row3, *row4;
row1 = &coeff_data[yp][xp];
row2 = &coeff_data[yp+1][xp];
- for(i = xp ; i < xstop ; i += 4)
+ for ( i = xp ; i < xstop ; i+=4)
{
- __m64 tmp = _mm_add_pi16(*(__m64 *)row2, *(__m64 *)row2);
- tmp = _mm_add_pi16(tmp, pred_round);
+ __m64 tmp = _mm_add_pi16 (*(__m64 *)row2, *(__m64 *)row2);
+ tmp = _mm_add_pi16 (tmp, pred_round);
tmp = _mm_srai_pi16(tmp, 2);
- *(__m64 *)row1 = _mm_sub_pi16(*(__m64*)row1, tmp);
+ *(__m64 *)row1 = _mm_sub_pi16 (*(__m64*)row1, tmp);
row1 += 4;
row2 += 4;
}
// Mopup
- for(i = xstop ; i < xend ; ++i)
+ for ( i = xstop ; i < xend ; ++i)
{
- predict.Filter(*row1, *row2, *row2);
+ predict.Filter( *row1, *row2, *row2 );
++row1;
++row2;
}// i
// Next, do the middle bit
- for(k = yp + 2 ; k < yend - 2 ; k += 2)
+ for ( k = yp+2 ; k < yend-2 ; k+=2)
{
CoeffType *row1 = &coeff_data[k-2][xp];
CoeffType *row2 = &coeff_data[k-1][xp];
CoeffType *row3 = &coeff_data[k][xp];
CoeffType *row4 = &coeff_data[k+1][xp];
- for(i = xp ; i < xstop ; i += 4)
+ for ( i = xp ; i < xstop ; i+=4)
{
- __m64 tmp = _mm_add_pi16(*(__m64 *)row4, *(__m64 *)row2);
- tmp = _mm_add_pi16(tmp, pred_round);
+ __m64 tmp = _mm_add_pi16 (*(__m64 *)row4, *(__m64 *)row2);
+ tmp = _mm_add_pi16 (tmp, pred_round);
tmp = _mm_srai_pi16(tmp, 2);
- *(__m64 *)row3 = _mm_sub_pi16(*(__m64*)row3, tmp);
+ *(__m64 *)row3 = _mm_sub_pi16 (*(__m64*)row3, tmp);
- tmp = _mm_add_pi16(*(__m64 *)row1, *(__m64 *)row3);
- tmp = _mm_add_pi16(tmp, update_round);
+ tmp = _mm_add_pi16 (*(__m64 *)row1, *(__m64 *)row3);
+ tmp = _mm_add_pi16 (tmp, update_round);
tmp = _mm_srai_pi16(tmp, 1);
- *(__m64 *)row2 = _mm_add_pi16(*(__m64*)row2, tmp);
+ *(__m64 *)row2 = _mm_add_pi16 (*(__m64*)row2, tmp);
row1 += 4;
row2 += 4;
row3 += 4;
@@ -1340,10 +1340,10 @@ void VHFilterLEGALL5_3::Synth(const int xp ,
}// i
//Mopup
- for(i = xstop ; i < xend ; ++i)
+ for ( i = xstop ; i < xend ; ++i)
{
- predict.Filter(*row3, *row2, *row4);
- update.Filter(*row2, *row1, *row3);
+ predict.Filter( *row3, *row2, *row4 );
+ update.Filter( *row2, *row1, *row3 );
++row1;
++row2;
++row3;
@@ -1351,32 +1351,32 @@ void VHFilterLEGALL5_3::Synth(const int xp ,
}// i
horiz_end = k - 2;
// Do the horizontal synthesis
- HorizSynth(xp, xl, horiz_start, horiz_end, coeff_data);
+ HorizSynth (xp, xl, horiz_start, horiz_end, coeff_data);
horiz_start = horiz_end + 1;
}// j
-
+
// Finally with the bottom edge
row1 = &coeff_data[yend-4][xp];
row2 = &coeff_data[yend-3][xp];
row3 = &coeff_data[yend-2][xp];
row4 = &coeff_data[yend-1][xp];
- for(i = xp ; i < xstop ; i += 4)
+ for ( i = xp ; i < xstop ; i+=4)
{
- __m64 tmp = _mm_add_pi16(*(__m64 *)row2, *(__m64 *)row4);
- tmp = _mm_add_pi16(tmp, pred_round);
+ __m64 tmp = _mm_add_pi16 (*(__m64 *)row2, *(__m64 *)row4);
+ tmp = _mm_add_pi16 (tmp, pred_round);
tmp = _mm_srai_pi16(tmp, 2);
- *(__m64 *)row3 = _mm_sub_pi16(*(__m64*)row3, tmp);
+ *(__m64 *)row3 = _mm_sub_pi16 (*(__m64*)row3, tmp);
- tmp = _mm_add_pi16(*(__m64 *)row3, *(__m64 *)row1);
- tmp = _mm_add_pi16(tmp, update_round);
+ tmp = _mm_add_pi16 (*(__m64 *)row3, *(__m64 *)row1);
+ tmp = _mm_add_pi16 (tmp, update_round);
tmp = _mm_srai_pi16(tmp, 1);
- *(__m64 *)row2 = _mm_add_pi16(*(__m64*)row2, tmp);
+ *(__m64 *)row2 = _mm_add_pi16 (*(__m64*)row2, tmp);
- tmp = _mm_add_pi16(*(__m64 *)row3, *(__m64 *)row3);
- tmp = _mm_add_pi16(tmp, update_round);
+ tmp = _mm_add_pi16 (*(__m64 *)row3, *(__m64 *)row3);
+ tmp = _mm_add_pi16 (tmp, update_round);
tmp = _mm_srai_pi16(tmp, 1);
- *(__m64 *)row4 = _mm_add_pi16(*(__m64*)row4, tmp);
+ *(__m64 *)row4 = _mm_add_pi16 (*(__m64*)row4, tmp);
row1 += 4;
row2 += 4;
@@ -1384,11 +1384,11 @@ void VHFilterLEGALL5_3::Synth(const int xp ,
row4 += 4;
}// i
// mopup
- for(i = xstop ; i < xend ; ++i)
+ for ( i = xstop ; i < xend ; ++i)
{
- predict.Filter(*row3, *row2, *row4);
- update.Filter(*row2, *row1, *row3);
- update.Filter(*row4, *row3, *row3);
+ predict.Filter( *row3, *row2, *row4 );
+ update.Filter( *row2, *row1, *row3 );
+ update.Filter( *row4, *row3, *row3 );
++row1;
++row2;
++row3;
@@ -1397,130 +1397,130 @@ void VHFilterLEGALL5_3::Synth(const int xp ,
_mm_empty();
// Last lines of horizontal synthesis
- HorizSynth(xp, xl, horiz_start, yend - 1, coeff_data);
+ HorizSynth (xp, xl, horiz_start, yend-1, coeff_data);
}
-void DeInterleave_mmx(const int xp ,
- const int yp ,
- const int xl ,
- const int yl ,
- CoeffArray &coeff_data)
+void DeInterleave_mmx( const int xp ,
+ const int yp ,
+ const int xl ,
+ const int yl ,
+ CoeffArray &coeff_data)
{
- const int xl2(xl >> 1);
- const int yl2(yl >> 1);
- const int yend(yp + yl);
+ const int xl2( xl>>1);
+ const int yl2( yl>>1);
+ const int yend( yp + yl );
- if(coeff_data.LengthX() > t_temp_data.LengthX() ||
- coeff_data.LengthY() > t_temp_data.LengthY())
+ if (coeff_data.LengthX() > t_temp_data.LengthX() ||
+ coeff_data.LengthY() > t_temp_data.LengthY())
{
t_temp_data.Resize(coeff_data.LengthY(), coeff_data.LengthX());
}
// Make a temporary copy of the subband
- for(int j = yp; j < yend ; j++)
- memcpy(t_temp_data[j-yp] , coeff_data[j] + xp , xl * sizeof(CoeffType));
-
- int stopx = (xl2 >> 2) << 2;
+ for (int j = yp; j<yend ; j++ )
+ memcpy( t_temp_data[j-yp] , coeff_data[j]+xp , xl * sizeof( CoeffType ) );
- for(int j = yp, s = 0; j < (yp + yl2) ; j++, s += 2)
+ int stopx = (xl2>>2)<<2;
+
+ for (int j = yp, s=0; j<(yp+yl2) ; j++, s+=2)
{
CoeffType *tmp1 = &t_temp_data[s][0];
CoeffType *out1 = &coeff_data[j][xp];
CoeffType *out2 = &coeff_data[j][xl2];
int r = xp;
- for(int i = 0; i < xp + stopx ; i += 4 , r += 8)
+ for (int i = 0; i<xp+stopx ; i+=4 , r+=8)
{
- __m64 m1 = _mm_unpacklo_pi16(*(__m64 *)tmp1, *(__m64 *)(tmp1 + 4));
- __m64 m2 = _mm_unpackhi_pi16(*(__m64 *)tmp1, *(__m64 *)(tmp1 + 4));
- *(__m64 *)out1 = _mm_unpacklo_pi16(m1, m2);
- *(__m64 *)out2 = _mm_unpackhi_pi16(m1, m2);
+ __m64 m1 = _mm_unpacklo_pi16 (*(__m64 *)tmp1, *(__m64 *)(tmp1+4));
+ __m64 m2 = _mm_unpackhi_pi16 (*(__m64 *)tmp1, *(__m64 *)(tmp1+4));
+ *(__m64 *)out1 = _mm_unpacklo_pi16 (m1, m2);
+ *(__m64 *)out2 = _mm_unpackhi_pi16 (m1, m2);
out1 += 4;
out2 += 4;
- tmp1 += 8;
+ tmp1+=8;
}
//mopup
- for(int i = xp + stopx; i < xp + xl2; ++i, r += 2)
+ for (int i = xp+stopx; i < xp+xl2; ++i, r+=2)
{
coeff_data[j][i] = t_temp_data[s][r];
coeff_data[j][i+xl2] = t_temp_data[s][r+1];
}
- }// j
+ }// j
- for(int j = yl2, s = 1; j < yend ; j++, s += 2)
+ for (int j = yl2, s=1; j< yend ; j++, s+=2)
{
CoeffType *tmp1 = &t_temp_data[s][0];
CoeffType *out1 = &coeff_data[j][xp];
CoeffType *out2 = &coeff_data[j][xl2];
int r = xp;
- for(int i = 0; i < xp + stopx ; i += 4 , r += 8)
+ for (int i = 0; i<xp+stopx ; i+=4 , r+=8)
{
- __m64 m1 = _mm_unpacklo_pi16(*(__m64 *)tmp1, *(__m64 *)(tmp1 + 4));
- __m64 m2 = _mm_unpackhi_pi16(*(__m64 *)tmp1, *(__m64 *)(tmp1 + 4));
- *(__m64 *)out1 = _mm_unpacklo_pi16(m1, m2);
- *(__m64 *)out2 = _mm_unpackhi_pi16(m1, m2);
+ __m64 m1 = _mm_unpacklo_pi16 (*(__m64 *)tmp1, *(__m64 *)(tmp1+4));
+ __m64 m2 = _mm_unpackhi_pi16 (*(__m64 *)tmp1, *(__m64 *)(tmp1+4));
+ *(__m64 *)out1 = _mm_unpacklo_pi16 (m1, m2);
+ *(__m64 *)out2 = _mm_unpackhi_pi16 (m1, m2);
out1 += 4;
out2 += 4;
- tmp1 += 8;
+ tmp1+=8;
}
//mopup
- for(int i = xp + stopx; i < xp + xl2; ++i, r += 2)
+ for (int i = xp+stopx; i < xp+xl2; ++i, r+=2)
{
coeff_data[j][i] = t_temp_data[s][r];
coeff_data[j][i+xl2] = t_temp_data[s][r+1];
}
- }// j
+ }// j
_mm_empty();
}
-void VHFilterLEGALL5_3::Split(const int xp ,
- const int yp ,
- const int xl ,
- const int yl ,
- CoeffArray& coeff_data)
+void VHFilterLEGALL5_3::Split(const int xp ,
+ const int yp ,
+ const int xl ,
+ const int yl ,
+ CoeffArray& coeff_data)
{
//version based on integer-like types
//using edge-extension rather than reflection
- const int xend = xp + xl;
- const int yend = yp + yl;
- const int xl2 = xl >> 1;
- const int yl2 = yl >> 1;
+ const int xend=xp+xl;
+ const int yend=yp+yl;
+ const int xl2 = xl>>1;
+ const int yl2 = yl>>1;
- CoeffType* line_data;
+ CoeffType* line_data;
// Positional variables
- int i, j, k;
-
- // Objects to do lifting stages
+ int i,j,k;
+
+ // Objects to do lifting stages
// (in revese order and type from synthesis)
const PredictStepShift< 1 > predict;
- __m64 pred_round = _mm_set_pi16(1, 1, 1, 1);
+ __m64 pred_round = _mm_set_pi16 (1, 1, 1, 1);
const UpdateStepShift< 2 > update;
- __m64 update_round = _mm_set_pi16(1 << (2 - 1), 1 << (2 - 1), 1 << (2 - 1), 1 << (2 - 1));
+ __m64 update_round = _mm_set_pi16 (1<<(2-1), 1<<(2-1), 1<<(2-1), 1<<(2-1));
// Lastly, have to reorder so that subbands are no longer interleaved
- DeInterleave_mmx(xp , yp , xl , yl , coeff_data);
- //first do horizontal
+ DeInterleave_mmx( xp , yp , xl , yl , coeff_data );
+ //first do horizontal
- for(j = yp; j < yend; ++j)
+ for (j = yp; j < yend; ++j)
{
// First lifting stage
line_data = &coeff_data[j][xp];
// Shift left by one bit to give us more accuracy
ShiftRowLeft(line_data, xl, 1);
- predict.Filter(line_data[xp+xl2] , line_data[1] , line_data[0]);
- update.Filter(line_data[0] , line_data[xp+xl2] , line_data[xp+xl2]);
+ predict.Filter( line_data[xp+xl2] , line_data[1] , line_data[0] );
+ update.Filter( line_data[0] , line_data[xp+xl2] , line_data[xp+xl2] );
- for(k = 1; k < xp + xl2 - 1; k += 1)
+ for (k = 1; k < xp+xl2-1; k+=1)
{
- predict.Filter(line_data[xp+xl2+k] , line_data[k+1] , line_data[k]);
- update.Filter(line_data[k] , line_data[xp+xl2+k-1] , line_data[xp+xl2+k]);
+ predict.Filter( line_data[xp+xl2+k] , line_data[k+1] , line_data[k] );
+ update.Filter( line_data[k] , line_data[xp+xl2+k-1] , line_data[xp+xl2+k] );
}// i
-
- predict.Filter(line_data[xl-1] , line_data[xp+xl2-1] , line_data[xp+xl2-1]);
- update.Filter(line_data[xp+xl2-1] , line_data[xl-2] , line_data[xl-1]);
+
+ predict.Filter( line_data[xl-1] , line_data[xp+xl2-1] , line_data[xp+xl2-1] );
+ update.Filter( line_data[xp+xl2-1] , line_data[xl-2] , line_data[xl-1] );
}// j
@@ -1529,54 +1529,54 @@ void VHFilterLEGALL5_3::Split(const int xp ,
// First lifting stage
// top edge - j=xp
- int stopX = (xl >> 2) << 2;
+ int stopX = (xl>>2)<<2;
CoeffType *in_val = &coeff_data[yp+yl2][xp];
CoeffType *val1 = &coeff_data[1][xp];
CoeffType *val2 = &coeff_data[0][xp];
- for(i = xp ; i < (xp + stopX); i += 4)
+ for ( i = xp ; i<(xp+stopX); i+=4)
{
//predict.Filter( coeff_data[yp+yl2][i] , coeff_data[1][i] , coeff_data[0][i] );
- __m64 m1 = _mm_add_pi16(*(__m64 *)val1, *(__m64 *)val2);
- m1 = _mm_add_pi16(m1, pred_round);
+ __m64 m1 = _mm_add_pi16 (*(__m64 *)val1, *(__m64 *)val2);
+ m1 = _mm_add_pi16 (m1, pred_round);
m1 = _mm_srai_pi16(m1, 1);
- *(__m64 *)in_val = _mm_sub_pi16(*(__m64 *)in_val, m1);
+ *(__m64 *)in_val = _mm_sub_pi16 (*(__m64 *)in_val, m1);
//update.Filter( coeff_data[0][i] , coeff_data[yp+yl2][i] , coeff_data[yp+yl2][i] );
- m1 = _mm_add_pi16(*(__m64 *)in_val, *(__m64 *)in_val);
- m1 = _mm_add_pi16(m1, update_round);
+ m1 = _mm_add_pi16 (*(__m64 *)in_val, *(__m64 *)in_val);
+ m1 = _mm_add_pi16 (m1, update_round);
m1 = _mm_srai_pi16(m1, 2);
- *(__m64 *)val2 = _mm_add_pi16(*(__m64 *)val2, m1);
+ *(__m64 *)val2 = _mm_add_pi16 (*(__m64 *)val2, m1);
in_val += 4;
val1 += 4;
val2 += 4;
}// i
// mopup
- for(i = xp + stopX ; i < xend ; ++ i)
+ for ( i = xp+stopX ; i<xend ; ++ i)
{
- predict.Filter(coeff_data[yp+yl2][i] , coeff_data[1][i] , coeff_data[0][i]);
- update.Filter(coeff_data[0][i] , coeff_data[yp+yl2][i] , coeff_data[yp+yl2][i]);
+ predict.Filter( coeff_data[yp+yl2][i] , coeff_data[1][i] , coeff_data[0][i] );
+ update.Filter( coeff_data[0][i] , coeff_data[yp+yl2][i] , coeff_data[yp+yl2][i] );
}// i
// middle bit
- for(k = 1 ; k < yp + yl2 - 1 ; k += 1)
+ for (k = 1 ; k<yp+yl2-1 ; k+=1)
{
CoeffType *in_val = &coeff_data[yp+yl2+k][xp];
CoeffType *in_val2 = &coeff_data[yp+yl2+k-1][xp];
CoeffType *val1 = &coeff_data[k+1][xp];
CoeffType *val2 = &coeff_data[k][xp];
- for(i = xp ; i < xp + stopX ; i += 4)
+ for ( i = xp ; i<xp+stopX ; i+=4)
{
//predict.Filter( coeff_data[yp+yl2+k][i] , coeff_data[k+1][i] , coeff_data[k][i] );
- __m64 m1 = _mm_add_pi16(*(__m64 *)val1, *(__m64 *)val2);
- m1 = _mm_add_pi16(m1, pred_round);
+ __m64 m1 = _mm_add_pi16 (*(__m64 *)val1, *(__m64 *)val2);
+ m1 = _mm_add_pi16 (m1, pred_round);
m1 = _mm_srai_pi16(m1, 1);
- *(__m64 *)in_val = _mm_sub_pi16(*(__m64 *)in_val, m1);
-
+ *(__m64 *)in_val = _mm_sub_pi16 (*(__m64 *)in_val, m1);
+
//update.Filter( coeff_data[k][i] , coeff_data[yp+yl2+k-1][i] , coeff_data[yp+yl2+k][i] );
- m1 = _mm_add_pi16(*(__m64 *)in_val, *(__m64 *)in_val2);
- m1 = _mm_add_pi16(m1, update_round);
+ m1 = _mm_add_pi16 (*(__m64 *)in_val, *(__m64 *)in_val2);
+ m1 = _mm_add_pi16 (m1, update_round);
m1 = _mm_srai_pi16(m1, 2);
- *(__m64 *)val2 = _mm_add_pi16(*(__m64 *)val2, m1);
+ *(__m64 *)val2 = _mm_add_pi16 (*(__m64 *)val2, m1);
in_val += 4;
in_val2 += 4;
@@ -1585,10 +1585,10 @@ void VHFilterLEGALL5_3::Split(const int xp ,
}// i
//mopup
- for(i = xp + stopX ; i < xend ; ++ i)
+ for ( i = xp+stopX ; i<xend ; ++ i)
{
- predict.Filter(coeff_data[yp+yl2+k][i] , coeff_data[k+1][i] , coeff_data[k][i]);
- update.Filter(coeff_data[k][i] , coeff_data[yp+yl2+k-1][i] , coeff_data[yp+yl2+k][i]);
+ predict.Filter( coeff_data[yp+yl2+k][i] , coeff_data[k+1][i] , coeff_data[k][i] );
+ update.Filter( coeff_data[k][i] , coeff_data[yp+yl2+k-1][i] , coeff_data[yp+yl2+k][i] );
}// i
}// j
@@ -1596,29 +1596,29 @@ void VHFilterLEGALL5_3::Split(const int xp ,
val2 = &coeff_data[yp+yl2-1][xp];
CoeffType *in_val2 = &coeff_data[yend-2][xp];
// bottom edge
- for(i = xp ; i < xp + stopX ; i += 4)
+ for ( i = xp ; i<xp+stopX ; i+=4)
{
//predict.Filter( coeff_data[yend-1][i] , coeff_data[yp+yl2-1][i] , coeff_data[yp+yl2-1][i] );
- __m64 m1 = _mm_add_pi16(*(__m64 *)val2, *(__m64 *)val2);
- m1 = _mm_add_pi16(m1, pred_round);
+ __m64 m1 = _mm_add_pi16 (*(__m64 *)val2, *(__m64 *)val2);
+ m1 = _mm_add_pi16 (m1, pred_round);
m1 = _mm_srai_pi16(m1, 1);
- *(__m64 *)in_val = _mm_sub_pi16(*(__m64 *)in_val, m1);
-
- //update.Filter( coeff_data[yp+yl2-1][i] , coeff_data[yend-2][i] , coeff_data[yend-1][i] );
- m1 = _mm_add_pi16(*(__m64 *)in_val2, *(__m64 *)in_val);
- m1 = _mm_add_pi16(m1, update_round);
+ *(__m64 *)in_val = _mm_sub_pi16 (*(__m64 *)in_val, m1);
+
+ //update.Filter( coeff_data[yp+yl2-1][i] , coeff_data[yend-2][i] , coeff_data[yend-1][i] );
+ m1 = _mm_add_pi16 (*(__m64 *)in_val2, *(__m64 *)in_val);
+ m1 = _mm_add_pi16 (m1, update_round);
m1 = _mm_srai_pi16(m1, 2);
- *(__m64 *)val2 = _mm_add_pi16(*(__m64 *)val2, m1);
+ *(__m64 *)val2 = _mm_add_pi16 (*(__m64 *)val2, m1);
in_val += 4;
in_val2 += 4;
val2 += 4;
}// i
// mopup
- for(i = xp + stopX ; i < xend ; ++ i)
+ for ( i = xp+stopX ; i<xend ; ++ i)
{
- predict.Filter(coeff_data[yend-1][i] , coeff_data[yp+yl2-1][i] , coeff_data[yp+yl2-1][i]);
- update.Filter(coeff_data[yp+yl2-1][i] , coeff_data[yend-2][i] , coeff_data[yend-1][i]);
+ predict.Filter( coeff_data[yend-1][i] , coeff_data[yp+yl2-1][i] , coeff_data[yp+yl2-1][i] );
+ update.Filter( coeff_data[yp+yl2-1][i] , coeff_data[yend-2][i] , coeff_data[yend-1][i] );
}// i
_mm_empty();
}
diff --git a/src/filters/parser/DiracSplitter/libdirac/libdirac_decoder/comp_decompress.cpp b/src/filters/parser/DiracSplitter/libdirac/libdirac_decoder/comp_decompress.cpp
index 3701865e5..3067c241e 100644
--- a/src/filters/parser/DiracSplitter/libdirac/libdirac_decoder/comp_decompress.cpp
+++ b/src/filters/parser/DiracSplitter/libdirac/libdirac_decoder/comp_decompress.cpp
@@ -53,11 +53,11 @@ using namespace dirac;
using std::vector;
//Constructor
-CompDecompressor::CompDecompressor(DecoderParams& decp, const PictureParams& pp)
- :
+CompDecompressor::CompDecompressor( DecoderParams& decp, const PictureParams& pp)
+:
m_decparams(decp),
m_pparams(pp),
- m_psort(pp.PicSort())
+ m_psort( pp.PicSort() )
{}
@@ -67,103 +67,97 @@ void CompDecompressor::Decompress(ComponentByteIO* p_component_byteio,
{
// Set up the code blocks
- SetupCodeBlocks(bands);
+ SetupCodeBlocks( bands );
- for(int b = bands.Length() ; b >= 1 ; --b)
- {
+ for ( int b=bands.Length() ; b>=1 ; --b ){
// Multiple quantiser are used only if
// a. The global code_block_mode is QUANT_MULTIPLE
// and
// b. More than one code block is present in the subband.
bands(b).SetUsingMultiQuants(
- m_decparams.SpatialPartition() &&
- m_decparams.GetCodeBlockMode() == QUANT_MULTIPLE &&
- (bands(b).GetCodeBlocks().LengthX() > 1 ||
- bands(b).GetCodeBlocks().LengthY() > 1)
- );
+ m_decparams.SpatialPartition() &&
+ m_decparams.GetCodeBlockMode() == QUANT_MULTIPLE &&
+ (bands(b).GetCodeBlocks().LengthX() > 1 ||
+ bands(b).GetCodeBlocks().LengthY() > 1)
+ );
// Read the header data first
SubbandByteIO subband_byteio(bands(b), *p_component_byteio);
subband_byteio.Input();
- if(!bands(b).Skipped())
- {
- if(m_pparams.UsingAC())
- {
+ if ( !bands(b).Skipped() ){
+ if (m_pparams.UsingAC()){
// A pointer to the object(s) we'll be using for coding the bands
BandCodec* bdecoder;
- if(b >= bands.Length() - 3)
- {
- if(m_psort.IsIntra() && b == bands.Length())
- bdecoder = new IntraDCBandCodec(&subband_byteio,
- TOTAL_COEFF_CTXS , bands);
+ if ( b>=bands.Length()-3){
+ if ( m_psort.IsIntra() && b==bands.Length() )
+ bdecoder=new IntraDCBandCodec(&subband_byteio,
+ TOTAL_COEFF_CTXS ,bands);
else
- bdecoder = new LFBandCodec(&subband_byteio ,
- TOTAL_COEFF_CTXS, bands ,
- b, m_psort.IsIntra());
+ bdecoder=new LFBandCodec(&subband_byteio ,
+ TOTAL_COEFF_CTXS, bands ,
+ b, m_psort.IsIntra());
}
else
- bdecoder = new BandCodec(&subband_byteio , TOTAL_COEFF_CTXS ,
- bands , b, m_psort.IsIntra());
+ bdecoder=new BandCodec( &subband_byteio , TOTAL_COEFF_CTXS ,
+ bands , b, m_psort.IsIntra());
bdecoder->Decompress(coeff_data , subband_byteio.GetBandDataLength());
delete bdecoder;
}
- else
- {
+ else{
// A pointer to the object(s) we'll be using for coding the bands
BandVLC* bdecoder;
- if(m_psort.IsIntra() && b == bands.Length())
- bdecoder = new IntraDCBandVLC(&subband_byteio, bands);
+ if ( m_psort.IsIntra() && b==bands.Length() )
+ bdecoder=new IntraDCBandVLC(&subband_byteio, bands);
else
- bdecoder = new BandVLC(&subband_byteio , 0, bands ,
- b, m_psort.IsIntra());
+ bdecoder=new BandVLC( &subband_byteio , 0, bands ,
+ b, m_psort.IsIntra());
bdecoder->Decompress(coeff_data , subband_byteio.GetBandDataLength());
delete bdecoder;
}
}
- else
- {
- SetToVal(coeff_data , bands(b) , 0);
+ else{
+ SetToVal( coeff_data , bands(b) , 0 );
}
}
}
-void CompDecompressor::SetupCodeBlocks(SubbandList& bands)
+void CompDecompressor::SetupCodeBlocks( SubbandList& bands )
{
int xregions;
int yregions;
- for(int band_num = 1; band_num <= bands.Length() ; ++band_num)
+ for (int band_num = 1; band_num<=bands.Length() ; ++band_num)
{
- if(m_decparams.SpatialPartition())
+ if (m_decparams.SpatialPartition())
{
- int level = m_decparams.TransformDepth() - (band_num - 1) / 3;
+ int level = m_decparams.TransformDepth() - (band_num-1)/3;
const CodeBlocks &cb = m_decparams.GetCodeBlocks(level);
xregions = cb.HorizontalCodeBlocks();
yregions = cb.VerticalCodeBlocks();
}
else
{
- xregions = 1;
- yregions = 1;
+ xregions = 1;
+ yregions = 1;
}
- bands(band_num).SetNumBlocks(yregions , xregions);
+ bands( band_num ).SetNumBlocks( yregions ,xregions );
}// band_num
}
-void CompDecompressor::SetToVal(CoeffArray& coeff_data ,
- const Subband& node ,
- CoeffType val)
+void CompDecompressor::SetToVal( CoeffArray& coeff_data ,
+ const Subband& node ,
+ CoeffType val )
{
- for(int j = node.Yp() ; j < node.Yp() + node.Yl() ; ++j)
- for(int i = node.Xp() ; i < node.Xp() + node.Xl() ; ++i)
- coeff_data[j][i] = val;
+ for (int j=node.Yp() ; j<node.Yp()+node.Yl() ; ++j)
+ for (int i=node.Xp() ; i<node.Xp()+node.Xl() ; ++i)
+ coeff_data[j][i]=val;
}
diff --git a/src/filters/parser/DiracSplitter/libdirac/libdirac_decoder/comp_decompress.h b/src/filters/parser/DiracSplitter/libdirac/libdirac_decoder/comp_decompress.h
index 97602c5d3..6468c4ba7 100644
--- a/src/filters/parser/DiracSplitter/libdirac/libdirac_decoder/comp_decompress.h
+++ b/src/filters/parser/DiracSplitter/libdirac/libdirac_decoder/comp_decompress.h
@@ -48,81 +48,81 @@
namespace dirac
{
-//! Decompress a picture component
-/*!
- This class decompresses one of the three components (Y, U, or V) of a
- picture according to a given set or parameters. CompDecompressor is used
- by PictureCompressor..
-*/
-class CompDecompressor
-{
-public:
- //! Constructor
- /*!
- Create and initialize a component decompressor with the given
- characteristics.
- \param decp decoding parameters
- \param fp picture parameters
- */
- CompDecompressor(DecoderParams& decp, const PictureParams& fp);
-
//! Decompress a picture component
/*!
- Decompress a PicArray containing a picture component (Y, U, or V).
-
- \param p_component_byteio Bytestream of component data
- \param coeff_data contains the component data to be decompressed
- \param bands the subband metadata
- */
- void Decompress(ComponentByteIO *p_component_byteio,
- CoeffArray& coeff_data,
- SubbandList& bands);
-
-private:
- //! Copy constructor is private and body-less
- /*!
- Copy constructor is private and body-less. This class should not
- be copied.
-
- */
- CompDecompressor(const CompDecompressor& cpy);
-
- //! Assignment = is private and body-less
- /*!
- Assignment = is private and body-less. This class should not be
- assigned.
-
+ This class decompresses one of the three components (Y, U, or V) of a
+ picture according to a given set or parameters. CompDecompressor is used
+ by PictureCompressor..
*/
- CompDecompressor& operator=(const CompDecompressor& rhs);
-
- //! Sets the data of a specific subband node to a given value
- /*!
- Sets the data of a specific subband node to a given value
-
- \param pic_data contains the component data
- \param node subband node
- \param val the value to set
- */
- void SetToVal(CoeffArray& pic_data, const Subband& node, CoeffType val);
-
- //! Set up the code block structures for each subband
- /*!
- Set up the code block structures for each subband
- \param bands the set of all the subbands
- */
- void SetupCodeBlocks(SubbandList& bands);
-
- //! Copy of the decompression parameters provided to the constructor
- DecoderParams& m_decparams;
-
- //! Reference to the picture parameters provided to the constructor
- const PictureParams& m_pparams;
-
- //! Reference to the picture sort
- const PictureSort& m_psort;
-
-
-};
+ class CompDecompressor
+ {
+ public:
+ //! Constructor
+ /*!
+ Create and initialize a component decompressor with the given
+ characteristics.
+ \param decp decoding parameters
+ \param fp picture parameters
+ */
+ CompDecompressor( DecoderParams& decp, const PictureParams& fp);
+
+ //! Decompress a picture component
+ /*!
+ Decompress a PicArray containing a picture component (Y, U, or V).
+
+ \param p_component_byteio Bytestream of component data
+ \param coeff_data contains the component data to be decompressed
+ \param bands the subband metadata
+ */
+ void Decompress(ComponentByteIO *p_component_byteio,
+ CoeffArray& coeff_data,
+ SubbandList& bands);
+
+ private:
+ //! Copy constructor is private and body-less
+ /*!
+ Copy constructor is private and body-less. This class should not
+ be copied.
+
+ */
+ CompDecompressor(const CompDecompressor& cpy);
+
+ //! Assignment = is private and body-less
+ /*!
+ Assignment = is private and body-less. This class should not be
+ assigned.
+
+ */
+ CompDecompressor& operator=(const CompDecompressor& rhs);
+
+ //! Sets the data of a specific subband node to a given value
+ /*!
+ Sets the data of a specific subband node to a given value
+
+ \param pic_data contains the component data
+ \param node subband node
+ \param val the value to set
+ */
+ void SetToVal(CoeffArray& pic_data,const Subband& node,CoeffType val);
+
+ //! Set up the code block structures for each subband
+ /*!
+ Set up the code block structures for each subband
+ \param bands the set of all the subbands
+ */
+ void SetupCodeBlocks( SubbandList& bands );
+
+ //! Copy of the decompression parameters provided to the constructor
+ DecoderParams& m_decparams;
+
+ //! Reference to the picture parameters provided to the constructor
+ const PictureParams& m_pparams;
+
+ //! Reference to the picture sort
+ const PictureSort& m_psort;
+
+
+ };
} // namespace dirac
diff --git a/src/filters/parser/DiracSplitter/libdirac/libdirac_decoder/decoder_types.h b/src/filters/parser/DiracSplitter/libdirac/libdirac_decoder/decoder_types.h
index 70011df5a..0f04c19be 100644
--- a/src/filters/parser/DiracSplitter/libdirac/libdirac_decoder/decoder_types.h
+++ b/src/filters/parser/DiracSplitter/libdirac/libdirac_decoder/decoder_types.h
@@ -43,17 +43,16 @@
#ifdef __cplusplus
extern "C" {
#endif
- /*
- * Different states the parser is in
- */
- typedef enum {
- STATE_BUFFER, /* need more data input */
- STATE_SEQUENCE, /* start of sequence detected */
- STATE_PICTURE_AVAIL, /* decoded frame available */
- STATE_SEQUENCE_END, /* end of sequence detected */
- STATE_INVALID /* invalid state. Stop further processing */
- }
- DecoderState;
+/*
+* Different states the parser is in
+*/
+typedef enum {
+ STATE_BUFFER, /* need more data input */
+ STATE_SEQUENCE, /* start of sequence detected */
+ STATE_PICTURE_AVAIL, /* decoded frame available */
+ STATE_SEQUENCE_END, /* end of sequence detected */
+ STATE_INVALID /* invalid state. Stop further processing */
+ } DecoderState;
#ifdef __cplusplus
}
diff --git a/src/filters/parser/DiracSplitter/libdirac/libdirac_decoder/dirac_cppparser.cpp b/src/filters/parser/DiracSplitter/libdirac/libdirac_decoder/dirac_cppparser.cpp
index 1cb61ea0a..3940b35fe 100644
--- a/src/filters/parser/DiracSplitter/libdirac/libdirac_decoder/dirac_cppparser.cpp
+++ b/src/filters/parser/DiracSplitter/libdirac/libdirac_decoder/dirac_cppparser.cpp
@@ -52,9 +52,9 @@ InputStreamBuffer::InputStreamBuffer()
{
m_chunk_buffer = new char[m_buffer_size];
- setg(m_chunk_buffer, //beginning of read area
- m_chunk_buffer, //read position
- m_chunk_buffer); //end position
+ setg (m_chunk_buffer, //beginning of read area
+ m_chunk_buffer, //read position
+ m_chunk_buffer); //end position
}
std::ios::pos_type InputStreamBuffer::Rewind()
@@ -71,7 +71,7 @@ std::ios::pos_type InputStreamBuffer::Seek(std::ios::pos_type bytes, std::ios::s
{
char *new_pos;
- switch(dir)
+ switch (dir)
{
case std::ios::beg:
new_pos = eback() + bytes;
@@ -83,12 +83,12 @@ std::ios::pos_type InputStreamBuffer::Seek(std::ios::pos_type bytes, std::ios::s
new_pos = gptr() + bytes;
break;
}
- if(new_pos > egptr() || new_pos < eback())
+ if (new_pos > egptr() || new_pos < eback())
return -1;
setg(eback(), //start of read
- new_pos, //current read position
- egptr()); //end of stream positon
+ new_pos, //current read position
+ egptr()); //end of stream positon
return 0;
}
@@ -96,44 +96,44 @@ std::ios::pos_type InputStreamBuffer::Seek(std::ios::pos_type bytes, std::ios::s
void InputStreamBuffer::Copy(char *start, int bytes)
{
//std::cerr << "eback=" << m_chunk_buffer - eback()
- // << "gptr=" << gptr() -m_chunk_buffer
- // << "egptr=" << egptr() - m_chunk_buffer << endl;
+ // << "gptr=" << gptr() -m_chunk_buffer
+ // << "egptr=" << egptr() - m_chunk_buffer << endl;
int bytes_left = m_buffer_size - (egptr() - m_chunk_buffer);
- if(bytes_left < bytes)
+ if (bytes_left < bytes)
{
char *temp = new char [m_buffer_size + bytes];
- memcpy(temp, m_chunk_buffer, m_buffer_size);
- setg(temp, temp + (gptr() - m_chunk_buffer), temp + (egptr() - m_chunk_buffer));
+ memcpy (temp, m_chunk_buffer, m_buffer_size);
+ setg (temp, temp+(gptr()-m_chunk_buffer), temp + (egptr() - m_chunk_buffer));
delete [] m_chunk_buffer;
m_chunk_buffer = temp;
}
//std::cerr << "eback=" << m_chunk_buffer - eback()
- // << "gptr=" << gptr() -m_chunk_buffer
- // << "egptr=" << egptr() - m_chunk_buffer << endl;
+ // << "gptr=" << gptr() -m_chunk_buffer
+ // << "egptr=" << egptr() - m_chunk_buffer << endl;
- memcpy(egptr(), start, bytes);
- setg(m_chunk_buffer, gptr(), egptr() + bytes);
+ memcpy (egptr(), start, bytes);
+ setg(m_chunk_buffer, gptr(), egptr()+bytes);
//std::cerr << "eback=" << m_chunk_buffer - eback()
- // << "gptr=" << gptr() -m_chunk_buffer
- // << "egptr=" << egptr() - m_chunk_buffer << endl;
+ // << "gptr=" << gptr() -m_chunk_buffer
+ // << "egptr=" << egptr() - m_chunk_buffer << endl;
}
void InputStreamBuffer::PurgeProcessedData()
{
//std::cerr << "eback=" << m_chunk_buffer - eback()
- // << "gptr=" << gptr() -m_chunk_buffer
- // << "egptr=" << egptr() - m_chunk_buffer << endl;
+ // << "gptr=" << gptr() -m_chunk_buffer
+ // << "egptr=" << egptr() - m_chunk_buffer << endl;
- if(gptr() != m_chunk_buffer)
+ if (gptr() != m_chunk_buffer)
{
- memmove(m_chunk_buffer, gptr(), egptr() - gptr());
- setg(m_chunk_buffer, m_chunk_buffer, m_chunk_buffer + (egptr() - gptr()));
+ memmove (m_chunk_buffer, gptr(), egptr() - gptr());
+ setg(m_chunk_buffer, m_chunk_buffer, m_chunk_buffer+(egptr() - gptr()));
}
//std::cerr << "eback=" << m_chunk_buffer - eback()
- // << "gptr=" << gptr() -m_chunk_buffer
- // << "egptr=" << egptr() - m_chunk_buffer << endl;
+ // << "gptr=" << gptr() -m_chunk_buffer
+ // << "egptr=" << egptr() - m_chunk_buffer << endl;
}
InputStreamBuffer::~InputStreamBuffer()
@@ -159,23 +159,23 @@ DiracParser::~DiracParser()
delete m_decomp;
}
-void DiracParser::SetBuffer(char *start, char *end)
+void DiracParser::SetBuffer (char *start, char *end)
{
- TEST(end > start);
- m_dirac_byte_stream.AddBytes(start, end - start);
+ TEST (end > start);
+ m_dirac_byte_stream.AddBytes(start, end-start);
}
DecoderState DiracParser::Parse()
{
while(true)
{
- ParseUnitByteIO *p_parse_unit = NULL;
- ParseUnitType pu_type = PU_UNDEFINED;
+ ParseUnitByteIO *p_parse_unit=NULL;
+ ParseUnitType pu_type=PU_UNDEFINED;
// look for end-of-sequence flag
- if(m_next_state == STATE_SEQUENCE_END)
+ if(m_next_state==STATE_SEQUENCE_END)
{
- if(!m_decomp)
+ if (!m_decomp)
return STATE_BUFFER;
// look to see if all pictures have been processed
@@ -183,7 +183,7 @@ DecoderState DiracParser::Parse()
{
// if so....delete
delete m_decomp;
- m_decomp = NULL;
+ m_decomp=NULL;
m_next_state = STATE_BUFFER;
return STATE_SEQUENCE_END;
}
@@ -193,12 +193,12 @@ DecoderState DiracParser::Parse()
}
// get next parse unit from stream
- if(m_next_state != STATE_SEQUENCE_END)
+ if(m_next_state!=STATE_SEQUENCE_END)
{
- p_parse_unit = m_dirac_byte_stream.GetNextParseUnit();
- if(p_parse_unit == NULL)
+ p_parse_unit=m_dirac_byte_stream.GetNextParseUnit();
+ if(p_parse_unit==NULL)
return STATE_BUFFER;
- pu_type = p_parse_unit->GetType();
+ pu_type=p_parse_unit->GetType();
}
switch(pu_type)
@@ -207,8 +207,8 @@ DecoderState DiracParser::Parse()
if(!m_decomp)
{
- m_decomp = new SequenceDecompressor(*p_parse_unit, m_verbose);
- m_next_state = STATE_BUFFER;
+ m_decomp = new SequenceDecompressor (*p_parse_unit, m_verbose);
+ m_next_state=STATE_BUFFER;
return STATE_SEQUENCE;
}
@@ -216,41 +216,41 @@ DecoderState DiracParser::Parse()
break;
case PU_CORE_PICTURE:
- {
- if(!m_decomp)
- continue;
-
- const Picture *my_picture = m_decomp->DecompressNextPicture(p_parse_unit);
- if(my_picture)
{
- int picturenum_decoded = my_picture->GetPparams().PictureNum();
- if(picturenum_decoded != m_show_pnum)
+ if (!m_decomp)
+ continue;
+
+ const Picture *my_picture = m_decomp->DecompressNextPicture(p_parse_unit);
+ if (my_picture)
{
- m_show_pnum = my_picture->GetPparams().PictureNum();
- if(m_verbose)
+ int picturenum_decoded = my_picture->GetPparams().PictureNum();
+ if (picturenum_decoded != m_show_pnum)
{
- std::cout << std::endl;
- std::cout << "Picture ";
- std::cout << m_show_pnum << " available";
+ m_show_pnum = my_picture->GetPparams().PictureNum();
+ if (m_verbose)
+ {
+ std::cout << std::endl;
+ std::cout << "Picture ";
+ std::cout<< m_show_pnum << " available";
+ }
+ m_state = STATE_PICTURE_AVAIL;
+ return m_state;
}
- m_state = STATE_PICTURE_AVAIL;
- return m_state;
}
- }
break;
- }
+ }
case PU_END_OF_SEQUENCE:
m_next_state = STATE_SEQUENCE_END;
break;
case PU_AUXILIARY_DATA:
case PU_PADDING_DATA:
- if(m_verbose)
+ if (m_verbose)
std::cerr << "Ignoring Auxiliary/Padding data" << std::endl;
// Ignore auxiliary and padding data and continue parsing
break;
case PU_LOW_DELAY_PICTURE:
- if(m_verbose)
+ if (m_verbose)
std::cerr << "Low delay picture decoding not yet supported" << std::endl;
return STATE_INVALID;
diff --git a/src/filters/parser/DiracSplitter/libdirac/libdirac_decoder/dirac_cppparser.h b/src/filters/parser/DiracSplitter/libdirac/libdirac_decoder/dirac_cppparser.h
index 4306117ea..1634dd390 100644
--- a/src/filters/parser/DiracSplitter/libdirac/libdirac_decoder/dirac_cppparser.h
+++ b/src/filters/parser/DiracSplitter/libdirac/libdirac_decoder/dirac_cppparser.h
@@ -49,141 +49,141 @@
namespace dirac
{
-class SequenceDecompressor;
-class Picture;
+ class SequenceDecompressor;
+ class Picture;
-//! Input Stream Buffer Class.
-class InputStreamBuffer : public std::streambuf
-{
-public:
- //! Constructor
- InputStreamBuffer();
+ //! Input Stream Buffer Class.
+ class InputStreamBuffer : public std::streambuf
+ {
+ public:
+ //! Constructor
+ InputStreamBuffer ();
- //! Destructor
- ~InputStreamBuffer();
+ //! Destructor
+ ~InputStreamBuffer();
- //! Rewind buffer to start of data
- std::ios::pos_type Rewind();
+ //! Rewind buffer to start of data
+ std::ios::pos_type Rewind();
- //! Seek to position specified by bytes offset from pos
- /*!
- Seek takes
- \param bytes offset in bytes
- \param pos the position from which the offset is applied
- */
- std::ios::pos_type Seek(std::ios::pos_type bytes,
- std::ios::seekdir pos = std::ios::cur);
+ //! Seek to position specified by bytes offset from pos
+ /*!
+ Seek takes
+ \param bytes offset in bytes
+ \param pos the position from which the offset is applied
+ */
+ std::ios::pos_type Seek(std::ios::pos_type bytes,
+ std::ios::seekdir pos = std::ios::cur);
- //! Return the current read position in the buffer
- std::ios::pos_type Tell();
+ //! Return the current read position in the buffer
+ std::ios::pos_type Tell();
- //! Copy data into buffer
- /*!
- Copy take
- \param start memory area start
- \param bytes number of bytes to copy starting from start
- */
- void Copy(char *start, int bytes);
-
- //! Delete all processed data from buffer
- void PurgeProcessedData();
-
-private:
-
- //! Private body-less copy constructor
- InputStreamBuffer(const InputStreamBuffer& inbuf);
-
- //! Private body-less assignment operator
- InputStreamBuffer& operator = (const InputStreamBuffer& inbuf);
-
- //! Buffer size
- static const int m_buffer_size = 1232896;
-
- //! Buffere
- char *m_chunk_buffer;
-};
-
-//! Dirac Stream Parser Class
-/*!
- This class is a wrapper around the SequenceDecompressor class. The
- Sequence Decompressor class needs a full picture of data to be available
- to decompress a picture successfully. So, the DiracParser class uses
- the InputStreamBuffer class to store data until a chunk is available
- to be processed and then invokes the SequenceDecompressor functions to
- process data. A chunk of data can be a start of sequence, a picture or
- end of sequence data. The istream used to instantiate the
- SequenceDecompressor object is created using an InputStreamBuffer
- object which is manipulated the DiracParser. This ensures that data is
- always available for processing by the SequenceDecompressor object.
-*/
-class DiracParser
-{
-public:
- //! Constructor
- /*!
- Constructor takes
- \param verbose boolean flag. Set to true for verbose output
- */
- DiracParser(bool verbose = false);
+ //! Copy data into buffer
+ /*!
+ Copy take
+ \param start memory area start
+ \param bytes number of bytes to copy starting from start
+ */
+ void Copy(char *start, int bytes);
- //! Destructor
- ~DiracParser();
+ //! Delete all processed data from buffer
+ void PurgeProcessedData();
- //! Adds bytes to encoder
- /*! SetBuffer takes
- \param start Start of input buffer
- \param end End of input buffer
- */
- void SetBuffer(char *start, char *end);
+ private:
+
+ //! Private body-less copy constructor
+ InputStreamBuffer (const InputStreamBuffer& inbuf);
+
+ //! Private body-less assignment operator
+ InputStreamBuffer& operator = (const InputStreamBuffer& inbuf);
+
+ //! Buffer size
+ static const int m_buffer_size = 1232896;
+
+ //! Buffere
+ char *m_chunk_buffer;
+ };
- //! Parse the data in internal buffer
+ //! Dirac Stream Parser Class
/*!
- Parses the data in the input buffer. This function returns one
- of the following values
- \n STATE_BUFFER : Not enough data in internal buffer to process
- \n STATE_SEQUENCE : Start of sequence detected
- \n STATE_PICTURE_AVAIL : Decoded picture available
- \n STATE_SEQUENCE_END : End of sequence detected
- \n STATE_INVALID : Invalid stream. Stop further processing
+ This class is a wrapper around the SequenceDecompressor class. The
+ Sequence Decompressor class needs a full picture of data to be available
+ to decompress a picture successfully. So, the DiracParser class uses
+ the InputStreamBuffer class to store data until a chunk is available
+ to be processed and then invokes the SequenceDecompressor functions to
+ process data. A chunk of data can be a start of sequence, a picture or
+ end of sequence data. The istream used to instantiate the
+ SequenceDecompressor object is created using an InputStreamBuffer
+ object which is manipulated the DiracParser. This ensures that data is
+ always available for processing by the SequenceDecompressor object.
*/
- DecoderState Parse();
-
- //! Return the parse parameters of the current sequence
- const ParseParams& GetParseParams() const;
-
- //! Return the source parameters of the current sequence
- const SourceParams& GetSourceParams() const;
-
- //! Return the picture parameters of the next picture to be decoded
- const PictureParams* GetNextPictureParams() const;
-
- //! Return the decoded picture
- const Picture* GetNextPicture() const;
-
- //! Return the coding parameters of the current sequence
- const DecoderParams& GetDecoderParams() const;
-
-private:
-
-private:
-
- //! private body-less copy constructor
- DiracParser(const DiracParser &dp);
- //! private body-less assignement constructor
- DiracParser& operator = (const DiracParser &dp);
- //! Current state of parser
- DecoderState m_state;
- //! Next state the parser will enter
- DecoderState m_next_state;
- //! picture number of last picture decoded in display order
- int m_show_pnum;
- //! Sequence decompressor object
- SequenceDecompressor *m_decomp;
- //! verbose flag
- bool m_verbose;
- //! Byte Stream Buffer
- DiracByteStream m_dirac_byte_stream;
-};
+ class DiracParser
+ {
+ public:
+ //! Constructor
+ /*!
+ Constructor takes
+ \param verbose boolean flag. Set to true for verbose output
+ */
+ DiracParser(bool verbose = false );
+
+ //! Destructor
+ ~DiracParser();
+
+ //! Adds bytes to encoder
+ /*! SetBuffer takes
+ \param start Start of input buffer
+ \param end End of input buffer
+ */
+ void SetBuffer (char *start, char *end);
+
+ //! Parse the data in internal buffer
+ /*!
+ Parses the data in the input buffer. This function returns one
+ of the following values
+ \n STATE_BUFFER : Not enough data in internal buffer to process
+ \n STATE_SEQUENCE : Start of sequence detected
+ \n STATE_PICTURE_AVAIL : Decoded picture available
+ \n STATE_SEQUENCE_END : End of sequence detected
+ \n STATE_INVALID : Invalid stream. Stop further processing
+ */
+ DecoderState Parse();
+
+ //! Return the parse parameters of the current sequence
+ const ParseParams& GetParseParams() const;
+
+ //! Return the source parameters of the current sequence
+ const SourceParams& GetSourceParams() const;
+
+ //! Return the picture parameters of the next picture to be decoded
+ const PictureParams* GetNextPictureParams() const;
+
+ //! Return the decoded picture
+ const Picture* GetNextPicture() const;
+
+ //! Return the coding parameters of the current sequence
+ const DecoderParams& GetDecoderParams() const;
+
+ private:
+
+ private:
+
+ //! private body-less copy constructor
+ DiracParser (const DiracParser &dp);
+ //! private body-less assignement constructor
+ DiracParser& operator = (const DiracParser &dp);
+ //! Current state of parser
+ DecoderState m_state;
+ //! Next state the parser will enter
+ DecoderState m_next_state;
+ //! picture number of last picture decoded in display order
+ int m_show_pnum;
+ //! Sequence decompressor object
+ SequenceDecompressor *m_decomp;
+ //! verbose flag
+ bool m_verbose;
+ //! Byte Stream Buffer
+ DiracByteStream m_dirac_byte_stream;
+ };
} // namespace dirac
diff --git a/src/filters/parser/DiracSplitter/libdirac/libdirac_decoder/dirac_parser.cpp b/src/filters/parser/DiracSplitter/libdirac/libdirac_decoder/dirac_parser.cpp
index eaeb6ab8d..629746634 100644
--- a/src/filters/parser/DiracSplitter/libdirac/libdirac_decoder/dirac_parser.cpp
+++ b/src/filters/parser/DiracSplitter/libdirac/libdirac_decoder/dirac_parser.cpp
@@ -52,357 +52,357 @@ using namespace dirac;
extern "C" {
#endif
- extern DllExport dirac_decoder_t *dirac_decoder_init(int verbose)
- {
- dirac_decoder_t* decoder = new dirac_decoder_t;
- memset(decoder, 0, sizeof(dirac_decoder_t));
+extern DllExport dirac_decoder_t *dirac_decoder_init(int verbose)
+{
+ dirac_decoder_t* decoder = new dirac_decoder_t;
+ memset (decoder, 0, sizeof(dirac_decoder_t));
+
+ bool verbosity = verbose > 0 ? true : false;
+ DiracParser *parser = new DiracParser(verbosity);
+ decoder->parser = static_cast<void *>(parser);
+
+ decoder->fbuf = new dirac_framebuf_t;
+ decoder->fbuf->id = NULL;
+ decoder->fbuf->buf[0] = decoder->fbuf->buf[1] = decoder->fbuf->buf[2] = NULL;
+ return decoder;
+}
- bool verbosity = verbose > 0 ? true : false;
- DiracParser *parser = new DiracParser(verbosity);
- decoder->parser = static_cast<void *>(parser);
+extern DllExport void dirac_decoder_close(dirac_decoder_t *decoder)
+{
+ TEST (decoder != NULL);
+ TEST (decoder->parser != NULL);
+ DiracParser *parser = static_cast<DiracParser *>(decoder->parser);
- decoder->fbuf = new dirac_framebuf_t;
- decoder->fbuf->id = NULL;
- decoder->fbuf->buf[0] = decoder->fbuf->buf[1] = decoder->fbuf->buf[2] = NULL;
- return decoder;
- }
-
- extern DllExport void dirac_decoder_close(dirac_decoder_t *decoder)
- {
- TEST(decoder != NULL);
- TEST(decoder->parser != NULL);
- DiracParser *parser = static_cast<DiracParser *>(decoder->parser);
+ delete parser;
- delete parser;
+ delete decoder->fbuf;
- delete decoder->fbuf;
+ delete decoder;
- delete decoder;
-
- decoder = NULL;
- }
+ decoder = NULL;
+}
- extern DllExport void dirac_buffer(dirac_decoder_t *decoder, unsigned char *start, unsigned char *end)
- {
- TEST(decoder != NULL);
- TEST(decoder->parser != NULL);
- DiracParser *parser = static_cast<DiracParser *>(decoder->parser);
+extern DllExport void dirac_buffer (dirac_decoder_t *decoder, unsigned char *start, unsigned char *end)
+{
+ TEST (decoder != NULL);
+ TEST (decoder->parser != NULL);
+ DiracParser *parser = static_cast<DiracParser *>(decoder->parser);
- parser->SetBuffer((char *)start, (char *)end);
- }
+ parser->SetBuffer((char *)start, (char *)end);
+}
- static void set_sequence_params(const DiracParser * const parser, dirac_decoder_t *decoder)
+static void set_sequence_params (const DiracParser * const parser, dirac_decoder_t *decoder)
+{
+ TEST (parser != NULL);
+ TEST (decoder != NULL);
+
+ dirac_sourceparams_t *src_params = &decoder->src_params;
+ dirac_parseparams_t *parse_params = &decoder->parse_params;
+ const SourceParams& srcparams = parser->GetSourceParams();
+ const ParseParams& pparams = parser->GetParseParams();
+
+ parse_params->major_ver = pparams.MajorVersion();
+ parse_params->minor_ver = pparams.MinorVersion();
+ parse_params->profile = pparams.Profile();
+ parse_params->level = pparams.Level();
+
+ src_params->width = srcparams.Xl();
+ src_params->height = srcparams.Yl();
+
+ src_params->chroma = (dirac_chroma_t)srcparams.CFormat();
+ src_params->chroma_width = srcparams.ChromaWidth();
+ src_params->chroma_height = srcparams.ChromaHeight();
+
+ // set the source parmeters
+ src_params->source_sampling = srcparams.SourceSampling();
+ src_params->topfieldfirst = srcparams.TopFieldFirst() ? 1 : 0;
+
+ src_params->frame_rate.numerator = srcparams.FrameRate().m_num;
+ src_params->frame_rate.denominator = srcparams.FrameRate().m_denom;
+
+ src_params->pix_asr.numerator = srcparams.PixelAspectRatio().m_num;
+ src_params->pix_asr.denominator = srcparams.PixelAspectRatio().m_denom;
+
+ // clean area
+ src_params->clean_area.width = srcparams.CleanWidth();
+ src_params->clean_area.height = srcparams.CleanHeight();
+ src_params->clean_area.left_offset = srcparams.LeftOffset();
+ src_params->clean_area.top_offset = srcparams.TopOffset();
+
+ // signal range
+ src_params->signal_range.luma_offset = srcparams.LumaOffset();
+ src_params->signal_range.luma_excursion = srcparams.LumaExcursion();
+ src_params->signal_range.chroma_offset = srcparams.ChromaOffset();
+ src_params->signal_range.chroma_excursion = srcparams.ChromaExcursion();
+
+ // Colour specfication
+ src_params->colour_spec.col_primary = srcparams.ColourPrimariesIndex();
+ src_params->colour_spec.trans_func = srcparams.TransferFunctionIndex();
+ switch(srcparams.ColourMatrixIndex())
{
- TEST(parser != NULL);
- TEST(decoder != NULL);
-
- dirac_sourceparams_t *src_params = &decoder->src_params;
- dirac_parseparams_t *parse_params = &decoder->parse_params;
- const SourceParams& srcparams = parser->GetSourceParams();
- const ParseParams& pparams = parser->GetParseParams();
-
- parse_params->major_ver = pparams.MajorVersion();
- parse_params->minor_ver = pparams.MinorVersion();
- parse_params->profile = pparams.Profile();
- parse_params->level = pparams.Level();
-
- src_params->width = srcparams.Xl();
- src_params->height = srcparams.Yl();
-
- src_params->chroma = (dirac_chroma_t)srcparams.CFormat();
- src_params->chroma_width = srcparams.ChromaWidth();
- src_params->chroma_height = srcparams.ChromaHeight();
-
- // set the source parmeters
- src_params->source_sampling = srcparams.SourceSampling();
- src_params->topfieldfirst = srcparams.TopFieldFirst() ? 1 : 0;
-
- src_params->frame_rate.numerator = srcparams.FrameRate().m_num;
- src_params->frame_rate.denominator = srcparams.FrameRate().m_denom;
-
- src_params->pix_asr.numerator = srcparams.PixelAspectRatio().m_num;
- src_params->pix_asr.denominator = srcparams.PixelAspectRatio().m_denom;
-
- // clean area
- src_params->clean_area.width = srcparams.CleanWidth();
- src_params->clean_area.height = srcparams.CleanHeight();
- src_params->clean_area.left_offset = srcparams.LeftOffset();
- src_params->clean_area.top_offset = srcparams.TopOffset();
-
- // signal range
- src_params->signal_range.luma_offset = srcparams.LumaOffset();
- src_params->signal_range.luma_excursion = srcparams.LumaExcursion();
- src_params->signal_range.chroma_offset = srcparams.ChromaOffset();
- src_params->signal_range.chroma_excursion = srcparams.ChromaExcursion();
-
- // Colour specfication
- src_params->colour_spec.col_primary = srcparams.ColourPrimariesIndex();
- src_params->colour_spec.trans_func = srcparams.TransferFunctionIndex();
- switch(srcparams.ColourMatrixIndex())
- {
- case CM_SDTV:
- src_params->colour_spec.col_matrix.kr = 0.299f;
- src_params->colour_spec.col_matrix.kb = 0.114f;
- break;
- case CM_REVERSIBLE:
- src_params->colour_spec.col_matrix.kr = 0.25f;
- src_params->colour_spec.col_matrix.kb = 0.25f;
- break;
- case CM_HDTV_COMP_INTERNET:
- default:
- src_params->colour_spec.col_matrix.kr = 0.2126f;
- src_params->colour_spec.col_matrix.kb = 0.0722f;
- break;
- }
+ case CM_SDTV:
+ src_params->colour_spec.col_matrix.kr = 0.299f;
+ src_params->colour_spec.col_matrix.kb = 0.114f;
+ break;
+ case CM_REVERSIBLE:
+ src_params->colour_spec.col_matrix.kr = 0.25f;
+ src_params->colour_spec.col_matrix.kb = 0.25f;
+ break;
+ case CM_HDTV_COMP_INTERNET:
+ default:
+ src_params->colour_spec.col_matrix.kr = 0.2126f;
+ src_params->colour_spec.col_matrix.kb = 0.0722f;
+ break;
}
+}
- static void set_frame_component(const PicArray& pic_data, const CompSort cs, dirac_decoder_t *decoder)
- {
- TEST(decoder->fbuf != NULL);
- int xl, yl;
+static void set_frame_component (const PicArray& pic_data, const CompSort cs, dirac_decoder_t *decoder)
+{
+ TEST (decoder->fbuf != NULL);
+ int xl, yl;
- unsigned char *buf;
+ unsigned char *buf;
- switch(cs)
- {
- case U_COMP:
- xl = decoder->src_params.chroma_width;
- yl = decoder->src_params.chroma_height;
- buf = decoder->fbuf->buf[1];
- break;
- case V_COMP:
- xl = decoder->src_params.chroma_width;
- yl = decoder->src_params.chroma_height;
- buf = decoder->fbuf->buf[2];
- break;
-
- case Y_COMP:
- default:
- xl = decoder->src_params.width;
- yl = decoder->src_params.height;
- buf = decoder->fbuf->buf[0];
- break;
- }
+ switch (cs)
+ {
+ case U_COMP:
+ xl = decoder->src_params.chroma_width;
+ yl = decoder->src_params.chroma_height;
+ buf = decoder->fbuf->buf[1];
+ break;
+ case V_COMP:
+ xl = decoder->src_params.chroma_width;
+ yl = decoder->src_params.chroma_height;
+ buf = decoder->fbuf->buf[2];
+ break;
+
+ case Y_COMP:
+ default:
+ xl = decoder->src_params.width;
+ yl = decoder->src_params.height;
+ buf = decoder->fbuf->buf[0];
+ break;
+ }
- TEST(buf != NULL);
+ TEST (buf != NULL);
#if defined HAVE_MMX
- int last_idx = (xl >> 3) << 3;
- __m64 tmp = _mm_set_pi16(128, 128, 128, 128);
- for(int j = 0 ; j < yl ; ++j)
+ int last_idx = (xl>>3)<<3;
+ __m64 tmp = _mm_set_pi16(128, 128, 128, 128);
+ for (int j=0 ; j<yl ;++j)
+ {
+ for (int i=0 ; i<last_idx ; i+=8 )
{
- for(int i = 0 ; i < last_idx ; i += 8)
- {
- __m64 pic1 = *(__m64 *)&pic_data[j][i];
- pic1 = _mm_add_pi16(pic1, tmp);
- __m64 pic2 = *(__m64 *)(&pic_data[j][i+4]);
- pic2 = _mm_add_pi16(pic2, tmp);
- __m64 *tmp = (__m64 *)&buf[j*xl+i];
- *tmp = _mm_packs_pu16(pic1, pic2);
- }//i
- }//j
- _mm_empty();
-
- // mop up remaining pixels
- for(int j = 0 ; j < yl ; ++j)
+ __m64 pic1 = *(__m64 *)&pic_data[j][i];
+ pic1 = _mm_add_pi16 (pic1, tmp);
+ __m64 pic2 = *(__m64 *)(&pic_data[j][i+4]);
+ pic2 = _mm_add_pi16 (pic2, tmp);
+ __m64 *tmp = (__m64 *)&buf[j*xl+i];
+ *tmp = _mm_packs_pu16 (pic1, pic2);
+ }//i
+ }//j
+ _mm_empty();
+
+ // mop up remaining pixels
+ for (int j=0 ; j<yl ;++j)
+ {
+ for (int i=last_idx ; i<xl ; i++ )
{
- for(int i = last_idx ; i < xl ; i++)
- {
- buf[j*xl+i] = (unsigned char)(pic_data[j][i] + 128);
- }//i
- }//j
- return;
+ buf[j*xl+i]=(unsigned char) (pic_data[j][i]+128);
+ }//i
+ }//j
+ return;
#else
- for(int j = 0 ; j < yl ; ++j)
+ for (int j=0 ; j<yl ;++j)
+ {
+ for (int i=0 ; i<xl ; ++i)
{
- for(int i = 0 ; i < xl ; ++i)
- {
- buf[j*xl+i] = (unsigned char)(pic_data[j][i] + 128);
- }//i
- }//j
+ buf[j*xl+i]=(unsigned char) (pic_data[j][i]+128);
+ }//i
+ }//j
#endif
- }
+}
- static void set_field_component(const PicArray& pic_data, const CompSort cs, dirac_decoder_t *decoder, unsigned int pic_num)
- {
- TEST(decoder->fbuf != NULL);
- int xl, yl;
+static void set_field_component (const PicArray& pic_data, const CompSort cs, dirac_decoder_t *decoder, unsigned int pic_num)
+{
+ TEST (decoder->fbuf != NULL);
+ int xl, yl;
- unsigned char *buf;
+ unsigned char *buf;
- switch(cs)
- {
- case U_COMP:
- xl = decoder->src_params.chroma_width;
- yl = decoder->src_params.chroma_height;
- buf = decoder->fbuf->buf[1];
- break;
- case V_COMP:
- xl = decoder->src_params.chroma_width;
- yl = decoder->src_params.chroma_height;
- buf = decoder->fbuf->buf[2];
- break;
-
- case Y_COMP:
- default:
- xl = decoder->src_params.width;
- yl = decoder->src_params.height;
- buf = decoder->fbuf->buf[0];
- break;
- }
+ switch (cs)
+ {
+ case U_COMP:
+ xl = decoder->src_params.chroma_width;
+ yl = decoder->src_params.chroma_height;
+ buf = decoder->fbuf->buf[1];
+ break;
+ case V_COMP:
+ xl = decoder->src_params.chroma_width;
+ yl = decoder->src_params.chroma_height;
+ buf = decoder->fbuf->buf[2];
+ break;
+
+ case Y_COMP:
+ default:
+ xl = decoder->src_params.width;
+ yl = decoder->src_params.height;
+ buf = decoder->fbuf->buf[0];
+ break;
+ }
- TEST(buf != NULL);
+ TEST (buf != NULL);
- // Seek offset before writing field to store
- int start = 0;
- // Seek offset between writing fields to store
- int skip = 0;
+ // Seek offset before writing field to store
+ int start = 0;
+ // Seek offset between writing fields to store
+ int skip = 0;
- bool top_field = decoder->src_params.topfieldfirst ? (!(pic_num % 2)) :
- (pic_num % 2);
+ bool top_field = decoder->src_params.topfieldfirst ? (!(pic_num%2)) :
+ (pic_num%2);
- if(top_field) // i.e. top field
- {
- start = 0;
- skip = 2 * xl * sizeof(char);
- }
- else // else bottom field
- {
- start = xl;
- skip = 2 * xl * sizeof(char);
- }
+ if (top_field) // i.e. top field
+ {
+ start = 0;
+ skip = 2 * xl * sizeof(char);
+ }
+ else // else bottom field
+ {
+ start = xl;
+ skip = 2 * xl * sizeof(char);
+ }
- unsigned char *tempc = buf + start;
+ unsigned char *tempc = buf + start;
- int field_yl = yl >> 1;
- int field_xl = xl;
+ int field_yl = yl>>1;
+ int field_xl = xl;
- for(int j = 0 ; j < field_yl ; ++j)
+ for (int j=0 ; j<field_yl ;++j)
+ {
+ for (int i=0 ; i<field_xl ; ++i)
{
- for(int i = 0 ; i < field_xl ; ++i)
- {
- tempc[i] = (unsigned char)(pic_data[j][i] + 128);
- }//I
- tempc += skip;
- }
+ tempc[i] = (unsigned char) (pic_data[j][i]+128);
+ }//I
+ tempc += skip;
}
+}
- static void set_frame_data(const DiracParser * const parser, dirac_decoder_t *decoder)
- {
- TEST(parser != NULL);
- TEST(decoder != NULL);
- TEST(decoder->fbuf != NULL);
- TEST(decoder->state == STATE_PICTURE_AVAIL);
+static void set_frame_data (const DiracParser * const parser, dirac_decoder_t *decoder)
+{
+ TEST (parser != NULL);
+ TEST (decoder != NULL);
+ TEST (decoder->fbuf != NULL);
+ TEST (decoder->state == STATE_PICTURE_AVAIL);
- const Picture* my_picture = parser->GetNextPicture();
+ const Picture* my_picture = parser->GetNextPicture();
- if(my_picture)
- {
- int pic_num = my_picture->GetPparams().PictureNum();
+ if (my_picture)
+ {
+ int pic_num = my_picture->GetPparams().PictureNum();
- if(!parser->GetDecoderParams().FieldCoding())
- {
- set_frame_component(my_picture->Data(Y_COMP), Y_COMP, decoder);
- set_frame_component(my_picture->Data(U_COMP), U_COMP, decoder);
- set_frame_component(my_picture->Data(V_COMP), V_COMP, decoder);
- }
- else
- {
- set_field_component(my_picture->Data(Y_COMP), Y_COMP, decoder, pic_num);
- set_field_component(my_picture->Data(U_COMP), U_COMP, decoder, pic_num);
- set_field_component(my_picture->Data(V_COMP), V_COMP, decoder, pic_num);
- }
+ if (!parser->GetDecoderParams().FieldCoding())
+ {
+ set_frame_component (my_picture->Data(Y_COMP), Y_COMP, decoder);
+ set_frame_component (my_picture->Data(U_COMP), U_COMP, decoder);
+ set_frame_component (my_picture->Data(V_COMP), V_COMP, decoder);
+ }
+ else
+ {
+ set_field_component (my_picture->Data(Y_COMP), Y_COMP, decoder, pic_num);
+ set_field_component (my_picture->Data(U_COMP), U_COMP, decoder, pic_num);
+ set_field_component (my_picture->Data(V_COMP), V_COMP, decoder, pic_num);
}
- return;
}
+ return;
+}
- extern DllExport dirac_decoder_state_t dirac_parse(dirac_decoder_t *decoder)
- {
- TEST(decoder != NULL);
- TEST(decoder->parser != NULL);
- DiracParser *parser = static_cast<DiracParser *>(decoder->parser);
+extern DllExport dirac_decoder_state_t dirac_parse (dirac_decoder_t *decoder)
+{
+ TEST (decoder != NULL);
+ TEST (decoder->parser != NULL);
+ DiracParser *parser = static_cast<DiracParser *>(decoder->parser);
- unsigned int pic_num;
+ unsigned int pic_num;
- while(true)
+ while(true)
+ {
+ try
{
- try
- {
- decoder->state = parser->Parse();
+ decoder->state = parser->Parse();
- switch(decoder->state)
- {
- case STATE_BUFFER:
- return decoder->state;
- break;
+ switch (decoder->state)
+ {
+ case STATE_BUFFER:
+ return decoder->state;
+ break;
- case STATE_SEQUENCE:
- set_sequence_params(parser, decoder);
- decoder->frame_avail = 0;
- return decoder->state;
- break;
+ case STATE_SEQUENCE:
+ set_sequence_params(parser, decoder);
+ decoder->frame_avail = 0;
+ return decoder->state;
+ break;
- case STATE_PICTURE_AVAIL:
+ case STATE_PICTURE_AVAIL:
+ {
+ const Picture *my_picture = parser->GetNextPicture();
+ if (my_picture)
{
- const Picture *my_picture = parser->GetNextPicture();
- if(my_picture)
+ pic_num = parser->GetNextPicture()->GetPparams().PictureNum();
+ decoder->frame_num = pic_num;
+ set_frame_data (parser, decoder);
+
+ /* A full frame is only available if we're doing
+ * progressive coding or have decoded the second field.
+ * Will only return when a full frame is available
+ */
+ if (!parser->GetDecoderParams().FieldCoding() ||
+ pic_num%2)
{
- pic_num = parser->GetNextPicture()->GetPparams().PictureNum();
+ /* Frame number currently available for display */
decoder->frame_num = pic_num;
- set_frame_data(parser, decoder);
-
- /* A full frame is only available if we're doing
- * progressive coding or have decoded the second field.
- * Will only return when a full frame is available
- */
- if(!parser->GetDecoderParams().FieldCoding() ||
- pic_num % 2)
- {
- /* Frame number currently available for display */
- decoder->frame_num = pic_num;
- if(parser->GetDecoderParams().FieldCoding())
- decoder->frame_num = pic_num >> 1;
- decoder->frame_avail = 1;
- return decoder->state;
- }
+ if (parser->GetDecoderParams().FieldCoding())
+ decoder->frame_num = pic_num>>1;
+ decoder->frame_avail = 1;
+ return decoder->state;
}
- break;
}
+ break;
+ }
- case STATE_INVALID:
- return decoder->state;
- break;
+ case STATE_INVALID:
+ return decoder->state;
+ break;
- case STATE_SEQUENCE_END:
- return decoder->state;
- break;
+ case STATE_SEQUENCE_END:
+ return decoder->state;
+ break;
- default:
- break;
- }
- }//try
- catch(const DiracException& e)
- {
- return STATE_INVALID;
+ default:
+ break;
}
+ }//try
+ catch (const DiracException& e)
+ {
+ return STATE_INVALID;
}
-
- return decoder->state;
}
- extern DllExport void dirac_set_buf(dirac_decoder_t *decoder, unsigned char *buf[3], void *id)
- {
- TEST(decoder != NULL);
- TEST(decoder->fbuf != NULL);
+ return decoder->state;
+}
- decoder->fbuf->buf[0] = buf[0];
- decoder->fbuf->buf[1] = buf[1];
- decoder->fbuf->buf[2] = buf[2];
- decoder->fbuf->id = id;
- }
+extern DllExport void dirac_set_buf (dirac_decoder_t *decoder, unsigned char *buf[3], void *id)
+{
+ TEST (decoder != NULL);
+ TEST (decoder->fbuf != NULL);
+
+ decoder->fbuf->buf[0] = buf[0];
+ decoder->fbuf->buf[1] = buf[1];
+ decoder->fbuf->buf[2] = buf[2];
+ decoder->fbuf->id = id;
+}
#ifdef __cplusplus
}
diff --git a/src/filters/parser/DiracSplitter/libdirac/libdirac_decoder/dirac_parser.h b/src/filters/parser/DiracSplitter/libdirac/libdirac_decoder/dirac_parser.h
index ba3153eee..75bdcc7c2 100644
--- a/src/filters/parser/DiracSplitter/libdirac/libdirac_decoder/dirac_parser.h
+++ b/src/filters/parser/DiracSplitter/libdirac/libdirac_decoder/dirac_parser.h
@@ -44,7 +44,7 @@
/*! \file
\brief C interface to Dirac decoder.
-
+
A set of 'C' functions that define the public interface to the Dirac decoder.
Refer to the the reference decoder source code, decoder/decmain.cpp for
an example of how to use the "C" interface. The pseudocode below gives
@@ -68,9 +68,9 @@
case STATE_SEQUENCE:
handle start of sequence.
- The decoder returns the sequence parameters in the
+ The decoder returns the sequence parameters in the
seq_params member of the decoder handle.
- Allocate space for the frame data buffers and pass
+ Allocate space for the frame data buffers and pass
this to the decoder.
dirac_set_buf (decoder_handle, buf, NULL);
break;
@@ -81,7 +81,7 @@
case STATE_PICTURE_AVAIL:
Handle picture data.
- The decoder sets the fbuf member in the decoder
+ The decoder sets the fbuf member in the decoder
handle to the frame decoded.
break;
@@ -90,7 +90,7 @@
break;
}
} while (data available && decoder state != STATE_INVALID
-
+
Free the decoder resources
dirac_decoder_close(decoder_handle)
\endverbatim
@@ -99,83 +99,83 @@
extern "C" {
#endif
- typedef DecoderState dirac_decoder_state_t;
-
- /*! Structure that holds the information returned by the parser */
- typedef struct
- {
- /*! parser state */
- dirac_decoder_state_t state;
- /*! parse parameters */
- dirac_parseparams_t parse_params;
- /*! source parameters */
- dirac_sourceparams_t src_params;
- /*! frame (NOT picture) number */
- unsigned int frame_num;
- /*! void pointer to internal parser */
- void *parser;
- /*! frame (NOT picture) buffer to hold luma and chroma data */
- dirac_framebuf_t *fbuf;
- /*! boolean flag that indicates if a decoded frame (NOT picture) is available */
- int frame_avail;
- /*! verbose output */
- int verbose;
-
- } dirac_decoder_t;
-
- /*!
- Decoder Init
- Initialise the decoder.
- \param verbose boolean flag to set verbose output
- \return decoder handle
- */
- extern DllExport dirac_decoder_t *dirac_decoder_init(int verbose);
-
- /*!
- Release the decoder resources
- \param decoder Decoder object
- */
- extern DllExport void dirac_decoder_close(dirac_decoder_t *decoder);
-
- /*!
- Parses the data in the input buffer. This function returns the
- following values.
- \n STATE_BUFFER: Not enough data in internal buffer to process
- \n STATE_SEQUENCE: Start of sequence detected. The seq_params member
- in the decoder object is set to the details of the
- next sequence to be processed.
- \n STATE_PICTURE_START: Start of picture detected. The frame_params member
- of the decoder object is set to the details of the
- next frame to be processed.
- \n STATE_PICTURE_AVAIL: Decoded picture available. The frame_aprams member
- of the decoder object is set the the details of
- the decoded frame available. The fbuf member of
- the decoder object has the luma and chroma data of
- the decompressed frame.
- \n STATE_SEQUENCE_END: End of sequence detected.
- \n STATE_INVALID: Invalid stream. Stop further processing.
-
- \param decoder Decoder object
- \return Decoder state
-
- */
- extern DllExport dirac_decoder_state_t dirac_parse(dirac_decoder_t *decoder);
-
- /*!
- Copy data into internal buffer
- \param decoder Decoder object
- \param start Start of data
- \param end End of data
- */
- extern DllExport void dirac_buffer(dirac_decoder_t *decoder, unsigned char *start, unsigned char *end);
-
- /*!
- Set the output buffer into which the decoder copies the decoded data
- \param decoder Decoder object
- \param buf Array of char buffers to hold luma and chroma data
- \param id User data
- */
- extern DllExport void dirac_set_buf(dirac_decoder_t *decoder, unsigned char *buf[3], void *id);
+typedef DecoderState dirac_decoder_state_t;
+
+/*! Structure that holds the information returned by the parser */
+typedef struct
+{
+ /*! parser state */
+ dirac_decoder_state_t state;
+ /*! parse parameters */
+ dirac_parseparams_t parse_params;
+ /*! source parameters */
+ dirac_sourceparams_t src_params;
+ /*! frame (NOT picture) number */
+ unsigned int frame_num;
+ /*! void pointer to internal parser */
+ void *parser;
+ /*! frame (NOT picture) buffer to hold luma and chroma data */
+ dirac_framebuf_t *fbuf;
+ /*! boolean flag that indicates if a decoded frame (NOT picture) is available */
+ int frame_avail;
+ /*! verbose output */
+ int verbose;
+
+} dirac_decoder_t;
+
+/*!
+ Decoder Init
+ Initialise the decoder.
+ \param verbose boolean flag to set verbose output
+ \return decoder handle
+*/
+extern DllExport dirac_decoder_t *dirac_decoder_init(int verbose);
+
+/*!
+ Release the decoder resources
+ \param decoder Decoder object
+*/
+extern DllExport void dirac_decoder_close(dirac_decoder_t *decoder);
+
+/*!
+ Parses the data in the input buffer. This function returns the
+ following values.
+ \n STATE_BUFFER: Not enough data in internal buffer to process
+ \n STATE_SEQUENCE: Start of sequence detected. The seq_params member
+ in the decoder object is set to the details of the
+ next sequence to be processed.
+ \n STATE_PICTURE_START: Start of picture detected. The frame_params member
+ of the decoder object is set to the details of the
+ next frame to be processed.
+ \n STATE_PICTURE_AVAIL: Decoded picture available. The frame_aprams member
+ of the decoder object is set the the details of
+ the decoded frame available. The fbuf member of
+ the decoder object has the luma and chroma data of
+ the decompressed frame.
+ \n STATE_SEQUENCE_END: End of sequence detected.
+ \n STATE_INVALID: Invalid stream. Stop further processing.
+
+ \param decoder Decoder object
+ \return Decoder state
+
+*/
+extern DllExport dirac_decoder_state_t dirac_parse (dirac_decoder_t *decoder);
+
+/*!
+ Copy data into internal buffer
+ \param decoder Decoder object
+ \param start Start of data
+ \param end End of data
+*/
+extern DllExport void dirac_buffer (dirac_decoder_t *decoder, unsigned char *start, unsigned char *end);
+
+/*!
+ Set the output buffer into which the decoder copies the decoded data
+ \param decoder Decoder object
+ \param buf Array of char buffers to hold luma and chroma data
+ \param id User data
+*/
+extern DllExport void dirac_set_buf (dirac_decoder_t *decoder, unsigned char *buf[3], void *id);
#ifdef __cplusplus
}
diff --git a/src/filters/parser/DiracSplitter/libdirac/libdirac_decoder/picture_decompress.cpp b/src/filters/parser/DiracSplitter/libdirac/libdirac_decoder/picture_decompress.cpp
index 27f581a8e..fe413551f 100644
--- a/src/filters/parser/DiracSplitter/libdirac/libdirac_decoder/picture_decompress.cpp
+++ b/src/filters/parser/DiracSplitter/libdirac/libdirac_decoder/picture_decompress.cpp
@@ -59,9 +59,9 @@ using std::vector;
using std::auto_ptr;
PictureDecompressor::PictureDecompressor(DecoderParams& decp, ChromaFormat cf)
- :
- m_decparams(decp),
- m_cformat(cf)
+:
+m_decparams(decp),
+m_cformat(cf)
{
}
@@ -71,167 +71,158 @@ PictureDecompressor::~PictureDecompressor()
bool PictureDecompressor::Decompress(ParseUnitByteIO& parseunit_byteio,
- PictureBuffer& my_buffer)
+ PictureBuffer& my_buffer)
{
// get current byte position
//int start_pos = parseunit_byteio.GetReadBytePosition();
- try
- {
+ try {
- // read picture data
- PictureByteIO picture_byteio(m_pparams,
- parseunit_byteio);
+ // read picture data
+ PictureByteIO picture_byteio(m_pparams,
+ parseunit_byteio);
- picture_byteio.Input();
+ picture_byteio.Input();
- PictureSort fs;
+ PictureSort fs;
- if(m_pparams.GetPictureType() == INTRA_PICTURE)
- fs.SetIntra();
- else
- fs.SetInter();
+ if (m_pparams.GetPictureType() == INTRA_PICTURE)
+ fs.SetIntra();
+ else
+ fs.SetInter();
- if(m_pparams.GetReferenceType() == REFERENCE_PICTURE)
- fs.SetRef();
- else
- fs.SetNonRef();
+ if (m_pparams.GetReferenceType() == REFERENCE_PICTURE)
+ fs.SetRef();
+ else
+ fs.SetNonRef();
- m_pparams.SetPicSort(fs);
+ m_pparams.SetPicSort(fs);
- if(m_pparams.GetReferenceType() == REFERENCE_PICTURE)
- // Now clean the reference pictures from the buffer
- CleanReferencePictures(my_buffer);
+ if (m_pparams.GetReferenceType() == REFERENCE_PICTURE)
+ // Now clean the reference pictures from the buffer
+ CleanReferencePictures( my_buffer );
- // Check if the picture can be decoded
- if(m_pparams.PicSort().IsInter())
- {
- const std::vector<int>& refs = m_pparams.Refs();
+ // Check if the picture can be decoded
+ if (m_pparams.PicSort().IsInter()){
+ const std::vector<int>& refs = m_pparams.Refs();
- for(unsigned int i = 0; i < refs.size(); ++i)
- if(!my_buffer.IsPictureAvail(refs[i]))
- return false;
- }
+ for (unsigned int i = 0; i < refs.size(); ++i)
+ if ( !my_buffer.IsPictureAvail(refs[i]) )
+ return false;
+ }
- // decode the rest of the picture
-
- if(m_decparams.Verbose())
- {
- std::cout << std::endl << "Decoding picture " << m_pparams.PictureNum() << " in display order";
- if(m_pparams.PicSort().IsInter())
- {
- std::cout << std::endl << "References: " << m_pparams.Refs()[0];
- if(m_pparams.Refs().size() > 1)
- std::cout << " and " << m_pparams.Refs()[1];
- }
- }
+ // decode the rest of the picture
- PictureSort psort = m_pparams.PicSort();
- auto_ptr<MvData> mv_data;
+ if ( m_decparams.Verbose() ){
+ std::cout<<std::endl<<"Decoding picture "<<m_pparams.PictureNum()<<" in display order";
+ if ( m_pparams.PicSort().IsInter() ){
+ std::cout<<std::endl<<"References: "<<m_pparams.Refs()[0];
+ if ( m_pparams.Refs().size()>1 )
+ std::cout<<" and "<<m_pparams.Refs()[1];
+ }
+ }
- if(psort.IsInter())
- //do all the MV stuff
- DecompressMVData(mv_data, picture_byteio);
+ PictureSort psort = m_pparams.PicSort();
+ auto_ptr<MvData> mv_data;
- // Read the transform header
- TransformByteIO transform_byteio(picture_byteio, m_pparams, m_decparams);
- transform_byteio.Input();
+ if ( psort.IsInter() )
+ //do all the MV stuff
+ DecompressMVData( mv_data, picture_byteio );
- if(m_pparams.PicSort().IsIntra() && m_decparams.ZeroTransform())
- {
- DIRAC_THROW_EXCEPTION(
- ERR_UNSUPPORTED_STREAM_DATA,
- "Intra pictures cannot have Zero-Residual",
- SEVERITY_PICTURE_ERROR);
- }
+ // Read the transform header
+ TransformByteIO transform_byteio(picture_byteio, m_pparams, m_decparams);
+ transform_byteio.Input();
- // Add a picture to the buffer to decode into
- PushPicture(my_buffer);
+ if (m_pparams.PicSort().IsIntra() && m_decparams.ZeroTransform()){
+ DIRAC_THROW_EXCEPTION(
+ ERR_UNSUPPORTED_STREAM_DATA,
+ "Intra pictures cannot have Zero-Residual",
+ SEVERITY_PICTURE_ERROR);
+ }
- //Reference to the picture being decoded
- Picture& my_picture = my_buffer.GetPicture(m_pparams.PictureNum());
+ // Add a picture to the buffer to decode into
+ PushPicture(my_buffer);
- if(!m_decparams.ZeroTransform())
- {
- //decode components
- Picture& pic = my_buffer.GetPicture(m_pparams.PictureNum());
+ //Reference to the picture being decoded
+ Picture& my_picture = my_buffer.GetPicture(m_pparams.PictureNum());
- CompDecompressor my_compdecoder(m_decparams , pic.GetPparams());
+ if (!m_decparams.ZeroTransform()){
+ //decode components
+ Picture& pic = my_buffer.GetPicture( m_pparams.PictureNum() );
- PicArray* comp_data[3];
- CoeffArray* coeff_data[3];
+ CompDecompressor my_compdecoder( m_decparams , pic.GetPparams() );
- const int depth(m_decparams.TransformDepth());
- WaveletTransform wtransform(depth, m_decparams.TransformFilter());
+ PicArray* comp_data[3];
+ CoeffArray* coeff_data[3];
- pic.InitWltData(depth);
+ const int depth( m_decparams.TransformDepth() );
+ WaveletTransform wtransform( depth, m_decparams.TransformFilter() );
- for(int c = 0; c < 3; ++c)
- {
- ComponentByteIO component_byteio((CompSort) c, transform_byteio);
- comp_data[c] = &pic.Data((CompSort) c);
- coeff_data[c] = &pic.WltData((CompSort) c);
+ pic.InitWltData( depth );
- SubbandList& bands = coeff_data[c]->BandList();
+ for (int c=0; c<3; ++c){
+ ComponentByteIO component_byteio((CompSort) c, transform_byteio);
+ comp_data[c] = &pic.Data((CompSort) c);
+ coeff_data[c] = &pic.WltData((CompSort) c);
- bands.Init(depth , coeff_data[c]->LengthX() , coeff_data[c]->LengthY());
- my_compdecoder.Decompress(&component_byteio, *(coeff_data[c]), bands);
+ SubbandList& bands = coeff_data[c]->BandList();
- wtransform.Transform(BACKWARD, *(comp_data[c]), *(coeff_data[c]));
- }
+ bands.Init(depth , coeff_data[c]->LengthX() , coeff_data[c]->LengthY());
+ my_compdecoder.Decompress(&component_byteio, *(coeff_data[c]), bands );
+
+ wtransform.Transform(BACKWARD,*(comp_data[c]), *(coeff_data[c]));
}
- else
- my_picture.Fill(0);
+ }
+ else
+ my_picture.Fill(0);
- if(psort.IsInter())
- {
- Picture* my_pic = &my_buffer.GetPicture(m_pparams.PictureNum());
+ if ( psort.IsInter() ){
+ Picture* my_pic = &my_buffer.GetPicture( m_pparams.PictureNum() );
- const std::vector<int>& refs = m_pparams.Refs();
- Picture* ref_pics[2];
+ const std::vector<int>& refs = m_pparams.Refs();
+ Picture* ref_pics[2];
- ref_pics[0] = &my_buffer.GetPicture(refs[0]);
- if(refs.size() > 1)
- ref_pics[1] = &my_buffer.GetPicture(refs[1]);
- else
- ref_pics[1] = ref_pics[0];
+ ref_pics[0] = &my_buffer.GetPicture( refs[0] );
+ if (refs.size()>1)
+ ref_pics[1] = &my_buffer.GetPicture( refs[1] );
+ else
+ ref_pics[1] = ref_pics[0];
- //motion compensate to add the data back in if we don't have an I picture
- MotionCompensator::CompensatePicture(m_decparams.GetPicPredParams() , ADD , *(mv_data.get()) ,
- my_pic, ref_pics);
- }
+ //motion compensate to add the data back in if we don't have an I picture
+ MotionCompensator::CompensatePicture( m_decparams.GetPicPredParams() , ADD , *(mv_data.get()) ,
+ my_pic, ref_pics );
+ }
- my_picture.Clip();
+ my_picture.Clip();
- if(m_decparams.Verbose())
- std::cout << std::endl;
+ if (m_decparams.Verbose())
+ std::cout<<std::endl;
- //exit success
- return true;
+ //exit success
+ return true;
}// try
- catch(const DiracException& e)
- {
+ catch (const DiracException& e) {
// skip picture
throw e;
}
- //exit failure
+ //exit failure
return false;
}
-void PictureDecompressor::CleanReferencePictures(PictureBuffer& my_buffer)
+void PictureDecompressor::CleanReferencePictures( PictureBuffer& my_buffer )
{
- if(m_decparams.Verbose())
- std::cout << std::endl << "Cleaning reference buffer: ";
+ if ( m_decparams.Verbose() )
+ std::cout<<std::endl<<"Cleaning reference buffer: ";
// Do picture buffer cleaning
int retd_pnum = m_pparams.RetiredPictureNum();
- if(retd_pnum >= 0 && my_buffer.IsPictureAvail(retd_pnum) && my_buffer.GetPicture(retd_pnum).GetPparams().PicSort().IsRef())
+ if ( retd_pnum >= 0 && my_buffer.IsPictureAvail(retd_pnum) && my_buffer.GetPicture(retd_pnum).GetPparams().PicSort().IsRef() )
{
my_buffer.Remove(retd_pnum);
- if(m_decparams.Verbose())
- std::cout << retd_pnum << " ";
+ if ( m_decparams.Verbose() )
+ std::cout<<retd_pnum<<" ";
}
}
@@ -242,17 +233,17 @@ void PictureDecompressor::SetMVBlocks()
predparams.SetBlockSizes(olb_params, m_cformat);
// Calculate the number of macro blocks
- int xnum_sb = (m_decparams.Xl() + predparams.LumaBParams(0).Xbsep() - 1) /
- predparams.LumaBParams(0).Xbsep();
- int ynum_sb = (m_decparams.Yl() + predparams.LumaBParams(0).Ybsep() - 1) /
- predparams.LumaBParams(0).Ybsep();
+ int xnum_sb = (m_decparams.Xl()+predparams.LumaBParams(0).Xbsep()-1)/
+ predparams.LumaBParams(0).Xbsep();
+ int ynum_sb = (m_decparams.Yl()+predparams.LumaBParams(0).Ybsep()-1)/
+ predparams.LumaBParams(0).Ybsep();
predparams.SetXNumSB(xnum_sb);
predparams.SetYNumSB(ynum_sb);
// Set the number of blocks
- predparams.SetXNumBlocks(4 * xnum_sb);
- predparams.SetYNumBlocks(4 * ynum_sb);
+ predparams.SetXNumBlocks(4*xnum_sb);
+ predparams.SetYNumBlocks(4*ynum_sb);
// Note that we do not have an integral number of superblocks in a picture
// So it is possible that part of a superblock and some blocks can fall
@@ -273,21 +264,21 @@ void PictureDecompressor::PushPicture(PictureBuffer &my_buffer)
my_buffer.PushPicture(m_pparams);
}
-void PictureDecompressor::DecompressMVData(std::auto_ptr<MvData>& mv_data,
- PictureByteIO& picture_byteio)
+void PictureDecompressor::DecompressMVData( std::auto_ptr<MvData>& mv_data,
+ PictureByteIO& picture_byteio )
{
PicturePredParams& predparams = m_decparams.GetPicPredParams();
- MvDataByteIO mvdata_byteio(picture_byteio, m_pparams, predparams);
+ MvDataByteIO mvdata_byteio (picture_byteio, m_pparams, predparams);
// Read in the picture prediction parameters
mvdata_byteio.Input();
SetMVBlocks();
- mv_data.reset(new MvData(predparams, m_pparams.NumRefs()));
+ mv_data.reset(new MvData( predparams, m_pparams.NumRefs() ));
// decode mv data
- if(m_decparams.Verbose())
- std::cout << std::endl << "Decoding motion data ...";
+ if (m_decparams.Verbose())
+ std::cout<<std::endl<<"Decoding motion data ...";
int num_bits;
@@ -295,88 +286,87 @@ void PictureDecompressor::DecompressMVData(std::auto_ptr<MvData>& mv_data,
mvdata_byteio.SplitModeData()->Input();
// Read the mode data
num_bits = mvdata_byteio.SplitModeData()->DataBlockSize();
- SplitModeCodec smode_decoder(mvdata_byteio.SplitModeData()->DataBlock(), TOTAL_MV_CTXS);
- smode_decoder.Decompress(*(mv_data.get()) , num_bits);
+ SplitModeCodec smode_decoder( mvdata_byteio.SplitModeData()->DataBlock(), TOTAL_MV_CTXS);
+ smode_decoder.Decompress( *(mv_data.get()) , num_bits);
// Read in the prediction mode data header
mvdata_byteio.PredModeData()->Input();
// Read the mode data
num_bits = mvdata_byteio.PredModeData()->DataBlockSize();
- PredModeCodec pmode_decoder(mvdata_byteio.PredModeData()->DataBlock(), TOTAL_MV_CTXS, m_pparams.NumRefs());
- pmode_decoder.Decompress(*(mv_data.get()) , num_bits);
+ PredModeCodec pmode_decoder( mvdata_byteio.PredModeData()->DataBlock(), TOTAL_MV_CTXS, m_pparams.NumRefs());
+ pmode_decoder.Decompress( *(mv_data.get()) , num_bits);
// Read in the MV1 horizontal data header
mvdata_byteio.MV1HorizData()->Input();
// Read the MV1 horizontal data
num_bits = mvdata_byteio.MV1HorizData()->DataBlockSize();
- VectorElementCodec vdecoder1h(mvdata_byteio.MV1HorizData()->DataBlock(), 1,
- HORIZONTAL, TOTAL_MV_CTXS);
- vdecoder1h.Decompress(*(mv_data.get()) , num_bits);
+ VectorElementCodec vdecoder1h( mvdata_byteio.MV1HorizData()->DataBlock(), 1,
+ HORIZONTAL, TOTAL_MV_CTXS);
+ vdecoder1h.Decompress( *(mv_data.get()) , num_bits);
// Read in the MV1 vertical data header
mvdata_byteio.MV1VertData()->Input();
// Read the MV1 data
num_bits = mvdata_byteio.MV1VertData()->DataBlockSize();
- VectorElementCodec vdecoder1v(mvdata_byteio.MV1VertData()->DataBlock(), 1,
- VERTICAL, TOTAL_MV_CTXS);
- vdecoder1v.Decompress(*(mv_data.get()) , num_bits);
+ VectorElementCodec vdecoder1v( mvdata_byteio.MV1VertData()->DataBlock(), 1,
+ VERTICAL, TOTAL_MV_CTXS);
+ vdecoder1v.Decompress( *(mv_data.get()) , num_bits);
- if(m_pparams.NumRefs() > 1)
+ if ( m_pparams.NumRefs()>1 )
{
// Read in the MV2 horizontal data header
mvdata_byteio.MV2HorizData()->Input();
// Read the MV2 horizontal data
num_bits = mvdata_byteio.MV2HorizData()->DataBlockSize();
- VectorElementCodec vdecoder2h(mvdata_byteio.MV2HorizData()->DataBlock(), 2,
- HORIZONTAL, TOTAL_MV_CTXS);
- vdecoder2h.Decompress(*(mv_data.get()) , num_bits);
+ VectorElementCodec vdecoder2h( mvdata_byteio.MV2HorizData()->DataBlock(), 2,
+ HORIZONTAL, TOTAL_MV_CTXS);
+ vdecoder2h.Decompress( *(mv_data.get()) , num_bits);
// Read in the MV2 vertical data header
mvdata_byteio.MV2VertData()->Input();
// Read the MV2 vertical data
num_bits = mvdata_byteio.MV2VertData()->DataBlockSize();
- VectorElementCodec vdecoder2v(mvdata_byteio.MV2VertData()->DataBlock(), 2,
- VERTICAL, TOTAL_MV_CTXS);
- vdecoder2v.Decompress(*(mv_data.get()) , num_bits);
+ VectorElementCodec vdecoder2v( mvdata_byteio.MV2VertData()->DataBlock(), 2,
+ VERTICAL, TOTAL_MV_CTXS);
+ vdecoder2v.Decompress( *(mv_data.get()) , num_bits);
}
// Read in the Y DC data header
mvdata_byteio.YDCData()->Input();
// Read the Y DC data
num_bits = mvdata_byteio.YDCData()->DataBlockSize();
- DCCodec ydc_decoder(mvdata_byteio.YDCData()->DataBlock(), Y_COMP, TOTAL_MV_CTXS);
- ydc_decoder.Decompress(*(mv_data.get()) , num_bits);
+ DCCodec ydc_decoder( mvdata_byteio.YDCData()->DataBlock(), Y_COMP, TOTAL_MV_CTXS);
+ ydc_decoder.Decompress( *(mv_data.get()) , num_bits);
// Read in the U DC data header
mvdata_byteio.UDCData()->Input();
// Read the U DC data
num_bits = mvdata_byteio.UDCData()->DataBlockSize();
- DCCodec udc_decoder(mvdata_byteio.YDCData()->DataBlock(), U_COMP, TOTAL_MV_CTXS);
- udc_decoder.Decompress(*(mv_data.get()) , num_bits);
+ DCCodec udc_decoder( mvdata_byteio.YDCData()->DataBlock(), U_COMP, TOTAL_MV_CTXS);
+ udc_decoder.Decompress( *(mv_data.get()) , num_bits);
// Read in the Y DC data header
mvdata_byteio.YDCData()->Input();
// Read the Y DC data
num_bits = mvdata_byteio.YDCData()->DataBlockSize();
- DCCodec vdc_decoder(mvdata_byteio.VDCData()->DataBlock(), V_COMP, TOTAL_MV_CTXS);
- vdc_decoder.Decompress(*(mv_data.get()) , num_bits);
+ DCCodec vdc_decoder( mvdata_byteio.VDCData()->DataBlock(), V_COMP, TOTAL_MV_CTXS);
+ vdc_decoder.Decompress( *(mv_data.get()) , num_bits);
}
-void PictureDecompressor::InitCoeffData(CoeffArray& coeff_data, const int xl, const int yl)
-{
+void PictureDecompressor::InitCoeffData( CoeffArray& coeff_data, const int xl, const int yl ){
// First set the dimensions up //
int xpad_len = xl;
int ypad_len = yl;
// The pic dimensions must be a multiple of 2^(transform depth)
- int tx_mul = (1 << m_decparams.TransformDepth());
+ int tx_mul = (1<<m_decparams.TransformDepth());
- if(xpad_len % tx_mul != 0)
- xpad_len = ((xpad_len / tx_mul) + 1) * tx_mul;
- if(ypad_len % tx_mul != 0)
- ypad_len = ((ypad_len / tx_mul) + 1) * tx_mul;
+ if ( xpad_len%tx_mul != 0 )
+ xpad_len = ( (xpad_len/tx_mul)+1 ) *tx_mul;
+ if ( ypad_len%tx_mul != 0 )
+ ypad_len = ( (ypad_len/tx_mul)+1 ) * tx_mul;
- coeff_data.Resize(ypad_len, xpad_len);
+ coeff_data.Resize( ypad_len, xpad_len );
}
diff --git a/src/filters/parser/DiracSplitter/libdirac/libdirac_decoder/picture_decompress.h b/src/filters/parser/DiracSplitter/libdirac/libdirac_decoder/picture_decompress.h
index 20f4a90d3..31efbe5db 100644
--- a/src/filters/parser/DiracSplitter/libdirac/libdirac_decoder/picture_decompress.h
+++ b/src/filters/parser/DiracSplitter/libdirac/libdirac_decoder/picture_decompress.h
@@ -50,110 +50,106 @@
namespace dirac
{
-class MvData;
-
-//! Compress a single image picture
-/*!
- This class decompresses a single picture at a time, using parameters
- supplied at its construction. PictureDecompressor is used by
- SequenceDecompressor.
-*/
-class PictureDecompressor
-{
-public:
- //! Constructor
- /*!
- Creates a PictureDecompressor with specific set of parameters the
- control the decompression process. It decodes motion data before
- decoding each component of the picture.
-
- \param decp decoder parameters
- \param cf the chroma format of the picture being decompressed
- */
- PictureDecompressor(DecoderParams& decp, ChromaFormat cf);
-
- //! Destructor
- /*!
- Releases resources.
- */
- ~PictureDecompressor();
-
- //! Decompress the next picture into the buffer
- /*!
- Decompresses the next picture from the stream and place at the end
- of a picture buffer.
- Returns true if able to decode successfully, false otherwise
-
- \param parseunit_byteio Picture info in Dirac-stream format
- \param my_buffer picture buffer into which the picture is placed
- */
- bool Decompress(ParseUnitByteIO& parseunit_byteio,
- PictureBuffer& my_buffer);
-
- //! Returns the picture parameters of the current picture being decoded
- const PictureParams& GetPicParams() const
- {
- return m_pparams;
- }
-
-private:
- //! Copy constructor is private and body-less
- /*!
- Copy constructor is private and body-less. This class should not be copied.
-
- */
- PictureDecompressor(const PictureDecompressor& cpy);
-
- //! Assignment = is private and body-less
+ class MvData;
+
+ //! Compress a single image picture
/*!
- Assignment = is private and body-less. This class should not be
- assigned.
+ This class decompresses a single picture at a time, using parameters
+ supplied at its construction. PictureDecompressor is used by
+ SequenceDecompressor.
*/
- PictureDecompressor& operator=(const PictureDecompressor& rhs);
-
- //! Initialise the padded coefficient data for the IDWT and subband decoding
- void InitCoeffData(CoeffArray& coeff_data, const int xl, const int yl);
-
- //! Removes all the reference pictures in the retired list
- void CleanReferencePictures(PictureBuffer& my_buffer);
-
- //! Decodes component data
- void CompDecompress(TransformByteIO *p_transform_byteio,
- PictureBuffer& my_buffer, int pnum, CompSort cs);
-
- //! Decodes the motion data
- void DecompressMVData(std::auto_ptr<MvData>& mv_data, PictureByteIO& picture_byteio);
-
-
- //! Set the number of superblocks and blocks
- void SetMVBlocks();
-
- //! Add a picture to the picture buffer
- void PushPicture(PictureBuffer &my_buffer);
-
- //Member variables
-
- //! Parameters for the decompression, as provided in constructor
- DecoderParams& m_decparams;
-
- //! Chroma format of the picture being decompressed
- ChromaFormat m_cformat;
-
- //! An indicator which is true if the picture has been skipped, false otherwise
- bool m_skipped;
-
- //! An indicator that is true if we use global motion vectors, false otherwise
- bool m_use_global;
-
- //! An indicator that is true if we use block motion vectors, false otherwise
- bool m_use_block_mv;
-
- //! Prediction mode to use if we only have global motion vectors
- PredMode m_global_pred_mode;
-
- //! Current Picture Parameters
- PictureParams m_pparams;
-};
+ class PictureDecompressor{
+ public:
+ //! Constructor
+ /*!
+ Creates a PictureDecompressor with specific set of parameters the
+ control the decompression process. It decodes motion data before
+ decoding each component of the picture.
+
+ \param decp decoder parameters
+ \param cf the chroma format of the picture being decompressed
+ */
+ PictureDecompressor(DecoderParams& decp, ChromaFormat cf);
+
+ //! Destructor
+ /*!
+ Releases resources.
+ */
+ ~PictureDecompressor();
+
+ //! Decompress the next picture into the buffer
+ /*!
+ Decompresses the next picture from the stream and place at the end
+ of a picture buffer.
+ Returns true if able to decode successfully, false otherwise
+
+ \param parseunit_byteio Picture info in Dirac-stream format
+ \param my_buffer picture buffer into which the picture is placed
+ */
+ bool Decompress(ParseUnitByteIO& parseunit_byteio,
+ PictureBuffer& my_buffer);
+
+ //! Returns the picture parameters of the current picture being decoded
+ const PictureParams& GetPicParams() const{ return m_pparams; }
+
+ private:
+ //! Copy constructor is private and body-less
+ /*!
+ Copy constructor is private and body-less. This class should not be copied.
+
+ */
+ PictureDecompressor(const PictureDecompressor& cpy);
+
+ //! Assignment = is private and body-less
+ /*!
+ Assignment = is private and body-less. This class should not be
+ assigned.
+ */
+ PictureDecompressor& operator=(const PictureDecompressor& rhs);
+
+ //! Initialise the padded coefficient data for the IDWT and subband decoding
+ void InitCoeffData( CoeffArray& coeff_data, const int xl, const int yl );
+
+ //! Removes all the reference pictures in the retired list
+ void CleanReferencePictures( PictureBuffer& my_buffer );
+
+ //! Decodes component data
+ void CompDecompress(TransformByteIO *p_transform_byteio,
+ PictureBuffer& my_buffer,int pnum, CompSort cs);
+
+ //! Decodes the motion data
+ void DecompressMVData( std::auto_ptr<MvData>& mv_data, PictureByteIO& picture_byteio );
+
+
+ //! Set the number of superblocks and blocks
+ void SetMVBlocks();
+
+ //! Add a picture to the picture buffer
+ void PushPicture(PictureBuffer &my_buffer);
+
+ //Member variables
+
+ //! Parameters for the decompression, as provided in constructor
+ DecoderParams& m_decparams;
+
+ //! Chroma format of the picture being decompressed
+ ChromaFormat m_cformat;
+
+ //! An indicator which is true if the picture has been skipped, false otherwise
+ bool m_skipped;
+
+ //! An indicator that is true if we use global motion vectors, false otherwise
+ bool m_use_global;
+
+ //! An indicator that is true if we use block motion vectors, false otherwise
+ bool m_use_block_mv;
+
+ //! Prediction mode to use if we only have global motion vectors
+ PredMode m_global_pred_mode;
+
+ //! Current Picture Parameters
+ PictureParams m_pparams;
+ };
} // namespace dirac
diff --git a/src/filters/parser/DiracSplitter/libdirac/libdirac_decoder/seq_decompress.cpp b/src/filters/parser/DiracSplitter/libdirac/libdirac_decoder/seq_decompress.cpp
index 79a8622ea..09421e934 100644
--- a/src/filters/parser/DiracSplitter/libdirac/libdirac_decoder/seq_decompress.cpp
+++ b/src/filters/parser/DiracSplitter/libdirac/libdirac_decoder/seq_decompress.cpp
@@ -53,25 +53,25 @@
#include <libdirac_byteio/accessunit_byteio.h>
using namespace dirac;
-SequenceDecompressor::SequenceDecompressor(ParseUnitByteIO& parseunit, bool verbosity)
- :
- m_all_done(false),
- m_current_code_pnum(0),
- m_delay(1),
- m_show_pnum(-1),
- m_highest_pnum(0)
+SequenceDecompressor::SequenceDecompressor(ParseUnitByteIO& parseunit,bool verbosity)
+:
+m_all_done(false),
+m_current_code_pnum(0),
+m_delay(1),
+m_show_pnum(-1),
+m_highest_pnum(0)
{
// read unit
NewAccessUnit(parseunit);
- if(m_decparams.FieldCoding())
+ if ( m_decparams.FieldCoding() )
m_delay = 2;
- m_decparams.SetVerbose(verbosity);
+ m_decparams.SetVerbose( verbosity );
- m_pbuffer = new PictureBuffer();
+ m_pbuffer= new PictureBuffer( );
- m_pdecoder = new PictureDecompressor(m_decparams , m_srcparams.CFormat());
+ m_pdecoder = new PictureDecompressor (m_decparams , m_srcparams.CFormat());
}
@@ -89,7 +89,7 @@ const PictureParams* SequenceDecompressor::GetNextPictureParams() const
void SequenceDecompressor::NewAccessUnit(ParseUnitByteIO& parseunit_byteio)
{
// read sequence header
- SequenceHeaderByteIO seqheader_byteio(parseunit_byteio, m_parse_params, m_srcparams, m_decparams);
+ SequenceHeaderByteIO seqheader_byteio(parseunit_byteio,m_parse_params, m_srcparams, m_decparams);
seqheader_byteio.Input();
}
@@ -103,38 +103,38 @@ const Picture* SequenceDecompressor::DecompressNextPicture(ParseUnitByteIO* p_pa
//the pictures out. It's up to the calling function to do something with the decoded pictures as they
//come out - write them to screen or to file, as required.
- TEST(m_pdecoder != NULL);
+ TEST (m_pdecoder != NULL);
// Remove the last displayed picture from the buffer if it wasn't a reference
- if(m_show_pnum > 0)
+ if ( m_show_pnum>0 )
{
- if(m_decparams.Verbose())
- std::cout << std::endl << "Cleaning display buffer: ";
- if(m_pbuffer->IsPictureAvail(m_show_pnum - 1) &&
- m_pbuffer->GetPicture(m_show_pnum - 1).GetPparams().PicSort().IsNonRef())
+ if ( m_decparams.Verbose() )
+ std::cout<<std::endl<<"Cleaning display buffer: ";
+ if ( m_pbuffer->IsPictureAvail(m_show_pnum-1) &&
+ m_pbuffer->GetPicture(m_show_pnum-1).GetPparams().PicSort().IsNonRef() )
{
- m_pbuffer->Remove(m_show_pnum - 1);
- if(m_decparams.Verbose())
- std::cout << (m_show_pnum - 1) << " ";
+ m_pbuffer->Remove(m_show_pnum-1);
+ if ( m_decparams.Verbose() )
+ std::cout<<(m_show_pnum-1)<<" ";
}
}
- bool new_picture_to_display = false;
+ bool new_picture_to_display=false;
- if(p_parseunit_byteio)
+ if (p_parseunit_byteio)
{
- if(m_decparams.Verbose())
- std::cout << std::endl << "Calling picture decompression function";
- new_picture_to_display = m_pdecoder->Decompress(*p_parseunit_byteio,
- *m_pbuffer);
+ if (m_decparams.Verbose())
+ std::cout<<std::endl<<"Calling picture decompression function";
+ new_picture_to_display = m_pdecoder->Decompress(*p_parseunit_byteio,
+ *m_pbuffer);
}
- if(m_show_pnum < 0 && new_picture_to_display == false)
+ if (m_show_pnum < 0 && new_picture_to_display == false)
return NULL;
- if(m_pbuffer->IsPictureAvail(m_show_pnum + 1))
+ if (m_pbuffer->IsPictureAvail(m_show_pnum+1 ))
++m_show_pnum;
- else if(new_picture_to_display && m_pdecoder->GetPicParams().PicSort().IsNonRef())
+ else if (new_picture_to_display && m_pdecoder->GetPicParams().PicSort().IsNonRef())
{
// if a decoded future non reference frame is available it implies
// that some frames have been skipped because of possible truncation
@@ -144,7 +144,7 @@ const Picture* SequenceDecompressor::DecompressNextPicture(ParseUnitByteIO* p_pa
m_highest_pnum = std::max(m_pdecoder->GetPicParams().PictureNum(), m_highest_pnum);
- if(m_pbuffer->IsPictureAvail(m_show_pnum))
+ if (m_pbuffer->IsPictureAvail(m_show_pnum))
return &m_pbuffer->GetPicture(m_show_pnum);
else
return NULL;
@@ -152,7 +152,7 @@ const Picture* SequenceDecompressor::DecompressNextPicture(ParseUnitByteIO* p_pa
const Picture* SequenceDecompressor::GetNextPicture()
{
- if(m_pbuffer->IsPictureAvail(m_show_pnum))
+ if (m_pbuffer->IsPictureAvail(m_show_pnum))
return &m_pbuffer->GetPicture(m_show_pnum);
else
return NULL;
@@ -160,10 +160,10 @@ const Picture* SequenceDecompressor::GetNextPicture()
bool SequenceDecompressor::Finished()
{
- if(m_show_pnum >= m_highest_pnum)
+ if (m_show_pnum>=m_highest_pnum)
return true;
- if(!m_pbuffer->IsPictureAvail(m_show_pnum + 1))
+ if (!m_pbuffer->IsPictureAvail(m_show_pnum+1 ))
++m_show_pnum;
return false;
diff --git a/src/filters/parser/DiracSplitter/libdirac/libdirac_decoder/seq_decompress.h b/src/filters/parser/DiracSplitter/libdirac/libdirac_decoder/seq_decompress.h
index 7dcc01a29..008ffc11d 100644
--- a/src/filters/parser/DiracSplitter/libdirac/libdirac_decoder/seq_decompress.h
+++ b/src/filters/parser/DiracSplitter/libdirac/libdirac_decoder/seq_decompress.h
@@ -54,146 +54,136 @@
namespace dirac
{
-class PictureBuffer;
-class Picture;
-class PictureDecompressor;
-
-//! Decompresses a sequence of pictures from a stream.
-/*!
- This class decompresses a sequence of frames, picture by picture.
-*/
-class SequenceDecompressor
-{
-public:
-
- //! Constructor
- /*!
- Initializes the decompressor with an input stream and level of
- output detail.
- \param parseunit First access-unit of new sequence
- \param verbosity when true, increases the amount of information displayed during decompression
- */
- SequenceDecompressor(ParseUnitByteIO& parseunit, bool verbosity);
-
- //! Destructor
- /*!
- Closes files and releases resources.
- */
- ~SequenceDecompressor();
-
- //! Marks beginning of a new AccessUnit
- /*!
- \param parseunit_byteio AccessUnit info in Dirac-stream format
- */
- void NewAccessUnit(ParseUnitByteIO& parseunit_byteio);
+ class PictureBuffer;
+ class Picture;
+ class PictureDecompressor;
-
- //! Decompress the next picture in sequence
- /*!
- This function decodes the next picture in coding order and returns
- the next picture in display order. In general these will differ, and
- because of re-ordering there is a delay which needs to be imposed.
- This creates problems at the start and at the end of the sequence
- which must be dealt with. At the start we just keep outputting
- picture 0. At the end you will need to loop for longer to get all
- the pictures out. It's up to the calling function to do something
- with the decoded pictures as they come out -- write them to screen
- or to file, as required.
-
- \param p_parseunit_byteio Picture information in Dirac-stream format
- \return reference to the next locally decoded picture available for display
- */
- const Picture* DecompressNextPicture(ParseUnitByteIO* p_parseunit_byteio);
-
- //! Get the next picture available for display
- const Picture* GetNextPicture();
-
- //! Get the next picture parameters
- const PictureParams* GetNextPictureParams() const;
- //! Determine if decompression is complete.
- /*!
- Indicates whether or not the last picture in the sequence has been
- decompressed.
- \return true if last picture has been compressed; false if not
- */
- bool Finished();
- //! Interrogates for parse parameters.
+ //! Decompresses a sequence of pictures from a stream.
/*!
- Returns the parse parameters used for this decompression run.
-
- \return parse parameters.
- */
- ParseParams & GetParseParams()
- {
- return m_parse_params;
- }
-
-
- //! Interrogates for source parameters.
- /*!
- Returns the source parameters used for this decompression run.
-
- \return source parameters.
- */
- SourceParams & GetSourceParams()
- {
- return m_srcparams;
- }
-
-
- //! Interrogates for coding parameters.
- /*!
- Returns the decoder parameters used for this decompression run.
-
- \return decoder parameters.
- */
- DecoderParams & GetDecoderParams()
- {
- return m_decparams;
- }
-private:
- //! Copy constructor is private and body-less
- /*!
- Copy constructor is private and body-less. This class should not
- be copied.
-
- */
- SequenceDecompressor(const SequenceDecompressor& cpy);
-
- //! Assignment = is private and body-less
- /*!
- Assignment = is private and body-less. This class should not be
- assigned.
-
+ This class decompresses a sequence of frames, picture by picture.
*/
- SequenceDecompressor& operator=(const SequenceDecompressor& rhs);
-
-
- //Member variables
-
- //! Completion flag, returned via the Finished method
- bool m_all_done;
- //! Parameters for the decompression, as provided in constructor
- DecoderParams m_decparams;
- //! The parse parameters obtained from the stream header
- ParseParams m_parse_params;
- //! The source parameters obtained from the stream header
- SourceParams m_srcparams;
- //! A picture buffer used for local storage of pictures whilst pending re-ordering or being used for reference.
- PictureBuffer* m_pbuffer;
- //! Number of the picture in coded order which is to be decoded
- int m_current_code_pnum;
- //! A delay so that we don't display what we haven't decoded
- int m_delay;
- //! Index, in display order, of the last picture read
- int m_last_picture_read;
- //! Index, in display order of the picture to be displayed next - computed from delay and current_code_pnum
- int m_show_pnum;
- //! Picture decompressor object
- PictureDecompressor *m_pdecoder;
- //! Highest picture-num processed - for tracking end-of-sequence
- int m_highest_pnum;
-};
+ class SequenceDecompressor{
+ public:
+
+ //! Constructor
+ /*!
+ Initializes the decompressor with an input stream and level of
+ output detail.
+ \param parseunit First access-unit of new sequence
+ \param verbosity when true, increases the amount of information displayed during decompression
+ */
+ SequenceDecompressor(ParseUnitByteIO& parseunit, bool verbosity);
+
+ //! Destructor
+ /*!
+ Closes files and releases resources.
+ */
+ ~SequenceDecompressor();
+
+ //! Marks beginning of a new AccessUnit
+ /*!
+ \param parseunit_byteio AccessUnit info in Dirac-stream format
+ */
+ void NewAccessUnit(ParseUnitByteIO& parseunit_byteio);
+
+
+ //! Decompress the next picture in sequence
+ /*!
+ This function decodes the next picture in coding order and returns
+ the next picture in display order. In general these will differ, and
+ because of re-ordering there is a delay which needs to be imposed.
+ This creates problems at the start and at the end of the sequence
+ which must be dealt with. At the start we just keep outputting
+ picture 0. At the end you will need to loop for longer to get all
+ the pictures out. It's up to the calling function to do something
+ with the decoded pictures as they come out -- write them to screen
+ or to file, as required.
+
+ \param p_parseunit_byteio Picture information in Dirac-stream format
+ \return reference to the next locally decoded picture available for display
+ */
+ const Picture* DecompressNextPicture(ParseUnitByteIO* p_parseunit_byteio);
+
+ //! Get the next picture available for display
+ const Picture* GetNextPicture();
+
+ //! Get the next picture parameters
+ const PictureParams* GetNextPictureParams() const;
+ //! Determine if decompression is complete.
+ /*!
+ Indicates whether or not the last picture in the sequence has been
+ decompressed.
+ \return true if last picture has been compressed; false if not
+ */
+ bool Finished();
+ //! Interrogates for parse parameters.
+ /*!
+ Returns the parse parameters used for this decompression run.
+
+ \return parse parameters.
+ */
+ ParseParams & GetParseParams() { return m_parse_params; }
+
+
+ //! Interrogates for source parameters.
+ /*!
+ Returns the source parameters used for this decompression run.
+
+ \return source parameters.
+ */
+ SourceParams & GetSourceParams() { return m_srcparams; }
+
+
+ //! Interrogates for coding parameters.
+ /*!
+ Returns the decoder parameters used for this decompression run.
+
+ \return decoder parameters.
+ */
+ DecoderParams & GetDecoderParams() { return m_decparams; }
+ private:
+ //! Copy constructor is private and body-less
+ /*!
+ Copy constructor is private and body-less. This class should not
+ be copied.
+
+ */
+ SequenceDecompressor(const SequenceDecompressor& cpy);
+
+ //! Assignment = is private and body-less
+ /*!
+ Assignment = is private and body-less. This class should not be
+ assigned.
+
+ */
+ SequenceDecompressor& operator=(const SequenceDecompressor& rhs);
+
+
+ //Member variables
+
+ //! Completion flag, returned via the Finished method
+ bool m_all_done;
+ //! Parameters for the decompression, as provided in constructor
+ DecoderParams m_decparams;
+ //! The parse parameters obtained from the stream header
+ ParseParams m_parse_params;
+ //! The source parameters obtained from the stream header
+ SourceParams m_srcparams;
+ //! A picture buffer used for local storage of pictures whilst pending re-ordering or being used for reference.
+ PictureBuffer* m_pbuffer;
+ //! Number of the picture in coded order which is to be decoded
+ int m_current_code_pnum;
+ //! A delay so that we don't display what we haven't decoded
+ int m_delay;
+ //! Index, in display order, of the last picture read
+ int m_last_picture_read;
+ //! Index, in display order of the picture to be displayed next - computed from delay and current_code_pnum
+ int m_show_pnum;
+ //! Picture decompressor object
+ PictureDecompressor *m_pdecoder;
+ //! Highest picture-num processed - for tracking end-of-sequence
+ int m_highest_pnum;
+ };
} // namespace dirac
diff --git a/src/filters/parser/DiracSplitter/libdirac/libdirac_encoder/comp_compress.cpp b/src/filters/parser/DiracSplitter/libdirac/libdirac_encoder/comp_compress.cpp
index da11d012f..07762d7ec 100644
--- a/src/filters/parser/DiracSplitter/libdirac/libdirac_encoder/comp_compress.cpp
+++ b/src/filters/parser/DiracSplitter/libdirac/libdirac_encoder/comp_compress.cpp
@@ -55,55 +55,54 @@ using namespace dirac;
#include <vector>
#include <iostream>
-CompCompressor::CompCompressor(EncoderParams& encp, const PictureParams& pp)
- : m_encparams(encp),
- m_pparams(pp),
- m_psort(m_pparams.PicSort()),
- m_cformat(m_pparams.CFormat())
+CompCompressor::CompCompressor( EncoderParams& encp,const PictureParams& pp)
+: m_encparams(encp),
+ m_pparams(pp),
+ m_psort( m_pparams.PicSort() ),
+ m_cformat( m_pparams.CFormat() )
{}
-ComponentByteIO* CompCompressor::Compress(CoeffArray& coeff_data ,
- SubbandList& bands,
- CompSort csort,
- const OneDArray<unsigned int>& estimated_bits)
+ComponentByteIO* CompCompressor::Compress( CoeffArray& coeff_data ,
+ SubbandList& bands,
+ CompSort csort,
+ const OneDArray<unsigned int>& estimated_bits)
{
// Need to transform, select quantisers for each band,
// and then compress each component in turn
- unsigned int num_band_bytes(0);
+ unsigned int num_band_bytes( 0 );
// create byte output
ComponentByteIO *p_component_byteio = new ComponentByteIO(csort);
// Loop over all the bands (from DC to HF) quantising and coding them
- for(int b = bands.Length() ; b >= 1 ; --b)
+ for (int b=bands.Length() ; b>=1 ; --b )
{
// create subband byte io
SubbandByteIO subband_byteio(bands(b));
- if(!bands(b).Skipped())
- {
- // If not skipped ...
- if(m_pparams.UsingAC())
+ if ( !bands(b).Skipped() )
+ { // If not skipped ...
+ if (m_pparams.UsingAC())
{
// A pointer to an object for coding the subband data
BandCodec* bcoder;
- // Pick the right codec according to the picture type and subband
- if(b >= bands.Length() - 3)
+ // Pick the right codec according to the picture type and subband
+ if (b >= bands.Length()-3)
{
- if(m_psort.IsIntra() && b == bands.Length())
- bcoder = new IntraDCBandCodec(&subband_byteio,
- TOTAL_COEFF_CTXS , bands);
+ if ( m_psort.IsIntra() && b == bands.Length() )
+ bcoder=new IntraDCBandCodec(&subband_byteio,
+ TOTAL_COEFF_CTXS , bands );
else
- bcoder = new LFBandCodec(&subband_byteio , TOTAL_COEFF_CTXS,
- bands , b, m_psort.IsIntra());
+ bcoder=new LFBandCodec(&subband_byteio ,TOTAL_COEFF_CTXS,
+ bands , b, m_psort.IsIntra());
}
else
- bcoder = new BandCodec(&subband_byteio , TOTAL_COEFF_CTXS ,
- bands , b, m_psort.IsIntra());
+ bcoder=new BandCodec(&subband_byteio , TOTAL_COEFF_CTXS ,
+ bands , b, m_psort.IsIntra() );
num_band_bytes = bcoder->Compress(coeff_data);
@@ -115,28 +114,27 @@ ComponentByteIO* CompCompressor::Compress(CoeffArray& coeff_data ,
// A pointer to an object for coding the subband data
BandVLC* bcoder;
- if(m_psort.IsIntra() && b == bands.Length())
- bcoder = new IntraDCBandVLC(&subband_byteio, bands);
+ if ( m_psort.IsIntra() && b == bands.Length() )
+ bcoder=new IntraDCBandVLC(&subband_byteio, bands );
else
- bcoder = new BandVLC(&subband_byteio , 0, bands , b,
- m_psort.IsIntra());
+ bcoder=new BandVLC(&subband_byteio , 0, bands , b,
+ m_psort.IsIntra() );
num_band_bytes = bcoder->Compress(coeff_data);
delete bcoder;
}
- // Update the entropy correction factors
- m_encparams.EntropyFactors().Update(b , m_pparams , csort ,
- estimated_bits[b] , 8 * num_band_bytes);
+ // Update the entropy correction factors
+ m_encparams.EntropyFactors().Update(b , m_pparams , csort ,
+ estimated_bits[b] , 8*num_band_bytes);
}
else
- {
- // ... skipped
- SetToVal(coeff_data , bands(b) , 0);
+ { // ... skipped
+ SetToVal( coeff_data , bands(b) , 0 );
}
- // output sub-band data
- p_component_byteio->AddSubband(&subband_byteio);
+ // output sub-band data
+ p_component_byteio->AddSubband(&subband_byteio);
}//b
@@ -144,12 +142,12 @@ ComponentByteIO* CompCompressor::Compress(CoeffArray& coeff_data ,
return p_component_byteio;
}
-void CompCompressor::SetToVal(CoeffArray& coeff_data, const Subband& node, ValueType val)
+void CompCompressor::SetToVal(CoeffArray& coeff_data,const Subband& node,ValueType val)
{
- for(int j = node.Yp() ; j < node.Yp() + node.Yl() ; ++j)
+ for (int j=node.Yp() ; j<node.Yp() + node.Yl() ; ++j)
{
- for(int i = node.Xp(); i < node.Xp() + node.Xl() ; ++i)
+ for (int i=node.Xp(); i<node.Xp() + node.Xl() ; ++i)
{
coeff_data[j][i] = val;
}// i
diff --git a/src/filters/parser/DiracSplitter/libdirac/libdirac_encoder/comp_compress.h b/src/filters/parser/DiracSplitter/libdirac/libdirac_encoder/comp_compress.h
index 025531d30..e21150904 100644
--- a/src/filters/parser/DiracSplitter/libdirac/libdirac_encoder/comp_compress.h
+++ b/src/filters/parser/DiracSplitter/libdirac/libdirac_encoder/comp_compress.h
@@ -47,65 +47,65 @@
namespace dirac
{
-class MEData;
-
-//! Compress a picture component
-/*!
- This class compresses one of the three components (Y, U, or V) of a
- picture according to a given set or parameters. CompCompressor is used
- by PictureCompressor.
-*/
-class CompCompressor
-{
-public:
- //! Constructor
- /*!
- Create and initialize a component compressor with the given
- characteristics.
- \param encp encoding parameters
- \param fp picture parameters
- */
- CompCompressor(EncoderParams & encp, const PictureParams& fp);
-
+ class MEData;
+
//! Compress a picture component
/*!
- Compress a PicArray containing a picture component (Y, U, or V).
- \param coeff_data the component data to be compressed
- \param bands Subbands list
- \param csort Chroma format
- \param estimated_bits the list of estimated number of bits in each subband
- \return Picture-component in Dirac-bytestream format
+ This class compresses one of the three components (Y, U, or V) of a
+ picture according to a given set or parameters. CompCompressor is used
+ by PictureCompressor.
*/
- ComponentByteIO* Compress(CoeffArray& coeff_data ,
- SubbandList& bands,
- CompSort csort,
- const OneDArray<unsigned int>& estimated_bits);
-
-private:
- //! Copy constructor is private and body-less. This class should not be copied.
- CompCompressor(const CompCompressor& cpy);
-
- //! Assignment = is private and body-less. This class should not be assigned.
- CompCompressor& operator=(const CompCompressor& rhs);
-
- //! Set a subband to a constant value
- void SetToVal(CoeffArray& coeff_data, const Subband& node, ValueType val);
-
-
-private:
-
- // member variables
- EncoderParams& m_encparams;
-
- const PictureParams& m_pparams;
-
- const PictureSort& m_psort;
-
- const ChromaFormat& m_cformat;
-
- float m_lambda;
-
-};
+ class CompCompressor
+ {
+ public:
+ //! Constructor
+ /*!
+ Create and initialize a component compressor with the given
+ characteristics.
+ \param encp encoding parameters
+ \param fp picture parameters
+ */
+ CompCompressor( EncoderParams & encp, const PictureParams& fp);
+
+ //! Compress a picture component
+ /*!
+ Compress a PicArray containing a picture component (Y, U, or V).
+ \param coeff_data the component data to be compressed
+ \param bands Subbands list
+ \param csort Chroma format
+ \param estimated_bits the list of estimated number of bits in each subband
+ \return Picture-component in Dirac-bytestream format
+ */
+ ComponentByteIO* Compress( CoeffArray& coeff_data ,
+ SubbandList& bands,
+ CompSort csort,
+ const OneDArray<unsigned int>& estimated_bits);
+
+ private:
+ //! Copy constructor is private and body-less. This class should not be copied.
+ CompCompressor(const CompCompressor& cpy);
+
+ //! Assignment = is private and body-less. This class should not be assigned.
+ CompCompressor& operator=(const CompCompressor& rhs);
+
+ //! Set a subband to a constant value
+ void SetToVal(CoeffArray& coeff_data,const Subband& node,ValueType val);
+
+
+ private:
+
+ // member variables
+ EncoderParams& m_encparams;
+
+ const PictureParams& m_pparams;
+
+ const PictureSort& m_psort;
+
+ const ChromaFormat& m_cformat;
+
+ float m_lambda;
+
+ };
} // namespace dirac
diff --git a/src/filters/parser/DiracSplitter/libdirac/libdirac_encoder/dirac_encoder.cpp b/src/filters/parser/DiracSplitter/libdirac/libdirac_encoder/dirac_encoder.cpp
index 7ca501460..09ba3f570 100644
--- a/src/filters/parser/DiracSplitter/libdirac/libdirac_encoder/dirac_encoder.cpp
+++ b/src/filters/parser/DiracSplitter/libdirac/libdirac_encoder/dirac_encoder.cpp
@@ -57,23 +57,23 @@ using namespace dirac;
using namespace std;
template <class T, class S >
-void copy_2dArray(const TwoDArray<T> & in, S *out)
+void copy_2dArray (const TwoDArray<T> & in, S *out)
{
- for(int j = 0 ; j < in.LengthY() ; ++j)
+ for (int j=0 ; j<in.LengthY() ; ++j)
{
- for(int i = 0 ; i < in.LengthX() ; ++i)
+ for (int i=0 ; i<in.LengthX() ; ++i)
{
// out[j*in.LengthX() + i] = in[j][i];
- *out++ = S(in[j][i]);
+ *out++ = S( in[j][i] );
}// i
}// j
}
-void copy_2dArray(const TwoDArray<PredMode> & in, int *out)
+void copy_2dArray (const TwoDArray<PredMode> & in, int *out)
{
- for(int j = 0 ; j < in.LengthY() ; ++j)
+ for (int j=0 ; j<in.LengthY() ; ++j)
{
- for(int i = 0 ; i < in.LengthX() ; ++i)
+ for (int i=0 ; i<in.LengthX() ; ++i)
{
// out[j*in.LengthX() + i] = in[j][i];
*out++ = in[j][i];
@@ -81,11 +81,11 @@ void copy_2dArray(const TwoDArray<PredMode> & in, int *out)
}// j
}
-void copy_2dArray(const TwoDArray<bool> & in, int *out)
+void copy_2dArray (const TwoDArray<bool> & in, int *out)
{
- for(int j = 0 ; j < in.LengthY() ; ++j)
+ for (int j=0 ; j<in.LengthY() ; ++j)
{
- for(int i = 0 ; i < in.LengthX() ; ++i)
+ for (int i=0 ; i<in.LengthX() ; ++i)
{
// out[j*in.LengthX() + i] = in[j][i];
*out++ = in[j][i];
@@ -93,11 +93,11 @@ void copy_2dArray(const TwoDArray<bool> & in, int *out)
}// j
}
-void copy_mv(const MvArray& mv, dirac_mv_t *dmv)
+void copy_mv ( const MvArray& mv, dirac_mv_t *dmv)
{
- for(int j = 0 ; j < mv.LengthY() ; ++j)
+ for (int j=0 ; j<mv.LengthY() ; ++j)
{
- for(int i = 0 ; i < mv.LengthX() ; ++i)
+ for (int i=0 ; i<mv.LengthX() ; ++i)
{
//dmv[j*mv.LengthX() + i].x = mv[j][i].x;
//dmv[j*mv.LengthX() + i].y = mv[j][i].y;
@@ -108,11 +108,11 @@ void copy_mv(const MvArray& mv, dirac_mv_t *dmv)
}// j
}
-void copy_mv_cost(const TwoDArray<MvCostData> &pc, dirac_mv_cost_t *dpc)
+void copy_mv_cost (const TwoDArray<MvCostData> &pc, dirac_mv_cost_t *dpc)
{
- for(int j = 0 ; j < pc.LengthY() ; ++j)
+ for (int j=0 ; j<pc.LengthY() ; ++j)
{
- for(int i = 0 ; i < pc.LengthX() ; ++i)
+ for (int i=0 ; i<pc.LengthX() ; ++i)
{
//dpc[j*pc.LengthX() + i].SAD = pc[j][i].SAD;
//dpc[j*pc.LengthX() + i].mvcost = pc[j][i].mvcost;
@@ -129,41 +129,41 @@ void copy_mv_cost(const TwoDArray<MvCostData> &pc, dirac_mv_cost_t *dpc)
void alloc_instr_data(dirac_instr_t *instr)
{
instr->sb_split_mode = new int [instr->sb_ylen*instr->sb_xlen];
- memset(instr->sb_split_mode, 0, sizeof(int)*instr->sb_ylen * instr->sb_xlen);
+ memset (instr->sb_split_mode, 0, sizeof(int)*instr->sb_ylen*instr->sb_xlen);
instr->sb_costs = new float [instr->sb_ylen*instr->sb_xlen];
- memset(instr->sb_costs, 0, sizeof(float)*instr->sb_ylen * instr->sb_xlen);
+ memset (instr->sb_costs, 0, sizeof(float)*instr->sb_ylen*instr->sb_xlen);
instr->pred_mode = new int [instr->mv_ylen * instr->mv_xlen];
- memset(instr->pred_mode, 0, sizeof(int)*instr->mv_ylen * instr->mv_xlen);
+ memset (instr->pred_mode, 0, sizeof(int)*instr->mv_ylen*instr->mv_xlen);
instr->intra_costs = new float [instr->mv_ylen * instr->mv_xlen];
- memset(instr->intra_costs, 0, sizeof(float)*instr->mv_ylen * instr->mv_xlen);
+ memset (instr->intra_costs, 0, sizeof(float)*instr->mv_ylen*instr->mv_xlen);
instr->bipred_costs = new dirac_mv_cost_t [instr->mv_ylen * instr->mv_xlen];
- memset(instr->bipred_costs, 0, sizeof(dirac_mv_cost_t)*instr->mv_ylen * instr->mv_xlen);
+ memset (instr->bipred_costs, 0, sizeof(dirac_mv_cost_t)*instr->mv_ylen*instr->mv_xlen);
instr->dc_ycomp = new short [instr->mv_ylen * instr->mv_xlen];
- memset(instr->dc_ycomp, 0, sizeof(short)*instr->mv_ylen * instr->mv_xlen);
+ memset (instr->dc_ycomp, 0, sizeof(short)*instr->mv_ylen*instr->mv_xlen);
instr->dc_ucomp = new short [instr->mv_ylen * instr->mv_xlen];
- memset(instr->dc_ucomp, 0, sizeof(short)*instr->mv_ylen * instr->mv_xlen);
+ memset (instr->dc_ucomp, 0, sizeof(short)*instr->mv_ylen*instr->mv_xlen);
instr->dc_vcomp = new short [instr->mv_ylen * instr->mv_xlen];
- memset(instr->dc_vcomp, 0, sizeof(short)*instr->mv_ylen * instr->mv_xlen);
+ memset (instr->dc_vcomp, 0, sizeof(short)*instr->mv_ylen*instr->mv_xlen);
- for(int i = 0; i < 2; i++)
+ for (int i = 0; i < 2; i++)
{
instr->mv[i] = new dirac_mv_t[instr->mv_ylen * instr->mv_xlen];
- memset(instr->mv[i], 0,
- sizeof(dirac_mv_t)*instr->mv_ylen * instr->mv_xlen);
+ memset (instr->mv[i], 0,
+ sizeof(dirac_mv_t)*instr->mv_ylen*instr->mv_xlen);
}
- for(int i = 0; i < 2; i++)
+ for (int i = 0; i < 2; i++)
{
instr->pred_costs[i] = new dirac_mv_cost_t[instr->mv_ylen * instr->mv_xlen];
- memset(instr->pred_costs[i], 0,
- sizeof(dirac_mv_cost_t)*instr->mv_ylen * instr->mv_xlen);
+ memset (instr->pred_costs[i], 0,
+ sizeof(dirac_mv_cost_t)*instr->mv_ylen*instr->mv_xlen);
}
}
@@ -172,38 +172,38 @@ void alloc_instr_data(dirac_instr_t *instr)
*/
void dealloc_instr_data(dirac_instr_t *instr)
{
- if(instr->sb_split_mode)
+ if (instr->sb_split_mode)
delete [] instr->sb_split_mode;
- if(instr->sb_costs)
+ if (instr->sb_costs)
delete [] instr->sb_costs;
- if(instr->pred_mode)
+ if (instr->pred_mode)
delete [] instr->pred_mode;
- if(instr->intra_costs)
+ if (instr->intra_costs)
delete [] instr->intra_costs;
- if(instr->bipred_costs)
+ if (instr->bipred_costs)
delete [] instr->bipred_costs;
- if(instr->dc_ycomp)
+ if (instr->dc_ycomp)
delete [] instr->dc_ycomp;
- if(instr->dc_ucomp)
+ if (instr->dc_ucomp)
delete [] instr->dc_ucomp;
- if(instr->dc_vcomp)
+ if (instr->dc_vcomp)
delete [] instr->dc_vcomp;
- for(int i = 0; i < 2; i++)
+ for (int i = 0; i < 2; i++)
{
- if(instr->mv[i])
+ if (instr->mv[i])
delete [] instr->mv[i];
}
- for(int i = 0; i < 2; i++)
+ for (int i = 0; i < 2; i++)
{
- if(instr->pred_costs[i])
+ if (instr->pred_costs[i])
delete [] instr->pred_costs[i];
}
}
@@ -229,55 +229,39 @@ public:
int GetEncodedData(dirac_encoder_t *encoder);
// Set the locally decoded frame data in encoder
- int GetDecodedData(dirac_encoder_t *encoder);
+ int GetDecodedData (dirac_encoder_t *encoder);
// Set the instrumentation data in encoder
- void GetInstrumentationData(dirac_encoder_t *encoder);
+ void GetInstrumentationData (dirac_encoder_t *encoder);
// Set the end of sequence infomration in encoder
int GetSequenceEnd(dirac_encoder_t *encoder);
// Set the buffer to hold the locally decoded frame
- void SetDecodeBuffer(unsigned char *buffer, int buffer_size);
+ void SetDecodeBuffer (unsigned char *buffer, int buffer_size);
// Return the encoder parameters
- const EncoderParams& GetEncParams() const
- {
- return m_encparams;
- }
+ const EncoderParams& GetEncParams() const { return m_encparams; }
// Return the source parameters
- const SourceParams& GetSrcParams() const
- {
- return m_srcparams;
- }
+ const SourceParams& GetSrcParams() const { return m_srcparams; }
// Return the pts offset
- int GetPTSOffset() const
- {
- return m_seqcomp->PTSOffset();
- }
+ int GetPTSOffset() const { return m_seqcomp->PTSOffset(); }
// Signal End of Sequence
- void SignalEOS()
- {
- m_eos_signalled = true;
- m_seqcomp->SignalEOS();
- }
+ void SignalEOS() { m_eos_signalled = true; m_seqcomp->SignalEOS(); }
// End of Sequence
- bool EOS()
- {
- return m_eos_signalled == true;
- }
+ bool EOS() { return m_eos_signalled == true; }
private:
// Set the encoder parameters
- void SetEncoderParams(const dirac_encoder_context_t *enc_ctx);
+ void SetEncoderParams (const dirac_encoder_context_t *enc_ctx);
// Set the source parameters
- void SetSourceParams(const dirac_encoder_context_t *enc_ctx);
+ void SetSourceParams (const dirac_encoder_context_t *enc_ctx);
// Get the picture statistics
void GetPictureStats(dirac_encoder_t *encoder);
@@ -327,7 +311,7 @@ private:
// Output destination for compressed data in bitstream format
DiracByteStream m_dirac_byte_stream;
- //Rate Control parameters
+ //Rate Control parameters
// Total Number of bits for a GOP
int m_gop_bits;
@@ -351,13 +335,13 @@ private:
SequenceCompressor constructor. It is called by the
FrameCompressor::Compress function once the frame is successfully compressed
*/
-void DiracEncoder::GetInstrumentationData(dirac_encoder_t *encoder)
+void DiracEncoder::GetInstrumentationData (dirac_encoder_t *encoder)
{
- ASSERT(encoder != NULL);
+ ASSERT (encoder != NULL);
dirac_instr_t *instr = &encoder->instr;
dirac_instr_t old_instr = *instr;
- if(!m_return_instr_data || m_enc_picture == NULL)
+ if (!m_return_instr_data || m_enc_picture == NULL)
return;
const PictureParams& pparams = m_enc_picture->GetPparams();
@@ -369,19 +353,19 @@ void DiracEncoder::GetInstrumentationData(dirac_encoder_t *encoder)
instr->num_refs = 0;
encoder->instr_data_avail = 1;
- if(psort.IsIntra())
+ if (psort.IsIntra())
{
// no MV data for Intra coded data
return;
}
- TESTM(m_enc_medata != NULL, "ME data available");
+ TESTM (m_enc_medata != NULL, "ME data available");
// Reference info
instr->num_refs = pparams.Refs().size();
- ASSERTM(instr->num_refs <= 2, "Max # reference frames is 2");
+ ASSERTM (instr->num_refs <= 2, "Max # reference frames is 2");
- for(int i = 0; i < instr->num_refs; ++i)
+ for (int i=0; i<instr->num_refs; ++i)
instr->refs[i] = pparams.Refs()[i];
// Block separation params
@@ -396,36 +380,36 @@ void DiracEncoder::GetInstrumentationData(dirac_encoder_t *encoder)
instr->mv_ylen = m_enc_medata->Vectors(1).LengthY();
instr->mv_xlen = m_enc_medata->Vectors(1).LengthX();
- if(old_instr.sb_ylen != instr->sb_ylen ||
- old_instr.sb_xlen != instr->sb_xlen ||
- old_instr.mv_ylen != instr->mv_ylen ||
- old_instr.mv_xlen != instr->mv_xlen)
+ if (old_instr.sb_ylen != instr->sb_ylen ||
+ old_instr.sb_xlen != instr->sb_xlen ||
+ old_instr.mv_ylen != instr->mv_ylen ||
+ old_instr.mv_xlen != instr->mv_xlen)
{
dealloc_instr_data(instr);
alloc_instr_data(instr);
}
- copy_2dArray(m_enc_medata->SBSplit(), instr->sb_split_mode);
- copy_2dArray(m_enc_medata->SBCosts(), instr->sb_costs);
- copy_2dArray(m_enc_medata->Mode(), instr->pred_mode);
- copy_2dArray(m_enc_medata->IntraCosts(), instr->intra_costs);
+ copy_2dArray (m_enc_medata->SBSplit(), instr->sb_split_mode);
+ copy_2dArray (m_enc_medata->SBCosts(), instr->sb_costs);
+ copy_2dArray (m_enc_medata->Mode(), instr->pred_mode);
+ copy_2dArray (m_enc_medata->IntraCosts(), instr->intra_costs);
- if(instr->num_refs > 1)
+ if (instr->num_refs > 1)
{
- copy_mv_cost(m_enc_medata->BiPredCosts(), instr->bipred_costs);
+ copy_mv_cost (m_enc_medata->BiPredCosts(), instr->bipred_costs);
}
- copy_2dArray(m_enc_medata->DC(Y_COMP), instr->dc_ycomp);
- if(m_enc_medata->DC().Length() == 3)
+ copy_2dArray (m_enc_medata->DC( Y_COMP ), instr->dc_ycomp);
+ if (m_enc_medata->DC().Length() == 3)
{
- copy_2dArray(m_enc_medata->DC(U_COMP), instr->dc_ucomp);
- copy_2dArray(m_enc_medata->DC(V_COMP), instr->dc_vcomp);
+ copy_2dArray (m_enc_medata->DC( U_COMP ), instr->dc_ucomp);
+ copy_2dArray (m_enc_medata->DC( V_COMP ), instr->dc_vcomp);
}
- for(int i = 1; i <= instr->num_refs; ++i)
+ for (int i=1; i<=instr->num_refs; ++i)
{
- copy_mv(m_enc_medata->Vectors(i), instr->mv[i-1]);
- copy_mv_cost(m_enc_medata->PredCosts(i), instr->pred_costs[i-1]);
+ copy_mv (m_enc_medata->Vectors(i), instr->mv[i-1]);
+ copy_mv_cost (m_enc_medata->PredCosts(i), instr->pred_costs[i-1]);
}
}
@@ -441,16 +425,16 @@ DiracEncoder::DiracEncoder(const dirac_encoder_context_t *enc_ctx,
m_dec_bufsize(0),
m_return_decoded_pictures(enc_ctx->decode_flag > 0),
m_return_instr_data(enc_ctx->instr_flag > 0),
- m_gop_bits(0),
+ m_gop_bits(0),
m_gop_count(0),
m_picture_count(0),
m_eos_signalled(false)
{
// Setup source parameters
- SetSourceParams(enc_ctx);
+ SetSourceParams (enc_ctx);
// Setup encoder parameters
- m_encparams.SetVerbose(verbose);
- SetEncoderParams(enc_ctx);
+ m_encparams.SetVerbose( verbose );
+ SetEncoderParams (enc_ctx);
// Set up the input data stream (uncompressed data)
m_inp_ptr = new MemoryStreamInput(m_srcparams, m_encparams.FieldCoding());
@@ -458,17 +442,17 @@ DiracEncoder::DiracEncoder(const dirac_encoder_context_t *enc_ctx,
m_out_ptr = new MemoryStreamOutput(m_srcparams, m_encparams.FieldCoding());
// initialise the sequence compressor
- if(!m_encparams.FieldCoding())
+ if (!m_encparams.FieldCoding())
{
- m_seqcomp = new FrameSequenceCompressor(m_inp_ptr->GetStream(), m_encparams, m_dirac_byte_stream);
+ m_seqcomp = new FrameSequenceCompressor (m_inp_ptr->GetStream(), m_encparams, m_dirac_byte_stream);
}
else
{
- m_seqcomp = new FieldSequenceCompressor(m_inp_ptr->GetStream(), m_encparams, m_dirac_byte_stream);
+ m_seqcomp = new FieldSequenceCompressor (m_inp_ptr->GetStream(), m_encparams, m_dirac_byte_stream);
}
}
-void DiracEncoder::SetDecodeBuffer(unsigned char *buffer, int buffer_size)
+void DiracEncoder::SetDecodeBuffer (unsigned char *buffer, int buffer_size)
{
m_dec_buf = buffer;
m_dec_bufsize = buffer_size;
@@ -482,29 +466,29 @@ DiracEncoder::~DiracEncoder()
delete m_out_ptr;
}
-void DiracEncoder::SetSourceParams(const dirac_encoder_context_t *enc_ctx)
+void DiracEncoder::SetSourceParams (const dirac_encoder_context_t *enc_ctx)
{
- m_srcparams.SetCFormat(enc_ctx->src_params.chroma);
- m_srcparams.SetXl(enc_ctx->src_params.width);
- m_srcparams.SetYl(enc_ctx->src_params.height);
-
- m_srcparams.SetCleanWidth(m_srcparams.Xl());
- m_srcparams.SetCleanHeight(m_srcparams.Yl());
- m_srcparams.SetLeftOffset(0);
- m_srcparams.SetTopOffset(0);
-
- m_srcparams.SetSourceSampling(enc_ctx->src_params.source_sampling);
- if(m_srcparams.FrameRate().m_num != (unsigned int)enc_ctx->src_params.frame_rate.numerator ||
- m_srcparams.FrameRate().m_denom != (unsigned int)enc_ctx->src_params.frame_rate.denominator)
+ m_srcparams.SetCFormat( enc_ctx->src_params.chroma );
+ m_srcparams.SetXl( enc_ctx->src_params.width );
+ m_srcparams.SetYl( enc_ctx->src_params.height );
+
+ m_srcparams.SetCleanWidth( m_srcparams.Xl() );
+ m_srcparams.SetCleanHeight( m_srcparams.Yl() );
+ m_srcparams.SetLeftOffset( 0 );
+ m_srcparams.SetTopOffset( 0 );
+
+ m_srcparams.SetSourceSampling( enc_ctx->src_params.source_sampling );
+ if (m_srcparams.FrameRate().m_num != (unsigned int)enc_ctx->src_params.frame_rate.numerator ||
+ m_srcparams.FrameRate().m_denom != (unsigned int)enc_ctx->src_params.frame_rate.denominator)
{
- m_srcparams.SetFrameRate(enc_ctx->src_params.frame_rate.numerator,
- enc_ctx->src_params.frame_rate.denominator);
+ m_srcparams.SetFrameRate( enc_ctx->src_params.frame_rate.numerator,
+ enc_ctx->src_params.frame_rate.denominator );
}
- if(m_srcparams.PixelAspectRatio().m_num != (unsigned int)enc_ctx->src_params.pix_asr.numerator ||
- m_srcparams.PixelAspectRatio().m_denom != (unsigned int)enc_ctx->src_params.pix_asr.denominator)
+ if (m_srcparams.PixelAspectRatio().m_num != (unsigned int)enc_ctx->src_params.pix_asr.numerator ||
+ m_srcparams.PixelAspectRatio().m_denom != (unsigned int)enc_ctx->src_params.pix_asr.denominator)
{
- m_srcparams.SetPixelAspectRatio(enc_ctx->src_params.pix_asr.numerator,
- enc_ctx->src_params.pix_asr.denominator);
+ m_srcparams.SetPixelAspectRatio( enc_ctx->src_params.pix_asr.numerator,
+ enc_ctx->src_params.pix_asr.denominator );
}
// TO DO: CLEAN AREA and signal range
// FIXME: Dirac currently support 8BIT_VIDEO only. Accept from command line
@@ -513,18 +497,18 @@ void DiracEncoder::SetSourceParams(const dirac_encoder_context_t *enc_ctx)
}
-void DiracEncoder::SetEncoderParams(const dirac_encoder_context_t *enc_ctx)
+void DiracEncoder::SetEncoderParams (const dirac_encoder_context_t *enc_ctx)
{
- TEST(enc_ctx != NULL);
+ TEST (enc_ctx != NULL);
OLBParams bparams(12, 12, 8, 8);
m_encparams.SetLocalDecode(enc_ctx->decode_flag);
- m_encparams.SetXl(enc_ctx->src_params.width);
- m_encparams.SetYl(enc_ctx->src_params.height);
- m_encparams.SetChromaXl(enc_ctx->src_params.chroma_width);
- m_encparams.SetChromaYl(enc_ctx->src_params.chroma_height);
+ m_encparams.SetXl( enc_ctx->src_params.width );
+ m_encparams.SetYl( enc_ctx->src_params.height );
+ m_encparams.SetChromaXl( enc_ctx->src_params.chroma_width );
+ m_encparams.SetChromaYl( enc_ctx->src_params.chroma_height );
- if(enc_ctx->enc_params.picture_coding_mode > 1)
+ if (enc_ctx->enc_params.picture_coding_mode > 1)
{
std::ostringstream errstr;
@@ -538,19 +522,19 @@ void DiracEncoder::SetEncoderParams(const dirac_encoder_context_t *enc_ctx)
}
m_encparams.SetPictureCodingMode(enc_ctx->enc_params.picture_coding_mode);
- if(m_encparams.FieldCoding())
+ if (m_encparams.FieldCoding())
{
// Change coding dimensions to field dimensions
- m_encparams.SetYl(enc_ctx->src_params.height >> 1);
- m_encparams.SetChromaYl(enc_ctx->src_params.chroma_height >> 1);
+ m_encparams.SetYl( enc_ctx->src_params.height>>1 );
+ m_encparams.SetChromaYl( enc_ctx->src_params.chroma_height >> 1);
}
- unsigned int luma_depth = static_cast<unsigned int>(
- std::log((double)m_srcparams.LumaExcursion()) / std::log(2.0) + 1);
+ unsigned int luma_depth = static_cast<unsigned int> (
+ std::log((double)m_srcparams.LumaExcursion())/std::log(2.0) + 1 );
m_encparams.SetLumaDepth(luma_depth);
- unsigned int chroma_depth = static_cast<unsigned int>(
- std::log((double)m_srcparams.ChromaExcursion()) / std::log(2.0) + 1);
+ unsigned int chroma_depth = static_cast<unsigned int> (
+ std::log((double)m_srcparams.ChromaExcursion())/std::log(2.0) + 1 );
m_encparams.SetChromaDepth(chroma_depth);
m_encparams.SetFullSearch(enc_ctx->enc_params.full_search);
@@ -569,24 +553,24 @@ void DiracEncoder::SetEncoderParams(const dirac_encoder_context_t *enc_ctx)
m_encparams.SetVFactor(0.75f);
m_encparams.GetPicPredParams().SetMVPrecision(enc_ctx->enc_params.mv_precision);
m_encparams.SetUsingAC(enc_ctx->enc_params.using_ac);
- bparams.SetYblen(enc_ctx->enc_params.yblen);
- bparams.SetXblen(enc_ctx->enc_params.xblen);
- bparams.SetYbsep(enc_ctx->enc_params.ybsep);
- bparams.SetXbsep(enc_ctx->enc_params.xbsep);
+ bparams.SetYblen( enc_ctx->enc_params.yblen );
+ bparams.SetXblen( enc_ctx->enc_params.xblen );
+ bparams.SetYbsep( enc_ctx->enc_params.ybsep );
+ bparams.SetXbsep( enc_ctx->enc_params.xbsep );
// Now rationalise the GOP options
// this stuff should really be done in a constructor!
- if(m_encparams.NumL1() < 0)
+ if (m_encparams.NumL1()<0)
{
//don't have a proper GOP
- m_encparams.SetL1Sep(std::max(1 , m_encparams.L1Sep()));
+ m_encparams.SetL1Sep( std::max(1 , m_encparams.L1Sep()) );
}
- else if(m_encparams.NumL1() == 0)
+ else if (m_encparams.NumL1() == 0)
{
//have I-frame only coding
m_encparams.SetL1Sep(0);
}
- m_encparams.GetPicPredParams().SetBlockSizes(bparams , enc_ctx->src_params.chroma);
+ m_encparams.GetPicPredParams().SetBlockSizes( bparams , enc_ctx->src_params.chroma );
// Set transforms parameters
m_encparams.SetIntraTransformFilter(enc_ctx->enc_params.intra_wlt_filter);
@@ -598,53 +582,51 @@ void DiracEncoder::SetEncoderParams(const dirac_encoder_context_t *enc_ctx)
}
-bool DiracEncoder::LoadNextFrame(unsigned char *data, int size)
+bool DiracEncoder::LoadNextFrame (unsigned char *data, int size)
{
- TESTM(m_seqcomp->Finished() != true, "Did not reach end of sequence");
+ TESTM (m_seqcomp->Finished() != true, "Did not reach end of sequence");
m_inp_ptr->SetMembufReference(data, size);
- if(m_seqcomp->LoadNextFrame())
+ if (m_seqcomp->LoadNextFrame())
{
- if(!m_encparams.FieldCoding())
+ if (!m_encparams.FieldCoding())
m_num_loaded_pictures++;
else
- m_num_loaded_pictures += 2;
+ m_num_loaded_pictures+=2;
return true;
}
return false;
}
-int DiracEncoder::CompressNextPicture()
+int DiracEncoder::CompressNextPicture ()
{
- TESTM(m_seqcomp->Finished() != true, "Did not reach end of sequence");
+ TESTM (m_seqcomp->Finished() != true, "Did not reach end of sequence");
- if(!m_num_loaded_pictures)
+ if (!m_num_loaded_pictures)
return 0;
const EncPicture *mypicture = m_seqcomp->CompressNextPicture();
m_decpnum = -1;
- if(mypicture)
- {
+ if (mypicture){
m_enc_picture = m_seqcomp->GetPictureEncoded();
- if(m_enc_picture->GetPparams().PicSort().IsIntra() == false)
+ if (m_enc_picture->GetPparams().PicSort().IsIntra()==false)
m_enc_medata = &m_enc_picture->GetMEData();
- else
- m_enc_medata = NULL;
+ else
+ m_enc_medata = NULL;
- if(m_return_decoded_pictures &&
- mypicture->GetPparams().PictureNum() != m_show_pnum)
- {
+ if (m_return_decoded_pictures &&
+ mypicture->GetPparams().PictureNum() != m_show_pnum){
int ret_val;
m_show_pnum = mypicture->GetPparams().PictureNum();
- TEST(!(m_return_decoded_pictures && !m_dec_buf));
- if(m_return_decoded_pictures && m_dec_buf)
+ TEST (! (m_return_decoded_pictures && !m_dec_buf) );
+ if (m_return_decoded_pictures && m_dec_buf)
{
// write locally decoded picture to decode buffer
m_out_ptr->SetMembufReference(m_dec_buf, m_dec_bufsize);
ret_val = m_out_ptr->GetStream()->WriteToNextFrame(*mypicture);
- if(ret_val)
+ if (ret_val)
{
m_decpnum = m_show_pnum;
m_decpsort = mypicture->GetPparams().PicSort();
@@ -652,8 +634,7 @@ int DiracEncoder::CompressNextPicture()
}
}
}
- else
- {
+ else{
m_enc_picture = NULL;
m_enc_medata = NULL;
}
@@ -661,10 +642,9 @@ int DiracEncoder::CompressNextPicture()
if(!m_dirac_byte_stream.IsUnitAvailable())
return 0;
- if(mypicture)
- {
- m_num_coded_pictures++;
- TESTM(m_enc_picture != 0, "Encoder picture available");
+ if (mypicture){
+ m_num_coded_pictures++;
+ TESTM (m_enc_picture != 0, "Encoder picture available");
}
return 1;
}
@@ -676,35 +656,35 @@ void DiracEncoder::GetPictureStats(dirac_encoder_t *encoder)
DiracByteStats dirac_byte_stats = m_dirac_byte_stream.GetLastUnitStats();
pstats->mv_bits = dirac_byte_stats.GetBitCount(STAT_MV_BYTE_COUNT);
- // pstats->mv_hdr_bits = poutput.MVBytes() * 8;
+ // pstats->mv_hdr_bits = poutput.MVBytes() * 8;
pstats->ycomp_bits = dirac_byte_stats.GetBitCount(STAT_YCOMP_BYTE_COUNT);
- // pstats->ycomp_hdr_bits = poutput.ComponentHeadBytes( Y_COMP ) * 8;
+ // pstats->ycomp_hdr_bits = poutput.ComponentHeadBytes( Y_COMP ) * 8;
pstats->ucomp_bits = dirac_byte_stats.GetBitCount(STAT_UCOMP_BYTE_COUNT);
- // pstats->ucomp_hdr_bits = poutput.ComponentHeadBytes( U_COMP ) * 8;
+ // pstats->ucomp_hdr_bits = poutput.ComponentHeadBytes( U_COMP ) * 8;
pstats->vcomp_bits = dirac_byte_stats.GetBitCount(STAT_VCOMP_BYTE_COUNT);
- // pstats->vcomp_hdr_bits = poutput.ComponentHeadBytes( V_COMP ) * 8;
+ // pstats->vcomp_hdr_bits = poutput.ComponentHeadBytes( V_COMP ) * 8;
pstats->pic_bits = dirac_byte_stats.GetBitCount(STAT_TOTAL_BYTE_COUNT);
- // pstats->pic_hdr_bits = poutput.PictureHeadBytes() * 8;
+ // pstats->pic_hdr_bits = poutput.PictureHeadBytes() * 8;
DiracEncoder *compressor = (DiracEncoder *)encoder->compressor;
- if(compressor->GetEncParams().Verbose())
+ if (compressor->GetEncParams().Verbose())
{
- std::cout << std::endl << "Number of MV bits=" << pstats->mv_bits;
- std::cout << std::endl << "Number of bits for Y=" << pstats->ycomp_bits;
- std::cout << std::endl << "Number of bits for U=" << pstats->ucomp_bits;
- std::cout << std::endl << "Number of bits for V=" << pstats->vcomp_bits;
- if(m_encparams.FieldCoding())
- std::cout << std::endl << "Total field bits=" << pstats->pic_bits;
+ std::cout<<std::endl<<"Number of MV bits="<<pstats->mv_bits;
+ std::cout<<std::endl<<"Number of bits for Y="<<pstats->ycomp_bits;
+ std::cout<<std::endl<<"Number of bits for U="<<pstats->ucomp_bits;
+ std::cout<<std::endl<<"Number of bits for V="<<pstats->vcomp_bits;
+ if (m_encparams.FieldCoding())
+ std::cout<<std::endl<<"Total field bits="<<pstats->pic_bits;
else
- std::cout << std::endl << "Total frame bits=" << pstats->pic_bits;
+ std::cout<<std::endl<<"Total frame bits="<<pstats->pic_bits;
}
}
-int DiracEncoder::GetEncodedData(dirac_encoder_t *encoder)
+int DiracEncoder::GetEncodedData (dirac_encoder_t *encoder)
{
int size = 0;
dirac_enc_data_t *encdata = &encoder->enc_buf;
@@ -712,14 +692,14 @@ int DiracEncoder::GetEncodedData(dirac_encoder_t *encoder)
string output = m_dirac_byte_stream.GetBytes();
size = output.size();
//std::cout << std::endl << "ParseUnit size=" << size << std::endl;
- if(size > 0)
+ if (size > 0)
{
- if(encdata->size < size)
+ if (encdata->size < size )
{
return -1;
}
- memmove(encdata->buffer, output.c_str(), output.size());
- if(m_enc_picture)
+ memmove (encdata->buffer, output.c_str(), output.size());
+ if (m_enc_picture)
{
// picture data
encoder->enc_pparams.pnum = m_enc_picture->GetPparams().PictureNum();
@@ -727,29 +707,29 @@ int DiracEncoder::GetEncodedData(dirac_encoder_t *encoder)
encoder->enc_pparams.rtype = m_enc_picture->GetPparams().PicSort().IsRef() ? REFERENCE_PICTURE : NON_REFERENCE_PICTURE;
// Get frame statistics
- GetPictureStats(encoder);
- if(m_encparams.Verbose() && encoder->enc_ctx.enc_params.picture_coding_mode == 1)
+ GetPictureStats (encoder);
+ if(m_encparams.Verbose() && encoder->enc_ctx.enc_params.picture_coding_mode==1)
{
- if(encoder->enc_pparams.pnum % 2 == 0)
+ if (encoder->enc_pparams.pnum%2 == 0)
m_field1_stats = encoder->enc_pstats;
else
{
- std::cout << std::endl << std::endl
- << "Frame " << encoder->enc_pparams.pnum / 2;
- std::cout << " stats";
- std::cout << std::endl << "Number of MV bits=";
- std::cout << m_field1_stats.mv_bits + encoder->enc_pstats.mv_bits;
- std::cout << std::endl << "Number of bits for Y=";
- std::cout << m_field1_stats.ycomp_bits + encoder->enc_pstats.ycomp_bits;
- std::cout << std::endl << "Number of bits for U=";
- std::cout << m_field1_stats.ucomp_bits + encoder->enc_pstats.ucomp_bits;
- std::cout << std::endl << "Number of bits for V=";
- std::cout << m_field1_stats.vcomp_bits + encoder->enc_pstats.vcomp_bits;
+ std::cout<<std::endl<<std::endl
+ <<"Frame "<<encoder->enc_pparams.pnum/2;
+ std::cout<< " stats";
+ std::cout<<std::endl<< "Number of MV bits=";
+ std::cout<< m_field1_stats.mv_bits + encoder->enc_pstats.mv_bits;
+ std::cout<< std::endl << "Number of bits for Y=";
+ std::cout<< m_field1_stats.ycomp_bits + encoder->enc_pstats.ycomp_bits;
+ std::cout<< std::endl << "Number of bits for U=";
+ std::cout<< m_field1_stats.ucomp_bits + encoder->enc_pstats.ucomp_bits;
+ std::cout<< std::endl << "Number of bits for V=";
+ std::cout<< m_field1_stats.vcomp_bits + encoder->enc_pstats.vcomp_bits;
std::cout << std::endl << "Total frame bits=";
- std::cout << m_field1_stats.pic_bits + encoder->enc_pstats.pic_bits;
+ std::cout<< m_field1_stats.pic_bits + encoder->enc_pstats.pic_bits;
}
}
- }
+ }
else
{
// Not picture data
@@ -765,51 +745,51 @@ int DiracEncoder::GetEncodedData(dirac_encoder_t *encoder)
encdata->size = 0;
}
- if(m_enc_picture)
+ if (m_enc_picture)
{
- //Rate Control - work out bit rate to date and for current GOP
- // and keep track of frame numbers
- int interlace_factor = m_encparams.FieldCoding() ? 2 : 1;
- int num_L1 = encoder->enc_ctx.enc_params.num_L1;
- int L1_sep = encoder->enc_ctx.enc_params.L1_sep;
-
- // Length of the GOP in pictures - twice as many if fields
- int GOP_pic_length = (num_L1 + 1) * L1_sep * interlace_factor;
+ //Rate Control - work out bit rate to date and for current GOP
+ // and keep track of frame numbers
+ int interlace_factor = m_encparams.FieldCoding() ? 2 : 1;
+ int num_L1 = encoder->enc_ctx.enc_params.num_L1;
+ int L1_sep = encoder->enc_ctx.enc_params.L1_sep;
- int offset;
- if(num_L1 == 0)
- {
- GOP_pic_length = 10;
- offset = 0;
- }
- else
- offset = std::max(L1_sep - 1, 0) * interlace_factor;
+ // Length of the GOP in pictures - twice as many if fields
+ int GOP_pic_length = (num_L1+1)*L1_sep*interlace_factor;
- m_gop_bits += encoder->enc_pstats.pic_bits;
- m_picture_count++;
+ int offset;
+ if (num_L1 == 0)
+ {
+ GOP_pic_length = 10;
+ offset = 0;
+ }
+ else
+ offset = std::max(L1_sep-1,0)*interlace_factor;
- if((m_gop_count == 0 && m_picture_count == GOP_pic_length - offset) ||
- (m_gop_count > 0 && m_picture_count == GOP_pic_length))
- {
- int denominator = encoder->enc_ctx.src_params.frame_rate.denominator;
- int numerator = encoder->enc_ctx.src_params.frame_rate.numerator;
- double frame_rate = (double)numerator / (double)denominator;
+ m_gop_bits += encoder->enc_pstats.pic_bits;
+ m_picture_count++;
- double gop_duration = double(m_picture_count) / interlace_factor / frame_rate;
- double bit_rate = double(m_gop_bits) / gop_duration;
+ if ( (m_gop_count==0 && m_picture_count == GOP_pic_length-offset) ||
+ (m_gop_count>0 && m_picture_count == GOP_pic_length))
+ {
+ int denominator = encoder->enc_ctx.src_params.frame_rate.denominator;
+ int numerator = encoder->enc_ctx.src_params.frame_rate.numerator;
+ double frame_rate = (double)numerator/(double)denominator;
- DiracEncoder *compressor = (DiracEncoder *)encoder->compressor;
- if(compressor->GetEncParams().Verbose())
- {
- std::cout << std::endl << std::endl << "Bit Rate for GOP number ";
- std::cout << m_gop_count << " is " << bit_rate / 1000.0 << " kbps" << std::endl;
- }
+ double gop_duration = double(m_picture_count)/interlace_factor/frame_rate;
+ double bit_rate = double(m_gop_bits)/gop_duration;
- m_gop_count++;
- m_gop_bits = 0;
- m_picture_count = 0;
+ DiracEncoder *compressor = (DiracEncoder *)encoder->compressor;
+ if (compressor->GetEncParams().Verbose())
+ {
+ std::cout<<std::endl<<std::endl<<"Bit Rate for GOP number ";
+ std::cout<<m_gop_count<<" is "<<bit_rate/1000.0<<" kbps"<<std::endl;
}
- //End of Rate Control
+
+ m_gop_count++;
+ m_gop_bits = 0;
+ m_picture_count = 0;
+ }
+ //End of Rate Control
}
m_dirac_byte_stream.Clear();
@@ -817,12 +797,12 @@ int DiracEncoder::GetEncodedData(dirac_encoder_t *encoder)
return size;
}
-int DiracEncoder::GetDecodedData(dirac_encoder_t *encoder)
+int DiracEncoder::GetDecodedData (dirac_encoder_t *encoder)
{
dirac_picparams_t *pp = &encoder->dec_pparams;
int ret_stat = (m_decpnum != -1);
- if(m_return_decoded_pictures && m_decpnum != -1)
+ if (m_return_decoded_pictures && m_decpnum != -1)
{
pp->ptype = m_decpsort.IsIntra() ? INTRA_PICTURE : INTER_PICTURE;
pp->rtype = m_decpsort.IsRef() ? REFERENCE_PICTURE : NON_REFERENCE_PICTURE;
@@ -845,36 +825,36 @@ void DiracEncoder::GetSequenceStats(dirac_encoder_t *encoder,
sstats->vcomp_bits = dirac_seq_stats.GetBitCount(STAT_VCOMP_BYTE_COUNT);
sstats->bit_rate = int64_t((sstats->seq_bits *
- (double)m_srcparams.FrameRate().m_num) /
- (m_srcparams.FrameRate().m_denom * m_num_coded_pictures));
- if(encoder->enc_ctx.enc_params.picture_coding_mode == 1)
+ (double)m_srcparams.FrameRate().m_num)/
+ (m_srcparams.FrameRate().m_denom * m_num_coded_pictures));
+ if (encoder->enc_ctx.enc_params.picture_coding_mode==1)
sstats->bit_rate *= 2;
DiracEncoder *compressor = (DiracEncoder *)encoder->compressor;
- if(compressor->GetEncParams().Verbose())
+ if (compressor->GetEncParams().Verbose())
{
- std::cout << std::endl << std::endl << "Total bits for sequence=" << sstats->seq_bits;
- std::cout << std::endl << "Of these: " << std::endl;
- std::cout << std::endl << sstats->ycomp_bits << " were Y, ";
- std::cout << std::endl << sstats->ucomp_bits << " were U, ";
- std::cout << std::endl << sstats->vcomp_bits << " were V, and ";
- std::cout << std::endl << sstats->mv_bits << " were motion vector data.";
+ std::cout<<std::endl<<std::endl<<"Total bits for sequence="<<sstats->seq_bits;
+ std::cout<<std::endl<<"Of these: "<<std::endl;
+ std::cout<<std::endl<<sstats->ycomp_bits <<" were Y, ";
+ std::cout<<std::endl<<sstats->ucomp_bits <<" were U, ";
+ std::cout<<std::endl<<sstats->vcomp_bits<<" were V, and ";
+ std::cout<<std::endl<<sstats->mv_bits<<" were motion vector data.";
}
}
-int DiracEncoder::GetSequenceEnd(dirac_encoder_t *encoder)
+int DiracEncoder::GetSequenceEnd (dirac_encoder_t *encoder)
{
dirac_enc_data_t *encdata = &encoder->enc_buf;
- DiracByteStats dirac_seq_stats = m_seqcomp->EndSequence();
+ DiracByteStats dirac_seq_stats=m_seqcomp->EndSequence();
string output = m_dirac_byte_stream.GetBytes();
int size = output.size();
- if(size > 0)
+ if (size > 0)
{
- if(encdata->size < size)
+ if (encdata->size < size )
{
return -1;
}
- memmove(encdata->buffer, output.c_str(), size);
+ memmove (encdata->buffer, output.c_str(), size);
GetSequenceStats(encoder,
dirac_seq_stats);
encdata->size = size;
@@ -887,61 +867,61 @@ int DiracEncoder::GetSequenceEnd(dirac_encoder_t *encoder)
return size;
}
-static bool InitialiseEncoder(const dirac_encoder_context_t *enc_ctx, bool verbose, dirac_encoder_t *encoder)
+static bool InitialiseEncoder (const dirac_encoder_context_t *enc_ctx, bool verbose, dirac_encoder_t *encoder)
{
- TEST(enc_ctx != NULL);
- TEST(encoder != NULL);
+ TEST (enc_ctx != NULL);
+ TEST (encoder != NULL);
- if(enc_ctx->src_params.width == 0 || enc_ctx->src_params.height == 0)
+ if (enc_ctx->src_params.width == 0 || enc_ctx->src_params.height == 0)
return false;
- if(enc_ctx->src_params.chroma < format444 ||
- enc_ctx->src_params.chroma >= formatNK)
+ if (enc_ctx->src_params.chroma < format444 ||
+ enc_ctx->src_params.chroma >= formatNK)
return false;
- if(!enc_ctx->src_params.frame_rate.numerator ||
- !enc_ctx->src_params.frame_rate.denominator)
+ if (!enc_ctx->src_params.frame_rate.numerator ||
+ !enc_ctx->src_params.frame_rate.denominator)
return false;
- memmove(&encoder->enc_ctx, enc_ctx, sizeof(dirac_encoder_context_t));
+ memmove (&encoder->enc_ctx, enc_ctx, sizeof(dirac_encoder_context_t));
encoder->dec_buf.id = 0;
- switch(enc_ctx->src_params.chroma)
+ switch ( enc_ctx->src_params.chroma )
{
case format420:
- encoder->enc_ctx.src_params.chroma_width = enc_ctx->src_params.width / 2;
- encoder->enc_ctx.src_params.chroma_height = enc_ctx->src_params.height / 2;
- break;
+ encoder->enc_ctx.src_params.chroma_width = enc_ctx->src_params.width/2;
+ encoder->enc_ctx.src_params.chroma_height = enc_ctx->src_params.height/2;
+ break;
case format422:
- encoder->enc_ctx.src_params.chroma_width = enc_ctx->src_params.width / 2;
- encoder->enc_ctx.src_params.chroma_height = enc_ctx->src_params.height;
- break;
+ encoder->enc_ctx.src_params.chroma_width = enc_ctx->src_params.width/2;
+ encoder->enc_ctx.src_params.chroma_height = enc_ctx->src_params.height;
+ break;
case format444:
default:
- encoder->enc_ctx.src_params.chroma_width = enc_ctx->src_params.width;
- encoder->enc_ctx.src_params.chroma_height = enc_ctx->src_params.height;
- break;
+ encoder->enc_ctx.src_params.chroma_width = enc_ctx->src_params.width;
+ encoder->enc_ctx.src_params.chroma_height = enc_ctx->src_params.height;
+ break;
}
try
{
- DiracEncoder *comp = new DiracEncoder(&encoder->enc_ctx, verbose);
+ DiracEncoder *comp = new DiracEncoder (&encoder->enc_ctx, verbose);
encoder->compressor = comp;
- if(encoder->enc_ctx.decode_flag)
+ if (encoder->enc_ctx.decode_flag)
{
- int bufsize = (encoder->enc_ctx.src_params.width * encoder->enc_ctx.src_params.height) + 2 * (encoder->enc_ctx.src_params.chroma_width * encoder->enc_ctx.src_params.chroma_height);
+ int bufsize = (encoder->enc_ctx.src_params.width * encoder->enc_ctx.src_params.height)+ 2*(encoder->enc_ctx.src_params.chroma_width*encoder->enc_ctx.src_params.chroma_height);
encoder->dec_buf.buf[0] = new unsigned char [bufsize];
encoder->dec_buf.buf[1] = encoder->dec_buf.buf[0] +
- (encoder->enc_ctx.src_params.width * encoder->enc_ctx.src_params.height);
+ (encoder->enc_ctx.src_params.width * encoder->enc_ctx.src_params.height);
encoder->dec_buf.buf[2] = encoder->dec_buf.buf[1] +
- (encoder->enc_ctx.src_params.chroma_width * encoder->enc_ctx.src_params.chroma_height);
+ (encoder->enc_ctx.src_params.chroma_width*encoder->enc_ctx.src_params.chroma_height);
- comp->SetDecodeBuffer(encoder->dec_buf.buf[0], bufsize);
+ comp->SetDecodeBuffer (encoder->dec_buf.buf[0], bufsize);
}
}
- catch(...)
+ catch (...)
{
return false;
}
@@ -949,9 +929,9 @@ static bool InitialiseEncoder(const dirac_encoder_context_t *enc_ctx, bool verbo
}
static void SetSourceParameters(dirac_encoder_context_t *enc_ctx,
- const VideoFormat& video_format)
+ const VideoFormat& video_format)
{
- TEST(enc_ctx != NULL);
+ TEST (enc_ctx != NULL);
dirac_sourceparams_t &src_params = enc_ctx->src_params;
// create object containing sequence params
@@ -978,7 +958,7 @@ static void SetSourceParameters(dirac_encoder_context_t *enc_ctx,
static void SetEncoderParameters(dirac_encoder_context_t *enc_ctx,
const VideoFormat& video_format)
{
- TEST(enc_ctx != NULL);
+ TEST (enc_ctx != NULL);
dirac_encparams_t &encparams = enc_ctx->enc_params;
encparams.video_format = static_cast<int>(video_format);
@@ -1033,165 +1013,165 @@ static void SetEncoderParameters(dirac_encoder_context_t *enc_ctx,
extern "C" {
#endif
- extern DllExport void dirac_encoder_context_init(dirac_encoder_context_t *enc_ctx, dirac_encoder_presets_t preset)
- {
- TEST(enc_ctx != NULL);
- memset(enc_ctx, 0, sizeof(dirac_encoder_context_t));
-
- // preset is the video format
- int ps = static_cast<int>(preset);
- VideoFormat video_format(static_cast<VideoFormat>(ps));
- SetSourceParameters(enc_ctx, video_format);
- SetEncoderParameters(enc_ctx, video_format);
- }
+extern DllExport void dirac_encoder_context_init ( dirac_encoder_context_t *enc_ctx, dirac_encoder_presets_t preset)
+{
+ TEST (enc_ctx != NULL);
+ memset (enc_ctx, 0, sizeof(dirac_encoder_context_t));
+
+ // preset is the video format
+ int ps = static_cast<int>(preset);
+ VideoFormat video_format(static_cast<VideoFormat>(ps));
+ SetSourceParameters (enc_ctx, video_format);
+ SetEncoderParameters (enc_ctx, video_format);
+}
- extern DllExport dirac_encoder_t *dirac_encoder_init(const dirac_encoder_context_t *enc_ctx, int verbose)
- {
- /* Allocate for encoder */
- dirac_encoder_t *encoder = new dirac_encoder_t;
+extern DllExport dirac_encoder_t *dirac_encoder_init (const dirac_encoder_context_t *enc_ctx, int verbose)
+{
+ /* Allocate for encoder */
+ dirac_encoder_t *encoder = new dirac_encoder_t;
- memset(encoder, 0, sizeof(dirac_encoder_t));
- /* initialse the encoder context */
- if(!InitialiseEncoder(enc_ctx, verbose > 0, encoder))
- {
- delete encoder;
- return NULL;
- }
+ memset (encoder, 0, sizeof(dirac_encoder_t));
+ /* initialse the encoder context */
+ if (!InitialiseEncoder(enc_ctx, verbose>0, encoder))
+ {
+ delete encoder;
+ return NULL;
+ }
- encoder->encoded_picture_avail = encoder->decoded_frame_avail = 0;
- encoder->instr_data_avail = 0;
+ encoder->encoded_picture_avail = encoder->decoded_frame_avail = 0;
+ encoder->instr_data_avail = 0;
- return encoder;
- }
+ return encoder;
+}
#if DIRAC_RESEARCH_VERSION_ATLEAST(1,0,2)
- extern DllExport int dirac_encoder_pts_offset(const dirac_encoder_t *encoder)
+extern DllExport int dirac_encoder_pts_offset (const dirac_encoder_t *encoder)
+{
+ TEST (encoder != NULL);
+ TEST (encoder->compressor != NULL);
+ DiracEncoder *compressor = (DiracEncoder *)encoder->compressor;
+ int ret;
+ try
{
- TEST(encoder != NULL);
- TEST(encoder->compressor != NULL);
- DiracEncoder *compressor = (DiracEncoder *)encoder->compressor;
- int ret;
- try
- {
- ret = compressor->GetPTSOffset();
- }
- catch(...)
- {
- ret = -1;
- }
-
- return ret;
+ ret = compressor->GetPTSOffset();
}
+ catch (...)
+ {
+ ret = -1;
+ }
+
+ return ret;
+}
#endif
- extern DllExport int dirac_encoder_load(dirac_encoder_t *encoder, unsigned char *uncdata, int uncdata_size)
+extern DllExport int dirac_encoder_load (dirac_encoder_t *encoder, unsigned char *uncdata, int uncdata_size)
+{
+ TEST (encoder != NULL);
+ TEST (encoder->compressor != NULL);
+ DiracEncoder *compressor = (DiracEncoder *)encoder->compressor;
+ int ret_stat = 0;
+ try
{
- TEST(encoder != NULL);
- TEST(encoder->compressor != NULL);
- DiracEncoder *compressor = (DiracEncoder *)encoder->compressor;
- int ret_stat = 0;
- try
+ if ( compressor->LoadNextFrame (uncdata, uncdata_size))
{
- if(compressor->LoadNextFrame(uncdata, uncdata_size))
- {
- ret_stat = uncdata_size;
- }
- }
- catch(...)
- {
- if(compressor->GetEncParams().Verbose())
- std::cerr << "dirac_encoder_load failed" << std::endl;
- ret_stat = -1;
+ ret_stat = uncdata_size;
}
- return ret_stat;
}
-
- extern DllExport dirac_encoder_state_t
- dirac_encoder_output(dirac_encoder_t *encoder)
+ catch (...)
{
- TEST(encoder != NULL);
- TEST(encoder->compressor != NULL);
- TEST(encoder->enc_buf.size != 0);
- TEST(encoder->enc_buf.buffer != NULL);
- DiracEncoder *compressor = (DiracEncoder *)encoder->compressor;
- dirac_encoder_state_t ret_stat = ENC_STATE_BUFFER;
+ if (compressor->GetEncParams().Verbose())
+ std::cerr << "dirac_encoder_load failed" << std::endl;
+ ret_stat = -1;
+ }
+ return ret_stat;
+}
- encoder->encoded_picture_avail = 0;
- encoder->decoded_frame_avail = 0;
- encoder->instr_data_avail = 0;
+extern DllExport dirac_encoder_state_t
+ dirac_encoder_output (dirac_encoder_t *encoder)
+{
+ TEST (encoder != NULL);
+ TEST (encoder->compressor != NULL);
+ TEST (encoder->enc_buf.size != 0);
+ TEST (encoder->enc_buf.buffer != NULL);
+ DiracEncoder *compressor = (DiracEncoder *)encoder->compressor;
+ dirac_encoder_state_t ret_stat = ENC_STATE_BUFFER;
- try
- {
- // Get the next compressed picture
- if(compressor->CompressNextPicture() != 0)
- {
- if(compressor->GetEncodedData(encoder) < 0)
- ret_stat = ENC_STATE_INVALID;
- else
- {
- if(encoder->enc_buf.size > 0)
- {
- ret_stat = ENC_STATE_AVAIL;
- }
+ encoder->encoded_picture_avail = 0;
+ encoder->decoded_frame_avail = 0;
+ encoder->instr_data_avail = 0;
- }
- }
+ try
+ {
+ // Get the next compressed picture
+ if (compressor->CompressNextPicture() != 0)
+ {
+ if (compressor->GetEncodedData (encoder) < 0)
+ ret_stat = ENC_STATE_INVALID;
else
{
- // check if EOS has been signalled by the user app
- if(compressor->EOS())
+ if (encoder->enc_buf.size > 0)
{
- compressor->GetSequenceEnd(encoder);
- encoder->end_of_sequence = 1;
- encoder->enc_pparams.pnum = -1;
- ret_stat = ENC_STATE_EOS;
+ ret_stat = ENC_STATE_AVAIL;
}
+
}
- if(encoder->enc_ctx.decode_flag)
- compressor->GetDecodedData(encoder);
}
- catch(...)
+ else
{
- if(compressor->GetEncParams().Verbose())
- std::cerr << "GetEncodedData failed..." << std::endl;
-
- ret_stat = ENC_STATE_INVALID;
+ // check if EOS has been signalled by the user app
+ if (compressor->EOS())
+ {
+ compressor->GetSequenceEnd (encoder);
+ encoder->end_of_sequence = 1;
+ encoder->enc_pparams.pnum = -1;
+ ret_stat = ENC_STATE_EOS;
+ }
}
- return ret_stat;
+ if (encoder->enc_ctx.decode_flag)
+ compressor->GetDecodedData(encoder);
}
-
- extern DllExport void dirac_encoder_end_sequence(dirac_encoder_t *encoder)
+ catch (...)
{
- TEST(encoder != NULL);
- TEST(encoder->compressor != NULL);
- DiracEncoder *compressor = (DiracEncoder *)encoder->compressor;
+ if (compressor->GetEncParams().Verbose())
+ std::cerr << "GetEncodedData failed..." << std::endl;
- encoder->encoded_picture_avail = 0;
- encoder->decoded_frame_avail = 0;
- encoder->instr_data_avail = 0;
+ ret_stat = ENC_STATE_INVALID;
+ }
+ return ret_stat;
+}
- compressor->SignalEOS();
+extern DllExport void dirac_encoder_end_sequence (dirac_encoder_t *encoder)
+{
+ TEST (encoder != NULL);
+ TEST (encoder->compressor != NULL);
+ DiracEncoder *compressor = (DiracEncoder *)encoder->compressor;
- }
+ encoder->encoded_picture_avail = 0;
+ encoder->decoded_frame_avail = 0;
+ encoder->instr_data_avail = 0;
- extern DllExport void dirac_encoder_close(dirac_encoder_t *encoder)
- {
- TEST(encoder != NULL);
- TEST(encoder->compressor != NULL);
+ compressor->SignalEOS();
- delete(DiracEncoder *)(encoder->compressor);
+}
- if(encoder->enc_ctx.instr_flag)
- {
- dealloc_instr_data(&encoder->instr);
- }
+extern DllExport void dirac_encoder_close (dirac_encoder_t *encoder)
+{
+ TEST (encoder != NULL);
+ TEST (encoder->compressor != NULL);
- if(encoder->enc_ctx.decode_flag)
- {
- delete [] encoder->dec_buf.buf[0];
- }
- delete encoder;
+ delete (DiracEncoder *)(encoder->compressor);
+
+ if (encoder->enc_ctx.instr_flag)
+ {
+ dealloc_instr_data(&encoder->instr);
+ }
+
+ if (encoder->enc_ctx.decode_flag)
+ {
+ delete [] encoder->dec_buf.buf[0];
}
+ delete encoder;
+}
#ifdef __cplusplus
diff --git a/src/filters/parser/DiracSplitter/libdirac/libdirac_encoder/dirac_encoder.h b/src/filters/parser/DiracSplitter/libdirac/libdirac_encoder/dirac_encoder.h
index 4a8c030f9..750c6a51a 100644
--- a/src/filters/parser/DiracSplitter/libdirac/libdirac_encoder/dirac_encoder.h
+++ b/src/filters/parser/DiracSplitter/libdirac/libdirac_encoder/dirac_encoder.h
@@ -23,7 +23,7 @@
* Contributor(s): Anuradha Suraparaju (Original Author)
* Andrew Kennedy,
* Thomas Davies
-* Myo Tun (Brunel University, myo.tun@brunel.ac.uk)
+* Myo Tun (Brunel University, myo.tun@brunel.ac.uk)
*
* Alternatively, the contents of this file may be used under the terms of
* the GNU General Public License Version 2 (the "GPL"), or the GNU Lesser
@@ -46,7 +46,7 @@
/*! \file
\brief C interface to Dirac Encoder.
-
+
A set of 'C' functions that define the public interface to the Dirac encoder.
Refer to the the reference encoder source code, encoder/encmain.cpp for
an example of how to use the "C" interface. The pseudocode below gives
@@ -75,7 +75,7 @@
// return locally decoded output
enc_ctx.decode_flag = 1;
- // Initialise the encoder with the encoder context.
+ // Initialise the encoder with the encoder context.
// Setting verbose output to false
encoder= dirac_encoder_init(&enc_ctx, false);
@@ -126,7 +126,7 @@
}
if (encoder->decoded_frame_avail)
{
- //locally decoded frame is available in
+ //locally decoded frame is available in
//encoder->dec_buf
//locally decoded frame parameters available
//in encoder->dec_fparams
@@ -152,329 +152,328 @@
extern "C" {
#endif
- /*! Enumerated type that defines encoder state */
- typedef enum
- {
- ENC_STATE_INVALID = -1,
- ENC_STATE_BUFFER,
- ENC_STATE_AVAIL,
- ENC_STATE_EOS
- }
- dirac_encoder_state_t ;
+/*! Enumerated type that defines encoder state */
+typedef enum
+{
+ ENC_STATE_INVALID = -1,
+ ENC_STATE_BUFFER,
+ ENC_STATE_AVAIL,
+ ENC_STATE_EOS
+} dirac_encoder_state_t ;
+
+/*! Enumerated type that defines prefiltering types supported by the
+ encoder. */
+typedef PrefilterType dirac_prefilter_t;
+
+/*! Enumerated type that defines encoder presets that set the encoder and
+ sequence paramters. More presets may be added in future*/
+typedef VideoFormat dirac_encoder_presets_t;
+
+/*! Enumerated type that defines motion vector precisions supported by the
+ encoder.*/
+typedef MVPrecisionType dirac_mvprecision_t;
+/*! Structure that holds the encoder specific parameters */
+typedef struct
+{
+ /*! Lossless coding */
+ int lossless;
+ /*! Quality factor */
+ float qf;
+ /*! Full-search motion estimation */
+ int full_search;
+ /*! Combined component motion estimation */
+ int combined_me;
+ /*! x-range for full search ME */
+ int x_range_me;
+ /*! y-range for full search ME */
+ int y_range_me;
+ /*! The separation between L1 frames */
+ int L1_sep;
+ /*! The number of L1 frames before the next intra frame. Together
+ with L1_sep determines the GOP structure.
+ */
+ int num_L1;
+ /*! Normalised viewing distance parameter, in cycles per degree */
+ float cpd;
+ /*! The width of blocks used for motion compensation */
+ int xblen;
+ /*! The height of blocks used for motion compensation */
+ int yblen;
+ /*! The horizontal separation between blocks. Always <xblen */
+ int xbsep;
+ /*! The vertical separation between blocks. Always <yblen */
+ int ybsep;
+ /*! Video format preset */
+ int video_format;
+ /*! Transform filter for intra frames*/
+ dirac_wlt_filter_t intra_wlt_filter;
+ /*! Transform filter for inter frames*/
+ dirac_wlt_filter_t inter_wlt_filter;
+ /*! Transform depth */
+ unsigned int wlt_depth;
+ /*! Spatial partitioning flag */
+ unsigned int spatial_partition;
+ /*! prefilter indicator */
+ dirac_prefilter_t prefilter;
+ /*! prefilter strength*/
+ unsigned int prefilter_strength;
+ /*! Multiple quantisers flag */
+ unsigned int multi_quants;
+ /*! motion-vector pixel precision */
+ dirac_mvprecision_t mv_precision;
+ /*! target bit rate in kbps */
+ int trate;
+ /*! picture coding mode: 0 - frame coding; 1 - field coding */
+ unsigned int picture_coding_mode;
+ /*! arithmetic coding flag: 0 - vlc coding; 1 - arithmetic coding */
+ int using_ac;
+} dirac_encparams_t;
+
+/*! Structure that holds the parameters that set up the encoder context */
+typedef struct
+{
+ /*! Source parameters */
+ dirac_sourceparams_t src_params;
+ /*! Encoder parameters */
+ dirac_encparams_t enc_params;
+ /*! Return diagnostics info 1-return mv data, 0-no diagnostics returned */
+ int instr_flag;
+ /*! Return locally decoded frames 1-return locally decoded frames,
+ 0-no decoded frames returned */
+ int decode_flag;
+} dirac_encoder_context_t;
+
+/*! Function that creates an encoder context based on a preset value. The
+ values can then be overridden by the user by setting each field separately
+ \param enc_ctx pointer to Encoder context tp be initialised.
+ \param preset Preset to be used to initialise the encoder context
+ \verbatim
+
+ For a full list of video formats presets supported and the default values
+ of the source and encoder parameters. refer to Annex C of the Dirac
+ ByteStream Specification.
+
+ \endverbatim
+*/
+extern DllExport void dirac_encoder_context_init (dirac_encoder_context_t *enc_ctx, dirac_encoder_presets_t preset);
+
+
+/*! Structure that holds the encoded data*/
+typedef struct
+{
+ /*! Buffer to hold encoded. Allocated and managed by library user. */
+ unsigned char *buffer;
+ /*! Buffer size */
+ int size;
+} dirac_enc_data_t;
+
+/*! Structure that holds the statistics about the encoded picture */
+typedef struct
+{
+ /*! Number of motion vector bits */
+ unsigned int mv_bits;
+ /*! Number of used to encode y component */
+ unsigned int ycomp_bits;
+ /*! Number of used to encode u component */
+ unsigned int ucomp_bits;
+ /*! Number of used to encode v component */
+ unsigned int vcomp_bits;
+ /*! Total number of bits used to encode picture */
+ unsigned int pic_bits;
+} dirac_enc_picstats_t;
+
+/*! Structure that holds the statistics about the encoded sequence */
+typedef struct
+{
+ /*! Number of motion vector bits */
+ int64_t mv_bits;
+ /*! Total number of bits used to encode sequence */
+ int64_t seq_bits;
+ /*! Number of used to encode y component */
+ int64_t ycomp_bits;
+ /*! Number of used to encode u component */
+ int64_t ucomp_bits;
+ /*! Number of used to encode v component */
+ int64_t vcomp_bits;
+ /*! Average bit rate for the sequence */
+ int64_t bit_rate;
+} dirac_enc_seqstats_t;
+
+/*! Structure that holds the motion vector information */
+typedef struct
+{
+ /*! X component */
+ int x;
+ /*! Y component */
+ int y;
+} dirac_mv_t;
+
+/*! Structure that holds the motion vector cost information*/
+typedef struct
+{
+ /*! The Sum of Absolute Differences */
+ float SAD;
+ /*! The (Lagrangian-weighted) motion vector cost */
+ float mvcost;
+} dirac_mv_cost_t;
+
+/*! Structure that diagnostics data returned by the encoder */
+typedef struct
+{
+ /*! Frame type */
+ dirac_picture_type_t ptype;
+ /*! Reference type */
+ dirac_reference_type_t rtype;
+ /*! Picture number */
+ int pnum;
+ /*! Number of reference pictures */
+ int num_refs;
+ /*! Array of Reference picture numbers */
+ int refs[2];
+ /*! Block separation in X direction */
+ int xbsep;
+ /*! Block separation in Y direction */
+ int ybsep;
+ /*! MacroBlock length in X direction */
+ int sb_xlen;
+ /*! MacroBlock length in Y direction */
+ int sb_ylen;
+ /*! Motion Vector array length in X direction */
+ int mv_xlen;
+ /*! Motion Vector array length in Y direction */
+ int mv_ylen;
+ /*! Macro-block split mode array - sb_ylen*sb_xlen*/
+ int *sb_split_mode;
+ /*! Macro-block costs array - sb_ylen*sb_xlen*/
+ float *sb_costs;
+ /*! Block prediction mode - mv_xlen*mv_ylen */
+ int *pred_mode;
+ /*! Block intrac costs - mv_xlen*mv_ylen */
+ float *intra_costs;
+ /*! Bi prediction costs - mv_xlen*mv_ylen*2 */
+ dirac_mv_cost_t *bipred_costs;
+ /*! DC values of y_comp */
+ short *dc_ycomp;
+ /*! DC values of u_comp */
+ short *dc_ucomp;
+ /*! DC values of v_comp */
+ short *dc_vcomp;
+ /*! Motion vectors for Reference frames mv_ylen*mv_xlen */
+ dirac_mv_t *mv[2];
+ /*! Predictions costs for Reference frames mv_ylen*mv_xlen */
+ dirac_mv_cost_t *pred_costs[2];
+} dirac_instr_t;
+
+/*! Structure that holds the information returned by the encoder */
+typedef struct
+{
+ /*! Encoder context */
+ dirac_encoder_context_t enc_ctx;
+
+ /*! encoded picture available flag */
+ int encoded_picture_avail;
+
+ /*!
+ encoded output. This buffer must be initialised by the user of the
+ library
+ */
+ dirac_enc_data_t enc_buf;
- /*! Enumerated type that defines prefiltering types supported by the
- encoder. */
- typedef PrefilterType dirac_prefilter_t;
+ /*! encoded picture params */
+ dirac_picparams_t enc_pparams;
- /*! Enumerated type that defines encoder presets that set the encoder and
- sequence paramters. More presets may be added in future*/
- typedef VideoFormat dirac_encoder_presets_t;
+ /*! encoded picture stats */
+ dirac_enc_picstats_t enc_pstats;
- /*! Enumerated type that defines motion vector precisions supported by the
- encoder.*/
- typedef MVPrecisionType dirac_mvprecision_t;
- /*! Structure that holds the encoder specific parameters */
- typedef struct
- {
- /*! Lossless coding */
- int lossless;
- /*! Quality factor */
- float qf;
- /*! Full-search motion estimation */
- int full_search;
- /*! Combined component motion estimation */
- int combined_me;
- /*! x-range for full search ME */
- int x_range_me;
- /*! y-range for full search ME */
- int y_range_me;
- /*! The separation between L1 frames */
- int L1_sep;
- /*! The number of L1 frames before the next intra frame. Together
- with L1_sep determines the GOP structure.
- */
- int num_L1;
- /*! Normalised viewing distance parameter, in cycles per degree */
- float cpd;
- /*! The width of blocks used for motion compensation */
- int xblen;
- /*! The height of blocks used for motion compensation */
- int yblen;
- /*! The horizontal separation between blocks. Always <xblen */
- int xbsep;
- /*! The vertical separation between blocks. Always <yblen */
- int ybsep;
- /*! Video format preset */
- int video_format;
- /*! Transform filter for intra frames*/
- dirac_wlt_filter_t intra_wlt_filter;
- /*! Transform filter for inter frames*/
- dirac_wlt_filter_t inter_wlt_filter;
- /*! Transform depth */
- unsigned int wlt_depth;
- /*! Spatial partitioning flag */
- unsigned int spatial_partition;
- /*! prefilter indicator */
- dirac_prefilter_t prefilter;
- /*! prefilter strength*/
- unsigned int prefilter_strength;
- /*! Multiple quantisers flag */
- unsigned int multi_quants;
- /*! motion-vector pixel precision */
- dirac_mvprecision_t mv_precision;
- /*! target bit rate in kbps */
- int trate;
- /*! picture coding mode: 0 - frame coding; 1 - field coding */
- unsigned int picture_coding_mode;
- /*! arithmetic coding flag: 0 - vlc coding; 1 - arithmetic coding */
- int using_ac;
- } dirac_encparams_t;
-
- /*! Structure that holds the parameters that set up the encoder context */
- typedef struct
- {
- /*! Source parameters */
- dirac_sourceparams_t src_params;
- /*! Encoder parameters */
- dirac_encparams_t enc_params;
- /*! Return diagnostics info 1-return mv data, 0-no diagnostics returned */
- int instr_flag;
- /*! Return locally decoded frames 1-return locally decoded frames,
- 0-no decoded frames returned */
- int decode_flag;
- } dirac_encoder_context_t;
-
- /*! Function that creates an encoder context based on a preset value. The
- values can then be overridden by the user by setting each field separately
- \param enc_ctx pointer to Encoder context tp be initialised.
- \param preset Preset to be used to initialise the encoder context
- \verbatim
-
- For a full list of video formats presets supported and the default values
- of the source and encoder parameters. refer to Annex C of the Dirac
- ByteStream Specification.
-
- \endverbatim
+ /*! encoded sequence stats */
+ dirac_enc_seqstats_t enc_seqstats;
+
+ /*! end of sequence */
+ int end_of_sequence;
+
+ /* locally decoded frame (NB: not picture) available flag.
+ 1 - locally decoded frame available in dec_buf.
+ 0 - locally decoded frame not available.
*/
- extern DllExport void dirac_encoder_context_init(dirac_encoder_context_t *enc_ctx, dirac_encoder_presets_t preset);
+ int decoded_frame_avail;
+ /*!
+ locally decoded output buffer. This buffer is allocated and managed by
+ the encoder library
+ */
+ dirac_framebuf_t dec_buf;
- /*! Structure that holds the encoded data*/
- typedef struct
- {
- /*! Buffer to hold encoded. Allocated and managed by library user. */
- unsigned char *buffer;
- /*! Buffer size */
- int size;
- } dirac_enc_data_t;
-
- /*! Structure that holds the statistics about the encoded picture */
- typedef struct
- {
- /*! Number of motion vector bits */
- unsigned int mv_bits;
- /*! Number of used to encode y component */
- unsigned int ycomp_bits;
- /*! Number of used to encode u component */
- unsigned int ucomp_bits;
- /*! Number of used to encode v component */
- unsigned int vcomp_bits;
- /*! Total number of bits used to encode picture */
- unsigned int pic_bits;
- } dirac_enc_picstats_t;
-
- /*! Structure that holds the statistics about the encoded sequence */
- typedef struct
- {
- /*! Number of motion vector bits */
- int64_t mv_bits;
- /*! Total number of bits used to encode sequence */
- int64_t seq_bits;
- /*! Number of used to encode y component */
- int64_t ycomp_bits;
- /*! Number of used to encode u component */
- int64_t ucomp_bits;
- /*! Number of used to encode v component */
- int64_t vcomp_bits;
- /*! Average bit rate for the sequence */
- int64_t bit_rate;
- } dirac_enc_seqstats_t;
-
- /*! Structure that holds the motion vector information */
- typedef struct
- {
- /*! X component */
- int x;
- /*! Y component */
- int y;
- } dirac_mv_t;
-
- /*! Structure that holds the motion vector cost information*/
- typedef struct
- {
- /*! The Sum of Absolute Differences */
- float SAD;
- /*! The (Lagrangian-weighted) motion vector cost */
- float mvcost;
- } dirac_mv_cost_t;
-
- /*! Structure that diagnostics data returned by the encoder */
- typedef struct
- {
- /*! Frame type */
- dirac_picture_type_t ptype;
- /*! Reference type */
- dirac_reference_type_t rtype;
- /*! Picture number */
- int pnum;
- /*! Number of reference pictures */
- int num_refs;
- /*! Array of Reference picture numbers */
- int refs[2];
- /*! Block separation in X direction */
- int xbsep;
- /*! Block separation in Y direction */
- int ybsep;
- /*! MacroBlock length in X direction */
- int sb_xlen;
- /*! MacroBlock length in Y direction */
- int sb_ylen;
- /*! Motion Vector array length in X direction */
- int mv_xlen;
- /*! Motion Vector array length in Y direction */
- int mv_ylen;
- /*! Macro-block split mode array - sb_ylen*sb_xlen*/
- int *sb_split_mode;
- /*! Macro-block costs array - sb_ylen*sb_xlen*/
- float *sb_costs;
- /*! Block prediction mode - mv_xlen*mv_ylen */
- int *pred_mode;
- /*! Block intrac costs - mv_xlen*mv_ylen */
- float *intra_costs;
- /*! Bi prediction costs - mv_xlen*mv_ylen*2 */
- dirac_mv_cost_t *bipred_costs;
- /*! DC values of y_comp */
- short *dc_ycomp;
- /*! DC values of u_comp */
- short *dc_ucomp;
- /*! DC values of v_comp */
- short *dc_vcomp;
- /*! Motion vectors for Reference frames mv_ylen*mv_xlen */
- dirac_mv_t *mv[2];
- /*! Predictions costs for Reference frames mv_ylen*mv_xlen */
- dirac_mv_cost_t *pred_costs[2];
- } dirac_instr_t;
-
- /*! Structure that holds the information returned by the encoder */
- typedef struct
- {
- /*! Encoder context */
- dirac_encoder_context_t enc_ctx;
-
- /*! encoded picture available flag */
- int encoded_picture_avail;
-
- /*!
- encoded output. This buffer must be initialised by the user of the
- library
- */
- dirac_enc_data_t enc_buf;
-
- /*! encoded picture params */
- dirac_picparams_t enc_pparams;
-
- /*! encoded picture stats */
- dirac_enc_picstats_t enc_pstats;
-
- /*! encoded sequence stats */
- dirac_enc_seqstats_t enc_seqstats;
-
- /*! end of sequence */
- int end_of_sequence;
-
- /* locally decoded frame (NB: not picture) available flag.
- 1 - locally decoded frame available in dec_buf.
- 0 - locally decoded frame not available.
- */
- int decoded_frame_avail;
-
- /*!
- locally decoded output buffer. This buffer is allocated and managed by
- the encoder library
- */
- dirac_framebuf_t dec_buf;
-
- /*! locally decoded picture params */
- dirac_picparams_t dec_pparams;
-
- /*!
- instrumentation data buffer. This buffer is allocated and managed by
- the encoder library. */
- dirac_instr_t instr;
-
- /*! instrumentation data available flag
- 1 - instrumentation data available in instr
- 0 - linstrumentation data not available.
- */
- int instr_data_avail;
-
- /*! void pointer to internal sequence compressor */
- const void *compressor;
- } dirac_encoder_t;
-
- /*!
- Initialise encoder. Makes a copy of the enc_ctx passed to it.
- \param enc_ctx Parameters to initialise encoder context
- \param verbose boolean flag to set verbose output
- \return encoder Handle to encoder if successful or NULL on failure
+ /*! locally decoded picture params */
+ dirac_picparams_t dec_pparams;
+
+ /*!
+ instrumentation data buffer. This buffer is allocated and managed by
+ the encoder library. */
+ dirac_instr_t instr;
+
+ /*! instrumentation data available flag
+ 1 - instrumentation data available in instr
+ 0 - linstrumentation data not available.
*/
- extern DllExport dirac_encoder_t *dirac_encoder_init(const dirac_encoder_context_t *enc_ctx, int verbose);
+ int instr_data_avail;
+
+ /*! void pointer to internal sequence compressor */
+ const void *compressor;
+} dirac_encoder_t;
+
+/*!
+ Initialise encoder. Makes a copy of the enc_ctx passed to it.
+ \param enc_ctx Parameters to initialise encoder context
+ \param verbose boolean flag to set verbose output
+ \return encoder Handle to encoder if successful or NULL on failure
+*/
+extern DllExport dirac_encoder_t *dirac_encoder_init (const dirac_encoder_context_t *enc_ctx, int verbose);
#if DIRAC_RESEARCH_VERSION_ATLEAST(1,0,2)
- /*!
- Query the encoder for the reordering depth.
- \param encoder Encoder Handle
- \return encoder The number of pictures a realtime decoder must wait
- before outputting the first picture in display order;
- or -1 for failure.
- */
- extern DllExport int dirac_encoder_pts_offset(const dirac_encoder_t *encoder);
+/*!
+ Query the encoder for the reordering depth.
+ \param encoder Encoder Handle
+ \return encoder The number of pictures a realtime decoder must wait
+ before outputting the first picture in display order;
+ or -1 for failure.
+*/
+extern DllExport int dirac_encoder_pts_offset (const dirac_encoder_t *encoder);
#endif
- /*!
- Load uncompressed data into the encoder. Expects one full frame of data
- \param encoder Encoder Handle
- \param uncdata Uncompressed data buffer
- \param uncdata_size boolean flag to set verbose output
- \return return status. >0 - successful; -1 failed
- Failure may be due to input data size not matching
- the required frame size.
- */
- extern DllExport int dirac_encoder_load(dirac_encoder_t *encoder, unsigned char *uncdata, int uncdata_size);
-
- /*!
- Retrieve an encoded frame from the encoder. Returns the state of the
- encoder. The encoder buffer enc_buf in the encodermust be
- set up with the buffer and buffer_size that will hold the encoded frame
- \param encoder Encoder Handle
- \return ENC_STATE_INVALID - unrecoverable error
- ENC_STATE_BUFFER - load data into encoder
- ENC_STATE_AVAIL - Encoded frame available
- ENC_STATE_EOS - End of Sequence info available
- */
- extern DllExport dirac_encoder_state_t dirac_encoder_output(dirac_encoder_t *encoder);
+/*!
+ Load uncompressed data into the encoder. Expects one full frame of data
+ \param encoder Encoder Handle
+ \param uncdata Uncompressed data buffer
+ \param uncdata_size boolean flag to set verbose output
+ \return return status. >0 - successful; -1 failed
+ Failure may be due to input data size not matching
+ the required frame size.
+*/
+extern DllExport int dirac_encoder_load (dirac_encoder_t *encoder, unsigned char *uncdata, int uncdata_size);
+
+/*!
+ Retrieve an encoded frame from the encoder. Returns the state of the
+ encoder. The encoder buffer enc_buf in the encodermust be
+ set up with the buffer and buffer_size that will hold the encoded frame
+ \param encoder Encoder Handle
+ \return ENC_STATE_INVALID - unrecoverable error
+ ENC_STATE_BUFFER - load data into encoder
+ ENC_STATE_AVAIL - Encoded frame available
+ ENC_STATE_EOS - End of Sequence info available
+*/
+extern DllExport dirac_encoder_state_t dirac_encoder_output (dirac_encoder_t *encoder);
- /*!
- Request the encoder to end the sequence.
- \param encoder Encoder Handle
- */
- extern DllExport void dirac_encoder_end_sequence(dirac_encoder_t *encoder);
+/*!
+ Request the encoder to end the sequence.
+ \param encoder Encoder Handle
+*/
+extern DllExport void dirac_encoder_end_sequence (dirac_encoder_t *encoder);
- /*!
- Free resources held by encoder
- \param encoder Encoder Handle
- */
- extern DllExport void dirac_encoder_close(dirac_encoder_t *encoder);
+/*!
+ Free resources held by encoder
+ \param encoder Encoder Handle
+*/
+extern DllExport void dirac_encoder_close (dirac_encoder_t *encoder);
#endif
#ifdef __cplusplus
diff --git a/src/filters/parser/DiracSplitter/libdirac/libdirac_encoder/enc_picture.cpp b/src/filters/parser/DiracSplitter/libdirac/libdirac_encoder/enc_picture.cpp
index 2a390e42c..5ad01bbe3 100644
--- a/src/filters/parser/DiracSplitter/libdirac/libdirac_encoder/enc_picture.cpp
+++ b/src/filters/parser/DiracSplitter/libdirac/libdirac_encoder/enc_picture.cpp
@@ -40,56 +40,49 @@
using namespace dirac;
-EncPicture::EncPicture(const PictureParams& pp):
- Picture(pp),
- m_me_data(NULL),
- m_status(NO_ENC),
- m_complexity(0.0),
- m_norm_complexity(1.0),
+EncPicture::EncPicture( const PictureParams& pp):
+ Picture( pp ),
+ m_me_data( NULL ),
+ m_status( NO_ENC ),
+ m_complexity( 0.0 ),
+ m_norm_complexity( 1.0 ),
m_pred_bias(0.5)
{
- for(int c = 0; c < 3; ++c)
- {
- m_orig_data[c] = new PicArray(m_pic_data[c]->LengthY(), m_pic_data[c]->LengthX());
+ for (int c=0; c<3; ++c ){
+ m_orig_data[c] = new PicArray( m_pic_data[c]->LengthY(), m_pic_data[c]->LengthX() );
m_orig_up_data[c] = NULL;
- m_filt_data[c] = NULL;
- m_filt_up_data[c] = NULL;
+ m_filt_data[c] = NULL;
+ m_filt_up_data[c] = NULL;
}
}
-void EncPicture::ClearData()
-{
+void EncPicture::ClearData(){
Picture::ClearData();
- for(int c = 0; c < 3; ++c)
- {
- if(m_orig_data[c] != NULL)
- {
+ for (int c=0;c<3;++c){
+ if (m_orig_data[c] != NULL){
delete m_orig_data[c];
m_orig_data[c] = NULL;
}
- if(m_orig_up_data[c] != NULL)
- {
+ if (m_orig_up_data[c] != NULL){
delete m_orig_up_data[c];
m_orig_up_data[c] = NULL;
}
- if(m_filt_data[c] != NULL)
- {
+ if (m_filt_data[c] != NULL){
delete m_filt_data[c];
m_filt_data[c] = NULL;
}
- if(m_filt_up_data[c] != NULL)
- {
+ if (m_filt_up_data[c] != NULL){
delete m_filt_up_data[c];
m_filt_up_data[c] = NULL;
}
}
- if(m_me_data != NULL)
+ if ( m_me_data != NULL )
delete m_me_data;
}
@@ -100,40 +93,38 @@ EncPicture::~EncPicture()
void EncPicture::SetOrigData()
{
- for(int c = 0; c < 3 ; ++c)
+ for ( int c=0; c<3 ; ++c )
SetOrigData(c);
}
-void EncPicture::SetOrigData(const int c)
+void EncPicture::SetOrigData( const int c )
{
- if(m_pic_data[c] != NULL)
+ if ( m_pic_data[c] != NULL )
*(m_orig_data[c]) = *(m_pic_data[c]);
}
-void EncPicture::InitMEData(const PicturePredParams& predparams , const int num_refs)
+void EncPicture::InitMEData( const PicturePredParams& predparams , const int num_refs)
{
- if(m_me_data != NULL)
+ if (m_me_data != NULL)
delete m_me_data;
- m_me_data = new MEData(predparams, num_refs);
+ m_me_data=new MEData( predparams, num_refs );
}
-const PicArray& EncPicture::DataForME(bool combined_me) const
-{
+const PicArray& EncPicture::DataForME( bool combined_me ) const{
- if(combined_me)
+ if (combined_me)
return CombinedData();
else
- return OrigData(Y_COMP);
+ return OrigData( Y_COMP );
}
-const PicArray& EncPicture::UpDataForME(bool combined_me) const
-{
+const PicArray& EncPicture::UpDataForME( bool combined_me ) const{
- if(combined_me)
+ if (combined_me)
return UpCombinedData();
else
- return UpOrigData(Y_COMP);
+ return UpOrigData( Y_COMP );
}
@@ -141,27 +132,26 @@ const PicArray& EncPicture::UpOrigData(CompSort cs) const
{
const int c = (int) cs;
- if(m_orig_up_data[c] != NULL)
+ if (m_orig_up_data[c] != NULL)
return *m_orig_up_data[c];
else
- {
- //we have to do the upconversion
+ {//we have to do the upconversion
- m_orig_up_data[c] = new PicArray(2 * m_orig_data[c]->LengthY(),
- 2 * m_orig_data[c]->LengthX());
+ m_orig_up_data[c] = new PicArray( 2*m_orig_data[c]->LengthY(),
+ 2*m_orig_data[c]->LengthX() );
UpConverter* myupconv;
- if(c > 0)
- myupconv = new UpConverter(-(1 << (m_pparams.ChromaDepth() - 1)),
- (1 << (m_pparams.ChromaDepth() - 1)) - 1,
- m_pparams.ChromaXl(), m_pparams.ChromaYl());
+ if (c>0)
+ myupconv = new UpConverter(-(1 << (m_pparams.ChromaDepth()-1)),
+ (1 << (m_pparams.ChromaDepth()-1))-1,
+ m_pparams.ChromaXl(), m_pparams.ChromaYl());
else
- myupconv = new UpConverter(-(1 << (m_pparams.LumaDepth() - 1)),
- (1 << (m_pparams.LumaDepth() - 1)) - 1,
- m_pparams.Xl(), m_pparams.Yl());
+ myupconv = new UpConverter(-(1 << (m_pparams.LumaDepth()-1)),
+ (1 << (m_pparams.LumaDepth()-1))-1,
+ m_pparams.Xl(), m_pparams.Yl());
- myupconv->DoUpConverter(*(m_orig_data[c]) , *(m_orig_up_data[c]));
+ myupconv->DoUpConverter( *(m_orig_data[c]) , *(m_orig_up_data[c]) );
- delete myupconv;
+ delete myupconv;
return *(m_orig_up_data[c]);
@@ -172,17 +162,16 @@ const PicArray& EncPicture::FiltData(CompSort cs) const
{
const int c = (int) cs;
- if(m_filt_data[c] != NULL)
+ if (m_filt_data[c] != NULL)
return *m_filt_data[c];
else
- {
- //we have to do the filtering
+ {//we have to do the filtering
- if(m_orig_data[c] != NULL)
- m_filt_data[c] = new PicArray(m_orig_data[c]->LengthY(),
- m_orig_data[c]->LengthX());
+ if (m_orig_data[c] != NULL )
+ m_filt_data[c] = new PicArray( m_orig_data[c]->LengthY(),
+ m_orig_data[c]->LengthX() );
- AntiAliasFilter(*(m_filt_data[c]), *(m_orig_data[c]));
+ AntiAliasFilter( *(m_filt_data[c]), *(m_orig_data[c]));
return *(m_filt_data[c]);
@@ -193,76 +182,73 @@ const PicArray& EncPicture::UpFiltData(CompSort cs) const
{
const int c = (int) cs;
- if(m_filt_up_data[c] != NULL)
+ if (m_filt_up_data[c] != NULL)
return *m_filt_up_data[c];
else
- {
- //we have to do the upconversion
+ {//we have to do the upconversion
- const PicArray& filt_data = FiltData(cs);
+ const PicArray& filt_data = FiltData( cs );
- m_filt_up_data[c] = new PicArray(2 * filt_data.LengthY(),
- 2 * filt_data.LengthX());
+ m_filt_up_data[c] = new PicArray( 2*filt_data.LengthY(),
+ 2*filt_data.LengthX() );
UpConverter* myupconv;
- if(c > 0)
- myupconv = new UpConverter(-(1 << (m_pparams.ChromaDepth() - 1)),
- (1 << (m_pparams.ChromaDepth() - 1)) - 1,
- m_pparams.ChromaXl(), m_pparams.ChromaYl());
+ if (c>0)
+ myupconv = new UpConverter(-(1 << (m_pparams.ChromaDepth()-1)),
+ (1 << (m_pparams.ChromaDepth()-1))-1,
+ m_pparams.ChromaXl(), m_pparams.ChromaYl());
else
- myupconv = new UpConverter(-(1 << (m_pparams.LumaDepth() - 1)),
- (1 << (m_pparams.LumaDepth() - 1)) - 1,
- m_pparams.Xl(), m_pparams.Yl());
+ myupconv = new UpConverter(-(1 << (m_pparams.LumaDepth()-1)),
+ (1 << (m_pparams.LumaDepth()-1))-1,
+ m_pparams.Xl(), m_pparams.Yl());
- myupconv->DoUpConverter(filt_data , *(m_filt_up_data[c]));
+ myupconv->DoUpConverter( filt_data , *(m_filt_up_data[c]) );
- delete myupconv;
+ delete myupconv;
return *(m_filt_up_data[c]);
}
}
-void EncPicture::AntiAliasFilter(PicArray& out_data, const PicArray& in_data) const
-{
+void EncPicture::AntiAliasFilter( PicArray& out_data, const PicArray& in_data ) const{
//Special case for first row
- for(int i = in_data.FirstX(); i <= in_data.LastX(); ++i)
+ for (int i = in_data.FirstX(); i <= in_data.LastX(); ++i)
{
- out_data[in_data.FirstY()][i] = (3 * in_data[in_data.FirstY()][i] +
- in_data[in_data.FirstY()+1][i] + 2) >> 2;
+ out_data[in_data.FirstY()][i] = (3*in_data[in_data.FirstY()][i] +
+ in_data[in_data.FirstY()+1][i] +2 )>>2;
}
//Middle section
- for(int j = in_data.FirstY() + 1; j < in_data.LastY(); ++j)
+ for (int j = in_data.FirstY()+1; j < in_data.LastY(); ++j)
{
- for(int i = in_data.FirstX(); i <= in_data.LastX(); ++i)
+ for (int i = in_data.FirstX(); i <= in_data.LastX(); ++i)
{
- out_data[j][i] = (in_data[j-1][i] + 2 * in_data[j][i] + in_data[j+1][i] + 2) >> 2;
+ out_data[j][i] = (in_data[j-1][i] + 2*in_data[j][i] + in_data[j+1][i] + 2)>>2;
}
}
//Special case for last row
- for(int i = in_data.FirstX(); i <= in_data.LastX(); ++i)
+ for (int i = in_data.FirstX(); i <= in_data.LastX(); ++i)
{
out_data[in_data.LastY()][i] = (in_data[in_data.LastY()-1][i] +
- 3 * in_data[in_data.LastY()][i] + 2) >> 2;
+ 3*in_data[in_data.LastY()][i] + 2)>>2;
}
}
const PicArray& EncPicture::CombinedData() const
{
- if(m_filt_data[Y_COMP] != NULL)
+ if (m_filt_data[Y_COMP] != NULL)
return *m_filt_data[Y_COMP];
else
- {
- //we have to do the combining
+ {//we have to do the combining
- if(m_orig_data[Y_COMP] != NULL)
- m_filt_data[Y_COMP] = new PicArray(m_orig_data[Y_COMP]->LengthY(),
- m_orig_data[Y_COMP]->LengthX());
+ if (m_orig_data[Y_COMP] != NULL )
+ m_filt_data[Y_COMP] = new PicArray( m_orig_data[Y_COMP]->LengthY(),
+ m_orig_data[Y_COMP]->LengthX() );
- Combine(*(m_filt_data[Y_COMP]), *(m_orig_data[Y_COMP]),
- *(m_orig_data[U_COMP]), *(m_orig_data[V_COMP])
- );
+ Combine( *(m_filt_data[Y_COMP]), *(m_orig_data[Y_COMP]),
+ *(m_orig_data[U_COMP]), *(m_orig_data[V_COMP])
+ );
return *(m_filt_data[Y_COMP]);
@@ -271,24 +257,23 @@ const PicArray& EncPicture::CombinedData() const
const PicArray& EncPicture::UpCombinedData() const
{
- if(m_filt_up_data[Y_COMP] != NULL)
+ if (m_filt_up_data[Y_COMP] != NULL)
return *m_filt_up_data[Y_COMP];
else
- {
- //we have to do the upconversion
+ {//we have to do the upconversion
const PicArray& filt_data = CombinedData();
- m_filt_up_data[Y_COMP] = new PicArray(2 * filt_data.LengthY(),
- 2 * filt_data.LengthX());
+ m_filt_up_data[Y_COMP] = new PicArray( 2*filt_data.LengthY(),
+ 2*filt_data.LengthX() );
UpConverter* myupconv;
- myupconv = new UpConverter(-(1 << (m_pparams.LumaDepth() - 1)),
- (1 << (m_pparams.LumaDepth() - 1)) - 1,
- m_pparams.Xl(), m_pparams.Yl());
+ myupconv = new UpConverter(-(1 << (m_pparams.LumaDepth()-1)),
+ (1 << (m_pparams.LumaDepth()-1))-1,
+ m_pparams.Xl(), m_pparams.Yl());
- myupconv->DoUpConverter(filt_data , *(m_filt_up_data[Y_COMP]));
+ myupconv->DoUpConverter( filt_data , *(m_filt_up_data[Y_COMP]) );
- delete myupconv;
+ delete myupconv;
return *(m_filt_up_data[Y_COMP]);
@@ -297,94 +282,85 @@ const PicArray& EncPicture::UpCombinedData() const
-void EncPicture::Combine(PicArray& comb_data, const PicArray& y_data,
- const PicArray& u_data, const PicArray& v_data) const
+void EncPicture::Combine( PicArray& comb_data, const PicArray& y_data,
+ const PicArray& u_data, const PicArray& v_data ) const
{
- int hcr = y_data.LengthX() / u_data.LengthX();
- int vcr = y_data.LengthY() / u_data.LengthY();
+ int hcr = y_data.LengthX()/u_data.LengthX();
+ int vcr = y_data.LengthY()/u_data.LengthY();
float val, valc, valy;
- if(vcr == 1)
- {
- for(int j = 0; j < comb_data.LengthY(); ++j)
- {
- if(hcr == 1) // 444 format
- {
- for(int i = 0; i < comb_data.LengthX(); ++i)
- {
+ if (vcr==1){
+ for (int j=0; j<comb_data.LengthY(); ++j) {
+ if (hcr==1){// 444 format
+ for (int i=0; i<comb_data.LengthX(); ++i ){
val = float(u_data[j][i]);
- val *= val;
- valc = val;
+ val *= val;
+ valc = val;
- val = float(v_data[j][i]);
- val *= val;
- valc += val;
+ val = float(v_data[j][i]);
+ val *= val;
+ valc += val;
valy = float(y_data[j][i]) + 128.0;
- valy *= valy;
- comb_data[j][i] = ValueType(std::sqrt(valc + valy) - 128.0);
+ valy *= valy;
+ comb_data[j][i] = ValueType( std::sqrt(valc+valy)-128.0 );
}// i
- }
- else // 422 format
- {
- for(int i = 0; i < comb_data.LengthX(); i += 2)
- {
+ }
+ else{ // 422 format
+ for (int i=0; i<comb_data.LengthX(); i+=2 ){
val = float(u_data[j][i>>1]);
- val *= val;
- valc = val;
+ val *= val;
+ valc = val;
- val = float(v_data[j][i>>1]);
- val *= val;
- valc += val;
+ val = float(v_data[j][i>>1]);
+ val *= val;
+ valc += val;
valy = float(y_data[j][i]) + 128.0;
- valy *= valy;
- comb_data[j][i] = ValueType(std::sqrt(valc + valy) - 128.0);
+ valy *= valy;
+ comb_data[j][i] = ValueType( std::sqrt(valc+valy)-128.0 );
- valy = float(y_data[j][i+1]) + 128.0;
- valy *= valy;
+ valy = float(y_data[j][i+1]) + 128.0;
+ valy *= valy;
- comb_data[j][i+1] = ValueType(std::sqrt(valc + valy) - 128.0);
+ comb_data[j][i+1] = ValueType( std::sqrt(valc+valy)-128.0 );
- }// i
- }
+ }// i
+ }
}// j
}
- else // 420 format
- {
- for(int j = 0; j < comb_data.LengthY(); j += 2)
- {
+ else{ // 420 format
+ for (int j=0; j<comb_data.LengthY(); j+=2 ) {
- for(int i = 0; i < comb_data.LengthX(); i += 2)
- {
+ for (int i=0; i<comb_data.LengthX(); i+=2 ){
val = float(u_data[j>>1][i>>1]);
- val *= val;
- valc = val;
+ val *= val;
+ valc = val;
- val = float(v_data[j>>1][i>>1]);
- val *= val;
- valc += val;
+ val = float(v_data[j>>1][i>>1]);
+ val *= val;
+ valc += val;
valy = float(y_data[j][i]) + 128.0;
- valy *= valy;
- comb_data[j][i] = ValueType(std::sqrt(valc + valy) - 128.0);
+ valy *= valy;
+ comb_data[j][i] = ValueType( std::sqrt(valc+valy)-128.0 );
- valy = float(y_data[j][i+1]) + 128.0;
- valy *= valy;
- comb_data[j][i+1] = ValueType(std::sqrt(valc + valy) - 128.0);
+ valy = float(y_data[j][i+1]) + 128.0;
+ valy *= valy;
+ comb_data[j][i+1] = ValueType( std::sqrt(valc+valy)-128.0 );
valy = float(y_data[j+1][i]) + 128.0;
- valy *= valy;
- comb_data[j+1][i] = ValueType(std::sqrt(valc + valy) - 128.0);
+ valy *= valy;
+ comb_data[j+1][i] = ValueType( std::sqrt(valc+valy)-128.0 );
- valy = float(y_data[j+1][i+1]) + 128.0;
- valy *= valy;
- comb_data[j+1][i+1] = ValueType(std::sqrt(valc + valy) - 128.0);
+ valy = float(y_data[j+1][i+1]) + 128.0;
+ valy *= valy;
+ comb_data[j+1][i+1] = ValueType( std::sqrt(valc+valy)-128.0 );
- }// i
+ }// i
}// j
}
@@ -393,16 +369,15 @@ void EncPicture::Combine(PicArray& comb_data, const PicArray& y_data,
}
-void EncPicture::DropRef(int rindex)
-{
+void EncPicture::DropRef( int rindex ){
std::vector<int>& refs = m_pparams.Refs();
- if(rindex == 1 || rindex == 2)
- refs.erase(refs.begin() + rindex - 1);
+ if (rindex==1 || rindex==2 )
+ refs.erase( refs.begin()+rindex-1 );
// Now reconfigure the motion data
- if(m_me_data != NULL)
- m_me_data->DropRef(rindex);
+ if ( m_me_data!=NULL )
+ m_me_data->DropRef( rindex );
}
diff --git a/src/filters/parser/DiracSplitter/libdirac/libdirac_encoder/enc_picture.h b/src/filters/parser/DiracSplitter/libdirac/libdirac_encoder/enc_picture.h
index 6f8b5690d..cbef4f5ce 100644
--- a/src/filters/parser/DiracSplitter/libdirac/libdirac_encoder/enc_picture.h
+++ b/src/filters/parser/DiracSplitter/libdirac/libdirac_encoder/enc_picture.h
@@ -64,34 +64,25 @@ static const unsigned int NO_ENC = 0;
class EncPicture : public Picture
{
public:
- EncPicture(const PictureParams& pp);
+ EncPicture( const PictureParams& pp );
virtual ~EncPicture();
//! Initialise the motion estimation data arrays
- void InitMEData(const PicturePredParams& predparams, const int num_refs);
+ void InitMEData( const PicturePredParams& predparams, const int num_refs);
//! Returns the motion data
- MEData& GetMEData()
- {
- return *m_me_data;
- }
+ MEData& GetMEData(){ return *m_me_data;}
//! Returns the motion data
- const MEData& GetMEData() const
- {
- return *m_me_data;
- }
+ const MEData& GetMEData() const { return *m_me_data;}
//! Drops a reference from the motion vector data
- void DropRef(int rindex);
+ void DropRef( int rindex );
//! Returns a given component of the original data
- const PicArray& OrigData(CompSort c) const
- {
- return *m_orig_data[(int) c];
- }
+ const PicArray& OrigData(CompSort c) const { return *m_orig_data[(int) c];}
//! Returns a given upconverted component of the original data
const PicArray& UpOrigData(CompSort cs) const;
@@ -106,56 +97,26 @@ public:
const PicArray& UpDataForME(bool combined_me) const;
- void UpdateStatus(const unsigned int mask)
- {
- m_status |= mask;
- }
+ void UpdateStatus( const unsigned int mask ){ m_status |= mask; }
- void FlipStatus(const unsigned int mask)
- {
- m_status ^= mask;
- }
+ void FlipStatus( const unsigned int mask){ m_status ^= mask; }
- void SetStatus(const int status)
- {
- m_status = status;
- }
+ void SetStatus( const int status ){ m_status = status; }
- unsigned int GetStatus() const
- {
- return m_status;
- }
+ unsigned int GetStatus() const{ return m_status; }
- double GetComplexity() const
- {
- return m_complexity;
- }
+ double GetComplexity() const {return m_complexity; }
- void SetComplexity(double c)
- {
- m_complexity = c;
- }
+ void SetComplexity(double c){ m_complexity = c; }
- double GetNormComplexity() const
- {
- return m_norm_complexity;
- }
+ double GetNormComplexity() const { return m_norm_complexity; }
- void SetNormComplexity(double c)
- {
- m_norm_complexity = c;
- }
+ void SetNormComplexity( double c ){ m_norm_complexity = c; }
- double GetPredBias() const
- {
- return m_pred_bias;
- }
+ double GetPredBias() const { return m_pred_bias; }
- void SetPredBias(double b)
- {
- m_pred_bias = b;
- }
+ void SetPredBias( double b ){ m_pred_bias = b; }
private:
@@ -163,15 +124,15 @@ private:
virtual void ClearData();
//! Filters a (field) picture vertically to reduce aliasing for motion estimation purposes
- void AntiAliasFilter(PicArray& out_data, const PicArray& in_data) const;
+ void AntiAliasFilter( PicArray& out_data, const PicArray& in_data ) const;
//! Returns an anti-aliased version of the original data
const PicArray& FiltData(CompSort c) const;
const PicArray& CombinedData() const;
const PicArray& UpCombinedData() const;
- void Combine(PicArray& comb_data, const PicArray& y_data,
- const PicArray& u_data, const PicArray& v_data) const;
+ void Combine( PicArray& comb_data, const PicArray& y_data,
+ const PicArray& u_data, const PicArray& v_data ) const;
//! Returns an upconverted anti-aliased version of the original data
const PicArray& UpFiltData(CompSort c) const;
diff --git a/src/filters/parser/DiracSplitter/libdirac/libdirac_encoder/enc_queue.cpp b/src/filters/parser/DiracSplitter/libdirac/libdirac_encoder/enc_queue.cpp
index ad6c11016..f64da8a0b 100644
--- a/src/filters/parser/DiracSplitter/libdirac/libdirac_encoder/enc_queue.cpp
+++ b/src/filters/parser/DiracSplitter/libdirac/libdirac_encoder/enc_queue.cpp
@@ -40,22 +40,21 @@
using namespace dirac;
//Simple constructor for decoder operation
-EncQueue::EncQueue() {}
+EncQueue::EncQueue(){}
//Copy constructor. Why anyone would need this I don't know.
EncQueue::EncQueue(const EncQueue& cpy)
-{
+ {
// first delete all frames in the current buffer
- for(size_t i = 0 ; i < m_pic_data.size() ; ++i)
+ for (size_t i=0 ; i<m_pic_data.size() ; ++i)
{
delete m_pic_data[i];
}//i
// next create new arrays, copying from the initialising buffer
m_pic_data.resize(cpy.m_pic_data.size());
- for(size_t i = 0 ; i < m_pic_data.size() ; ++i)
- {
- m_pic_data[i] = new EncPicture(*(cpy.m_pic_data[i]));
+ for (size_t i=0 ; i<m_pic_data.size() ; ++i){
+ m_pic_data[i] = new EncPicture( *(cpy.m_pic_data[i]) );
}//i
// now copy the map
@@ -64,21 +63,20 @@ EncQueue::EncQueue(const EncQueue& cpy)
}
//Assignment=. Not sure why this would be used either.
-EncQueue& EncQueue::operator=(const EncQueue& rhs)
-{
- if(&rhs != this)
+EncQueue& EncQueue::operator=(const EncQueue& rhs){
+ if (&rhs!=this)
{
// delete all the frames in the lhs buffer
- for(size_t i = 0 ; i < m_pic_data.size() ; ++i)
+ for (size_t i=0 ; i<m_pic_data.size() ; ++i)
{
delete m_pic_data[i];
}//i
// next create new arrays, copying from the rhs
m_pic_data.resize(rhs.m_pic_data.size());
- for(size_t i = 0 ; i < m_pic_data.size() ; ++i)
+ for (size_t i=0 ; i<m_pic_data.size() ; ++i)
{
- m_pic_data[i] = new EncPicture(*(rhs.m_pic_data[i]));
+ m_pic_data[i] = new EncPicture( *(rhs.m_pic_data[i]) );
}//i
// now copy the map
@@ -91,80 +89,76 @@ EncQueue& EncQueue::operator=(const EncQueue& rhs)
//Destructor
EncQueue::~EncQueue()
{
- for(size_t i = 0 ; i < m_pic_data.size() ; ++i)
+ for (size_t i=0 ; i<m_pic_data.size() ;++i)
delete m_pic_data[i];
}
-EncPicture& EncQueue::GetPicture(const unsigned int pnum)
-{
- //get picture with a given picture number, NOT with a given position in the buffer.
-//If the picture number does not occur, the first picture in the buffer is returned.
+EncPicture& EncQueue::GetPicture( const unsigned int pnum )
+{//get picture with a given picture number, NOT with a given position in the buffer.
+ //If the picture number does not occur, the first picture in the buffer is returned.
- std::map<unsigned int, unsigned int>::iterator it = m_pnum_map.find(pnum);
+ std::map<unsigned int,unsigned int>::iterator it = m_pnum_map.find(pnum);
unsigned int pos = 0;
- if(it != m_pnum_map.end())
+ if (it != m_pnum_map.end())
pos = it->second;
return *(m_pic_data[pos]);
}
-const EncPicture& EncQueue::GetPicture(const unsigned int pnum) const
-{
- //as above, but const version
+const EncPicture& EncQueue::GetPicture( const unsigned int pnum ) const
+{ //as above, but const version
- std::map<unsigned int, unsigned int>::const_iterator it = m_pnum_map.find(pnum);
+ std::map<unsigned int,unsigned int>::const_iterator it = m_pnum_map.find(pnum);
- unsigned int pos = 0;
- if(it != m_pnum_map.end())
+ unsigned int pos=0;
+ if (it != m_pnum_map.end())
pos = it->second;
return *(m_pic_data[pos]);
}
-EncPicture& EncQueue::GetPicture(const unsigned int pnum, bool& is_present)
-{
- //get picture with a given picture number, NOT with a given position in the buffer.
-//If the picture number does not occur, the first picture in the buffer is returned.
+EncPicture& EncQueue::GetPicture( const unsigned int pnum, bool& is_present )
+{//get picture with a given picture number, NOT with a given position in the buffer.
+ //If the picture number does not occur, the first picture in the buffer is returned.
- std::map<unsigned int, unsigned int>::iterator it = m_pnum_map.find(pnum);
+ std::map<unsigned int,unsigned int>::iterator it = m_pnum_map.find(pnum);
unsigned int pos = 0;
- if(it != m_pnum_map.end())
+ if (it != m_pnum_map.end())
{
is_present = true;
pos = it->second;
}
else
- is_present = false;
+ is_present=false;
return *(m_pic_data[pos]);
}
-const EncPicture& EncQueue::GetPicture(const unsigned int pnum, bool& is_present) const
-{
- //as above, but const version
+const EncPicture& EncQueue::GetPicture( const unsigned int pnum, bool& is_present ) const
+{ //as above, but const version
- std::map<unsigned int, unsigned int>::const_iterator it = m_pnum_map.find(pnum);
+ std::map<unsigned int,unsigned int>::const_iterator it = m_pnum_map.find(pnum);
- unsigned int pos = 0;
- if(it != m_pnum_map.end())
+ unsigned int pos=0;
+ if (it != m_pnum_map.end())
{
is_present = true;
pos = it->second;
}
else
- is_present = false;
+ is_present=false;
return *(m_pic_data[pos]);
}
-bool EncQueue::IsPictureAvail(const unsigned int pnum) const
+bool EncQueue::IsPictureAvail( const unsigned int pnum ) const
{
- std::map<unsigned int, unsigned int>::const_iterator it = m_pnum_map.find(pnum);
+ std::map<unsigned int,unsigned int>::const_iterator it = m_pnum_map.find(pnum);
- if(it != m_pnum_map.end())
+ if (it != m_pnum_map.end())
return true;
else
return false;
@@ -172,22 +166,21 @@ bool EncQueue::IsPictureAvail(const unsigned int pnum) const
std::vector<int> EncQueue::Members() const
{
- std::vector<int> members(0);
- for(unsigned int i = 0; i < m_pic_data.size(); ++i)
+ std::vector<int> members( 0 );
+ for (unsigned int i=0; i<m_pic_data.size(); ++i )
{
const PictureParams& pparams = m_pic_data[i]->GetPparams();
- members.push_back(pparams.PictureNum());
+ members.push_back( pparams.PictureNum() );
}// i
return members;
}
-void EncQueue::PushPicture(const PictureParams& pp)
-{
- // Put a new picture onto the top of the stack
+void EncQueue::PushPicture( const PictureParams& pp )
+{// Put a new picture onto the top of the stack
// if picture is present - return
- if(IsPictureAvail(pp.PictureNum()))
+ if (IsPictureAvail(pp.PictureNum()))
return;
// if ( pp.PicSort().IsRef() )
@@ -198,17 +191,17 @@ void EncQueue::PushPicture(const PictureParams& pp)
m_pic_data.push_back(pptr);
// put the picture number into the index table
- std::pair<unsigned int, unsigned int> temp_pair(pp.PictureNum() , m_pic_data.size() - 1);
+ std::pair<unsigned int,unsigned int> temp_pair(pp.PictureNum() , m_pic_data.size()-1);
m_pnum_map.insert(temp_pair);
}
-void EncQueue::CopyPicture(const EncPicture& picture)
+void EncQueue::CopyPicture( const EncPicture& picture )
{
PushPicture(picture.GetPparams());
bool is_present;
- EncPicture & p = GetPicture(picture.GetPparams().PictureNum(), is_present);
+ EncPicture & p= GetPicture(picture.GetPparams().PictureNum(), is_present);
if(is_present)
p = picture;
}
@@ -217,19 +210,19 @@ void EncQueue::ClearSlot(const unsigned int pos)
{
// Clear a slot corresponding to position pos to take more data
- std::pair<unsigned int, unsigned int>* tmp_pair;
+ std::pair<unsigned int,unsigned int>* tmp_pair;
- if(pos < m_pic_data.size())
+ if (pos<m_pic_data.size())
{
delete m_pic_data[pos];
m_pic_data.erase(m_pic_data.begin() + pos);
- //make a new map
+ //make a new map
m_pnum_map.clear();
- for(size_t i = 0 ; i < m_pic_data.size() ; ++i)
+ for (size_t i=0 ; i<m_pic_data.size() ; ++i)
{
- tmp_pair = new std::pair<unsigned int, unsigned int>(m_pic_data[i]->GetPparams().PictureNum() , i);
+ tmp_pair = new std::pair<unsigned int,unsigned int>( m_pic_data[i]->GetPparams().PictureNum() , i);
m_pnum_map.insert(*tmp_pair);
delete tmp_pair;
}//i
@@ -240,15 +233,15 @@ void EncQueue::ClearSlot(const unsigned int pos)
void EncQueue::SetRetiredPictureNum(const int show_pnum, const int current_coded_pnum)
{
- if(IsPictureAvail(current_coded_pnum))
+ if ( IsPictureAvail(current_coded_pnum))
{
PictureParams &pparams = GetPicture(current_coded_pnum).GetPparams();
pparams.SetRetiredPictureNum(-1);
- for(size_t i = 0 ; i < m_pic_data.size() ; ++i)
+ for (size_t i=0 ; i<m_pic_data.size() ; ++i)
{
- if(m_pic_data[i]->GetPparams().PicSort().IsRef())
+ if (m_pic_data[i]->GetPparams().PicSort().IsRef() )
{
- if((m_pic_data[i]->GetPparams().PictureNum() + m_pic_data[i]->GetPparams().ExpiryTime()) <= show_pnum)
+ if ( (m_pic_data[i]->GetPparams().PictureNum() + m_pic_data[i]->GetPparams().ExpiryTime() ) <= show_pnum)
{
pparams.SetRetiredPictureNum(m_pic_data[i]->GetPparams().PictureNum());
break;
@@ -259,34 +252,31 @@ void EncQueue::SetRetiredPictureNum(const int show_pnum, const int current_coded
}
void EncQueue::CleanAll(const int show_pnum, const int current_coded_pnum)
-{
- // clean out all frames that have expired
- if(IsPictureAvail(current_coded_pnum))
+{// clean out all frames that have expired
+ if (IsPictureAvail(current_coded_pnum))
{
- for(size_t i = 0 ; i < m_pic_data.size() ; ++i)
+ for (size_t i=0 ; i<m_pic_data.size() ; ++i)
{
- if((m_pic_data[i]->GetPparams().PictureNum() + m_pic_data[i]->GetPparams().ExpiryTime()) <= show_pnum)
+ if ( (m_pic_data[i]->GetPparams().PictureNum() + m_pic_data[i]->GetPparams().ExpiryTime() ) <= show_pnum)
ClearSlot(i);
}//i
}
}
void EncQueue::CleanRetired(const int show_pnum, const int current_coded_pnum)
-{
- // clean out all frames that have expired
- if(IsPictureAvail(current_coded_pnum))
+{// clean out all frames that have expired
+ if ( IsPictureAvail(current_coded_pnum) )
{
PictureParams &pparams = GetPicture(current_coded_pnum).GetPparams();
// Remove Reference picture specified in retired picture number.
- if(pparams.PicSort().IsRef() && pparams.RetiredPictureNum() >= 0)
+ if (pparams.PicSort().IsRef() && pparams.RetiredPictureNum()>= 0)
Remove(pparams.RetiredPictureNum());
pparams.SetRetiredPictureNum(-1);
// Remove non-reference frames that have expired
- for(size_t i = 0 ; i < m_pic_data.size() ; ++i)
- {
- if((m_pic_data[i]->GetPparams().PictureNum() +
- m_pic_data[i]->GetPparams().ExpiryTime()) <= show_pnum
- && m_pic_data[i]->GetPparams().PicSort().IsNonRef())
+ for (size_t i=0 ; i<m_pic_data.size() ; ++i){
+ if ( (m_pic_data[i]->GetPparams().PictureNum()+
+ m_pic_data[i]->GetPparams().ExpiryTime() )<=show_pnum
+ && m_pic_data[i]->GetPparams().PicSort().IsNonRef() )
ClearSlot(i);
}//i
}
@@ -294,9 +284,8 @@ void EncQueue::CleanRetired(const int show_pnum, const int current_coded_pnum)
void EncQueue::Remove(const int pnum)
{
- for(size_t i = 0 ; i < m_pic_data.size() ; ++i)
- {
- if(m_pic_data[i]->GetPparams().PictureNum() == pnum)
+ for (size_t i=0 ; i<m_pic_data.size() ; ++i){
+ if ( m_pic_data[i]->GetPparams().PictureNum() == pnum)
ClearSlot(i);
}//i
}
diff --git a/src/filters/parser/DiracSplitter/libdirac/libdirac_encoder/enc_queue.h b/src/filters/parser/DiracSplitter/libdirac/libdirac_encoder/enc_queue.h
index 975a02565..2d282ebce 100644
--- a/src/filters/parser/DiracSplitter/libdirac/libdirac_encoder/enc_queue.h
+++ b/src/filters/parser/DiracSplitter/libdirac/libdirac_encoder/enc_queue.h
@@ -46,180 +46,176 @@
namespace dirac
{
-//! Holds pictures both for reference and to overcome reordering delay
-/*!
- The buffer holds pictures in a stack to overcome both reordering due to
- bi-directional prediction and use as references for subsequence motion
- estimation. Pictures, and components of pictures, can be accessed by their
- picture numbers. GOP parameters can be included in the constructors so
- that pictures can be given types (I picture, L1 picture or L2 picture) on
- being pushed onto the stack; alternatively, these parameters can be
- overridden.
-*/
-class EncQueue
-{
-public:
- //! Default Constructor
- EncQueue();
-
- //! Constructor
- /*!
- Creates a EncQueue using the chroma format. Suitable for
- compressing when there are no L2 pictures, or when the temporal
- prediction structure is to be determined on the fly.
-
- \param cf the Chroma format of pictures in the buffer
- \param xlen the luma width of pictures in the buffer
- \param ylen the luma height of pictures in the buffer
- \param luma_depth the video depth of the luma comp in the buffer
- \param chroma_depth the video depth of the chroma comp in the buffer
- \param using_ac True if using Arithmetic coding to code coefficient data
-
- */
- EncQueue(ChromaFormat cf,
- const int xlen,
- const int ylen,
- const unsigned int luma_depth,
- const unsigned int chroma_depth,
- bool using_ac);
-
- //! Constructor
- /*!
- Creates a EncQueue using the chroma format, the number of L1
- pictures between I pictures and the separation in pictures between L1
- pictures. Suitable for compressing when there is a full GOP structure
- or when the temporal prediction structure is to be determined on
- the fly.
-
- \param cf the Chroma format of pictures in the buffer
- \param numL1 the number of Layer 1 pictures before the next I picture. 0 means that there is only one I picture.
- \param L1sep the number of Layer 2 pictures between Layer 1 pictures
- \param xlen the luma width of pictures in the buffer
- \param ylen the luma height of pictures in the buffer
- \param luma_depth the video depth of the luma comp in the buffer
- \param chroma_depth the video depth of the chroma comp in the buffer
- \param interlace Set true if material is being coded in interlaced mode
- \param using_ac True if using Arithmetic coding to code coefficient data
- */
- EncQueue(ChromaFormat cf,
- const int numL1,
- const int L1sep,
- const int xlen,
- const int ylen,
- const unsigned int luma_depth,
- const unsigned int chroma_depth,
- bool interlace,
- bool using_ac);
-
- //! Copy constructor
- /*!
- Copy constructor. Removes the current contents of the pictureture buffer
- and copies in the contents of the initialising buffer.
- */
- EncQueue(const EncQueue& cpy);
-
- //! Operator=.
+ //! Holds pictures both for reference and to overcome reordering delay
/*!
- Operator=. Assigns all elements of the rhs to the lhs.
+ The buffer holds pictures in a stack to overcome both reordering due to
+ bi-directional prediction and use as references for subsequence motion
+ estimation. Pictures, and components of pictures, can be accessed by their
+ picture numbers. GOP parameters can be included in the constructors so
+ that pictures can be given types (I picture, L1 picture or L2 picture) on
+ being pushed onto the stack; alternatively, these parameters can be
+ overridden.
*/
- EncQueue& operator=(const EncQueue& rhs);
-
- //! Destructor
- ~EncQueue();
-
- //! Get picture with a given picture number (NOT with a given position in the buffer)
- EncPicture& GetPicture(const unsigned int pnum);
-
- //! Get picture with a given picture number (NOT with a given position in the buffer)
- const EncPicture& GetPicture(const unsigned int pnum) const;
-
- //! Get picture with a given picture number, setting a flag to true if it's there
- EncPicture& GetPicture(const unsigned int pnum, bool& is_present);
-
- //! Get picture with a given picture number, setting a flag to true if it's there
- const EncPicture& GetPicture(const unsigned int pnum, bool& is_present) const;
-
- //! Return true if picture with the particular picture number is available else return false
- bool IsPictureAvail(const unsigned int pnum) const;
-
- //! Returns a list of member pictures
- std::vector<int> Members() const;
-
- //! Returns the size of the queue
- int Size() const
- {
- return m_pic_data.size();
- }
-
- //! Put a new picture into the top of the buffer
- /*!
- Put a new picture into the top of the buffer. EncPicture parameters
- associated with the picture will be as given by the picture parameter
- object.
- */
- void PushPicture(const PictureParams& pp);
-
- //! Put a copy of a new picture into the buffer
- /*!
- Put a copy of a new picture into the buffer.
- */
- void CopyPicture(const EncPicture& picture);
-
- //! Sets the reference picture number that will be cleaned
- /*!
- Indicate which picture which has been output and which is no longer
- required for reference. Expiry times are set in each picture's
- picture parameters.
- \param show_pnum picture number in display order that can be output
- \param current_coded_pnum picture number in display order of picture currently being coded
- */
- void SetRetiredPictureNum(const int show_pnum, const int current_coded_pnum);
-
- //! Delete all expired pictures
- /*!
- Delete pictures which have been output and which are no longer
- required for reference. Expiry times are set in each picture's
- picture parameters.
- \param show_pnum picture number in display order that can be output
- \param current_coded_pnum picture number in display order of picture currently being coded
- */
- void CleanAll(const int show_pnum, const int current_coded_pnum);
-
- //! Delete retired reference pictures and expired non-ref pictures
- /*!
- Delete pictures which have been output and retired reference pictures.
- Expiry times are set in each picture's picture parameters.
- \param show_pnum picture number in display order that can be output
- \param current_coded_pnum picture number in display order of picture currently being coded
- */
- void CleanRetired(const int show_pnum, const int current_coded_pnum);
-
- //! Delete picture
- /*!
- Delete picture.
- \param pnum picture number in display order to be deleted from picture buffer
- */
- void Remove(int pnum);
-
-private:
- //! Clear internal data slot number pos
- /*!
- Clear internal data slot number pos
- */
- void ClearSlot(const unsigned int pos);
-
-private:
+ class EncQueue{
+ public:
+ //! Default Constructor
+ EncQueue();
+
+ //! Constructor
+ /*!
+ Creates a EncQueue using the chroma format. Suitable for
+ compressing when there are no L2 pictures, or when the temporal
+ prediction structure is to be determined on the fly.
+
+ \param cf the Chroma format of pictures in the buffer
+ \param xlen the luma width of pictures in the buffer
+ \param ylen the luma height of pictures in the buffer
+ \param luma_depth the video depth of the luma comp in the buffer
+ \param chroma_depth the video depth of the chroma comp in the buffer
+ \param using_ac True if using Arithmetic coding to code coefficient data
+
+ */
+ EncQueue(ChromaFormat cf,
+ const int xlen,
+ const int ylen,
+ const unsigned int luma_depth,
+ const unsigned int chroma_depth,
+ bool using_ac);
+
+ //! Constructor
+ /*!
+ Creates a EncQueue using the chroma format, the number of L1
+ pictures between I pictures and the separation in pictures between L1
+ pictures. Suitable for compressing when there is a full GOP structure
+ or when the temporal prediction structure is to be determined on
+ the fly.
+
+ \param cf the Chroma format of pictures in the buffer
+ \param numL1 the number of Layer 1 pictures before the next I picture. 0 means that there is only one I picture.
+ \param L1sep the number of Layer 2 pictures between Layer 1 pictures
+ \param xlen the luma width of pictures in the buffer
+ \param ylen the luma height of pictures in the buffer
+ \param luma_depth the video depth of the luma comp in the buffer
+ \param chroma_depth the video depth of the chroma comp in the buffer
+ \param interlace Set true if material is being coded in interlaced mode
+ \param using_ac True if using Arithmetic coding to code coefficient data
+ */
+ EncQueue(ChromaFormat cf,
+ const int numL1,
+ const int L1sep,
+ const int xlen,
+ const int ylen,
+ const unsigned int luma_depth,
+ const unsigned int chroma_depth,
+ bool interlace,
+ bool using_ac);
+
+ //! Copy constructor
+ /*!
+ Copy constructor. Removes the current contents of the pictureture buffer
+ and copies in the contents of the initialising buffer.
+ */
+ EncQueue(const EncQueue& cpy);
+
+ //! Operator=.
+ /*!
+ Operator=. Assigns all elements of the rhs to the lhs.
+ */
+ EncQueue& operator=(const EncQueue& rhs);
+
+ //! Destructor
+ ~EncQueue();
+
+ //! Get picture with a given picture number (NOT with a given position in the buffer)
+ EncPicture& GetPicture(const unsigned int pnum );
+
+ //! Get picture with a given picture number (NOT with a given position in the buffer)
+ const EncPicture& GetPicture(const unsigned int pnum) const;
+
+ //! Get picture with a given picture number, setting a flag to true if it's there
+ EncPicture& GetPicture(const unsigned int pnum, bool& is_present);
+
+ //! Get picture with a given picture number, setting a flag to true if it's there
+ const EncPicture& GetPicture(const unsigned int pnum, bool& is_present) const;
+
+ //! Return true if picture with the particular picture number is available else return false
+ bool IsPictureAvail(const unsigned int pnum) const;
+
+ //! Returns a list of member pictures
+ std::vector<int> Members() const;
+
+ //! Returns the size of the queue
+ int Size() const { return m_pic_data.size(); }
+
+ //! Put a new picture into the top of the buffer
+ /*!
+ Put a new picture into the top of the buffer. EncPicture parameters
+ associated with the picture will be as given by the picture parameter
+ object.
+ */
+ void PushPicture(const PictureParams& pp);
+
+ //! Put a copy of a new picture into the buffer
+ /*!
+ Put a copy of a new picture into the buffer.
+ */
+ void CopyPicture( const EncPicture& picture );
+
+ //! Sets the reference picture number that will be cleaned
+ /*!
+ Indicate which picture which has been output and which is no longer
+ required for reference. Expiry times are set in each picture's
+ picture parameters.
+ \param show_pnum picture number in display order that can be output
+ \param current_coded_pnum picture number in display order of picture currently being coded
+ */
+ void SetRetiredPictureNum(const int show_pnum, const int current_coded_pnum);
+
+ //! Delete all expired pictures
+ /*!
+ Delete pictures which have been output and which are no longer
+ required for reference. Expiry times are set in each picture's
+ picture parameters.
+ \param show_pnum picture number in display order that can be output
+ \param current_coded_pnum picture number in display order of picture currently being coded
+ */
+ void CleanAll(const int show_pnum, const int current_coded_pnum);
+
+ //! Delete retired reference pictures and expired non-ref pictures
+ /*!
+ Delete pictures which have been output and retired reference pictures.
+ Expiry times are set in each picture's picture parameters.
+ \param show_pnum picture number in display order that can be output
+ \param current_coded_pnum picture number in display order of picture currently being coded
+ */
+ void CleanRetired(const int show_pnum, const int current_coded_pnum);
+
+ //! Delete picture
+ /*!
+ Delete picture.
+ \param pnum picture number in display order to be deleted from picture buffer
+ */
+ void Remove(int pnum);
+
+ private:
+ //! Clear internal data slot number pos
+ /*!
+ Clear internal data slot number pos
+ */
+ void ClearSlot(const unsigned int pos);
+
+ private:
// //! the count of the number of reference pictures in the buffer
// int m_ref_count;
- //! the buffer storing all the values
- std::vector<EncPicture*> m_pic_data;
+ //! the buffer storing all the values
+ std::vector<EncPicture*> m_pic_data;
- //!the map from picture numbers to position in the buffer
- std::map<unsigned int, unsigned int> m_pnum_map;
+ //!the map from picture numbers to position in the buffer
+ std::map<unsigned int,unsigned int> m_pnum_map;
-};
+ };
} // namespace dirac
diff --git a/src/filters/parser/DiracSplitter/libdirac/libdirac_encoder/picture_compress.cpp b/src/filters/parser/DiracSplitter/libdirac/libdirac_encoder/picture_compress.cpp
index 793652033..93c6be9b4 100644
--- a/src/filters/parser/DiracSplitter/libdirac/libdirac_encoder/picture_compress.cpp
+++ b/src/filters/parser/DiracSplitter/libdirac/libdirac_encoder/picture_compress.cpp
@@ -58,7 +58,7 @@ using namespace dirac;
#include <iostream>
#include <sstream>
-PictureCompressor::PictureCompressor(EncoderParams& encp) :
+PictureCompressor::PictureCompressor( EncoderParams& encp ) :
m_encparams(encp),
m_skipped(false),
m_use_global(false),
@@ -73,110 +73,101 @@ PictureCompressor::~PictureCompressor()
{}
-void PictureCompressor::PixelME(EncQueue& my_buffer , int pnum)
+void PictureCompressor::PixelME( EncQueue& my_buffer , int pnum )
{
- PixelMatcher pix_match(m_encparams);
- pix_match.DoSearch(my_buffer , pnum);
+ PixelMatcher pix_match( m_encparams );
+ pix_match.DoSearch( my_buffer , pnum );
}
-void PictureCompressor::CalcComplexity(EncQueue& my_buffer, int pnum , const OLBParams& olbparams)
+void PictureCompressor::CalcComplexity( EncQueue& my_buffer, int pnum , const OLBParams& olbparams )
{
- EncPicture& my_picture = my_buffer.GetPicture(pnum);
+ EncPicture& my_picture = my_buffer.GetPicture( pnum );
PictureParams& pparams = my_picture.GetPparams();
- if((my_picture.GetStatus()&DONE_PEL_ME) != 0)
- {
+ if ( (my_picture.GetStatus()&DONE_PEL_ME) != 0 ){
MEData& me_data = my_picture.GetMEData();
TwoDArray<MvCostData>* pcosts1;
TwoDArray<MvCostData>* pcosts2;
- pcosts1 = &me_data.PredCosts(1);
- if(pparams.NumRefs() > 1)
- pcosts2 = &me_data.PredCosts(2);
- else
- pcosts2 = pcosts1;
+ pcosts1 = &me_data.PredCosts(1);
+ if (pparams.NumRefs()>1)
+ pcosts2 = &me_data.PredCosts(2);
+ else
+ pcosts2 = pcosts1;
float cost1, cost2, cost;
- double total_cost1 = 0.0;
- double total_cost2 = 0.0;
- double total_cost = 0.0;
-
- int count1 = 0;
- int count = 0;
-
- float cost_threshold = float(olbparams.Xblen() * olbparams.Yblen() * 10);
-
- for(int j = 4; j < pcosts1->LengthY() - 4; ++j)
- {
- for(int i = 4; i < pcosts1->LengthX() - 4; ++i)
- {
- cost1 = (*pcosts1)[j][i].SAD;
- cost2 = (*pcosts2)[j][i].SAD;
- cost = std::min(cost1, cost2);
- total_cost1 += cost1;
- total_cost2 += cost2;
- total_cost += cost;
- if(pparams.NumRefs() > 1 && cost <= cost_threshold)
- {
- ++count;
- if(cost1 <= cost2)
- ++count1;
- }
- }
-
- }
- total_cost1 *= olbparams.Xbsep() * olbparams.Ybsep();
- total_cost1 /= olbparams.Xblen() * olbparams.Yblen();
-
- total_cost2 *= olbparams.Xbsep() * olbparams.Ybsep();
- total_cost2 /= olbparams.Xblen() * olbparams.Yblen();
-
- if(pparams.NumRefs() > 1)
- {
- my_picture.SetPredBias(float(count1) / float(count));
+ double total_cost1 = 0.0;
+ double total_cost2 = 0.0;
+ double total_cost = 0.0;
+
+ int count1=0;int count=0;
+
+ float cost_threshold = float(olbparams.Xblen()*olbparams.Yblen()*10);
+
+ for (int j=4; j<pcosts1->LengthY()-4; ++j){
+ for (int i=4; i<pcosts1->LengthX()-4; ++i){
+ cost1 = (*pcosts1)[j][i].SAD;
+ cost2 = (*pcosts2)[j][i].SAD;
+ cost = std::min(cost1, cost2);
+ total_cost1 += cost1;
+ total_cost2 += cost2;
+ total_cost += cost;
+ if (pparams.NumRefs()>1 && cost<=cost_threshold){
+ ++count;
+ if (cost1<=cost2)
+ ++count1;
+ }
+ }
+
+ }
+ total_cost1 *= olbparams.Xbsep()*olbparams.Ybsep();
+ total_cost1 /= olbparams.Xblen()*olbparams.Yblen();
+
+ total_cost2 *= olbparams.Xbsep()*olbparams.Ybsep();
+ total_cost2 /= olbparams.Xblen()*olbparams.Yblen();
+
+ if (pparams.NumRefs()>1){
+ my_picture.SetPredBias(float(count1)/float(count));
}
- else
- my_picture.SetPredBias(0.5);
+ else
+ my_picture.SetPredBias(0.5);
- total_cost *= olbparams.Xbsep() * olbparams.Ybsep();
- total_cost /= olbparams.Xblen() * olbparams.Yblen();
+ total_cost *= olbparams.Xbsep()*olbparams.Ybsep();
+ total_cost /= olbparams.Xblen()*olbparams.Yblen();
// my_picture.SetComplexity( total_cost );
- my_picture.SetComplexity(total_cost * total_cost);
+ my_picture.SetComplexity( total_cost*total_cost );
}
}
-void PictureCompressor::CalcComplexity2(EncQueue& my_buffer, int pnum)
+void PictureCompressor::CalcComplexity2( EncQueue& my_buffer, int pnum )
{
// to be used after doing motion compensation
- EncPicture& my_picture = my_buffer.GetPicture(pnum);
- const PicArray& pic_data = my_picture.Data(Y_COMP);
+ EncPicture& my_picture = my_buffer.GetPicture( pnum );
+ const PicArray& pic_data = my_picture.Data( Y_COMP );
- if((my_picture.GetStatus()&DONE_MC) != 0)
- {
+ if ( (my_picture.GetStatus()&DONE_MC) != 0 ){
float cost;
- double total_sq_cost = 0.0;
- double total_cost = 0.0;
+ double total_sq_cost = 0.0;
+ double total_cost = 0.0;
- for(int j = 0; j < pic_data.LengthY(); ++j)
- {
- for(int i = 0; i < pic_data.LengthX(); ++i)
- {
- cost = float(pic_data[j][i]);
- total_cost += cost;
- total_sq_cost += cost * cost;
- }
+ for (int j=0; j<pic_data.LengthY(); ++j){
+ for (int i=0; i<pic_data.LengthX(); ++i){
+ cost = float( pic_data[j][i] );
+ total_cost += cost;
+ total_sq_cost += cost*cost;
+ }
- }
+ }
- total_cost /= (pic_data.LengthX() * pic_data.LengthY());
- total_sq_cost /= (pic_data.LengthX() * pic_data.LengthY());
+ total_cost /= ( pic_data.LengthX()*pic_data.LengthY() );
+ total_sq_cost /= ( pic_data.LengthX()*pic_data.LengthY() );
- my_picture.SetComplexity(total_sq_cost - total_cost * total_cost);
+ my_picture.SetComplexity( total_sq_cost - total_cost*total_cost );
}
@@ -184,40 +175,37 @@ void PictureCompressor::CalcComplexity2(EncQueue& my_buffer, int pnum)
-void PictureCompressor::NormaliseComplexity(EncQueue& my_buffer, int pnum)
+void PictureCompressor::NormaliseComplexity( EncQueue& my_buffer, int pnum )
{
- EncPicture& my_picture = my_buffer.GetPicture(pnum);
+ EncPicture& my_picture = my_buffer.GetPicture( pnum );
- if((my_picture.GetStatus()&DONE_PIC_COMPLEXITY) != 0)
- {
+ if ( (my_picture.GetStatus()&DONE_PIC_COMPLEXITY) != 0 ){
- std::vector<int> queue_members = my_buffer.Members();
+ std::vector<int> queue_members = my_buffer.Members();
- double mean_complexity = 0.0;
- int count = 0;
- for(size_t i = 0; i < queue_members.size(); ++ i)
- {
- int n = queue_members[i];
- EncPicture& enc_pic = my_buffer.GetPicture(n);
+ double mean_complexity = 0.0;
+ int count = 0;
+ for (size_t i=0; i<queue_members.size(); ++ i){
+ int n = queue_members[i];
+ EncPicture& enc_pic = my_buffer.GetPicture( n );
- if((enc_pic.GetStatus()&DONE_PIC_COMPLEXITY) != 0
- && enc_pic.GetPparams().PicSort().IsInter()
- && n >= pnum - 10
- && n <= pnum + 10)
- {
- mean_complexity += enc_pic.GetComplexity();
- count++;
- }
+ if ( (enc_pic.GetStatus()&DONE_PIC_COMPLEXITY) != 0
+ && enc_pic.GetPparams().PicSort().IsInter()
+ && n >= pnum - 10
+ && n <= pnum + 10){
+ mean_complexity += enc_pic.GetComplexity();
+ count++;
+ }
- }
- mean_complexity /= count;
- my_picture.SetNormComplexity(my_picture.GetComplexity() / mean_complexity);
+ }
+ mean_complexity /= count;
+ my_picture.SetNormComplexity( my_picture.GetComplexity() / mean_complexity );
}
}
-void PictureCompressor::SubPixelME(EncQueue& my_buffer , int pnum)
+void PictureCompressor::SubPixelME( EncQueue& my_buffer , int pnum )
{
const std::vector<int>& refs = my_buffer.GetPicture(pnum).GetPparams().Refs();
const int num_refs = refs.size();
@@ -227,7 +215,7 @@ void PictureCompressor::SubPixelME(EncQueue& my_buffer , int pnum)
PicturePredParams& predparams = me_data.GetPicPredParams();
float lambda;
- if(pparams.IsBPicture())
+ if ( pparams.IsBPicture())
lambda = m_encparams.L2MELambda();
else
lambda = m_encparams.L1MELambda();
@@ -235,17 +223,17 @@ void PictureCompressor::SubPixelME(EncQueue& my_buffer , int pnum)
//lambda *= my_buffer.GetPicture(pnum).GetNormComplexity();
// Set up the lambda to be used
- me_data.SetLambdaMap(num_refs , lambda);
+ me_data.SetLambdaMap( num_refs , lambda );
m_orig_prec = predparams.MVPrecision();
// Step 2.
// Pixel accurate vectors are then refined to sub-pixel accuracy
- if(m_orig_prec != MV_PRECISION_PIXEL)
+ if (m_orig_prec != MV_PRECISION_PIXEL)
{
- SubpelRefine pelrefine(m_encparams);
- pelrefine.DoSubpel(my_buffer , pnum);
+ SubpelRefine pelrefine( m_encparams );
+ pelrefine.DoSubpel( my_buffer , pnum );
}
else
{
@@ -253,17 +241,17 @@ void PictureCompressor::SubPixelME(EncQueue& my_buffer , int pnum)
// Mutiplying the motion vectors by 2 and setting MV precision to
// HALF_PIXEL to implement pixel accurate motion estimate
MvArray &mv_arr1 = me_data.Vectors(1);
- for(int j = 0; j < mv_arr1.LengthY(); ++j)
+ for (int j = 0; j < mv_arr1.LengthY(); ++j)
{
- for(int i = 0; i < mv_arr1.LengthX(); ++i)
+ for (int i = 0; i < mv_arr1.LengthX(); ++i)
mv_arr1[j][i] = mv_arr1[j][i] << 1;
}
- if(num_refs > 1)
+ if (num_refs > 1)
{
MvArray &mv_arr2 = me_data.Vectors(2);
- for(int j = 0; j < mv_arr2.LengthY(); ++j)
+ for (int j = 0; j < mv_arr2.LengthY(); ++j)
{
- for(int i = 0; i < mv_arr2.LengthX(); ++i)
+ for (int i = 0; i < mv_arr2.LengthX(); ++i)
mv_arr2[j][i] = mv_arr2[j][i] << 1;
}
}
@@ -272,36 +260,36 @@ void PictureCompressor::SubPixelME(EncQueue& my_buffer , int pnum)
}
-void PictureCompressor::ModeDecisionME(EncQueue& my_buffer, int pnum)
+void PictureCompressor::ModeDecisionME( EncQueue& my_buffer, int pnum )
{
MEData& me_data = my_buffer.GetPicture(pnum).GetMEData();
PictureParams& pparams = my_buffer.GetPicture(pnum).GetPparams();
PicturePredParams& predparams = me_data.GetPicPredParams();
- ModeDecider my_mode_dec(m_encparams);
- my_mode_dec.DoModeDecn(my_buffer , pnum);
+ ModeDecider my_mode_dec( m_encparams );
+ my_mode_dec.DoModeDecn( my_buffer , pnum );
const int num_refs = pparams.NumRefs();
- if(m_orig_prec == MV_PRECISION_PIXEL)
+ if (m_orig_prec == MV_PRECISION_PIXEL)
{
// FIXME: HACK HACK
// Divide the motion vectors by 2 to convert back to pixel
// accurate motion vectors and reset MV precision to
// PIXEL accuracy
MvArray &mv_arr1 = me_data.Vectors(1);
- for(int j = 0; j < mv_arr1.LengthY(); ++j)
+ for (int j = 0; j < mv_arr1.LengthY(); ++j)
{
- for(int i = 0; i < mv_arr1.LengthX(); ++i)
+ for (int i = 0; i < mv_arr1.LengthX(); ++i)
mv_arr1[j][i] = mv_arr1[j][i] >> 1;
}
- if(num_refs > 1)
+ if (num_refs > 1)
{
MvArray &mv_arr2 = me_data.Vectors(2);
- for(int j = 0; j < mv_arr2.LengthY(); ++j)
+ for (int j = 0; j < mv_arr2.LengthY(); ++j)
{
- for(int i = 0; i < mv_arr2.LengthX(); ++i)
- mv_arr2[j][i] = mv_arr2[j][i] >> 1;
+ for (int i = 0; i < mv_arr2.LengthX(); ++i)
+ mv_arr2[j][i] = mv_arr2[j][i]>>1;
}
}
predparams.SetMVPrecision(MV_PRECISION_PIXEL);
@@ -309,7 +297,7 @@ void PictureCompressor::ModeDecisionME(EncQueue& my_buffer, int pnum)
}
-void PictureCompressor::IntraModeAnalyse(EncQueue& my_buffer, int pnum)
+void PictureCompressor::IntraModeAnalyse( EncQueue& my_buffer, int pnum )
{
MEData& me_data = my_buffer.GetPicture(pnum).GetMEData();
@@ -317,118 +305,113 @@ void PictureCompressor::IntraModeAnalyse(EncQueue& my_buffer, int pnum)
const TwoDArray<PredMode>& modes = me_data.Mode();
int count_intra = 0;
- for(int j = 0 ; j < modes.LengthY() ; ++j)
+ for ( int j=0 ; j<modes.LengthY() ; ++j )
{
- for(int i = 0 ; i < modes.LengthX() ; ++i)
+ for ( int i=0 ; i<modes.LengthX() ; ++i )
{
- if(modes[j][i] == INTRA)
+ if ( modes[j][i] == INTRA )
count_intra++;
}
}// j
- me_data.SetIntraBlockRatio(static_cast<double>(count_intra) /
- static_cast<double>(modes.LengthX() * modes.LengthY()));
+ me_data.SetIntraBlockRatio(static_cast<double>( count_intra ) /
+ static_cast<double>( modes.LengthX() * modes.LengthY() ) );
}
-void PictureCompressor::MotionCompensate(EncQueue& my_buffer, int pnum,
- AddOrSub dirn)
+void PictureCompressor::MotionCompensate( EncQueue& my_buffer, int pnum,
+ AddOrSub dirn )
{
EncPicture* my_pic = &my_buffer.GetPicture(pnum);
std::vector<int>& my_refs = my_pic->GetPparams().Refs();
Picture* ref_pics[2];
- ref_pics[0] = &my_buffer.GetPicture(my_refs[0]);
- if(my_refs.size() > 1)
- ref_pics[1] = &my_buffer.GetPicture(my_refs[1]);
+ ref_pics[0]=&my_buffer.GetPicture(my_refs[0]);
+ if (my_refs.size()>1)
+ ref_pics[1]=&my_buffer.GetPicture(my_refs[1]);
else
- ref_pics[1] = &my_buffer.GetPicture(my_refs[0]);
+ ref_pics[1]=&my_buffer.GetPicture(my_refs[0]);
PicturePredParams& predparams = my_pic->GetMEData().GetPicPredParams();
- MotionCompensator::CompensatePicture(predparams , dirn ,
- my_pic->GetMEData() , my_pic, ref_pics);
+ MotionCompensator::CompensatePicture( predparams , dirn ,
+ my_pic->GetMEData() , my_pic, ref_pics );
}
-void PictureCompressor::Prefilter(EncQueue& my_buffer, int pnum)
+void PictureCompressor::Prefilter( EncQueue& my_buffer, int pnum )
{
- Picture& my_picture = my_buffer.GetPicture(pnum);
+ Picture& my_picture = my_buffer.GetPicture( pnum );
- for(int c = 0; c < 3; ++c)
- {
- if(m_encparams.Prefilter() == RECTLP)
- LPFilter(my_picture.Data((CompSort) c) , m_encparams.Qf(),
- m_encparams.PrefilterStrength());
+ for (int c=0; c<3; ++c ){
+ if ( m_encparams.Prefilter() == RECTLP )
+ LPFilter( my_picture.Data( (CompSort) c) , m_encparams.Qf(),
+ m_encparams.PrefilterStrength() );
- if(m_encparams.Prefilter() == DIAGLP)
+ if ( m_encparams.Prefilter() == DIAGLP )
// DiagFilter( my_picture.Data( (CompSort) c), 3.0, 5 );
- DiagFilter(my_picture.Data((CompSort) c) , m_encparams.Qf(),
- m_encparams.PrefilterStrength());
+ DiagFilter( my_picture.Data( (CompSort) c) , m_encparams.Qf(),
+ m_encparams.PrefilterStrength() );
}
}
-void PictureCompressor::DoDWT(EncQueue& my_buffer , int pnum, Direction dirn)
+void PictureCompressor::DoDWT( EncQueue& my_buffer , int pnum, Direction dirn )
{
- Picture& my_picture = my_buffer.GetPicture(pnum);
+ Picture& my_picture = my_buffer.GetPicture( pnum );
PictureParams& pparams = my_picture.GetPparams();
const PictureSort& psort = pparams.PicSort();
// Set the wavelet filter
- if(psort.IsIntra())
- {
- m_encparams.SetTransformFilter(m_encparams.IntraTransformFilter());
- m_encparams.SetUsualCodeBlocks(INTRA_PICTURE);
+ if ( psort.IsIntra() ){
+ m_encparams.SetTransformFilter( m_encparams.IntraTransformFilter() );
+ m_encparams.SetUsualCodeBlocks( INTRA_PICTURE );
}
- else
- {
- m_encparams.SetTransformFilter(m_encparams.InterTransformFilter());
- m_encparams.SetUsualCodeBlocks(INTER_PICTURE);
+ else{
+ m_encparams.SetTransformFilter( m_encparams.InterTransformFilter() );
+ m_encparams.SetUsualCodeBlocks( INTER_PICTURE );
}
- const int depth = m_encparams.TransformDepth();
+ const int depth=m_encparams.TransformDepth();
const WltFilter filter = m_encparams.TransformFilter();
- WaveletTransform wtransform(depth, filter);
+ WaveletTransform wtransform( depth, filter );
- if(dirn == FORWARD)
- my_picture.InitWltData(depth);
+ if ( dirn==FORWARD )
+ my_picture.InitWltData( depth );
- for(int c = 0; c < 3; ++c)
- {
+ for (int c=0; c<3; ++c){
- PicArray& comp_data = my_buffer.GetPicture(pnum).Data((CompSort) c);
- CoeffArray& coeff_data = my_buffer.GetPicture(pnum).WltData((CompSort) c);
+ PicArray& comp_data = my_buffer.GetPicture( pnum ).Data((CompSort) c );
+ CoeffArray& coeff_data = my_buffer.GetPicture( pnum ).WltData((CompSort) c );
- wtransform.Transform(dirn , comp_data, coeff_data);
+ wtransform.Transform( dirn , comp_data, coeff_data );
}
}
-void PictureCompressor::CodeResidue(EncQueue& my_buffer ,
- int pnum, PictureByteIO* p_picture_byteio)
+void PictureCompressor::CodeResidue( EncQueue& my_buffer ,
+ int pnum, PictureByteIO* p_picture_byteio )
{
- EncPicture& my_picture = my_buffer.GetPicture(pnum);
+ EncPicture& my_picture = my_buffer.GetPicture( pnum );
PictureParams& pparams = my_picture.GetPparams();
- if(!m_skipped)
- {
+ if ( !m_skipped ){
// If not skipped we continue with the coding ...
- if(m_encparams.Verbose())
- std::cout << std::endl << "Using QF: " << m_encparams.Qf();
+ if (m_encparams.Verbose() )
+ std::cout<<std::endl<<"Using QF: "<<m_encparams.Qf();
//Write Transform Header
TransformByteIO *p_transform_byteio = new TransformByteIO(pparams,
- static_cast<CodecParams&>(m_encparams));
+ static_cast<CodecParams&>(m_encparams));
p_picture_byteio->SetTransformData(p_transform_byteio);
p_transform_byteio->Output();
/* Code component data */
/////////////////////////
- CompCompressor my_compcoder(m_encparams , pparams);
+ CompCompressor my_compcoder(m_encparams , pparams );
- const int depth = m_encparams.TransformDepth();
+ const int depth=m_encparams.TransformDepth();
PicArray* comp_data[3];
CoeffArray* coeff_data[3];
@@ -436,45 +419,41 @@ void PictureCompressor::CodeResidue(EncQueue& my_buffer ,
float lambda[3];
// Construction and definition of objects
- for(int c = 0; c < 3; ++c)
- {
- comp_data[c] = &my_picture.Data((CompSort) c);
- coeff_data[c] = &my_picture.WltData((CompSort) c);
- est_bits[c] = new OneDArray<unsigned int>(Range(1, 3 * depth + 1));
+ for (int c=0;c<3;++c){
+ comp_data[c] = &my_picture.Data((CompSort) c );
+ coeff_data[c] = &my_picture.WltData((CompSort) c );
+ est_bits[c] = new OneDArray<unsigned int>( Range( 1, 3*depth+1 ) );
}// c
/* Do the wavelet transforms and select the component
* quantisers using perceptual weighting
*/
- double cpd_scale;
- if(pparams.PicSort().IsIntra())
- {
- cpd_scale = 1.0;
- }
- else
- {
- float intra_ratio = my_picture.GetMEData().IntraBlockRatio();
+ double cpd_scale;
+ if (pparams.PicSort().IsIntra() ){
+ cpd_scale = 1.0;
+ }
+ else{
+ float intra_ratio = my_picture.GetMEData().IntraBlockRatio();
- cpd_scale = 5.0 * intra_ratio * 1.0 + (1.0 - 5.0 * intra_ratio) * 0.125;
- cpd_scale = std::max(0.125, std::min(1.2, cpd_scale));
- }
- for(int c = 0; c < 3; ++c)
- {
- lambda[c] = GetCompLambda(my_picture, (CompSort) c);
+ cpd_scale = 5.0*intra_ratio*1.0 + (1.0-5.0*intra_ratio)*0.125;
+ cpd_scale = std::max( 0.125, std::min( 1.2, cpd_scale ) );
+ }
+ for (int c=0; c<3; ++c){
+ lambda[c] = GetCompLambda( my_picture, (CompSort) c );
- coeff_data[c]->SetBandWeights(m_encparams , pparams, (CompSort) c, cpd_scale);
+ coeff_data[c]->SetBandWeights( m_encparams , pparams, (CompSort) c, cpd_scale);
SubbandList& bands = coeff_data[c]->BandList();
- SetupCodeBlocks(bands);
- SelectQuantisers(*(coeff_data[c]) , bands , lambda[c],
- *est_bits[c] , m_encparams.GetCodeBlockMode(), pparams, (CompSort) c);
+ SetupCodeBlocks( bands );
+ SelectQuantisers( *(coeff_data[c]) , bands , lambda[c],
+ *est_bits[c] , m_encparams.GetCodeBlockMode(), pparams, (CompSort) c );
- p_transform_byteio->AddComponent(my_compcoder.Compress(
- *(coeff_data[c]), bands, (CompSort) c, *est_bits[c]));
+ p_transform_byteio->AddComponent( my_compcoder.Compress(
+ *(coeff_data[c]), bands, (CompSort) c, *est_bits[c] ) );
}
// Destruction of objects
- for(int c = 0; c < 3; ++c)
+ for (int c=0; c<3; ++c)
delete est_bits[c];
}//?m_skipped
@@ -488,72 +467,70 @@ void PictureCompressor::CodeMVData(EncQueue& my_buffer, int pnum, PictureByteIO*
EncPicture& my_picture = my_buffer.GetPicture(pnum);
PictureParams& pparams = my_picture.GetPparams();
- MvData& mv_data = static_cast<MvData&>(my_picture.GetMEData());
+ MvData& mv_data = static_cast<MvData&> (my_picture.GetMEData());
// If we're using global motion parameters, code them
- if(m_use_global)
- {
- /*
- Code the global motion parameters
- TBC ....
- */
+ if (m_use_global){
+ /*
+ Code the global motion parameters
+ TBC ....
+ */
}
// If we're using block motion vectors, code them
- if(m_use_block_mv)
- {
+ if ( m_use_block_mv ){
MvDataByteIO *mv_byteio = new MvDataByteIO(pparams, mv_data.GetPicPredParams());
pic_byteio->SetMvData(mv_byteio);
- SplitModeCodec smode_coder(mv_byteio->SplitModeData()->DataBlock(), TOTAL_MV_CTXS);
- smode_coder.Compress(mv_data);
+ SplitModeCodec smode_coder( mv_byteio->SplitModeData()->DataBlock(), TOTAL_MV_CTXS);
+ smode_coder.Compress( mv_data );
mv_byteio->SplitModeData()->Output();
- PredModeCodec pmode_coder(mv_byteio->PredModeData()->DataBlock(), TOTAL_MV_CTXS, pparams.NumRefs());
- pmode_coder.Compress(mv_data);
+ PredModeCodec pmode_coder( mv_byteio->PredModeData()->DataBlock(), TOTAL_MV_CTXS, pparams.NumRefs() );
+ pmode_coder.Compress( mv_data );
mv_byteio->PredModeData()->Output();
- VectorElementCodec vcoder1h(mv_byteio->MV1HorizData()->DataBlock(), 1,
- HORIZONTAL, TOTAL_MV_CTXS);
- vcoder1h.Compress(mv_data);
+ VectorElementCodec vcoder1h( mv_byteio->MV1HorizData()->DataBlock(), 1,
+ HORIZONTAL, TOTAL_MV_CTXS);
+ vcoder1h.Compress( mv_data );
mv_byteio->MV1HorizData()->Output();
- VectorElementCodec vcoder1v(mv_byteio->MV1VertData()->DataBlock(), 1,
- VERTICAL, TOTAL_MV_CTXS);
- vcoder1v.Compress(mv_data);
+ VectorElementCodec vcoder1v( mv_byteio->MV1VertData()->DataBlock(), 1,
+ VERTICAL, TOTAL_MV_CTXS);
+ vcoder1v.Compress( mv_data );
mv_byteio->MV1VertData()->Output();
- if(pparams.NumRefs() > 1)
+ if ( pparams.NumRefs()>1 )
{
- VectorElementCodec vcoder2h(mv_byteio->MV2HorizData()->DataBlock(), 2,
- HORIZONTAL, TOTAL_MV_CTXS);
- vcoder2h.Compress(mv_data);
+ VectorElementCodec vcoder2h( mv_byteio->MV2HorizData()->DataBlock(), 2,
+ HORIZONTAL, TOTAL_MV_CTXS);
+ vcoder2h.Compress( mv_data );
mv_byteio->MV2HorizData()->Output();
- VectorElementCodec vcoder2v(mv_byteio->MV2VertData()->DataBlock(), 2,
- VERTICAL, TOTAL_MV_CTXS);
- vcoder2v.Compress(mv_data);
+ VectorElementCodec vcoder2v( mv_byteio->MV2VertData()->DataBlock(), 2,
+ VERTICAL, TOTAL_MV_CTXS);
+ vcoder2v.Compress( mv_data );
mv_byteio->MV2VertData()->Output();
}
- DCCodec ydc_coder(mv_byteio->YDCData()->DataBlock(), Y_COMP, TOTAL_MV_CTXS);
- ydc_coder.Compress(mv_data);
+ DCCodec ydc_coder( mv_byteio->YDCData()->DataBlock(), Y_COMP, TOTAL_MV_CTXS);
+ ydc_coder.Compress( mv_data );
mv_byteio->YDCData()->Output();
- DCCodec udc_coder(mv_byteio->UDCData()->DataBlock(), U_COMP, TOTAL_MV_CTXS);
- udc_coder.Compress(mv_data);
+ DCCodec udc_coder( mv_byteio->UDCData()->DataBlock(), U_COMP, TOTAL_MV_CTXS);
+ udc_coder.Compress( mv_data );
mv_byteio->UDCData()->Output();
- DCCodec vdc_coder(mv_byteio->VDCData()->DataBlock(), V_COMP, TOTAL_MV_CTXS);
- vdc_coder.Compress(mv_data);
+ DCCodec vdc_coder( mv_byteio->VDCData()->DataBlock(), V_COMP, TOTAL_MV_CTXS);
+ vdc_coder.Compress( mv_data );
mv_byteio->VDCData()->Output();
mv_byteio->Output();
}
}
-float PictureCompressor::GetCompLambda(const EncPicture& my_picture,
- const CompSort csort)
+float PictureCompressor::GetCompLambda( const EncPicture& my_picture,
+ const CompSort csort )
{
const PictureParams& pparams = my_picture.GetPparams();
@@ -561,166 +538,157 @@ float PictureCompressor::GetCompLambda(const EncPicture& my_picture,
float lambda;
- if(psort.IsIntra())
- {
- if(m_is_a_cut)
- lambda = m_encparams.L1Lambda() / 8;
- else
+ if ( psort.IsIntra() ){
+ if ( m_is_a_cut )
+ lambda = m_encparams.L1Lambda()/8;
+ else
lambda = m_encparams.ILambda();
}
- else
- {
- double log_intra_lambda = std::log10(m_encparams.ILambda());
- /*
- double picture_lambda = m_encparams.L1Lambda() / my_picture.GetNormComplexity();
- if (pparams.IsBPicture() )
- picture_lambda *= 1.2;
-
- double log_picture_lambda = std::log10( picture_lambda );
- */
+ else{
+ double log_intra_lambda = std::log10( m_encparams.ILambda() );
+/*
+double picture_lambda = m_encparams.L1Lambda() / my_picture.GetNormComplexity();
+if (pparams.IsBPicture() )
+ picture_lambda *= 1.2;
+
+ double log_picture_lambda = std::log10( picture_lambda );
+*/
///*
double log_picture_lambda;
- if(pparams.IsBPicture())
- log_picture_lambda = std::log10(m_encparams.L2Lambda());
+ if (pparams.IsBPicture() )
+ log_picture_lambda= std::log10( m_encparams.L2Lambda() );
else
- log_picture_lambda = std::log10(m_encparams.L1Lambda());
+ log_picture_lambda= std::log10( m_encparams.L1Lambda() );
//*/
float intra_ratio = my_picture.GetMEData().IntraBlockRatio();
- lambda = std::pow(10.0, 3.0 * intra_ratio * log_intra_lambda +
- (1.0 - 3.0 * intra_ratio) * log_picture_lambda);
+ lambda= std::pow(10.0, 3.0*intra_ratio*log_intra_lambda+
+ (1.0-3.0*intra_ratio)*log_picture_lambda );
//lambda /= my_picture.GetNormComplexity();
}
- if(csort == U_COMP)
- lambda *= m_encparams.UFactor();
- if(csort == V_COMP)
- lambda *= m_encparams.VFactor();
+ if (csort == U_COMP)
+ lambda*= m_encparams.UFactor();
+ if (csort == V_COMP)
+ lambda*= m_encparams.VFactor();
return lambda;
}
-void PictureCompressor::SetupCodeBlocks(SubbandList& bands)
+void PictureCompressor::SetupCodeBlocks( SubbandList& bands )
{
int xregions;
int yregions;
- for(int band_num = 1; band_num <= bands.Length() ; ++band_num)
- {
- if(m_encparams.SpatialPartition())
- {
- int level = m_encparams.TransformDepth() - (band_num - 1) / 3;
+ for (int band_num = 1; band_num<=bands.Length() ; ++band_num){
+ if (m_encparams.SpatialPartition()){
+ int level = m_encparams.TransformDepth() - (band_num-1)/3;
const CodeBlocks &cb = m_encparams.GetCodeBlocks(level);
xregions = cb.HorizontalCodeBlocks();
yregions = cb.VerticalCodeBlocks();
}
- else
- {
- xregions = 1;
- yregions = 1;
+ else{
+ xregions = 1;
+ yregions = 1;
}
- bands(band_num).SetNumBlocks(yregions , xregions);
+ bands( band_num ).SetNumBlocks( yregions , xregions );
}// band_num
}
-void PictureCompressor::SelectQuantisers(CoeffArray& coeff_data ,
- SubbandList& bands ,
- const float lambda,
- OneDArray<unsigned int>& est_bits,
- const CodeBlockMode cb_mode,
- const PictureParams& pp,
- const CompSort csort)
+void PictureCompressor::SelectQuantisers( CoeffArray& coeff_data ,
+ SubbandList& bands ,
+ const float lambda,
+ OneDArray<unsigned int>& est_bits,
+ const CodeBlockMode cb_mode,
+ const PictureParams& pp,
+ const CompSort csort )
{
- // Set up the multiquantiser mode
- for(int b = bands.Length() ; b >= 1 ; --b)
- {
+ // Set up the multiquantiser mode
+ for ( int b=bands.Length() ; b>=1 ; --b ){
// Set multiquants flag in the subband only if
// a. Global m_cb_mode flag is set to QUANT_MULTIPLE in encparams
// and
// b. Current subband has more than one block
- if(
+ if (
cb_mode == QUANT_MULTIPLE &&
(bands(b).GetCodeBlocks().LengthX() > 1 ||
- bands(b).GetCodeBlocks().LengthY() > 1)
- )
- bands(b).SetUsingMultiQuants(true);
+ bands(b).GetCodeBlocks().LengthY() > 1)
+ )
+ bands(b).SetUsingMultiQuants( true );
else
- bands(b).SetUsingMultiQuants(false);
+ bands(b).SetUsingMultiQuants( false );
}// b
// Select all the quantizers
- if(!m_encparams.Lossless())
- {
+ if ( !m_encparams.Lossless() ){
// Set quantizers for all bands.
- for(int b = bands.Length() ; b >= 1 ; --b)
- est_bits[b] = SelectMultiQuants(coeff_data , bands , b, lambda,
- pp, csort);
+ for ( int b=bands.Length() ; b>=1 ; --b )
+ est_bits[b] = SelectMultiQuants( coeff_data , bands , b, lambda,
+ pp, csort );
}
- else
- {
- for(int b = bands.Length() ; b >= 1 ; --b)
- {
- bands(b).SetQuantIndex(0);
+ else{
+ for ( int b=bands.Length() ; b>=1 ; --b ){
+ bands(b).SetQuantIndex( 0 );
est_bits[b] = 0;
TwoDArray<CodeBlock>& blocks = bands(b).GetCodeBlocks();
- for(int j = 0; j < blocks.LengthY() ; ++j)
- for(int i = 0; i < blocks.LengthX() ; ++i)
- blocks[j][i].SetQuantIndex(0);
+ for (int j=0; j<blocks.LengthY() ;++j)
+ for (int i=0; i<blocks.LengthX() ;++i)
+ blocks[j][i].SetQuantIndex( 0 );
}// b
}
}
-int PictureCompressor::SelectMultiQuants(CoeffArray& coeff_data , SubbandList& bands ,
- const int band_num , const float lambda, const PictureParams& pp, const CompSort csort)
+int PictureCompressor::SelectMultiQuants( CoeffArray& coeff_data , SubbandList& bands ,
+ const int band_num , const float lambda, const PictureParams& pp, const CompSort csort)
{
- Subband& node(bands(band_num));
+ Subband& node( bands( band_num ) );
// Now select the quantisers //
///////////////////////////////
- QuantChooser qchooser(coeff_data , lambda);
+ QuantChooser qchooser( coeff_data , lambda );
// For the DC band in I pictures, remove the average
- if(band_num == bands.Length() && pp.PicSort().IsIntra())
- AddSubAverage(coeff_data , node.Xl() , node.Yl() , SUBTRACT);
+ if ( band_num == bands.Length() && pp.PicSort().IsIntra() )
+ AddSubAverage( coeff_data , node.Xl() , node.Yl() , SUBTRACT);
// The total estimated bits for the subband
- int band_bits(0);
- qchooser.SetEntropyCorrection(m_encparams.EntropyFactors().Factor(band_num, pp, csort));
- band_bits = qchooser.GetBestQuant(node);
+ int band_bits( 0 );
+ qchooser.SetEntropyCorrection( m_encparams.EntropyFactors().Factor( band_num, pp, csort ) );
+ band_bits = qchooser.GetBestQuant( node );
// Put the DC band average back in if necessary
- if(band_num == bands.Length() && pp.PicSort().IsIntra())
- AddSubAverage(coeff_data , node.Xl() , node.Yl() , ADD);
+ if ( band_num == bands.Length() && pp.PicSort().IsIntra() )
+ AddSubAverage( coeff_data , node.Xl() , node.Yl() , ADD);
- if(band_bits == 0)
- node.SetSkip(true);
+ if ( band_bits == 0 )
+ node.SetSkip( true );
else
- node.SetSkip(false);
+ node.SetSkip( false );
return band_bits;
}
-void PictureCompressor::AddSubAverage(CoeffArray& coeff_data, int xl, int yl ,
- AddOrSub dirn)
+void PictureCompressor::AddSubAverage( CoeffArray& coeff_data, int xl, int yl ,
+ AddOrSub dirn)
{
- ValueType last_val = 0;
+ ValueType last_val=0;
ValueType last_val2;
- if(dirn == SUBTRACT)
+ if ( dirn == SUBTRACT )
{
- for(int j = 0 ; j < yl ; j++)
- {
- for(int i = 0 ; i < xl ; i++)
+ for ( int j=0 ; j<yl ; j++)
{
+ for ( int i=0 ; i<xl ; i++)
+ {
last_val2 = coeff_data[j][i];
coeff_data[j][i] -= last_val;
last_val = last_val2;
@@ -729,9 +697,9 @@ void PictureCompressor::AddSubAverage(CoeffArray& coeff_data, int xl, int yl ,
}
else
{
- for(int j = 0 ; j < yl ; j++)
+ for ( int j=0 ; j<yl ; j++)
{
- for(int i = 0 ; i < xl; i++)
+ for ( int i=0 ; i<xl; i++ )
{
coeff_data[j][i] += last_val;
last_val = coeff_data[j][i];
diff --git a/src/filters/parser/DiracSplitter/libdirac/libdirac_encoder/picture_compress.h b/src/filters/parser/DiracSplitter/libdirac/libdirac_encoder/picture_compress.h
index 25da86bbc..84f2d983b 100644
--- a/src/filters/parser/DiracSplitter/libdirac/libdirac_encoder/picture_compress.h
+++ b/src/filters/parser/DiracSplitter/libdirac/libdirac_encoder/picture_compress.h
@@ -50,157 +50,151 @@
namespace dirac
{
-class MvData;
-
-//! Compress a single image picture
-/*!
- This class compresses a single picture at a time, using parameters
- supplied at its construction. PictureCompressor is used by
- SequenceCompressor.
-*/
-class PictureCompressor
-{
-public:
- //! Constructor
- /*!
- Creates a FrameEncoder with specific set of parameters the control
- the compression process. It encodes motion data before encoding
- each component of the picture.
- \param encp encoder parameters
- */
- PictureCompressor(EncoderParams& encp);
-
- //! Destructor
- ~PictureCompressor();
-
- //! Do pixel accurate motion estimate
- void PixelME(EncQueue& my_buffer , int pnum);
-
- //! Calculate the complexity of a picture
- void CalcComplexity(EncQueue& my_buffer, int pnum , const OLBParams& olbparams);
- void CalcComplexity2(EncQueue& my_buffer, int pnum);
-
- //! Normalise picture complexity with respect to others in the queue
- void NormaliseComplexity(EncQueue& my_buffer, int pnum);
-
- //! Do subpixel accurate motion vector refinement
- void SubPixelME(EncQueue& my_buffer , int pnum);
-
- //! Do mode decision based on sub-pel vectors
- void ModeDecisionME(EncQueue& my_buffer, int pnum);
-
- //! Detect cuts in the current picture
- void IntraModeAnalyse(EncQueue& my_buffer, int pnum);
-
- //! Does motion compensation on picture pnum (forward or backward)
- void MotionCompensate(EncQueue& my_buffer, int pnum, AddOrSub dirn);
+ class MvData;
- //! Prefilter if required
- void Prefilter(EncQueue& my_buffer, int pnum);
-
- //! Do the DWT on a given picture
- void DoDWT(EncQueue& my_buffer , int pnum, Direction dirn);
-
- //! Compress a specific picture within a group of pictures (GOP)
+ //! Compress a single image picture
/*!
- Compresses a specified picture within a group of pictures.
- \param my_pbuffer picture buffer in which the reference frames resides
- \param pnum picture number to compress
- \param pic_byteio compressed picture in Dirac bytestream format
+ This class compresses a single picture at a time, using parameters
+ supplied at its construction. PictureCompressor is used by
+ SequenceCompressor.
*/
- void CodeResidue(EncQueue& my_pbuffer , int pnum , PictureByteIO* pic_byteio);
-
- //! Compresses the motion vector data
- void CodeMVData(EncQueue& my_buffer, int pnum, PictureByteIO* pic_byteio);
-
- //! Returns true if the picture has been skipped rather than coded normally
- bool IsSkipped()
- {
- return m_skipped;
- }
-
- //! Returns true if Motion estimation data is available
- bool IsMEDataAvail() const
+ class PictureCompressor
{
- return m_medata_avail;
- }
-
- //! Returns the motion estimation data
- const MEData* GetMEData() const;
-
-private:
- //! Copy constructor is private and body-less
- /*!
- Copy constructor is private and body-less. This class should not
- be copied.
- */
- PictureCompressor(const PictureCompressor& cpy);
-
- //! Assignment = is private and body-less
- /*!
- Assignment = is private and body-less. This class should not be
- assigned.
- */
- PictureCompressor& operator=(const PictureCompressor& rhs);
-
- //! Initialise the coefficient data array for holding wavelet coefficients
- void InitCoeffData(CoeffArray& coeff_data, const int xl, const int yl);
-
- //! Returns the value lambda according to picture and component type
- float GetCompLambda(const EncPicture& my_picture,
- const CompSort csort);
-
- void SelectQuantisers(CoeffArray& coeff_data ,
- SubbandList& bands ,
- const float lambda,
- OneDArray<unsigned int>& est_counts,
- const CodeBlockMode cb_mode,
- const PictureParams& pp,
- const CompSort csort);
-
- int SelectMultiQuants(CoeffArray& coeff_data ,
- SubbandList& bands ,
- const int band_num,
- const float lambda,
- const PictureParams& pp,
- const CompSort csort);
-
- void SetupCodeBlocks(SubbandList& bands);
-
-
- void AddSubAverage(CoeffArray& coeff_data, int xl, int yl, AddOrSub dirn);
-
-private:
-
- //member variables
- // a local copy of the encoder params
- EncoderParams& m_encparams;
-
- // True if the picture has been skipped, false otherwise
- bool m_skipped;
-
- // True if we use global motion vectors, false otherwise
- bool m_use_global;
-
- // True if we use block motion vectors, false otherwise
- bool m_use_block_mv;
-
- // Prediction mode to use if we only have global motion vectors
- PredMode m_global_pred_mode;
-
- // A pointer to the current picture motion vector data
- MEData* m_me_data;
-
- // True if motion estimation data is available
- bool m_medata_avail;
-
- // True if we have detected a cut
- bool m_is_a_cut;
-
- // The original MV precision type
- MVPrecisionType m_orig_prec;
+ public:
+ //! Constructor
+ /*!
+ Creates a FrameEncoder with specific set of parameters the control
+ the compression process. It encodes motion data before encoding
+ each component of the picture.
+ \param encp encoder parameters
+ */
+ PictureCompressor( EncoderParams& encp );
+
+ //! Destructor
+ ~PictureCompressor( );
+
+ //! Do pixel accurate motion estimate
+ void PixelME( EncQueue& my_buffer , int pnum );
+
+ //! Calculate the complexity of a picture
+ void CalcComplexity( EncQueue& my_buffer, int pnum , const OLBParams& olbparams );
+ void CalcComplexity2( EncQueue& my_buffer, int pnum );
+
+ //! Normalise picture complexity with respect to others in the queue
+ void NormaliseComplexity( EncQueue& my_buffer, int pnum );
+
+ //! Do subpixel accurate motion vector refinement
+ void SubPixelME( EncQueue& my_buffer , int pnum );
+
+ //! Do mode decision based on sub-pel vectors
+ void ModeDecisionME( EncQueue& my_buffer, int pnum );
+
+ //! Detect cuts in the current picture
+ void IntraModeAnalyse( EncQueue& my_buffer, int pnum );
+
+ //! Does motion compensation on picture pnum (forward or backward)
+ void MotionCompensate( EncQueue& my_buffer, int pnum, AddOrSub dirn );
+
+ //! Prefilter if required
+ void Prefilter( EncQueue& my_buffer, int pnum );
+
+ //! Do the DWT on a given picture
+ void DoDWT( EncQueue& my_buffer , int pnum, Direction dirn );
+
+ //! Compress a specific picture within a group of pictures (GOP)
+ /*!
+ Compresses a specified picture within a group of pictures.
+ \param my_pbuffer picture buffer in which the reference frames resides
+ \param pnum picture number to compress
+ \param pic_byteio compressed picture in Dirac bytestream format
+ */
+ void CodeResidue( EncQueue& my_pbuffer , int pnum , PictureByteIO* pic_byteio);
+
+ //! Compresses the motion vector data
+ void CodeMVData( EncQueue& my_buffer, int pnum, PictureByteIO* pic_byteio);
+
+ //! Returns true if the picture has been skipped rather than coded normally
+ bool IsSkipped(){ return m_skipped; }
+
+ //! Returns true if Motion estimation data is available
+ bool IsMEDataAvail() const { return m_medata_avail; }
+
+ //! Returns the motion estimation data
+ const MEData* GetMEData() const;
+
+ private:
+ //! Copy constructor is private and body-less
+ /*!
+ Copy constructor is private and body-less. This class should not
+ be copied.
+ */
+ PictureCompressor( const PictureCompressor& cpy );
+
+ //! Assignment = is private and body-less
+ /*!
+ Assignment = is private and body-less. This class should not be
+ assigned.
+ */
+ PictureCompressor& operator=(const PictureCompressor& rhs);
+
+ //! Initialise the coefficient data array for holding wavelet coefficients
+ void InitCoeffData( CoeffArray& coeff_data, const int xl, const int yl );
+
+ //! Returns the value lambda according to picture and component type
+ float GetCompLambda( const EncPicture& my_picture,
+ const CompSort csort );
+
+ void SelectQuantisers( CoeffArray& coeff_data ,
+ SubbandList& bands ,
+ const float lambda,
+ OneDArray<unsigned int>& est_counts,
+ const CodeBlockMode cb_mode,
+ const PictureParams& pp,
+ const CompSort csort );
+
+ int SelectMultiQuants( CoeffArray& coeff_data ,
+ SubbandList& bands ,
+ const int band_num,
+ const float lambda,
+ const PictureParams& pp,
+ const CompSort csort );
+
+ void SetupCodeBlocks( SubbandList& bands );
+
+
+ void AddSubAverage(CoeffArray& coeff_data,int xl,int yl,AddOrSub dirn);
+
+ private:
+
+ //member variables
+ // a local copy of the encoder params
+ EncoderParams& m_encparams;
+
+ // True if the picture has been skipped, false otherwise
+ bool m_skipped;
-};
+ // True if we use global motion vectors, false otherwise
+ bool m_use_global;
+
+ // True if we use block motion vectors, false otherwise
+ bool m_use_block_mv;
+
+ // Prediction mode to use if we only have global motion vectors
+ PredMode m_global_pred_mode;
+
+ // A pointer to the current picture motion vector data
+ MEData* m_me_data;
+
+ // True if motion estimation data is available
+ bool m_medata_avail;
+
+ // True if we have detected a cut
+ bool m_is_a_cut;
+
+ // The original MV precision type
+ MVPrecisionType m_orig_prec;
+
+ };
} // namespace dirac
diff --git a/src/filters/parser/DiracSplitter/libdirac/libdirac_encoder/prefilter.cpp b/src/filters/parser/DiracSplitter/libdirac/libdirac_encoder/prefilter.cpp
index d02696f72..7920ed0d1 100644
--- a/src/filters/parser/DiracSplitter/libdirac/libdirac_encoder/prefilter.cpp
+++ b/src/filters/parser/DiracSplitter/libdirac/libdirac_encoder/prefilter.cpp
@@ -40,78 +40,74 @@
using namespace dirac;
-void dirac::CWMFilter(Picture& picture, const int strength)
+void dirac::CWMFilter( Picture& picture, const int strength )
{
- CWMFilterComponent(picture.Data(Y_COMP), strength);
- CWMFilterComponent(picture.Data(U_COMP), strength);
- CWMFilterComponent(picture.Data(V_COMP), strength);
+ CWMFilterComponent( picture.Data(Y_COMP), strength );
+ CWMFilterComponent( picture.Data(U_COMP), strength );
+ CWMFilterComponent( picture.Data(V_COMP), strength );
}
-void dirac::CWMFilterComponent(PicArray& pic_data, const int strength)
+void dirac::CWMFilterComponent( PicArray& pic_data, const int strength )
{
// Do centre-weighted median denoising
- PicArray pic_copy(pic_data);
+ PicArray pic_copy( pic_data );
- const int width(3);
- const int offset((width - 1) / 2);
- const int centre_weight = std::max(1, (width * width + 1) - strength);
- const int list_length = centre_weight + (width * width) - 1;
+ const int width( 3 );
+ const int offset( (width-1)/2 );
+ const int centre_weight = std::max(1, (width*width+1)-strength );
+ const int list_length = centre_weight+(width*width)-1;
ValueType* val_list = new ValueType[list_length];
- for(int j = offset; j < pic_data.LengthY() - offset; ++j)
- {
- for(int i = offset; i < pic_data.LastX() - offset; ++i)
- {
+ for (int j=offset; j<pic_data.LengthY()-offset; ++j){
+ for (int i=offset; i<pic_data.LastX()-offset; ++i){
// Make the value list
- int pos = 0;
- for(; pos < centre_weight - 1; ++pos)
+ int pos=0;
+ for (; pos<centre_weight-1; ++pos)
val_list[pos] = pic_copy[j][i];
- for(int s = -offset; s <= offset; ++s)
- {
- for(int r = -offset; r <= offset; ++r)
- {
- val_list[pos] = pic_copy[j+s][i+r];
+ for (int s=-offset; s<=offset; ++s){
+ for (int r=-offset; r<=offset; ++r){
+ val_list[pos]=pic_copy[j+s][i+r];
pos++;
}// r
}// s
- pic_data[j][i] = Median(val_list, list_length);
+ pic_data[j][i] = Median( val_list, list_length );
}// i
}// j
delete[] val_list;
}
-ValueType dirac::Median(const ValueType* val_list, const int length)
+ValueType dirac::Median( const ValueType* val_list, const int length)
{
- OneDArray<ValueType> ordered_vals(length);
+ OneDArray<ValueType> ordered_vals( length );
// Place the values in order
- int pos = 0;
+ int pos=0;
ordered_vals[0] = val_list[0];
- for(int i = 1 ; i < length ; ++i)
+ for (int i=1 ; i<length ; ++i )
{
- for(int k = 0 ; k < i ; ++k)
+ for (int k=0 ; k<i ; ++k)
{
- if(val_list[i] < ordered_vals[k])
+ if (val_list[i]<ordered_vals[k])
{
- pos = k;
+ pos=k;
break;
}
else
- pos = k + 1;
+ pos=k+1;
}// k
- if(pos == i)
+ if ( pos==i)
ordered_vals[i] = val_list[i];
else
{
- for(int k = i - 1 ; k >= pos ; --k)
+ for (int k=i-1 ; k>=pos ; --k )
{
ordered_vals[k+1] = ordered_vals[k];
}// k
@@ -120,125 +116,125 @@ ValueType dirac::Median(const ValueType* val_list, const int length)
}// i
// return the middle value
- if(length % 2 != 0)
+ if ( length%2!=0 )
return ordered_vals[(length-1)/2];
else
- return (ordered_vals[(length/2)-1] + ordered_vals[length/2] + 1) >> 1;
+ return (ordered_vals[(length/2)-1]+ordered_vals[length/2]+1)>>1;
}
/*************************************************************/
-void VFilter(PicArray& pic_data, const OneDArray<int>& filter, const int bits);
-void HFilter(PicArray& pic_data, const OneDArray<int>& filter, const int bits);
+void VFilter( PicArray& pic_data, const OneDArray<int>& filter, const int bits );
+void HFilter( PicArray& pic_data, const OneDArray<int>& filter, const int bits );
-double sinxoverx(const double val)
+double sinxoverx( const double val )
{
- if(0.0f == val)
+ if ( 0.0f == val )
return 1.0;
else
- return sin(val) / val;
+ return sin(val)/val;
}
-OneDArray<int> MakeLPRectFilter(const float bw, const int bits)
+OneDArray<int> MakeLPRectFilter( const float bw, const int bits )
{
const int tl = 8;
const float pi = 3.1415926535;
- OneDArray<double> double_filter(Range(-tl, tl));
- OneDArray<int> int_filter(Range(-tl, tl));
+ OneDArray<double> double_filter( Range( -tl, tl ) );
+ OneDArray<int> int_filter( Range( -tl, tl) );
// Use the Hanning window
- for(int i = double_filter.First(); i <= double_filter.Last(); ++i)
+ for (int i=double_filter.First(); i<=double_filter.Last(); ++i)
{
- double_filter[i] = cos((pi * i) /
- (double_filter.Length() + 1));
+ double_filter[i] = cos( (pi*i)/
+ (double_filter.Length()+1) );
}
// Apply sinc function
- for(int i = double_filter.First(); i <= double_filter.Last(); ++i)
+ for (int i=double_filter.First(); i<=double_filter.Last(); ++i)
{
- double_filter[i] *= sinxoverx(pi * 1.0 * bw * i);
+ double_filter[i] *= sinxoverx( pi*1.0*bw*i );
}
// Get DC gain = 1<<bits
double sum = 0.0;
- for(int i = double_filter.First(); i <= double_filter.Last(); ++i)
+ for (int i=double_filter.First(); i<=double_filter.Last(); ++i)
sum += double_filter[i];
- for(int i = double_filter.First(); i <= double_filter.Last(); ++i)
+ for (int i=double_filter.First(); i<=double_filter.Last(); ++i)
{
- double_filter[i] *= double(1 << (bits + 4));
+ double_filter[i] *= double(1<<(bits+4));
double_filter[i] /= sum;
}
// Turn the float filter into an integer filter
- for(int i = double_filter.First(); i <= double_filter.Last(); ++i)
+ for (int i=double_filter.First(); i<=double_filter.Last(); ++i)
{
- int_filter[i] = double_filter[i] > 0 ? int(double_filter[i] + 0.5) : -int(-double_filter[i] + 0.5);
- int_filter[i] = (int_filter[i] + 8) >> 4;
+ int_filter[i] = double_filter[i]>0 ? int( double_filter[i]+0.5 ) : -int( -double_filter[i]+0.5 );
+ int_filter[i] = (int_filter[i]+8)>>4;
}
return int_filter;
}
-void dirac::LPFilter(PicArray& pic_data, const float qf, const int strength)
+void dirac::LPFilter( PicArray& pic_data, const float qf, const int strength )
{
- float bw = (std::min(std::max(qf + 3.0f - float(strength), 1.0f), 10.0f)) / 10.0;
+ float bw = (std::min( std::max( qf+3.0f-float(strength), 1.0f ), 10.0f ))/10.0;
// filter with 14-bit accuracy
- OneDArray<int> filter = MakeLPRectFilter(bw, 14);
+ OneDArray<int> filter=MakeLPRectFilter(bw, 14);
- HFilter(pic_data, filter, 14);
- VFilter(pic_data, filter, 14);
+ HFilter( pic_data, filter, 14 );
+ VFilter( pic_data, filter, 14 );
}
-void HFilter(PicArray& pic_data, const OneDArray<int>& filter, const int bits)
+void HFilter( PicArray& pic_data, const OneDArray<int>& filter, const int bits )
{
ValueType* line_data = new ValueType[pic_data.LengthX()];
- const int offset = (1 << (bits - 1));
+ const int offset = (1<<(bits-1));
int sum;
- for(int j = 0; j < pic_data.LengthY(); ++j)
+ for (int j=0; j<pic_data.LengthY(); ++j)
{
// Do the first bit
- for(int i = 0; i < filter.Last(); ++i)
+ for (int i=0; i<filter.Last(); ++i)
{
sum = offset;
- for(int k = filter.Last(); k >= filter.First(); --k)
- sum += filter[k] * pic_data[j][std::max(i-k, 0)];
+ for (int k=filter.Last(); k>=filter.First(); --k)
+ sum += filter[k]*pic_data[j][std::max(i-k,0)];
sum >>= bits;
- sum = std::min(127, std::max(-128, sum));
- line_data[i] = ValueType(sum);
+ sum = std::min( 127, std::max( -128, sum) );
+ line_data[i] = ValueType( sum );
}// i
// Do the middle bit
- for(int i = filter.Last(); i <= pic_data.LastX() + filter.First(); ++i)
+ for (int i=filter.Last(); i<=pic_data.LastX()+filter.First(); ++i)
{
sum = offset;
- for(int k = filter.Last(); k >= filter.First(); --k)
- sum += filter[k] * pic_data[j][i-k];
+ for (int k=filter.Last(); k>=filter.First(); --k)
+ sum += filter[k]*pic_data[j][i-k];
sum >>= bits;
- sum = std::min(127, std::max(-128, sum));
- line_data[i] = ValueType(sum);
+ sum = std::min( 127, std::max( -128, sum) );
+ line_data[i] = ValueType( sum );
}// i
// Do the last bit
- for(int i = pic_data.LastX() + filter.First() + 1; i < pic_data.LengthX(); ++i)
+ for (int i=pic_data.LastX()+filter.First()+1; i<pic_data.LengthX(); ++i)
{
sum = offset;
- for(int k = filter.Last(); k >= filter.First(); --k)
- sum += filter[k] * pic_data[j][std::min(i-k, pic_data.LastX())];
+ for (int k=filter.Last(); k>=filter.First(); --k)
+ sum += filter[k]*pic_data[j][std::min(i-k,pic_data.LastX())];
sum >>= bits;
- sum = std::min(127, std::max(-128, sum));
- line_data[i] = ValueType(sum);
+ sum = std::min( 127, std::max( -128, sum) );
+ line_data[i] = ValueType( sum );
}// i
// Copy data back
- for(int i = 0; i < pic_data.LengthX(); ++i)
+ for (int i=0; i<pic_data.LengthX(); ++i )
pic_data[j][i] = line_data[i];
}// j
@@ -246,57 +242,57 @@ void HFilter(PicArray& pic_data, const OneDArray<int>& filter, const int bits)
delete[] line_data;
}
-void VFilter(PicArray& pic_data, const OneDArray<int>& filter, const int bits)
+void VFilter( PicArray& pic_data, const OneDArray<int>& filter, const int bits )
{
- PicArray tmp_data(pic_data);
- const int offset = (1 << (bits - 1));
+ PicArray tmp_data( pic_data );
+ const int offset = (1<<(bits-1));
int sum;
// Do the first bit
- for(int j = 0; j < filter.Last(); ++j)
+ for (int j=0; j<filter.Last(); ++j)
{
- for(int i = 0; i < pic_data.LengthX(); ++i)
+ for (int i=0; i<pic_data.LengthX(); ++i)
{
sum = offset;
- for(int k = filter.Last(); k >= filter.First(); --k)
- sum += filter[k] * pic_data[std::max(j-k, 0)][i];
+ for (int k=filter.Last(); k>=filter.First(); --k)
+ sum += filter[k]*pic_data[std::max(j-k,0)][i];
sum >>= bits;
- sum = std::min(127, std::max(-128, sum));
- tmp_data[j][i] = ValueType(sum);
+ sum = std::min( 127, std::max( -128, sum) );
+ tmp_data[j][i] = ValueType( sum );
}// i
}// j
// Do the middle bit
- for(int j = filter.Last(); j <= pic_data.LastY() + filter.First(); ++j)
+ for (int j=filter.Last(); j<=pic_data.LastY()+filter.First(); ++j)
{
- for(int i = 0; i < pic_data.LengthX(); ++i)
+ for (int i=0; i<pic_data.LengthX(); ++i)
{
sum = offset;
- for(int k = filter.Last(); k >= filter.First(); --k)
- sum += filter[k] * pic_data[j-k][i];
+ for (int k=filter.Last(); k>=filter.First(); --k)
+ sum += filter[k]*pic_data[j-k][i];
sum >>= bits;
- sum = std::min(127, std::max(-128, sum));
- tmp_data[j][i] = ValueType(sum);
+ sum = std::min( 127, std::max( -128, sum) );
+ tmp_data[j][i] = ValueType( sum );
}// i
}// j
// Do the last bit
- for(int j = pic_data.LastY() + filter.First() + 1; j < pic_data.LengthY(); ++j)
+ for (int j=pic_data.LastY()+filter.First()+1; j<pic_data.LengthY(); ++j)
{
- for(int i = 0; i < pic_data.LengthX(); ++i)
+ for (int i=0; i<pic_data.LengthX(); ++i)
{
sum = offset;
- for(int k = filter.Last(); k >= filter.First(); --k)
- sum += filter[k] * pic_data[std::min(j-k, pic_data.LastY())][i];
+ for (int k=filter.Last(); k>=filter.First(); --k)
+ sum += filter[k]*pic_data[std::min(j-k,pic_data.LastY())][i];
sum >>= bits;
- sum = std::min(127, std::max(-128, sum));
- tmp_data[j][i] = ValueType(sum);
+ sum = std::min( 127, std::max( -128, sum) );
+ tmp_data[j][i] = ValueType( sum );
}// i
}// j
@@ -308,10 +304,10 @@ void VFilter(PicArray& pic_data, const OneDArray<int>& filter, const int bits)
/***************************************************************************/
-ValueType DiagFilterBchkD(const PicArray& pic,
- const int xpos, const int ypos,
- const TwoDArray<int>& filter,
- const int shift)
+ValueType DiagFilterBchkD( const PicArray& pic,
+ const int xpos, const int ypos,
+ const TwoDArray<int>& filter,
+ const int shift)
{
// Half the filter length
const int len2 = 6;
@@ -320,40 +316,37 @@ ValueType DiagFilterBchkD(const PicArray& pic,
const int width = pic.LengthX();
int uplus, uneg, vplus, vneg;
- int val = (1 << (shift - 1));
+ int val = (1<<(shift-1));
// Do 0 position horizontally
- val += filter[0][0] * pic[ypos][xpos];
+ val += filter[0][0]*pic[ypos][xpos];
- for(int i = 1; i <= len2; ++i)
- {
- uplus = xpos + i;
- uplus = (uplus >= width ? width - 1 : uplus);
- uneg = xpos - i;
- uneg = (uneg < 0 ? 0 : uneg);
- val += filter[0][i] * (pic[ypos][uplus] + pic[ypos][uneg]);
+ for (int i=1; i<=len2;++i){
+ uplus = xpos + i;
+ uplus = (uplus>=width ? width-1 : uplus);
+ uneg = xpos - i;
+ uneg = (uneg<0 ? 0 : uneg );
+ val += filter[0][i]*(pic[ypos][uplus]+pic[ypos][uneg] );
}
// Do other positions vertically//
//////////////////////////////////
- for(int j = 1; j <= len2; ++j)
- {
+ for (int j=1; j<=len2;++j){
vplus = ypos + j;
- vplus = (vplus >= height ? height - 1 : vplus);
+ vplus = ( vplus>=height ? height-1 : vplus);
vneg = ypos - j;
- vneg = (vneg < 0 ? 0 : vneg);
+ vneg = (vneg<0 ? 0 : vneg );
// Do 0 position horizontally
- val += filter[j][0] * (pic[vneg][xpos] + pic[vplus][xpos]);
- for(int i = 1; i <= len2; ++i)
- {
+ val += filter[j][0]*(pic[vneg][xpos]+pic[vplus][xpos]);
+ for (int i=1; i<=len2;++i){
uplus = xpos + i;
- uplus = (uplus >= width ? width - 1 : uplus);
+ uplus = (uplus>=width ? width-1 : uplus);
uneg = xpos - i;
- uneg = (uneg < 0 ? 0 : uneg);
- val += filter[j][i] * (pic[vneg][uplus] + pic[vneg][uneg] +
- pic[vplus][uplus] + pic[vplus][uneg]);
+ uneg = (uneg<0 ? 0 : uneg );
+ val += filter[j][i]*(pic[vneg][uplus]+pic[vneg][uneg]+
+ pic[vplus][uplus]+pic[vplus][uneg] );
}
}
@@ -362,43 +355,40 @@ ValueType DiagFilterBchkD(const PicArray& pic,
return ValueType(val);
}
-ValueType DiagFilterD(const PicArray& pic,
- const int xpos, const int ypos,
- const TwoDArray<int>& filter,
- const int shift)
+ValueType DiagFilterD( const PicArray& pic,
+ const int xpos, const int ypos,
+ const TwoDArray<int>& filter,
+ const int shift)
{
// Half the filter length
const int len2 = 6;
int uplus, uneg, vplus, vneg;
- int val = (1 << (shift - 1));
+ int val = (1<<(shift-1));
// Do 0 position horizontally
- val += filter[0][0] * pic[ypos][xpos];
+ val += filter[0][0]*pic[ypos][xpos];
- for(int i = 1; i <= len2; ++i)
- {
- uplus = xpos + i;
- uneg = xpos - i;
- val += filter[0][i] * (pic[ypos][uplus] + pic[ypos][uneg]);
+ for (int i=1; i<=len2;++i){
+ uplus = xpos + i;
+ uneg = xpos - i;
+ val += filter[0][i]*(pic[ypos][uplus]+pic[ypos][uneg] );
}
// Do other positions vertically//
//////////////////////////////////
- for(int j = 1; j <= len2; ++j)
- {
+ for (int j=1; j<=len2;++j){
vplus = ypos + j;
vneg = ypos - j;
// Do 0 position horizontally
- val += filter[j][0] * (pic[vneg][xpos] + pic[vplus][xpos]);
- for(int i = 1; i <= len2; ++i)
- {
+ val += filter[j][0]*(pic[vneg][xpos]+pic[vplus][xpos]);
+ for (int i=1; i<=len2;++i){
uplus = xpos + i;
uneg = xpos - i;
- val += filter[j][i] * (pic[vneg][uplus] + pic[vneg][uneg] +
- pic[vplus][uplus] + pic[vplus][uneg]);
+ val += filter[j][i]*(pic[vneg][uplus]+pic[vneg][uneg]+
+ pic[vplus][uplus]+pic[vplus][uneg] );
}
}
@@ -408,508 +398,127 @@ ValueType DiagFilterD(const PicArray& pic,
}
-TwoDArray<int> GetDiagLPFilter(const float bw)
+TwoDArray<int> GetDiagLPFilter( const float bw )
{
- TwoDArray<int> f(7, 7);
+ TwoDArray<int> f( 7, 7 );
// Bandwidth quantised to range 0.2-1
- int qbf = int(bw * 10.0 + 0.5);
- qbf = std::min(std::max(qbf, 2) , 10);
+ int qbf = int( bw*10.0 + 0.5 );
+ qbf = std::min( std::max( qbf, 2 ) , 10 );
- switch(qbf)
- {
+ switch (qbf){
case 1 :
- f[0][0] = 1651;
- f[0][1] = 1544;
- f[0][2] = 1259;
- f[0][3] = 887;
- f[0][4] = 530;
- f[0][5] = 260;
- f[0][6] = 99;
- f[1][0] = 1544;
- f[1][1] = 1442;
- f[1][2] = 1170;
- f[1][3] = 817;
- f[1][4] = 480;
- f[1][5] = 229;
- f[1][6] = 83;
- f[2][0] = 1259;
- f[2][1] = 1170;
- f[2][2] = 935;
- f[2][3] = 634;
- f[2][4] = 354;
- f[2][5] = 153;
- f[2][6] = 45;
- f[3][0] = 887;
- f[3][1] = 817;
- f[3][2] = 634;
- f[3][3] = 405;
- f[3][4] = 202;
- f[3][5] = 70;
- f[3][6] = 11;
- f[4][0] = 530;
- f[4][1] = 480;
- f[4][2] = 354;
- f[4][3] = 202;
- f[4][4] = 80;
- f[4][5] = 15;
- f[4][6] = 0;
- f[5][0] = 260;
- f[5][1] = 229;
- f[5][2] = 153;
- f[5][3] = 70;
- f[5][4] = 15;
- f[5][5] = 0;
- f[5][6] = 0;
- f[6][0] = 99;
- f[6][1] = 83;
- f[6][2] = 45;
- f[6][3] = 11;
- f[6][4] = 0;
- f[6][5] = 0;
- f[6][6] = 0;
+ f[0][0]=1651; f[0][1]=1544; f[0][2]=1259; f[0][3]=887; f[0][4]=530; f[0][5]=260; f[0][6]=99;
+ f[1][0]=1544; f[1][1]=1442; f[1][2]=1170; f[1][3]=817; f[1][4]=480; f[1][5]=229; f[1][6]=83;
+ f[2][0]=1259; f[2][1]=1170; f[2][2]=935; f[2][3]=634; f[2][4]=354; f[2][5]=153; f[2][6]=45;
+ f[3][0]=887; f[3][1]=817; f[3][2]=634; f[3][3]=405; f[3][4]=202; f[3][5]=70; f[3][6]=11;
+ f[4][0]=530; f[4][1]=480; f[4][2]=354; f[4][3]=202; f[4][4]=80; f[4][5]=15; f[4][6]=0;
+ f[5][0]=260; f[5][1]=229; f[5][2]=153; f[5][3]=70; f[5][4]=15; f[5][5]=0; f[5][6]=0;
+ f[6][0]=99; f[6][1]=83; f[6][2]=45; f[6][3]=11; f[6][4]=0; f[6][5]=0; f[6][6]=0;
break;
case 2:
- f[0][0] = 2855;
- f[0][1] = 2540;
- f[0][2] = 1775;
- f[0][3] = 947;
- f[0][4] = 364;
- f[0][5] = 89;
- f[0][6] = 10;
- f[1][0] = 2540;
- f[1][1] = 2251;
- f[1][2] = 1551;
- f[1][3] = 804;
- f[1][4] = 290;
- f[1][5] = 59;
- f[1][6] = 1;
- f[2][0] = 1775;
- f[2][1] = 1551;
- f[2][2] = 1020;
- f[2][3] = 475;
- f[2][4] = 130;
- f[2][5] = 3;
- f[2][6] = -10;
- f[3][0] = 947;
- f[3][1] = 804;
- f[3][2] = 475;
- f[3][3] = 165;
- f[3][4] = 5;
- f[3][5] = -22;
- f[3][6] = -6;
- f[4][0] = 364;
- f[4][1] = 290;
- f[4][2] = 130;
- f[4][3] = 5;
- f[4][4] = -28;
- f[4][5] = -10;
- f[4][6] = 0;
- f[5][0] = 89;
- f[5][1] = 59;
- f[5][2] = 3;
- f[5][3] = -22;
- f[5][4] = -10;
- f[5][5] = 0;
- f[5][6] = 0;
- f[6][0] = 10;
- f[6][1] = 1;
- f[6][2] = -10;
- f[6][3] = -6;
- f[6][4] = 0;
- f[6][5] = 0;
- f[6][6] = 0;
+ f[0][0]=2855; f[0][1]=2540; f[0][2]=1775; f[0][3]=947; f[0][4]=364; f[0][5]=89; f[0][6]=10;
+ f[1][0]=2540; f[1][1]=2251; f[1][2]=1551; f[1][3]=804; f[1][4]=290; f[1][5]=59; f[1][6]=1;
+ f[2][0]=1775; f[2][1]=1551; f[2][2]=1020; f[2][3]=475; f[2][4]=130; f[2][5]=3; f[2][6]=-10;
+ f[3][0]=947; f[3][1]=804; f[3][2]=475; f[3][3]=165; f[3][4]=5; f[3][5]=-22; f[3][6]=-6;
+ f[4][0]=364; f[4][1]=290; f[4][2]=130; f[4][3]=5; f[4][4]=-28; f[4][5]=-10; f[4][6]=0;
+ f[5][0]=89; f[5][1]=59; f[5][2]=3; f[5][3]=-22; f[5][4]=-10; f[5][5]=0; f[5][6]=0;
+ f[6][0]=10; f[6][1]=1; f[6][2]=-10; f[6][3]=-6; f[6][4]=0; f[6][5]=0; f[6][6]=0;
break;
case 3:
- f[0][0] = 5767;
- f[0][1] = 4718;
- f[0][2] = 2498;
- f[0][3] = 745;
- f[0][4] = 72;
- f[0][5] = 5;
- f[0][6] = 23;
- f[1][0] = 4718;
- f[1][1] = 3796;
- f[1][2] = 1875;
- f[1][3] = 423;
- f[1][4] = -58;
- f[1][5] = -41;
- f[1][6] = 7;
- f[2][0] = 2498;
- f[2][1] = 1875;
- f[2][2] = 643;
- f[2][3] = -146;
- f[2][4] = -241;
- f[2][5] = -88;
- f[2][6] = -9;
- f[3][0] = 745;
- f[3][1] = 423;
- f[3][2] = -146;
- f[3][3] = -367;
- f[3][4] = -220;
- f[3][5] = -51;
- f[3][6] = -2;
- f[4][0] = 72;
- f[4][1] = -58;
- f[4][2] = -241;
- f[4][3] = -220;
- f[4][4] = -78;
- f[4][5] = -5;
- f[4][6] = 0;
- f[5][0] = 5;
- f[5][1] = -41;
- f[5][2] = -88;
- f[5][3] = -51;
- f[5][4] = -5;
- f[5][5] = 0;
- f[5][6] = 0;
- f[6][0] = 23;
- f[6][1] = 7;
- f[6][2] = -9;
- f[6][3] = -2;
- f[6][4] = 0;
- f[6][5] = 0;
- f[6][6] = 0;
+ f[0][0]=5767; f[0][1]=4718; f[0][2]=2498; f[0][3]=745; f[0][4]=72; f[0][5]=5; f[0][6]=23;
+ f[1][0]=4718; f[1][1]=3796; f[1][2]=1875; f[1][3]=423; f[1][4]=-58; f[1][5]=-41; f[1][6]=7;
+ f[2][0]=2498; f[2][1]=1875; f[2][2]=643; f[2][3]=-146; f[2][4]=-241; f[2][5]=-88; f[2][6]=-9;
+ f[3][0]=745; f[3][1]=423; f[3][2]=-146; f[3][3]=-367; f[3][4]=-220; f[3][5]=-51; f[3][6]=-2;
+ f[4][0]=72; f[4][1]=-58; f[4][2]=-241; f[4][3]=-220; f[4][4]=-78; f[4][5]=-5; f[4][6]=0;
+ f[5][0]=5; f[5][1]=-41; f[5][2]=-88; f[5][3]=-51; f[5][4]=-5; f[5][5]=0; f[5][6]=0;
+ f[6][0]=23; f[6][1]=7; f[6][2]=-9; f[6][3]=-2; f[6][4]=0; f[6][5]=0; f[6][6]=0;
break;
case 4:
- f[0][0] = 10534;
- f[0][1] = 7642;
- f[0][2] = 2603;
- f[0][3] = 194;
- f[0][4] = 56;
- f[0][5] = 120;
- f[0][6] = 28;
- f[1][0] = 7642;
- f[1][1] = 5237;
- f[1][2] = 1218;
- f[1][3] = -383;
- f[1][4] = -153;
- f[1][5] = 40;
- f[1][6] = 2;
- f[2][0] = 2603;
- f[2][1] = 1218;
- f[2][2] = -771;
- f[2][3] = -958;
- f[2][4] = -269;
- f[2][5] = -3;
- f[2][6] = -7;
- f[3][0] = 194;
- f[3][1] = -383;
- f[3][2] = -958;
- f[3][3] = -541;
- f[3][4] = -18;
- f[3][5] = 48;
- f[3][6] = 4;
- f[4][0] = 56;
- f[4][1] = -153;
- f[4][2] = -269;
- f[4][3] = -18;
- f[4][4] = 96;
- f[4][5] = 22;
- f[4][6] = 0;
- f[5][0] = 120;
- f[5][1] = 40;
- f[5][2] = -3;
- f[5][3] = 48;
- f[5][4] = 22;
- f[5][5] = 0;
- f[5][6] = 0;
- f[6][0] = 28;
- f[6][1] = 2;
- f[6][2] = -7;
- f[6][3] = 4;
- f[6][4] = 0;
- f[6][5] = 0;
- f[6][6] = 0;
+ f[0][0]=10534; f[0][1]=7642; f[0][2]=2603; f[0][3]=194; f[0][4]=56; f[0][5]=120; f[0][6]=28;
+ f[1][0]=7642; f[1][1]=5237; f[1][2]=1218; f[1][3]=-383; f[1][4]=-153; f[1][5]=40; f[1][6]=2;
+ f[2][0]=2603; f[2][1]=1218; f[2][2]=-771; f[2][3]=-958; f[2][4]=-269; f[2][5]=-3; f[2][6]=-7;
+ f[3][0]=194; f[3][1]=-383; f[3][2]=-958; f[3][3]=-541; f[3][4]=-18; f[3][5]=48; f[3][6]=4;
+ f[4][0]=56; f[4][1]=-153; f[4][2]=-269; f[4][3]=-18; f[4][4]=96; f[4][5]=22; f[4][6]=0;
+ f[5][0]=120; f[5][1]=40; f[5][2]=-3; f[5][3]=48; f[5][4]=22; f[5][5]=0; f[5][6]=0;
+ f[6][0]=28; f[6][1]=2; f[6][2]=-7; f[6][3]=4; f[6][4]=0; f[6][5]=0; f[6][6]=0;
break;
case 5 :
- f[0][0] = 16421;
- f[0][1] = 10159;
- f[0][2] = 1716;
- f[0][3] = 33;
- f[0][4] = 325;
- f[0][5] = 57;
- f[0][6] = 6;
- f[1][0] = 10159;
- f[1][1] = 5309;
- f[1][2] = -580;
- f[1][3] = -747;
- f[1][4] = 44;
- f[1][5] = -43;
- f[1][6] = -25;
- f[2][0] = 1716;
- f[2][1] = -580;
- f[2][2] = -2310;
- f[2][3] = -763;
- f[2][4] = 100;
- f[2][5] = -19;
- f[2][6] = -12;
- f[3][0] = 33;
- f[3][1] = -747;
- f[3][2] = -763;
- f[3][3] = 308;
- f[3][4] = 326;
- f[3][5] = 27;
- f[3][6] = 1;
- f[4][0] = 325;
- f[4][1] = 44;
- f[4][2] = 100;
- f[4][3] = 326;
- f[4][4] = 84;
- f[4][5] = -14;
- f[4][6] = 0;
- f[5][0] = 57;
- f[5][1] = -43;
- f[5][2] = -19;
- f[5][3] = 27;
- f[5][4] = -14;
- f[5][5] = 0;
- f[5][6] = 0;
- f[6][0] = 6;
- f[6][1] = -25;
- f[6][2] = -12;
- f[6][3] = 1;
- f[6][4] = 0;
- f[6][5] = 0;
- f[6][6] = 0;
+ f[0][0]=16421; f[0][1]=10159; f[0][2]=1716; f[0][3]=33; f[0][4]=325; f[0][5]=57; f[0][6]=6;
+ f[1][0]=10159; f[1][1]=5309; f[1][2]=-580; f[1][3]=-747; f[1][4]=44; f[1][5]=-43; f[1][6]=-25;
+ f[2][0]=1716; f[2][1]=-580; f[2][2]=-2310; f[2][3]=-763; f[2][4]=100; f[2][5]=-19; f[2][6]=-12;
+ f[3][0]=33; f[3][1]=-747; f[3][2]=-763; f[3][3]=308; f[3][4]=326; f[3][5]=27; f[3][6]=1;
+ f[4][0]=325; f[4][1]=44; f[4][2]=100; f[4][3]=326; f[4][4]=84; f[4][5]=-14; f[4][6]=0;
+ f[5][0]=57; f[5][1]=-43; f[5][2]=-19; f[5][3]=27; f[5][4]=-14; f[5][5]=0; f[5][6]=0;
+ f[6][0]=6; f[6][1]=-25; f[6][2]=-12; f[6][3]=1; f[6][4]=0; f[6][5]=0; f[6][6]=0;
break;
case 6 :
- f[0][0] = 23511;
- f[0][1] = 11883;
- f[0][2] = 566;
- f[0][3] = 524;
- f[0][4] = 231;
- f[0][5] = 18;
- f[0][6] = 41;
- f[1][0] = 11883;
- f[1][1] = 3647;
- f[1][2] = -2496;
- f[1][3] = -361;
- f[1][4] = -96;
- f[1][5] = -97;
- f[1][6] = 1;
- f[2][0] = 566;
- f[2][1] = -2496;
- f[2][2] = -2329;
- f[2][3] = 459;
- f[2][4] = 152;
- f[2][5] = -7;
- f[2][6] = 18;
- f[3][0] = 524;
- f[3][1] = -361;
- f[3][2] = 459;
- f[3][3] = 979;
- f[3][4] = 33;
- f[3][5] = -28;
- f[3][6] = 3;
- f[4][0] = 231;
- f[4][1] = -96;
- f[4][2] = 152;
- f[4][3] = 33;
- f[4][4] = -184;
- f[4][5] = -15;
- f[4][6] = 0;
- f[5][0] = 18;
- f[5][1] = -97;
- f[5][2] = -7;
- f[5][3] = -28;
- f[5][4] = -15;
- f[5][5] = 0;
- f[5][6] = 0;
- f[6][0] = 41;
- f[6][1] = 1;
- f[6][2] = 18;
- f[6][3] = 3;
- f[6][4] = 0;
- f[6][5] = 0;
- f[6][6] = 0;
+ f[0][0]=23511; f[0][1]=11883; f[0][2]=566; f[0][3]=524; f[0][4]=231; f[0][5]=18; f[0][6]=41;
+ f[1][0]= 11883; f[1][1]=3647; f[1][2]=-2496; f[1][3]=-361; f[1][4]=-96; f[1][5]=-97; f[1][6]=1;
+ f[2][0]=566; f[2][1]=-2496; f[2][2]=-2329; f[2][3]=459; f[2][4]=152; f[2][5]=-7; f[2][6]=18;
+ f[3][0]=524; f[3][1]=-361; f[3][2]=459; f[3][3]=979; f[3][4]=33; f[3][5]=-28; f[3][6]=3;
+ f[4][0]=231; f[4][1]=-96; f[4][2]=152; f[4][3]=33; f[4][4]=-184; f[4][5]=-15; f[4][6]=0;
+ f[5][0]=18; f[5][1]=-97; f[5][2]=-7; f[5][3]=-28; f[5][4]=-15; f[5][5]=0; f[5][6]=0;
+ f[6][0]=41; f[6][1]=1; f[6][2]=18; f[6][3]=3; f[6][4]=0; f[6][5]=0; f[6][6]=0;
break;
case 7 :
- f[0][0] = 32188;
- f[0][1] = 12652;
- f[0][2] = 3;
- f[0][3] = 921;
- f[0][4] = 1;
- f[0][5] = 128;
- f[0][6] = 0;
- f[1][0] = 12652;
- f[1][1] = 295;
- f[1][2] = -3414;
- f[1][3] = -2;
- f[1][4] = -343;
- f[1][5] = -1;
- f[1][6] = -37;
- f[2][0] = 3;
- f[2][1] = -3414;
- f[2][2] = -212;
- f[2][3] = 1273;
- f[2][4] = 1;
- f[2][5] = 98;
- f[2][6] = 0;
- f[3][0] = 921;
- f[3][1] = -2;
- f[3][2] = 1273;
- f[3][3] = 110;
- f[3][4] = -363;
- f[3][5] = 0;
- f[3][6] = -8;
- f[4][0] = 1;
- f[4][1] = -343;
- f[4][2] = 1;
- f[4][3] = -363;
- f[4][4] = -29;
- f[4][5] = 29;
- f[4][6] = 0;
- f[5][0] = 128;
- f[5][1] = -1;
- f[5][2] = 98;
- f[5][3] = 0;
- f[5][4] = 29;
- f[5][5] = 0;
- f[5][6] = 0;
- f[6][0] = 0;
- f[6][1] = -37;
- f[6][2] = 0;
- f[6][3] = -8;
- f[6][4] = 0;
- f[6][5] = 0;
- f[6][6] = 0;
+ f[0][0]=32188; f[0][1]=12652; f[0][2]=3; f[0][3]=921; f[0][4]=1; f[0][5]=128; f[0][6]=0;
+ f[1][0]=12652; f[1][1]=295; f[1][2]=-3414; f[1][3]=-2; f[1][4]=-343; f[1][5]=-1; f[1][6]=-37;
+ f[2][0]=3; f[2][1]=-3414; f[2][2]=-212; f[2][3]=1273; f[2][4]=1; f[2][5]=98; f[2][6]=0;
+ f[3][0]=921; f[3][1]=-2; f[3][2]=1273; f[3][3]=110; f[3][4]=-363; f[3][5]=0; f[3][6]=-8;
+ f[4][0]=1; f[4][1]=-343; f[4][2]=1; f[4][3]=-363; f[4][4]=-29; f[4][5]=29; f[4][6]=0;
+ f[5][0]=128; f[5][1]=-1; f[5][2]=98; f[5][3]=0; f[5][4]=29; f[5][5]=0; f[5][6]=0;
+ f[6][0]=0; f[6][1]=-37; f[6][2]=0; f[6][3]=-8; f[6][4]=0; f[6][5]=0; f[6][6]=0;
break;
case 8 :
- f[0][0] = 41902;
- f[0][1] = 12084;
- f[0][2] = 435;
- f[0][3] = 610;
- f[0][4] = 188;
- f[0][5] = 34;
- f[0][6] = 37;
- f[1][0] = 12084;
- f[1][1] = -4268;
- f[1][2] = -2715;
- f[1][3] = -286;
- f[1][4] = -144;
- f[1][5] = -84;
- f[1][6] = -2;
- f[2][0] = 435;
- f[2][1] = -2715;
- f[2][2] = 2809;
- f[2][3] = 640;
- f[2][4] = 127;
- f[2][5] = 10;
- f[2][6] = 17;
- f[3][0] = 610;
- f[3][1] = -286;
- f[3][2] = 640;
- f[3][3] = -1250;
- f[3][4] = -45;
- f[3][5] = -26;
- f[3][6] = 2;
- f[4][0] = 188;
- f[4][1] = -144;
- f[4][2] = 127;
- f[4][3] = -45;
- f[4][4] = 259;
- f[4][5] = -8;
- f[4][6] = 0;
- f[5][0] = 34;
- f[5][1] = -84;
- f[5][2] = 10;
- f[5][3] = -26;
- f[5][4] = -8;
- f[5][5] = 0;
- f[5][6] = 0;
- f[6][0] = 37;
- f[6][1] = -2;
- f[6][2] = 17;
- f[6][3] = 2;
- f[6][4] = 0;
- f[6][5] = 0;
- f[6][6] = 0;
+ f[0][0]=41902; f[0][1]=12084; f[0][2]=435; f[0][3]=610; f[0][4]=188; f[0][5]=34; f[0][6]=37;
+ f[1][0]=12084; f[1][1]=-4268; f[1][2]=-2715; f[1][3]=-286; f[1][4]=-144; f[1][5]=-84; f[1][6]=-2;
+ f[2][0]=435; f[2][1]=-2715; f[2][2]=2809; f[2][3]=640; f[2][4]=127; f[2][5]=10; f[2][6]=17;
+ f[3][0]=610; f[3][1]=-286; f[3][2]=640; f[3][3]=-1250; f[3][4]=-45; f[3][5]=-26; f[3][6]=2;
+ f[4][0]=188; f[4][1]=-144; f[4][2]=127; f[4][3]=-45; f[4][4]=259; f[4][5]=-8; f[4][6]=0;
+ f[5][0]=34; f[5][1]=-84; f[5][2]=10; f[5][3]=-26; f[5][4]=-8; f[5][5]=0; f[5][6]=0;
+ f[6][0]=37; f[6][1]=-2; f[6][2]=17; f[6][3]=2; f[6][4]=0; f[6][5]=0; f[6][6]=0;
break;
case 9 :
- f[0][0] = 53098;
- f[0][1] = 10449;
- f[0][2] = 1546;
- f[0][3] = 73;
- f[0][4] = 342;
- f[0][5] = 38;
- f[0][6] = 12;
- f[1][0] = 10449;
- f[1][1] = -9060;
- f[1][2] = -873;
- f[1][3] = -727;
- f[1][4] = 52;
- f[1][5] = -65;
- f[1][6] = -20;
- f[2][0] = 1546;
- f[2][1] = -873;
- f[2][2] = 4261;
- f[2][3] = -627;
- f[2][4] = 137;
- f[2][5] = -27;
- f[2][6] = -7;
- f[3][0] = 73;
- f[3][1] = -727;
- f[3][2] = -627;
- f[3][3] = -804;
- f[3][4] = 328;
- f[3][5] = 14;
- f[3][6] = 2;
- f[4][0] = 342;
- f[4][1] = 52;
- f[4][2] = 137;
- f[4][3] = 328;
- f[4][4] = -83;
- f[4][5] = -20;
- f[4][6] = 0;
- f[5][0] = 38;
- f[5][1] = -65;
- f[5][2] = -27;
- f[5][3] = 14;
- f[5][4] = -20;
- f[5][5] = 0;
- f[5][6] = 0;
- f[6][0] = 12;
- f[6][1] = -20;
- f[6][2] = -7;
- f[6][3] = 2;
- f[6][4] = 0;
- f[6][5] = 0;
- f[6][6] = 0;
+ f[0][0]=53098; f[0][1]=10449; f[0][2]=1546; f[0][3]=73; f[0][4]=342; f[0][5]=38; f[0][6]=12;
+ f[1][0]=10449; f[1][1]=-9060; f[1][2]=-873; f[1][3]=-727; f[1][4]=52; f[1][5]=-65; f[1][6]=-20;
+ f[2][0]=1546; f[2][1]=-873; f[2][2]=4261; f[2][3]=-627; f[2][4]=137; f[2][5]=-27; f[2][6]=-7;
+ f[3][0]=73; f[3][1]=-727; f[3][2]=-627; f[3][3]=-804; f[3][4]=328; f[3][5]=14; f[3][6]=2;
+ f[4][0]=342; f[4][1]=52; f[4][2]=137; f[4][3]=328; f[4][4]=-83; f[4][5]=-20; f[4][6]=0;
+ f[5][0]=38; f[5][1]=-65; f[5][2]=-27; f[5][3]=14; f[5][4]=-20; f[5][5]=0; f[5][6]=0;
+ f[6][0]=12; f[6][1]=-20; f[6][2]=-7; f[6][3]=2; f[6][4]=0; f[6][5]=0; f[6][6]=0;
break;
default:// case 10
- for(int j = 0; j < f.LengthY(); ++j)
- {
- for(int i = 0; i < f.LengthX(); ++i)
- {
+ for (int j=0; j<f.LengthY(); ++j ){
+ for (int i=0; i<f.LengthX(); ++i ){
f[j][i] = 0;
}
}
@@ -923,59 +532,55 @@ TwoDArray<int> GetDiagLPFilter(const float bw)
// Does a diagnonal prefilter
-void dirac::DiagFilter(PicArray& pic_data, const float qf, const int strength)
-{
+void dirac::DiagFilter( PicArray& pic_data, const float qf, const int strength ){
// One quadrant of the filter taps
- float ffactor = (8.0 + strength - 4.0 - qf) / 5.0;
- int factor = std::max(0, std::min(256, int(ffactor * 256.0))) ;
+ float ffactor = (8.0+strength-4.0 - qf )/5.0;
+ int factor = std::max(0, std::min( 256, int( ffactor*256.0 ) ) ) ;
- float bw = (1.0 - ffactor) * 0.6 + 0.4;
+ float bw = (1.0-ffactor)*0.6+0.4;
//std::cout<<std::endl<<"Diagonal prefiltering with bandwidth = "<<bw;
- if(bw > 0.9)
+ if (bw>0.9)
return;
- TwoDArray<int> filter = GetDiagLPFilter(bw);
+ TwoDArray<int> filter = GetDiagLPFilter( bw );
- filter[0][0] = (factor * filter[0][0] + ((1 << 8) - factor) * (1 << 16) + (1 << 7)) >> 8;
+ filter[0][0] = ( factor*filter[0][0] + ( (1<<8)-factor )*(1<<16) + (1<<7) ) >> 8;
- for(int i = 1;
- i < 7;
- ++i)
- filter[0][i] = (factor * filter[0][i] + (1 << 7)) >> 8;
+ for (int i=1;i<7; ++i )
+ filter[0][i] = ( factor*filter[0][i] + (1<<7) ) >> 8;
- for(int j = 1; j < 7; ++j)
- for(int i = 0; i < 7; ++i)
- filter[j][i] = (factor * filter[j][i] + (1 << 7)) >> 8;
+ for (int j=1;j<7; ++j )
+ for (int i=0;i<7; ++i )
+ filter[j][i] = ( factor*filter[j][i] + (1<<7) ) >> 8;
- PicArray tmp_data(pic_data.LengthY(), pic_data.LengthX(), pic_data.CSort());
+ PicArray tmp_data( pic_data.LengthY(), pic_data.LengthX(), pic_data.CSort() );
const int shift = 16;
- for(int j = 0; j < 7; ++j)
- for(int i = 0; i < pic_data.LengthX(); ++i)
- tmp_data[j][i] = DiagFilterBchkD(pic_data, i, j, filter, shift);
+ for (int j=0; j<7;++j)
+ for (int i=0; i<pic_data.LengthX();++i)
+ tmp_data[j][i] = DiagFilterBchkD( pic_data, i, j, filter, shift);
- for(int j = 7; j < pic_data.LengthY() - 7; ++j)
- {
- for(int i = 0; i < 7; ++i)
- tmp_data[j][i] = DiagFilterBchkD(pic_data, i, j, filter, shift);
+ for (int j=7; j<pic_data.LengthY()-7;++j){
+ for (int i=0; i<7;++i)
+ tmp_data[j][i] = DiagFilterBchkD( pic_data, i, j, filter, shift );
- for(int i = 7; i < pic_data.LengthX() - 7; ++i)
- tmp_data[j][i] = DiagFilterD(pic_data, i, j, filter, shift);
+ for (int i=7; i<pic_data.LengthX()-7;++i)
+ tmp_data[j][i] = DiagFilterD( pic_data, i, j, filter, shift );
- for(int i = pic_data.LengthX() - 7; i < pic_data.LengthX(); ++i)
- tmp_data[j][i] = DiagFilterBchkD(pic_data, i, j, filter, shift);
+ for (int i=pic_data.LengthX()-7; i<pic_data.LengthX();++i)
+ tmp_data[j][i] = DiagFilterBchkD( pic_data, i, j, filter, shift );
}
- for(int j = pic_data.LengthY() - 7; j < pic_data.LengthY(); ++j)
- for(int i = 0; i < pic_data.LengthX(); ++i)
- tmp_data[j][i] = DiagFilterBchkD(pic_data, i, j, filter, shift);
+ for (int j=pic_data.LengthY()-7; j<pic_data.LengthY();++j)
+ for (int i=0; i<pic_data.LengthX();++i)
+ tmp_data[j][i] = DiagFilterBchkD( pic_data, i, j, filter, shift );
pic_data = tmp_data;
diff --git a/src/filters/parser/DiracSplitter/libdirac/libdirac_encoder/prefilter.h b/src/filters/parser/DiracSplitter/libdirac/libdirac_encoder/prefilter.h
index 4fb8a975b..2a37c4aaf 100644
--- a/src/filters/parser/DiracSplitter/libdirac/libdirac_encoder/prefilter.h
+++ b/src/filters/parser/DiracSplitter/libdirac/libdirac_encoder/prefilter.h
@@ -48,20 +48,20 @@ namespace dirac
/*************************************************************/
//! Denoises an input frame
-void CWMFilter(Picture& picture, const int strength);
+void CWMFilter( Picture& picture, const int strength );
-void CWMFilterComponent(PicArray& pic_data, const int strength);
+void CWMFilterComponent( PicArray& pic_data, const int strength );
-ValueType Median(const ValueType* val_list, const int length);
+ValueType Median( const ValueType* val_list, const int length);
/*************************************************************/
//! Denoises a component
-void LPFilter(PicArray& pic_data, const float qf, const int strength);
+void LPFilter( PicArray& pic_data, const float qf, const int strength );
//! Diagonally filters an input component
-void DiagFilter(PicArray& pic_data, const float qf , const int strength);
+void DiagFilter( PicArray& pic_data, const float qf , const int strength );
} // namespace dirac
diff --git a/src/filters/parser/DiracSplitter/libdirac/libdirac_encoder/quality_monitor.cpp b/src/filters/parser/DiracSplitter/libdirac/libdirac_encoder/quality_monitor.cpp
index d3f0c2893..93934f372 100644
--- a/src/filters/parser/DiracSplitter/libdirac/libdirac_encoder/quality_monitor.cpp
+++ b/src/filters/parser/DiracSplitter/libdirac/libdirac_encoder/quality_monitor.cpp
@@ -57,7 +57,7 @@ QualityMonitor::~QualityMonitor()
void QualityMonitor::ResetAll()
{
- for(int i = 0; i < 3 ; ++i)
+ for (int i=0; i<3 ; ++i )
{
m_mse_averageY[i] = 0.0;
m_mse_averageU[i] = 0.0;
@@ -72,102 +72,90 @@ void QualityMonitor::ResetAll()
void QualityMonitor::WriteLog()
{
- const double Ymax = double((1 << m_encparams.LumaDepth()) - 1);
- const double UVmax = double((1 << m_encparams.ChromaDepth()) - 1);
-
- std::cout << std::endl << "Overall mean PSNR values";
- std::cout << std::endl << "------------------------";
- std::cout << std::endl << "Y: ";
- std::cout.width(5);
- std::cout.precision(4);
- std::cout << 10 * std::log10(Ymax * Ymax / (m_totalmse_averageY / m_allpicture_total)) << std::endl;
- std::cout << std::endl << "U: ";
- std::cout.width(5);
- std::cout.precision(4);
- std::cout << 10 * std::log10(UVmax * UVmax / (m_totalmse_averageU / m_allpicture_total)) << std::endl;
- std::cout << std::endl << "V: ";
- std::cout.width(5);
- std::cout.precision(4);
- std::cout << 10 * std::log10(UVmax * UVmax / (m_totalmse_averageV / m_allpicture_total)) << std::endl;
-
-
- std::cout << std::endl << "Mean PSNR values by picture type and component";
- std::cout << std::endl << "--------------------------------------------";
- std::cout << std::endl;
-
- std::cout << std::endl << " || Y || U || V ||";
- std::cout << std::endl << "=================||===================================================";
- std::cout << std::endl << " Intra || ";
- std::cout.width(5);
- std::cout.precision(4);
- std::cout << 10 * std::log10(Ymax * Ymax / (m_mse_averageY[0] / m_picture_total[0])) << " || ";
- std::cout.width(5);
- std::cout.precision(4);
- std::cout << 10 * std::log10(UVmax * UVmax / (m_mse_averageU[0] / m_picture_total[0])) << " || ";
- std::cout.width(5);
- std::cout.precision(4);
- std::cout << 10 * std::log10(UVmax * UVmax / (m_mse_averageV[0] / m_picture_total[0])) << " || ";
- std::cout << std::endl << "-----------------||---------------------------------------------------";
- std::cout << std::endl << " Inter Ref || ";
- std::cout.width(5);
- std::cout.precision(4);
- std::cout << 10 * std::log10(Ymax * Ymax / (m_mse_averageY[1] / m_picture_total[1])) << " || ";
- std::cout.width(5);
- std::cout.precision(4);
- std::cout << 10 * std::log10(UVmax * UVmax / (m_mse_averageU[1] / m_picture_total[1])) << " || ";
- std::cout.width(5);
- std::cout.precision(4);
- std::cout << 10 * std::log10(UVmax * UVmax / (m_mse_averageV[1] / m_picture_total[1])) << " || ";
- std::cout << std::endl << "-----------------||---------------------------------------------------";
- std::cout << std::endl << " Inter Non Ref || ";
- std::cout.width(5);
- std::cout.precision(4);
- std::cout << 10 * std::log10(Ymax * Ymax / (m_mse_averageY[2] / m_picture_total[2])) << " || ";
- std::cout.width(5);
- std::cout.precision(4);
- std::cout << 10 * std::log10(UVmax * UVmax / (m_mse_averageU[2] / m_picture_total[2])) << " || ";
- std::cout.width(5);
- std::cout.precision(4);
- std::cout << 10 * std::log10(UVmax * UVmax / (m_mse_averageV[2] / m_picture_total[2])) << " || ";
- std::cout << std::endl << "-----------------||---------------------------------------------------";
+ const double Ymax = double( (1<<m_encparams.LumaDepth())-1 );
+ const double UVmax = double( (1<<m_encparams.ChromaDepth())-1 );
+
+ std::cout<<std::endl<<"Overall mean PSNR values";
+ std::cout<<std::endl<<"------------------------";
+ std::cout<<std::endl<<"Y: ";
+ std::cout.width(5);std::cout.precision(4);
+ std::cout<<10*std::log10(Ymax*Ymax/(m_totalmse_averageY/m_allpicture_total))<<std::endl;
+ std::cout<<std::endl<<"U: ";
+ std::cout.width(5);std::cout.precision(4);
+ std::cout<<10*std::log10(UVmax*UVmax/(m_totalmse_averageU/m_allpicture_total))<<std::endl;
+ std::cout<<std::endl<<"V: ";
+ std::cout.width(5);std::cout.precision(4);
+ std::cout<<10*std::log10(UVmax*UVmax/(m_totalmse_averageV/m_allpicture_total))<<std::endl;
+
+
+ std::cout<<std::endl<<"Mean PSNR values by picture type and component";
+ std::cout<<std::endl<<"--------------------------------------------";
+ std::cout<<std::endl;
+
+ std::cout<<std::endl<<" || Y || U || V ||";
+ std::cout<<std::endl<<"=================||===================================================";
+ std::cout<<std::endl<<" Intra || ";
+ std::cout.width(5);std::cout.precision(4);
+ std::cout<<10*std::log10(Ymax*Ymax/(m_mse_averageY[0]/m_picture_total[0]))<<" || ";
+ std::cout.width(5);std::cout.precision(4);
+ std::cout<<10*std::log10(UVmax*UVmax/(m_mse_averageU[0]/m_picture_total[0]))<<" || ";
+ std::cout.width(5);std::cout.precision(4);
+ std::cout<<10*std::log10(UVmax*UVmax/(m_mse_averageV[0]/m_picture_total[0]))<<" || ";
+ std::cout<<std::endl<<"-----------------||---------------------------------------------------";
+ std::cout<<std::endl<<" Inter Ref || ";
+ std::cout.width(5);std::cout.precision(4);
+ std::cout<<10*std::log10(Ymax*Ymax/(m_mse_averageY[1]/m_picture_total[1]))<<" || ";
+ std::cout.width(5);std::cout.precision(4);
+ std::cout<<10*std::log10(UVmax*UVmax/(m_mse_averageU[1]/m_picture_total[1]))<<" || ";
+ std::cout.width(5);std::cout.precision(4);
+ std::cout<<10*std::log10(UVmax*UVmax/(m_mse_averageV[1]/m_picture_total[1]))<<" || ";
+ std::cout<<std::endl<<"-----------------||---------------------------------------------------";
+ std::cout<<std::endl<<" Inter Non Ref || ";
+ std::cout.width(5);std::cout.precision(4);
+ std::cout<<10*std::log10(Ymax*Ymax/(m_mse_averageY[2]/m_picture_total[2]))<<" || ";
+ std::cout.width(5);std::cout.precision(4);
+ std::cout<<10*std::log10(UVmax*UVmax/(m_mse_averageU[2]/m_picture_total[2]))<<" || ";
+ std::cout.width(5);std::cout.precision(4);
+ std::cout<<10*std::log10(UVmax*UVmax/(m_mse_averageV[2]/m_picture_total[2]))<<" || ";
+ std::cout<<std::endl<<"-----------------||---------------------------------------------------";
}
-void QualityMonitor::UpdateModel(const EncPicture& enc_picture)
+void QualityMonitor::UpdateModel(const EncPicture& enc_picture )
{
- const double Ymax = double((1 << m_encparams.LumaDepth()) - 1);
- const double UVmax = double((1 << m_encparams.ChromaDepth()) - 1);
+ const double Ymax = double( (1<<m_encparams.LumaDepth())-1 );
+ const double UVmax = double( (1<<m_encparams.ChromaDepth())-1 );
const PictureSort& psort = enc_picture.GetPparams().PicSort();
int idx = psort.IsIntra() ? 0 : (psort.IsRef() ? 1 : 2);
double fmseY, fmseU, fmseV;
- fmseY = QualityVal(enc_picture.Data(Y_COMP) , enc_picture.OrigData(Y_COMP),
- m_encparams.Xl(), m_encparams.Yl());
+ fmseY = QualityVal( enc_picture.Data(Y_COMP) , enc_picture.OrigData(Y_COMP),
+ m_encparams.Xl(), m_encparams.Yl());
m_mse_averageY[idx] += fmseY;
m_totalmse_averageY += fmseY;
- fmseU = QualityVal(enc_picture.Data(U_COMP) , enc_picture.OrigData(U_COMP),
- m_encparams.ChromaXl(),
- m_encparams.ChromaYl());
+ fmseU = QualityVal( enc_picture.Data(U_COMP) , enc_picture.OrigData(U_COMP),
+ m_encparams.ChromaXl(),
+ m_encparams.ChromaYl());
m_mse_averageU[idx] += fmseU;
m_totalmse_averageU += fmseU;
- fmseV = QualityVal(enc_picture.Data(V_COMP) , enc_picture.OrigData(V_COMP),
- m_encparams.ChromaXl(),
- m_encparams.ChromaYl());
+ fmseV = QualityVal( enc_picture.Data(V_COMP) , enc_picture.OrigData(V_COMP),
+ m_encparams.ChromaXl(),
+ m_encparams.ChromaYl());
m_mse_averageV[idx] += fmseV;
m_totalmse_averageV += fmseV;
m_picture_total[idx]++;
m_allpicture_total++;
- if(m_encparams.Verbose())
+ if (m_encparams.Verbose() )
{
- std::cout << std::endl << (!m_encparams.FieldCoding() ? "Frame" : "Field");
- std::cout << " PSNR: Y=" << 10.0 * std::log10(Ymax * Ymax / fmseY);
- std::cout << ", U=" << 10.0 * std::log10(UVmax * UVmax / fmseU);
- std::cout << ", V=" << 10.0 * std::log10(UVmax * UVmax / fmseV);
+ std::cout<<std::endl<< (!m_encparams.FieldCoding() ? "Frame" : "Field");
+ std::cout << " PSNR: Y="<<10.0 * std::log10( Ymax*Ymax / fmseY );
+ std::cout<<", U="<<10.0 * std::log10( UVmax*UVmax / fmseU );
+ std::cout<<", V="<<10.0 * std::log10( UVmax*UVmax / fmseV );
}
}
@@ -179,18 +167,18 @@ double QualityMonitor::QualityVal(const PicArray& coded_data,
{
long double sum_sq_diff = 0.0;
double diff;
- for(int j = 0; j < ylen; ++j)
+ for ( int j=0;j<ylen; ++j )
{
- for(int i = 0; i < xlen; ++i)
+ for ( int i=0;i<xlen; ++i )
{
diff = orig_data[j][i] - coded_data[j][i];
- sum_sq_diff += diff * diff;
+ sum_sq_diff += diff*diff;
}// i
}// j
- sum_sq_diff /= xlen * ylen;
+ sum_sq_diff /= xlen*ylen;
return (double) sum_sq_diff;
}
diff --git a/src/filters/parser/DiracSplitter/libdirac/libdirac_encoder/quality_monitor.h b/src/filters/parser/DiracSplitter/libdirac/libdirac_encoder/quality_monitor.h
index 7c2efc7b3..7f21a944d 100644
--- a/src/filters/parser/DiracSplitter/libdirac/libdirac_encoder/quality_monitor.h
+++ b/src/filters/parser/DiracSplitter/libdirac/libdirac_encoder/quality_monitor.h
@@ -44,80 +44,80 @@
namespace dirac
{
-//! Class to monitor the quality of pictures and adjust coding parameters appropriately
-class QualityMonitor
-{
-public:
+ //! Class to monitor the quality of pictures and adjust coding parameters appropriately
+ class QualityMonitor
+ {
+ public:
- //! Constructor. Sets up initial Lagrangian values
- /*
- Constructor sets up initial Lagrangian values.
- */
- QualityMonitor(EncoderParams& ep);
+ //! Constructor. Sets up initial Lagrangian values
+ /*
+ Constructor sets up initial Lagrangian values.
+ */
+ QualityMonitor(EncoderParams& ep);
- //! Destructor
- ~QualityMonitor();
+ //! Destructor
+ ~QualityMonitor();
- ////////////////////////////////////////////////////////////
- // //
- // Assumes default copy constructor, assignment = //
- // and destructor //
- ////////////////////////////////////////////////////////////
+ ////////////////////////////////////////////////////////////
+ // //
+ // Assumes default copy constructor, assignment = //
+ // and destructor //
+ ////////////////////////////////////////////////////////////
- //! Update the mse factors, returning true if we need to recode
- /*!
- Update the mse factors, returning true if we need to recode
- \param enc_picture the picture being encoded
- */
- void UpdateModel(const EncPicture& enc_picture);
+ //! Update the mse factors, returning true if we need to recode
+ /*!
+ Update the mse factors, returning true if we need to recode
+ \param enc_picture the picture being encoded
+ */
+ void UpdateModel(const EncPicture& enc_picture );
- //! Reset the quality factors (say if there's been a cut)
- void ResetAll();
+ //! Reset the quality factors (say if there's been a cut)
+ void ResetAll();
- //! Write a log of the quality to date
- void WriteLog();
+ //! Write a log of the quality to date
+ void WriteLog();
-private:
- //functions
+ private:
+ //functions
- //! Calculate the quality of coded wrt original picture
- double QualityVal(const PicArray& coded_data ,
- const PicArray& orig_data,
- const int xlen,
- const int ylen);
+ //! Calculate the quality of coded wrt original picture
+ double QualityVal( const PicArray& coded_data ,
+ const PicArray& orig_data,
+ const int xlen,
+ const int ylen);
- //member variables//
- ////////////////////
+ //member variables//
+ ////////////////////
- //! A reference to the encoder parameters
- EncoderParams& m_encparams;
+ //! A reference to the encoder parameters
+ EncoderParams& m_encparams;
- //! The overall average Y mse
- long double m_totalmse_averageY;
+ //! The overall average Y mse
+ long double m_totalmse_averageY;
- //! The overall average U mse
- long double m_totalmse_averageU;
+ //! The overall average U mse
+ long double m_totalmse_averageU;
- //! The overall average V mse
- long double m_totalmse_averageV;
+ //! The overall average V mse
+ long double m_totalmse_averageV;
- //! The total number of pictures coded
- int m_allpicture_total;
+ //! The total number of pictures coded
+ int m_allpicture_total;
- //! The average Y mse for the picture types
- OneDArray<long double> m_mse_averageY;
+ //! The average Y mse for the picture types
+ OneDArray<long double> m_mse_averageY;
- //! The average U mse for the picture types
- OneDArray<long double> m_mse_averageU;
+ //! The average U mse for the picture types
+ OneDArray<long double> m_mse_averageU;
- //! The average V mse for the picture types
- OneDArray<long double> m_mse_averageV;
+ //! The average V mse for the picture types
+ OneDArray<long double> m_mse_averageV;
- //! The number of pictures of each type
- OneDArray<int> m_picture_total;
-};
+ //! The number of pictures of each type
+ OneDArray<int> m_picture_total;
+ };
} // namespace dirac
diff --git a/src/filters/parser/DiracSplitter/libdirac/libdirac_encoder/quant_chooser.cpp b/src/filters/parser/DiracSplitter/libdirac/libdirac_encoder/quant_chooser.cpp
index 9708a5166..9f369ffe8 100644
--- a/src/filters/parser/DiracSplitter/libdirac/libdirac_encoder/quant_chooser.cpp
+++ b/src/filters/parser/DiracSplitter/libdirac/libdirac_encoder/quant_chooser.cpp
@@ -45,21 +45,21 @@
using namespace dirac;
// Custom 4th power, to speed things up
-static inline double pow4(double x)
+static inline double pow4 (double x)
{
- return x * x * x * x;
+ return x * x * x* x;
}
// Constructor
-QuantChooser::QuantChooser(const CoeffArray& coeff_data,
- const float lambda):
- m_coeff_data(coeff_data),
- m_lambda(lambda),
- m_entropy_correctionfactor(1.0)
+QuantChooser::QuantChooser( const CoeffArray& coeff_data,
+ const float lambda ):
+ m_coeff_data( coeff_data ),
+ m_lambda( lambda ),
+ m_entropy_correctionfactor( 1.0 )
{}
-int QuantChooser::GetBestQuant(Subband& node)
+int QuantChooser::GetBestQuant( Subband& node )
{
// NB : quantiser selection only supports a single quantiser per subband
// Setting MultiQuants=true and using this function will get the same
@@ -71,131 +71,131 @@ int QuantChooser::GetBestQuant(Subband& node)
CoeffType max_val;
// The index of the maximum bit of the largest value
- int max_bit(0);
+ int max_bit( 0 );
- max_val = BlockAbsMax(node);
+ max_val = BlockAbsMax( node );
- if(max_val >= 1)
- max_bit = int(std::floor(std::log(float(max_val)) / std::log(2.0)));
+ if ( max_val>=1 )
+ max_bit = int( std::floor( std::log( float( max_val ) )/std::log( 2.0 ) ) );
else
{
- // Exit saying 'Skip this subband' if there's no data in it
- node.SetSkip(true);
+ // Exit saying 'Skip this subband' if there's no data in it
+ node.SetSkip( true );
return 0;
}
// The number of quantisers to be tested
- int num_quants(4 * max_bit + 5);
+ int num_quants( 4 * max_bit + 5 );
// Set the array sizes
- m_costs.Resize(num_quants);
- m_count0.Resize(num_quants);
- m_count1 = node.Xl() * node.Yl();
- m_countPOS.Resize(num_quants);
- m_countNEG.Resize(num_quants);
- m_error_total.Resize(num_quants);
+ m_costs.Resize( num_quants );
+ m_count0.Resize( num_quants );
+ m_count1=node.Xl()*node.Yl();
+ m_countPOS.Resize( num_quants );
+ m_countNEG.Resize( num_quants );
+ m_error_total.Resize( num_quants );
// Total estimated bits for the subband
- double bit_sum(0.0);
+ double bit_sum( 0.0 );
// Step 1. Do integral bits first
m_bottom_idx = 0;
- m_top_idx = num_quants - 1;
+ m_top_idx = num_quants-1;
m_index_step = 4;
- IntegralErrorCalc(node, 2 , 2);
- LagrangianCalc();
+ IntegralErrorCalc( node, 2 , 2);
+ LagrangianCalc( );
SelectBestQuant();
// Step 2. Do 1/2-bit accuracy next
- m_bottom_idx = std::max(m_min_idx - 2 , 0);
- m_top_idx = std::min(m_min_idx + 2 , num_quants - 1);
+ m_bottom_idx = std::max( m_min_idx - 2 , 0 );
+ m_top_idx = std::min( m_min_idx + 2 , num_quants-1 );
m_index_step = 2;
- NonIntegralErrorCalc(node, 2 , 2);
- LagrangianCalc();
+ NonIntegralErrorCalc( node, 2 , 2);
+ LagrangianCalc( );
SelectBestQuant();
// Step 3. Finally, do 1/4-bit accuracy next
- m_bottom_idx = std::max(m_min_idx - 1 , 0);
- m_top_idx = std::min(m_min_idx + 1 , num_quants - 1);
+ m_bottom_idx = std::max( m_min_idx - 1 , 0 );
+ m_top_idx = std::min( m_min_idx + 1 , num_quants-1 );
m_index_step = 1;
- NonIntegralErrorCalc(node, 1 , 2);
- LagrangianCalc();
+ NonIntegralErrorCalc( node, 1 , 2);
+ LagrangianCalc( );
SelectBestQuant();
bit_sum = m_costs[m_min_idx].ENTROPY * node.Xl() * node.Yl();
- node.SetQuantIndex(m_min_idx);
+ node.SetQuantIndex( m_min_idx );
- TwoDArray<CodeBlock>& block_list(node.GetCodeBlocks());
+ TwoDArray<CodeBlock>& block_list( node.GetCodeBlocks() );
// Set the codeblock quantisers
- for(int j = 0 ; j < block_list.LengthY() ; ++j)
- for(int i = 0 ; i < block_list.LengthX() ; ++i)
- block_list[j][i].SetQuantIndex(m_min_idx);
+ for (int j=0 ; j<block_list.LengthY() ; ++j )
+ for (int i=0 ; i<block_list.LengthX() ; ++i )
+ block_list[j][i].SetQuantIndex( m_min_idx );
// Set the codeblock skip flags
- for(int j = 0 ; j < block_list.LengthY() ; ++j)
- for(int i = 0 ; i < block_list.LengthX() ; ++i)
- SetSkip(block_list[j][i], m_min_idx);
+ for (int j=0 ; j<block_list.LengthY() ; ++j )
+ for (int i=0 ; i<block_list.LengthX() ; ++i )
+ SetSkip( block_list[j][i], m_min_idx );
- return static_cast<int>(bit_sum);
+ return static_cast<int>( bit_sum );
}
-void QuantChooser::IntegralErrorCalc(Subband& node, const int xratio , const int yratio)
+void QuantChooser::IntegralErrorCalc( Subband& node, const int xratio , const int yratio )
{
CoeffType val, quant_val , abs_val;
CalcValueType error;
- m_count1 = ((node.Xl() / xratio) * (node.Yl() / yratio));
- for(int q = m_bottom_idx ; q <= m_top_idx ; q += 4)
+ m_count1 = ( (node.Xl()/xratio)*(node.Yl()/yratio) );
+ for (int q = m_bottom_idx ; q<=m_top_idx ; q+=4 )
{
m_error_total[q] = 0.0;
- m_count0[q] = 0;
+ m_count0[q] =0;
m_countPOS[q] = 0;
m_countNEG[q] = 0;
}
// Work out the error totals and counts for each quantiser
- for(int j = node.Yp(); j < node.Yp() + node.Yl() ; j += yratio)
+ for ( int j=node.Yp(); j<node.Yp()+node.Yl() ; j+=yratio )
{
- for(int i = node.Xp(); i < node.Xp() + node.Xl() ; i += xratio)
+ for ( int i=node.Xp(); i<node.Xp()+node.Xl() ; i+=xratio )
{
val = m_coeff_data[j][i];
abs_val = quant_val = abs(val);
int q = m_bottom_idx;
- for(; q <= m_top_idx ; q += 4)
+ for ( ; q<=m_top_idx ; q+=4 )
{
// Quantiser is 2^(q/4), so we divide by this
- quant_val >>= (q >> 2);
- if(!quant_val)
+ quant_val >>= (q>>2);
+ if (!quant_val)
break;
m_count0[q] += quant_val;
// Multiply back up so that we can quantise again in the next loop step
- quant_val <<= (q >> 2) + 2;
- quant_val += dirac_quantiser_lists.InterQuantOffset4(q) + 2;
+ quant_val <<= (q>>2)+2;
+ quant_val += dirac_quantiser_lists.InterQuantOffset4( q )+2;
quant_val >>= 2;
- if(val > 0)
+ if (val>0)
m_countPOS[q]++;
else
m_countNEG[q]++;
- error = abs_val - quant_val;
+ error = abs_val-quant_val;
// Using the fourth power to measure the error
- m_error_total[q] += pow4(static_cast<double>(error));
+ m_error_total[q] += pow4( static_cast<double>( error ) );
}// q
- double derror = pow4(static_cast<double>(abs_val));
- for(; q <= m_top_idx; q += 4)
+ double derror = pow4 ( static_cast<double>( abs_val ) );
+ for (; q <= m_top_idx; q+= 4)
{
m_error_total[q] += derror;
}
@@ -204,7 +204,7 @@ void QuantChooser::IntegralErrorCalc(Subband& node, const int xratio , const int
}
-void QuantChooser::NonIntegralErrorCalc(Subband& node , const int xratio , const int yratio)
+void QuantChooser::NonIntegralErrorCalc( Subband& node , const int xratio , const int yratio )
{
CoeffType val, abs_val;
@@ -212,51 +212,51 @@ void QuantChooser::NonIntegralErrorCalc(Subband& node , const int xratio , const
CalcValueType quant_val;
CalcValueType error;
- m_count1 = ((node.Xl() / xratio) * (node.Yl() / yratio));
- for(int q = m_bottom_idx ; q <= m_top_idx ; q += m_index_step)
+ m_count1 = ( (node.Xl()/xratio)*(node.Yl()/yratio) );
+ for (int q = m_bottom_idx ; q<=m_top_idx ; q+=m_index_step )
{
m_error_total[q] = 0.0;
- m_count0[q] = 0;
+ m_count0[q] =0;
m_countPOS[q] = 0;
m_countNEG[q] = 0;
}
// Work out the error totals and counts for each quantiser
- for(int j = node.Yp(); j < node.Yp() + node.Yl() ; j += yratio)
+ for ( int j=node.Yp(); j<node.Yp()+node.Yl() ; j+=yratio )
{
- for(int i = node.Xp(); i < node.Xp() + node.Xl() ; i += xratio)
+ for ( int i=node.Xp(); i<node.Xp()+node.Xl() ; i+=xratio )
{
val = m_coeff_data[j][i];
- abs_val = abs(val);
+ abs_val = abs( val );
- int q = m_bottom_idx;
- for(; q <= m_top_idx ; q += m_index_step)
+ int q=m_bottom_idx;
+ for ( ; q<=m_top_idx ; q+=m_index_step )
{
- // Since the quantiser isn't a power of 2 we have to divide each time
- quant_val = static_cast<CalcValueType>(abs_val);
- quant_val <<= 2;
- quant_val /= dirac_quantiser_lists.QuantFactor4(q);
-
- if(!quant_val)
- break;
-
- m_count0[q] += quant_val;
- quant_val *= dirac_quantiser_lists.QuantFactor4(q);
- quant_val += dirac_quantiser_lists.InterQuantOffset4(q) + 2;
- quant_val >>= 2;
-
- if(val > 0)
- m_countPOS[q]++;
- else
- m_countNEG[q]++;
-
- error = abs_val - quant_val;
- m_error_total[q] += pow4(error);
- }// q
- double derror = pow4(abs_val);
- for(; q <= m_top_idx; q += m_index_step)
- m_error_total[q] += derror;
+ // Since the quantiser isn't a power of 2 we have to divide each time
+ quant_val = static_cast<CalcValueType>( abs_val );
+ quant_val <<= 2;
+ quant_val /= dirac_quantiser_lists.QuantFactor4( q );
+
+ if ( !quant_val )
+ break;
+
+ m_count0[q] += quant_val;
+ quant_val *= dirac_quantiser_lists.QuantFactor4( q );
+ quant_val += dirac_quantiser_lists.InterQuantOffset4( q )+2;
+ quant_val >>= 2;
+
+ if ( val>0 )
+ m_countPOS[q]++;
+ else
+ m_countNEG[q]++;
+
+ error = abs_val-quant_val;
+ m_error_total[q] += pow4( error );
+ }// q
+ double derror = pow4( abs_val );
+ for ( ; q <= m_top_idx; q += m_index_step)
+ m_error_total[q] += derror;
}// i
}// j
@@ -267,52 +267,52 @@ void QuantChooser::LagrangianCalc()
{
// probabilities
- double p0, p1;
+ double p0,p1;
double sign_entropy;
- // Do Lagrangian costs calculation
- for(int q = m_bottom_idx ; q <= m_top_idx ; q += m_index_step)
+ // Do Lagrangian costs calculation
+ for ( int q=m_bottom_idx ; q<=m_top_idx ; q += m_index_step )
{
- m_costs[q].Error = m_error_total[q] / double(m_count1);
- m_costs[q].Error = std::sqrt(m_costs[q].Error) / (m_subband_wt * m_subband_wt);
+ m_costs[q].Error = m_error_total[q]/double(m_count1);
+ m_costs[q].Error = std::sqrt( m_costs[q].Error )/( m_subband_wt*m_subband_wt );
// Calculate probabilities and entropy
- p0 = double(m_count0[q]) / double(m_count0[q] + m_count1);
+ p0 = double( m_count0[q] )/ double( m_count0[q]+m_count1 );
p1 = 1.0 - p0;
- if(p0 != 0.0 && p1 != 0.0)
- m_costs[q].ENTROPY = -(p0 * std::log(p0) + p1 * std::log(p1)) / std::log(2.0);
+ if ( p0 != 0.0 && p1 != 0.0)
+ m_costs[q].ENTROPY = -( p0*std::log(p0)+p1*std::log(p1) ) / std::log(2.0);
else
m_costs[q].ENTROPY = 0.0;
- // We want the entropy *per symbol*, not per bit ...
- m_costs[q].ENTROPY *= double(m_count0[q] + m_count1);
+ // We want the entropy *per symbol*, not per bit ...
+ m_costs[q].ENTROPY *= double(m_count0[q]+m_count1);
m_costs[q].ENTROPY /= double(m_count1);
// Now add in the sign entropy
- if(m_countPOS[q] + m_countNEG[q] != 0)
+ if ( m_countPOS[q] + m_countNEG[q] != 0 )
{
- p0 = double(m_countNEG[q]) / double(m_countPOS[q] + m_countNEG[q]);
- p1 = 1.0 - p0;
- if(p0 != 0.0 && p1 != 0.0)
- sign_entropy = -((p0 * std::log(p0) + p1 * std::log(p1)) / std::log(2.0));
+ p0 = double( m_countNEG[q] )/double( m_countPOS[q]+m_countNEG[q] );
+ p1 = 1.0-p0;
+ if ( p0 != 0.0 && p1 != 0.0)
+ sign_entropy = -( (p0*std::log(p0)+p1*std::log(p1) ) / std::log(2.0));
else
sign_entropy = 0.0;
}
else
- sign_entropy = 0.0;
+ sign_entropy = 0.0;
// We want the entropy *per symbol*, not per bit ...
- sign_entropy *= double(m_countNEG[q] + m_countPOS[q]);
+ sign_entropy *= double( m_countNEG[q] + m_countPOS[q] );
sign_entropy /= double(m_count1);
m_costs[q].ENTROPY += sign_entropy;
// Sort out correction factors
m_costs[q].ENTROPY *= m_entropy_correctionfactor;
- m_costs[q].TOTAL = m_costs[q].Error + m_lambda * m_costs[q].ENTROPY;
+ m_costs[q].TOTAL = m_costs[q].Error+m_lambda*m_costs[q].ENTROPY;
}// q
}
@@ -322,40 +322,40 @@ void QuantChooser::SelectBestQuant()
// Selects the best quantiser to use for a subband block
m_min_idx = m_bottom_idx;
- for(int q = m_bottom_idx + m_index_step; q <= m_top_idx ; q += m_index_step)
+ for ( int q=m_bottom_idx + m_index_step; q<=m_top_idx ; q +=m_index_step )
{
- if(m_costs[q].TOTAL < m_costs[m_min_idx].TOTAL)
+ if ( m_costs[q].TOTAL < m_costs[m_min_idx].TOTAL)
m_min_idx = q;
}// q
-
+
}
-void QuantChooser::SetSkip(CodeBlock& cblock , const int qidx)
+void QuantChooser::SetSkip( CodeBlock& cblock , const int qidx)
{
- const int u_threshold = dirac_quantiser_lists.QuantFactor4(qidx);
-
+ const int u_threshold = dirac_quantiser_lists.QuantFactor4( qidx );
+
// Sets the skip flag for a codeblock
bool can_skip = true;
- for(int j = cblock.Ystart(); j < cblock.Yend(); ++j)
+ for (int j=cblock.Ystart(); j<cblock.Yend(); ++j )
{
- for(int i = cblock.Xstart(); i < cblock.Xend(); ++i)
+ for (int i=cblock.Xstart(); i<cblock.Xend(); ++i )
{
- if((std::abs(m_coeff_data[j][i]) << 2) >= u_threshold)
+ if ( (std::abs(m_coeff_data[j][i])<<2) >= u_threshold )
can_skip = false;
- }
+ }
}
- cblock.SetSkip(can_skip);
+ cblock.SetSkip( can_skip );
}
-CoeffType QuantChooser::BlockAbsMax(const Subband& node)
+CoeffType QuantChooser::BlockAbsMax( const Subband& node )
{
- int val(0);
+ int val( 0 );
- for(int j = node.Yp() ; j < node.Yp() + node.Yl(); ++j)
+ for (int j=node.Yp() ; j<node.Yp()+node.Yl(); ++j)
{
- for(int i = node.Xp() ; i < node.Xp() + node.Xl(); ++i)
- {
- val = std::max(val , std::abs(m_coeff_data[j][i]));
+ for (int i=node.Xp() ; i<node.Xp()+node.Xl(); ++i)
+ {
+ val = std::max( val , std::abs(m_coeff_data[j][i]) );
}// i
}// j
diff --git a/src/filters/parser/DiracSplitter/libdirac/libdirac_encoder/quant_chooser.h b/src/filters/parser/DiracSplitter/libdirac/libdirac_encoder/quant_chooser.h
index 56c0c18a3..c1d28302c 100644
--- a/src/filters/parser/DiracSplitter/libdirac/libdirac_encoder/quant_chooser.h
+++ b/src/filters/parser/DiracSplitter/libdirac/libdirac_encoder/quant_chooser.h
@@ -45,86 +45,83 @@
namespace dirac
{
-//! Choose a quantiser
-/*!
- This class chooses a quantiser or quantisers for a subband
-*/
-class QuantChooser
-{
-public:
-
- //! Constructor
- QuantChooser(const CoeffArray& pic_data , const float lambda);
+ //! Choose a quantiser
+ /*!
+ This class chooses a quantiser or quantisers for a subband
+ */
+ class QuantChooser
+ {
+ public:
- //! Finds the best quantisers for the subband, returning the predicted number of bits needed
- int GetBestQuant(Subband& node);
+ //! Constructor
+ QuantChooser( const CoeffArray& pic_data , const float lambda );
- //! Sets the factor used for correcting the entropy calculation
- void SetEntropyCorrection(const float ecfac)
- {
- m_entropy_correctionfactor = ecfac;
- }
-private:
- //! Copy constructor is private and body-less. This class should not be copied.
- QuantChooser(const QuantChooser& cpy);
+ //! Finds the best quantisers for the subband, returning the predicted number of bits needed
+ int GetBestQuant( Subband& node );
- //! Assignment = is private and body-less. This class should not be assigned.
- QuantChooser& operator=(const QuantChooser& rhs);
+ //! Sets the factor used for correcting the entropy calculation
+ void SetEntropyCorrection( const float ecfac ){ m_entropy_correctionfactor = ecfac; }
+ private:
+ //! Copy constructor is private and body-less. This class should not be copied.
+ QuantChooser(const QuantChooser& cpy);
- //! Calculate errors and entropies for integral-bit quantisers
- void IntegralErrorCalc(Subband& node , const int xratio , const int yratio);
+ //! Assignment = is private and body-less. This class should not be assigned.
+ QuantChooser& operator=(const QuantChooser& rhs);
+
+ //! Calculate errors and entropies for integral-bit quantisers
+ void IntegralErrorCalc( Subband& node , const int xratio , const int yratio );
- //! Calculate errors and entropies for non-integral-bit quantisers
- void NonIntegralErrorCalc(Subband& node, const int xratio, const int yratio);
+ //! Calculate errors and entropies for non-integral-bit quantisers
+ void NonIntegralErrorCalc( Subband& node, const int xratio, const int yratio );
- //! Having got statistics, calculate the Lagrangian costs
- void LagrangianCalc();
+ //! Having got statistics, calculate the Lagrangian costs
+ void LagrangianCalc();
- //! Select the best quantisation index on the basis of the Lagrangian calculations
- void SelectBestQuant();
+ //! Select the best quantisation index on the basis of the Lagrangian calculations
+ void SelectBestQuant();
- CoeffType BlockAbsMax(const Subband& node);
+ CoeffType BlockAbsMax( const Subband& node );
- //! Set the skip flag for a codeblock
- void SetSkip(CodeBlock& cblock , const int qidx);
+ //! Set the skip flag for a codeblock
+ void SetSkip( CodeBlock& cblock , const int qidx);
-private:
- //! The perceptual weighting factor of the subband being tested
- float m_subband_wt;
+ private:
+ //! The perceptual weighting factor of the subband being tested
+ float m_subband_wt;
- //! The smallest quantisation index being tested
- int m_bottom_idx;
- //! The largest quantisation index being tested
- int m_top_idx;
- //! The step we use in jumping through the list of quantisers
- int m_index_step;
+ //! The smallest quantisation index being tested
+ int m_bottom_idx;
+ //! The largest quantisation index being tested
+ int m_top_idx;
+ //! The step we use in jumping through the list of quantisers
+ int m_index_step;
- //! The index of the quantiser with the lowest cost
- int m_min_idx;
+ //! The index of the quantiser with the lowest cost
+ int m_min_idx;
- //! A local reference to the data under consideration
- const CoeffArray& m_coeff_data;
+ //! A local reference to the data under consideration
+ const CoeffArray& m_coeff_data;
- //! The lambda value to be used in the Lagrangian calculation
- const float m_lambda;
+ //! The lambda value to be used in the Lagrangian calculation
+ const float m_lambda;
- //! A value for correcting the crude calculation of the entropy
- float m_entropy_correctionfactor;
+ //! A value for correcting the crude calculation of the entropy
+ float m_entropy_correctionfactor;
- //! An array used to count the number of zeroes
- OneDArray<int> m_count0;
- //! The number of ones (equal to the number of coefficients)
- int m_count1;
- //! An array used to count the number of positive values
- OneDArray<int> m_countPOS;
- //! An array used to count the number of negative values
- OneDArray<int> m_countNEG;
- //! An array used to collate the sum of the perceptually-weighted errors
- OneDArray<double> m_error_total;
- //! An array used to collate the computed costs
- OneDArray<CostType> m_costs;
+ //! An array used to count the number of zeroes
+ OneDArray<int> m_count0;
+ //! The number of ones (equal to the number of coefficients)
+ int m_count1;
+ //! An array used to count the number of positive values
+ OneDArray<int> m_countPOS;
+ //! An array used to count the number of negative values
+ OneDArray<int> m_countNEG;
+ //! An array used to collate the sum of the perceptually-weighted errors
+ OneDArray<double> m_error_total;
+ //! An array used to collate the computed costs
+ OneDArray<CostType> m_costs;
-};
+ };
} // namespace dirac
diff --git a/src/filters/parser/DiracSplitter/libdirac/libdirac_encoder/rate_control.cpp b/src/filters/parser/DiracSplitter/libdirac/libdirac_encoder/rate_control.cpp
index da4b4bab8..bd5b62346 100644
--- a/src/filters/parser/DiracSplitter/libdirac/libdirac_encoder/rate_control.cpp
+++ b/src/filters/parser/DiracSplitter/libdirac/libdirac_encoder/rate_control.cpp
@@ -89,30 +89,30 @@ FrameComplexity::FrameComplexity():
//Default constructor
RateController::RateController(int trate, SourceParams& srcp, EncoderParams& encp):
- m_qf(encp.Qf()),
- m_I_qf(encp.Qf()),
+ m_qf (encp.Qf()),
+ m_I_qf (encp.Qf()),
m_I_qf_long_term(encp.Qf()),
m_target_rate(trate),
- m_buffer_size(5000 * trate), // for the moment, set buffer size to 5 seconds
- m_buffer_bits((m_buffer_size * 9) / 10), // initial occupancy of 90%
+ m_buffer_size(5000*trate),// for the moment, set buffer size to 5 seconds
+ m_buffer_bits((m_buffer_size*9)/10),// initial occupancy of 90%
m_encparams(encp),
- m_fcount(encp.L1Sep()),
+ m_fcount(encp.L1Sep() ),
m_intra_only(false),
m_L2_complexity_sum(0)
{
SetFrameDistribution();
CalcTotalBits(srcp);
- if(m_intra_only)
+ if (m_intra_only)
m_Iframe_bits = m_total_GOP_bits;
else
{
- m_Iframe_bits = m_total_GOP_bits / 10;
- m_L1frame_bits = (m_Iframe_bits * 3) / m_num_L1frame;
- if(m_encparams.L1Sep() > 1)
- m_L2frame_bits = (m_total_GOP_bits - m_Iframe_bits -
- m_L1frame_bits * m_num_L1frame) /
- (m_encparams.GOPLength() - 1 - m_num_L1frame);
+ m_Iframe_bits = m_total_GOP_bits/10;
+ m_L1frame_bits = (m_Iframe_bits*3)/m_num_L1frame;
+ if (m_encparams.L1Sep()>1)
+ m_L2frame_bits = ( m_total_GOP_bits - m_Iframe_bits -
+ m_L1frame_bits*m_num_L1frame )/
+ (m_encparams.GOPLength()-1-m_num_L1frame);
else
m_L2frame_bits = 0;
@@ -124,7 +124,7 @@ void RateController::SetFrameDistribution()
m_num_L1frame = m_encparams.NumL1();
m_num_Iframe = 1;
- if(m_num_L1frame == 0)
+ if (m_num_L1frame == 0)
{
m_num_Iframe = m_encparams.GOPLength();
m_intra_only = true;
@@ -136,60 +136,60 @@ void RateController::SetFrameDistribution()
void RateController::CalcTotalBits(const SourceParams& sourceparams)
{
const Rational& frame_rate = sourceparams.FrameRate();
- double f_rate = double(frame_rate.m_num) / double(frame_rate.m_denom);
+ double f_rate = double(frame_rate.m_num)/double(frame_rate.m_denom);
int GOP_length = m_encparams.GOPLength();
- m_GOP_duration = GOP_length / f_rate;
- m_total_GOP_bits = (long int)(m_GOP_duration * 1000.0) * m_target_rate; //Unit in bits
+ m_GOP_duration = GOP_length/f_rate;
+ m_total_GOP_bits = (long int)(m_GOP_duration*1000.0)*m_target_rate; //Unit in bits
m_GOP_target = m_total_GOP_bits;
- m_picture_bits = m_total_GOP_bits / GOP_length;
+ m_picture_bits = m_total_GOP_bits/GOP_length;
- if(m_encparams.Verbose())
+ if (m_encparams.Verbose())
{
- std::cout << "\nRate Control Encoding with target bit rate = ";
- std::cout << m_target_rate << " kbps" << std::endl;
+ std::cout<<"\nRate Control Encoding with target bit rate = ";
+ std::cout<<m_target_rate<<" kbps"<< std::endl;
- std::cout << "GOP Length = " << GOP_length << std::endl;
+ std::cout<<"GOP Length = "<<GOP_length<< std::endl;
- std::cout << "Frame Rate = " << f_rate << std::endl;
+ std::cout<<"Frame Rate = "<<f_rate<< std::endl;
- std::cout << "GOP Duration = " << m_GOP_duration << std::endl;
+ std::cout<<"GOP Duration = "<<m_GOP_duration<< std::endl;
- std::cout << "Total Allocated Num. of bits for each GOP = ";
- std::cout << m_total_GOP_bits << " (" << m_picture_bits << " per frame)";
- std::cout << std::endl;
+ std::cout<<"Total Allocated Num. of bits for each GOP = ";
+ std::cout<<m_total_GOP_bits<<" ("<<m_picture_bits<<" per frame)";
+ std::cout<<std::endl;
}
}
void RateController::Report()
{
- std::cout << std::endl;
- std::cout << std::endl << "GOP target is " << m_GOP_target;
- std::cout << std::endl << "Allocated frame bits by type: ";
- std::cout << "I frames - " << m_Iframe_bits;
- std::cout << "; L1/P frames - " << m_L1frame_bits;
- std::cout << "; L2/B frames - " << m_L2frame_bits;
- std::cout << std::endl;
+ std::cout<<std::endl;
+ std::cout<<std::endl<<"GOP target is "<<m_GOP_target;
+ std::cout<<std::endl<<"Allocated frame bits by type: ";
+ std::cout<<"I frames - "<<m_Iframe_bits;
+ std::cout<<"; L1/P frames - "<<m_L1frame_bits;
+ std::cout<<"; L2/B frames - "<<m_L2frame_bits;
+ std::cout<<std::endl;
}
double RateController::TargetSubgroupRate()
{
- long int bits = (m_encparams.L1Sep() - 1) * m_L2frame_bits +
- m_L1frame_bits;
- return (double)(bits) / (1000.0 * m_GOP_duration);
+ long int bits = (m_encparams.L1Sep()-1)*m_L2frame_bits+
+ m_L1frame_bits;
+ return (double)(bits)/(1000.0*m_GOP_duration);
}
double RateController::ProjectedSubgroupRate()
{
- int bits = (m_encparams.L1Sep() - 1) * m_frame_complexity.L2Complexity() +
+ int bits = (m_encparams.L1Sep()-1)*m_frame_complexity.L2Complexity()+
m_frame_complexity.L1Complexity();
- return (double)(bits) / (1000.0 * m_GOP_duration);
+ return (double)(bits)/(1000.0*m_GOP_duration);
}
void RateController::CalcNextQualFactor(const PictureParams& pparams, int num_bits)
{
@@ -198,54 +198,53 @@ void RateController::CalcNextQualFactor(const PictureParams& pparams, int num_bi
// L2 frame before the next L1 frame i.e. before the start of an L1L2L2
// subgroup
m_fcount--;
- UpdateBuffer(num_bits);
+ UpdateBuffer( num_bits );
// filter tap for adjusting the QF
double target_ratio = 0.9;
int field_factor = m_encparams.FieldCoding() ? 2 : 1;
- double top_size = (1.0 - target_ratio) - 0.5;
- double bottom_size = target_ratio - 0.1;
- double actual_ratio = double(m_buffer_bits) / double(m_buffer_size);
+ double top_size = (1.0 - target_ratio)-0.5;
+ double bottom_size = target_ratio-0.1;
+ double actual_ratio = double(m_buffer_bits)/double(m_buffer_size);
double tap;
- if((pparams.PictureNum() / field_factor) <= 3 * m_encparams.L1Sep())
+ if ((pparams.PictureNum()/field_factor)<=3*m_encparams.L1Sep() )
tap = 1.0;
- else
- {
- if(actual_ratio > target_ratio)
- tap = (actual_ratio - target_ratio) / top_size;
+ else{
+ if (actual_ratio>target_ratio)
+ tap = (actual_ratio-target_ratio)/top_size;
else
- tap = (target_ratio - actual_ratio) / bottom_size;
+ tap = (target_ratio-actual_ratio)/bottom_size;
- tap = std::min(1.0, std::max(tap, 0.25));
+ tap = std::min( 1.0, std::max(tap, 0.25 ));
}
- if(!m_intra_only)
+ if (!m_intra_only)
{
bool emergency_realloc = false;
int target;
// First, do normal coding
- if(pparams.PicSort().IsIntra() == true)
+ if ( pparams.PicSort().IsIntra() == true )
{
target = m_Iframe_bits;
- if(num_bits < target / 2)
+ if (num_bits < target/2 )
emergency_realloc = true;
// Update the statistics
- m_frame_complexity.SetIComplexity(num_bits);
+ m_frame_complexity.SetIComplexity( num_bits );
// We've just coded an intra frame so we need to set qf for
// the next group of L2(B) frames
- m_qf = std::max(tap * m_qf + (1.0 - tap) * m_encparams.Qf(), m_encparams.Qf() - 1.0);
- m_encparams.SetQf(m_qf);
+ m_qf = std::max(tap*m_qf+(1.0-tap)*m_encparams.Qf(), m_encparams.Qf()-1.0);
+ m_encparams.SetQf( m_qf );
- if(pparams.PictureNum() / field_factor == 0)
+ if (pparams.PictureNum()/field_factor==0)
{
// We've just coded the very first frame, which is a special
// case as the two L2 frames which normally follow are missing
@@ -255,47 +254,45 @@ void RateController::CalcNextQualFactor(const PictureParams& pparams, int num_bi
}
//Update complexities
- if((pparams.PictureNum() / field_factor) % m_encparams.L1Sep() != 0)
+ if ( (pparams.PictureNum()/field_factor) % m_encparams.L1Sep() !=0 )
{
// Scheduled B/L2 picture
target = m_L2frame_bits;
- if(num_bits < target / 2)
- {
+ if (num_bits < target/2 ){
emergency_realloc = true;
}
m_L2_complexity_sum += num_bits;
}
- else if(pparams.PicSort().IsIntra() == false)
+ else if ( pparams.PicSort().IsIntra() == false )
{
// Scheduled P/L1 picture (if inserted I picture, don't change the complexity)
target = m_L1frame_bits;
- if(num_bits < target / 2 || num_bits > target * 3)
- {
+ if (num_bits < target/2 || num_bits > target*3 ){
emergency_realloc = true;
}
m_frame_complexity.SetL1Complexity(num_bits);
}
- if(m_fcount == 0 || emergency_realloc == true)
+ if ( m_fcount==0 || emergency_realloc==true)
{
- if(emergency_realloc == true && m_encparams.Verbose() == true)
- std::cout << std::endl << "Major mis-prediction of frame bit rate: re-allocating";
+ if (emergency_realloc==true && m_encparams.Verbose()==true )
+ std::cout<<std::endl<<"Major mis-prediction of frame bit rate: re-allocating";
/* We recompute allocations for the next subgroup */
- if(m_encparams.L1Sep() > 1 && m_fcount < m_encparams.L1Sep() - 1)
+ if ( m_encparams.L1Sep()>1 && m_fcount<m_encparams.L1Sep()-1)
{
- m_frame_complexity.SetL2Complexity(m_L2_complexity_sum /
- (m_encparams.L1Sep() - 1 - m_fcount));
+ m_frame_complexity.SetL2Complexity(m_L2_complexity_sum/
+ (m_encparams.L1Sep()-1-m_fcount));
}
- Allocate((pparams.PictureNum() / field_factor));
+ Allocate( (pparams.PictureNum()/field_factor) );
/* We work out what this means for the quality factor and set it*/
@@ -307,29 +304,28 @@ void RateController::CalcNextQualFactor(const PictureParams& pparams, int num_bi
// from measured values (complexities)
double prate = ProjectedSubgroupRate();
- if(m_encparams.Verbose() == true)
+ if (m_encparams.Verbose()==true )
{
- std::cout << std::endl << "Target subgroup rate = " << trate;
- std::cout << ", projected subgroup rate = " << prate;
+ std::cout<<std::endl<<"Target subgroup rate = "<<trate;
+ std::cout<<", projected subgroup rate = "<<prate;
}
// Determine K value
- double K = std::pow(prate, 2) * std::pow(10.0, ((double)2 / 5 * (10 - m_qf))) / 16;
+ double K = std::pow(prate, 2)*std::pow(10.0, ((double)2/5*(10-m_qf)))/16;
// Determine a new QF
- double new_qf = 10 - (double)5 / 2 * log10(16 * K / std::pow(trate, 2));
- if((std::abs(m_qf - new_qf) < 0.25 && new_qf > 4.0) || new_qf > 8.0)
+ double new_qf = 10 - (double)5/2*log10(16*K/std::pow(trate, 2));
+ if ( ( std::abs(m_qf-new_qf)<0.25 && new_qf > 4.0 ) || new_qf>8.0)
m_qf = new_qf;
else
- m_qf = tap * new_qf + (1.0 - tap) * m_qf;
+ m_qf = tap*new_qf+(1.0-tap)*m_qf;
- m_qf = ReviewQualityFactor(m_qf , num_bits);
+ m_qf = ReviewQualityFactor( m_qf , num_bits );
- if(m_qf < 8.0)
- {
- if(prate < 2 * trate)
- m_qf = std::max(m_qf, m_encparams.Qf() - 1.0);
+ if ( m_qf<8.0 ){
+ if (prate<2*trate)
+ m_qf = std::max(m_qf,m_encparams.Qf()-1.0);
else
- m_qf = std::max(m_qf, m_encparams.Qf() - 2.0);
+ m_qf = std::max(m_qf,m_encparams.Qf()-2.0);
}
m_encparams.SetQf(m_qf);
@@ -338,7 +334,7 @@ void RateController::CalcNextQualFactor(const PictureParams& pparams, int num_bi
/* Resetting */
// Reset the frame counter
- if(m_fcount == 0)
+ if (m_fcount==0)
m_fcount = m_encparams.L1Sep();
// Reset the count of L2 bits
@@ -352,22 +348,22 @@ void RateController::CalcNextQualFactor(const PictureParams& pparams, int num_bi
// Target rate
- double trate = double(m_total_GOP_bits) / (1000.0 * m_num_Iframe);
+ double trate = double(m_total_GOP_bits)/(1000.0*m_num_Iframe);
// Projected rate with current QF
- double prate = double(num_bits) / 1000.0;
+ double prate = double(num_bits)/1000.0;
// Determine K value
- double K = std::pow(prate, 2) * std::pow(10.0, ((double)2 / 5 * (10 - m_qf))) / 16;
+ double K = std::pow(prate, 2)*std::pow(10.0, ((double)2/5*(10-m_qf)))/16;
// Determine a new QF
- double new_qf = 10 - (double)5 / 2 * log10(16 * K / std::pow(trate, 2));
+ double new_qf = 10 - (double)5/2*log10(16*K/std::pow(trate, 2));
// Adjust the QF to meet the target
- double abs_delta = std::abs(new_qf - m_qf);
- if(abs_delta > 0.01)
+ double abs_delta = std::abs( new_qf - m_qf );
+ if ( abs_delta>0.01)
{
// Rate of convergence to new QF
double r;
@@ -386,16 +382,16 @@ void RateController::CalcNextQualFactor(const PictureParams& pparams, int num_bi
Actual parameters may be adjusted later. Some applications may
require instant lock.
*/
- double lg_diff = std::log(abs_delta / 2.0);
- if(lg_diff < 0.0)
- r = 0.5 * std::exp(-lg_diff * lg_diff / 2.0);
+ double lg_diff = std::log( abs_delta/2.0 );
+ if ( lg_diff< 0.0 )
+ r = 0.5*std::exp(-lg_diff*lg_diff/2.0);
else
- r = 1.0 - 0.5 * std::exp(-lg_diff * lg_diff / 2.0);
+ r = 1.0-0.5*std::exp(-lg_diff*lg_diff/2.0);
r *= 0.75;
- m_qf = r * m_qf + (1.0 - r) * new_qf;
- m_qf = ReviewQualityFactor(m_qf , num_bits);
+ m_qf = r*m_qf + (1.0-r)*new_qf;
+ m_qf = ReviewQualityFactor( m_qf , num_bits );
m_encparams.SetQf(m_qf);
}
@@ -406,31 +402,31 @@ void RateController::CalcNextQualFactor(const PictureParams& pparams, int num_bi
}
-void RateController::UpdateBuffer(const long int num_bits)
+void RateController::UpdateBuffer( const long int num_bits )
{
m_buffer_bits -= num_bits;
m_buffer_bits += m_picture_bits;
- if(m_encparams.Verbose())
+ if (m_encparams.Verbose())
{
- std::cout << std::endl << "Buffer occupancy = " << ((double)m_buffer_bits * 100.0)
- / ((double)m_buffer_size) << "%";
+ std::cout<<std::endl<<"Buffer occupancy = "<<((double)m_buffer_bits*100.0)
+ /((double)m_buffer_size)<<"%";
}
- if(m_buffer_bits < 0)
+ if (m_buffer_bits<0)
{
- if(m_encparams.Verbose())
+ if (m_encparams.Verbose())
{
- std::cout << std::endl << "WARNING: decoder buffer is out of bits - bit rate is too high";
+ std::cout<<std::endl<<"WARNING: decoder buffer is out of bits - bit rate is too high";
}
// m_buffer_bits = 0;
}
- if(m_buffer_bits > m_buffer_size)
+ if (m_buffer_bits>m_buffer_size)
{
- if(m_encparams.Verbose())
+ if (m_encparams.Verbose())
{
- std::cout << std::endl << "WARNING: decoder buffer has overflowed - bit rate is too low. Assuming bit-stuffing.";
+ std::cout<<std::endl<<"WARNING: decoder buffer has overflowed - bit rate is too low. Assuming bit-stuffing.";
}
m_buffer_bits = m_buffer_size;
}
@@ -438,97 +434,97 @@ void RateController::UpdateBuffer(const long int num_bits)
}
-void RateController::Allocate(const int fnum)
+void RateController::Allocate (const int fnum)
{
const int XI = m_frame_complexity.IComplexity();
const int XL1 = m_frame_complexity.L1Complexity();
const int XL2 = m_frame_complexity.L2Complexity();
- double buffer_occ = ((double)m_buffer_bits) / ((double)m_buffer_size);
+ double buffer_occ = ( (double)m_buffer_bits)/((double)m_buffer_size);
- if(!m_intra_only)
+ if ( !m_intra_only)
{
double correction;
- if(buffer_occ < 0.9 && ((fnum + 1) % 4 * m_encparams.L1Sep()) == 0)
+ if (buffer_occ<0.9 && ( (fnum+1) % 4*m_encparams.L1Sep())==0 )
{
// If we're undershooting buffer target, correct slowly
- correction = std::min(0.25, 0.25 * (0.9 - buffer_occ) / 0.9);
- m_GOP_target = (long int)(double(m_total_GOP_bits) * (1.0 - correction));
+ correction = std::min( 0.25, 0.25*(0.9 - buffer_occ )/0.9 );
+ m_GOP_target = ( long int)(double(m_total_GOP_bits)*( 1.0-correction) );
}
- else if(buffer_occ > 0.9 && ((fnum + 1) % m_encparams.L1Sep()) == 0)
+ else if (buffer_occ>0.9 && ((fnum+1) % m_encparams.L1Sep())==0)
{
// If we're overshooting buffer target, correct quickly
- correction = std::min(0.5, 0.5 * (buffer_occ - 0.9) / 0.9);
- m_GOP_target = (long int)(double(m_total_GOP_bits) * (1.0 + correction));
+ correction = std::min( 0.5, 0.5*( buffer_occ - 0.9 )/0.9 );
+ m_GOP_target = ( long int)(double(m_total_GOP_bits)*( 1.0+correction) );
}
}
- const long int min_bits = m_total_GOP_bits / (100 * m_encparams.GOPLength());
+ const long int min_bits = m_total_GOP_bits/(100*m_encparams.GOPLength());
// Allocate intra bits
- m_Iframe_bits = (long int)(m_GOP_target
- / (m_num_Iframe
- + (double)(m_num_L1frame * XL1) / XI
- + (double)(m_num_L2frame * XL2) / XI));
+ m_Iframe_bits = (long int) (m_GOP_target
+ / (m_num_Iframe
+ +(double)(m_num_L1frame*XL1)/XI
+ +(double)(m_num_L2frame*XL2)/XI));
- m_Iframe_bits = std::max(min_bits, m_Iframe_bits);
+ m_Iframe_bits = std::max( min_bits, m_Iframe_bits );
// Allocate L1 bits
- m_L1frame_bits = (long int)(m_GOP_target
- / (m_num_L1frame
- + (double)(m_num_Iframe * XI) / XL1
- + (double)(m_num_L2frame * XL2) / XL1));
+ m_L1frame_bits = (long int) (m_GOP_target
+ / (m_num_L1frame
+ +(double)(m_num_Iframe*XI)/XL1
+ +(double)(m_num_L2frame*XL2)/XL1));
- m_L1frame_bits = std::max(min_bits, m_L1frame_bits);
+ m_L1frame_bits = std::max( min_bits, m_L1frame_bits );
// Allocate L2 bits
- m_L2frame_bits = (long int)(m_GOP_target
- / (m_num_L2frame
- + (double)(m_num_Iframe * XI) / XL2
- + (double)(m_num_L1frame * XL1) / XL2));
+ m_L2frame_bits = (long int) (m_GOP_target
+ / (m_num_L2frame
+ +(double)(m_num_Iframe*XI)/XL2
+ +(double)(m_num_L1frame*XL1)/XL2));
- m_L2frame_bits = std::max(min_bits, m_L2frame_bits);
+ m_L2frame_bits = std::max( min_bits, m_L2frame_bits );
}
-float RateController::ReviewQualityFactor(const float qfac, const long int num_bits)
+float RateController::ReviewQualityFactor( const float qfac, const long int num_bits )
{
- if(num_bits > m_total_GOP_bits / 2)
+ if (num_bits>m_total_GOP_bits/2)
{
// The frame is too big, so reset to a smaller quality factor
- return ClipQualityFactor(qfac - 2);
+ return ClipQualityFactor(qfac-2);
}
else
{
// Keep the quality factor in a sensible range
- return ClipQualityFactor(qfac);
+ return ClipQualityFactor( qfac );
}
}
-float RateController::ClipQualityFactor(const float qfac)
+float RateController::ClipQualityFactor( const float qfac )
{
// Keep the quality factor in a sensible range
- if(!m_intra_only)
- return std::min(std::max(qfac, 0.0f), 16.0f);
+ if ( !m_intra_only )
+ return std::min( std::max(qfac, 0.0f), 16.0f);
else
return std::max(qfac, 0.0f);
}
void RateController::CalcNextIntraQualFactor()
{
- m_I_qf = (m_I_qf + m_qf) / 2.0;
- m_I_qf = ClipQualityFactor(m_I_qf);
+ m_I_qf = (m_I_qf + m_qf)/2.0;
+ m_I_qf = ClipQualityFactor( m_I_qf );
m_encparams.SetQf(m_I_qf);
const double ff = 0.95;
m_I_qf_long_term *= ff;
- m_I_qf_long_term += (1.0 - ff) * m_I_qf;
+ m_I_qf_long_term += ( 1.0 - ff )*m_I_qf;
}
void RateController::SetCutPictureQualFactor()
{
- m_qf = std::min(m_qf , m_I_qf_long_term);
- m_encparams.SetQf(m_qf);
+ m_qf = std::min( m_qf , m_I_qf_long_term );
+ m_encparams.SetQf( m_qf );
}
diff --git a/src/filters/parser/DiracSplitter/libdirac/libdirac_encoder/rate_control.h b/src/filters/parser/DiracSplitter/libdirac/libdirac_encoder/rate_control.h
index 7e003e736..a54bb5d95 100644
--- a/src/filters/parser/DiracSplitter/libdirac/libdirac_encoder/rate_control.h
+++ b/src/filters/parser/DiracSplitter/libdirac/libdirac_encoder/rate_control.h
@@ -49,199 +49,172 @@
namespace dirac
{
-class FrameComplexity
-{
-public:
- //! Default constructor
- FrameComplexity();
-
- //! Return the complexity of I frame
- int IComplexity()
+ class FrameComplexity
{
- return m_XI;
- }
+ public:
+ //! Default constructor
+ FrameComplexity();
- //! Return the complexity of L1 frame
- int L1Complexity()
- {
- return m_XL1;
- }
+ //! Return the complexity of I frame
+ int IComplexity() {return m_XI;}
- //! Return the complexity of L2 frame
- int L2Complexity()
- {
- return m_XL2;
- }
+ //! Return the complexity of L1 frame
+ int L1Complexity() {return m_XL1;}
- //! Set the complexity of I frame
- void SetIComplexity(int cpx)
- {
- m_XI = cpx;
- }
+ //! Return the complexity of L2 frame
+ int L2Complexity() {return m_XL2;}
- //! Set the complexity of L1 frame
- void SetL1Complexity(int cpx)
- {
- m_XL1 = cpx;
- }
+ //! Set the complexity of I frame
+ void SetIComplexity(int cpx) {m_XI = cpx;}
- //! Set the complexity of L2 frame
- void SetL2Complexity(int cpx)
- {
- m_XL2 = cpx;
- }
+ //! Set the complexity of L1 frame
+ void SetL1Complexity(int cpx) {m_XL1 = cpx;}
+ //! Set the complexity of L2 frame
+ void SetL2Complexity(int cpx) {m_XL2 = cpx;}
-private:
- //! Complexity of I frame
- int m_XI;
+ private:
- //! Complexity of L1 frame
- int m_XL1;
+ //! Complexity of I frame
+ int m_XI;
- //! Complexity of L2 frame
- int m_XL2;
-};
+ //! Complexity of L1 frame
+ int m_XL1;
+ //! Complexity of L2 frame
+ int m_XL2;
+ };
-//! A clas for allocation the bits to each and every types of frames in a GOP
-class RateController
-{
-public:
- //! Default constructor
- RateController(int trate, SourceParams& srcp, EncoderParams& encp);
+ //! A clas for allocation the bits to each and every types of frames in a GOP
+ class RateController
+ {
+ public:
+ //! Default constructor
+ RateController(int trate, SourceParams& srcp, EncoderParams& encp);
- //! Calculate the Quality factor of the next frame to encode
- void CalcNextQualFactor(const PictureParams& fparams, int num_bits);
- //! Calculate the Quality factor of the next I frame to encode
- void CalcNextIntraQualFactor();
+ //! Calculate the Quality factor of the next frame to encode
+ void CalcNextQualFactor(const PictureParams& fparams, int num_bits);
- //! Use the long-term average intra quality factor
- void SetCutPictureQualFactor();
+ //! Calculate the Quality factor of the next I frame to encode
+ void CalcNextIntraQualFactor();
- //! Return I frame qf
- double IntraQualFactor()
- {
- return m_I_qf;
- }
+ //! Use the long-term average intra quality factor
+ void SetCutPictureQualFactor();
- //! Return qf
- double QualFactor()
- {
- return m_qf;
- }
+ //! Return I frame qf
+ double IntraQualFactor() {return m_I_qf;}
- //! Report the allocation to picture types
- void Report();
+ //! Return qf
+ double QualFactor() {return m_qf;}
+
+ //! Report the allocation to picture types
+ void Report();
-private:
+ private:
- double TargetSubgroupRate();
+ double TargetSubgroupRate();
- double ProjectedSubgroupRate();
+ double ProjectedSubgroupRate();
- //! Allocate the bits to each type of frame in a GOP
- void Allocate(const int fnum);
+ //! Allocate the bits to each type of frame in a GOP
+ void Allocate(const int fnum);
- //! Calculate the total number of bits in a GOP
- void CalcTotalBits(const SourceParams& sourceparams);
+ //! Calculate the total number of bits in a GOP
+ void CalcTotalBits(const SourceParams& sourceparams);
- //! Set the value of Current IQF
- void SetIntraQualFactor(double value)
- {
- m_I_qf = value;
- }
+ //! Set the value of Current IQF
+ void SetIntraQualFactor(double value){m_I_qf = value;}
- //! Set the number of I, L1 and L2 frames in the GOP
- void SetFrameDistribution();
+ //! Set the number of I, L1 and L2 frames in the GOP
+ void SetFrameDistribution();
- //! Review the quality factor to make sure it's being set sensibly
- float ReviewQualityFactor(const float qfac, const long int num_bits);
+ //! Review the quality factor to make sure it's being set sensibly
+ float ReviewQualityFactor( const float qfac, const long int num_bits );
- //! Clip the quality factor to something sensible
- float ClipQualityFactor(const float qfac);
+ //! Clip the quality factor to something sensible
+ float ClipQualityFactor( const float qfac );
- //! Update the internal decoder buffer model
- void UpdateBuffer(const long int num_bits);
+ //! Update the internal decoder buffer model
+ void UpdateBuffer( const long int num_bits );
-private:
+ private:
- //! Current Quality Factor
- double m_qf;
+ //! Current Quality Factor
+ double m_qf;
- //! I frame Quality Factor
- double m_I_qf;
+ //! I frame Quality Factor
+ double m_I_qf;
- //! Long-term average of I frame Quality Factor
- double m_I_qf_long_term;
+ //! Long-term average of I frame Quality Factor
+ double m_I_qf_long_term;
- //! Target bit rate in kbps
- const int m_target_rate;
+ //! Target bit rate in kbps
+ const int m_target_rate;
- //! Number of bits for I frame
- long int m_Iframe_bits;
+ //! Number of bits for I frame
+ long int m_Iframe_bits;
- //! Number of bits for L1 frame
- long int m_L1frame_bits;
+ //! Number of bits for L1 frame
+ long int m_L1frame_bits;
- //! Number of bits for L2 frame
- long int m_L2frame_bits;
+ //! Number of bits for L2 frame
+ long int m_L2frame_bits;
- //! Number of I frames
- int m_num_Iframe;
+ //! Number of I frames
+ int m_num_Iframe;
- //! Number of L1 frames
- int m_num_L1frame;
+ //! Number of L1 frames
+ int m_num_L1frame;
- //! Number of L2 frames
- int m_num_L2frame;
+ //! Number of L2 frames
+ int m_num_L2frame;
- //! Total Number of bits in a GOP
- long int m_total_GOP_bits;
+ //! Total Number of bits in a GOP
+ long int m_total_GOP_bits;
- //! Mean number of bits in a picture
- long int m_picture_bits;
+ //! Mean number of bits in a picture
+ long int m_picture_bits;
- //! Size of the decoded bit buffer
- const long int m_buffer_size;
+ //! Size of the decoded bit buffer
+ const long int m_buffer_size;
- //! Number of bits in the buffer
- long int m_buffer_bits;
+ //! Number of bits in the buffer
+ long int m_buffer_bits;
- //! The old buffer occupancy
- long int m_old_buffer_bits;
+ //! The old buffer occupancy
+ long int m_old_buffer_bits;
- //! The rate of change of buffer occupancy
- double m_buffer_rate_of_change;
+ //! The rate of change of buffer occupancy
+ double m_buffer_rate_of_change;
- //! The target number of bits for the current GOP
- long int m_GOP_target;
+ //! The target number of bits for the current GOP
+ long int m_GOP_target;
- //! The duration of a GOP
- double m_GOP_duration;
+ //! The duration of a GOP
+ double m_GOP_duration;
- //! A reference to the encoder parameters
- EncoderParams& m_encparams;
+ //! A reference to the encoder parameters
+ EncoderParams& m_encparams;
- //! A class to hold the frame complexity object
- FrameComplexity m_frame_complexity;
+ //! A class to hold the frame complexity object
+ FrameComplexity m_frame_complexity;
- //! A frame counter, giving the position within a subgroup
- int m_fcount;
+ //! A frame counter, giving the position within a subgroup
+ int m_fcount;
- // Indicated whether a sequence is being coded intra only or not
- bool m_intra_only;
+ // Indicated whether a sequence is being coded intra only or not
+ bool m_intra_only;
- // Sum of complexity of L2 frames
- int m_L2_complexity_sum;
+ // Sum of complexity of L2 frames
+ int m_L2_complexity_sum;
-};
+ };
}// namespace dirac
diff --git a/src/filters/parser/DiracSplitter/libdirac/libdirac_encoder/seq_compress.cpp b/src/filters/parser/DiracSplitter/libdirac/libdirac_encoder/seq_compress.cpp
index d01c35e18..da4f73b2b 100644
--- a/src/filters/parser/DiracSplitter/libdirac/libdirac_encoder/seq_compress.cpp
+++ b/src/filters/parser/DiracSplitter/libdirac/libdirac_encoder/seq_compress.cpp
@@ -44,9 +44,9 @@
using namespace dirac;
-SequenceCompressor::SequenceCompressor(StreamPicInput* pin ,
- EncoderParams& encp,
- DiracByteStream& dirac_byte_stream):
+SequenceCompressor::SequenceCompressor( StreamPicInput* pin ,
+ EncoderParams& encp,
+ DiracByteStream& dirac_byte_stream):
m_all_done(false),
m_just_finished(true),
m_srcparams(pin->GetSourceParams()),
@@ -57,66 +57,64 @@ SequenceCompressor::SequenceCompressor(StreamPicInput* pin ,
m_encparams.Xl(),
m_encparams.Yl(),
m_encparams.LumaDepth(),
- m_encparams.ChromaDepth()),
- m_pic_in(pin),
+ m_encparams.ChromaDepth() ),
+ m_pic_in(pin),
m_current_display_pnum(-1),
m_current_code_pnum(0),
- m_show_pnum(-1), m_last_picture_read(-1),
+ m_show_pnum(-1),m_last_picture_read(-1),
m_gop_start_num(0),
m_delay(1),
- m_qmonitor(m_encparams),
- m_pcoder(m_encparams),
+ m_qmonitor( m_encparams ),
+ m_pcoder( m_encparams ),
m_dirac_byte_stream(dirac_byte_stream),
m_eos_signalled(false)
{
// Set up the compression of the sequence
//TBD: put into the constructor for EncoderParams
- m_encparams.SetEntropyFactors(new EntropyCorrector(m_encparams.TransformDepth()));
+ m_encparams.SetEntropyFactors( new EntropyCorrector(m_encparams.TransformDepth()) );
// Set up generic picture parameters
- m_pparams.SetUsingAC(m_encparams.UsingAC());
+ m_pparams.SetUsingAC(m_encparams.UsingAC() );
// Set up a rate controller if rate control being used
- if(m_encparams.TargetRate() != 0)
+ if (m_encparams.TargetRate() != 0)
m_ratecontrol = new RateController(m_encparams.TargetRate(),
m_pic_in->GetSourceParams(), encp);
// Copy in the block parameters in case we want to change them dynamically
m_basic_olb_params2 = &m_predparams.LumaBParams(2);
- m_basic_olb_params1 = new OLBParams(2 * m_predparams.LumaBParams(2).Xblen(),
- 2 * m_predparams.LumaBParams(2).Yblen(),
- 2 * m_predparams.LumaBParams(2).Xbsep(),
- 2 * m_predparams.LumaBParams(2).Ybsep());
+ m_basic_olb_params1 = new OLBParams( 2*m_predparams.LumaBParams(2).Xblen(),
+ 2*m_predparams.LumaBParams(2).Yblen(),
+ 2*m_predparams.LumaBParams(2).Xbsep(),
+ 2*m_predparams.LumaBParams(2).Ybsep() );
- m_basic_olb_params0 = new OLBParams(4 * m_predparams.LumaBParams(2).Xblen(),
- 4 * m_predparams.LumaBParams(2).Yblen(),
- 4 * m_predparams.LumaBParams(2).Xbsep(),
- 4 * m_predparams.LumaBParams(2).Ybsep());
+ m_basic_olb_params0 = new OLBParams( 4*m_predparams.LumaBParams(2).Xblen(),
+ 4*m_predparams.LumaBParams(2).Yblen(),
+ 4*m_predparams.LumaBParams(2).Xbsep(),
+ 4*m_predparams.LumaBParams(2).Ybsep() );
- m_intra_olbp = new OLBParams(2 * m_basic_olb_params2->Xbsep() ,
- 2 * m_basic_olb_params2->Ybsep() ,
- m_basic_olb_params2->Xbsep() ,
- m_basic_olb_params2->Ybsep());
+ m_intra_olbp = new OLBParams( 2*m_basic_olb_params2->Xbsep() ,
+ 2*m_basic_olb_params2->Ybsep() ,
+ m_basic_olb_params2->Xbsep() ,
+ m_basic_olb_params2->Ybsep() );
SetMotionParameters();
}
-void SequenceCompressor::SetMotionParameters()
-{
+void SequenceCompressor::SetMotionParameters(){
- if(m_encparams.TargetRate() != 0)
- {
+ if ( m_encparams.TargetRate() != 0 ){
OLBParams new_olb_params = *m_basic_olb_params2;
- if(m_encparams.Qf() < 2.5)
+ if (m_encparams.Qf()<2.5)
new_olb_params = *m_basic_olb_params1;
- else if(m_encparams.Qf() < 1.5)
+ else if (m_encparams.Qf()<1.5)
new_olb_params = *m_basic_olb_params0;
- m_predparams.SetBlockSizes(new_olb_params , m_srcparams.CFormat());
+ m_predparams.SetBlockSizes( new_olb_params , m_srcparams.CFormat() );
}
@@ -124,13 +122,13 @@ void SequenceCompressor::SetMotionParameters()
int yl = m_encparams.Yl();
// Make sure we have enough macroblocks to cover the pictures
- m_predparams.SetXNumSB((xl + m_predparams.LumaBParams(0).Xbsep() - 1) /
- m_predparams.LumaBParams(0).Xbsep());
- m_predparams.SetYNumSB((yl + m_predparams.LumaBParams(0).Ybsep() - 1) /
- m_predparams.LumaBParams(0).Ybsep());
+ m_predparams.SetXNumSB( (xl+m_predparams.LumaBParams(0).Xbsep()-1)/
+ m_predparams.LumaBParams(0).Xbsep() );
+ m_predparams.SetYNumSB( (yl+m_predparams.LumaBParams(0).Ybsep()-1)/
+ m_predparams.LumaBParams(0).Ybsep() );
- m_predparams.SetXNumBlocks(4 * m_predparams.XNumSB());
- m_predparams.SetYNumBlocks(4 * m_predparams.YNumSB());
+ m_predparams.SetXNumBlocks( 4 * m_predparams.XNumSB() );
+ m_predparams.SetYNumBlocks( 4 * m_predparams.YNumSB() );
}
@@ -140,54 +138,54 @@ SequenceCompressor::~SequenceCompressor()
delete m_basic_olb_params1;
delete m_basic_olb_params0;
- if(m_encparams.Verbose())
+ if ( m_encparams.Verbose())
MakeSequenceReport();
//TBD: put into the destructor for EncoderParams
delete &m_encparams.EntropyFactors();
- if(m_encparams.TargetRate() != 0)
+ if (m_encparams.TargetRate()!=0)
delete m_ratecontrol;
}
bool SequenceCompressor::CanEncode()
{
- const int queue_size = std::max(4 , 2 * m_encparams.L1Sep());
+ const int queue_size = std::max( 4 , 2*m_encparams.L1Sep() );
- if(m_eos_signalled)
+ if (m_eos_signalled)
{
- if(m_encparams.NumL1() > 0)
+ if (m_encparams.NumL1() > 0)
{
- /*
- * Long-GOP sequence
- */
+ /*
+ * Long-GOP sequence
+ */
int field_factor = m_encparams.PictureCodingMode() ? 2 : 1;
- int last_frame_read = m_last_picture_read / field_factor;
- int current_code_fnum = m_current_code_pnum / field_factor;
+ int last_frame_read = m_last_picture_read/field_factor;
+ int current_code_fnum = m_current_code_pnum/field_factor;
- if((last_frame_read >= (current_code_fnum + (last_frame_read % m_encparams.L1Sep()))))
+ if ((last_frame_read >= (current_code_fnum + (last_frame_read%m_encparams.L1Sep()))))
return true;
- /*
- * Encode the remaining picture in the frame buffer. We check if
- * the reference pictures are available and modify the picture sort
- * accordingly.
- */
- if(current_code_fnum <= last_frame_read)
- {
- m_current_display_pnum = m_current_code_pnum;
- return true;
- }
+ /*
+ * Encode the remaining picture in the frame buffer. We check if
+ * the reference pictures are available and modify the picture sort
+ * accordingly.
+ */
+ if (current_code_fnum <= last_frame_read)
+ {
+ m_current_display_pnum = m_current_code_pnum;
+ return true;
+ }
}
else
{
- if(m_last_picture_read >= m_current_display_pnum)
+ if (m_last_picture_read >= m_current_display_pnum)
return true;
}
}
else
{
- if(m_last_picture_read >= m_current_display_pnum + queue_size)
+ if (m_last_picture_read >= m_current_display_pnum + queue_size)
return true;
}
return false;
@@ -209,21 +207,20 @@ const EncPicture* SequenceCompressor::CompressNextPicture()
// m_show_pnum is the index of the picture number that can be shown when current_pnum has been coded.
// Var m_delay is the m_delay caused by reordering (as distinct from buffering)
- TESTM(m_last_picture_read >= 0, "Data loaded before calling CompressNextPicture");
+ TESTM (m_last_picture_read >= 0, "Data loaded before calling CompressNextPicture");
const int field_factor = m_encparams.FieldCoding() ? 2 : 1;
// If we have a scheduled P picture, reset the P separation to normal
- if(m_encparams.L1Sep() != m_L1_sep)
- {
- if((m_current_code_pnum - field_factor) % (m_encparams.L1Sep()*field_factor) == 0)
+ if ( m_encparams.L1Sep()!=m_L1_sep ){
+ if ( (m_current_code_pnum-field_factor) % (m_encparams.L1Sep()*field_factor)==0 )
m_L1_sep = m_encparams.L1Sep();
}
- m_current_display_pnum = CodedToDisplay(m_current_code_pnum);
- m_show_pnum = std::max(m_current_code_pnum - m_delay , 0);
+ m_current_display_pnum = CodedToDisplay( m_current_code_pnum );
+ m_show_pnum = std::max( m_current_code_pnum - m_delay , 0 );
- if(CanEncode())
+ if ( CanEncode() )
{
// Compress the picture//
@@ -231,58 +228,50 @@ const EncPicture* SequenceCompressor::CompressNextPicture()
const std::vector<int>& queue_members = m_enc_pbuffer.Members();
- EncPicture* current_pic = &m_enc_pbuffer.GetPicture(m_current_display_pnum);
+ EncPicture* current_pic = &m_enc_pbuffer.GetPicture( m_current_display_pnum );
PictureParams* current_pp = &current_pic->GetPparams();
// 1. Set the picture type and refs for all the pictures in the queue not already encoded
- for(size_t i = 0; i < queue_members.size(); ++i)
- {
+ for (size_t i=0; i<queue_members.size(); ++i){
int pnum = queue_members[i];
EncPicture& enc_pic = m_enc_pbuffer.GetPicture(pnum);
- if((enc_pic.GetStatus() & DONE_SET_PTYPE) == 0)
- {
+ if ( (enc_pic.GetStatus() & DONE_SET_PTYPE) == 0 ){
PictureParams& pparams = enc_pic.GetPparams();
// only look one subgroup ahead
- if((m_encparams.NumL1() == 0) || pparams.PictureNum() < m_current_display_pnum + m_encparams.L1Sep())
- {
- SetPicTypeAndRefs(pparams);
- enc_pic.UpdateStatus(DONE_SET_PTYPE);
+ if ((m_encparams.NumL1() == 0) || pparams.PictureNum() < m_current_display_pnum + m_encparams.L1Sep() ){
+ SetPicTypeAndRefs( pparams );
+ enc_pic.UpdateStatus( DONE_SET_PTYPE );
}
}
}
/* Do motion estimation and compensation if inter*/
- bool is_a_cut(false);
+ bool is_a_cut( false );
//2. Set up block sizes etc
SetMotionParameters();
// Loop over the whole queue and ...
- for(size_t i = 0; i < queue_members.size(); ++i)
- {
+ for (size_t i=0; i<queue_members.size(); ++i){
int pnum = queue_members[i];
EncPicture& enc_pic = m_enc_pbuffer.GetPicture(pnum);
- if((enc_pic.GetStatus() & DONE_SET_PTYPE) != 0)
- {
+ if ( ( enc_pic.GetStatus() & DONE_SET_PTYPE) != 0 ){
PictureParams& pparams = enc_pic.GetPparams();
- if(pparams.PicSort().IsInter())
- {
- // 3.Initialise motion data
- if((enc_pic.GetStatus() & DONE_ME_INIT) == 0)
- {
- enc_pic.InitMEData(m_predparams , pparams.NumRefs());
- enc_pic.UpdateStatus(DONE_ME_INIT);
+ if ( pparams.PicSort().IsInter() ){
+ // 3.Initialise motion data
+ if ( ( enc_pic.GetStatus() & DONE_ME_INIT) == 0 ){
+ enc_pic.InitMEData( m_predparams , pparams.NumRefs() );
+ enc_pic.UpdateStatus( DONE_ME_INIT );
}
// 4. Do pixel-accurate motion estimation
- if((enc_pic.GetStatus() & DONE_PEL_ME) == 0)
- {
- m_pcoder.PixelME(m_enc_pbuffer, pnum);
- enc_pic.UpdateStatus(DONE_PEL_ME);
- }
+ if ( ( enc_pic.GetStatus() & DONE_PEL_ME) == 0 ){
+ m_pcoder.PixelME( m_enc_pbuffer, pnum );
+ enc_pic.UpdateStatus( DONE_PEL_ME );
+ }
// // 5. Set picture complexity
// if ( (enc_pic.GetStatus() & DONE_PIC_COMPLEXITY ) == 0 ){
@@ -290,7 +279,7 @@ const EncPicture* SequenceCompressor::CompressNextPicture()
// enc_pic.UpdateStatus( DONE_PIC_COMPLEXITY );
// }
- //6. Revise the number of references if one ref is a bad predictor
+ //6. Revise the number of references if one ref is a bad predictor
// if ( (enc_pic.GetStatus() & DONE_PIC_COMPLEXITY)!=0 &&
// pparams.NumRefs()==2){
// if (enc_pic.GetPredBias()>0.8)
@@ -302,165 +291,155 @@ const EncPicture* SequenceCompressor::CompressNextPicture()
}
}
- if(current_pp->PicSort().IsInter())
- {
+ if ( current_pp->PicSort().IsInter() ){
// // 7. Normalise complexity for the current picture
// m_pcoder.NormaliseComplexity( m_enc_pbuffer, m_current_display_pnum );
bool subgroup_reconfig;
- do
- {
+ do{
subgroup_reconfig = false;
//8. Do subpel refinement
- m_pcoder.SubPixelME(m_enc_pbuffer, m_current_display_pnum);
+ m_pcoder.SubPixelME( m_enc_pbuffer, m_current_display_pnum );
//9. Do mode decision
- m_pcoder.ModeDecisionME(m_enc_pbuffer, m_current_display_pnum);
+ m_pcoder.ModeDecisionME( m_enc_pbuffer, m_current_display_pnum );
//10. Work out how many blocks are intra
- m_pcoder.IntraModeAnalyse(m_enc_pbuffer, m_current_display_pnum);
+ m_pcoder.IntraModeAnalyse( m_enc_pbuffer, m_current_display_pnum );
//11. Change the GOP structure to PPP if there are too many intras
- if(m_L1_sep > 1 && current_pic->GetMEData().IntraBlockRatio() > 0.25
- && (m_current_display_pnum % (m_encparams.L1Sep()*field_factor)) == 0)
- {
+ if ( m_L1_sep>1 && current_pic->GetMEData().IntraBlockRatio()>0.25
+ && (m_current_display_pnum % (m_encparams.L1Sep()*field_factor))==0){
subgroup_reconfig = true;
m_L1_sep = 1;
- for(int i = 0; i < field_factor * m_encparams.L1Sep(); ++i)
- {
+ for (int i = 0; i<field_factor*m_encparams.L1Sep(); ++i){
- int pnum = m_current_display_pnum - i + (field_factor - 1);
+ int pnum = m_current_display_pnum-i+(field_factor-1);
EncPicture& enc_pic = m_enc_pbuffer.GetPicture(pnum);
PictureParams& pparams = enc_pic.GetPparams();
- SetPicTypeAndRefs(pparams);
- enc_pic.UpdateStatus(DONE_SET_PTYPE);
+ SetPicTypeAndRefs( pparams );
+ enc_pic.UpdateStatus( DONE_SET_PTYPE );
}
- current_pic->SetStatus(DONE_SET_PTYPE);
+ current_pic->SetStatus( DONE_SET_PTYPE );
// Current picture to code has now changed: recalculate
- m_current_display_pnum = CodedToDisplay(m_current_code_pnum);
- current_pic = &m_enc_pbuffer.GetPicture(m_current_display_pnum);
+ m_current_display_pnum = CodedToDisplay( m_current_code_pnum );
+ current_pic = &m_enc_pbuffer.GetPicture(m_current_display_pnum );
current_pp = &current_pic->GetPparams();
}
- }
- while(subgroup_reconfig == true);
+ }while(subgroup_reconfig==true);
//11. Do cut detection and insert intra pictures
- if(current_pic->GetMEData().IntraBlockRatio() > 0.3333)
- {
+ if ( current_pic->GetMEData().IntraBlockRatio()>0.3333 ){
is_a_cut = true;
- if(m_encparams.L1Sep() > 1 &&
- (m_current_display_pnum % (field_factor * m_encparams.L1Sep())) == 0)
- {
+ if ( m_encparams.L1Sep()>1 &&
+ (m_current_display_pnum % (field_factor*m_encparams.L1Sep())) == 0){
m_gop_start_num = current_pp->PictureNum();//restart the GOP
}
- if(current_pp->PicSort().IsRef()) // Set the picture type to intra
- current_pic->SetPictureSort(PictureSort::IntraRefPictureSort());
+ if ( current_pp->PicSort().IsRef() ) // Set the picture type to intra
+ current_pic->SetPictureSort (PictureSort::IntraRefPictureSort());
else
- current_pic->SetPictureSort(PictureSort::IntraNonRefPictureSort());
+ current_pic->SetPictureSort (PictureSort::IntraNonRefPictureSort());
- if(m_encparams.Verbose())
- std::cout << std::endl << "Cut detected and I-picture inserted!";
+ if ( m_encparams.Verbose() )
+ std::cout<<std::endl<<"Cut detected and I-picture inserted!";
}
- else
- {
- //12. Do motion compensation if not a cut
+ else{
+ //12. Do motion compensation if not a cut
// MEData& me_data = current_pic->GetMEData();
//
// if (me_data.IntraBlockRatio()>0.1)//FIXME: this is broken with adaptive block sizes
// m_predparams.SetBlockSizes(*m_intra_olbp, m_srcparams.CFormat() );
- m_pcoder.MotionCompensate(m_enc_pbuffer, m_current_display_pnum, SUBTRACT);
- current_pic->UpdateStatus(DONE_MC);
+ m_pcoder.MotionCompensate(m_enc_pbuffer, m_current_display_pnum, SUBTRACT );
+ current_pic->UpdateStatus( DONE_MC );
}
}
- if(current_pp->PicSort().IsRef() == true)
- m_enc_pbuffer.SetRetiredPictureNum(m_show_pnum, m_current_display_pnum);
+ if ( current_pp->PicSort().IsRef()==true )
+ m_enc_pbuffer.SetRetiredPictureNum( m_show_pnum, m_current_display_pnum );
// 12. Now code the residual data and motion data
- if(m_encparams.TargetRate() != 0)
- UpdateIntraPicCBRModel(*current_pp, is_a_cut);
+ if (m_encparams.TargetRate() != 0)
+ UpdateIntraPicCBRModel( *current_pp, is_a_cut );
// 13. Write a sequence header if necessary
- if((m_encparams.NumL1() > 0 && current_pp->PicSort().IsRef() == true &&
- current_pp->PicSort().IsIntra() == true && (m_current_display_pnum % m_encparams.L1Sep() == 0)) ||
- (m_encparams.NumL1() == 0 && (m_current_display_pnum % m_encparams.GOPLength()) == 0))
+ if( (m_encparams.NumL1() > 0 && current_pp->PicSort().IsRef()==true &&
+ current_pp->PicSort().IsIntra()==true && (m_current_display_pnum % m_encparams.L1Sep() == 0)) ||
+ (m_encparams.NumL1() == 0 && (m_current_display_pnum % m_encparams.GOPLength())==0))
{
- if(m_encparams.Verbose())
+ if (m_encparams.Verbose())
{
- std::cout << std::endl << std::endl << "GOP start: writing sequence header before picture ";
- std::cout << m_current_display_pnum;
+ std::cout<<std::endl<<std::endl<<"GOP start: writing sequence header before picture ";
+ std::cout<<m_current_display_pnum;
}
SequenceHeaderByteIO *p_seqheader_byteio = new SequenceHeaderByteIO
- (m_pic_in->GetSourceParams(),
- m_encparams);
+ ( m_pic_in->GetSourceParams(),
+ m_encparams);
p_seqheader_byteio->Output();
m_dirac_byte_stream.AddSequenceHeader(p_seqheader_byteio);
}
// 13. Write the picture header.
- PictureByteIO* p_picture_byteio = new PictureByteIO(*current_pp, m_current_display_pnum);
+ PictureByteIO* p_picture_byteio = new PictureByteIO(*current_pp, m_current_display_pnum );
p_picture_byteio->Output();
- if(m_encparams.Verbose())
- {
- if(m_encparams.TargetRate() != 0)
+ if ( m_encparams.Verbose() ){
+ if (m_encparams.TargetRate()!=0 )
m_ratecontrol->Report();
- if(m_encparams.FieldCoding())
- std::cout << std::endl << std::endl << "Compressing field " << m_current_code_pnum << ", ";
+ if (m_encparams.FieldCoding())
+ std::cout<<std::endl<<std::endl<<"Compressing field "<<m_current_code_pnum<<", ";
else
- std::cout << std::endl << std::endl << "Compressing frame " << m_current_code_pnum << ", ";
- std::cout << m_current_display_pnum << " in display order";
-
- if(is_a_cut == true || current_pp->PicSort().IsIntra() == false)
- std::cout << std::endl << current_pic->GetMEData().IntraBlockRatio() * 100.0 << "% of blocks are intra ";
- if(is_a_cut == true)
- std::cout << std::endl << "Cut detected and intra picture inserted.";
-
- std::cout << std::endl << "Picture type is ";
- if(current_pp->PicSort().IsRef())
- std::cout << "REF";
- else std::cout << "NON-REF";
-
- std::cout << " , ";
- if(current_pp->PicSort().IsIntra())
- std::cout << "INTRA";
- else std::cout << "INTER";
-
- if(current_pp->PicSort().IsInter())
- {
- std::cout << std::endl << "References "
- << (m_encparams.FieldCoding() ? "field " : "frame ")
- << current_pp->Refs()[0];
- if(current_pp->Refs().size() > 1)
- std::cout << " and " << current_pp->Refs()[1];
+ std::cout<<std::endl<<std::endl<<"Compressing frame "<<m_current_code_pnum<<", ";
+ std::cout<<m_current_display_pnum<<" in display order";
+
+ if (is_a_cut==true || current_pp->PicSort().IsIntra()==false )
+ std::cout<<std::endl<<current_pic->GetMEData().IntraBlockRatio()*100.0<<"% of blocks are intra ";
+ if (is_a_cut==true)
+ std::cout<<std::endl<<"Cut detected and intra picture inserted.";
+
+ std::cout<<std::endl<<"Picture type is ";
+ if (current_pp->PicSort().IsRef() )
+ std::cout<<"REF";
+ else std::cout<<"NON-REF";
+
+ std::cout<<" , ";
+ if (current_pp->PicSort().IsIntra())
+ std::cout<<"INTRA";
+ else std::cout<<"INTER";
+
+ if ( current_pp->PicSort().IsInter() ){
+ std::cout<<std::endl<<"References "
+ << (m_encparams.FieldCoding() ? "field " : "frame ")
+ << current_pp->Refs()[0];
+ if (current_pp->Refs().size() > 1)
+ std::cout<<" and "<< current_pp->Refs()[1];
}
}
// 14. Code the motion vectors
- if(current_pp->PicSort().IsInter())
+ if ( current_pp->PicSort().IsInter() )
m_pcoder.CodeMVData(m_enc_pbuffer , m_current_display_pnum, p_picture_byteio);
// 15. Do prefiltering on the residue if necessary
- if(m_encparams.Prefilter() != NO_PF)
- m_pcoder.Prefilter(m_enc_pbuffer, m_current_display_pnum);
+ if (m_encparams.Prefilter() != NO_PF )
+ m_pcoder.Prefilter( m_enc_pbuffer, m_current_display_pnum );
// 16. Do the transform on the 3 components
- m_pcoder.DoDWT(m_enc_pbuffer, m_current_display_pnum , FORWARD);
+ m_pcoder.DoDWT( m_enc_pbuffer, m_current_display_pnum , FORWARD);
// 17. Select the quantisers
@@ -474,46 +453,44 @@ const EncPicture* SequenceCompressor::CompressNextPicture()
m_dirac_byte_stream.AddPicture(p_picture_byteio);
// 19. Do the inverse DWT if necessary
- m_pcoder.DoDWT(m_enc_pbuffer, m_current_display_pnum , BACKWARD);
+ m_pcoder.DoDWT( m_enc_pbuffer, m_current_display_pnum , BACKWARD);
// 20. Motion compensate back if necessary
- if(psort.IsInter() && !is_a_cut)
- m_pcoder.MotionCompensate(m_enc_pbuffer, m_current_display_pnum, ADD);
+ if (psort.IsInter() && !is_a_cut )
+ m_pcoder.MotionCompensate(m_enc_pbuffer, m_current_display_pnum, ADD );
// Reset block sizes for next picture
- m_predparams.SetBlockSizes(*m_basic_olb_params2, m_srcparams.CFormat());
+ m_predparams.SetBlockSizes(*m_basic_olb_params2, m_srcparams.CFormat() );
// 21. Clip the data to keep it in range
current_pic->Clip();
// Use the results of encoding to update the CBR model
- if(m_encparams.TargetRate() != 0)
- UpdateCBRModel(*current_pic, p_picture_byteio);
+ if (m_encparams.TargetRate() != 0 )
+ UpdateCBRModel(*current_pic, p_picture_byteio);
// 22. Measure the encoded picture quality
- if(m_encparams.LocalDecode())
- m_qmonitor.UpdateModel(*current_pic);
+ if ( m_encparams.LocalDecode() )
+ m_qmonitor.UpdateModel( *current_pic );
// Increment our position
m_current_code_pnum++;
CleanBuffers();
- current_pic->SetStatus(ALL_ENC);
+ current_pic->SetStatus( ALL_ENC );
}
// Return the latest picture that can be shown
- if(m_enc_pbuffer.GetPicture(m_show_pnum).GetStatus() == ALL_ENC)
- {
- if(m_encparams.Verbose())
- {
- std::cout << std::endl << "Return " <<
- (m_encparams.FieldCoding() ? "field " : "frame ") <<
- m_show_pnum << " in display order";
+ if ( m_enc_pbuffer.GetPicture(m_show_pnum).GetStatus() == ALL_ENC ){
+ if ( m_encparams.Verbose() ){
+ std::cout<<std::endl<<"Return " <<
+ (m_encparams.FieldCoding() ? "field " : "frame ") <<
+ m_show_pnum << " in display order";
}
- return &m_enc_pbuffer.GetPicture(m_show_pnum);
+ return &m_enc_pbuffer.GetPicture(m_show_pnum );
}
else
return NULL;
@@ -524,14 +501,14 @@ const EncPicture* SequenceCompressor::CompressNextPicture()
void SequenceCompressor::CleanBuffers()
{
// If we're not at the beginning, clean the buffer
- if(m_current_code_pnum != 0)
- m_enc_pbuffer.CleanRetired(m_show_pnum, m_current_display_pnum);
+ if ( m_current_code_pnum != 0 )
+ m_enc_pbuffer.CleanRetired( m_show_pnum, m_current_display_pnum );
}
const EncPicture *SequenceCompressor::GetPictureEncoded()
{
- if(m_current_display_pnum >= 0)
- return &m_enc_pbuffer.GetPicture(m_current_display_pnum);
+ if (m_current_display_pnum >= 0)
+ return &m_enc_pbuffer.GetPicture( m_current_display_pnum );
return 0;
}
@@ -540,9 +517,9 @@ DiracByteStats SequenceCompressor::EndSequence()
{
DiracByteStats seq_stats;
- if(m_just_finished)
+ if (m_just_finished)
{
- seq_stats = m_dirac_byte_stream.EndSequence();
+ seq_stats=m_dirac_byte_stream.EndSequence();
m_just_finished = false;
m_all_done = true;
}
@@ -554,23 +531,21 @@ DiracByteStats SequenceCompressor::EndSequence()
void SequenceCompressor::MakeSequenceReport()
{
- if(m_encparams.LocalDecode())
+ if ( m_encparams.LocalDecode() )
m_qmonitor.WriteLog();
- std::cout << std::endl;
+ std::cout<<std::endl;
}
-void SequenceCompressor::UpdateIntraPicCBRModel(const PictureParams& pparams, const bool is_a_cut)
-{
+void SequenceCompressor::UpdateIntraPicCBRModel( const PictureParams& pparams, const bool is_a_cut ){
// For intra pictures we want to update before coding
// especially if they're inserted
- if(pparams.PicSort().IsIntra() && m_current_display_pnum > 0 &&
- m_encparams.NumL1() != 0)
- {
+ if ( pparams.PicSort().IsIntra() && m_current_display_pnum > 0 &&
+ m_encparams.NumL1() != 0){
// Calculate the new QF for encoding the following I picture
- if(is_a_cut)
+ if ( is_a_cut )
m_ratecontrol->SetCutPictureQualFactor();
else
m_ratecontrol->CalcNextIntraQualFactor();
@@ -578,14 +553,14 @@ void SequenceCompressor::UpdateIntraPicCBRModel(const PictureParams& pparams, co
}
FrameSequenceCompressor::FrameSequenceCompressor(
- StreamPicInput* pin ,
- EncoderParams& encp,
- DiracByteStream& dirac_byte_stream):
+ StreamPicInput* pin ,
+ EncoderParams& encp,
+ DiracByteStream& dirac_byte_stream):
SequenceCompressor(pin, encp, dirac_byte_stream)
{
}
-void FrameSequenceCompressor::SetPicTypeAndRefs(PictureParams& pparams)
+void FrameSequenceCompressor::SetPicTypeAndRefs( PictureParams& pparams )
{
// Set the temporal prediction parameters for frame coding
@@ -594,94 +569,88 @@ void FrameSequenceCompressor::SetPicTypeAndRefs(PictureParams& pparams)
const int gop_len = m_encparams.GOPLength();
const int num_L1 = m_encparams.NumL1();
- pparams.SetRetiredPictureNum(-1);
+ pparams.SetRetiredPictureNum( -1 );
pparams.Refs().clear();
- if(num_L1 > 0)
- {
+ if ( num_L1>0 ){
- if(rel_pnum % gop_len == 0)
- {
- if(gop_len > 1)
- pparams.SetPicSort(PictureSort::IntraRefPictureSort());
+ if ( rel_pnum % gop_len == 0){
+ if (gop_len > 1)
+ pparams.SetPicSort( PictureSort::IntraRefPictureSort());
else // I-picture only coding
- pparams.SetPicSort(PictureSort::IntraNonRefPictureSort());
+ pparams.SetPicSort( PictureSort::IntraNonRefPictureSort());
// I picture expires after we've coded the next I picture
- pparams.SetExpiryTime(2 * m_L1_sep);
+ pparams.SetExpiryTime( 2*m_L1_sep );
}
- else if(rel_pnum % m_L1_sep == 0)
- {
- pparams.SetPicSort(PictureSort::InterRefPictureSort());
+ else if (rel_pnum % m_L1_sep == 0){
+ pparams.SetPicSort( PictureSort::InterRefPictureSort());
// Ref the previous I or L1 picture
- pparams.Refs().push_back(pnum - m_L1_sep);
+ pparams.Refs().push_back( pnum - m_L1_sep );
// if we don't have the first L1 picture ...
- if(((rel_pnum - m_L1_sep) % gop_len > 0) && m_L1_sep > 1)
+ if ( ((rel_pnum-m_L1_sep) % gop_len>0) && m_L1_sep>1)
// ... other ref is the prior I/L1 picture but one
- pparams.Refs().push_back(pnum - 2 * m_L1_sep);
+ pparams.Refs().push_back( pnum - 2*m_L1_sep );
// Expires after the next L1 or I picture
- pparams.SetExpiryTime(2 * m_L1_sep);
- if(rel_pnum % m_encparams.L1Sep() == 0)
- pparams.SetExpiryTime(2 * m_encparams.L1Sep());
+ pparams.SetExpiryTime( 2*m_L1_sep );
+ if (rel_pnum % m_encparams.L1Sep() == 0 )
+ pparams.SetExpiryTime(2*m_encparams.L1Sep());
}
- else if((rel_pnum + 1) % m_L1_sep == 0)
- {
- pparams.SetPicSort(PictureSort::InterNonRefPictureSort());
+ else if ((rel_pnum+1) % m_L1_sep == 0){
+ pparams.SetPicSort( PictureSort::InterNonRefPictureSort());
// .. and the previous picture
- pparams.Refs().push_back(pnum - 1);
+ pparams.Refs().push_back(pnum-1);
// Refs are the next I or L1 picture ...
- if(m_enc_pbuffer.IsPictureAvail(pnum + 1))
- pparams.Refs().push_back(pnum + 1);
+ if (m_enc_pbuffer.IsPictureAvail(pnum+1))
+ pparams.Refs().push_back(pnum+1);
- pparams.SetExpiryTime(1);
+ pparams.SetExpiryTime( 1 );
}
- else
- {
- pparams.SetPicSort(PictureSort::InterRefPictureSort());
+ else{
+ pparams.SetPicSort( PictureSort::InterRefPictureSort());
// .. and the previous picture
- pparams.Refs().push_back(pnum - 1);
+ pparams.Refs().push_back(pnum-1);
// Refs are the next I or L1 picture ...
- int next_ref = ((pnum / m_L1_sep) + 1) * m_L1_sep;
- if(m_enc_pbuffer.IsPictureAvail(next_ref))
+ int next_ref = ((pnum/m_L1_sep)+1)*m_L1_sep;
+ if (m_enc_pbuffer.IsPictureAvail(next_ref))
pparams.Refs().push_back(next_ref);
- pparams.SetExpiryTime(2);
+ pparams.SetExpiryTime( 2 );
}
}
- else
- {
- pparams.SetPicSort(PictureSort::IntraNonRefPictureSort());
- pparams.SetExpiryTime(1);
+ else{
+ pparams.SetPicSort( PictureSort::IntraNonRefPictureSort());
+ pparams.SetExpiryTime( 1 );
}
}
bool FrameSequenceCompressor::LoadNextFrame()
{
- PictureParams pp(m_pparams);
- pp.SetPictureNum(m_last_picture_read + 1);
+ PictureParams pp( m_pparams );
+ pp.SetPictureNum( m_last_picture_read+1 );
// Set an initially huge expiry time as we don't know when it will expire yet
- pp.SetExpiryTime(1 << 30);
+ pp.SetExpiryTime(1<<30);
- m_enc_pbuffer.PushPicture(pp);
+ m_enc_pbuffer.PushPicture( pp );
- m_pic_in->ReadNextPicture(m_enc_pbuffer.GetPicture(m_last_picture_read + 1));
+ m_pic_in->ReadNextPicture( m_enc_pbuffer.GetPicture(m_last_picture_read+1) );
// Copy into the original data
- m_enc_pbuffer.GetPicture(m_last_picture_read + 1).SetOrigData();
+ m_enc_pbuffer.GetPicture(m_last_picture_read+1).SetOrigData();
- if(m_encparams.Prefilter() == CWM)
- CWMFilter(m_enc_pbuffer.GetPicture(m_last_picture_read + 1) ,
- m_encparams.PrefilterStrength());
+ if ( m_encparams.Prefilter()==CWM )
+ CWMFilter(m_enc_pbuffer.GetPicture( m_last_picture_read+1 ) ,
+ m_encparams.PrefilterStrength() );
- if(m_pic_in->End())
+ if ( m_pic_in->End() )
{
m_all_done = true;
return false;
@@ -692,45 +661,43 @@ bool FrameSequenceCompressor::LoadNextFrame()
return true;
}
-int FrameSequenceCompressor::CodedToDisplay(const int cnum)
+int FrameSequenceCompressor::CodedToDisplay( const int cnum )
{
int div;
- if(m_L1_sep > 0)
+ if (m_L1_sep>0)
{
// We have L1 and L2 pictures
- if(cnum == 0)
+ if (cnum==0)
return 0;
- else if((cnum - 1) % m_L1_sep == 0)
- {
- //we have L1 or subsequent I pictures
- div = (cnum - 1) / m_L1_sep;
- return cnum + m_L1_sep - 1;
+ else if ((cnum-1)% m_L1_sep==0)
+ {//we have L1 or subsequent I pictures
+ div=(cnum-1)/m_L1_sep;
+ return cnum+m_L1_sep-1;
}
else//we have L2 pictures
- return cnum - 1;
+ return cnum-1;
}
else
- {
- //we just have I-pictures, so no re-ordering
+ {//we just have I-pictures, so no re-ordering
return cnum;
}
}
void FrameSequenceCompressor::UpdateCBRModel(EncPicture& my_frame,
- const PictureByteIO* p_picture_byteio)
+ const PictureByteIO* p_picture_byteio)
{
// Update the quality factor
- m_ratecontrol->CalcNextQualFactor(my_frame.GetPparams(), p_picture_byteio->GetSize() * 8);
+ m_ratecontrol->CalcNextQualFactor(my_frame.GetPparams(), p_picture_byteio->GetSize()*8);
}
FieldSequenceCompressor::FieldSequenceCompressor(
- StreamPicInput* pin ,
- EncoderParams& encp,
- DiracByteStream& dirac_byte_stream):
+ StreamPicInput* pin ,
+ EncoderParams& encp,
+ DiracByteStream& dirac_byte_stream):
SequenceCompressor(pin, encp, dirac_byte_stream)
{
m_delay = 2;
@@ -738,37 +705,34 @@ FieldSequenceCompressor::FieldSequenceCompressor(
bool FieldSequenceCompressor::LoadNextFrame()
{
- PictureParams pp(m_pparams);
- pp.SetExpiryTime(1 << 30);
+ PictureParams pp( m_pparams );
+ pp.SetExpiryTime( 1<<30 );
- int pnum = m_last_picture_read + 1;
+ int pnum = m_last_picture_read+1;
- for(int j = pnum; j <= pnum + 1; ++j)
- {
- pp.SetPictureNum(j);
- m_enc_pbuffer.PushPicture(pp);
+ for (int j=pnum; j<=pnum+1; ++j){
+ pp.SetPictureNum( j );
+ m_enc_pbuffer.PushPicture( pp );
}
StreamFieldInput* field_input = (StreamFieldInput*) m_pic_in;
- field_input->ReadNextFrame(m_enc_pbuffer.GetPicture(pnum), m_enc_pbuffer.GetPicture(pnum + 1));
+ field_input->ReadNextFrame( m_enc_pbuffer.GetPicture( pnum ), m_enc_pbuffer.GetPicture(pnum+1) );
// Copy data across
- for(int j = pnum; j <= pnum + 1; ++j)
- {
- m_enc_pbuffer.GetPicture(j).SetOrigData();
+ for (int j=pnum; j<=pnum+1; ++j){
+ m_enc_pbuffer.GetPicture( j ).SetOrigData();
- if(m_encparams.Prefilter() == CWM)
- CWMFilter(m_enc_pbuffer.GetPicture(j), m_encparams.PrefilterStrength());
+ if ( m_encparams.Prefilter()==CWM )
+ CWMFilter(m_enc_pbuffer.GetPicture( j ), m_encparams.PrefilterStrength() );
}
- if(m_pic_in->End())
- {
+ if ( m_pic_in->End() ){
m_all_done = true;
return false;
}
- m_last_picture_read += 2;
+ m_last_picture_read +=2;
return true;
}
@@ -776,124 +740,113 @@ bool FieldSequenceCompressor::LoadNextFrame()
void FieldSequenceCompressor::PreMotionEstmationFilter(PicArray& comp)
{
//Special case for first row
- for(int i = comp.FirstX(); i <= comp.LastX(); ++i)
+ for (int i = comp.FirstX(); i <= comp.LastX(); ++i)
{
- comp[comp.FirstY()][i] = (3 * comp[comp.FirstY()][i] +
- comp[comp.FirstY()+1][i] + 2) >> 2;
+ comp[comp.FirstY()][i] = (3*comp[comp.FirstY()][i] +
+ comp[comp.FirstY()+1][i] +2 )>>2;
}
//Middle section
- for(int j = comp.FirstY() + 1; j < comp.LastY(); ++j)
+ for (int j = comp.FirstY()+1; j < comp.LastY(); ++j)
{
- for(int i = comp.FirstX(); i <= comp.LastX(); ++i)
+ for (int i = comp.FirstX(); i <= comp.LastX(); ++i)
{
- comp[j][i] = (comp[j-1][i] + 2 * comp[j][i] + comp[j+1][i] + 2) >> 2;
+ comp[j][i] = (comp[j-1][i] + 2*comp[j][i] + comp[j+1][i] + 2)>>2;
}
}
//Special case for last row
- for(int i = comp.FirstX(); i <= comp.LastX(); ++i)
+ for (int i = comp.FirstX(); i <= comp.LastX(); ++i)
{
comp[comp.LastY()][i] = (comp[comp.LastY()-1][i] +
- 3 * comp[comp.LastY()][i] + 2) >> 2;
+ 3*comp[comp.LastY()][i] + 2)>>2;
}
}
-void FieldSequenceCompressor::SetPicTypeAndRefs(PictureParams& pparams)
+void FieldSequenceCompressor::SetPicTypeAndRefs( PictureParams& pparams )
{
// FIXME: won't work with adaptive GOP properly
// Set the temporal prediction parameters for field coding
const int pnum = pparams.PictureNum();
- const int rel_pnum = pparams.PictureNum() - m_gop_start_num;
+ const int rel_pnum = pparams.PictureNum()-m_gop_start_num;
const int gop_len = m_encparams.GOPLength();
const int num_L1 = m_encparams.NumL1();
- pparams.SetRetiredPictureNum(-1);
+ pparams.SetRetiredPictureNum( -1 );
pparams.Refs().clear();
- if(num_L1 > 0)
- {
+ if ( num_L1>0 ){
- if((rel_pnum / 2) % gop_len == 0)
- {
+ if ( (rel_pnum/2) % gop_len == 0){
// Field 1 is Intra Field
- if(gop_len > 1)
- {
- pparams.SetPicSort(PictureSort::IntraRefPictureSort());
+ if (gop_len > 1){
+ pparams.SetPicSort( PictureSort::IntraRefPictureSort());
// I picture expires after we've coded the next L1 picture
- pparams.SetExpiryTime(gop_len * 2);
- pparams.SetExpiryTime(2 * m_L1_sep);
- if(pnum % 2)
- {
- pparams.SetPicSort(PictureSort::InterRefPictureSort());
+ pparams.SetExpiryTime( gop_len * 2);
+ pparams.SetExpiryTime( 2*m_L1_sep );
+ if ( pnum%2){
+ pparams.SetPicSort( PictureSort::InterRefPictureSort());
// Ref the previous I field
- pparams.Refs().push_back(pnum - 1);
+ pparams.Refs().push_back( pnum-1 );
}
}
- else
- {
+ else{
// I-picture only coding
- pparams.SetPicSort(PictureSort::IntraNonRefPictureSort());
- pparams.SetExpiryTime(gop_len);
+ pparams.SetPicSort( PictureSort::IntraNonRefPictureSort());
+ pparams.SetExpiryTime( gop_len );
}
}
- else if((rel_pnum / 2) % m_L1_sep == 0)
- {
+ else if ((rel_pnum/2) % m_L1_sep == 0){
- pparams.SetPicSort(PictureSort::InterRefPictureSort());
+ pparams.SetPicSort( PictureSort::InterRefPictureSort());
- if(pnum % 2)
- {
+ if (pnum%2){
// Field 2
// Ref the first field of same picture
- pparams.Refs().push_back(pnum - 1);
+ pparams.Refs().push_back( pnum - 1);
// Ref the previous field 2 of I or L1 picture
- pparams.Refs().push_back(pnum - m_L1_sep * 2);
+ pparams.Refs().push_back( pnum - m_L1_sep*2 );
}
- else
- {
+ else{
// Field 1
// Ref the field 1 of previous I or L1 picture
- pparams.Refs().push_back(pnum - m_L1_sep * 2);
+ pparams.Refs().push_back( pnum - m_L1_sep*2 );
// Ref the field 2 of previous I or L1 picture
- pparams.Refs().push_back(pnum - m_L1_sep * 2 + 1);
+ pparams.Refs().push_back( pnum - m_L1_sep*2 + 1 );
}
// Expires after the next L1 or I picture
- pparams.SetExpiryTime((m_L1_sep + 1) * 2 - 1);
- if((rel_pnum / 2) % m_encparams.L1Sep() == 0)
- pparams.SetExpiryTime((2 * m_encparams.L1Sep()) + 1 * 2 - 1);
+ pparams.SetExpiryTime( (m_L1_sep+1)*2-1 );
+ if ((rel_pnum/2) % m_encparams.L1Sep() == 0 )
+ pparams.SetExpiryTime((2*m_encparams.L1Sep())+1*2-1);
}
- else if((rel_pnum / 2 + 1) % m_L1_sep == 0)
- {
+ else if ((rel_pnum/2+1) % m_L1_sep == 0){
// Bi-directional non-reference fields.
- if(pnum % 2)
- pparams.SetPicSort(PictureSort::InterNonRefPictureSort());
+ if (pnum%2)
+ pparams.SetPicSort( PictureSort::InterNonRefPictureSort());
else
- pparams.SetPicSort(PictureSort::InterRefPictureSort());
+ pparams.SetPicSort( PictureSort::InterRefPictureSort());
- pparams.Refs().push_back(pnum - 1);
- if(m_enc_pbuffer.IsPictureAvail(pnum + 2))
- pparams.Refs().push_back(pnum + 2);
+ pparams.Refs().push_back(pnum-1);
+ if (m_enc_pbuffer.IsPictureAvail(pnum+2))
+ pparams.Refs().push_back(pnum+2);
- pparams.SetExpiryTime(1);
+ pparams.SetExpiryTime( 1 );
}
- else
- {
+ else{
// Bi-directional reference fields.
- pparams.SetPicSort(PictureSort::InterRefPictureSort());
+ pparams.SetPicSort( PictureSort::InterRefPictureSort());
- pparams.Refs().push_back(pnum - 1);
- int next_ref = (((pnum / 2) / m_L1_sep + 1) * m_L1_sep) * 2 + (pnum % 2);
- if(m_enc_pbuffer.IsPictureAvail(next_ref))
+ pparams.Refs().push_back(pnum-1);
+ int next_ref = (((pnum/2)/m_L1_sep+1)*m_L1_sep)*2+(pnum%2);
+ if (m_enc_pbuffer.IsPictureAvail(next_ref))
pparams.Refs().push_back(next_ref);
- pparams.SetExpiryTime(4);
+ pparams.SetExpiryTime( 4 );
}
}
- else
- {
- pparams.SetPicSort(PictureSort::IntraNonRefPictureSort());
- pparams.SetExpiryTime(2);
+ else{
+ pparams.SetPicSort( PictureSort::IntraNonRefPictureSort());
+ pparams.SetExpiryTime( 2 );
}
}
@@ -901,41 +854,39 @@ FieldSequenceCompressor::~FieldSequenceCompressor()
{
}
-int FieldSequenceCompressor::CodedToDisplay(const int pnum)
+int FieldSequenceCompressor::CodedToDisplay( const int pnum )
{
- // Frame the field pnum belongs to
- int fnum = pnum >> 1;
- if(m_L1_sep > 0)
+ // Frame the field pnum belongs to
+ int fnum = pnum>>1;
+ if (m_L1_sep>0)
{
// We have L1 and L2 frames
- if(fnum == 0)
+ if (fnum==0)
return pnum;
- else if((fnum - 1) % m_L1_sep == 0)
- {
- //we have L1 or subsequent I frames
- return (pnum + (m_L1_sep - 1) * 2);
+ else if ((fnum-1)% m_L1_sep==0)
+ {//we have L1 or subsequent I frames
+ return (pnum+(m_L1_sep-1)*2);
}
else//we have L2 frames
return (pnum - 2);
}
else
- {
- //we just have I-frames, so no re-ordering
+ {//we just have I-frames, so no re-ordering
return (pnum);
}
}
void FieldSequenceCompressor::UpdateCBRModel(EncPicture& my_picture,
- const PictureByteIO* p_picture_byteio)
+ const PictureByteIO* p_picture_byteio)
{
- if(m_current_display_pnum % 2 == 0)
+ if (m_current_display_pnum%2 == 0)
m_field1_bytes = p_picture_byteio->GetSize();
else
m_field2_bytes = p_picture_byteio->GetSize();
// Update the quality factor
- if(my_picture.GetPparams().PictureNum() % 2)
- m_ratecontrol->CalcNextQualFactor(my_picture.GetPparams(), (m_field1_bytes + m_field2_bytes) * 8);
+ if (my_picture.GetPparams().PictureNum()%2)
+ m_ratecontrol->CalcNextQualFactor(my_picture.GetPparams(), (m_field1_bytes+m_field2_bytes)*8);
}
diff --git a/src/filters/parser/DiracSplitter/libdirac/libdirac_encoder/seq_compress.h b/src/filters/parser/DiracSplitter/libdirac/libdirac_encoder/seq_compress.h
index 40e754e71..37f5496be 100644
--- a/src/filters/parser/DiracSplitter/libdirac/libdirac_encoder/seq_compress.h
+++ b/src/filters/parser/DiracSplitter/libdirac/libdirac_encoder/seq_compress.h
@@ -61,337 +61,327 @@
namespace dirac
{
-//! Compresses a sequence of frames/fields from a stream.
-/*!
- This class compresses a sequence of frames/fields, frame by frame.
- or field by field. It currently uses GOP parameters set in the encoder
- parameters in order to define the temporal prediction structure.
- A version to incorporate non-GOP structures is TBC.
-
- This is an abstract class.
-*/
-class SequenceCompressor
-{
-public:
- //! Constructor
+ //! Compresses a sequence of frames/fields from a stream.
/*!
- Creates a sequence compressor, and prepares to begin compressing
- with the first picture.Sets up picture padding in the picture input if
- necesary
- \param pin an input stream containing a sequence of frames
- \param encp parameters for the encoding process
- \param dirac_byte_stream Output destination for compressed data
- */
- SequenceCompressor(StreamPicInput* pin,
- EncoderParams& encp,
- DiracByteStream& dirac_byte_stream);
+ This class compresses a sequence of frames/fields, frame by frame.
+ or field by field. It currently uses GOP parameters set in the encoder
+ parameters in order to define the temporal prediction structure.
+ A version to incorporate non-GOP structures is TBC.
- //! Destructor
- /*!
- Destructor. Must delete IO objects created by constructor.
+ This is an abstract class.
*/
- virtual ~SequenceCompressor();
+ class SequenceCompressor{
+ public:
+ //! Constructor
+ /*!
+ Creates a sequence compressor, and prepares to begin compressing
+ with the first picture.Sets up picture padding in the picture input if
+ necesary
+ \param pin an input stream containing a sequence of frames
+ \param encp parameters for the encoding process
+ \param dirac_byte_stream Output destination for compressed data
+ */
+ SequenceCompressor(StreamPicInput* pin,
+ EncoderParams& encp,
+ DiracByteStream& dirac_byte_stream);
+
+ //! Destructor
+ /*!
+ Destructor. Must delete IO objects created by constructor.
+ */
+ virtual ~SequenceCompressor();
+
+ //! Load data
+ /*!
+ Load one picture of data into the Sequence Compressor. Sets
+ m_all_done to true if no more data is available to be loaded.
+ Input can be frame or field. So the child class will have to
+ implement this function.
+ \return true - if frame load succeeded.
+ false - otherwise
+ */
+ virtual bool LoadNextFrame() = 0;
+
+ //! Compress the next picture in sequence
+ /*!
+ This function codes the next picture in coding order and returns the
+ next picture in display order. In general these will differ, and
+ because of re-ordering there is a delay which needs to be imposed.
+ This creates problems at the start and at the end of the sequence
+ which must be dealt with. At the start we just keep outputting
+ picture 0. At the end you will need to loop for longer to get all
+ the pictures out. It's up to the calling function to do something
+ with the decoded pictures as they come out -- write them to screen
+ or to file, for example. .
+ If coding is fast enough the compressed version could be watched
+ real-time (with suitable buffering in the calling function to
+ account for encode-time variations).
+
+ NOTE: LoadNextFrame must be called atleast once before invoking this
+ method.
+
+ \return pointer to the next locally decoded picture available for display
+ */
+ const EncPicture *CompressNextPicture();
+
+ //! Set up the appropriate prediction parameters for a picture
+ virtual void SetPicTypeAndRefs( PictureParams& pparams ) = 0;
+
+ //! Return a pointer to the most recent picture encoded
+ const EncPicture *GetPictureEncoded();
+
+ DiracByteStats EndSequence();
+
+ //! Determine if compression is complete.
+ /*!
+ Indicates whether or not the last picture in the sequence has been
+ compressed.
+ \return true if last picture has been compressed; false if not
+ */
+ bool Finished(){return m_all_done;}
+
+ //! Signal end of sequence
+ void SignalEOS() { m_eos_signalled = true; }
+
+ //! The delay required for correct timestamps
+ int PTSOffset(){return m_delay;}
+
+ protected:
+
+ //! Set up the motion block parameters
+ void SetMotionParameters();
+
+ //! Uses the GOP parameters to convert picture numbers in coded order to display order.
+ /*!
+ Uses the GOP parameters to convert picture numbers in coded order
+ to display order. Pure virtual function. The child class will
+ have to define it.
+ \param pnum the picture number in coded order
+ */
+ virtual int CodedToDisplay(const int pnum) = 0;
+
+ //! Make a report to screen on the coding results for the whole sequence
+ void MakeSequenceReport();
+
+ //! Remove unwanted pictures from picture buffers
+ virtual void CleanBuffers();
+
+ //! Update the CBR model based on the data we've compressed.
+ //Purely virtual. The child class will have to define it.
+ virtual void UpdateCBRModel(EncPicture& my_picture, const PictureByteIO* picture_byteio) = 0;
+
+ //! Update the parameters to be used in advance of coding an intra frame
+ void UpdateIntraPicCBRModel( const PictureParams& , const bool is_a_cut );
+
+ //! Returns true if the encoder can encode a picture
+ bool CanEncode();
- //! Load data
- /*!
- Load one picture of data into the Sequence Compressor. Sets
- m_all_done to true if no more data is available to be loaded.
- Input can be frame or field. So the child class will have to
- implement this function.
- \return true - if frame load succeeded.
- false - otherwise
- */
- virtual bool LoadNextFrame() = 0;
+ //! Completion flag, returned via the Finished method.
+ bool m_all_done;
- //! Compress the next picture in sequence
- /*!
- This function codes the next picture in coding order and returns the
- next picture in display order. In general these will differ, and
- because of re-ordering there is a delay which needs to be imposed.
- This creates problems at the start and at the end of the sequence
- which must be dealt with. At the start we just keep outputting
- picture 0. At the end you will need to loop for longer to get all
- the pictures out. It's up to the calling function to do something
- with the decoded pictures as they come out -- write them to screen
- or to file, for example. .
- If coding is fast enough the compressed version could be watched
- real-time (with suitable buffering in the calling function to
- account for encode-time variations).
-
- NOTE: LoadNextFrame must be called atleast once before invoking this
- method.
-
- \return pointer to the next locally decoded picture available for display
- */
- const EncPicture *CompressNextPicture();
+ //! Flag indicating whether we've just finished.
+ /*!
+ Flag which is false if we've been all-done for more than one
+ picture, true otherwise (so that we can take actions on finishing
+ once only).
+ */
+ bool m_just_finished;
- //! Set up the appropriate prediction parameters for a picture
- virtual void SetPicTypeAndRefs(PictureParams& pparams) = 0;
+ //! A class to hold the basic block parameters
+ OLBParams* m_basic_olb_params0;
- //! Return a pointer to the most recent picture encoded
- const EncPicture *GetPictureEncoded();
+ //! A class to hold the basic block parameters
+ OLBParams* m_basic_olb_params1;
- DiracByteStats EndSequence();
+ //! A class to hold the basic block parameters
+ const OLBParams* m_basic_olb_params2;
- //! Determine if compression is complete.
- /*!
- Indicates whether or not the last picture in the sequence has been
- compressed.
- \return true if last picture has been compressed; false if not
- */
- bool Finished()
- {
- return m_all_done;
- }
+ //! A class to hold block parameters to use when there are lots of intra blocks
+ OLBParams* m_intra_olbp;
- //! Signal end of sequence
- void SignalEOS()
- {
- m_eos_signalled = true;
- }
+ //! The parameters of the input source
+ SourceParams& m_srcparams;
- //! The delay required for correct timestamps
- int PTSOffset()
- {
- return m_delay;
- }
+ //! The parameters used for encoding.
+ EncoderParams& m_encparams;
-protected:
+ //! The parameters used for ME/MC
+ PicturePredParams& m_predparams;
- //! Set up the motion block parameters
- void SetMotionParameters();
+ //! The L1 separation currently in use
+ int m_L1_sep;
- //! Uses the GOP parameters to convert picture numbers in coded order to display order.
- /*!
- Uses the GOP parameters to convert picture numbers in coded order
- to display order. Pure virtual function. The child class will
- have to define it.
- \param pnum the picture number in coded order
- */
- virtual int CodedToDisplay(const int pnum) = 0;
+ //! Generic picture parameters for initialising pictures
+ PictureParams m_pparams;
- //! Make a report to screen on the coding results for the whole sequence
- void MakeSequenceReport();
+ //! Pointer pointing at the picture input.
+ StreamPicInput* m_pic_in;
- //! Remove unwanted pictures from picture buffers
- virtual void CleanBuffers();
+ //! A picture buffer used for local storage of pictures whilst pending re-ordering or being used for reference.
+ EncQueue m_enc_pbuffer;
- //! Update the CBR model based on the data we've compressed.
- //Purely virtual. The child class will have to define it.
- virtual void UpdateCBRModel(EncPicture& my_picture, const PictureByteIO* picture_byteio) = 0;
+ //state variables for CompressNextPicture
- //! Update the parameters to be used in advance of coding an intra frame
- void UpdateIntraPicCBRModel(const PictureParams& , const bool is_a_cut);
+ //! The number of the current picture to be coded, in display order
+ int m_current_display_pnum;
- //! Returns true if the encoder can encode a picture
- bool CanEncode();
+ //! The number of the current picture to be coded, in coded order
+ int m_current_code_pnum;
- //! Completion flag, returned via the Finished method.
- bool m_all_done;
+ //! The number of the picture which should be output for concurrent display or storage
+ int m_show_pnum;
- //! Flag indicating whether we've just finished.
- /*!
- Flag which is false if we've been all-done for more than one
- picture, true otherwise (so that we can take actions on finishing
- once only).
- */
- bool m_just_finished;
-
- //! A class to hold the basic block parameters
- OLBParams* m_basic_olb_params0;
-
- //! A class to hold the basic block parameters
- OLBParams* m_basic_olb_params1;
-
- //! A class to hold the basic block parameters
- const OLBParams* m_basic_olb_params2;
-
- //! A class to hold block parameters to use when there are lots of intra blocks
- OLBParams* m_intra_olbp;
-
- //! The parameters of the input source
- SourceParams& m_srcparams;
-
- //! The parameters used for encoding.
- EncoderParams& m_encparams;
-
- //! The parameters used for ME/MC
- PicturePredParams& m_predparams;
+ //! The index, in display order, of the last picture read
+ int m_last_picture_read;
- //! The L1 separation currently in use
- int m_L1_sep;
+ //! The picture number of the last GOP start
+ int m_gop_start_num;
- //! Generic picture parameters for initialising pictures
- PictureParams m_pparams;
+ //! A delay so that we don't display what we haven't coded
+ int m_delay;
- //! Pointer pointing at the picture input.
- StreamPicInput* m_pic_in;
+ //! A class for monitoring the quality of pictures and adjusting parameters appropriately
+ QualityMonitor m_qmonitor;
- //! A picture buffer used for local storage of pictures whilst pending re-ordering or being used for reference.
- EncQueue m_enc_pbuffer;
+ //! A class for monitoring and controlling bit rate
+ RateController* m_ratecontrol;
- //state variables for CompressNextPicture
+ //! A class to hold the picture compressor object
+ PictureCompressor m_pcoder;
- //! The number of the current picture to be coded, in display order
- int m_current_display_pnum;
+ //! Output destination for compressed data in bitstream format
+ DiracByteStream& m_dirac_byte_stream;
- //! The number of the current picture to be coded, in coded order
- int m_current_code_pnum;
+ //! Flag to check if End of Sequence has been signalled by the end user
+ bool m_eos_signalled;
- //! The number of the picture which should be output for concurrent display or storage
- int m_show_pnum;
+ private:
+ //! Copy constructor is private and body-less
+ /*!
+ Copy constructor is private and body-less. This class should not
+ be copied.
+ */
+ SequenceCompressor(const SequenceCompressor& cpy);
- //! The index, in display order, of the last picture read
- int m_last_picture_read;
+ //! Assignment = is private and body-less
+ /*!
+ Assignment = is private and body-less. This class should not be
+ assigned..
+ */
+ SequenceCompressor& operator=(const SequenceCompressor& rhs);
- //! The picture number of the last GOP start
- int m_gop_start_num;
- //! A delay so that we don't display what we haven't coded
- int m_delay;
+ };
- //! A class for monitoring the quality of pictures and adjusting parameters appropriately
- QualityMonitor m_qmonitor;
-
- //! A class for monitoring and controlling bit rate
- RateController* m_ratecontrol;
-
- //! A class to hold the picture compressor object
- PictureCompressor m_pcoder;
-
- //! Output destination for compressed data in bitstream format
- DiracByteStream& m_dirac_byte_stream;
-
- //! Flag to check if End of Sequence has been signalled by the end user
- bool m_eos_signalled;
-
-private:
- //! Copy constructor is private and body-less
+ //! Compresses a sequence of frames from a stream.
/*!
- Copy constructor is private and body-less. This class should not
- be copied.
+ This class compresses a sequence of frames, frame by frame. It
+ currently uses GOP parameters set in the encoder parameters in order
+ to define the temporal prediction structure. A version to incorporate
+ non-GOP structures is TBC.
*/
- SequenceCompressor(const SequenceCompressor& cpy);
-
- //! Assignment = is private and body-less
- /*!
- Assignment = is private and body-less. This class should not be
- assigned..
- */
- SequenceCompressor& operator=(const SequenceCompressor& rhs);
-
-
-};
-
-//! Compresses a sequence of frames from a stream.
-/*!
- This class compresses a sequence of frames, frame by frame. It
- currently uses GOP parameters set in the encoder parameters in order
- to define the temporal prediction structure. A version to incorporate
- non-GOP structures is TBC.
-*/
-class FrameSequenceCompressor : public SequenceCompressor
-{
-public:
- //! Constructor
- /*!
- Creates a sequence compressor that compresses frames i.e.
- progressive data, and prepares to begin compressing
- with the first frame.Sets up frame padding in the picture input if
- necesary
- \param pin an input stream containing a sequence of frames
- \param encp parameters for the encoding process
- \param dirac_byte_stream Output destination for compressed data
- */
- FrameSequenceCompressor(StreamPicInput* pin,
- EncoderParams& encp,
- DiracByteStream& dirac_byte_stream);
-
- //! Destructor
- /*!
- Destructor. Must delete IO objects created by constructor.
- */
- virtual ~FrameSequenceCompressor() {};
-
- //! Load data
- /*!
- Load one frame of data into the Sequence Compressor. Sets
- m_all_done to true if no more data is available to be loaded.
- \return true - if frame load succeeded.
- false - otherwise
- */
- virtual bool LoadNextFrame();
-
- //! Set up the appropriate prediction parameters for a picture
- virtual void SetPicTypeAndRefs(PictureParams& pparams);
-
-protected:
- virtual int CodedToDisplay(const int pnum);
- virtual void UpdateCBRModel(EncPicture& my_picture, const PictureByteIO* picture_byteio);
-
-};
-
-//! Compresses a sequence of fields from a stream.
-/*!
- This class compresses a sequence of fields, field by field. It
- currently uses GOP parameters set in the encoder parameters in order
- to define the temporal prediction structure. A version to incorporate
- non-GOP structures is TBC.
-*/
-class FieldSequenceCompressor : public SequenceCompressor
-{
-public:
- //! Constructor
- /*!
- Creates a sequence compressor that compresses fields i.e.
- interlaced data, and prepares to begin compressing
- with the first field.
- \param pin an input stream containing a sequence of frames
- \param encp parameters for the encoding process
- \param dirac_byte_stream Output destination for compressed data
- */
- FieldSequenceCompressor(StreamPicInput* pin,
- EncoderParams& encp,
- DiracByteStream& dirac_byte_stream);
-
- //! Destructor
- /*!
- Destructor. Must delete IO objects created by constructor.
- */
- virtual ~FieldSequenceCompressor();
-
- //! Load data
- /*!
- Load one frame i.e. two fields of data into the Sequence
- Compressor. Sets m_all_done to true if no more data is available
- to be loaded.
- \return true - if both fields load succeeded.
- false - otherwise
- */
- virtual bool LoadNextFrame();
-
-
- //! Set up the appropriate prediction parameters for a picture
- virtual void SetPicTypeAndRefs(PictureParams& pparams);
+ class FrameSequenceCompressor : public SequenceCompressor
+ {
+ public:
+ //! Constructor
+ /*!
+ Creates a sequence compressor that compresses frames i.e.
+ progressive data, and prepares to begin compressing
+ with the first frame.Sets up frame padding in the picture input if
+ necesary
+ \param pin an input stream containing a sequence of frames
+ \param encp parameters for the encoding process
+ \param dirac_byte_stream Output destination for compressed data
+ */
+ FrameSequenceCompressor(StreamPicInput* pin,
+ EncoderParams& encp,
+ DiracByteStream& dirac_byte_stream);
+
+ //! Destructor
+ /*!
+ Destructor. Must delete IO objects created by constructor.
+ */
+ virtual ~FrameSequenceCompressor(){};
+
+ //! Load data
+ /*!
+ Load one frame of data into the Sequence Compressor. Sets
+ m_all_done to true if no more data is available to be loaded.
+ \return true - if frame load succeeded.
+ false - otherwise
+ */
+ virtual bool LoadNextFrame();
+
+ //! Set up the appropriate prediction parameters for a picture
+ virtual void SetPicTypeAndRefs( PictureParams& pparams );
protected:
+ virtual int CodedToDisplay(const int pnum);
+ virtual void UpdateCBRModel(EncPicture& my_picture, const PictureByteIO* picture_byteio);
- virtual int CodedToDisplay(const int pnum);
+ };
- virtual void UpdateCBRModel(EncPicture& my_picture, const PictureByteIO* picture_byteio);
-private:
- //! Filter fields
+ //! Compresses a sequence of fields from a stream.
/*!
- Low pass filter the components in the fields used in Motion
- Estimation so that ME works better. Using a 1/4 1/2 1/4 filter
+ This class compresses a sequence of fields, field by field. It
+ currently uses GOP parameters set in the encoder parameters in order
+ to define the temporal prediction structure. A version to incorporate
+ non-GOP structures is TBC.
*/
- void PreMotionEstmationFilter(PicArray& comp);
-
- // Field1 bytes
- int m_field1_bytes;
- // Field2 bytes
- int m_field2_bytes;
-};
+ class FieldSequenceCompressor : public SequenceCompressor
+ {
+ public:
+ //! Constructor
+ /*!
+ Creates a sequence compressor that compresses fields i.e.
+ interlaced data, and prepares to begin compressing
+ with the first field.
+ \param pin an input stream containing a sequence of frames
+ \param encp parameters for the encoding process
+ \param dirac_byte_stream Output destination for compressed data
+ */
+ FieldSequenceCompressor(StreamPicInput* pin,
+ EncoderParams& encp,
+ DiracByteStream& dirac_byte_stream);
+
+ //! Destructor
+ /*!
+ Destructor. Must delete IO objects created by constructor.
+ */
+ virtual ~FieldSequenceCompressor();
+
+ //! Load data
+ /*!
+ Load one frame i.e. two fields of data into the Sequence
+ Compressor. Sets m_all_done to true if no more data is available
+ to be loaded.
+ \return true - if both fields load succeeded.
+ false - otherwise
+ */
+ virtual bool LoadNextFrame();
+
+
+ //! Set up the appropriate prediction parameters for a picture
+ virtual void SetPicTypeAndRefs( PictureParams& pparams );
+
+ protected:
+
+ virtual int CodedToDisplay(const int pnum);
+
+ virtual void UpdateCBRModel(EncPicture& my_picture, const PictureByteIO* picture_byteio);
+ private:
+ //! Filter fields
+ /*!
+ Low pass filter the components in the fields used in Motion
+ Estimation so that ME works better. Using a 1/4 1/2 1/4 filter
+ */
+ void PreMotionEstmationFilter (PicArray& comp);
+
+ // Field1 bytes
+ int m_field1_bytes;
+ // Field2 bytes
+ int m_field2_bytes;
+ };
} // namespace dirac
#endif
diff --git a/src/filters/parser/DiracSplitter/libdirac/libdirac_motionest/block_match.cpp b/src/filters/parser/DiracSplitter/libdirac/libdirac_motionest/block_match.cpp
index f0b63410e..bf5725c6e 100644
--- a/src/filters/parser/DiracSplitter/libdirac/libdirac_motionest/block_match.cpp
+++ b/src/filters/parser/DiracSplitter/libdirac/libdirac_motionest/block_match.cpp
@@ -45,199 +45,199 @@ using std::vector;
namespace dirac
{
-void AddNewVlist(CandidateList& vect_list, const MVector& mv,
- const int xr , const int yr , const int step)
+void AddNewVlist( CandidateList& vect_list, const MVector& mv,
+ const int xr , const int yr , const int step )
{
- //Creates a new motion vector list in a square region around mv
+ //Creates a new motion vector list in a square region around mv
vector<MVector> tmp_list;
vect_list.push_back(tmp_list);
- int list_num = vect_list.size() - 1;
+ int list_num=vect_list.size()-1;
- MVector tmp_mv(mv);
- AddVect(vect_list , tmp_mv , list_num);
+ MVector tmp_mv( mv );
+ AddVect(vect_list , tmp_mv , list_num );
- for(int i = 1 ; i <= xr ; ++i)
+ for ( int i=1 ; i<=xr ; ++i )
{
- tmp_mv.x = mv.x + i * step;
- AddVect(vect_list , tmp_mv , list_num);
+ tmp_mv.x = mv.x + i*step;
+ AddVect( vect_list , tmp_mv , list_num );
- tmp_mv.x = mv.x - i * step;
- AddVect(vect_list , tmp_mv , list_num);
+ tmp_mv.x = mv.x - i*step;
+ AddVect( vect_list , tmp_mv , list_num );
}
- for(int j = 1 ; j <= yr ; ++j)
+ for ( int j=1 ; j<=yr ; ++j)
{
- for(int i = -xr ; i <= xr ; ++i)
+ for ( int i=-xr ; i<=xr ; ++i)
{
- tmp_mv.x = mv.x + i * step;
- tmp_mv.y = mv.y + j * step;
- AddVect(vect_list, tmp_mv, list_num);
+ tmp_mv.x = mv.x + i*step;
+ tmp_mv.y = mv.y + j*step;
+ AddVect(vect_list,tmp_mv,list_num);
- tmp_mv.y = mv.y - j * step;
- AddVect(vect_list, tmp_mv, list_num);
+ tmp_mv.y = mv.y -j*step;
+ AddVect(vect_list,tmp_mv,list_num);
- }// i
+ }// i
}// j
// If we've not managed to add any element to the list
// remove the list so we don't ever have to check its size
- if(vect_list[list_num].size() == 0)
- vect_list.erase(vect_list.begin() + list_num);
+ if ( vect_list[list_num].size() == 0 )
+ vect_list.erase( vect_list.begin() + list_num );
}
-void AddNewVlist(CandidateList& vect_list , const MVector& mv , const int xr , const int yr)
+void AddNewVlist( CandidateList& vect_list , const MVector& mv , const int xr , const int yr)
{
- // Creates a new motion vector list in a square region around mv
-
+ // Creates a new motion vector list in a square region around mv
+
vector<MVector> tmp_list;
vect_list.push_back(tmp_list);
- int list_num = vect_list.size() - 1;
+ int list_num=vect_list.size()-1;
MVector tmp_mv(mv);
- AddVect(vect_list, tmp_mv, list_num);
+ AddVect(vect_list,tmp_mv,list_num);
- for(int i = 1 ; i <= xr ; ++i)
+ for ( int i=1 ; i<=xr ; ++i)
{
tmp_mv.x = mv.x + i;
- AddVect(vect_list , tmp_mv , list_num);
+ AddVect( vect_list , tmp_mv , list_num );
- tmp_mv.x = mv.x - i;
- AddVect(vect_list , tmp_mv , list_num);
+ tmp_mv.x = mv.x - i;
+ AddVect( vect_list , tmp_mv , list_num );
}
- for(int j = 1 ; j <= yr ; ++j)
+ for ( int j=1 ; j<=yr ; ++j)
{
- for(int i = -xr ; i <= xr ; ++i)
+ for ( int i=-xr ; i<=xr ; ++i)
{
tmp_mv.x = mv.x + i;
tmp_mv.y = mv.y + j;
- AddVect(vect_list , tmp_mv , list_num);
+ AddVect( vect_list , tmp_mv , list_num );
- tmp_mv.y = mv.y - j;
- AddVect(vect_list , tmp_mv , list_num);
- }
+ tmp_mv.y = mv.y-j;
+ AddVect( vect_list , tmp_mv , list_num );
+ }
}
// If we've not managed to add any element to the list
// remove the list so we don't ever have to check its size
- if(vect_list[list_num].size() == 0)
- vect_list.erase(vect_list.begin() + list_num);
+ if ( vect_list[list_num].size() == 0 )
+ vect_list.erase( vect_list.begin() + list_num );
}
-void AddNewVlistD(CandidateList& vect_list , const MVector& mv , const int xr , const int yr)
+void AddNewVlistD( CandidateList& vect_list , const MVector& mv , const int xr , const int yr )
{
- //As above, but using a diamond pattern
+ //As above, but using a diamond pattern
vector<MVector> tmp_list;
- vect_list.push_back(tmp_list);
+ vect_list.push_back( tmp_list );
- int list_num = vect_list.size() - 1;
+ int list_num=vect_list.size()-1;
int xlim;
- MVector tmp_mv(mv);
- AddVect(vect_list , tmp_mv , list_num);
+ MVector tmp_mv( mv );
+ AddVect( vect_list , tmp_mv , list_num );
- for(int i = 1 ; i <= xr ; ++i)
+ for ( int i=1 ; i<=xr ; ++i)
{
tmp_mv.x = mv.x + i;
- AddVect(vect_list , tmp_mv , list_num);
+ AddVect( vect_list , tmp_mv , list_num );
- tmp_mv.x = mv.x - i;
- AddVect(vect_list , tmp_mv , list_num);
+ tmp_mv.x = mv.x - i;
+ AddVect( vect_list , tmp_mv , list_num );
}
- for(int j = 1 ; j <= yr ; ++j)
+ for ( int j=1 ; j<=yr ; ++j)
{
- xlim = xr * (yr - std::abs(j)) / yr;
- for(int i = -xlim ; i <= xlim ; ++i)
+ xlim = xr * (yr-std::abs(j)) / yr;
+ for ( int i=-xlim ; i<=xlim ; ++i)
{
tmp_mv.x = mv.x + i;
tmp_mv.y = mv.y + j;
- AddVect(vect_list , tmp_mv , list_num);
+ AddVect( vect_list , tmp_mv , list_num );
tmp_mv.y = mv.y - j;
- AddVect(vect_list , tmp_mv , list_num);
- }
+ AddVect( vect_list , tmp_mv , list_num );
+ }
}
// If we've not managed to add any element to the list
// remove the list so we don't ever have to check its size
- if(vect_list[list_num].size() == 0)
- vect_list.erase(vect_list.begin() + list_num);
+ if ( vect_list[list_num].size() == 0 )
+ vect_list.erase( vect_list.begin() + list_num );
}
-void AddVect(CandidateList& vect_list, const MVector& mv, int list_num)
+void AddVect(CandidateList& vect_list,const MVector& mv,int list_num)
{
- bool is_in_list = false;
-
- size_t lnum = 0;
- size_t i;
+ bool is_in_list=false;
+
+ size_t lnum=0;
+ size_t i;
- while(!is_in_list && lnum < vect_list.size())
+ while( !is_in_list && lnum<vect_list.size() )
{
- i = 0;
- while(!is_in_list && i < vect_list[lnum].size())
- {
- if(vect_list[lnum][i].x == mv.x && vect_list[lnum][i].y == mv.y)
- is_in_list = true;
- ++i;
+ i=0;
+ while( !is_in_list && i<vect_list[lnum].size())
+ {
+ if ( vect_list[lnum][i].x == mv.x && vect_list[lnum][i].y == mv.y )
+ is_in_list=true;
+ ++i;
}
++lnum;
}
- if(!is_in_list)
+ if ( !is_in_list )
vect_list[list_num].push_back(mv);
-
+
}
-BlockMatcher::BlockMatcher(const PicArray& pic_data ,
- const PicArray& ref_data ,
- const OLBParams& bparams ,
- const int precision ,
- const MvArray& mv_array ,
- const TwoDArray< MvCostData >& cost_array):
- m_pic_data(pic_data),
+BlockMatcher::BlockMatcher( const PicArray& pic_data ,
+ const PicArray& ref_data ,
+ const OLBParams& bparams ,
+ const int precision ,
+ const MvArray& mv_array ,
+ const TwoDArray< MvCostData >& cost_array):
+ m_pic_data(pic_data),
m_ref_data(ref_data),
m_mv_array(mv_array),
m_cost_array(cost_array),
- m_peldiff(ref_data , pic_data), //NB: ORDER!!!!!!!!!!!!!!!!!!!!!!!!!!!!
- m_subpeldiff(3),
- m_bparams(bparams),
- m_var_max((pic_data.LengthX() + pic_data.LengthY()) / 216),
- m_var_max_up((pic_data.LengthX() + pic_data.LengthY()) / 27),
- m_precision(precision)
+ m_peldiff( ref_data , pic_data ), //NB: ORDER!!!!!!!!!!!!!!!!!!!!!!!!!!!!
+ m_subpeldiff( 3 ),
+ m_bparams( bparams ),
+ m_var_max( (pic_data.LengthX()+pic_data.LengthY() )/216 ),
+ m_var_max_up( (pic_data.LengthX()+pic_data.LengthY() )/27 ),
+ m_precision( precision )
{
- m_subpeldiff[0] = new BlockDiffHalfPel(ref_data, pic_data);
- m_subpeldiff[1] = new BlockDiffQuarterPel(ref_data, pic_data);
- m_subpeldiff[2] = new BlockDiffEighthPel(ref_data, pic_data);
+ m_subpeldiff[0] = new BlockDiffHalfPel( ref_data, pic_data );
+ m_subpeldiff[1] = new BlockDiffQuarterPel( ref_data, pic_data );
+ m_subpeldiff[2] = new BlockDiffEighthPel( ref_data, pic_data );
}
BlockMatcher::~BlockMatcher()
{
- for(int i = 0; i < 3; ++i)
+ for (int i=0; i<3; ++i )
delete m_subpeldiff[i];
}
-ValueType BlockMatcher::GetVar(const MVector& predmv , const MVector& mv) const
+ValueType BlockMatcher::GetVar( const MVector& predmv , const MVector& mv ) const
{
MVector diff;
- diff.x = mv.x - predmv.x;
- diff.y = mv.y - predmv.y;
+ diff.x = mv.x-predmv.x;
+ diff.y = mv.y-predmv.y;
- return Norm1(diff);
+ return Norm1( diff );
}
-
-ValueType BlockMatcher::GetVarUp(const MVector& predmv , const MVector& mv) const
+
+ValueType BlockMatcher::GetVarUp( const MVector& predmv , const MVector& mv ) const
{
MVector diff;
- diff.x = mv.x - predmv.x;
- diff.y = mv.y - predmv.y;
+ diff.x = mv.x-predmv.x;
+ diff.y = mv.y-predmv.y;
- return std::min(Norm1(diff) , Norm1(mv));
-}
+ return std::min( Norm1( diff ) , Norm1( mv ) );
+}
void BlockMatcher::FindBestMatchPel(const int xpos , const int ypos ,
const CandidateList& cand_list,
@@ -245,23 +245,23 @@ void BlockMatcher::FindBestMatchPel(const int xpos , const int ypos ,
const int list_start)
{
BlockDiffParams dparams;
- dparams.SetBlockLimits(m_bparams , m_pic_data , xpos , ypos);
-
+ dparams.SetBlockLimits( m_bparams , m_pic_data , xpos , ypos);
+
//now test against the offsets in the MV list to get the lowest cost//
- //////////////////////////////////////////////////////////////////////
+ //////////////////////////////////////////////////////////////////////
float best_cost = m_cost_array[ypos][xpos].total;
MVector best_mv = m_mv_array[ypos][xpos];
- for(size_t lnum = list_start ; lnum < cand_list.size() ; ++lnum)
+ for ( size_t lnum=list_start ; lnum<cand_list.size() ; ++lnum)
{
- for(size_t i = 0 ; i < cand_list[lnum].size() ; ++i)
+ for (size_t i=0 ; i<cand_list[lnum].size() ; ++i)
{
- m_peldiff.Diff(dparams ,
- cand_list[lnum][i] ,
- best_cost ,
- best_mv);
+ m_peldiff.Diff( dparams ,
+ cand_list[lnum][i] ,
+ best_cost ,
+ best_mv);
}// i
}// num
@@ -270,49 +270,49 @@ void BlockMatcher::FindBestMatchPel(const int xpos , const int ypos ,
m_mv_array[ypos][xpos] = best_mv;
m_cost_array[ypos][xpos].SAD = best_cost;
- m_cost_array[ypos][xpos].mvcost = GetVar(mv_prediction , best_mv);
- m_cost_array[ypos][xpos].SetTotal(0.0);
+ m_cost_array[ypos][xpos].mvcost = GetVar( mv_prediction , best_mv);
+ m_cost_array[ypos][xpos].SetTotal( 0.0 );
}
-void BlockMatcher::FindBestMatchSubp(const int xpos, const int ypos,
- const CandidateList& cand_list,
- const MVector& mv_prediction,
- const float lambda)
+void BlockMatcher::FindBestMatchSubp( const int xpos, const int ypos,
+ const CandidateList& cand_list,
+ const MVector& mv_prediction,
+ const float lambda)
{
BlockDiffParams dparams;
- dparams.SetBlockLimits(m_bparams , m_pic_data , xpos , ypos);
+ dparams.SetBlockLimits( m_bparams , m_pic_data , xpos , ypos);
//now test against the offsets in the MV list to get the lowest cost//
- //////////////////////////////////////////////////////////////////////
+ //////////////////////////////////////////////////////////////////////
// Numbers of the lists to do more searching in
- vector<int> list_nums;
+ vector<int> list_nums;
// Costs of the initial vectors in each list
- OneDArray<float> list_costs(cand_list.size());
+ OneDArray<float> list_costs( cand_list.size() );
// First test the first in each of the lists to choose which lists to pursue
- MvCostData best_costs(m_cost_array[ypos][xpos]);
+ MvCostData best_costs( m_cost_array[ypos][xpos] );
best_costs.total = 100000000.0f;
- MVector best_mv(m_mv_array[ypos][xpos]);
+ MVector best_mv( m_mv_array[ypos][xpos] );
MvCostData cand_costs;
MVector cand_mv;
- for(size_t list_num = 0 ; list_num < cand_list.size() ; ++list_num)
+ for (size_t list_num=0 ; list_num<cand_list.size() ; ++list_num )
{
- for(size_t i = 0 ; i < cand_list[list_num].size() ; ++i)
+ for (size_t i=0 ; i<cand_list[list_num].size() ; ++i )
{
cand_mv = cand_list[list_num][i];
- cand_costs.mvcost = GetVarUp(mv_prediction , cand_mv);
-
- m_subpeldiff[m_precision-1]->Diff(dparams,
- cand_mv ,
- cand_costs.mvcost,
- lambda,
- best_costs ,
- best_mv);
+ cand_costs.mvcost = GetVarUp( mv_prediction , cand_mv );
+
+ m_subpeldiff[m_precision-1]->Diff( dparams,
+ cand_mv ,
+ cand_costs.mvcost,
+ lambda,
+ best_costs ,
+ best_mv);
}//
}// list_num
@@ -320,8 +320,8 @@ void BlockMatcher::FindBestMatchSubp(const int xpos, const int ypos,
// Write the results in the arrays //
/////////////////////////////////////
- m_mv_array[ypos][xpos] = best_mv;
- m_cost_array[ypos][xpos] = best_costs;
+ m_mv_array[ypos][xpos] = best_mv;
+ m_cost_array[ypos][xpos] = best_costs;
}
void BlockMatcher::RefineMatchSubp(const int xpos, const int ypos,
@@ -330,31 +330,31 @@ void BlockMatcher::RefineMatchSubp(const int xpos, const int ypos,
{
BlockDiffParams dparams;
- dparams.SetBlockLimits(m_bparams , m_pic_data , xpos , ypos);
+ dparams.SetBlockLimits( m_bparams , m_pic_data , xpos , ypos);
- m_cost_array[ypos][xpos].mvcost = GetVarUp(mv_prediction,
- m_mv_array[ypos][xpos] << m_precision);
- m_cost_array[ypos][xpos].SetTotal(lambda);
+ m_cost_array[ypos][xpos].mvcost = GetVarUp( mv_prediction,
+ m_mv_array[ypos][xpos]<<m_precision );
+ m_cost_array[ypos][xpos].SetTotal( lambda );
// Initialise to the best pixel value
- MvCostData best_costs(m_cost_array[ypos][xpos]);
- MVector pel_mv(m_mv_array[ypos][xpos]);
- MVector best_mv(pel_mv);
+ MvCostData best_costs( m_cost_array[ypos][xpos] );
+ MVector pel_mv( m_mv_array[ypos][xpos] );
+ MVector best_mv( pel_mv );
// If the integer value is good enough, bail out
- if(best_costs.SAD < 2 * dparams.Xl()*dparams.Yl())
+ if ( best_costs.SAD < 2*dparams.Xl()*dparams.Yl() )
{
- m_mv_array[ypos][xpos] = m_mv_array[ypos][xpos] << m_precision;
+ m_mv_array[ypos][xpos] = m_mv_array[ypos][xpos]<<m_precision;
return;
}
// Next, test the predictor. If that's good enough, bail out
MvCostData pred_costs;
pred_costs.mvcost = 0;
- pred_costs.SAD = m_subpeldiff[m_precision-1]->Diff(dparams, mv_prediction);
+ pred_costs.SAD = m_subpeldiff[m_precision-1]->Diff( dparams, mv_prediction);
pred_costs.total = pred_costs.SAD;
- if(pred_costs.SAD < 2 * dparams.Xl()*dparams.Yl())
+ if (pred_costs.SAD<2*dparams.Xl()*dparams.Yl() )
{
m_mv_array[ypos][xpos] = mv_prediction;
m_cost_array[ypos][xpos] = pred_costs;
@@ -366,9 +366,9 @@ void BlockMatcher::RefineMatchSubp(const int xpos, const int ypos,
MvCostData cand_costs;
MVector cand_mv, old_best_mv;
- for(int i = 1; i <= m_precision; ++i)
+ for (int i=1; i<=m_precision; ++i )
{
- best_mv = best_mv << 1;
+ best_mv = best_mv<<1;
MVector temp_best_mv = best_mv;
// Do a neighbourhood of best_mv
@@ -376,83 +376,83 @@ void BlockMatcher::RefineMatchSubp(const int xpos, const int ypos,
// Stage 1 - look at the 4 nearest points
cand_mv.x = best_mv.x - 1;
cand_mv.y = best_mv.y;
- m_subpeldiff[i-1]->Diff(dparams, cand_mv ,
- GetVarUp(mv_prediction,
- cand_mv << (m_precision - i)) ,
- lambda , best_costs ,
- temp_best_mv);
+ m_subpeldiff[i-1]->Diff( dparams, cand_mv ,
+ GetVarUp( mv_prediction,
+ cand_mv<<(m_precision-i) ) ,
+ lambda , best_costs ,
+ temp_best_mv);
cand_mv.x = best_mv.x + 1;
cand_mv.y = best_mv.y;
- m_subpeldiff[i-1]->Diff(dparams, cand_mv ,
- GetVarUp(mv_prediction,
- cand_mv << (m_precision - i)) ,
- lambda , best_costs ,
- temp_best_mv);
+ m_subpeldiff[i-1]->Diff( dparams, cand_mv ,
+ GetVarUp( mv_prediction,
+ cand_mv<<(m_precision-i) ) ,
+ lambda , best_costs ,
+ temp_best_mv);
cand_mv.x = best_mv.x;
cand_mv.y = best_mv.y - 1;
- m_subpeldiff[i-1]->Diff(dparams, cand_mv ,
- GetVarUp(mv_prediction,
- cand_mv << (m_precision - i)) ,
- lambda , best_costs ,
- temp_best_mv);
+ m_subpeldiff[i-1]->Diff( dparams, cand_mv ,
+ GetVarUp( mv_prediction,
+ cand_mv<<(m_precision-i) ) ,
+ lambda , best_costs ,
+ temp_best_mv);
cand_mv.x = best_mv.x;
cand_mv.y = best_mv.y + 1;
- m_subpeldiff[i-1]->Diff(dparams, cand_mv ,
- GetVarUp(mv_prediction,
- cand_mv << (m_precision - i)) ,
- lambda , best_costs ,
- temp_best_mv);
-
- // Stage 2. If we've done better than the original value,
- // look at the other two neighbours
- if(temp_best_mv.x != best_mv.x)
+ m_subpeldiff[i-1]->Diff( dparams, cand_mv ,
+ GetVarUp( mv_prediction,
+ cand_mv<<(m_precision-i) ) ,
+ lambda , best_costs ,
+ temp_best_mv);
+
+ // Stage 2. If we've done better than the original value,
+ // look at the other two neighbours
+ if ( temp_best_mv.x != best_mv.x )
{
MVector new_best_mv = temp_best_mv;
cand_mv.x = new_best_mv.x;
cand_mv.y = new_best_mv.y - 1;
- m_subpeldiff[i-1]->Diff(dparams, cand_mv ,
- GetVarUp(mv_prediction,
- cand_mv << (m_precision - i)) ,
- lambda , best_costs ,
- temp_best_mv);
+ m_subpeldiff[i-1]->Diff( dparams, cand_mv ,
+ GetVarUp( mv_prediction,
+ cand_mv<<(m_precision-i) ) ,
+ lambda , best_costs ,
+ temp_best_mv);
cand_mv.x = new_best_mv.x;
cand_mv.y = new_best_mv.y + 1;
- m_subpeldiff[i-1]->Diff(dparams, cand_mv ,
- GetVarUp(mv_prediction,
- cand_mv << (m_precision - i)) ,
- lambda , best_costs ,
- temp_best_mv);
+ m_subpeldiff[i-1]->Diff( dparams, cand_mv ,
+ GetVarUp( mv_prediction,
+ cand_mv<<(m_precision-i) ) ,
+ lambda , best_costs ,
+ temp_best_mv);
}
- else if(temp_best_mv.y != best_mv.y)
+ else if ( temp_best_mv.y != best_mv.y )
{
MVector new_best_mv = temp_best_mv;
cand_mv.x = new_best_mv.x - 1;
cand_mv.y = new_best_mv.y;
- m_subpeldiff[i-1]->Diff(dparams, cand_mv ,
- GetVarUp(mv_prediction,
- cand_mv << (m_precision - i)) ,
- lambda , best_costs ,
- temp_best_mv);
+ m_subpeldiff[i-1]->Diff( dparams, cand_mv ,
+ GetVarUp( mv_prediction,
+ cand_mv<<(m_precision-i) ) ,
+ lambda , best_costs ,
+ temp_best_mv);
cand_mv.x = new_best_mv.x + 1;
cand_mv.y = new_best_mv.y;
- m_subpeldiff[i-1]->Diff(dparams, cand_mv ,
- GetVarUp(mv_prediction,
- cand_mv << (m_precision - i)) ,
- lambda , best_costs ,
- temp_best_mv);
- }
+ m_subpeldiff[i-1]->Diff( dparams, cand_mv ,
+ GetVarUp( mv_prediction,
+ cand_mv<<(m_precision-i) ) ,
+ lambda , best_costs ,
+ temp_best_mv);
+ }
best_mv = temp_best_mv;
// Bail out if we can't do better than 10% worse than the predictor at
// each stage
- if(best_costs.total > 1.1 * pred_costs.total)
+ if ( best_costs.total>1.1*pred_costs.total )
{
m_mv_array[ypos][xpos] = mv_prediction;
m_cost_array[ypos][xpos] = pred_costs;
- return;
+ return;
}
}//i
@@ -461,8 +461,8 @@ void BlockMatcher::RefineMatchSubp(const int xpos, const int ypos,
// Write the results in the arrays //
/////////////////////////////////////
- m_mv_array[ypos][xpos] = best_mv;
- m_cost_array[ypos][xpos] = best_costs;
+ m_mv_array[ypos][xpos] = best_mv;
+ m_cost_array[ypos][xpos] = best_costs;
}
diff --git a/src/filters/parser/DiracSplitter/libdirac/libdirac_motionest/block_match.h b/src/filters/parser/DiracSplitter/libdirac/libdirac_motionest/block_match.h
index 3063900e2..2bcb5e2b3 100644
--- a/src/filters/parser/DiracSplitter/libdirac/libdirac_motionest/block_match.h
+++ b/src/filters/parser/DiracSplitter/libdirac/libdirac_motionest/block_match.h
@@ -45,166 +45,163 @@
namespace dirac
{
-typedef std::vector< std::vector< MVector > > CandidateList;
-
-//! Add a new motion vector list of neighbours of a vector to the set of lists
-/*
- Add a new motion vector list to the set of lists consisting of the
- square neighbourhood [mv.x-xr,mv.x+xr] by
- [mv.y-yr,mv.y+yr]. Vectors that already occur in previous lists are
- not added.
-*/
-void AddNewVlist(CandidateList& vect_list , const MVector& mv , const int xr , const int yr);
-
-//! Add a new motion vector list to the set of lists for sub-pixel matching
-/*
- Add a new motion vector list to the set of lists consisting of the
- vectors of the form (mv.x+m*step,mv.y+n*step) where m lies between
- -xr and xr and n lies between -yr and yr. Vectors that already occur
- in previous lists are not added.
-*/
-void AddNewVlist(CandidateList& vect_list , const MVector& mv , const int xr , const int yr , const int step);
-
-//! Add a new motion vector list of diagnonal neighbours of a vector to the set of lists
-/*
- Add a new motion vector list to the set of lists consisting of the
- diagonal neighbourhood of height 2yr+1 pixels and width 2xr+1 centred
- on \param mv.
- Vectors that already occur in previous lists are not added.
-*/
-void AddNewVlistD(CandidateList& vect_list , const MVector& mv , const int xr, const int yr);
-
-//! Add a motion vector to the set of motion vector lists
-/*!
- Add a motion vector to the set of motion vector lists, making sure
- it's not a duplicate.
-*/
-void AddVect(CandidateList& vect_list , const MVector& mv , const int list_num);
-
-//! Get the (absolute) variation between two motion vectors
-/*!
- Return the variation between two motion vectors, computed as the sum
- of absolute differences of their components.
-*/
-ValueType GetVar(const MVector& mv1, const MVector& mv2);
-
-//! Get the (absolute) variation between a motion vector and a list of motion vectors
-/*!
- Return the variation between a motion vector and a list of motion
- vectos, computed as the sum of absolute differences between the
- components of the vector and the median vector produced by the list of
- vectors
-*/
-ValueType GetVar(const std::vector<MVector>& pred_list, const MVector& mv);
-
-
-//! Class to do block matching
-
-// Subsumes FindBestMatch and FindBestMatchSubpel
-class BlockMatcher
-{
-public:
- //! Constructor
- /*!
- Constructor
- \param ref_data the reference picture component
- \param pic_data the picture being matched
- \param bparams the (overlapped) block parameters to be used for the matching
- \param precision the number of bits of precision being used for estimation
- \param mv_array the array of vectors we're going to write into
- \param cost_array the array of costs we're going to write into
-
+ typedef std::vector< std::vector< MVector > > CandidateList;
+
+ //! Add a new motion vector list of neighbours of a vector to the set of lists
+ /*
+ Add a new motion vector list to the set of lists consisting of the
+ square neighbourhood [mv.x-xr,mv.x+xr] by
+ [mv.y-yr,mv.y+yr]. Vectors that already occur in previous lists are
+ not added.
*/
- BlockMatcher(const PicArray& ref_data ,
- const PicArray& pic_data ,
- const OLBParams& bparams ,
- const int precision ,
- const MvArray& mv_array ,
- const TwoDArray< MvCostData >& cost_array);
-
- ~BlockMatcher();
-
- //! Find the best matching vector from a list of candidates
- /*!
- Find the best matching vector from a list of candidates.
- \param xpos the horizontal location of the block being matched
- \param ypos the vertical location of the block being matched
- \param cand_list the list of candidate vectors
- \param mv_prediction Prediction used for each block used to control the variation in the motion vector field.
- \param list_start index into the candidate vectors list
+ void AddNewVlist( CandidateList& vect_list , const MVector& mv , const int xr , const int yr );
+
+ //! Add a new motion vector list to the set of lists for sub-pixel matching
+ /*
+ Add a new motion vector list to the set of lists consisting of the
+ vectors of the form (mv.x+m*step,mv.y+n*step) where m lies between
+ -xr and xr and n lies between -yr and yr. Vectors that already occur
+ in previous lists are not added.
+ */
+ void AddNewVlist( CandidateList& vect_list , const MVector& mv , const int xr , const int yr , const int step );
+
+ //! Add a new motion vector list of diagnonal neighbours of a vector to the set of lists
+ /*
+ Add a new motion vector list to the set of lists consisting of the
+ diagonal neighbourhood of height 2yr+1 pixels and width 2xr+1 centred
+ on \param mv.
+ Vectors that already occur in previous lists are not added.
*/
- void FindBestMatchPel(const int xpos , const int ypos ,
- const CandidateList& cand_list,
- const MVector& mv_prediction,
- const int list_start);
+ void AddNewVlistD( CandidateList& vect_list , const MVector& mv , const int xr, const int yr);
- //! Find the best matching vector from a list of candidates, to sub-pixel accuracy (TBC: merge with FindBestMatch)
+ //! Add a motion vector to the set of motion vector lists
/*!
- Find the best matching vector from a list of candidates.
- \param xpos the horizontal location of the block being matched
- \param ypos the vertical location of the block being matched
- \param cand_list the list of candidate vectors
- \param mv_prediction the prediction for the motion vector
- \param lambda the Lagrangian parameter
+ Add a motion vector to the set of motion vector lists, making sure
+ it's not a duplicate.
*/
- void FindBestMatchSubp(const int xpos, const int ypos,
- const CandidateList& cand_list,
- const MVector& mv_prediction,
- const float lambda);
+ void AddVect( CandidateList& vect_list , const MVector& mv , const int list_num);
- void RefineMatchSubp(const int xpos, const int ypos,
- const MVector& mv_prediction,
- const float lambda);
-
- //! Get a measure of the difference between a motion vector and a prediction
+ //! Get the (absolute) variation between two motion vectors
/*!
- Get a measure of the difference between a motion vector and a prediction
- \param predmv the predicting motion vector
- \param mv the motion vector
+ Return the variation between two motion vectors, computed as the sum
+ of absolute differences of their components.
*/
- ValueType GetVar(const MVector& predmv , const MVector& mv) const;
+ ValueType GetVar(const MVector& mv1,const MVector& mv2);
- //! Get a measure of the difference between a motion vector and a prediction, to 1/8pel accuracy
+ //! Get the (absolute) variation between a motion vector and a list of motion vectors
/*!
- Get a measure of the difference between a motion vector and a prediction, to 1/8pel accuracy
- \param predmv the predicting motion vector
- \param mv the motion vector
+ Return the variation between a motion vector and a list of motion
+ vectos, computed as the sum of absolute differences between the
+ components of the vector and the median vector produced by the list of
+ vectors
*/
- ValueType GetVarUp(const MVector& predmv , const MVector& mv) const;
+ ValueType GetVar(const std::vector<MVector>& pred_list,const MVector& mv);
- void SetPrecision(const int n)
- {
- m_precision = n;
- }
-private:
- // Local copies of the picture and reference
- const PicArray& m_pic_data;
- const PicArray& m_ref_data;
+ //! Class to do block matching
- // Local copy of the motion vector array being populated
- const MvArray& m_mv_array;
-
- // Local copy of the costs being determined through the matching
- const TwoDArray< MvCostData >& m_cost_array;
-
- // Block difference elements. Will choose between them depending
- // on whether we're at the edge of the picture
- PelBlockDiff m_peldiff;
-
- OneDArray<BlockDiffUp* > m_subpeldiff;
-
- // The block parameters we're using
- OLBParams m_bparams;
-
- // The maximum variations allowed in calculating motion vector costs
- const int m_var_max;
- const int m_var_max_up;
-
- // The motion vector precision
- int m_precision;
-
-};
+ // Subsumes FindBestMatch and FindBestMatchSubpel
+ class BlockMatcher
+ {
+ public:
+ //! Constructor
+ /*!
+ Constructor
+ \param ref_data the reference picture component
+ \param pic_data the picture being matched
+ \param bparams the (overlapped) block parameters to be used for the matching
+ \param precision the number of bits of precision being used for estimation
+ \param mv_array the array of vectors we're going to write into
+ \param cost_array the array of costs we're going to write into
+
+ */
+ BlockMatcher( const PicArray& ref_data ,
+ const PicArray& pic_data ,
+ const OLBParams& bparams ,
+ const int precision ,
+ const MvArray& mv_array ,
+ const TwoDArray< MvCostData >& cost_array);
+
+ ~BlockMatcher();
+
+ //! Find the best matching vector from a list of candidates
+ /*!
+ Find the best matching vector from a list of candidates.
+ \param xpos the horizontal location of the block being matched
+ \param ypos the vertical location of the block being matched
+ \param cand_list the list of candidate vectors
+ \param mv_prediction Prediction used for each block used to control the variation in the motion vector field.
+ \param list_start index into the candidate vectors list
+ */
+ void FindBestMatchPel( const int xpos , const int ypos ,
+ const CandidateList& cand_list,
+ const MVector& mv_prediction,
+ const int list_start);
+
+ //! Find the best matching vector from a list of candidates, to sub-pixel accuracy (TBC: merge with FindBestMatch)
+ /*!
+ Find the best matching vector from a list of candidates.
+ \param xpos the horizontal location of the block being matched
+ \param ypos the vertical location of the block being matched
+ \param cand_list the list of candidate vectors
+ \param mv_prediction the prediction for the motion vector
+ \param lambda the Lagrangian parameter
+ */
+ void FindBestMatchSubp( const int xpos, const int ypos,
+ const CandidateList& cand_list,
+ const MVector& mv_prediction,
+ const float lambda);
+
+ void RefineMatchSubp(const int xpos, const int ypos,
+ const MVector& mv_prediction,
+ const float lambda);
+
+ //! Get a measure of the difference between a motion vector and a prediction
+ /*!
+ Get a measure of the difference between a motion vector and a prediction
+ \param predmv the predicting motion vector
+ \param mv the motion vector
+ */
+ ValueType GetVar( const MVector& predmv , const MVector& mv ) const;
+
+ //! Get a measure of the difference between a motion vector and a prediction, to 1/8pel accuracy
+ /*!
+ Get a measure of the difference between a motion vector and a prediction, to 1/8pel accuracy
+ \param predmv the predicting motion vector
+ \param mv the motion vector
+ */
+ ValueType GetVarUp( const MVector& predmv , const MVector& mv ) const;
+
+ void SetPrecision( const int n ){ m_precision = n; }
+
+ private:
+ // Local copies of the picture and reference
+ const PicArray& m_pic_data;
+ const PicArray& m_ref_data;
+
+ // Local copy of the motion vector array being populated
+ const MvArray& m_mv_array;
+
+ // Local copy of the costs being determined through the matching
+ const TwoDArray< MvCostData >& m_cost_array;
+
+ // Block difference elements. Will choose between them depending
+ // on whether we're at the edge of the picture
+ PelBlockDiff m_peldiff;
+
+ OneDArray<BlockDiffUp* > m_subpeldiff;
+
+ // The block parameters we're using
+ OLBParams m_bparams;
+
+ // The maximum variations allowed in calculating motion vector costs
+ const int m_var_max;
+ const int m_var_max_up;
+
+ // The motion vector precision
+ int m_precision;
+
+ };
} // namespace dirac
#endif
diff --git a/src/filters/parser/DiracSplitter/libdirac/libdirac_motionest/downconvert.cpp b/src/filters/parser/DiracSplitter/libdirac/libdirac_motionest/downconvert.cpp
index 1d37203c0..75bd0739e 100644
--- a/src/filters/parser/DiracSplitter/libdirac/libdirac_motionest/downconvert.cpp
+++ b/src/filters/parser/DiracSplitter/libdirac/libdirac_motionest/downconvert.cpp
@@ -20,7 +20,7 @@
* Portions created by the Initial Developer are Copyright (C) 2004.
* All Rights Reserved.
*
-* Contributor(s): Richard Felton (Original Author),
+* Contributor(s): Richard Felton (Original Author),
* Thomas Davies
*
* Alternatively, the contents of this file may be used under the terms of
@@ -51,89 +51,89 @@ DownConverter::DownConverter()
void DownConverter::DoDownConvert(const PicArray& old_data, PicArray& new_data)
{
//Down-convert by a factor of two.
- m_row_buffer = new ValueType[old_data.LengthX()];
+ m_row_buffer= new ValueType[old_data.LengthX()];
//Variables that will be used by the filter calculations
int sum;
int colpos;
// The area of the picture that will be downconverted
- const int xlen = 2 * new_data.LengthX();
- const int ylen = 2 * new_data.LengthY();
+ const int xlen = 2*new_data.LengthX();
+ const int ylen = 2*new_data.LengthY();
- //There are three y loops to cope with the leading edge, middle
+ //There are three y loops to cope with the leading edge, middle
//and trailing edge of each column.
- colpos = 0;
- for(int y = 0; y < Stage_I_Size * 2 ; y += 2 , colpos++)
+ colpos=0;
+ for( int y=0; y<Stage_I_Size*2 ; y+=2 , colpos++ )
{
// We are filtering each column but doing it bit by bit.
// This means our main loop is in the x direction and
// there is a much greater chance the data we need will
// be in the cache.
- for(int x = 0 ; x < xlen ; x++)
- {
+ for( int x=0 ; x<xlen ; x++ )
+ {
// In down conversion we interpolate every pixel
// so there is no copying.
// Excuse the complicated ternary stuff but it sorts out the edge
- sum = (old_data[y][x] + old_data[y+1][x]) * StageI_I;
- sum += (old_data[((y-1)>=0)?(y-1):0][x] + old_data[y+2][x]) * StageI_II;
- sum += (old_data[((y-2)>=0)?(y-2):0][x] + old_data[y+3][x]) * StageI_III;
- sum += (old_data[((y-3)>=0)?(y-3):0][x] + old_data[y+4][x]) * StageI_IV;
- sum += (old_data[((y-4)>=0)?(y-4):0][x] + old_data[y+5][x]) * StageI_V;
- sum += (old_data[((y-5)>=0)?(y-5):0][x] + old_data[y+6][x]) * StageI_VI;
- sum += 1 << (StageI_Shift - 1); //do rounding right
+ sum = (old_data[y][x] + old_data[y+1][x])*StageI_I;
+ sum += (old_data[((y-1)>=0)?(y-1):0][x] + old_data[y+2][x])*StageI_II;
+ sum += (old_data[((y-2)>=0)?(y-2):0][x] + old_data[y+3][x])*StageI_III;
+ sum += (old_data[((y-3)>=0)?(y-3):0][x] + old_data[y+4][x])*StageI_IV;
+ sum += (old_data[((y-4)>=0)?(y-4):0][x] + old_data[y+5][x])*StageI_V;
+ sum += (old_data[((y-5)>=0)?(y-5):0][x] + old_data[y+6][x])*StageI_VI;
+ sum += 1<<(StageI_Shift-1);//do rounding right
m_row_buffer[x] = sum >> StageI_Shift;
}// x
//Speaking of which - the row loop.
- RowLoop(colpos, new_data);
- }// y
+ RowLoop(colpos,new_data);
+ }// y
// This loop is like the last one but it deals with the center
// section of the image and so the ternary operations are dropped
// from the filter section.
- for(int y = Stage_I_Size * 2 ; y < ylen - Stage_I_Size * 2 ; y += 2 , colpos++)
+ for( int y=Stage_I_Size*2 ; y<ylen-Stage_I_Size*2 ; y+=2 , colpos++ )
{
- for(int x = 0 ; x < xlen ; x++)
+ for( int x=0 ; x<xlen ; x++ )
{
- sum = (old_data[y][x] + old_data[y+1][x]) * StageI_I;
- sum += (old_data[y-1][x] + old_data[y+2][x]) * StageI_II;
- sum += (old_data[y-2][x] + old_data[y+3][x]) * StageI_III;
- sum += (old_data[y-3][x] + old_data[y+4][x]) * StageI_IV;
- sum += (old_data[y-4][x] + old_data[y+5][x]) * StageI_V;
- sum += (old_data[y-5][x] + old_data[y+6][x]) * StageI_VI;
- sum += 1 << (StageI_Shift - 1); //do rounding right
+ sum = (old_data[y][x] + old_data[y+1][x])*StageI_I;
+ sum += (old_data[y-1][x] + old_data[y+2][x])*StageI_II;
+ sum += (old_data[y-2][x] + old_data[y+3][x])*StageI_III;
+ sum += (old_data[y-3][x] + old_data[y+4][x])*StageI_IV;
+ sum += (old_data[y-4][x] + old_data[y+5][x])*StageI_V;
+ sum += (old_data[y-5][x] + old_data[y+6][x])*StageI_VI;
+ sum += 1<<(StageI_Shift-1);//do rounding right
m_row_buffer[x] = sum >> StageI_Shift;
}// x
- RowLoop(colpos , new_data);
+ RowLoop( colpos , new_data );
}// y
// Another similar loop! - this time we are dealing with
// the trailing edge so the ternary stuff is back in the
// filter calcs but in the second parameter.
- for(int y = ylen - (Stage_I_Size * 2) ; y < ylen - 1 ; y += 2 , colpos++)
+ for( int y=ylen-(Stage_I_Size*2) ; y<ylen-1 ; y+=2 , colpos++ )
{
- for(int x = 0; x < xlen ; x++)
+ for( int x=0; x<xlen ; x++ )
{
- sum = (old_data[y][x] + old_data[((y+1)<ylen)?(y+1):(ylen-1)][x]) * StageI_I;
- sum += (old_data[y-1][x] + old_data[((y+2)<ylen)?(y+2):(ylen-1)][x]) * StageI_II;
- sum += (old_data[y-2][x] + old_data[((y+3)<ylen)?(y+3):(ylen-1)][x]) * StageI_III;
- sum += (old_data[y-3][x] + old_data[((y+4)<ylen)?(y+4):(ylen-1)][x]) * StageI_IV;
- sum += (old_data[y-4][x] + old_data[((y+5)<ylen)?(y+5):(ylen-1)][x]) * StageI_V;
- sum += (old_data[y-5][x] + old_data[((y+6)<ylen)?(y+6):(ylen-1)][x]) * StageI_VI;
+ sum = (old_data[y][x] + old_data[((y+1)<ylen)?(y+1):(ylen-1)][x])*StageI_I;
+ sum += (old_data[y-1][x] + old_data[((y+2)<ylen)?(y+2):(ylen-1)][x])*StageI_II;
+ sum += (old_data[y-2][x] + old_data[((y+3)<ylen)?(y+3):(ylen-1)][x])*StageI_III;
+ sum += (old_data[y-3][x] + old_data[((y+4)<ylen)?(y+4):(ylen-1)][x])*StageI_IV;
+ sum += (old_data[y-4][x] + old_data[((y+5)<ylen)?(y+5):(ylen-1)][x])*StageI_V;
+ sum += (old_data[y-5][x] + old_data[((y+6)<ylen)?(y+6):(ylen-1)][x])*StageI_VI;
// Do rounding right
- sum += 1 << (StageI_Shift - 1);
+ sum += 1<<(StageI_Shift-1);
m_row_buffer[x] = sum >> StageI_Shift;
}// x
- RowLoop(colpos , new_data);
+ RowLoop( colpos , new_data );
}// y
@@ -146,56 +146,56 @@ void DownConverter::DoDownConvert(const PicArray& old_data, PicArray& new_data)
// The loop over the columns is the same every time so lends itself to isolation
// as an individual function.
-void DownConverter::RowLoop(const int colpos , PicArray& new_data)
+void DownConverter::RowLoop( const int colpos , PicArray& new_data)
{
- //Calculation variables
+ //Calculation variables
int sum;
- const int xlen = 2 * new_data.LengthX();
- int linepos = 0;
+ const int xlen = 2*new_data.LengthX();
+ int linepos=0;
- // Leading Column Edge
- // Similar loops to the x case in ByHalf_opto, for explanation look there.
- // Note the factor of two difference as we only want to fill in every other
- // line as the others have already been created by the line loops.
+ // Leading Column Edge
+ // Similar loops to the x case in ByHalf_opto, for explanation look there.
+ // Note the factor of two difference as we only want to fill in every other
+ // line as the others have already been created by the line loops.
- for(int x = 0; x < (2 * Stage_I_Size) ; x += 2 , linepos++)
+ for( int x=0; x<(2*Stage_I_Size) ; x+=2 , linepos++ )
{
- sum = (m_row_buffer[((x)>=0)?(x):0] + m_row_buffer[x+1]) * StageI_I;
- sum += (m_row_buffer[((x-1)>=0)?(x-1):0] + m_row_buffer[x+2]) * StageI_II;
- sum += (m_row_buffer[((x-2)>=0)?(x-2):0] + m_row_buffer[x+3]) * StageI_III;
- sum += (m_row_buffer[((x-3)>=0)?(x-3):0] + m_row_buffer[x+4]) * StageI_IV;
- sum += (m_row_buffer[((x-4)>=0)?(x-4):0] + m_row_buffer[x+5]) * StageI_V;
- sum += (m_row_buffer[((x-5)>=0)?(x-5):0] + m_row_buffer[x+6]) * StageI_VI;
- sum += 1 << (StageI_Shift - 1); //do rounding right
+ sum = (m_row_buffer[((x)>=0)?(x):0] + m_row_buffer[x+1])*StageI_I;
+ sum += (m_row_buffer[((x-1)>=0)?(x-1):0] + m_row_buffer[x+2])*StageI_II;
+ sum += (m_row_buffer[((x-2)>=0)?(x-2):0] + m_row_buffer[x+3])*StageI_III;
+ sum += (m_row_buffer[((x-3)>=0)?(x-3):0] + m_row_buffer[x+4])*StageI_IV;
+ sum += (m_row_buffer[((x-4)>=0)?(x-4):0] + m_row_buffer[x+5])*StageI_V;
+ sum += (m_row_buffer[((x-5)>=0)?(x-5):0] + m_row_buffer[x+6])*StageI_VI;
+ sum += 1<<(StageI_Shift-1);//do rounding right
new_data[colpos][linepos] = sum >> StageI_Shift;
}
- //Middle of column
- for(int x = (2 * Stage_I_Size) ; x < xlen - (2 * Stage_I_Size) ; x += 2 , linepos++)
+ //Middle of column
+ for( int x=(2*Stage_I_Size) ; x<xlen-(2*Stage_I_Size) ; x+=2 , linepos++)
{
- sum = (m_row_buffer[x] + m_row_buffer[x+1]) * StageI_I;
- sum += (m_row_buffer[x-1] + m_row_buffer[x+2]) * StageI_II;
- sum += (m_row_buffer[x-2] + m_row_buffer[x+3]) * StageI_III;
- sum += (m_row_buffer[x-3] + m_row_buffer[x+4]) * StageI_IV;
- sum += (m_row_buffer[x-4] + m_row_buffer[x+5]) * StageI_V;
- sum += (m_row_buffer[x-5] + m_row_buffer[x+6]) * StageI_VI;
- sum += 1 << (StageI_Shift - 1); //do rounding right
+ sum = (m_row_buffer[x] + m_row_buffer[x+1])*StageI_I;
+ sum += (m_row_buffer[x-1] + m_row_buffer[x+2])*StageI_II;
+ sum += (m_row_buffer[x-2] + m_row_buffer[x+3])*StageI_III;
+ sum += (m_row_buffer[x-3] + m_row_buffer[x+4])*StageI_IV;
+ sum += (m_row_buffer[x-4] + m_row_buffer[x+5])*StageI_V;
+ sum += (m_row_buffer[x-5] + m_row_buffer[x+6])*StageI_VI;
+ sum += 1<<(StageI_Shift-1);//do rounding right
new_data[colpos][linepos] = sum >> StageI_Shift;
}
- //Trailing column edge
- for(int x = xlen - (2 * Stage_I_Size) ; x < xlen - 1 ; x += 2 , linepos++)
+ //Trailing column edge
+ for( int x=xlen-(2*Stage_I_Size) ; x< xlen-1 ; x+=2 , linepos++ )
{
- sum = (m_row_buffer[x] + m_row_buffer[((x+1)<xlen)?(x+1):(xlen-1)]) * StageI_I;
- sum += (m_row_buffer[x-1] + m_row_buffer[((x+2)<xlen)?(x+2):(xlen-1)]) * StageI_II;
- sum += (m_row_buffer[x-2] + m_row_buffer[((x+3)<xlen)?(x+3):(xlen-1)]) * StageI_III;
- sum += (m_row_buffer[x-3] + m_row_buffer[((x+4)<xlen)?(x+4):(xlen-1)]) * StageI_IV;
- sum += (m_row_buffer[x-4] + m_row_buffer[((x+5)<xlen)?(x+5):(xlen-1)]) * StageI_V;
- sum += (m_row_buffer[x-5] + m_row_buffer[((x+6)<xlen)?(x+6):(xlen-1)]) * StageI_VI;
- sum += 1 << (StageI_Shift - 1); //do rounding right
+ sum = (m_row_buffer[x] + m_row_buffer[((x+1)<xlen)?(x+1):(xlen-1)])*StageI_I;
+ sum += (m_row_buffer[x-1] + m_row_buffer[((x+2)<xlen)?(x+2):(xlen-1)])*StageI_II;
+ sum += (m_row_buffer[x-2] + m_row_buffer[((x+3)<xlen)?(x+3):(xlen-1)])*StageI_III;
+ sum += (m_row_buffer[x-3] + m_row_buffer[((x+4)<xlen)?(x+4):(xlen-1)])*StageI_IV;
+ sum += (m_row_buffer[x-4] + m_row_buffer[((x+5)<xlen)?(x+5):(xlen-1)])*StageI_V;
+ sum += (m_row_buffer[x-5] + m_row_buffer[((x+6)<xlen)?(x+6):(xlen-1)])*StageI_VI;
+ sum += 1<<(StageI_Shift-1);//do rounding right
new_data[colpos][linepos] = sum >> StageI_Shift;
diff --git a/src/filters/parser/DiracSplitter/libdirac/libdirac_motionest/downconvert.h b/src/filters/parser/DiracSplitter/libdirac/libdirac_motionest/downconvert.h
index eeb40c21c..bb2bdcf1e 100644
--- a/src/filters/parser/DiracSplitter/libdirac/libdirac_motionest/downconvert.h
+++ b/src/filters/parser/DiracSplitter/libdirac/libdirac_motionest/downconvert.h
@@ -43,52 +43,51 @@
namespace dirac
{
-//! A class for fast downconversion of picture data
-/*!
- A class for fast down-conversion of picture data. The picture data is
- downconverted by a factor of two in each dimension, using fast
- filtering techniques. The filter is a half-band filter designed to
- trade off frequency response, ringiness, and aliasing
- */
-class DownConverter
-{
+ //! A class for fast downconversion of picture data
+ /*!
+ A class for fast down-conversion of picture data. The picture data is
+ downconverted by a factor of two in each dimension, using fast
+ filtering techniques. The filter is a half-band filter designed to
+ trade off frequency response, ringiness, and aliasing
+ */
+ class DownConverter{
-public:
+ public:
- //! Constructor
- DownConverter();
- //! Destructor
- ~DownConverter() {};
+ //! Constructor
+ DownConverter();
+ //! Destructor
+ ~DownConverter(){};
- //! A function to do the actual down-conversion
- /*!
- A function to do the actual downconversion.
- \param old_data the picture data to be downconverted
- \param new_data the resulting down-converted data. The array must be of the correct size.
- */
- void DoDownConvert(const PicArray& old_data, PicArray& new_data);
+ //! A function to do the actual down-conversion
+ /*!
+ A function to do the actual downconversion.
+ \param old_data the picture data to be downconverted
+ \param new_data the resulting down-converted data. The array must be of the correct size.
+ */
+ void DoDownConvert(const PicArray& old_data, PicArray& new_data);
-private:
- //Copy constructor
- DownConverter(const DownConverter& cpy);//private, body-less: class should not be copied
- //Assignment=
- DownConverter& operator=(const DownConverter& rhs);//private, body-less: class should not be assigned
+ private:
+ //Copy constructor
+ DownConverter(const DownConverter& cpy);//private, body-less: class should not be copied
+ //Assignment=
+ DownConverter& operator=(const DownConverter& rhs);//private, body-less: class should not be assigned
- //Applies the filter to a single column
- void RowLoop(const int colpos , PicArray& new_data);
+ //Applies the filter to a single column
+ void RowLoop(const int colpos , PicArray& new_data );
- ValueType* m_row_buffer;
+ ValueType* m_row_buffer;
- //Define filter parameters
- static const int Stage_I_Size = 6;
- static const int StageI_I = 86;
- static const int StageI_II = 46;
- static const int StageI_III = 4;
- static const int StageI_IV = -8;
- static const int StageI_V = -4;
- static const int StageI_VI = 4;
- static const int StageI_Shift = 8;
-};
+ //Define filter parameters
+ static const int Stage_I_Size = 6;
+ static const int StageI_I = 86;
+ static const int StageI_II = 46;
+ static const int StageI_III = 4;
+ static const int StageI_IV = -8;
+ static const int StageI_V = -4;
+ static const int StageI_VI = 4;
+ static const int StageI_Shift = 8;
+ };
} // namespace dirac
diff --git a/src/filters/parser/DiracSplitter/libdirac/libdirac_motionest/downconvert_mmx.cpp b/src/filters/parser/DiracSplitter/libdirac/libdirac_motionest/downconvert_mmx.cpp
index f3d98bb12..efdc261e5 100644
--- a/src/filters/parser/DiracSplitter/libdirac/libdirac_motionest/downconvert_mmx.cpp
+++ b/src/filters/parser/DiracSplitter/libdirac/libdirac_motionest/downconvert_mmx.cpp
@@ -41,7 +41,7 @@ using namespace dirac;
#if defined (HAVE_MMX)
#include <mmintrin.h>
-typedef union
+typedef union
{
__m64 m;
int i[2];
@@ -56,64 +56,64 @@ typedef union
m2 = _mm_madd_pi16 (m2, tap); \
*sum1 = _mm_add_pi32 (*sum1, m1); \
*sum2 = _mm_add_pi32 (*sum2, m2); \
-
+
//General function - does some admin and calls the correct function
void DownConverter::DoDownConvert(const PicArray& old_data, PicArray& new_data)
{
//Down-convert by a factor of two.
- m_row_buffer = new ValueType[old_data.LengthX()];
+ m_row_buffer= new ValueType[old_data.LengthX()];
//Variables that will be used by the filter calculations
int sum;
int colpos;
// The area of the picture that will be downconverted
- const int xlen = 2 * new_data.LengthX();
- const int ylen = 2 * new_data.LengthY();
+ const int xlen = 2*new_data.LengthX();
+ const int ylen = 2*new_data.LengthY();
- //There are three y loops to cope with the leading edge, middle
+ //There are three y loops to cope with the leading edge, middle
//and trailing edge of each column.
- colpos = 0;
+ colpos=0;
static __m64 zero = _mm_set_pi16(0, 0, 0, 0);
- static __m64 tap0 = _mm_set_pi16(0, StageI_I, 0, StageI_I);
- static __m64 tap1 = _mm_set_pi16(0, StageI_II, 0, StageI_II);
- static __m64 tap2 = _mm_set_pi16(0, StageI_III, 0, StageI_III);
- static __m64 tap3 = _mm_set_pi16(0, StageI_IV, 0, StageI_IV);
- static __m64 tap4 = _mm_set_pi16(0, StageI_V, 0, StageI_V);
- static __m64 tap5 = _mm_set_pi16(0, StageI_VI, 0, StageI_VI);
- static __m64 round = _mm_set_pi32(1 << (StageI_Shift - 1), 1 << (StageI_Shift - 1));
+ static __m64 tap0 = _mm_set_pi16 (0, StageI_I, 0, StageI_I);
+ static __m64 tap1 = _mm_set_pi16 (0, StageI_II, 0, StageI_II);
+ static __m64 tap2 = _mm_set_pi16 (0, StageI_III, 0, StageI_III);
+ static __m64 tap3 = _mm_set_pi16 (0, StageI_IV, 0, StageI_IV);
+ static __m64 tap4 = _mm_set_pi16 (0, StageI_V, 0, StageI_V);
+ static __m64 tap5 = _mm_set_pi16 (0, StageI_VI, 0, StageI_VI);
+ static __m64 round = _mm_set_pi32 ( 1<<(StageI_Shift-1), 1<<(StageI_Shift-1));
u_sum sum1, sum2;
__m64 tmp, m1, m2;
- int stopX = (xlen >> 2) << 2;
- for(int y = 0; y < Stage_I_Size * 2 ; y += 2 , colpos++)
+ int stopX = (xlen >> 2)<<2;
+ for( int y=0; y<Stage_I_Size*2 ; y+=2 , colpos++ )
{
// We are filtering each column but doing it bit by bit.
// This means our main loop is in the x direction and
// there is a much greater chance the data we need will
// be in the cache.
- for(int x = 0 ; x < stopX ; x += 4)
- {
+ for( int x=0 ; x<stopX ; x+=4 )
+ {
// In down conversion we interpolate every pixel
// so there is no copying.
// Excuse the complicated ternary stuff but it sorts out the edge
- sum1.m = _mm_set_pi32(0, 0);
- sum2.m = _mm_set_pi32(0, 0);
+ sum1.m = _mm_set_pi32 (0, 0);
+ sum2.m = _mm_set_pi32 (0, 0);
- mmx_add(&old_data[y][x], &old_data[y+1][x], tap0, zero, &sum1.m, &sum2.m);
+ mmx_add (&old_data[y][x], &old_data[y+1][x], tap0, zero, &sum1.m, &sum2.m);
mmx_add(&old_data[((y-1)>=0)?(y-1):0][x] , &old_data[y+2][x], tap1, zero, &sum1.m, &sum2.m);
mmx_add(&old_data[((y-2)>=0)?(y-2):0][x] , &old_data[y+3][x], tap2, zero, &sum1.m, &sum2.m);
mmx_add(&old_data[((y-3)>=0)?(y-3):0][x] , &old_data[y+4][x], tap3, zero, &sum1.m, &sum2.m);
mmx_add(&old_data[((y-4)>=0)?(y-4):0][x] , &old_data[y+5][x], tap4, zero, &sum1.m, &sum2.m);
mmx_add(&old_data[((y-5)>=0)?(y-5):0][x] , &old_data[y+6][x], tap5, zero, &sum1.m, &sum2.m);
- sum1.m = _mm_add_pi32(sum1.m, round);
- sum2.m = _mm_add_pi32(sum2.m, round);
- sum1.m = _mm_srai_pi32(sum1.m, StageI_Shift);
- sum2.m = _mm_srai_pi32(sum2.m, StageI_Shift);
+ sum1.m = _mm_add_pi32 (sum1.m, round);
+ sum2.m = _mm_add_pi32 (sum2.m, round);
+ sum1.m = _mm_srai_pi32 (sum1.m, StageI_Shift);
+ sum2.m = _mm_srai_pi32 (sum2.m, StageI_Shift);
m_row_buffer[x] = sum1.i[0];
m_row_buffer[x+1] = sum1.i[1];
m_row_buffer[x+2] = sum2.i[0];
@@ -121,49 +121,49 @@ void DownConverter::DoDownConvert(const PicArray& old_data, PicArray& new_data)
}// x
_mm_empty();
- for(int x = stopX ; x < xlen ; x++)
- {
+ for( int x=stopX ; x<xlen ; x++ )
+ {
// In down conversion we interpolate every pixel
// so there is no copying.
// Excuse the complicated ternary stuff but it sorts out the edge
- sum = (old_data[y][x] + old_data[y+1][x]) * StageI_I;
- sum += (old_data[((y-1)>=0)?(y-1):0][x] + old_data[y+2][x]) * StageI_II;
- sum += (old_data[((y-2)>=0)?(y-2):0][x] + old_data[y+3][x]) * StageI_III;
- sum += (old_data[((y-3)>=0)?(y-3):0][x] + old_data[y+4][x]) * StageI_IV;
- sum += (old_data[((y-4)>=0)?(y-4):0][x] + old_data[y+5][x]) * StageI_V;
- sum += (old_data[((y-5)>=0)?(y-5):0][x] + old_data[y+6][x]) * StageI_VI;
- sum += 1 << (StageI_Shift - 1); //do rounding right
+ sum = (old_data[y][x] + old_data[y+1][x])*StageI_I;
+ sum += (old_data[((y-1)>=0)?(y-1):0][x] + old_data[y+2][x])*StageI_II;
+ sum += (old_data[((y-2)>=0)?(y-2):0][x] + old_data[y+3][x])*StageI_III;
+ sum += (old_data[((y-3)>=0)?(y-3):0][x] + old_data[y+4][x])*StageI_IV;
+ sum += (old_data[((y-4)>=0)?(y-4):0][x] + old_data[y+5][x])*StageI_V;
+ sum += (old_data[((y-5)>=0)?(y-5):0][x] + old_data[y+6][x])*StageI_VI;
+ sum += 1<<(StageI_Shift-1);//do rounding right
m_row_buffer[x] = sum >> StageI_Shift;
}// x
//Speaking of which - the row loop.
- RowLoop(colpos, new_data);
- }// y
+ RowLoop(colpos,new_data);
+ }// y
// This loop is like the last one but it deals with the center
// section of the image and so the ternary operations are dropped
// from the filter section.
- for(int y = Stage_I_Size * 2 ; y < ylen - Stage_I_Size * 2 ; y += 2 , colpos++)
+ for( int y=Stage_I_Size*2 ; y<ylen-Stage_I_Size*2 ; y+=2 , colpos++ )
{
- for(int x = 0 ; x < stopX ; x += 4)
- {
+ for( int x=0 ; x<stopX ; x+=4 )
+ {
// In down conversion we interpolate every pixel
// so there is no copying.
// Excuse the complicated ternary stuff but it sorts out the edge
- sum1.m = _mm_set_pi32(0, 0);
- sum2.m = _mm_set_pi32(0, 0);
+ sum1.m = _mm_set_pi32 (0, 0);
+ sum2.m = _mm_set_pi32 (0, 0);
- mmx_add(&old_data[y][x], &old_data[y+1][x], tap0, zero, &sum1.m, &sum2.m);
+ mmx_add (&old_data[y][x], &old_data[y+1][x], tap0, zero, &sum1.m, &sum2.m);
mmx_add(&old_data[y-1][x] , &old_data[y+2][x], tap1, zero, &sum1.m, &sum2.m);
mmx_add(&old_data[y-2][x] , &old_data[y+3][x], tap2, zero, &sum1.m, &sum2.m);
mmx_add(&old_data[y-3][x] , &old_data[y+4][x], tap3, zero, &sum1.m, &sum2.m);
mmx_add(&old_data[y-4][x] , &old_data[y+5][x], tap4, zero, &sum1.m, &sum2.m);
mmx_add(&old_data[y-5][x] , &old_data[y+6][x], tap5, zero, &sum1.m, &sum2.m);
- sum1.m = _mm_add_pi32(sum1.m, round);
- sum2.m = _mm_add_pi32(sum2.m, round);
- sum1.m = _mm_srai_pi32(sum1.m, StageI_Shift);
- sum2.m = _mm_srai_pi32(sum2.m, StageI_Shift);
+ sum1.m = _mm_add_pi32 (sum1.m, round);
+ sum2.m = _mm_add_pi32 (sum2.m, round);
+ sum1.m = _mm_srai_pi32 (sum1.m, StageI_Shift);
+ sum2.m = _mm_srai_pi32 (sum2.m, StageI_Shift);
m_row_buffer[x] = sum1.i[0];
m_row_buffer[x+1] = sum1.i[1];
m_row_buffer[x+2] = sum2.i[0];
@@ -171,46 +171,46 @@ void DownConverter::DoDownConvert(const PicArray& old_data, PicArray& new_data)
}// x
_mm_empty();
- for(int x = stopX ; x < xlen ; x++)
+ for( int x=stopX ; x<xlen ; x++ )
{
- sum = (old_data[y][x] + old_data[y+1][x]) * StageI_I;
- sum += (old_data[y-1][x] + old_data[y+2][x]) * StageI_II;
- sum += (old_data[y-2][x] + old_data[y+3][x]) * StageI_III;
- sum += (old_data[y-3][x] + old_data[y+4][x]) * StageI_IV;
- sum += (old_data[y-4][x] + old_data[y+5][x]) * StageI_V;
- sum += (old_data[y-5][x] + old_data[y+6][x]) * StageI_VI;
- sum += 1 << (StageI_Shift - 1); //do rounding right
+ sum = (old_data[y][x] + old_data[y+1][x])*StageI_I;
+ sum += (old_data[y-1][x] + old_data[y+2][x])*StageI_II;
+ sum += (old_data[y-2][x] + old_data[y+3][x])*StageI_III;
+ sum += (old_data[y-3][x] + old_data[y+4][x])*StageI_IV;
+ sum += (old_data[y-4][x] + old_data[y+5][x])*StageI_V;
+ sum += (old_data[y-5][x] + old_data[y+6][x])*StageI_VI;
+ sum += 1<<(StageI_Shift-1);//do rounding right
m_row_buffer[x] = sum >> StageI_Shift;
}// x
- RowLoop(colpos , new_data);
+ RowLoop( colpos , new_data );
}// y
// Another similar loop! - this time we are dealing with
// the trailing edge so the ternary stuff is back in the
// filter calcs but in the second parameter.
- for(int y = ylen - (Stage_I_Size * 2) ; y < ylen - 1 ; y += 2 , colpos++)
+ for( int y=ylen-(Stage_I_Size*2) ; y<ylen-1 ; y+=2 , colpos++ )
{
- for(int x = 0 ; x < stopX ; x += 4)
- {
+ for( int x=0 ; x<stopX ; x+=4 )
+ {
// In down conversion we interpolate every pixel
// so there is no copying.
// Excuse the complicated ternary stuff but it sorts out the edge
- sum1.m = _mm_set_pi32(0, 0);
- sum2.m = _mm_set_pi32(0, 0);
+ sum1.m = _mm_set_pi32 (0, 0);
+ sum2.m = _mm_set_pi32 (0, 0);
- mmx_add(&old_data[y][x], &old_data[((y+1)<ylen)?(y+1):(ylen-1)][x], tap0, zero, &sum1.m, &sum2.m);
+ mmx_add (&old_data[y][x], &old_data[((y+1)<ylen)?(y+1):(ylen-1)][x], tap0, zero, &sum1.m, &sum2.m);
mmx_add(&old_data[y-1][x] , &old_data[((y+2)<ylen)?(y+2):(ylen-1)][x], tap1, zero, &sum1.m, &sum2.m);
mmx_add(&old_data[y-2][x] , &old_data[((y+3)<ylen)?(y+3):(ylen-1)][x], tap2, zero, &sum1.m, &sum2.m);
mmx_add(&old_data[y-3][x] , &old_data[((y+4)<ylen)?(y+4):(ylen-1)][x], tap3, zero, &sum1.m, &sum2.m);
mmx_add(&old_data[y-4][x] , &old_data[((y+5)<ylen)?(y+5):(ylen-1)][x], tap4, zero, &sum1.m, &sum2.m);
mmx_add(&old_data[y-5][x] , &old_data[((y+6)<ylen)?(y+6):(ylen-1)][x], tap5, zero, &sum1.m, &sum2.m);
- sum1.m = _mm_add_pi32(sum1.m, round);
- sum2.m = _mm_add_pi32(sum2.m, round);
- sum1.m = _mm_srai_pi32(sum1.m, StageI_Shift);
- sum2.m = _mm_srai_pi32(sum2.m, StageI_Shift);
+ sum1.m = _mm_add_pi32 (sum1.m, round);
+ sum2.m = _mm_add_pi32 (sum2.m, round);
+ sum1.m = _mm_srai_pi32 (sum1.m, StageI_Shift);
+ sum2.m = _mm_srai_pi32 (sum2.m, StageI_Shift);
m_row_buffer[x] = sum1.i[0];
m_row_buffer[x+1] = sum1.i[1];
@@ -219,23 +219,23 @@ void DownConverter::DoDownConvert(const PicArray& old_data, PicArray& new_data)
}// x
_mm_empty();
- for(int x = stopX; x < xlen ; x++)
+ for( int x=stopX; x<xlen ; x++ )
{
- sum = (old_data[y][x] + old_data[((y+1)<ylen)?(y+1):(ylen-1)][x]) * StageI_I;
- sum += (old_data[y-1][x] + old_data[((y+2)<ylen)?(y+2):(ylen-1)][x]) * StageI_II;
- sum += (old_data[y-2][x] + old_data[((y+3)<ylen)?(y+3):(ylen-1)][x]) * StageI_III;
- sum += (old_data[y-3][x] + old_data[((y+4)<ylen)?(y+4):(ylen-1)][x]) * StageI_IV;
- sum += (old_data[y-4][x] + old_data[((y+5)<ylen)?(y+5):(ylen-1)][x]) * StageI_V;
- sum += (old_data[y-5][x] + old_data[((y+6)<ylen)?(y+6):(ylen-1)][x]) * StageI_VI;
+ sum = (old_data[y][x] + old_data[((y+1)<ylen)?(y+1):(ylen-1)][x])*StageI_I;
+ sum += (old_data[y-1][x] + old_data[((y+2)<ylen)?(y+2):(ylen-1)][x])*StageI_II;
+ sum += (old_data[y-2][x] + old_data[((y+3)<ylen)?(y+3):(ylen-1)][x])*StageI_III;
+ sum += (old_data[y-3][x] + old_data[((y+4)<ylen)?(y+4):(ylen-1)][x])*StageI_IV;
+ sum += (old_data[y-4][x] + old_data[((y+5)<ylen)?(y+5):(ylen-1)][x])*StageI_V;
+ sum += (old_data[y-5][x] + old_data[((y+6)<ylen)?(y+6):(ylen-1)][x])*StageI_VI;
// Do rounding right
- sum += 1 << (StageI_Shift - 1);
+ sum += 1<<(StageI_Shift-1);
m_row_buffer[x] = sum >> StageI_Shift;
}// x
- RowLoop(colpos , new_data);
+ RowLoop( colpos , new_data );
}// y
diff --git a/src/filters/parser/DiracSplitter/libdirac/libdirac_motionest/me_mode_decn.cpp b/src/filters/parser/DiracSplitter/libdirac/libdirac_motionest/me_mode_decn.cpp
index c411c46d1..a23e705de 100644
--- a/src/filters/parser/DiracSplitter/libdirac/libdirac_motionest/me_mode_decn.cpp
+++ b/src/filters/parser/DiracSplitter/libdirac/libdirac_motionest/me_mode_decn.cpp
@@ -44,8 +44,8 @@ using namespace dirac;
using std::vector;
-ModeDecider::ModeDecider(const EncoderParams& encp):
- m_encparams(encp),
+ModeDecider::ModeDecider( const EncoderParams& encp):
+ m_encparams( encp ),
m_level_factor(3),
m_mode_factor(3),
m_me_data_set(3)
@@ -56,17 +56,17 @@ ModeDecider::ModeDecider(const EncoderParams& encp):
ModeDecider::~ModeDecider()
{
- if(m_psort.IsInter())
+ if (m_psort.IsInter())
{
delete m_me_data_set[0];
delete m_me_data_set[1];
}
}
-void ModeDecider::DoModeDecn(EncQueue& my_buffer, int pic_num)
+void ModeDecider::DoModeDecn( EncQueue& my_buffer, int pic_num )
{
-
- m_predparams = &(my_buffer.GetPicture(pic_num).GetMEData().GetPicPredParams());
+
+ m_predparams = &(my_buffer.GetPicture(pic_num).GetMEData().GetPicPredParams() );
// The following factors normalise costs for sub-SBs and SBs to those of
// blocks, so that the overlap is take into account (e.g. a sub-SB has
@@ -76,28 +76,28 @@ void ModeDecider::DoModeDecn(EncQueue& my_buffer, int pic_num)
// all SAD costs are normalised to the area corresponding to non-overlapping
// 16 blocks of size XBLEN*YBLEN.
- m_level_factor[0] = float(16 * m_predparams->LumaBParams(2).Xblen() * m_predparams->LumaBParams(2).Yblen()) /
- float(m_predparams->LumaBParams(0).Xblen() * m_predparams->LumaBParams(0).Yblen());
+ m_level_factor[0] = float( 16 * m_predparams->LumaBParams(2).Xblen() * m_predparams->LumaBParams(2).Yblen() )/
+ float( m_predparams->LumaBParams(0).Xblen() * m_predparams->LumaBParams(0).Yblen() );
- m_level_factor[1] = float(4 * m_predparams->LumaBParams(2).Xblen() * m_predparams->LumaBParams(2).Yblen()) /
- float(m_predparams->LumaBParams(1).Xblen() * m_predparams->LumaBParams(1).Yblen());
+ m_level_factor[1] = float( 4 * m_predparams->LumaBParams(2).Xblen() * m_predparams->LumaBParams(2).Yblen() )/
+ float( m_predparams->LumaBParams(1).Xblen() * m_predparams->LumaBParams(1).Yblen() );
m_level_factor[2] = 1.0f;
- for(int i = 0 ; i <= 2 ; ++i)
- m_mode_factor[i] = 80.0 * std::pow(0.8 , 2 - i);
+ for (int i=0 ; i<=2 ; ++i)
+ m_mode_factor[i] = 80.0*std::pow(0.8 , 2-i);
- // We've got 'raw' block motion vectors for up to two reference pictures. Now we want
- // to make a decision as to mode. In this initial implementation, this is bottom-up
+ // We've got 'raw' block motion vectors for up to two reference pictures. Now we want
+ // to make a decision as to mode. In this initial implementation, this is bottom-up
// i.e. find mvs for SBs and sub-SBs and see whether it's worthwhile merging.
- int ref1, ref2;
+ int ref1,ref2;
// Initialise //
////////////////
m_psort = my_buffer.GetPicture(pic_num).GetPparams().PicSort();
- if(m_psort.IsInter())
+ if (m_psort.IsInter())
{
// Extract the references
const vector<int>& refs = my_buffer.GetPicture(pic_num).GetPparams().Refs();
@@ -105,46 +105,46 @@ void ModeDecider::DoModeDecn(EncQueue& my_buffer, int pic_num)
ref1 = refs[0];
// The picture we're doing estimation from
- m_pic_data = &(my_buffer.GetPicture(pic_num).DataForME(m_encparams.CombinedME()));
+ m_pic_data = &(my_buffer.GetPicture( pic_num ).DataForME(m_encparams.CombinedME()) );
// Set up the hierarchy of motion vector data objects
- PicturePredParams predparams0 = *m_predparams;
- predparams0.SetXNumBlocks(m_predparams->XNumBlocks() / 4);
- predparams0.SetYNumBlocks(m_predparams->YNumBlocks() / 4);
+ PicturePredParams predparams0 = *m_predparams;
+ predparams0.SetXNumBlocks( m_predparams->XNumBlocks()/4 );
+ predparams0.SetYNumBlocks( m_predparams->YNumBlocks()/4 );
- PicturePredParams predparams1 = *m_predparams;
- predparams1.SetXNumBlocks(m_predparams->XNumBlocks() / 2);
- predparams1.SetYNumBlocks(m_predparams->YNumBlocks() / 2);
+ PicturePredParams predparams1 = *m_predparams;
+ predparams1.SetXNumBlocks( m_predparams->XNumBlocks()/2 );
+ predparams1.SetYNumBlocks( m_predparams->YNumBlocks()/2 );
- m_me_data_set[0] = new MEData(predparams0, num_refs);
- m_me_data_set[1] = new MEData(predparams1, num_refs);
+ m_me_data_set[0] = new MEData( predparams0, num_refs );
+ m_me_data_set[1] = new MEData( predparams1, num_refs );
m_me_data_set[2] = &my_buffer.GetPicture(pic_num).GetMEData();
// Set up the lambdas to use per block
- m_me_data_set[0]->SetLambdaMap(0 , m_me_data_set[2]->LambdaMap() , 1.0 / m_level_factor[0]);
- m_me_data_set[1]->SetLambdaMap(1 , m_me_data_set[2]->LambdaMap() , 1.0 / m_level_factor[1]);
+ m_me_data_set[0]->SetLambdaMap( 0 , m_me_data_set[2]->LambdaMap() , 1.0/m_level_factor[0] );
+ m_me_data_set[1]->SetLambdaMap( 1 , m_me_data_set[2]->LambdaMap() , 1.0/m_level_factor[1] );
// Set up the reference pictures
- m_ref1_updata = &(my_buffer.GetPicture(ref1).UpDataForME(m_encparams.CombinedME()));
+ m_ref1_updata = &(my_buffer.GetPicture( ref1 ).UpDataForME(m_encparams.CombinedME()) );
- if(num_refs > 1)
+ if (num_refs>1)
{
ref2 = refs[1];
- m_ref2_updata = &(my_buffer.GetPicture(ref2).UpDataForME(m_encparams.CombinedME()));
+ m_ref2_updata = &(my_buffer.GetPicture( ref2).UpDataForME(m_encparams.CombinedME()) );
// Create an object for computing bi-directional prediction calculations
- if(m_predparams->MVPrecision() == MV_PRECISION_EIGHTH_PIXEL)
- m_bicheckdiff = new BiBlockEighthPel(*m_ref1_updata ,
- *m_ref2_updata ,
- *m_pic_data);
- else if(m_predparams->MVPrecision() == MV_PRECISION_QUARTER_PIXEL)
- m_bicheckdiff = new BiBlockQuarterPel(*m_ref1_updata ,
+ if ( m_predparams->MVPrecision()==MV_PRECISION_EIGHTH_PIXEL )
+ m_bicheckdiff = new BiBlockEighthPel( *m_ref1_updata ,
*m_ref2_updata ,
- *m_pic_data);
+ *m_pic_data );
+ else if ( m_predparams->MVPrecision()==MV_PRECISION_QUARTER_PIXEL )
+ m_bicheckdiff = new BiBlockQuarterPel( *m_ref1_updata ,
+ *m_ref2_updata ,
+ *m_pic_data );
else
- m_bicheckdiff = new BiBlockHalfPel(*m_ref1_updata ,
- *m_ref2_updata ,
- *m_pic_data);
+ m_bicheckdiff = new BiBlockHalfPel( *m_ref1_updata ,
+ *m_ref2_updata ,
+ *m_pic_data );
}
else
{
@@ -153,34 +153,32 @@ void ModeDecider::DoModeDecn(EncQueue& my_buffer, int pic_num)
// Create an object for doing intra calculations
- m_intradiff = new IntraBlockDiff(*m_pic_data);
+ m_intradiff = new IntraBlockDiff( *m_pic_data );
// Loop over all the superblocks, doing the work //
///////////////////////////////////////////////////
- for(m_ysb_loc = 0 ; m_ysb_loc < m_predparams->YNumSB() ; ++m_ysb_loc)
- {
- for(m_xsb_loc = 0 ; m_xsb_loc < m_predparams->XNumSB(); ++m_xsb_loc)
- {
+ for (m_ysb_loc=0 ; m_ysb_loc<m_predparams->YNumSB() ; ++m_ysb_loc ){
+ for (m_xsb_loc=0 ; m_xsb_loc<m_predparams->XNumSB(); ++m_xsb_loc ){
DoSBDecn();
}//m_xsb_loc
}//m_ysb_loc
delete m_intradiff;
- if(num_refs > 1)
+ if (num_refs>1)
delete m_bicheckdiff;
}
// Finally, although not strictly part of motion estimation,
// we have to assign DC values for
// blocks we're decided are intra.
- SetDC(my_buffer , pic_num);
+ SetDC( my_buffer , pic_num );
}
void ModeDecider::DoSBDecn()
{
- // Does the mode decision for the given SB, in three stages
+ // Does the mode decision for the given SB, in three stages
// Start with 4x4 modes
DoLevelDecn(2);
@@ -190,7 +188,7 @@ void ModeDecider::DoSBDecn()
DoLevelDecn(1);
// Do 1x1 mode if merging worked before
- if(m_me_data_set[2]->SBCosts()[m_ysb_loc][m_xsb_loc] <= old_best_SB_cost)
+ if ( m_me_data_set[2]->SBCosts()[m_ysb_loc][m_xsb_loc] <= old_best_SB_cost)
{
old_best_SB_cost = m_me_data_set[2]->SBCosts()[m_ysb_loc][m_xsb_loc];
DoLevelDecn(0);
@@ -198,7 +196,7 @@ void ModeDecider::DoSBDecn()
}
-void ModeDecider::DoLevelDecn(int level)
+void ModeDecider::DoLevelDecn( int level )
{
// Computes the best costs if we were to
// stick to a decomposition at this level
@@ -208,35 +206,35 @@ void ModeDecider::DoLevelDecn(int level)
// for each constituent is different.
// The limits of the prediction units
- const int xstart = m_xsb_loc << level;
- const int ystart = m_ysb_loc << level;
+ const int xstart = m_xsb_loc <<level;
+ const int ystart = m_ysb_loc <<level;
- const int xend = xstart + (1 << level);
- const int yend = ystart + (1 << level);
+ const int xend = xstart + (1<<level);
+ const int yend = ystart + (1<<level);
// Case 1: prediction modes are all different
float SB_cost = 0.0;
- for(int j = ystart ; j < yend ; ++j)
+ for ( int j=ystart ; j<yend ; ++j)
{
- for(int i = xstart ; i < xend ; ++i)
- {
- if(level < 2)
- DoME(i , j , level);
- SB_cost += DoUnitDecn(i , j , level);
+ for (int i=xstart ; i<xend ; ++i)
+ {
+ if ( level<2 )
+ DoME( i , j , level);
+ SB_cost += DoUnitDecn( i , j ,level );
}// i
}// j
// if we've improved on the best cost, we should propagate data in
// the base level motion vector set
- if(level == 2)
+ if (level == 2)
{
m_me_data_set[2]->SBSplit()[m_ysb_loc][m_xsb_loc] = 2;
m_me_data_set[2]->SBCosts()[m_ysb_loc][m_xsb_loc] = SB_cost;
}
- if(level < 2 && SB_cost <= m_me_data_set[2]->SBCosts()[m_ysb_loc][m_xsb_loc])
+ if ( level<2 && SB_cost <= m_me_data_set[2]->SBCosts()[m_ysb_loc][m_xsb_loc] )
{
m_me_data_set[2]->SBCosts()[m_ysb_loc][m_xsb_loc] = SB_cost;
m_me_data_set[2]->SBSplit()[m_ysb_loc][m_xsb_loc] = level;
@@ -248,23 +246,23 @@ void ModeDecider::DoLevelDecn(int level)
int xblock_end;
int yblock_end;
- for(int j = ystart ; j < yend ; ++j)
+ for ( int j=ystart ; j<yend ; ++j )
{
- yblock_start = j << (2 - level);
- yblock_end = (j + 1) << (2 - level);
- for(int i = xstart ; i < xend ; ++i)
+ yblock_start = j<<(2-level);
+ yblock_end = (j+1)<<(2-level);
+ for ( int i=xstart ; i<xend ; ++i )
{
- xblock_start = i << (2 - level);
- xblock_end = (i + 1) << (2 - level);
+ xblock_start = i<<(2-level);
+ xblock_end = (i+1)<<(2-level);
- for(int v = yblock_start ; v < yblock_end ; ++v)
+ for ( int v=yblock_start ; v<yblock_end ; ++v )
{
- for(int u = xblock_start ; u < xblock_end ; ++u)
+ for ( int u=xblock_start ; u<xblock_end ; ++u )
{
m_me_data_set[2]->Mode()[v][u] = m_me_data_set[level]->Mode()[j][i];
- m_me_data_set[2]->DC(Y_COMP)[v][u] = m_me_data_set[level]->DC(Y_COMP)[j][i];
+ m_me_data_set[2]->DC( Y_COMP )[v][u] = m_me_data_set[level]->DC( Y_COMP )[j][i];
m_me_data_set[2]->Vectors(1)[v][u] = m_me_data_set[level]->Vectors(1)[j][i];
- if(num_refs > 1)
+ if ( num_refs>1 )
m_me_data_set[2]->Vectors(2)[v][u] = m_me_data_set[level]->Vectors(2)[j][i];
}// u
@@ -287,12 +285,12 @@ void ModeDecider::DoME(const int xpos , const int ypos , const int level)
const MEData& guide_data = *(m_me_data_set[level+1]);
// The corresponding location of the guide data
- const int guide_xpos = xpos << 1;
- const int guide_ypos = ypos << 1;
+ const int guide_xpos = xpos<<1;
+ const int guide_ypos = ypos<<1;
// The location of the lowest level vectors
- const int xblock = xpos << (2 - level);
- const int yblock = ypos << (2 - level);
+ const int xblock = xpos << ( 2 - level);
+ const int yblock = ypos << ( 2 - level);
// The list of potential candidate vectors
CandidateList cand_list;
@@ -303,80 +301,77 @@ void ModeDecider::DoME(const int xpos , const int ypos , const int level)
// The predicting motion vector
MVector mv_pred;
- for(int j = 0 ; j < 2 ; ++j)
- for(int i = 0 ; i < 2 ; ++i)
- AddNewVlist(cand_list , guide_data.Vectors(1)[guide_ypos+j][guide_xpos+i] , 0 , 0);
-
- if(xblock > 0 && yblock > 0)
- mv_pred = MvMedian(m_me_data_set[2]->Vectors(1)[yblock][xblock-1] ,
- m_me_data_set[2]->Vectors(1)[yblock-1][xblock-1],
- m_me_data_set[2]->Vectors(1)[yblock-1][xblock]);
- else if(xblock == 0 && yblock > 0)
- mv_pred = MvMean(m_me_data_set[2]->Vectors(1)[yblock-1][xblock],
- m_me_data_set[2]->Vectors(1)[yblock-1][xblock+1]);
- else if(xblock > 0 && yblock == 0)
- mv_pred = MvMean(m_me_data_set[2]->Vectors(1)[yblock][xblock-1],
- m_me_data_set[2]->Vectors(1)[yblock+1][xblock-1]);
- else
- {
+ for ( int j=0 ; j<2 ; ++j )
+ for (int i=0 ; i<2 ; ++i )
+ AddNewVlist( cand_list , guide_data.Vectors(1)[guide_ypos+j][guide_xpos+i] , 0 , 0 );
+
+ if (xblock>0 && yblock>0)
+ mv_pred = MvMedian( m_me_data_set[2]->Vectors(1)[yblock][xblock-1] ,
+ m_me_data_set[2]->Vectors(1)[yblock-1][xblock-1],
+ m_me_data_set[2]->Vectors(1)[yblock-1][xblock]);
+ else if (xblock==0 && yblock>0)
+ mv_pred = MvMean( m_me_data_set[2]->Vectors(1)[yblock-1][xblock],
+ m_me_data_set[2]->Vectors(1)[yblock-1][xblock+1]);
+ else if (xblock>0 && yblock==0)
+ mv_pred = MvMean( m_me_data_set[2]->Vectors(1)[yblock][xblock-1],
+ m_me_data_set[2]->Vectors(1)[yblock+1][xblock-1]);
+ else{
mv_pred.x = 0;
mv_pred.y = 0;
}
- BlockMatcher my_bmatch1(*m_pic_data ,
- *m_ref1_updata ,
- m_predparams->LumaBParams(level) ,
- m_predparams->MVPrecision(),
- me_data.Vectors(1) , me_data.PredCosts(1));
+ BlockMatcher my_bmatch1( *m_pic_data ,
+ *m_ref1_updata ,
+ m_predparams->LumaBParams(level) ,
+ m_predparams->MVPrecision(),
+ me_data.Vectors(1) , me_data.PredCosts(1) );
me_data.PredCosts(1)[ypos][xpos].total = 100000000.0f;
- my_bmatch1.FindBestMatchSubp(xpos , ypos , cand_list, mv_pred, lambda);
+ my_bmatch1.FindBestMatchSubp( xpos , ypos , cand_list, mv_pred, lambda );
- if(num_refs > 1)
- {
- //do the same for the other reference
+ if (num_refs>1)
+ {//do the same for the other reference
cand_list.clear();
- for(int j = 0 ; j < 2 ; ++j)
- for(int i = 0 ; i < 2 ; ++i)
- AddNewVlist(cand_list , guide_data.Vectors(2)[guide_ypos+j][guide_xpos+i] , 0 , 0);
-
- if(xblock > 0 && yblock > 0)
- mv_pred = MvMedian(m_me_data_set[2]->Vectors(2)[yblock][xblock-1] ,
- m_me_data_set[2]->Vectors(2)[yblock-1][xblock-1],
- m_me_data_set[2]->Vectors(2)[yblock-1][xblock]);
- else if(xblock == 0 && yblock > 0)
- mv_pred = MvMean(m_me_data_set[2]->Vectors(2)[yblock-1][xblock],
- m_me_data_set[2]->Vectors(2)[yblock-1][xblock+1]);
- else if(xblock > 0 && yblock == 0)
- mv_pred = MvMean(m_me_data_set[2]->Vectors(2)[yblock][xblock-1],
- m_me_data_set[2]->Vectors(2)[yblock+1][xblock-1]);
- else
- {
- mv_pred.x = 0;
- mv_pred.y = 0;
+ for ( int j=0 ; j<2 ; ++j )
+ for (int i=0 ; i<2 ; ++i )
+ AddNewVlist( cand_list , guide_data.Vectors(2)[guide_ypos+j][guide_xpos+i] , 0 , 0 );
+
+ if (xblock>0 && yblock>0)
+ mv_pred = MvMedian( m_me_data_set[2]->Vectors(2)[yblock][xblock-1] ,
+ m_me_data_set[2]->Vectors(2)[yblock-1][xblock-1],
+ m_me_data_set[2]->Vectors(2)[yblock-1][xblock]);
+ else if (xblock==0 && yblock>0)
+ mv_pred = MvMean( m_me_data_set[2]->Vectors(2)[yblock-1][xblock],
+ m_me_data_set[2]->Vectors(2)[yblock-1][xblock+1]);
+ else if (xblock>0 && yblock==0)
+ mv_pred = MvMean( m_me_data_set[2]->Vectors(2)[yblock][xblock-1],
+ m_me_data_set[2]->Vectors(2)[yblock+1][xblock-1]);
+ else{
+ mv_pred.x = 0;
+ mv_pred.y = 0;
}
- BlockMatcher my_bmatch2(*m_pic_data ,
- *m_ref2_updata ,
- m_predparams->LumaBParams(level) ,
- m_predparams->MVPrecision(),
- me_data.Vectors(2) , me_data.PredCosts(2));
+ BlockMatcher my_bmatch2( *m_pic_data ,
+ *m_ref2_updata ,
+ m_predparams->LumaBParams(level) ,
+ m_predparams->MVPrecision(),
+ me_data.Vectors(2) , me_data.PredCosts(2) );
me_data.PredCosts(2)[ypos][xpos].total = 100000000.0f;
- my_bmatch2.FindBestMatchSubp(xpos , ypos , cand_list, mv_pred, lambda);
+ my_bmatch2.FindBestMatchSubp( xpos , ypos , cand_list, mv_pred, lambda );
- }
+ }
}
-float ModeDecider::DoUnitDecn(const int xpos , const int ypos , const int level)
+float ModeDecider::DoUnitDecn(const int xpos , const int ypos , const int level )
{
// For a given prediction unit (SB, subSB or block) find the best
// mode, given that the REF1 and REF2 motion estimation has
// already been done.
- MEData& me_data = *(m_me_data_set[level]);
+ MEData& me_data = *( m_me_data_set[level] );
// Coords of the top-leftmost block belonging to this unit
// const int xblock = xpos<<(2-level);
@@ -391,9 +386,9 @@ float ModeDecider::DoUnitDecn(const int xpos , const int ypos , const int level)
BlockDiffParams dparams;
- dparams.SetBlockLimits(m_predparams->LumaBParams(level) , *m_pic_data, xpos , ypos);
+ dparams.SetBlockLimits( m_predparams->LumaBParams( level ) , *m_pic_data, xpos , ypos);
- // First check REF1 costs //
+ // First check REF1 costs //
/**************************/
// mode_cost = ModeCost( xblock , yblock )*m_mode_factor[level];
@@ -402,15 +397,15 @@ float ModeDecider::DoUnitDecn(const int xpos , const int ypos , const int level)
min_unit_cost = me_data.PredCosts(1)[ypos][xpos].total + mode_cost;
best_SAD_value = me_data.PredCosts(1)[ypos][xpos].SAD;
- if(num_refs > 1)
+ if (num_refs>1)
{
- // Next check REF2 costs //
- /*************************/
+ // Next check REF2 costs //
+ /*************************/
// mode_cost = ModeCost( xblock , yblock )*m_mode_factor[level];
me_data.PredCosts(2)[ypos][xpos].total *= m_level_factor[level];
unit_cost = me_data.PredCosts(2)[ypos][xpos].total + mode_cost;
- if(unit_cost < min_unit_cost)
+ if ( unit_cost<min_unit_cost )
{
me_data.Mode()[ypos][xpos] = REF2_ONLY;
min_unit_cost = unit_cost;
@@ -422,19 +417,19 @@ float ModeDecider::DoUnitDecn(const int xpos , const int ypos , const int level)
// mode_cost = ModeCost( xpos , ypos )*m_mode_factor[level];
me_data.BiPredCosts()[ypos][xpos].mvcost =
- me_data.PredCosts(1)[ypos][xpos].mvcost +
- me_data.PredCosts(2)[ypos][xpos].mvcost;
+ me_data.PredCosts(1)[ypos][xpos].mvcost+
+ me_data.PredCosts(2)[ypos][xpos].mvcost;
me_data.BiPredCosts()[ypos][xpos].SAD = m_bicheckdiff->Diff(dparams ,
- me_data.Vectors(1)[ypos][xpos] ,
- me_data.Vectors(2)[ypos][xpos]);
+ me_data.Vectors(1)[ypos][xpos] ,
+ me_data.Vectors(2)[ypos][xpos] );
- me_data.BiPredCosts()[ypos][xpos].SetTotal(loc_lambda);
+ me_data.BiPredCosts()[ypos][xpos].SetTotal( loc_lambda );
me_data.BiPredCosts()[ypos][xpos].total *= m_level_factor[level];
unit_cost = me_data.BiPredCosts()[ypos][xpos].total + mode_cost;
- if(unit_cost < min_unit_cost)
+ if ( unit_cost<min_unit_cost )
{
me_data.Mode()[ypos][xpos] = REF1AND2;
min_unit_cost = unit_cost;
@@ -446,17 +441,17 @@ float ModeDecider::DoUnitDecn(const int xpos , const int ypos , const int level)
// Calculate the cost if we were to code the block as intra //
/************************************************************/
- if(level == 2 && best_SAD_value > 4.0 * m_predparams->LumaBParams(level).Xblen()*
- m_predparams->LumaBParams(level).Yblen())
+ if ( level==2 && best_SAD_value> 4.0*m_predparams->LumaBParams( level ).Xblen()*
+ m_predparams->LumaBParams( level ).Yblen() )
{
// mode_cost = ModeCost( xblock , yblock ) * m_mode_factor[level];
- me_data.IntraCosts()[ypos][xpos] = m_intradiff->Diff(dparams , me_data.DC(Y_COMP)[ypos][xpos]);
-// me_data.IntraCosts()[ypos][xpos] += loc_lambda *
+ me_data.IntraCosts()[ypos][xpos] = m_intradiff->Diff( dparams , me_data.DC( Y_COMP )[ypos][xpos] );
+// me_data.IntraCosts()[ypos][xpos] += loc_lambda *
// GetDCVar( me_data.DC( Y_COMP )[ypos][xpos] , GetDCPred( xblock , yblock ) );
me_data.IntraCosts()[ypos][xpos] *= m_level_factor[level];
unit_cost = me_data.IntraCosts()[ypos][xpos] + mode_cost;
- if(unit_cost < min_unit_cost && me_data.IntraCosts()[ypos][xpos] < 0.85 * best_SAD_value)
+ if ( unit_cost<min_unit_cost && me_data.IntraCosts()[ypos][xpos]<0.85*best_SAD_value)
{
me_data.Mode()[ypos][xpos] = INTRA;
min_unit_cost = unit_cost;
@@ -466,16 +461,16 @@ float ModeDecider::DoUnitDecn(const int xpos , const int ypos , const int level)
return min_unit_cost;
}
-ValueType ModeDecider::GetDCPred(int xblock , int yblock)
+ValueType ModeDecider::GetDCPred( int xblock , int yblock )
{
ValueType dc_pred = 0;
- if(xblock > 0 && m_me_data_set[2]->Mode()[yblock][xblock-1] == INTRA)
+ if ( xblock>0 && m_me_data_set[2]->Mode()[yblock][xblock-1] == INTRA )
{
- dc_pred = m_me_data_set[2]->DC(Y_COMP)[yblock][xblock-1];
- if(yblock > 0 && m_me_data_set[2]->Mode()[yblock-1][xblock] == INTRA)
+ dc_pred = m_me_data_set[2]->DC( Y_COMP )[yblock][xblock-1];
+ if ( yblock>0 && m_me_data_set[2]->Mode()[yblock-1][xblock] == INTRA )
{
- dc_pred += m_me_data_set[2]->DC(Y_COMP)[yblock-1][xblock];
+ dc_pred += m_me_data_set[2]->DC( Y_COMP )[yblock-1][xblock];
dc_pred >>= 1;
}
}
@@ -489,95 +484,90 @@ float ModeDecider::ModeCost(const int xindex , const int yindex)
// First, get a prediction for the mode
unsigned int mode_predictor = (unsigned int)(REF1_ONLY);
- const TwoDArray<PredMode>& preddata(m_me_data_set[2]->Mode());
+ const TwoDArray<PredMode>& preddata( m_me_data_set[2]->Mode() );
- unsigned int num_ref1_nbrs(0);
- unsigned int num_ref2_nbrs(0);
+ unsigned int num_ref1_nbrs( 0 );
+ unsigned int num_ref2_nbrs( 0 );
- if(xindex > 0 && yindex > 0)
+ if (xindex > 0 && yindex > 0)
{
- num_ref1_nbrs += ((unsigned int)(preddata[yindex-1][xindex])) & 1;
- num_ref1_nbrs += ((unsigned int)(preddata[yindex-1][xindex-1])) & 1;
- num_ref1_nbrs += ((unsigned int)(preddata[yindex][xindex-1])) & 1;
+ num_ref1_nbrs += ((unsigned int)( preddata[yindex-1][xindex] ) ) & 1;
+ num_ref1_nbrs += ((unsigned int)( preddata[yindex-1][xindex-1] ) ) & 1;
+ num_ref1_nbrs += ((unsigned int)( preddata[yindex][xindex-1] ) ) & 1;
- mode_predictor = num_ref1_nbrs >> 1;
+ mode_predictor = num_ref1_nbrs>>1;
- num_ref2_nbrs += ((unsigned int)(preddata[yindex-1][xindex])) & 2;
- num_ref2_nbrs += ((unsigned int)(preddata[yindex-1][xindex-1])) & 2;
- num_ref2_nbrs += ((unsigned int)(preddata[yindex][xindex-1])) & 2;
+ num_ref2_nbrs += ((unsigned int)( preddata[yindex-1][xindex] ) ) & 2;
+ num_ref2_nbrs += ((unsigned int)( preddata[yindex-1][xindex-1] ) ) & 2;
+ num_ref2_nbrs += ((unsigned int)( preddata[yindex][xindex-1] ) ) & 2;
num_ref2_nbrs >>= 1;
- mode_predictor ^= ((num_ref2_nbrs >> 1) << 1);
+ mode_predictor ^= ( (num_ref2_nbrs>>1)<<1 );
}
- else if(xindex > 0 && yindex == 0)
- mode_predictor = (unsigned int)(preddata[0][xindex-1]);
- else if(xindex == 0 && yindex > 0)
- mode_predictor = (unsigned int)(preddata[yindex-1][0]);
+ else if (xindex > 0 && yindex == 0)
+ mode_predictor = (unsigned int)( preddata[0][xindex-1] );
+ else if (xindex == 0 && yindex > 0)
+ mode_predictor = (unsigned int)( preddata[yindex-1][0] );
- unsigned int var = (mode_predictor & 1) + ((mode_predictor >> 1) & 1);
+ unsigned int var = (mode_predictor & 1)+((mode_predictor>>1) &1);
- return var * m_me_data_set[2]->LambdaMap()[yindex][xindex];
+ return var*m_me_data_set[2]->LambdaMap()[yindex][xindex];
}
-float ModeDecider::GetDCVar(const ValueType dc_val , const ValueType dc_pred)
+float ModeDecider::GetDCVar( const ValueType dc_val , const ValueType dc_pred)
{
- return 4.0 * std::abs(static_cast<float>(dc_val - dc_pred));
+ return 4.0*std::abs( static_cast<float>( dc_val - dc_pred ) );
}
ValueType ModeDecider::GetBlockDC(const PicArray& pic_data,
- int xunit , int yunit , int split, CompSort cs)
+ int xunit , int yunit , int split, CompSort cs)
{
BlockDiffParams dparams;
- if(cs != Y_COMP)
- dparams.SetBlockLimits(m_predparams->ChromaBParams(split) ,
- pic_data, xunit , yunit);
+ if ( cs!=Y_COMP )
+ dparams.SetBlockLimits( m_predparams->ChromaBParams( split ) ,
+ pic_data, xunit , yunit);
else
- dparams.SetBlockLimits(m_predparams->LumaBParams(split) ,
- pic_data, xunit , yunit);
+ dparams.SetBlockLimits( m_predparams->LumaBParams( split ) ,
+ pic_data, xunit , yunit);
- IntraBlockDiff intradiff(pic_data);
+ IntraBlockDiff intradiff( pic_data );
- return intradiff.CalcDC(dparams);
+ return intradiff.CalcDC( dparams );
}
-void ModeDecider::SetDC(const PicArray& pic_data , MEData& me_data , CompSort cs)
+void ModeDecider::SetDC( const PicArray& pic_data , MEData& me_data , CompSort cs )
{
- TwoDArray<ValueType>& dcarray = me_data.DC(cs);
- TwoDArray<ValueType> temp_dcarray(dcarray.LengthY(), dcarray.LengthX());
+ TwoDArray<ValueType>& dcarray = me_data.DC( cs );
+ TwoDArray<ValueType> temp_dcarray (dcarray.LengthY(), dcarray.LengthX() );
- for(int y = 0 ; y < dcarray.LengthY() ; ++y)
- {
- for(int x = 0 ; x < dcarray.LengthX() ; ++x)
- {
- temp_dcarray[y][x] = GetBlockDC(pic_data , x , y , 2, cs);
+ for ( int y=0 ; y<dcarray.LengthY() ; ++y ){
+ for ( int x=0 ; x<dcarray.LengthX() ; ++x ){
+ temp_dcarray[y][x] = GetBlockDC( pic_data , x , y , 2, cs );
}
}
- for(int x = 0 ; x < dcarray.LengthX() ; ++x)
- {
+ for ( int x=0 ; x<dcarray.LengthX() ; ++x ){
dcarray[0][x] = temp_dcarray[0][x];
}
- for(int y = 1 ; y < dcarray.LengthY() - 1 ; ++y)
- {
+ for ( int y=1 ; y<dcarray.LengthY()-1 ; ++y ){
dcarray[y][0] = temp_dcarray[y][0];
- for(int x = 1 ; x < dcarray.LengthX() - 1 ; ++x)
- {
- dcarray[y][x] = (temp_dcarray[y-1][x-1] + 3 * temp_dcarray[y-1][x] + temp_dcarray[y-1][x+1] +
- 3 * temp_dcarray[y][x-1] + 3 * temp_dcarray[y][x+1] +
- temp_dcarray[y+1][x-1] + 3 * temp_dcarray[y+1][x] + temp_dcarray[y+1][x+1] + 8) >> 4;
- }
+ for ( int x=1 ; x<dcarray.LengthX()-1 ; ++x ){
+ dcarray[y][x] = (temp_dcarray[y-1][x-1]+3*temp_dcarray[y-1][x]+temp_dcarray[y-1][x+1]+
+ 3*temp_dcarray[y][x-1]+ 3*temp_dcarray[y][x+1]+
+ temp_dcarray[y+1][x-1]+3*temp_dcarray[y+1][x]+temp_dcarray[y+1][x+1]+8 )>>4;
+ }
dcarray[y][dcarray.LastX()] = temp_dcarray[y][dcarray.LastX()];
}
}
-void ModeDecider::SetDC(EncQueue& my_buffer , int pic_num)
+void ModeDecider::SetDC( EncQueue& my_buffer , int pic_num )
{
MEData& me_data = my_buffer.GetPicture(pic_num).GetMEData();
- SetDC(my_buffer.GetPicture(pic_num).OrigData(Y_COMP) , me_data , Y_COMP);
- SetDC(my_buffer.GetPicture(pic_num).OrigData(U_COMP) , me_data , U_COMP);
- SetDC(my_buffer.GetPicture(pic_num).OrigData(V_COMP) , me_data , V_COMP);
+ SetDC( my_buffer.GetPicture( pic_num ).OrigData(Y_COMP) , me_data , Y_COMP );
+ SetDC( my_buffer.GetPicture( pic_num ).OrigData(U_COMP) , me_data , U_COMP );
+ SetDC( my_buffer.GetPicture( pic_num ).OrigData(V_COMP) , me_data , V_COMP );
}
diff --git a/src/filters/parser/DiracSplitter/libdirac/libdirac_motionest/me_mode_decn.h b/src/filters/parser/DiracSplitter/libdirac/libdirac_motionest/me_mode_decn.h
index fd0df3339..08f4b6e00 100644
--- a/src/filters/parser/DiracSplitter/libdirac/libdirac_motionest/me_mode_decn.h
+++ b/src/filters/parser/DiracSplitter/libdirac/libdirac_motionest/me_mode_decn.h
@@ -43,124 +43,124 @@
namespace dirac
{
-class EncQueue;
-
-//! Decides between superblock and block prediction modes.
-/*!
- Loops over all the superblocks and decides on the best modes. A
- superblock is a square of 16 blocks. There are three possible
- splitting levels:
- level 0 means the superblock is considered as a single block;
- level 1 means the superblock is considered as 4 larger blocks,
- termed sub-superblocks;
- level 0 means the superblock is split right down to blocks.
-
- In deciding which modes
- to adopt, the ModeDecider object calculates costs for all
- permutations, doing motion estimation for the level 1 and level 0
- modes as these have not been calculated before.
- The process of decision for each is as follows. For each SB, we loop
- over the levels, and call DoLevelDecn. DoLevelDecn does motion
- estimation if it's necessary. Then it assumes that we don't have a
- common block mode and calls DoUnitDecn which finds the best mode for
- each unit in the SB at that level, individually. When we've got a
- best cost for that level we go up to the next one.
- */
-class ModeDecider
-{
+ class EncQueue;
-public:
- //! Constructor
+ //! Decides between superblock and block prediction modes.
/*!
- The constructor creates arrays for handling the motion vector data
- at splitting levels 0 and 1, as motion
- estimation must be performed for these levels.
+ Loops over all the superblocks and decides on the best modes. A
+ superblock is a square of 16 blocks. There are three possible
+ splitting levels:
+ level 0 means the superblock is considered as a single block;
+ level 1 means the superblock is considered as 4 larger blocks,
+ termed sub-superblocks;
+ level 0 means the superblock is split right down to blocks.
+
+ In deciding which modes
+ to adopt, the ModeDecider object calculates costs for all
+ permutations, doing motion estimation for the level 1 and level 0
+ modes as these have not been calculated before.
+ The process of decision for each is as follows. For each SB, we loop
+ over the levels, and call DoLevelDecn. DoLevelDecn does motion
+ estimation if it's necessary. Then it assumes that we don't have a
+ common block mode and calls DoUnitDecn which finds the best mode for
+ each unit in the SB at that level, individually. When we've got a
+ best cost for that level we go up to the next one.
*/
- ModeDecider(const EncoderParams& encp);
+ class ModeDecider
+ {
- //! Destructor
- /*!
- The destructor destroys the classes created in the constructor
- */
- ~ModeDecider();
+ public:
+ //! Constructor
+ /*!
+ The constructor creates arrays for handling the motion vector data
+ at splitting levels 0 and 1, as motion
+ estimation must be performed for these levels.
+ */
+ ModeDecider(const EncoderParams& encp );
- //! Does the actual mode decision
- /*!
- Does the mode decision
- \param my_buffer the buffer of all the relevant frames
- \param pic_num the picture number for which motion estimation is being done
- */
- void DoModeDecn(EncQueue& my_buffer , int pic_num);
+ //! Destructor
+ /*!
+ The destructor destroys the classes created in the constructor
+ */
+ ~ModeDecider();
+
+ //! Does the actual mode decision
+ /*!
+ Does the mode decision
+ \param my_buffer the buffer of all the relevant frames
+ \param pic_num the picture number for which motion estimation is being done
+ */
+ void DoModeDecn( EncQueue& my_buffer , int pic_num );
-private:
- ModeDecider(const ModeDecider& cpy); //private, body-less copy constructor: this class should not be copied
- ModeDecider& operator=(const ModeDecider& rhs); //private, body-less assignment=: this class should not be assigned
+ private:
+ ModeDecider( const ModeDecider& cpy );//private, body-less copy constructor: this class should not be copied
+ ModeDecider& operator=( const ModeDecider& rhs );//private, body-less assignment=: this class should not be assigned
- //functions
- void DoSBDecn(); //called by do_mode_decn for each SB
+ //functions
+ void DoSBDecn(); //called by do_mode_decn for each SB
- //! Make a mode decision given a particular level of decomposition
- void DoLevelDecn(int level);
+ //! Make a mode decision given a particular level of decomposition
+ void DoLevelDecn( int level );
- //! Decide on a mode for a given prediction unit (block, sub-SB or SB)
- float DoUnitDecn(const int xpos , const int ypos , const int level);
+ //! Decide on a mode for a given prediction unit (block, sub-SB or SB)
+ float DoUnitDecn( const int xpos , const int ypos , const int level );
- //! Do motion estimation for a prediction unit at a given level
- void DoME(const int xpos , const int ypos , const int level);
+ //! Do motion estimation for a prediction unit at a given level
+ void DoME( const int xpos , const int ypos , const int level );
- //! Return a measure of the cost of coding a given mode
- float ModeCost(const int xindex , const int yindex);
+ //! Return a measure of the cost of coding a given mode
+ float ModeCost( const int xindex , const int yindex );
- //! Get a prediction for the dc value of a block
- ValueType GetDCPred(int xblock , int yblock);
+ //! Get a prediction for the dc value of a block
+ ValueType GetDCPred( int xblock , int yblock );
- //! Get a measure of DC value variance
- float GetDCVar(const ValueType dc_val , const ValueType dc_pred);
+ //! Get a measure of DC value variance
+ float GetDCVar( const ValueType dc_val , const ValueType dc_pred);
- //! Go through all the intra blocks and extract the chroma dc values to be coded
- void SetDC(EncQueue& my_buffer, int pic_num);
+ //! Go through all the intra blocks and extract the chroma dc values to be coded
+ void SetDC( EncQueue& my_buffer, int pic_num);
- //! Called by previous fn for each component
- void SetDC(const PicArray& pic_data, MEData& me_data, CompSort cs);
+ //! Called by previous fn for each component
+ void SetDC(const PicArray& pic_data, MEData& me_data,CompSort cs);
- //! Called by previous fn for each block
- ValueType GetBlockDC(const PicArray& pic_data, int xloc, int yloc, int split, CompSort cs);
+ //! Called by previous fn for each block
+ ValueType GetBlockDC(const PicArray& pic_data, int xloc,int yloc,int split, CompSort cs);
- // Member data
- PictureSort m_psort;
+ // Member data
+ PictureSort m_psort;
- //! A local reference to the encoder parameters
- const EncoderParams& m_encparams;
+ //! A local reference to the encoder parameters
+ const EncoderParams& m_encparams;
- //! A local pointer to the picture prediction params
- const PicturePredParams* m_predparams;
+ //! A local pointer to the picture prediction params
+ const PicturePredParams* m_predparams;
- //! The Lagrangian parameter for motion estimation
- float m_lambda;
+ //! The Lagrangian parameter for motion estimation
+ float m_lambda;
- //! Correction factor for comparing SAD costs for different SB splittings
- OneDArray<float> m_level_factor;
+ //! Correction factor for comparing SAD costs for different SB splittings
+ OneDArray<float> m_level_factor;
- //! Correction factor for comparing mode costs for different SB splittings
- OneDArray<float> m_mode_factor;
+ //! Correction factor for comparing mode costs for different SB splittings
+ OneDArray<float> m_mode_factor;
- //! Motion vector data for each level of splitting
- OneDArray< MEData* > m_me_data_set;
+ //! Motion vector data for each level of splitting
+ OneDArray< MEData* > m_me_data_set;
- const PicArray* m_pic_data;
- const PicArray* m_ref1_updata;
- const PicArray* m_ref2_updata;
- int num_refs;
+ const PicArray* m_pic_data;
+ const PicArray* m_ref1_updata;
+ const PicArray* m_ref2_updata;
+ int num_refs;
- IntraBlockDiff* m_intradiff;
- BiBlockDiff* m_bicheckdiff;
+ IntraBlockDiff* m_intradiff;
+ BiBlockDiff* m_bicheckdiff;
- //position variables, used in all the mode decisions
- int m_xsb_loc, m_ysb_loc; //coords of the current SB
+ //position variables, used in all the mode decisions
+ int m_xsb_loc,m_ysb_loc; //coords of the current SB
-};
+ };
} // namespace dirac
diff --git a/src/filters/parser/DiracSplitter/libdirac/libdirac_motionest/me_subpel.cpp b/src/filters/parser/DiracSplitter/libdirac/libdirac_motionest/me_subpel.cpp
index 9d204f638..51376808b 100644
--- a/src/filters/parser/DiracSplitter/libdirac/libdirac_motionest/me_subpel.cpp
+++ b/src/filters/parser/DiracSplitter/libdirac/libdirac_motionest/me_subpel.cpp
@@ -62,23 +62,23 @@ SubpelRefine::SubpelRefine(const EncoderParams& encp):
}
-void SubpelRefine::DoSubpel(EncQueue& my_buffer, int pic_num)
+void SubpelRefine::DoSubpel( EncQueue& my_buffer,int pic_num )
{
- m_predparams = &(my_buffer.GetPicture(pic_num).GetMEData().GetPicPredParams());
+ m_predparams = &(my_buffer.GetPicture(pic_num).GetMEData().GetPicPredParams() );
//main loop for the subpel refinement
- int ref1, ref2;
+ int ref1,ref2;
const PictureSort psort = my_buffer.GetPicture(pic_num).GetPparams().PicSort();
- if(psort.IsInter())
+ if (psort.IsInter())
{
// Get the references
const vector<int>& refs = my_buffer.GetPicture(pic_num).GetPparams().Refs();
int num_refs = refs.size();
ref1 = refs[0];
- if(num_refs > 1)
+ if (num_refs>1)
ref2 = refs[1];
else
ref2 = ref1;
@@ -87,19 +87,19 @@ void SubpelRefine::DoSubpel(EncQueue& my_buffer, int pic_num)
const PicArray& refup1_data = my_buffer.GetPicture(ref1).UpDataForME(m_encparams.CombinedME());
const PicArray& refup2_data = my_buffer.GetPicture(ref2).UpDataForME(m_encparams.CombinedME());
- MEData& me_data = my_buffer.GetPicture(pic_num).GetMEData();
+ MEData& me_data = my_buffer.GetPicture(pic_num).GetMEData();
// Now match the pictures
- MatchPic(pic_data , refup1_data , me_data , 1);
+ MatchPic( pic_data , refup1_data , me_data ,1 );
- if(ref1 != ref2)
- MatchPic(pic_data , refup2_data , me_data , 2);
+ if (ref1 != ref2 )
+ MatchPic( pic_data , refup2_data , me_data ,2 );
}
}
void SubpelRefine::MatchPic(const PicArray& pic_data , const PicArray& refup_data , MEData& me_data ,
- int ref_id)
+ int ref_id)
{
// Match a picture against a single reference. Loop over all the blocks
// doing the matching
@@ -108,66 +108,64 @@ void SubpelRefine::MatchPic(const PicArray& pic_data , const PicArray& refup_dat
////////////////////
// Provide aliases for the appropriate motion vector data components
- MvArray& mv_array = me_data.Vectors(ref_id);
- TwoDArray<MvCostData>& pred_costs = me_data.PredCosts(ref_id);
+ MvArray& mv_array = me_data.Vectors( ref_id );
+ TwoDArray<MvCostData>& pred_costs = me_data.PredCosts( ref_id );
// Provide a block matching object to do the work
- BlockMatcher my_bmatch(pic_data , refup_data , m_predparams->LumaBParams(2) ,
- m_predparams->MVPrecision() , mv_array , pred_costs);
+ BlockMatcher my_bmatch( pic_data , refup_data , m_predparams->LumaBParams(2) ,
+ m_predparams->MVPrecision() , mv_array , pred_costs );
// Do the work //
/////////////////
// Loop over all the blocks, doing the work
- for(int yblock = 0 ; yblock < m_predparams->YNumBlocks() ; ++yblock)
- {
- for(int xblock = 0 ; xblock < m_predparams->XNumBlocks() ; ++xblock)
- {
- DoBlock(xblock , yblock , my_bmatch , me_data , ref_id);
+ for (int yblock=0 ; yblock<m_predparams->YNumBlocks() ; ++yblock){
+ for (int xblock=0 ; xblock<m_predparams->XNumBlocks() ; ++xblock){
+ DoBlock(xblock , yblock , my_bmatch , me_data , ref_id );
}// xblock
}// yblock
}
void SubpelRefine::DoBlock(const int xblock , const int yblock ,
- BlockMatcher& my_bmatch, MEData& me_data , const int ref_id)
+ BlockMatcher& my_bmatch, MEData& me_data , const int ref_id )
{
// For each block, home into the sub-pixel vector
// Provide aliases for the appropriate motion vector data components
- MvArray& mv_array = me_data.Vectors(ref_id);
+ MvArray& mv_array = me_data.Vectors( ref_id );
- const MVector mv_pred = GetPred(xblock , yblock , mv_array);
+ const MVector mv_pred = GetPred( xblock , yblock , mv_array );
const float loc_lambda = me_data.LambdaMap()[yblock][xblock];
- my_bmatch.RefineMatchSubp(xblock , yblock , mv_pred, loc_lambda);
+ my_bmatch.RefineMatchSubp( xblock , yblock , mv_pred, loc_lambda );
}
-MVector SubpelRefine::GetPred(int xblock, int yblock, const MvArray& mvarray)
+MVector SubpelRefine::GetPred(int xblock,int yblock,const MvArray& mvarray)
{
MVector mv_pred;
ImageCoords n_coords;
vector<MVector> neighbours;
- if(xblock > 0 && yblock > 0 && xblock < mvarray.LastX())
+ if (xblock>0 && yblock>0 && xblock<mvarray.LastX())
{
- for(int i = 0 ; i < m_nshift.Length() ; ++i)
+ for (int i=0 ; i<m_nshift.Length() ; ++i)
{
- n_coords.x = xblock + m_nshift[i].x;
- n_coords.y = yblock + m_nshift[i].y;
+ n_coords.x = xblock+m_nshift[i].x;
+ n_coords.y = yblock+m_nshift[i].y;
neighbours.push_back(mvarray[n_coords.y][n_coords.x]);
}// i
}
else
{
- for(int i = 0 ; i < m_nshift.Length(); ++i)
+ for (int i=0 ; i<m_nshift.Length(); ++i )
{
- n_coords.x = xblock + m_nshift[i].x;
- n_coords.y = yblock + m_nshift[i].y;
- if(n_coords.x >= 0 && n_coords.y >= 0 && n_coords.x < mvarray.LengthX() && n_coords.y < mvarray.LengthY())
+ n_coords.x = xblock+m_nshift[i].x;
+ n_coords.y = yblock+m_nshift[i].y;
+ if (n_coords.x>=0 && n_coords.y>=0 && n_coords.x<mvarray.LengthX() && n_coords.y<mvarray.LengthY())
neighbours.push_back(mvarray[n_coords.y][n_coords.x]);
}// i
}
diff --git a/src/filters/parser/DiracSplitter/libdirac/libdirac_motionest/me_subpel.h b/src/filters/parser/DiracSplitter/libdirac/libdirac_motionest/me_subpel.h
index 7038f90d2..bd5724928 100644
--- a/src/filters/parser/DiracSplitter/libdirac/libdirac_motionest/me_subpel.h
+++ b/src/filters/parser/DiracSplitter/libdirac/libdirac_motionest/me_subpel.h
@@ -44,71 +44,71 @@
namespace dirac
{
-class EncQueue;
-class MvData;
-class PicArray;
-
-//! The SubpelRefine class takes pixel-accurate motion vectors and refines them to 1/8-pixel accuracy
-/*!
- The SubpelRefine class takes pixel-accurate motion vectors and refines
- them to 1/8-pixel accuracy. It uses references upconverted by a factor
- of 2 in each dimension, with the remaining precision gained by doing
- linear interpolation between values on-the-fly.
- */
-class SubpelRefine
-{
-public:
- //! Constructor
+ class EncQueue;
+ class MvData;
+ class PicArray;
+
+ //! The SubpelRefine class takes pixel-accurate motion vectors and refines them to 1/8-pixel accuracy
/*!
- The constructor initialises the encoder parameters.
- \param encp the parameters used for controlling ME/MC
+ The SubpelRefine class takes pixel-accurate motion vectors and refines
+ them to 1/8-pixel accuracy. It uses references upconverted by a factor
+ of 2 in each dimension, with the remaining precision gained by doing
+ linear interpolation between values on-the-fly.
*/
- SubpelRefine(const EncoderParams& encp);
+ class SubpelRefine
+ {
+ public:
+ //! Constructor
+ /*!
+ The constructor initialises the encoder parameters.
+ \param encp the parameters used for controlling ME/MC
+ */
+ SubpelRefine(const EncoderParams& encp);
- //! Destructor
- ~SubpelRefine() {}
+ //! Destructor
+ ~SubpelRefine(){}
- //! Does the actual sub-pixel refinement
- /*!
- Does the actual sub-pixel refinement.
- \param my_buffer the buffer of pictures being used
- \param pic_num the picture number on which motion estimation is being performed
- */
- void DoSubpel(EncQueue& my_buffer , int pic_num);
+ //! Does the actual sub-pixel refinement
+ /*!
+ Does the actual sub-pixel refinement.
+ \param my_buffer the buffer of pictures being used
+ \param pic_num the picture number on which motion estimation is being performed
+ */
+ void DoSubpel( EncQueue& my_buffer , int pic_num );
-private:
- //! Private, body-less copy constructor: this class should not be copied
- SubpelRefine(const SubpelRefine& cpy);
+ private:
+ //! Private, body-less copy constructor: this class should not be copied
+ SubpelRefine( const SubpelRefine& cpy );
- //! Private, body-less assignment=: this class should not be assigned
- SubpelRefine& operator=(const SubpelRefine& rhs);
+ //! Private, body-less assignment=: this class should not be assigned
+ SubpelRefine& operator=( const SubpelRefine& rhs );
- //! Match a picture from its (upconverted) reference, and record the block mvs
- void MatchPic(const PicArray& pic_data , const PicArray& refup_data , MEData& me_data ,
- int ref_id);
+ //! Match a picture from its (upconverted) reference, and record the block mvs
+ void MatchPic(const PicArray& pic_data , const PicArray& refup_data , MEData& me_data ,
+ int ref_id);
- //! Match an individual block
- void DoBlock(const int xblock , const int yblock ,
- BlockMatcher& my_bmatch, MEData& me_data , const int ref_id);
+ //! Match an individual block
+ void DoBlock( const int xblock , const int yblock ,
+ BlockMatcher& my_bmatch, MEData& me_data , const int ref_id );
- //! Get a prediction for a block MV from the neighbouring blocks
- MVector GetPred(int xblock , int yblock , const MvArray& mvarray);
+ //! Get a prediction for a block MV from the neighbouring blocks
+ MVector GetPred( int xblock , int yblock , const MvArray& mvarray );
- //member variables
+ //member variables
- //! Local reference to the encoder params
- const EncoderParams& m_encparams;
+ //! Local reference to the encoder params
+ const EncoderParams& m_encparams;
- //! A local pointer to the encoder params
- const PicturePredParams* m_predparams;
+ //! A local pointer to the encoder params
+ const PicturePredParams* m_predparams;
- //! The list of candidate vectors being tested
- CandidateList m_cand_list;
+ //! The list of candidate vectors being tested
+ CandidateList m_cand_list;
- //! The relative coords of the set of neighbours used to generate MV predictions
- OneDArray<ImageCoords> m_nshift;
+ //! The relative coords of the set of neighbours used to generate MV predictions
+ OneDArray<ImageCoords> m_nshift;
-};
+ };
} // namespace dirac
diff --git a/src/filters/parser/DiracSplitter/libdirac/libdirac_motionest/me_utils.cpp b/src/filters/parser/DiracSplitter/libdirac/libdirac_motionest/me_utils.cpp
index 05e9216df..007334151 100644
--- a/src/filters/parser/DiracSplitter/libdirac/libdirac_motionest/me_utils.cpp
+++ b/src/filters/parser/DiracSplitter/libdirac/libdirac_motionest/me_utils.cpp
@@ -20,7 +20,7 @@
* Portions created by the Initial Developer are Copyright (C) 2004.
* All Rights Reserved.
*
-* Contributor(s): Thomas Davies (Original Author),
+* Contributor(s): Thomas Davies (Original Author),
* Peter Meerwald (pmeerw@users.sourceforge.net)
* Steve Bearcroft (bearcrsw@users.sourceforge.net)
*
@@ -55,25 +55,25 @@ using namespace dirac;
#include <algorithm>
//#define INTRA_HAAR
-void BlockDiffParams::SetBlockLimits(const OLBParams& bparams ,
- const PicArray& m_pic_data ,
- const int xbpos , const int ybpos)
+void BlockDiffParams::SetBlockLimits( const OLBParams& bparams ,
+ const PicArray& m_pic_data ,
+ const int xbpos , const int ybpos)
{
const int loc_xp = xbpos * bparams.Xbsep() - bparams.Xoffset();
const int loc_yp = ybpos * bparams.Ybsep() - bparams.Yoffset();
- m_xp = std::max(loc_xp , 0);
- m_yp = std::max(loc_yp , 0);
+ m_xp=std::max( loc_xp , 0 );
+ m_yp=std::max( loc_yp , 0 );
m_xl = bparams.Xblen() - m_xp + loc_xp;
m_yl = bparams.Yblen() - m_yp + loc_yp;
- //constrain block lengths to fall within the picture
- m_xl = ((m_xp + m_xl - 1) > m_pic_data.LastX()) ? (m_pic_data.LastX() + 1 - m_xp) : m_xl;
- m_yl = ((m_yp + m_yl - 1) > m_pic_data.LastY()) ? (m_pic_data.LastY() + 1 - m_yp) : m_yl;
+ //constrain block lengths to fall within the picture
+ m_xl = ( ( m_xp + m_xl - 1) > m_pic_data.LastX() ) ? ( m_pic_data.LastX() + 1 - m_xp ): m_xl;
+ m_yl = ( ( m_yp + m_yl - 1) > m_pic_data.LastY() ) ? ( m_pic_data.LastY() + 1 - m_yp ) : m_yl;
- m_xend = m_xp + m_xl;
- m_yend = m_yp + m_yl;
+ m_xend = m_xp+m_xl;
+ m_yend = m_yp+m_yl;
}
@@ -81,92 +81,92 @@ void BlockDiffParams::SetBlockLimits(const OLBParams& bparams ,
// Constructors ...
-BlockDiff::BlockDiff(const PicArray& ref, const PicArray& pic) :
- m_pic_data(pic),
- m_ref_data(ref)
+BlockDiff::BlockDiff(const PicArray& ref,const PicArray& pic) :
+ m_pic_data( pic ),
+ m_ref_data( ref )
{}
-PelBlockDiff::PelBlockDiff(const PicArray& ref , const PicArray& pic) :
- BlockDiff(ref , pic)
+PelBlockDiff::PelBlockDiff( const PicArray& ref , const PicArray& pic ) :
+ BlockDiff( ref , pic )
{}
-IntraBlockDiff::IntraBlockDiff(const PicArray& pic) :
- m_pic_data(pic)
+IntraBlockDiff::IntraBlockDiff( const PicArray& pic ) :
+ m_pic_data( pic )
{}
-BiBlockDiff::BiBlockDiff(const PicArray& ref1 , const PicArray& ref2 ,
- const PicArray& pic) :
- m_pic_data(pic),
- m_ref_data1(ref1),
- m_ref_data2(ref2)
+BiBlockDiff::BiBlockDiff( const PicArray& ref1 , const PicArray& ref2 ,
+ const PicArray& pic) :
+ m_pic_data( pic ),
+ m_ref_data1( ref1 ),
+ m_ref_data2( ref2 )
{}
-BlockDiffUp::BlockDiffUp(const PicArray& ref , const PicArray& pic):
- BlockDiff(ref , pic)
+BlockDiffUp::BlockDiffUp( const PicArray& ref , const PicArray& pic ):
+ BlockDiff( ref , pic )
{}
-BlockDiffHalfPel::BlockDiffHalfPel(const PicArray& ref , const PicArray& pic) :
- BlockDiffUp(ref , pic)
+BlockDiffHalfPel::BlockDiffHalfPel( const PicArray& ref , const PicArray& pic ) :
+ BlockDiffUp( ref , pic )
{}
-BlockDiffQuarterPel::BlockDiffQuarterPel(const PicArray& ref , const PicArray& pic) :
- BlockDiffUp(ref , pic)
+BlockDiffQuarterPel::BlockDiffQuarterPel( const PicArray& ref , const PicArray& pic ) :
+ BlockDiffUp( ref , pic )
{}
-BlockDiffEighthPel::BlockDiffEighthPel(const PicArray& ref , const PicArray& pic) :
- BlockDiffUp(ref , pic)
+BlockDiffEighthPel::BlockDiffEighthPel( const PicArray& ref , const PicArray& pic ) :
+ BlockDiffUp( ref , pic )
{}
-BiBlockHalfPel::BiBlockHalfPel(const PicArray& ref1 , const PicArray& ref2 ,
- const PicArray& pic):
- BiBlockDiff(ref1 , ref2 , pic)
+BiBlockHalfPel::BiBlockHalfPel( const PicArray& ref1 , const PicArray& ref2 ,
+ const PicArray& pic ):
+ BiBlockDiff( ref1 , ref2 , pic)
{}
-BiBlockQuarterPel::BiBlockQuarterPel(const PicArray& ref1 , const PicArray& ref2 ,
- const PicArray& pic):
- BiBlockDiff(ref1 , ref2 , pic)
+BiBlockQuarterPel::BiBlockQuarterPel( const PicArray& ref1 , const PicArray& ref2 ,
+ const PicArray& pic ):
+ BiBlockDiff( ref1 , ref2 , pic)
{}
-BiBlockEighthPel::BiBlockEighthPel(const PicArray& ref1 , const PicArray& ref2 ,
- const PicArray& pic):
- BiBlockDiff(ref1 , ref2 , pic)
+BiBlockEighthPel::BiBlockEighthPel( const PicArray& ref1 , const PicArray& ref2 ,
+ const PicArray& pic ):
+ BiBlockDiff( ref1 , ref2 , pic)
{}
// Difference functions ...
-float PelBlockDiff::Diff(const BlockDiffParams& dparams, const MVector& mv)
+float PelBlockDiff::Diff( const BlockDiffParams& dparams, const MVector& mv )
{
- if(dparams.Xl() <= 0 || dparams.Yl() <= 0)
+ if (dparams.Xl() <= 0 || dparams.Yl() <= 0)
{
return 0;
}
- CalcValueType sum(0);
+ CalcValueType sum( 0 );
- const ImageCoords ref_start(dparams.Xp() + mv.x , dparams.Yp() + mv.y);
- const ImageCoords ref_stop(dparams.Xend() + mv.x , dparams.Yend() + mv.y);
+ const ImageCoords ref_start( dparams.Xp()+mv.x , dparams.Yp()+mv.y );
+ const ImageCoords ref_stop( dparams.Xend()+mv.x , dparams.Yend()+mv.y );
+
+ bool bounds_check( false );
- bool bounds_check(false);
-
- if(ref_start.x < 0 ||
- ref_stop.x >= m_ref_data.LengthX() ||
- ref_start.y < 0 ||
- ref_stop.y >= m_ref_data.LengthY())
+ if ( ref_start.x<0 ||
+ ref_stop.x >= m_ref_data.LengthX() ||
+ ref_start.y<0 ||
+ ref_stop.y >= m_ref_data.LengthY() )
bounds_check = true;
- if(!bounds_check)
+ if ( !bounds_check )
{
#if defined(HAVE_MMX)
return static_cast<float>(simple_block_diff_mmx_4(dparams, mv, m_pic_data, m_ref_data, INT_MAX));
#else
- ValueType diff;
- for(int j = dparams.Yp() ; j < dparams.Yp() + dparams.Yl() ; ++j)
- {
- for(int i = dparams.Xp() ; i < dparams.Xp() + dparams.Xl() ; ++i)
+ ValueType diff;
+ for ( int j=dparams.Yp() ; j<dparams.Yp()+dparams.Yl() ; ++j )
+ {
+ for(int i=dparams.Xp() ; i< dparams.Xp()+dparams.Xl() ; ++i )
{
- diff = m_pic_data[j][i] - m_ref_data[j+mv.y][i+mv.x];
- sum += std::abs(diff);
+ diff = m_pic_data[j][i]-m_ref_data[j+mv.y][i+mv.x];
+ sum += std::abs( diff );
}// i
}// j
#endif /* HAVE_MMX */
@@ -176,73 +176,73 @@ float PelBlockDiff::Diff(const BlockDiffParams& dparams, const MVector& mv)
#if defined (HAVE_MMX)
return static_cast<float>(bchk_simple_block_diff_mmx_4(dparams, mv, m_pic_data, m_ref_data, INT_MAX));
#else
- ValueType diff;
- for(int j = dparams.Yp() ; j < dparams.Yp() + dparams.Yl() ; ++j)
- {
- for(int i = dparams.Xp() ; i < dparams.Xp() + dparams.Xl() ; ++i)
+ ValueType diff;
+ for ( int j=dparams.Yp() ; j < dparams.Yp()+dparams.Yl() ; ++j )
+ {
+ for( int i=dparams.Xp() ; i < dparams.Xp()+dparams.Xl() ; ++i )
{
diff = m_pic_data[j][i] - m_ref_data[BChk(j+mv.y , m_ref_data.LengthY())][BChk(i+mv.x , m_ref_data.LengthX())];
- sum += std::abs(diff);
+ sum += std::abs( diff );
}// i
}// j
#endif /* HAVE_MMX */
}
-
- return static_cast<float>(sum);
+
+ return static_cast<float>( sum );
}
-void PelBlockDiff::Diff(const BlockDiffParams& dparams,
- const MVector& mv,
- float& best_sum,
- MVector& best_mv)
+void PelBlockDiff::Diff( const BlockDiffParams& dparams,
+ const MVector& mv,
+ float& best_sum,
+ MVector& best_mv )
{
- if(dparams.Xl() <= 0 || dparams.Yl() <= 0)
+ if (dparams.Xl() <= 0 || dparams.Yl() <= 0)
{
return;
}
- CalcValueType sum(0);
+ CalcValueType sum( 0 );
- const ImageCoords ref_start(dparams.Xp() + mv.x , dparams.Yp() + mv.y);
- const ImageCoords ref_stop(dparams.Xend() + mv.x , dparams.Yend() + mv.y);
+ const ImageCoords ref_start( dparams.Xp()+mv.x , dparams.Yp()+mv.y );
+ const ImageCoords ref_stop( dparams.Xend()+mv.x , dparams.Yend()+mv.y );
- bool bounds_check(false);
+ bool bounds_check( false );
- if(ref_start.x < 0 ||
- ref_stop.x >= m_ref_data.LengthX() ||
- ref_start.y < 0 ||
- ref_stop.y >= m_ref_data.LengthY())
+ if ( ref_start.x<0 ||
+ ref_stop.x >= m_ref_data.LengthX() ||
+ ref_start.y<0 ||
+ ref_stop.y >= m_ref_data.LengthY() )
bounds_check = true;
- if(!bounds_check)
+ if ( !bounds_check )
{
#if defined (HAVE_MMX)
sum = simple_block_diff_mmx_4(dparams, mv, m_pic_data, m_ref_data, static_cast<int>(best_sum));
- if(sum < best_sum)
+ if (sum < best_sum)
{
- best_sum = sum;
- best_mv = mv;
+ best_sum = sum;
+ best_mv = mv;
}
- return;
+ return;
#else
- ValueType diff;
+ ValueType diff;
ValueType *pic_curr = &m_pic_data[dparams.Yp()][dparams.Xp()];
- const int pic_next(m_pic_data.LengthX() - dparams.Xl()); // - go down a row and back along
-
+ const int pic_next( m_pic_data.LengthX() - dparams.Xl() ); // - go down a row and back along
+
ValueType *ref_curr = &m_ref_data[ref_start.y][ref_start.x];
- for(int y = dparams.Yl(); y > 0; --y, pic_curr += pic_next, ref_curr += pic_next)
+ for( int y=dparams.Yl(); y>0; --y, pic_curr+=pic_next, ref_curr+=pic_next )
{
- for(int x = dparams.Xl(); x > 0; --x, ++pic_curr, ++ref_curr)
+ for( int x=dparams.Xl(); x>0; --x, ++pic_curr, ++ref_curr )
{
- diff = (*pic_curr) - (*ref_curr);
- sum += std::abs(diff);
+ diff = (*pic_curr)-(*ref_curr);
+ sum += std::abs( diff );
}// x
- if(sum >= best_sum)
+ if ( sum>=best_sum )
return;
}// y
@@ -251,25 +251,25 @@ void PelBlockDiff::Diff(const BlockDiffParams& dparams,
else
{
#if defined (HAVE_MMX)
- sum = (bchk_simple_block_diff_mmx_4(dparams, mv, m_pic_data, m_ref_data, static_cast<int>(best_sum)));
- if(sum < best_sum)
+ sum = (bchk_simple_block_diff_mmx_4(dparams, mv, m_pic_data, m_ref_data, static_cast<int>(best_sum)));
+ if (sum < best_sum)
{
best_sum = sum;
best_mv = mv;
}
return;
#else
- ValueType diff;
- for(int j = dparams.Yp() ; j < dparams.Yend() ; ++j)
- {
- for(int i = dparams.Xp() ; i < dparams.Xend() ; ++i)
+ ValueType diff;
+ for ( int j=dparams.Yp() ; j<dparams.Yend() ; ++j )
+ {
+ for( int i=dparams.Xp() ; i<dparams.Xend() ; ++i )
{
diff = m_pic_data[j][i] - m_ref_data[BChk(j+mv.y , m_ref_data.LengthY())][BChk(i+mv.x , m_ref_data.LengthX())];
- sum += std::abs(diff);
+ sum += std::abs( diff );
}// i
- if(sum >= best_sum)
+ if ( sum>=best_sum )
return;
}// j
@@ -278,31 +278,30 @@ void PelBlockDiff::Diff(const BlockDiffParams& dparams,
best_sum = sum;
best_mv = mv;
-
+
}
-ValueType IntraBlockDiff::CalcDC(const BlockDiffParams& dparams)
-{
+ValueType IntraBlockDiff::CalcDC( const BlockDiffParams& dparams ){
- CalcValueType int_dc(0);
- if(dparams.Xl() <= 0 || dparams.Yl() <= 0)
+ CalcValueType int_dc( 0 );
+ if (dparams.Xl() <= 0 || dparams.Yl() <= 0)
{
return 0;
}
- for(int j = dparams.Yp() ; j < dparams.Yp() + dparams.Yl() ; ++j)
- for(int i = dparams.Xp(); i < dparams.Xp() + dparams.Xl() ; ++i)
- int_dc += static_cast<int>(m_pic_data[j][i]);
+ for ( int j=dparams.Yp() ; j<dparams.Yp()+dparams.Yl() ; ++j)
+ for(int i=dparams.Xp(); i<dparams.Xp()+dparams.Xl() ; ++i )
+ int_dc += static_cast<int>( m_pic_data[j][i] );
- int_dc /= (dparams.Xl() * dparams.Yl());
+ int_dc /= ( dparams.Xl() * dparams.Yl() );
- return static_cast<ValueType>(int_dc);
+ return static_cast<ValueType>( int_dc );
}
#ifdef INTRA_HAAR
-float IntraBlockDiff::Diff(const BlockDiffParams& dparams , ValueType& dc_val)
+float IntraBlockDiff::Diff( const BlockDiffParams& dparams , ValueType& dc_val )
{
- if(dparams.Xl() <= 0 || dparams.Yl() <= 0)
+ if (dparams.Xl() <= 0 || dparams.Yl() <= 0)
{
dc_val = 0;
return 0;
@@ -311,72 +310,70 @@ float IntraBlockDiff::Diff(const BlockDiffParams& dparams , ValueType& dc_val)
dc_val = CalcDC(dparams);
// Now compute the resulting SAD
- ValueType dc(dc_val);
- CalcValueType intra_cost(0);
-
- for(int j = dparams.Yp(); j < dparams.Yend() ; j += 2)
- {
- for(int i = dparams.Xp() ; i < dparams.Xend() ; i += 2)
- {
- intra_cost += std::abs(m_pic_data[j][i]
- + m_pic_data[j][i+1]
- + m_pic_data[j+1][i]
- + m_pic_data[j+1][i+1]
- - 4 * dc);
- intra_cost += std::abs(m_pic_data[j][i]
- + m_pic_data[j][i+1]
- - m_pic_data[j+1][i]
- - m_pic_data[j+1][i+1]);
- intra_cost += std::abs(m_pic_data[j][i]
- - m_pic_data[j][i+1]
- + m_pic_data[j+1][i]
- - m_pic_data[j+1][i+1]);
- intra_cost += std::abs(m_pic_data[j][i]
- - m_pic_data[j][i+1]
- - m_pic_data[j+1][i]
- + m_pic_data[j+1][i+1]);
+ ValueType dc( dc_val );
+ CalcValueType intra_cost( 0 );
+
+ for (int j=dparams.Yp(); j<dparams.Yend() ; j+=2){
+ for( int i=dparams.Xp() ; i<dparams.Xend() ;i+=2 ){
+ intra_cost += std::abs( m_pic_data[j][i]
+ + m_pic_data[j][i+1]
+ + m_pic_data[j+1][i]
+ + m_pic_data[j+1][i+1]
+ - 4*dc );
+ intra_cost += std::abs( m_pic_data[j][i]
+ + m_pic_data[j][i+1]
+ - m_pic_data[j+1][i]
+ - m_pic_data[j+1][i+1] );
+ intra_cost += std::abs( m_pic_data[j][i]
+ - m_pic_data[j][i+1]
+ + m_pic_data[j+1][i]
+ - m_pic_data[j+1][i+1] );
+ intra_cost += std::abs( m_pic_data[j][i]
+ - m_pic_data[j][i+1]
+ - m_pic_data[j+1][i]
+ + m_pic_data[j+1][i+1] );
}
}
-
- return static_cast<float>(intra_cost);
+
+ return static_cast<float>( intra_cost );
}
#else
-float IntraBlockDiff::Diff(const BlockDiffParams& dparams , ValueType& dc_val)
+float IntraBlockDiff::Diff( const BlockDiffParams& dparams , ValueType& dc_val )
{
- if(dparams.Xl() <= 0 || dparams.Yl() <= 0)
+ if (dparams.Xl() <= 0 || dparams.Yl() <= 0)
{
dc_val = 0;
return 0;
}
- //computes the cost if block is predicted by its dc component
+ //computes the cost if block is predicted by its dc component
#if defined(HAVE_MMX)
CalcValueType intra_cost =
- simple_intra_block_diff_mmx_4(dparams, m_pic_data, dc_val);
+ simple_intra_block_diff_mmx_4 (dparams, m_pic_data, dc_val);
#ifdef DIRAC_DEBUG
- CalcValueType int_dc(0);
+ CalcValueType int_dc( 0 );
ValueType non_mmx_dc(0);
- for(int j = dparams.Yp() ; j < dparams.Yp() + dparams.Yl() ; ++j)
- for(int i = dparams.Xp(); i < dparams.Xp() + dparams.Xl() ; ++i)
- int_dc += static_cast<int>(m_pic_data[j][i]);
+ for ( int j=dparams.Yp() ; j<dparams.Yp()+dparams.Yl() ; ++j)
+ for(int i=dparams.Xp(); i<dparams.Xp()+dparams.Xl() ; ++i )
+ int_dc += static_cast<int>( m_pic_data[j][i] );
- int_dc /= (dparams.Xl() * dparams.Yl());
+ int_dc /= ( dparams.Xl() * dparams.Yl() );
- non_mmx_dc = static_cast<ValueType>(int_dc);
+ non_mmx_dc = static_cast<ValueType>( int_dc );
// Now compute the resulting SAD
- ValueType dc(non_mmx_dc);
- CalcValueType non_mmx_intra_cost(0);
+ ValueType dc( non_mmx_dc );
+ CalcValueType non_mmx_intra_cost( 0 );
- for(int j = dparams.Yp(); j < dparams.Yend() ; ++j)
- for(int i = dparams.Xp() ; i < dparams.Xend() ; ++i)
- non_mmx_intra_cost += std::abs(m_pic_data[j][i] - dc);
+ for (int j=dparams.Yp(); j<dparams.Yend() ; ++j)
+ for( int i=dparams.Xp() ; i<dparams.Xend() ;++i )
+ non_mmx_intra_cost += std::abs( m_pic_data[j][i] - dc );
- if(non_mmx_dc != dc_val || non_mmx_intra_cost != intra_cost)
+ if (non_mmx_dc != dc_val || non_mmx_intra_cost != intra_cost)
{
std::cerr << "MMX vals: dc=" << dc_val;
std::cerr << " cost=" << intra_cost << std::endl;
@@ -385,76 +382,76 @@ float IntraBlockDiff::Diff(const BlockDiffParams& dparams , ValueType& dc_val)
std::cerr << " cost=" << non_mmx_intra_cost << std::endl;
}
#endif
- return static_cast<float>(intra_cost);
+ return static_cast<float>( intra_cost );
#else
-CalcValueType int_dc(0);
-
-for(int j = dparams.Yp() ; j < dparams.Yp() + dparams.Yl() ; ++j)
- for(int i = dparams.Xp(); i < dparams.Xp() + dparams.Xl() ; ++i)
- int_dc += static_cast<int>(m_pic_data[j][i]);
-
-int_dc /= (dparams.Xl() * dparams.Yl());
+ CalcValueType int_dc( 0 );
-dc_val = static_cast<ValueType>(int_dc);
+ for ( int j=dparams.Yp() ; j<dparams.Yp()+dparams.Yl() ; ++j)
+ for(int i=dparams.Xp(); i<dparams.Xp()+dparams.Xl() ; ++i )
+ int_dc += static_cast<int>( m_pic_data[j][i] );
-// Now compute the resulting SAD
-ValueType dc(dc_val);
-CalcValueType intra_cost(0);
+ int_dc /= ( dparams.Xl() * dparams.Yl() );
-for(int j = dparams.Yp(); j < dparams.Yend() ; ++j)
- for(int i = dparams.Xp() ; i < dparams.Xend() ; ++i)
- intra_cost += std::abs(m_pic_data[j][i] - dc);
+ dc_val = static_cast<ValueType>( int_dc );
-return static_cast<float>(intra_cost);
+ // Now compute the resulting SAD
+ ValueType dc( dc_val );
+ CalcValueType intra_cost( 0 );
+
+ for (int j=dparams.Yp(); j<dparams.Yend() ; ++j)
+ for( int i=dparams.Xp() ; i<dparams.Xend() ;++i )
+ intra_cost += std::abs( m_pic_data[j][i] - dc );
+
+ return static_cast<float>( intra_cost );
#endif //HAVE_MMX
}
#endif
-float BlockDiffHalfPel::Diff(const BlockDiffParams& dparams ,
- const MVector& mv)
+float BlockDiffHalfPel::Diff( const BlockDiffParams& dparams ,
+ const MVector& mv )
{
- if(dparams.Xl() <= 0 || dparams.Yl() <= 0)
+ if (dparams.Xl() <= 0 || dparams.Yl() <= 0)
{
return 0;
}
- //Where to start in the upconverted image
- const ImageCoords ref_start((dparams.Xp() << 1) + mv.x , (dparams.Yp() << 1) + mv.y);
- const ImageCoords ref_stop(ref_start.x + (dparams.Xl() << 1) , ref_start.y + (dparams.Yl() << 1));
+ //Where to start in the upconverted image
+ const ImageCoords ref_start( ( dparams.Xp()<<1 ) + mv.x ,( dparams.Yp()<<1 ) + mv.y );
+ const ImageCoords ref_stop( ref_start.x+(dparams.Xl()<<1) , ref_start.y+(dparams.Yl()<<1));
- bool bounds_check(false);
+ bool bounds_check( false );
- if(ref_start.x < 0 ||
- ref_stop.x >= m_ref_data.LengthX() ||
- ref_start.y < 0 ||
- ref_stop.y >= m_ref_data.LengthY())
+ if ( ref_start.x<0 ||
+ ref_stop.x >= m_ref_data.LengthX() ||
+ ref_start.y<0 ||
+ ref_stop.y >= m_ref_data.LengthY() )
bounds_check = true;
- float sum(0);
+ float sum( 0 );
- if(!bounds_check)
+ if ( !bounds_check )
{
#if defined (HAVE_MMX)
- MVector rmdr(0, 0);
+ MVector rmdr(0,0);
const ImageCoords start_pos(dparams.Xp(), dparams.Yp());
const ImageCoords end_pos(dparams.Xp() + dparams.Xl(), dparams.Yp() + dparams.Yl());
- sum = simple_block_diff_up_mmx_4(m_pic_data, m_ref_data,
- start_pos, end_pos,
- ref_start, ref_stop,
- rmdr,
- sum,
- static_cast<float>(INT_MAX));
+ sum = simple_block_diff_up_mmx_4 (m_pic_data, m_ref_data,
+ start_pos, end_pos,
+ ref_start, ref_stop,
+ rmdr,
+ sum,
+ static_cast<float>(INT_MAX));
#else
ValueType* pic_curr = &m_pic_data[dparams.Yp()][dparams.Xp()];
- const int pic_next(m_pic_data.LengthX() - dparams.Xl()); // go down a row and back up
+ const int pic_next( m_pic_data.LengthX() - dparams.Xl() );// go down a row and back up
ValueType *ref_curr = &m_ref_data[ref_start.y][ref_start.x];
- const int ref_next((m_ref_data.LengthX() - dparams.Xl()) * 2);// go down 2 rows and back up
+ const int ref_next( (m_ref_data.LengthX() - dparams.Xl())*2 );// go down 2 rows and back up
- for(int y = dparams.Yl(); y > 0; --y, pic_curr += pic_next, ref_curr += ref_next)
+ for( int y=dparams.Yl(); y > 0; --y, pic_curr+=pic_next, ref_curr+=ref_next )
{
- for(int x = dparams.Xl(); x > 0; --x, ++pic_curr, ref_curr += 2)
+ for( int x=dparams.Xl(); x > 0; --x, ++pic_curr, ref_curr+=2 )
{
- sum += std::abs(*ref_curr - *pic_curr);
+ sum += std::abs( *ref_curr - *pic_curr );
}// x
}// y
#endif
@@ -464,17 +461,17 @@ float BlockDiffHalfPel::Diff(const BlockDiffParams& dparams ,
{
// We're doing bounds checking because we'll fall off the edge of the reference otherwise.
ValueType* pic_curr = &m_pic_data[dparams.Yp()][dparams.Xp()];
- const int pic_next(m_pic_data.LengthX() - dparams.Xl()); // go down a row and back up
- for(int y = dparams.Yl(), ry = ref_start.y, by = BChk(ry, m_ref_data.LengthY());
- y > 0;
- --y, pic_curr += pic_next, ry += 2 , by = BChk(ry, m_ref_data.LengthY()))
+ const int pic_next( m_pic_data.LengthX() - dparams.Xl() );// go down a row and back up
+ for( int y=dparams.Yl(), ry=ref_start.y, by=BChk(ry,m_ref_data.LengthY());
+ y>0;
+ --y, pic_curr+=pic_next, ry+=2 , by=BChk(ry,m_ref_data.LengthY()))
{
- for(int x = dparams.Xl() , rx = ref_start.x , bx = BChk(rx, m_ref_data.LengthX());
- x > 0 ;
- --x, ++pic_curr, rx += 2 , bx = BChk(rx, m_ref_data.LengthX()))
- {
- sum += std::abs(m_ref_data[by][bx] - *pic_curr);
- }// x
+ for( int x=dparams.Xl() , rx=ref_start.x , bx=BChk(rx,m_ref_data.LengthX());
+ x>0 ;
+ --x, ++pic_curr, rx+=2 , bx=BChk(rx,m_ref_data.LengthX()))
+ {
+ sum += std::abs( m_ref_data[by][bx] -*pic_curr);
+ }// x
}// y
}
@@ -483,63 +480,63 @@ float BlockDiffHalfPel::Diff(const BlockDiffParams& dparams ,
}
-void BlockDiffHalfPel::Diff(const BlockDiffParams& dparams,
- const MVector& mv ,
- const float mvcost,
- const float lambda,
- MvCostData& best_costs ,
- MVector& best_mv)
+void BlockDiffHalfPel::Diff( const BlockDiffParams& dparams,
+ const MVector& mv ,
+ const float mvcost,
+ const float lambda,
+ MvCostData& best_costs ,
+ MVector& best_mv )
{
- if(dparams.Xl() <= 0 || dparams.Yl() <= 0)
+ if (dparams.Xl() <= 0 || dparams.Yl() <= 0)
{
- return;
+ return;
}
//Where to start in the upconverted image
- const ImageCoords ref_start((dparams.Xp() << 1) + mv.x , (dparams.Yp() << 1) + mv.y);
- const ImageCoords ref_stop(ref_start.x + (dparams.Xl() << 1) , ref_start.y + (dparams.Yl() << 1));
+ const ImageCoords ref_start( ( dparams.Xp()<<1 ) + mv.x ,( dparams.Yp()<<1 ) + mv.y );
+ const ImageCoords ref_stop( ref_start.x+(dparams.Xl()<<1) , ref_start.y+(dparams.Yl()<<1));
- bool bounds_check(false);
+ bool bounds_check( false );
- if(ref_start.x < 0 ||
- ref_stop.x >= m_ref_data.LengthX() ||
- ref_start.y < 0 ||
- ref_stop.y >= m_ref_data.LengthY())
+ if ( ref_start.x<0 ||
+ ref_stop.x >= m_ref_data.LengthX() ||
+ ref_start.y<0 ||
+ ref_stop.y >= m_ref_data.LengthY() )
bounds_check = true;
- const float start_val(mvcost * lambda);
- float sum(start_val);
+ const float start_val( mvcost*lambda );
+ float sum( start_val );
- if(!bounds_check)
+ if ( !bounds_check )
{
#if defined (HAVE_MMX)
-
+
const ImageCoords start_pos(dparams.Xp(), dparams.Yp());
const ImageCoords end_pos(dparams.Xp() + dparams.Xl(), dparams.Yp() + dparams.Yl());
- MVector rmdr(0, 0);
- sum = simple_block_diff_up_mmx_4(m_pic_data, m_ref_data,
- start_pos, end_pos,
- ref_start, ref_stop,
- rmdr,
- sum,
- best_costs.total);
- if(sum >= best_costs.total)
+ MVector rmdr(0,0);
+ sum = simple_block_diff_up_mmx_4 (m_pic_data, m_ref_data,
+ start_pos, end_pos,
+ ref_start, ref_stop,
+ rmdr,
+ sum,
+ best_costs.total);
+ if ( sum>=best_costs.total )
return;
#else
- ValueType* pic_curr = &m_pic_data[dparams.Yp()][dparams.Xp()];
- const int pic_next(m_pic_data.LengthX() - dparams.Xl()); // go down a row and back up
+ ValueType* pic_curr = &m_pic_data[dparams.Yp()][dparams.Xp()];
+ const int pic_next( m_pic_data.LengthX() - dparams.Xl() );// go down a row and back up
ValueType *ref_curr = &m_ref_data[ref_start.y][ref_start.x];
- const int ref_next((m_ref_data.LengthX() - dparams.Xl()) * 2);// go down 2 rows and back up
+ const int ref_next( (m_ref_data.LengthX() - dparams.Xl())*2 );// go down 2 rows and back up
- for(int y = dparams.Yl(); y > 0; --y, pic_curr += pic_next, ref_curr += ref_next)
+ for( int y=dparams.Yl(); y > 0; --y, pic_curr+=pic_next, ref_curr+=ref_next )
{
- for(int x = dparams.Xl(); x > 0; --x, ++pic_curr, ref_curr += 2)
+ for( int x=dparams.Xl(); x > 0; --x, ++pic_curr, ref_curr+=2 )
{
- sum += std::abs(*ref_curr - *pic_curr);
+ sum += std::abs( *ref_curr - *pic_curr );
}// x
- if(sum >= best_costs.total)
+ if ( sum>=best_costs.total )
return;
}// y
@@ -548,20 +545,20 @@ void BlockDiffHalfPel::Diff(const BlockDiffParams& dparams,
else
{
// We're doing bounds checking because we'll fall off the edge of the reference otherwise.
- ValueType* pic_curr = &m_pic_data[dparams.Yp()][dparams.Xp()];
- const int pic_next(m_pic_data.LengthX() - dparams.Xl()); // go down a row and back up
- for(int y = dparams.Yl(), ry = ref_start.y, by = BChk(ry, m_ref_data.LengthY());
- y > 0;
- --y, pic_curr += pic_next, ry += 2 , by = BChk(ry, m_ref_data.LengthY()))
+ ValueType* pic_curr = &m_pic_data[dparams.Yp()][dparams.Xp()];
+ const int pic_next( m_pic_data.LengthX() - dparams.Xl() );// go down a row and back up
+ for( int y=dparams.Yl(), ry=ref_start.y, by=BChk(ry,m_ref_data.LengthY());
+ y>0;
+ --y, pic_curr+=pic_next, ry+=2 , by=BChk(ry,m_ref_data.LengthY()))
{
- for(int x = dparams.Xl() , rx = ref_start.x , bx = BChk(rx, m_ref_data.LengthX());
- x > 0 ;
- --x, ++pic_curr, rx += 2 , bx = BChk(rx, m_ref_data.LengthX()))
- {
- sum += std::abs(m_ref_data[by][bx] - *pic_curr);
- }// x
-
- if(sum >= best_costs.total)
+ for( int x=dparams.Xl() , rx=ref_start.x , bx=BChk(rx,m_ref_data.LengthX());
+ x>0 ;
+ --x, ++pic_curr, rx+=2 , bx=BChk(rx,m_ref_data.LengthX()))
+ {
+ sum += std::abs( m_ref_data[by][bx] -*pic_curr);
+ }// x
+
+ if ( sum>=best_costs.total )
return;
}// y
@@ -574,109 +571,109 @@ void BlockDiffHalfPel::Diff(const BlockDiffParams& dparams,
best_costs.SAD = sum - start_val;
}
-float BlockDiffQuarterPel::Diff(const BlockDiffParams& dparams , const MVector& mv)
+float BlockDiffQuarterPel::Diff( const BlockDiffParams& dparams , const MVector& mv )
{
- if(dparams.Xl() <= 0 || dparams.Yl() <= 0)
+ if (dparams.Xl() <= 0 || dparams.Yl() <= 0)
{
- return 0;
+ return 0;
}
- // Set up the start point in the reference image by rounding the motion vector
+ // Set up the start point in the reference image by rounding the motion vector
// to 1/2 pel accuracy.NB: bit shift rounds negative values DOWN, as required
- const MVector roundvec(mv.x >> 1 , mv.y >> 1);
+ const MVector roundvec( mv.x>>1 , mv.y>>1 );
//Get the remainder after rounding. NB rmdr values always 0 or 1
- const MVector rmdr(mv.x & 1 , mv.y & 1);
+ const MVector rmdr( mv.x & 1 , mv.y & 1 );
//Where to start in the upconverted image
- const ImageCoords ref_start((dparams.Xp() << 1) + roundvec.x , (dparams.Yp() << 1) + roundvec.y);
- const ImageCoords ref_stop(ref_start.x + (dparams.Xl() << 1) , ref_start.y + (dparams.Yl() << 1));
- bool bounds_check(false);
-
- if(ref_start.x < 0 ||
- ref_stop.x >= m_ref_data.LengthX() ||
- ref_start.y < 0 ||
- ref_stop.y >= m_ref_data.LengthY())
+ const ImageCoords ref_start( ( dparams.Xp()<<1 ) + roundvec.x ,( dparams.Yp()<<1 ) + roundvec.y );
+ const ImageCoords ref_stop( ref_start.x+(dparams.Xl()<<1) , ref_start.y+(dparams.Yl()<<1));
+ bool bounds_check( false );
+
+ if ( ref_start.x<0 ||
+ ref_stop.x >= m_ref_data.LengthX() ||
+ ref_start.y<0 ||
+ ref_stop.y >= m_ref_data.LengthY() )
bounds_check = true;
- float sum(0.0f);
- CalcValueType temp;
+ float sum( 0.0f );
+ CalcValueType temp;
- if(!bounds_check)
+ if ( !bounds_check )
{
#if defined (HAVE_MMX)
const ImageCoords start_pos(dparams.Xp(), dparams.Yp());
const ImageCoords end_pos(dparams.Xp() + dparams.Xl(), dparams.Yp() + dparams.Yl());
-
- sum = simple_block_diff_up_mmx_4(m_pic_data, m_ref_data,
- start_pos, end_pos,
- ref_start, ref_stop,
- rmdr,
- sum,
- static_cast<float>(INT_MAX));
+
+ sum = simple_block_diff_up_mmx_4 (m_pic_data, m_ref_data,
+ start_pos, end_pos,
+ ref_start, ref_stop,
+ rmdr,
+ sum,
+ static_cast<float>(INT_MAX));
#else
ValueType* pic_curr = &m_pic_data[dparams.Yp()][dparams.Xp()];
- const int pic_next(m_pic_data.LengthX() - dparams.Xl()); // go down a row and back up
- if(rmdr.x == 0 && rmdr.y == 0)
+ const int pic_next( m_pic_data.LengthX() - dparams.Xl() );// go down a row and back up
+ if( rmdr.x == 0 && rmdr.y == 0 )
{
ValueType *ref_curr = &m_ref_data[ref_start.y][ref_start.x];
- const int ref_next((m_ref_data.LengthX() - dparams.Xl()) * 2);// go down 2 rows and back up
- for(int y = dparams.Yl(); y > 0; --y, pic_curr += pic_next, ref_curr += ref_next)
+ const int ref_next( (m_ref_data.LengthX() - dparams.Xl())*2 );// go down 2 rows and back up
+ for( int y=dparams.Yl(); y > 0; --y, pic_curr+=pic_next, ref_curr+=ref_next )
{
- for(int x = dparams.Xl(); x > 0; --x, ++pic_curr, ref_curr += 2)
+ for( int x=dparams.Xl(); x > 0; --x, ++pic_curr, ref_curr+=2 )
{
- sum += std::abs(*ref_curr - *pic_curr);
+ sum += std::abs( *ref_curr - *pic_curr );
}// x
}// y
}
- else if(rmdr.y == 0)
+ else if( rmdr.y == 0 )
{
ValueType *ref_curr = &m_ref_data[ref_start.y][ref_start.x];
- const int ref_next((m_ref_data.LengthX() - dparams.Xl()) * 2);// go down 2 rows and back up
- for(int y = dparams.Yl(); y > 0; --y, pic_curr += pic_next, ref_curr += ref_next)
+ const int ref_next( (m_ref_data.LengthX() - dparams.Xl())*2 );// go down 2 rows and back up
+ for( int y=dparams.Yl(); y > 0; --y, pic_curr+=pic_next, ref_curr+=ref_next )
{
- for(int x = dparams.Xl(); x > 0; --x, ++pic_curr, ref_curr += 2)
+ for( int x=dparams.Xl(); x > 0; --x, ++pic_curr, ref_curr+=2 )
{
- temp = (CalcValueType(ref_curr[0]) +
- CalcValueType(ref_curr[1]) +
- 1
- ) >> 1;
- sum += std::abs(temp - *pic_curr);
+ temp = ( CalcValueType( ref_curr[0] ) +
+ CalcValueType( ref_curr[1] ) +
+ 1
+ ) >> 1;
+ sum += std::abs( temp - *pic_curr );
}// x
}// y
}
- else if(rmdr.x == 0)
+ else if( rmdr.x == 0 )
{
ValueType *ref_curr = &m_ref_data[ref_start.y][ref_start.x];
- const int ref_next((m_ref_data.LengthX() - dparams.Xl()) * 2);// go down 2 rows and back up
- for(int y = dparams.Yl(); y > 0; --y, pic_curr += pic_next, ref_curr += ref_next)
+ const int ref_next( (m_ref_data.LengthX() - dparams.Xl())*2 );// go down 2 rows and back up
+ for( int y=dparams.Yl(); y > 0; --y, pic_curr+=pic_next, ref_curr+=ref_next )
{
- for(int x = dparams.Xl(); x > 0; --x, ++pic_curr, ref_curr += 2)
+ for( int x=dparams.Xl(); x > 0; --x, ++pic_curr, ref_curr+=2 )
{
- temp = (CalcValueType(ref_curr[0]) +
- CalcValueType(ref_curr[m_ref_data.LengthX()]) +
- 1
- ) >> 1;
- sum += std::abs(temp - *pic_curr);
+ temp = ( CalcValueType( ref_curr[0] ) +
+ CalcValueType( ref_curr[m_ref_data.LengthX()] ) +
+ 1
+ ) >> 1;
+ sum += std::abs( temp - *pic_curr );
}// x
}// y
}
else
{
ValueType *ref_curr = &m_ref_data[ref_start.y][ref_start.x];
- const int ref_next((m_ref_data.LengthX() - dparams.Xl()) * 2);// go down 2 rows and back up
- for(int y = dparams.Yl(); y > 0; --y, pic_curr += pic_next, ref_curr += ref_next)
+ const int ref_next( (m_ref_data.LengthX() - dparams.Xl())*2 );// go down 2 rows and back up
+ for( int y=dparams.Yl(); y > 0; --y, pic_curr+=pic_next, ref_curr+=ref_next )
{
- for(int x = dparams.Xl(); x > 0; --x, ++pic_curr, ref_curr += 2)
+ for( int x=dparams.Xl(); x > 0; --x, ++pic_curr, ref_curr+=2 )
{
- temp = (CalcValueType(ref_curr[0]) +
- CalcValueType(ref_curr[1]) +
- CalcValueType(ref_curr[m_ref_data.LengthX()+0]) +
- CalcValueType(ref_curr[m_ref_data.LengthX()+1]) +
- 2
- ) >> 2;
- sum += std::abs(temp - *pic_curr);
+ temp = ( CalcValueType( ref_curr[0] ) +
+ CalcValueType( ref_curr[1] ) +
+ CalcValueType( ref_curr[m_ref_data.LengthX()+0] ) +
+ CalcValueType( ref_curr[m_ref_data.LengthX()+1] ) +
+ 2
+ ) >> 2;
+ sum += std::abs( temp - *pic_curr );
}// x
}// y
}
@@ -686,30 +683,29 @@ float BlockDiffQuarterPel::Diff(const BlockDiffParams& dparams , const MVector&
{
// We're doing bounds checking because we'll fall off the edge of the reference otherwise.
- // weights for doing linear interpolation, calculated from the remainder values
- const ValueType linear_wts[4] = { (2 - rmdr.x) *(2 - rmdr.y), //tl
- rmdr.x *(2 - rmdr.y), //tr
+ // weights for doing linear interpolation, calculated from the remainder values
+ const ValueType linear_wts[4] = { (2 - rmdr.x) * (2 - rmdr.y), //tl
+ rmdr.x * (2 - rmdr.y), //tr
(2 - rmdr.x) * rmdr.y, //bl
- rmdr.x * rmdr.y
- }; //br
+ rmdr.x * rmdr.y }; //br
- const int refXlen(m_ref_data.LengthX());
- const int refYlen(m_ref_data.LengthY());
+ const int refXlen( m_ref_data.LengthX() );
+ const int refYlen( m_ref_data.LengthY() );
- for(int y = dparams.Yp(), uY = ref_start.y, BuY = BChk(uY, refYlen), BuY1 = BChk(uY + 1, refYlen);
- y < dparams.Yend(); ++y, uY += 2, BuY = BChk(uY, refYlen), BuY1 = BChk(uY + 1, refYlen))
+ for(int y = dparams.Yp(), uY = ref_start.y,BuY=BChk(uY,refYlen),BuY1=BChk(uY+1,refYlen);
+ y < dparams.Yend(); ++y, uY += 2,BuY=BChk(uY,refYlen),BuY1=BChk(uY+1,refYlen))
{
- for(int x = dparams.Xp(), uX = ref_start.x, BuX = BChk(uX, refXlen), BuX1 = BChk(uX + 1, refXlen);
- x < dparams.Xend(); ++x, uX += 2, BuX = BChk(uX, refXlen), BuX1 = BChk(uX + 1, refXlen))
+ for(int x = dparams.Xp(), uX = ref_start.x,BuX=BChk(uX,refXlen),BuX1=BChk(uX+1,refXlen);
+ x < dparams.Xend(); ++x, uX += 2,BuX=BChk(uX,refXlen),BuX1=BChk(uX+1,refXlen))
{
-
- temp = (linear_wts[0] * CalcValueType(m_ref_data[BuY][BuX]) +
- linear_wts[1] * CalcValueType(m_ref_data[BuY][BuX1]) +
- linear_wts[2] * CalcValueType(m_ref_data[BuY1][BuX]) +
- linear_wts[3] * CalcValueType(m_ref_data[BuY1][BuX1]) +
- 2
- ) >> 2;
- sum += std::abs(temp - m_pic_data[y][x]);
+
+ temp = ( linear_wts[0] * CalcValueType( m_ref_data[BuY][BuX] ) +
+ linear_wts[1] * CalcValueType( m_ref_data[BuY][BuX1] ) +
+ linear_wts[2] * CalcValueType( m_ref_data[BuY1][BuX] )+
+ linear_wts[3] * CalcValueType( m_ref_data[BuY1][BuX1] ) +
+ 2
+ ) >> 2;
+ sum += std::abs( temp - m_pic_data[y][x] );
}// x
}// y
@@ -719,127 +715,127 @@ float BlockDiffQuarterPel::Diff(const BlockDiffParams& dparams , const MVector&
}
-void BlockDiffQuarterPel::Diff(const BlockDiffParams& dparams,
- const MVector& mv ,
- const float mvcost,
- const float lambda,
- MvCostData& best_costs ,
- MVector& best_mv)
+void BlockDiffQuarterPel::Diff( const BlockDiffParams& dparams,
+ const MVector& mv ,
+ const float mvcost,
+ const float lambda,
+ MvCostData& best_costs ,
+ MVector& best_mv)
{
- if(dparams.Xl() <= 0 || dparams.Yl() <= 0)
+ if (dparams.Xl() <= 0 || dparams.Yl() <= 0)
{
- return;
+ return;
}
// Set up the start point in the reference image by rounding the motion vector
// to 1/2 pel accuracy.NB: bit shift rounds negative values DOWN, as required
- const MVector roundvec(mv.x >> 1 , mv.y >> 1);
+ const MVector roundvec( mv.x>>1 , mv.y>>1 );
//Get the remainder after rounding. NB rmdr values always 0 or 1
- const MVector rmdr(mv.x & 1 , mv.y & 1);
+ const MVector rmdr( mv.x & 1 , mv.y & 1 );
//Where to start in the upconverted image
- const ImageCoords ref_start((dparams.Xp() << 1) + roundvec.x , (dparams.Yp() << 1) + roundvec.y);
- const ImageCoords ref_stop(ref_start.x + (dparams.Xl() << 1) , ref_start.y + (dparams.Yl() << 1));
+ const ImageCoords ref_start( ( dparams.Xp()<<1 ) + roundvec.x ,( dparams.Yp()<<1 ) + roundvec.y );
+ const ImageCoords ref_stop( ref_start.x+(dparams.Xl()<<1) , ref_start.y+(dparams.Yl()<<1));
- bool bounds_check(false);
+ bool bounds_check( false );
- if(ref_start.x < 0 ||
- ref_stop.x >= m_ref_data.LengthX() ||
- ref_start.y < 0 ||
- ref_stop.y >= m_ref_data.LengthY())
+ if ( ref_start.x<0 ||
+ ref_stop.x >= m_ref_data.LengthX() ||
+ ref_start.y<0 ||
+ ref_stop.y >= m_ref_data.LengthY() )
bounds_check = true;
- const float start_val(mvcost * lambda);
- float sum(start_val);
+ const float start_val( mvcost*lambda );
+ float sum( start_val );
CalcValueType temp;
- if(!bounds_check)
+ if ( !bounds_check )
{
#if defined (HAVE_MMX)
const ImageCoords start_pos(dparams.Xp(), dparams.Yp());
const ImageCoords end_pos(dparams.Xp() + dparams.Xl(), dparams.Yp() + dparams.Yl());
-
- sum = simple_block_diff_up_mmx_4(m_pic_data, m_ref_data,
- start_pos, end_pos,
- ref_start, ref_stop,
- rmdr,
- sum,
- best_costs.total);
-
- if(sum >= best_costs.total)
+
+ sum = simple_block_diff_up_mmx_4 (m_pic_data, m_ref_data,
+ start_pos, end_pos,
+ ref_start, ref_stop,
+ rmdr,
+ sum,
+ best_costs.total);
+
+ if ( sum>=best_costs.total )
return;
#else
ValueType* pic_curr = &m_pic_data[dparams.Yp()][dparams.Xp()];
- const int pic_next(m_pic_data.LengthX() - dparams.Xl()); // go down a row and back up
+ const int pic_next( m_pic_data.LengthX() - dparams.Xl() );// go down a row and back up
ValueType *ref_curr = &m_ref_data[ref_start.y][ref_start.x];
- const int ref_next((m_ref_data.LengthX() - dparams.Xl()) * 2);// go down 2 rows and back up
+ const int ref_next( (m_ref_data.LengthX() - dparams.Xl())*2 );// go down 2 rows and back up
- if(rmdr.x == 0 && rmdr.y == 0)
+ if( rmdr.x == 0 && rmdr.y == 0 )
{
- for(int y = dparams.Yl(); y > 0; --y, pic_curr += pic_next, ref_curr += ref_next)
+ for( int y=dparams.Yl(); y > 0; --y, pic_curr+=pic_next, ref_curr+=ref_next )
{
- for(int x = dparams.Xl(); x > 0; --x, ++pic_curr, ref_curr += 2)
+ for( int x=dparams.Xl(); x > 0; --x, ++pic_curr, ref_curr+=2 )
{
- sum += std::abs(*ref_curr - *pic_curr);
+ sum += std::abs( *ref_curr - *pic_curr );
}// x
-
- if(sum >= best_costs.total)
+
+ if ( sum>=best_costs.total )
return;
}// y
}
- else if(rmdr.y == 0)
+ else if( rmdr.y == 0 )
{
- for(int y = dparams.Yl(); y > 0; --y, pic_curr += pic_next, ref_curr += ref_next)
+ for( int y=dparams.Yl(); y > 0; --y, pic_curr+=pic_next, ref_curr+=ref_next )
{
- for(int x = dparams.Xl(); x > 0; --x, ++pic_curr, ref_curr += 2)
+ for( int x=dparams.Xl(); x > 0; --x, ++pic_curr, ref_curr+=2 )
{
- temp = (CalcValueType(ref_curr[0]) +
- CalcValueType(ref_curr[1]) +
- 1
- ) >> 1;
- sum += std::abs(temp - *pic_curr);
+ temp = ( CalcValueType( ref_curr[0] ) +
+ CalcValueType( ref_curr[1] ) +
+ 1
+ ) >> 1;
+ sum += std::abs( temp - *pic_curr );
}// x
-
- if(sum >= best_costs.total)
+
+ if ( sum>=best_costs.total )
return;
}// y
}
- else if(rmdr.x == 0)
+ else if( rmdr.x == 0 )
{
- for(int y = dparams.Yl(); y > 0; --y, pic_curr += pic_next, ref_curr += ref_next)
+ for( int y=dparams.Yl(); y > 0; --y, pic_curr+=pic_next, ref_curr+=ref_next )
{
- for(int x = dparams.Xl(); x > 0; --x, ++pic_curr, ref_curr += 2)
+ for( int x=dparams.Xl(); x > 0; --x, ++pic_curr, ref_curr+=2 )
{
- temp = (CalcValueType(ref_curr[0]) +
- CalcValueType(ref_curr[m_ref_data.LengthX()]) +
- 1
- ) >> 1;
- sum += std::abs(temp - *pic_curr);
+ temp = ( CalcValueType( ref_curr[0] ) +
+ CalcValueType( ref_curr[m_ref_data.LengthX()] ) +
+ 1
+ ) >> 1;
+ sum += std::abs( temp - *pic_curr );
}// x
-
- if(sum >= best_costs.total)
+
+ if ( sum>=best_costs.total )
return;
}// y
}
else
{
- for(int y = dparams.Yl(); y > 0; --y, pic_curr += pic_next, ref_curr += ref_next)
+ for( int y=dparams.Yl(); y > 0; --y, pic_curr+=pic_next, ref_curr+=ref_next )
{
- for(int x = dparams.Xl(); x > 0; --x, ++pic_curr, ref_curr += 2)
+ for( int x=dparams.Xl(); x > 0; --x, ++pic_curr, ref_curr+=2 )
{
- temp = (CalcValueType(ref_curr[0]) +
- CalcValueType(ref_curr[1]) +
- CalcValueType(ref_curr[m_ref_data.LengthX()+0]) +
- CalcValueType(ref_curr[m_ref_data.LengthX()+1]) +
- 2
- ) >> 2;
- sum += std::abs(temp - *pic_curr);
+ temp = ( CalcValueType( ref_curr[0] ) +
+ CalcValueType( ref_curr[1] ) +
+ CalcValueType( ref_curr[m_ref_data.LengthX()+0] ) +
+ CalcValueType( ref_curr[m_ref_data.LengthX()+1] ) +
+ 2
+ ) >> 2;
+ sum += std::abs( temp - *pic_curr );
}// x
-
- if(sum >= best_costs.total)
+
+ if ( sum>=best_costs.total )
return;
}// y
@@ -851,33 +847,32 @@ void BlockDiffQuarterPel::Diff(const BlockDiffParams& dparams,
{
// We're doing bounds checking because we'll fall off the edge of the reference otherwise.
- // weights for doing linear interpolation, calculated from the remainder values
- const ValueType linear_wts[4] = { (2 - rmdr.x) *(2 - rmdr.y), //tl
- rmdr.x *(2 - rmdr.y), //tr
+ // weights for doing linear interpolation, calculated from the remainder values
+ const ValueType linear_wts[4] = { (2 - rmdr.x) * (2 - rmdr.y), //tl
+ rmdr.x * (2 - rmdr.y), //tr
(2 - rmdr.x) * rmdr.y, //bl
- rmdr.x * rmdr.y
- }; //br
+ rmdr.x * rmdr.y }; //br
- const int refXlen(m_ref_data.LengthX());
- const int refYlen(m_ref_data.LengthY());
+ const int refXlen( m_ref_data.LengthX() );
+ const int refYlen( m_ref_data.LengthY() );
- for(int y = dparams.Yp(), uY = ref_start.y, BuY = BChk(uY, refYlen), BuY1 = BChk(uY + 1, refYlen);
- y < dparams.Yend(); ++y, uY += 2, BuY = BChk(uY, refYlen), BuY1 = BChk(uY + 1, refYlen))
+ for(int y = dparams.Yp(), uY = ref_start.y,BuY=BChk(uY,refYlen),BuY1=BChk(uY+1,refYlen);
+ y < dparams.Yend(); ++y, uY += 2,BuY=BChk(uY,refYlen),BuY1=BChk(uY+1,refYlen))
{
- for(int x = dparams.Xp(), uX = ref_start.x, BuX = BChk(uX, refXlen), BuX1 = BChk(uX + 1, refXlen);
- x < dparams.Xend(); ++x, uX += 2, BuX = BChk(uX, refXlen), BuX1 = BChk(uX + 1, refXlen))
+ for(int x = dparams.Xp(), uX = ref_start.x,BuX=BChk(uX,refXlen),BuX1=BChk(uX+1,refXlen);
+ x < dparams.Xend(); ++x, uX += 2,BuX=BChk(uX,refXlen),BuX1=BChk(uX+1,refXlen))
{
-
- temp = (linear_wts[0] * CalcValueType(m_ref_data[BuY][BuX]) +
- linear_wts[1] * CalcValueType(m_ref_data[BuY][BuX1]) +
- linear_wts[2] * CalcValueType(m_ref_data[BuY1][BuX]) +
- linear_wts[3] * CalcValueType(m_ref_data[BuY1][BuX1]) +
- 2
- ) >> 2;
- sum += std::abs(temp - m_pic_data[y][x]);
+
+ temp = ( linear_wts[0] * CalcValueType( m_ref_data[BuY][BuX] ) +
+ linear_wts[1] * CalcValueType( m_ref_data[BuY][BuX1] ) +
+ linear_wts[2] * CalcValueType( m_ref_data[BuY1][BuX] )+
+ linear_wts[3] * CalcValueType( m_ref_data[BuY1][BuX1] ) +
+ 2
+ ) >> 2;
+ sum += std::abs( temp - m_pic_data[y][x] );
}// x
-
- if(sum >= best_costs.total)
+
+ if ( sum>=best_costs.total )
return;
}// y
@@ -892,101 +887,100 @@ void BlockDiffQuarterPel::Diff(const BlockDiffParams& dparams,
best_costs.SAD = sum - start_val;
}
-float BlockDiffEighthPel::Diff(const BlockDiffParams& dparams , const MVector& mv)
+float BlockDiffEighthPel::Diff( const BlockDiffParams& dparams , const MVector& mv )
{
- if(dparams.Xl() <= 0 || dparams.Yl() <= 0)
+ if (dparams.Xl() <= 0 || dparams.Yl() <= 0)
{
- return 0;
+ return 0;
}
- //Set up the start point in the reference image by rounding the motion vector
+ //Set up the start point in the reference image by rounding the motion vector
//NB: bit shift rounds negative values DOWN, as required
- const MVector roundvec(mv.x >> 2 , mv.y >> 2);
+ const MVector roundvec( mv.x>>2 , mv.y>>2 );
//Get the remainder after rounding. NB rmdr values always 0,1,2 or 3
- const MVector rmdr(mv.x & 3 , mv.y & 3);
+ const MVector rmdr( mv.x & 3 , mv.y & 3 );
//Where to start in the upconverted image
- const ImageCoords ref_start((dparams.Xp() << 1) + roundvec.x , (dparams.Yp() << 1) + roundvec.y);
- const ImageCoords ref_stop(ref_start.x + (dparams.Xl() << 1) , ref_start.y + (dparams.Yl() << 1));
+ const ImageCoords ref_start( ( dparams.Xp()<<1 ) + roundvec.x ,( dparams.Yp()<<1 ) + roundvec.y );
+ const ImageCoords ref_stop( ref_start.x+(dparams.Xl()<<1) , ref_start.y+(dparams.Yl()<<1));
ValueType* pic_curr = &m_pic_data[dparams.Yp()][dparams.Xp()];
- const int pic_next(m_pic_data.LengthX() - dparams.Xl()); // go down a row and back up
+ const int pic_next( m_pic_data.LengthX() - dparams.Xl() );// go down a row and back up
//weights for doing linear interpolation, calculated from the remainder values
- const ValueType linear_wts[4] = { (4 - rmdr.x) *(4 - rmdr.y), //tl
- rmdr.x *(4 - rmdr.y), //tr
+ const ValueType linear_wts[4] = { (4 - rmdr.x) * (4 - rmdr.y), //tl
+ rmdr.x * (4 - rmdr.y), //tr
(4 - rmdr.x) * rmdr.y, //bl
- rmdr.x * rmdr.y
- }; //br
+ rmdr.x * rmdr.y }; //br
- bool bounds_check(false);
+ bool bounds_check( false );
- if(ref_start.x < 0 ||
- ref_stop.x >= m_ref_data.LengthX() ||
- ref_start.y < 0 ||
- ref_stop.y >= m_ref_data.LengthY())
+ if ( ref_start.x<0 ||
+ ref_stop.x >= m_ref_data.LengthX() ||
+ ref_start.y<0 ||
+ ref_stop.y >= m_ref_data.LengthY() )
bounds_check = true;
- float sum(0.0f);
+ float sum( 0.0f );
CalcValueType temp;
- if(!bounds_check)
+ if ( !bounds_check )
{
ValueType *ref_curr = &m_ref_data[ref_start.y][ref_start.x];
- const int ref_next((m_ref_data.LengthX() - dparams.Xl()) * 2);// go down 2 rows and back up
+ const int ref_next( (m_ref_data.LengthX() - dparams.Xl())*2 );// go down 2 rows and back up
- if(rmdr.x == 0 && rmdr.y == 0)
+ if( rmdr.x == 0 && rmdr.y == 0 )
{
- for(int y = dparams.Yl(); y > 0; --y, pic_curr += pic_next, ref_curr += ref_next)
+ for( int y=dparams.Yl(); y > 0; --y, pic_curr+=pic_next, ref_curr+=ref_next )
{
- for(int x = dparams.Xl(); x > 0; --x, ++pic_curr, ref_curr += 2)
+ for( int x=dparams.Xl(); x > 0; --x, ++pic_curr, ref_curr+=2 )
{
- sum += CalcValueType(std::abs(ref_curr[0] - *pic_curr));
+ sum += CalcValueType( std::abs( ref_curr[0] - *pic_curr ) );
}// x
}// y
}
- else if(rmdr.y == 0)
+ else if( rmdr.y == 0 )
{
- for(int y = dparams.Yl(); y > 0; --y, pic_curr += pic_next, ref_curr += ref_next)
+ for( int y=dparams.Yl(); y > 0; --y, pic_curr+=pic_next, ref_curr+=ref_next )
{
- for(int x = dparams.Xl(); x > 0; --x, ++pic_curr, ref_curr += 2)
+ for( int x=dparams.Xl(); x > 0; --x, ++pic_curr, ref_curr+=2 )
{
- temp = ((linear_wts[0] * CalcValueType(ref_curr[0]) +
- linear_wts[1] * CalcValueType(ref_curr[1]) +
- 8
+ temp = (( linear_wts[0] * CalcValueType( ref_curr[0] ) +
+ linear_wts[1] * CalcValueType( ref_curr[1] ) +
+ 8
) >> 4);
- sum += std::abs(temp - *pic_curr);
+ sum += std::abs( temp - *pic_curr );
}// x
}// y
}
- else if(rmdr.x == 0)
+ else if( rmdr.x == 0 )
{
- for(int y = dparams.Yl(); y > 0; --y, pic_curr += pic_next, ref_curr += ref_next)
+ for( int y=dparams.Yl(); y > 0; --y, pic_curr+=pic_next, ref_curr+=ref_next )
{
- for(int x = dparams.Xl(); x > 0; --x, ++pic_curr, ref_curr += 2)
+ for( int x=dparams.Xl(); x > 0; --x, ++pic_curr, ref_curr+=2 )
{
- temp = ((linear_wts[0] * CalcValueType(ref_curr[0]) +
- linear_wts[2] * CalcValueType(ref_curr[m_ref_data.LengthX()+0]) +
- 8
- ) >> 4);
- sum += std::abs(temp - *pic_curr);
+ temp = (( linear_wts[0] * CalcValueType( ref_curr[0] ) +
+ linear_wts[2] * CalcValueType( ref_curr[m_ref_data.LengthX()+0] ) +
+ 8
+ ) >> 4);
+ sum += std::abs( temp - *pic_curr );
}// x
}// y
}
else
{
- for(int y = dparams.Yl(); y > 0; --y, pic_curr += pic_next, ref_curr += ref_next)
+ for( int y=dparams.Yl(); y > 0; --y, pic_curr+=pic_next, ref_curr+=ref_next )
{
- for(int x = dparams.Xl(); x > 0; --x, ++pic_curr, ref_curr += 2)
+ for( int x=dparams.Xl(); x > 0; --x, ++pic_curr, ref_curr+=2 )
{
- temp = ((linear_wts[0] * CalcValueType(ref_curr[0]) +
- linear_wts[1] * CalcValueType(ref_curr[1]) +
- linear_wts[2] * CalcValueType(ref_curr[m_ref_data.LengthX()+0]) +
- linear_wts[3] * CalcValueType(ref_curr[m_ref_data.LengthX()+1]) +
- 8
+ temp = (( linear_wts[0] * CalcValueType( ref_curr[0] ) +
+ linear_wts[1] * CalcValueType( ref_curr[1] ) +
+ linear_wts[2] * CalcValueType( ref_curr[m_ref_data.LengthX()+0] ) +
+ linear_wts[3] * CalcValueType( ref_curr[m_ref_data.LengthX()+1] ) +
+ 8
) >> 4);
- sum += std::abs(temp - *pic_curr);
+ sum += std::abs( temp - *pic_curr );
}// x
}// y
}
@@ -994,23 +988,23 @@ float BlockDiffEighthPel::Diff(const BlockDiffParams& dparams , const MVector& m
else
{
// We're doing bounds checking because we'll fall off the edge of the reference otherwise.
- const int refXlen(m_ref_data.LengthX());
- const int refYlen(m_ref_data.LengthY());
+ const int refXlen( m_ref_data.LengthX() );
+ const int refYlen( m_ref_data.LengthY() );
- for(int y = dparams.Yp(), uY = ref_start.y, BuY = BChk(uY, refYlen), BuY1 = BChk(uY + 1, refYlen);
- y < dparams.Yend(); ++y, uY += 2, BuY = BChk(uY, refYlen), BuY1 = BChk(uY + 1, refYlen))
+ for(int y = dparams.Yp(), uY = ref_start.y,BuY=BChk(uY,refYlen),BuY1=BChk(uY+1,refYlen);
+ y < dparams.Yend(); ++y, uY += 2,BuY=BChk(uY,refYlen),BuY1=BChk(uY+1,refYlen))
{
- for(int x = dparams.Xp(), uX = ref_start.x, BuX = BChk(uX, refXlen), BuX1 = BChk(uX + 1, refXlen);
- x < dparams.Xend(); ++x, uX += 2, BuX = BChk(uX, refXlen), BuX1 = BChk(uX + 1, refXlen))
+ for(int x = dparams.Xp(), uX = ref_start.x,BuX=BChk(uX,refXlen),BuX1=BChk(uX+1,refXlen);
+ x < dparams.Xend(); ++x, uX += 2,BuX=BChk(uX,refXlen),BuX1=BChk(uX+1,refXlen))
{
-
- temp = (linear_wts[0] * CalcValueType(m_ref_data[BuY][BuX]) +
- linear_wts[1] * CalcValueType(m_ref_data[BuY][BuX1]) +
- linear_wts[2] * CalcValueType(m_ref_data[BuY1][BuX]) +
- linear_wts[3] * CalcValueType(m_ref_data[BuY1][BuX1]) +
- 8
- ) >> 4;
- sum += std::abs(temp - m_pic_data[y][x]);
+
+ temp = ( linear_wts[0] * CalcValueType( m_ref_data[BuY][BuX] ) +
+ linear_wts[1] * CalcValueType( m_ref_data[BuY][BuX1] ) +
+ linear_wts[2] * CalcValueType( m_ref_data[BuY1][BuX] )+
+ linear_wts[3] * CalcValueType( m_ref_data[BuY1][BuX1] ) +
+ 8
+ ) >> 4;
+ sum += std::abs( temp - m_pic_data[y][x] );
}// x
}// y
@@ -1019,122 +1013,121 @@ float BlockDiffEighthPel::Diff(const BlockDiffParams& dparams , const MVector& m
return sum;
}
-void BlockDiffEighthPel::Diff(const BlockDiffParams& dparams,
- const MVector& mv ,
- const float mvcost,
- const float lambda,
- MvCostData& best_costs ,
- MVector& best_mv)
+void BlockDiffEighthPel::Diff( const BlockDiffParams& dparams,
+ const MVector& mv ,
+ const float mvcost,
+ const float lambda,
+ MvCostData& best_costs ,
+ MVector& best_mv)
{
- if(dparams.Xl() <= 0 || dparams.Yl() <= 0)
+ if (dparams.Xl() <= 0 || dparams.Yl() <= 0)
{
- return;
+ return;
}
//Set up the start point in the reference image by rounding the motion vector
//NB: bit shift rounds negative values DOWN, as required
- const MVector roundvec(mv.x >> 2 , mv.y >> 2);
+ const MVector roundvec( mv.x>>2 , mv.y>>2 );
//Get the remainder after rounding. NB rmdr values always 0,1,2 or 3
- const MVector rmdr(mv.x & 3 , mv.y & 3);
+ const MVector rmdr( mv.x & 3 , mv.y & 3 );
//Where to start in the upconverted image
- const ImageCoords ref_start((dparams.Xp() << 1) + roundvec.x , (dparams.Yp() << 1) + roundvec.y);
- const ImageCoords ref_stop(ref_start.x + (dparams.Xl() << 1) , ref_start.y + (dparams.Yl() << 1));
+ const ImageCoords ref_start( ( dparams.Xp()<<1 ) + roundvec.x ,( dparams.Yp()<<1 ) + roundvec.y );
+ const ImageCoords ref_stop( ref_start.x+(dparams.Xl()<<1) , ref_start.y+(dparams.Yl()<<1));
ValueType* pic_curr = &m_pic_data[dparams.Yp()][dparams.Xp()];
- const int pic_next(m_pic_data.LengthX() - dparams.Xl()); // go down a row and back up
+ const int pic_next( m_pic_data.LengthX() - dparams.Xl() );// go down a row and back up
//weights for doing linear interpolation, calculated from the remainder values
- const ValueType linear_wts[4] = { (4 - rmdr.x) *(4 - rmdr.y), //tl
- rmdr.x *(4 - rmdr.y), //tr
+ const ValueType linear_wts[4] = { (4 - rmdr.x) * (4 - rmdr.y), //tl
+ rmdr.x * (4 - rmdr.y), //tr
(4 - rmdr.x) * rmdr.y, //bl
- rmdr.x * rmdr.y
- }; //br
+ rmdr.x * rmdr.y }; //br
- bool bounds_check(false);
+ bool bounds_check( false );
- if(ref_start.x < 0 ||
- ref_stop.x >= m_ref_data.LengthX() ||
- ref_start.y < 0 ||
- ref_stop.y >= m_ref_data.LengthY())
+ if ( ref_start.x<0 ||
+ ref_stop.x >= m_ref_data.LengthX() ||
+ ref_start.y<0 ||
+ ref_stop.y >= m_ref_data.LengthY() )
bounds_check = true;
- const float start_val(mvcost * lambda);
- float sum(start_val);
+ const float start_val( mvcost*lambda );
+ float sum( start_val );
CalcValueType temp;
- if(!bounds_check)
+ if ( !bounds_check )
{
ValueType *ref_curr = &m_ref_data[ref_start.y][ref_start.x];
- const int ref_next((m_ref_data.LengthX() - dparams.Xl()) * 2);// go down 2 rows and back up
+ const int ref_next( (m_ref_data.LengthX() - dparams.Xl())*2 );// go down 2 rows and back up
- if(rmdr.x == 0 && rmdr.y == 0)
+ if( rmdr.x == 0 && rmdr.y == 0 )
{
- for(int y = dparams.Yl(); y > 0; --y, pic_curr += pic_next, ref_curr += ref_next)
+ for( int y=dparams.Yl(); y > 0; --y, pic_curr+=pic_next, ref_curr+=ref_next )
{
- for(int x = dparams.Xl(); x > 0; --x, ++pic_curr, ref_curr += 2)
+ for( int x=dparams.Xl(); x > 0; --x, ++pic_curr, ref_curr+=2 )
{
- sum += CalcValueType(std::abs(ref_curr[0] - *pic_curr));
+ sum += CalcValueType( std::abs( ref_curr[0] - *pic_curr ) );
}// x
-
- if(sum >= best_costs.total)
+
+ if ( sum>=best_costs.total )
return;
}// y
}
- else if(rmdr.y == 0)
+ else if( rmdr.y == 0 )
{
- for(int y = dparams.Yl(); y > 0; --y, pic_curr += pic_next, ref_curr += ref_next)
+ for( int y=dparams.Yl(); y > 0; --y, pic_curr+=pic_next, ref_curr+=ref_next )
{
- for(int x = dparams.Xl(); x > 0; --x, ++pic_curr, ref_curr += 2)
+ for( int x=dparams.Xl(); x > 0; --x, ++pic_curr, ref_curr+=2 )
{
- temp = ((linear_wts[0] * CalcValueType(ref_curr[0]) +
- linear_wts[1] * CalcValueType(ref_curr[1]) +
- 8
+ temp = (( linear_wts[0] * CalcValueType( ref_curr[0] ) +
+ linear_wts[1] * CalcValueType( ref_curr[1] ) +
+ 8
) >> 4);
- sum += std::abs(temp - *pic_curr);
+ sum += std::abs( temp - *pic_curr );
}// x
-
- if(sum >= best_costs.total)
+
+ if ( sum>=best_costs.total )
return;
}// y
}
- else if(rmdr.x == 0)
+ else if( rmdr.x == 0 )
{
- for(int y = dparams.Yl(); y > 0; --y, pic_curr += pic_next, ref_curr += ref_next)
+ for( int y=dparams.Yl(); y > 0; --y, pic_curr+=pic_next, ref_curr+=ref_next )
{
- for(int x = dparams.Xl(); x > 0; --x, ++pic_curr, ref_curr += 2)
+ for( int x=dparams.Xl(); x > 0; --x, ++pic_curr, ref_curr+=2 )
{
- temp = ((linear_wts[0] * CalcValueType(ref_curr[0]) +
- linear_wts[2] * CalcValueType(ref_curr[m_ref_data.LengthX()+0]) +
- 8
- ) >> 4);
- sum += std::abs(temp - *pic_curr);
+ temp = (( linear_wts[0] * CalcValueType( ref_curr[0] ) +
+ linear_wts[2] * CalcValueType( ref_curr[m_ref_data.LengthX()+0] ) +
+ 8
+ ) >> 4);
+ sum += std::abs( temp - *pic_curr );
}// x
-
- if(sum >= best_costs.total)
+
+ if ( sum>=best_costs.total )
return;
}// y
}
else
{
- for(int y = dparams.Yl(); y > 0; --y, pic_curr += pic_next, ref_curr += ref_next)
+ for( int y=dparams.Yl(); y > 0; --y, pic_curr+=pic_next, ref_curr+=ref_next )
{
- for(int x = dparams.Xl(); x > 0; --x, ++pic_curr, ref_curr += 2)
+ for( int x=dparams.Xl(); x > 0; --x, ++pic_curr, ref_curr+=2 )
{
- temp = ((linear_wts[0] * CalcValueType(ref_curr[0]) +
- linear_wts[1] * CalcValueType(ref_curr[1]) +
- linear_wts[2] * CalcValueType(ref_curr[m_ref_data.LengthX()+0]) +
- linear_wts[3] * CalcValueType(ref_curr[m_ref_data.LengthX()+1]) +
- 8
+ temp = (( linear_wts[0] * CalcValueType( ref_curr[0] ) +
+ linear_wts[1] * CalcValueType( ref_curr[1] ) +
+ linear_wts[2] * CalcValueType( ref_curr[m_ref_data.LengthX()+0] ) +
+ linear_wts[3] * CalcValueType( ref_curr[m_ref_data.LengthX()+1] ) +
+ 8
) >> 4);
- sum += std::abs(temp - *pic_curr);
+ sum += std::abs( temp - *pic_curr );
}// x
-
- if(sum >= best_costs.total)
+
+ if ( sum>=best_costs.total )
return;
}// y
@@ -1143,26 +1136,26 @@ void BlockDiffEighthPel::Diff(const BlockDiffParams& dparams,
else
{
// We're doing bounds checking because we'll fall off the edge of the reference otherwise.
- const int refXlen(m_ref_data.LengthX());
- const int refYlen(m_ref_data.LengthY());
+ const int refXlen( m_ref_data.LengthX() );
+ const int refYlen( m_ref_data.LengthY() );
- for(int y = dparams.Yp(), uY = ref_start.y, BuY = BChk(uY, refYlen), BuY1 = BChk(uY + 1, refYlen);
- y < dparams.Yend(); ++y, uY += 2, BuY = BChk(uY, refYlen), BuY1 = BChk(uY + 1, refYlen))
+ for(int y = dparams.Yp(), uY = ref_start.y,BuY=BChk(uY,refYlen),BuY1=BChk(uY+1,refYlen);
+ y < dparams.Yend(); ++y, uY += 2,BuY=BChk(uY,refYlen),BuY1=BChk(uY+1,refYlen))
{
- for(int x = dparams.Xp(), uX = ref_start.x, BuX = BChk(uX, refXlen), BuX1 = BChk(uX + 1, refXlen);
- x < dparams.Xend(); ++x, uX += 2, BuX = BChk(uX, refXlen), BuX1 = BChk(uX + 1, refXlen))
+ for(int x = dparams.Xp(), uX = ref_start.x,BuX=BChk(uX,refXlen),BuX1=BChk(uX+1,refXlen);
+ x < dparams.Xend(); ++x, uX += 2,BuX=BChk(uX,refXlen),BuX1=BChk(uX+1,refXlen))
{
-
- temp = (linear_wts[0] * CalcValueType(m_ref_data[BuY][BuX]) +
- linear_wts[1] * CalcValueType(m_ref_data[BuY][BuX1]) +
- linear_wts[2] * CalcValueType(m_ref_data[BuY1][BuX]) +
- linear_wts[3] * CalcValueType(m_ref_data[BuY1][BuX1]) +
- 8
- ) >> 4;
- sum += std::abs(temp - m_pic_data[y][x]);
+
+ temp = ( linear_wts[0] * CalcValueType( m_ref_data[BuY][BuX] ) +
+ linear_wts[1] * CalcValueType( m_ref_data[BuY][BuX1] ) +
+ linear_wts[2] * CalcValueType( m_ref_data[BuY1][BuX] )+
+ linear_wts[3] * CalcValueType( m_ref_data[BuY1][BuX1] ) +
+ 8
+ ) >> 4;
+ sum += std::abs( temp - m_pic_data[y][x] );
}// x
-
- if(sum >= best_costs.total)
+
+ if ( sum>=best_costs.total )
return;
}// y
@@ -1176,47 +1169,47 @@ void BlockDiffEighthPel::Diff(const BlockDiffParams& dparams,
best_costs.SAD = sum - start_val;
}
-float BiBlockHalfPel::Diff(const BlockDiffParams& dparams ,
- const MVector& mv1 ,
- const MVector& mv2)
+float BiBlockHalfPel::Diff( const BlockDiffParams& dparams ,
+ const MVector& mv1 ,
+ const MVector& mv2 )
{
- if(dparams.Xl() <= 0 || dparams.Yl() <= 0)
+ if (dparams.Xl() <= 0 || dparams.Yl() <= 0)
{
- return 0;
+ return 0;
}
// First create a difference array, and subtract the reference 1 data into it
- TwoDArray<ValueType> diff_array(dparams.Yl() , dparams.Xl());
+ TwoDArray<ValueType> diff_array( dparams.Yl() , dparams.Xl() );
//Where to start in the upconverted images
- const ImageCoords ref_start1((dparams.Xp() << 1) + mv1.x , (dparams.Yp() << 1) + mv1.y);
- const ImageCoords ref_stop1(ref_start1.x + (dparams.Xl() << 1) , ref_start1.y + (dparams.Yl() << 1));
+ const ImageCoords ref_start1( ( dparams.Xp()<<1 ) + mv1.x ,( dparams.Yp()<<1 ) + mv1.y );
+ const ImageCoords ref_stop1( ref_start1.x+(dparams.Xl()<<1) , ref_start1.y+(dparams.Yl()<<1));
- const ImageCoords ref_start2((dparams.Xp() << 1) + mv2.x , (dparams.Yp() << 1) + mv2.y);
- const ImageCoords ref_stop2(ref_start2.x + (dparams.Xl() << 1) , ref_start2.y + (dparams.Yl() << 1));
+ const ImageCoords ref_start2( ( dparams.Xp()<<1 ) + mv2.x ,( dparams.Yp()<<1 ) + mv2.y );
+ const ImageCoords ref_stop2( ref_start2.x+(dparams.Xl()<<1) , ref_start2.y+(dparams.Yl()<<1));
ValueType* pic_curr = &m_pic_data[dparams.Yp()][dparams.Xp()];
- const int pic_next(m_pic_data.LengthX() - dparams.Xl()); // go down a row and back up
+ const int pic_next( m_pic_data.LengthX() - dparams.Xl() );// go down a row and back up
ValueType* diff_curr = &diff_array[0][0];
- bool bounds_check(false);
+ bool bounds_check( false );
- if(ref_start1.x < 0 ||
- ref_stop1.x >= m_ref_data1.LengthX() ||
- ref_start1.y < 0 ||
- ref_stop1.y >= m_ref_data1.LengthY())
+ if ( ref_start1.x<0 ||
+ ref_stop1.x >= m_ref_data1.LengthX() ||
+ ref_start1.y<0 ||
+ ref_stop1.y >= m_ref_data1.LengthY() )
bounds_check = true;
- if(!bounds_check)
+ if ( !bounds_check )
{
ValueType *ref_curr = &m_ref_data1[ref_start1.y][ref_start1.x];
- const int ref_next((m_ref_data1.LengthX() - dparams.Xl()) * 2);// go down 2 rows and back up
+ const int ref_next( (m_ref_data1.LengthX() - dparams.Xl())*2 );// go down 2 rows and back up
- for(int y = dparams.Yl(); y > 0; --y, pic_curr += pic_next, ref_curr += ref_next)
+ for( int y=dparams.Yl(); y > 0; --y, pic_curr+=pic_next, ref_curr+=ref_next)
{
- for(int x = dparams.Xl(); x > 0; --x, ++pic_curr, ref_curr += 2, ++diff_curr)
+ for( int x=dparams.Xl(); x > 0; --x, ++pic_curr, ref_curr+=2, ++diff_curr )
{
- *diff_curr = ((*pic_curr) << 1) - *ref_curr;
+ *diff_curr = ( (*pic_curr)<<1 ) - *ref_curr;
}// x
}// y
@@ -1225,16 +1218,16 @@ float BiBlockHalfPel::Diff(const BlockDiffParams& dparams ,
else
{
// We're doing bounds checking because we'll fall off the edge of the reference otherwise.
- for(int y = dparams.Yl(), ry = ref_start1.y, by = BChk(ry, m_ref_data1.LengthY());
- y > 0;
- --y, pic_curr += pic_next, ry += 2 , by = BChk(ry, m_ref_data1.LengthY()))
+ for( int y=dparams.Yl(), ry=ref_start1.y, by=BChk(ry,m_ref_data1.LengthY());
+ y>0;
+ --y, pic_curr+=pic_next, ry+=2 , by=BChk(ry,m_ref_data1.LengthY()))
{
- for(int x = dparams.Xl() , rx = ref_start1.x , bx = BChk(rx, m_ref_data1.LengthX());
- x > 0 ;
- --x, ++pic_curr, rx += 2 , ++diff_curr, bx = BChk(rx, m_ref_data1.LengthX()))
- {
- *diff_curr = ((*pic_curr) << 1) - m_ref_data1[by][bx];
- }// x
+ for( int x=dparams.Xl() , rx=ref_start1.x , bx=BChk(rx,m_ref_data1.LengthX());
+ x>0 ;
+ --x, ++pic_curr, rx+=2 , ++diff_curr, bx=BChk(rx,m_ref_data1.LengthX()))
+ {
+ *diff_curr = ( (*pic_curr)<<1 ) - m_ref_data1[by][bx];
+ }// x
}// y
}
@@ -1243,28 +1236,28 @@ float BiBlockHalfPel::Diff(const BlockDiffParams& dparams ,
bounds_check = false;
- if(ref_start2.x < 0 ||
- ref_stop2.x >= m_ref_data2.LengthX() ||
- ref_start2.y < 0 ||
- ref_stop2.y >= m_ref_data2.LengthY())
+ if ( ref_start2.x<0 ||
+ ref_stop2.x >= m_ref_data2.LengthX() ||
+ ref_start2.y<0 ||
+ ref_stop2.y >= m_ref_data2.LengthY() )
bounds_check = true;
- float sum(0);
+ float sum( 0 );
diff_curr = &diff_array[0][0];
ValueType temp;
- if(!bounds_check)
+ if ( !bounds_check )
{
ValueType *ref_curr = &m_ref_data2[ref_start2.y][ref_start2.x];
- const int ref_next((m_ref_data2.LengthX() - dparams.Xl()) * 2);// go down 2 rows and back up
+ const int ref_next( (m_ref_data2.LengthX() - dparams.Xl())*2 );// go down 2 rows and back up
- for(int y = dparams.Yl(); y > 0; --y, pic_curr += pic_next, ref_curr += ref_next)
+ for( int y=dparams.Yl(); y > 0; --y, pic_curr+=pic_next, ref_curr+=ref_next)
{
- for(int x = dparams.Xl(); x > 0; --x, ++pic_curr, ref_curr += 2, ++diff_curr)
+ for( int x=dparams.Xl(); x > 0; --x, ++pic_curr, ref_curr+=2, ++diff_curr )
{
- temp = (*diff_curr - *ref_curr) >> 1;
- sum += std::abs(temp);
+ temp = (*diff_curr - *ref_curr )>>1;
+ sum += std::abs( temp );
}// x
}// y
@@ -1273,17 +1266,17 @@ float BiBlockHalfPel::Diff(const BlockDiffParams& dparams ,
else
{
// We're doing bounds checking because we'll fall off the edge of the reference otherwise.
- for(int y = dparams.Yl(), ry = ref_start2.y, by = BChk(ry, m_ref_data2.LengthY());
- y > 0;
- --y, pic_curr += pic_next, ry += 2 , by = BChk(ry, m_ref_data2.LengthY()))
+ for( int y=dparams.Yl(), ry=ref_start2.y, by=BChk(ry,m_ref_data2.LengthY());
+ y>0;
+ --y, pic_curr+=pic_next, ry+=2 , by=BChk(ry,m_ref_data2.LengthY()))
{
- for(int x = dparams.Xl() , rx = ref_start2.x , bx = BChk(rx, m_ref_data2.LengthX());
- x > 0 ;
- --x, ++pic_curr, rx += 2 , ++diff_curr, bx = BChk(rx, m_ref_data2.LengthX()))
- {
- temp = (*diff_curr - m_ref_data2[by][bx]) >> 1;
- sum += std::abs(temp);
- }// x
+ for( int x=dparams.Xl() , rx=ref_start2.x , bx=BChk(rx,m_ref_data2.LengthX());
+ x>0 ;
+ --x, ++pic_curr, rx+=2 , ++diff_curr, bx=BChk(rx,m_ref_data2.LengthX()))
+ {
+ temp = (*diff_curr - m_ref_data2[by][bx] )>>1;
+ sum += std::abs( temp );
+ }// x
}// y
}
@@ -1292,116 +1285,116 @@ float BiBlockHalfPel::Diff(const BlockDiffParams& dparams ,
}
-float BiBlockQuarterPel::Diff(const BlockDiffParams& dparams ,
- const MVector& mv1 ,
- const MVector& mv2)
+float BiBlockQuarterPel::Diff( const BlockDiffParams& dparams ,
+ const MVector& mv1 ,
+ const MVector& mv2 )
{
- if(dparams.Xl() <= 0 || dparams.Yl() <= 0)
+ if (dparams.Xl() <= 0 || dparams.Yl() <= 0)
{
- return 0;
+ return 0;
}
// First create a difference array, and subtract the reference 1 data into it
- TwoDArray<ValueType> diff_array(dparams.Yl() , dparams.Xl());
+ TwoDArray<ValueType> diff_array( dparams.Yl() , dparams.Xl() );
- // Set up the start point in the reference images by rounding the motion vectors
+ // Set up the start point in the reference images by rounding the motion vectors
// to 1/2 pel accuracy.NB: bit shift rounds negative values DOWN, as required
- const MVector roundvec1(mv1.x >> 1 , mv1.y >> 1);
- const MVector roundvec2(mv2.x >> 1 , mv2.y >> 1);
+ const MVector roundvec1 ( mv1.x>>1 , mv1.y>>1 );
+ const MVector roundvec2 ( mv2.x>>1 , mv2.y>>1 );
- //Get the remainders after rounding. NB rmdr values always 0 or 1
- const MVector rmdr1(mv1.x & 1 , mv1.y & 1);
- const MVector rmdr2(mv2.x & 1 , mv2.y & 1);
+ //Get the remainders after rounding. NB rmdr values always 0 or 1
+ const MVector rmdr1( mv1.x & 1 , mv1.y & 1 );
+ const MVector rmdr2( mv2.x & 1 , mv2.y & 1 );
//Where to start in the upconverted images
- const ImageCoords ref_start1((dparams.Xp() << 1) + roundvec1.x , (dparams.Yp() << 1) + roundvec1.y);
- const ImageCoords ref_stop1(ref_start1.x + (dparams.Xl() << 1) , ref_start1.y + (dparams.Yl() << 1));
+ const ImageCoords ref_start1( ( dparams.Xp()<<1 ) + roundvec1.x ,( dparams.Yp()<<1 ) + roundvec1.y );
+ const ImageCoords ref_stop1( ref_start1.x+(dparams.Xl()<<1) , ref_start1.y+(dparams.Yl()<<1));
- const ImageCoords ref_start2((dparams.Xp() << 1) + roundvec2.x , (dparams.Yp() << 1) + roundvec2.y);
- const ImageCoords ref_stop2(ref_start2.x + (dparams.Xl() << 1) , ref_start2.y + (dparams.Yl() << 1));
+ const ImageCoords ref_start2( ( dparams.Xp()<<1 ) + roundvec2.x ,( dparams.Yp()<<1 ) + roundvec2.y );
+ const ImageCoords ref_stop2( ref_start2.x+(dparams.Xl()<<1) , ref_start2.y+(dparams.Yl()<<1));
ValueType* pic_curr = &m_pic_data[dparams.Yp()][dparams.Xp()];
- const int pic_next(m_pic_data.LengthX() - dparams.Xl()); // go down a row and back up
+ const int pic_next( m_pic_data.LengthX() - dparams.Xl() );// go down a row and back up
ValueType* diff_curr = &diff_array[0][0];
- bool bounds_check(false);
+ bool bounds_check( false );
- if(ref_start1.x < 0 ||
- ref_stop1.x >= m_ref_data1.LengthX() ||
- ref_start1.y < 0 ||
- ref_stop1.y >= m_ref_data1.LengthY())
+ if ( ref_start1.x<0 ||
+ ref_stop1.x >= m_ref_data1.LengthX() ||
+ ref_start1.y<0 ||
+ ref_stop1.y >= m_ref_data1.LengthY() )
bounds_check = true;
ValueType temp;
- if(!bounds_check)
+ if ( !bounds_check )
{
#if defined (HAVE_MMX)
const ImageCoords start_pos(dparams.Xp(), dparams.Yp());
const ImageCoords end_pos(dparams.Xp() + dparams.Xl(), dparams.Yp() + dparams.Yl());
-
- simple_biblock_diff_pic_mmx_4(m_pic_data, m_ref_data1, diff_array,
- start_pos, end_pos,
- ref_start1, ref_stop1,
- rmdr1);
+
+ simple_biblock_diff_pic_mmx_4 (m_pic_data, m_ref_data1, diff_array,
+ start_pos, end_pos,
+ ref_start1, ref_stop1,
+ rmdr1);
#else
ValueType *ref_curr = &m_ref_data1[ref_start1.y][ref_start1.x];
- const int ref_next((m_ref_data1.LengthX() - dparams.Xl()) * 2);// go down 2 rows and back up
+ const int ref_next( (m_ref_data1.LengthX() - dparams.Xl())*2 );// go down 2 rows and back up
- if(rmdr1.x == 0 && rmdr1.y == 0)
+ if( rmdr1.x == 0 && rmdr1.y == 0 )
{
- for(int y = dparams.Yl(); y > 0; --y, pic_curr += pic_next, ref_curr += ref_next)
+ for( int y=dparams.Yl(); y > 0; --y, pic_curr+=pic_next, ref_curr+=ref_next )
{
- for(int x = dparams.Xl(); x > 0; --x, ++pic_curr, ref_curr += 2, ++diff_curr)
+ for( int x=dparams.Xl(); x > 0; --x, ++pic_curr, ref_curr+=2, ++diff_curr )
{
- *diff_curr = ((*pic_curr) << 1) - *ref_curr;
+ *diff_curr = ( (*pic_curr)<<1 ) - *ref_curr;
}// x
}// y
}
- else if(rmdr1.y == 0)
+ else if( rmdr1.y == 0 )
{
- for(int y = dparams.Yl(); y > 0; --y, pic_curr += pic_next, ref_curr += ref_next)
+ for( int y=dparams.Yl(); y > 0; --y, pic_curr+=pic_next, ref_curr+=ref_next )
{
- for(int x = dparams.Xl(); x > 0; --x, ++pic_curr, ref_curr += 2, ++diff_curr)
+ for( int x=dparams.Xl(); x > 0; --x, ++pic_curr, ref_curr+=2, ++diff_curr )
{
- temp = (CalcValueType(ref_curr[0]) +
- CalcValueType(ref_curr[1]) +
- 1
- ) >> 1;
+ temp = ( CalcValueType( ref_curr[0] ) +
+ CalcValueType( ref_curr[1] ) +
+ 1
+ ) >> 1;
- *diff_curr = ((*pic_curr) << 1) - temp;
+ *diff_curr = ( (*pic_curr)<<1 ) - temp;
}// x
}// y
}
- else if(rmdr1.x == 0)
+ else if( rmdr1.x == 0 )
{
- for(int y = dparams.Yl(); y > 0; --y, pic_curr += pic_next, ref_curr += ref_next)
+ for( int y=dparams.Yl(); y > 0; --y, pic_curr+=pic_next, ref_curr+=ref_next )
{
- for(int x = dparams.Xl(); x > 0; --x, ++pic_curr, ref_curr += 2, ++diff_curr)
+ for( int x=dparams.Xl(); x > 0; --x, ++pic_curr, ref_curr+=2, ++diff_curr )
{
- temp = (CalcValueType(ref_curr[0]) +
- CalcValueType(ref_curr[m_ref_data1.LengthX()]) +
- 1
- ) >> 1;
- *diff_curr = ((*pic_curr) << 1) - temp;
+ temp = ( CalcValueType( ref_curr[0] ) +
+ CalcValueType( ref_curr[m_ref_data1.LengthX()] ) +
+ 1
+ ) >> 1;
+ *diff_curr = ( (*pic_curr)<<1 ) - temp;
}// x
}// y
}
else
{
- for(int y = dparams.Yl(); y > 0; --y, pic_curr += pic_next, ref_curr += ref_next)
+ for( int y=dparams.Yl(); y > 0; --y, pic_curr+=pic_next, ref_curr+=ref_next )
{
- for(int x = dparams.Xl(); x > 0; --x, ++pic_curr, ref_curr += 2, ++diff_curr)
+ for( int x=dparams.Xl(); x > 0; --x, ++pic_curr, ref_curr+=2, ++diff_curr )
{
- temp = (CalcValueType(ref_curr[0]) +
- CalcValueType(ref_curr[1]) +
- CalcValueType(ref_curr[m_ref_data1.LengthX()+0]) +
- CalcValueType(ref_curr[m_ref_data1.LengthX()+1]) +
- 2
- ) >> 2;
- *diff_curr = ((*pic_curr) << 1) - temp;
+ temp = ( CalcValueType( ref_curr[0] ) +
+ CalcValueType( ref_curr[1] ) +
+ CalcValueType( ref_curr[m_ref_data1.LengthX()+0] ) +
+ CalcValueType( ref_curr[m_ref_data1.LengthX()+1] ) +
+ 2
+ ) >> 2;
+ *diff_curr = ( (*pic_curr)<<1 ) - temp;
}// x
}// y
}
@@ -1410,29 +1403,28 @@ float BiBlockQuarterPel::Diff(const BlockDiffParams& dparams ,
}
else
{
- const ValueType linear_wts[4] = { (2 - rmdr1.x) *(2 - rmdr1.y), //tl
- rmdr1.x *(2 - rmdr1.y), //tr
+ const ValueType linear_wts[4] = { (2 - rmdr1.x) * (2 - rmdr1.y), //tl
+ rmdr1.x * (2 - rmdr1.y), //tr
(2 - rmdr1.x) * rmdr1.y, //bl
- rmdr1.x * rmdr1.y
- }; //br
+ rmdr1.x * rmdr1.y }; //br
// We're doing bounds checking because we'll fall off the edge of the reference otherwise.
- for(int y = dparams.Yl(), ry = ref_start1.y, by = BChk(ry, m_ref_data1.LengthY()), by1 = BChk(ry + 1, m_ref_data1.LengthY());
- y > 0;
- --y, pic_curr += pic_next, ry += 2 , by = BChk(ry, m_ref_data1.LengthY()), by1 = BChk(ry + 1, m_ref_data1.LengthY()))
+ for( int y=dparams.Yl(), ry=ref_start1.y, by=BChk(ry,m_ref_data1.LengthY()), by1=BChk(ry+1,m_ref_data1.LengthY());
+ y>0;
+ --y, pic_curr+=pic_next, ry+=2 , by=BChk(ry,m_ref_data1.LengthY()), by1=BChk(ry+1,m_ref_data1.LengthY()) )
{
- for(int x = dparams.Xl() , rx = ref_start1.x , bx = BChk(rx, m_ref_data1.LengthX()), bx1 = BChk(rx + 1, m_ref_data1.LengthX());
- x > 0 ;
- --x, ++pic_curr, rx += 2 , ++diff_curr, bx = BChk(rx, m_ref_data1.LengthX()), bx1 = BChk(rx + 1, m_ref_data1.LengthX()))
- {
- temp = (linear_wts[0] * CalcValueType(m_ref_data1[by][bx]) +
- linear_wts[1] * CalcValueType(m_ref_data1[by][bx1]) +
- linear_wts[2] * CalcValueType(m_ref_data1[by1][bx]) +
- linear_wts[3] * CalcValueType(m_ref_data1[by1][bx1]) +
- 2
- ) >> 2;
- *diff_curr = ((*pic_curr) << 1) - temp;
- }// x
+ for( int x=dparams.Xl() , rx=ref_start1.x , bx=BChk(rx,m_ref_data1.LengthX()), bx1=BChk(rx+1,m_ref_data1.LengthX());
+ x>0 ;
+ --x, ++pic_curr, rx+=2 , ++diff_curr, bx=BChk(rx,m_ref_data1.LengthX()), bx1=BChk(rx+1,m_ref_data1.LengthX()))
+ {
+ temp = ( linear_wts[0] * CalcValueType( m_ref_data1[by][bx] ) +
+ linear_wts[1] * CalcValueType( m_ref_data1[by][bx1] ) +
+ linear_wts[2] * CalcValueType( m_ref_data1[by1][bx] )+
+ linear_wts[3] * CalcValueType( m_ref_data1[by1][bx1] ) +
+ 2
+ ) >> 2;
+ *diff_curr = ( (*pic_curr)<<1 ) - temp;
+ }// x
}// y
}
@@ -1440,80 +1432,80 @@ float BiBlockQuarterPel::Diff(const BlockDiffParams& dparams ,
bounds_check = false;
- if(ref_start2.x < 0 ||
- ref_stop2.x >= m_ref_data2.LengthX() ||
- ref_start2.y < 0 ||
- ref_stop2.y >= m_ref_data2.LengthY())
+ if ( ref_start2.x<0 ||
+ ref_stop2.x >= m_ref_data2.LengthX() ||
+ ref_start2.y<0 ||
+ ref_stop2.y >= m_ref_data2.LengthY() )
bounds_check = true;
- float sum(0);
+ float sum( 0 );
diff_curr = &diff_array[0][0];
- if(!bounds_check)
+ if ( !bounds_check )
{
#if defined (HAVE_MMX)
- sum = static_cast<float>(simple_biblock_diff_up_mmx_4(diff_array,
- m_ref_data2,
- ref_start2, ref_stop2,
- rmdr2));
+ sum = static_cast<float>( simple_biblock_diff_up_mmx_4 (diff_array,
+ m_ref_data2,
+ ref_start2, ref_stop2,
+ rmdr2) );
#else
ValueType *ref_curr = &m_ref_data2[ref_start2.y][ref_start2.x];
- const int ref_next((m_ref_data2.LengthX() - dparams.Xl()) * 2);// go down 2 rows and back up
- if(rmdr2.x == 0 && rmdr2.y == 0)
+ const int ref_next( (m_ref_data2.LengthX() - dparams.Xl())*2 );// go down 2 rows and back up
+ if( rmdr2.x == 0 && rmdr2.y == 0 )
{
- for(int y = dparams.Yl(); y > 0; --y, pic_curr += pic_next, ref_curr += ref_next)
+ for( int y=dparams.Yl(); y > 0; --y, pic_curr+=pic_next, ref_curr+=ref_next )
{
- for(int x = dparams.Xl(); x > 0; --x, ++pic_curr, ref_curr += 2, ++diff_curr)
+ for( int x=dparams.Xl(); x > 0; --x, ++pic_curr, ref_curr+=2, ++diff_curr )
{
- sum += std::abs((*diff_curr - *ref_curr) >> 1);
+ sum += std::abs( (*diff_curr - *ref_curr)>>1 );
}// x
}// y
}
- else if(rmdr2.y == 0)
+ else if( rmdr2.y == 0 )
{
- for(int y = dparams.Yl(); y > 0; --y, pic_curr += pic_next, ref_curr += ref_next)
+ for( int y=dparams.Yl(); y > 0; --y, pic_curr+=pic_next, ref_curr+=ref_next )
{
- for(int x = dparams.Xl(); x > 0; --x, ++pic_curr, ref_curr += 2, ++diff_curr)
+ for( int x=dparams.Xl(); x > 0; --x, ++pic_curr, ref_curr+=2, ++diff_curr )
{
- temp = (CalcValueType(ref_curr[0]) +
- CalcValueType(ref_curr[1]) +
- 1
- ) >> 1;
+ temp = ( CalcValueType( ref_curr[0] ) +
+ CalcValueType( ref_curr[1] ) +
+ 1
+ ) >> 1;
- sum += std::abs((*diff_curr - temp) >> 1);
+ sum += std::abs( (*diff_curr - temp)>>1 );
}// x
}// y
}
- else if(rmdr2.x == 0)
+ else if( rmdr2.x == 0 )
{
- for(int y = dparams.Yl(); y > 0; --y, pic_curr += pic_next, ref_curr += ref_next)
+ for( int y=dparams.Yl(); y > 0; --y, pic_curr+=pic_next, ref_curr+=ref_next )
{
- for(int x = dparams.Xl(); x > 0; --x, ++pic_curr, ref_curr += 2, ++diff_curr)
+ for( int x=dparams.Xl(); x > 0; --x, ++pic_curr, ref_curr+=2, ++diff_curr )
{
- temp = (CalcValueType(ref_curr[0]) +
- CalcValueType(ref_curr[m_ref_data2.LengthX()]) +
- 1
- ) >> 1;
- sum += std::abs((*diff_curr - temp) >> 1);
+ temp = ( CalcValueType( ref_curr[0] ) +
+ CalcValueType( ref_curr[m_ref_data2.LengthX()] ) +
+ 1
+ ) >> 1;
+ sum += std::abs( (*diff_curr - temp)>>1 );
}// x
}// y
}
else
{
- for(int y = dparams.Yl(); y > 0; --y, pic_curr += pic_next, ref_curr += ref_next)
+ for( int y=dparams.Yl(); y > 0; --y, pic_curr+=pic_next, ref_curr+=ref_next )
{
- for(int x = dparams.Xl(); x > 0; --x, ++pic_curr, ref_curr += 2, ++diff_curr)
+ for( int x=dparams.Xl(); x > 0; --x, ++pic_curr, ref_curr+=2, ++diff_curr )
{
- temp = (CalcValueType(ref_curr[0]) +
- CalcValueType(ref_curr[1]) +
- CalcValueType(ref_curr[m_ref_data2.LengthX()+0]) +
- CalcValueType(ref_curr[m_ref_data2.LengthX()+1]) +
- 2
- ) >> 2;
- sum += std::abs((*diff_curr - temp) >> 1);
+ temp = ( CalcValueType( ref_curr[0] ) +
+ CalcValueType( ref_curr[1] ) +
+ CalcValueType( ref_curr[m_ref_data2.LengthX()+0] ) +
+ CalcValueType( ref_curr[m_ref_data2.LengthX()+1] ) +
+ 2
+ ) >> 2;
+ sum += std::abs( (*diff_curr - temp)>>1 );
}// x
}// y
}
@@ -1521,29 +1513,28 @@ float BiBlockQuarterPel::Diff(const BlockDiffParams& dparams ,
}
else
{
- const ValueType linear_wts[4] = { (2 - rmdr2.x) *(2 - rmdr2.y), //tl
- rmdr2.x *(2 - rmdr2.y), //tr
+ const ValueType linear_wts[4] = { (2 - rmdr2.x) * (2 - rmdr2.y), //tl
+ rmdr2.x * (2 - rmdr2.y), //tr
(2 - rmdr2.x) * rmdr2.y, //bl
- rmdr2.x * rmdr2.y
- }; //br
+ rmdr2.x * rmdr2.y }; //br
// We're doing bounds checking because we'll fall off the edge of the reference otherwise.
- for(int y = dparams.Yl(), ry = ref_start2.y, by = BChk(ry, m_ref_data2.LengthY()), by1 = BChk(ry + 1, m_ref_data2.LengthY());
- y > 0;
- --y, pic_curr += pic_next, ry += 2 , by = BChk(ry, m_ref_data2.LengthY()), by1 = BChk(ry + 1, m_ref_data2.LengthY()))
+ for( int y=dparams.Yl(), ry=ref_start2.y, by=BChk(ry,m_ref_data2.LengthY()),by1=BChk(ry+1,m_ref_data2.LengthY());
+ y>0;
+ --y, pic_curr+=pic_next, ry+=2 , by=BChk(ry,m_ref_data2.LengthY()),by1=BChk(ry+1,m_ref_data2.LengthY()))
{
- for(int x = dparams.Xl() , rx = ref_start2.x , bx = BChk(rx, m_ref_data2.LengthX()), bx1 = BChk(rx + 1, m_ref_data2.LengthX());
- x > 0 ;
- --x, ++pic_curr, rx += 2 , ++diff_curr, bx = BChk(rx, m_ref_data2.LengthX()), bx1 = BChk(rx + 1, m_ref_data2.LengthX()))
- {
- temp = (linear_wts[0] * CalcValueType(m_ref_data2[by][bx]) +
- linear_wts[1] * CalcValueType(m_ref_data2[by][bx1]) +
- linear_wts[2] * CalcValueType(m_ref_data2[by1][bx]) +
- linear_wts[3] * CalcValueType(m_ref_data2[by1][bx1]) +
- 2
- ) >> 2;
- sum += std::abs((*diff_curr - temp) >> 1);
- }// x
+ for( int x=dparams.Xl() , rx=ref_start2.x , bx=BChk(rx,m_ref_data2.LengthX()), bx1=BChk(rx+1,m_ref_data2.LengthX());
+ x>0 ;
+ --x, ++pic_curr, rx+=2 , ++diff_curr, bx=BChk(rx,m_ref_data2.LengthX()), bx1=BChk(rx+1,m_ref_data2.LengthX()))
+ {
+ temp = ( linear_wts[0] * CalcValueType( m_ref_data2[by][bx] ) +
+ linear_wts[1] * CalcValueType( m_ref_data2[by][bx1] ) +
+ linear_wts[2] * CalcValueType( m_ref_data2[by1][bx] )+
+ linear_wts[3] * CalcValueType( m_ref_data2[by1][bx1] ) +
+ 2
+ ) >> 2;
+ sum += std::abs( (*diff_curr - temp)>>1 );
+ }// x
}// y
}
@@ -1551,119 +1542,117 @@ float BiBlockQuarterPel::Diff(const BlockDiffParams& dparams ,
}
-float BiBlockEighthPel::Diff(const BlockDiffParams& dparams ,
+float BiBlockEighthPel::Diff( const BlockDiffParams& dparams ,
const MVector& mv1 ,
- const MVector& mv2)
+ const MVector& mv2 )
{
- if(dparams.Xl() <= 0 || dparams.Yl() <= 0)
+ if (dparams.Xl() <= 0 || dparams.Yl() <= 0)
{
- return 0;
+ return 0;
}
// First create a difference array, and subtract the reference 1 data into it
- TwoDArray<ValueType> diff_array(dparams.Yl() , dparams.Xl());
+ TwoDArray<ValueType> diff_array( dparams.Yl() , dparams.Xl() );
- // Set up the start point in the reference images by rounding the motion vectors
+ // Set up the start point in the reference images by rounding the motion vectors
// to 1/2 pel accuracy.NB: bit shift rounds negative values DOWN, as required
- const MVector roundvec1(mv1.x >> 2 , mv1.y >> 2);
- const MVector roundvec2(mv2.x >> 2 , mv2.y >> 2);
+ const MVector roundvec1 ( mv1.x>>2 , mv1.y>>2 );
+ const MVector roundvec2 ( mv2.x>>2 , mv2.y>>2 );
- //Get the remainders after rounding. NB rmdr values always 0-3
- const MVector rmdr1(mv1.x & 3 , mv1.y & 3);
- const MVector rmdr2(mv2.x & 3 , mv2.y & 3);
+ //Get the remainders after rounding. NB rmdr values always 0-3
+ const MVector rmdr1( mv1.x & 3 , mv1.y & 3 );
+ const MVector rmdr2( mv2.x & 3 , mv2.y & 3 );
//weights for doing linear interpolation, calculated from the remainder values
- const ValueType linear_wts1[4] = { (4 - rmdr1.x) *(4 - rmdr1.y), //tl
- rmdr1.x *(4 - rmdr1.y), //tr
- (4 - rmdr1.x) * rmdr1.y, //bl
- rmdr1.x * rmdr1.y
- }; //br
- const ValueType linear_wts2[4] = { (4 - rmdr2.x) *(4 - rmdr2.y), //tl
- rmdr2.x *(4 - rmdr2.y), //tr
- (4 - rmdr2.x) * rmdr2.y, //bl
- rmdr2.x * rmdr2.y
- }; //br
+ const ValueType linear_wts1[4] = { (4 - rmdr1.x) * (4 - rmdr1.y), //tl
+ rmdr1.x * (4 - rmdr1.y), //tr
+ (4 - rmdr1.x) * rmdr1.y, //bl
+ rmdr1.x * rmdr1.y }; //br
+ const ValueType linear_wts2[4] = { (4 - rmdr2.x) * (4 - rmdr2.y), //tl
+ rmdr2.x * (4 - rmdr2.y), //tr
+ (4 - rmdr2.x) * rmdr2.y, //bl
+ rmdr2.x * rmdr2.y }; //br
//Where to start in the upconverted images
- const ImageCoords ref_start1((dparams.Xp() << 1) + roundvec1.x , (dparams.Yp() << 1) + roundvec1.y);
- const ImageCoords ref_stop1(ref_start1.x + (dparams.Xl() << 1) , ref_start1.y + (dparams.Yl() << 1));
+ const ImageCoords ref_start1( ( dparams.Xp()<<1 ) + roundvec1.x ,( dparams.Yp()<<1 ) + roundvec1.y );
+ const ImageCoords ref_stop1( ref_start1.x+(dparams.Xl()<<1) , ref_start1.y+(dparams.Yl()<<1));
- const ImageCoords ref_start2((dparams.Xp() << 1) + roundvec2.x , (dparams.Yp() << 1) + roundvec2.y);
- const ImageCoords ref_stop2(ref_start2.x + (dparams.Xl() << 1) , ref_start2.y + (dparams.Yl() << 1));
+ const ImageCoords ref_start2( ( dparams.Xp()<<1 ) + roundvec2.x ,( dparams.Yp()<<1 ) + roundvec2.y );
+ const ImageCoords ref_stop2( ref_start2.x+(dparams.Xl()<<1) , ref_start2.y+(dparams.Yl()<<1));
ValueType* pic_curr = &m_pic_data[dparams.Yp()][dparams.Xp()];
- const int pic_next(m_pic_data.LengthX() - dparams.Xl()); // go down a row and back up
+ const int pic_next( m_pic_data.LengthX() - dparams.Xl() );// go down a row and back up
ValueType* diff_curr = &diff_array[0][0];
- bool bounds_check(false);
+ bool bounds_check( false );
- if(ref_start1.x < 0 ||
- ref_stop1.x >= m_ref_data1.LengthX() ||
- ref_start1.y < 0 ||
- ref_stop1.y >= m_ref_data1.LengthY())
+ if ( ref_start1.x<0 ||
+ ref_stop1.x >= m_ref_data1.LengthX() ||
+ ref_start1.y<0 ||
+ ref_stop1.y >= m_ref_data1.LengthY() )
bounds_check = true;
ValueType temp;
- if(!bounds_check)
+ if ( !bounds_check )
{
ValueType *ref_curr = &m_ref_data1[ref_start1.y][ref_start1.x];
- const int ref_next((m_ref_data1.LengthX() - dparams.Xl()) * 2);// go down 2 rows and back up
+ const int ref_next( (m_ref_data1.LengthX() - dparams.Xl())*2 );// go down 2 rows and back up
- if(rmdr1.x == 0 && rmdr1.y == 0)
+ if( rmdr1.x == 0 && rmdr1.y == 0 )
{
- for(int y = dparams.Yl(); y > 0; --y, pic_curr += pic_next, ref_curr += ref_next)
+ for( int y=dparams.Yl(); y > 0; --y, pic_curr+=pic_next, ref_curr+=ref_next )
{
- for(int x = dparams.Xl(); x > 0; --x, ++pic_curr, ref_curr += 2, ++diff_curr)
+ for( int x=dparams.Xl(); x > 0; --x, ++pic_curr, ref_curr+=2, ++diff_curr )
{
- *diff_curr = ((*pic_curr) << 1) - *ref_curr;
+ *diff_curr = ( (*pic_curr)<<1 ) - *ref_curr;
}// x
}// y
}
- else if(rmdr1.y == 0)
+ else if( rmdr1.y == 0 )
{
- for(int y = dparams.Yl(); y > 0; --y, pic_curr += pic_next, ref_curr += ref_next)
+ for( int y=dparams.Yl(); y > 0; --y, pic_curr+=pic_next, ref_curr+=ref_next )
{
- for(int x = dparams.Xl(); x > 0; --x, ++pic_curr, ref_curr += 2, ++diff_curr)
+ for( int x=dparams.Xl(); x > 0; --x, ++pic_curr, ref_curr+=2, ++diff_curr )
{
- temp = ((linear_wts1[0] * CalcValueType(ref_curr[0]) +
- linear_wts1[1] * CalcValueType(ref_curr[1]) +
- 8
+ temp = (( linear_wts1[0] * CalcValueType( ref_curr[0] ) +
+ linear_wts1[1] * CalcValueType( ref_curr[1] ) +
+ 8
) >> 4);
- *diff_curr = ((*pic_curr) << 1) - temp;
+ *diff_curr = ( (*pic_curr)<<1 ) - temp;
}// x
}// y
}
- else if(rmdr1.x == 0)
+ else if( rmdr1.x == 0 )
{
- for(int y = dparams.Yl(); y > 0; --y, pic_curr += pic_next, ref_curr += ref_next)
+ for( int y=dparams.Yl(); y > 0; --y, pic_curr+=pic_next, ref_curr+=ref_next )
{
- for(int x = dparams.Xl(); x > 0; --x, ++pic_curr, ref_curr += 2, ++diff_curr)
+ for( int x=dparams.Xl(); x > 0; --x, ++pic_curr, ref_curr+=2, ++diff_curr )
{
- temp = ((linear_wts1[0] * CalcValueType(ref_curr[0]) +
- linear_wts1[2] * CalcValueType(ref_curr[m_ref_data1.LengthX()+0]) +
- 8
- ) >> 4);
+ temp = (( linear_wts1[0] * CalcValueType( ref_curr[0] ) +
+ linear_wts1[2] * CalcValueType( ref_curr[m_ref_data1.LengthX()+0] ) +
+ 8
+ ) >> 4);
- *diff_curr = ((*pic_curr) << 1) - temp;
+ *diff_curr = ( (*pic_curr)<<1 ) - temp;
}// x
}// y
}
else
{
- for(int y = dparams.Yl(); y > 0; --y, pic_curr += pic_next, ref_curr += ref_next)
+ for( int y=dparams.Yl(); y > 0; --y, pic_curr+=pic_next, ref_curr+=ref_next )
{
- for(int x = dparams.Xl(); x > 0; --x, ++pic_curr, ref_curr += 2, ++diff_curr)
+ for( int x=dparams.Xl(); x > 0; --x, ++pic_curr, ref_curr+=2, ++diff_curr )
{
- temp = ((linear_wts1[0] * CalcValueType(ref_curr[0]) +
- linear_wts1[1] * CalcValueType(ref_curr[1]) +
- linear_wts1[2] * CalcValueType(ref_curr[m_ref_data1.LengthX()+0]) +
- linear_wts1[3] * CalcValueType(ref_curr[m_ref_data1.LengthX()+1]) +
- 8
+ temp = (( linear_wts1[0] * CalcValueType( ref_curr[0] ) +
+ linear_wts1[1] * CalcValueType( ref_curr[1] ) +
+ linear_wts1[2] * CalcValueType( ref_curr[m_ref_data1.LengthX()+0] ) +
+ linear_wts1[3] * CalcValueType( ref_curr[m_ref_data1.LengthX()+1] ) +
+ 8
) >> 4);
- *diff_curr = ((*pic_curr) << 1) - temp;
+ *diff_curr = ( (*pic_curr)<<1 ) - temp;
}// x
}// y
}
@@ -1673,22 +1662,22 @@ float BiBlockEighthPel::Diff(const BlockDiffParams& dparams ,
else
{
// We're doing bounds checking because we'll fall off the edge of the reference otherwise.
- for(int y = dparams.Yl(), ry = ref_start1.y, by = BChk(ry, m_ref_data1.LengthY()), by1 = BChk(ry + 1, m_ref_data1.LengthY());
- y > 0;
- --y, pic_curr += pic_next, ry += 2 , by = BChk(ry, m_ref_data1.LengthY()), by1 = BChk(ry + 1, m_ref_data1.LengthY()))
+ for( int y=dparams.Yl(), ry=ref_start1.y, by=BChk(ry,m_ref_data1.LengthY()), by1=BChk(ry+1,m_ref_data1.LengthY());
+ y>0;
+ --y, pic_curr+=pic_next, ry+=2 , by=BChk(ry,m_ref_data1.LengthY()), by1=BChk(ry+1,m_ref_data1.LengthY()) )
{
- for(int x = dparams.Xl() , rx = ref_start1.x , bx = BChk(rx, m_ref_data1.LengthX()), bx1 = BChk(rx + 1, m_ref_data1.LengthX());
- x > 0 ;
- --x, ++pic_curr, rx += 2 , ++diff_curr, bx = BChk(rx, m_ref_data1.LengthX()), bx1 = BChk(rx + 1, m_ref_data1.LengthX()))
- {
- temp = (linear_wts1[0] * CalcValueType(m_ref_data1[by][bx]) +
- linear_wts1[1] * CalcValueType(m_ref_data1[by][bx1]) +
- linear_wts1[2] * CalcValueType(m_ref_data1[by1][bx]) +
- linear_wts1[3] * CalcValueType(m_ref_data1[by1][bx1]) +
- 8
- ) >> 4;
- *diff_curr = ((*pic_curr) << 1) - temp;
- }// x
+ for( int x=dparams.Xl() , rx=ref_start1.x , bx=BChk(rx,m_ref_data1.LengthX()), bx1=BChk(rx+1,m_ref_data1.LengthX());
+ x>0 ;
+ --x, ++pic_curr, rx+=2 , ++diff_curr, bx=BChk(rx,m_ref_data1.LengthX()), bx1=BChk(rx+1,m_ref_data1.LengthX()))
+ {
+ temp = ( linear_wts1[0] * CalcValueType( m_ref_data1[by][bx] ) +
+ linear_wts1[1] * CalcValueType( m_ref_data1[by][bx1] ) +
+ linear_wts1[2] * CalcValueType( m_ref_data1[by1][bx] )+
+ linear_wts1[3] * CalcValueType( m_ref_data1[by1][bx1] ) +
+ 8
+ ) >> 4;
+ *diff_curr = ( (*pic_curr)<<1 ) - temp;
+ }// x
}// y
}
@@ -1696,74 +1685,74 @@ float BiBlockEighthPel::Diff(const BlockDiffParams& dparams ,
bounds_check = false;
- if(ref_start2.x < 0 ||
- ref_stop2.x >= m_ref_data2.LengthX() ||
- ref_start2.y < 0 ||
- ref_stop2.y >= m_ref_data2.LengthY())
+ if ( ref_start2.x<0 ||
+ ref_stop2.x >= m_ref_data2.LengthX() ||
+ ref_start2.y<0 ||
+ ref_stop2.y >= m_ref_data2.LengthY() )
bounds_check = true;
- float sum(0);
+ float sum( 0 );
diff_curr = &diff_array[0][0];
- if(!bounds_check)
+ if ( !bounds_check )
{
ValueType *ref_curr = &m_ref_data2[ref_start2.y][ref_start2.x];
- const int ref_next((m_ref_data2.LengthX() - dparams.Xl()) * 2);// go down 2 rows and back up
+ const int ref_next( (m_ref_data2.LengthX() - dparams.Xl())*2 );// go down 2 rows and back up
- if(rmdr2.x == 0 && rmdr2.y == 0)
+ if( rmdr2.x == 0 && rmdr2.y == 0 )
{
- for(int y = dparams.Yl(); y > 0; --y, pic_curr += pic_next, ref_curr += ref_next)
+ for( int y=dparams.Yl(); y > 0; --y, pic_curr+=pic_next, ref_curr+=ref_next )
{
- for(int x = dparams.Xl(); x > 0; --x, ++pic_curr, ref_curr += 2, ++diff_curr)
+ for( int x=dparams.Xl(); x > 0; --x, ++pic_curr, ref_curr+=2, ++diff_curr )
{
- sum += std::abs((*diff_curr - *ref_curr) >> 1);
+ sum += std::abs( (*diff_curr - *ref_curr)>>1 );
}// x
}// y
}
- else if(rmdr2.y == 0)
+ else if( rmdr2.y == 0 )
{
- for(int y = dparams.Yl(); y > 0; --y, pic_curr += pic_next, ref_curr += ref_next)
+ for( int y=dparams.Yl(); y > 0; --y, pic_curr+=pic_next, ref_curr+=ref_next )
{
- for(int x = dparams.Xl(); x > 0; --x, ++pic_curr, ref_curr += 2, ++diff_curr)
+ for( int x=dparams.Xl(); x > 0; --x, ++pic_curr, ref_curr+=2, ++diff_curr )
{
- temp = ((linear_wts2[0] * CalcValueType(ref_curr[0]) +
- linear_wts2[1] * CalcValueType(ref_curr[1]) +
- 8
+ temp = (( linear_wts2[0] * CalcValueType( ref_curr[0] ) +
+ linear_wts2[1] * CalcValueType( ref_curr[1] ) +
+ 8
) >> 4);
- sum += std::abs((*diff_curr - temp) >> 1);
+ sum += std::abs( (*diff_curr - temp)>>1 );
}// x
}// y
}
- else if(rmdr2.x == 0)
+ else if( rmdr2.x == 0 )
{
- for(int y = dparams.Yl(); y > 0; --y, pic_curr += pic_next, ref_curr += ref_next)
+ for( int y=dparams.Yl(); y > 0; --y, pic_curr+=pic_next, ref_curr+=ref_next )
{
- for(int x = dparams.Xl(); x > 0; --x, ++pic_curr, ref_curr += 2, ++diff_curr)
+ for( int x=dparams.Xl(); x > 0; --x, ++pic_curr, ref_curr+=2, ++diff_curr )
{
- temp = ((linear_wts2[0] * CalcValueType(ref_curr[0]) +
- linear_wts2[2] * CalcValueType(ref_curr[m_ref_data2.LengthX()+0]) +
- 8
- ) >> 4);
+ temp = (( linear_wts2[0] * CalcValueType( ref_curr[0] ) +
+ linear_wts2[2] * CalcValueType( ref_curr[m_ref_data2.LengthX()+0] ) +
+ 8
+ ) >> 4);
- sum += std::abs((*diff_curr - temp) >> 1);
+ sum += std::abs( (*diff_curr - temp)>>1 );
}// x
}// y
}
else
{
- for(int y = dparams.Yl(); y > 0; --y, pic_curr += pic_next, ref_curr += ref_next)
+ for( int y=dparams.Yl(); y > 0; --y, pic_curr+=pic_next, ref_curr+=ref_next )
{
- for(int x = dparams.Xl(); x > 0; --x, ++pic_curr, ref_curr += 2, ++diff_curr)
+ for( int x=dparams.Xl(); x > 0; --x, ++pic_curr, ref_curr+=2, ++diff_curr )
{
- temp = ((linear_wts2[0] * CalcValueType(ref_curr[0]) +
- linear_wts2[1] * CalcValueType(ref_curr[1]) +
- linear_wts2[2] * CalcValueType(ref_curr[m_ref_data2.LengthX()+0]) +
- linear_wts2[3] * CalcValueType(ref_curr[m_ref_data2.LengthX()+1]) +
- 8
+ temp = (( linear_wts2[0] * CalcValueType( ref_curr[0] ) +
+ linear_wts2[1] * CalcValueType( ref_curr[1] ) +
+ linear_wts2[2] * CalcValueType( ref_curr[m_ref_data2.LengthX()+0] ) +
+ linear_wts2[3] * CalcValueType( ref_curr[m_ref_data2.LengthX()+1] ) +
+ 8
) >> 4);
- sum += std::abs((*diff_curr - temp) >> 1);
+ sum += std::abs( (*diff_curr - temp)>>1 );
}// x
}// y
}
@@ -1772,22 +1761,22 @@ float BiBlockEighthPel::Diff(const BlockDiffParams& dparams ,
else
{
// We're doing bounds checking because we'll fall off the edge of the reference otherwise.
- for(int y = dparams.Yl(), ry = ref_start1.y, by = BChk(ry, m_ref_data2.LengthY()), by1 = BChk(ry + 1, m_ref_data2.LengthY());
- y > 0;
- --y, pic_curr += pic_next, ry += 2 , by = BChk(ry, m_ref_data2.LengthY()), by1 = BChk(ry + 1, m_ref_data2.LengthY()))
+ for( int y=dparams.Yl(), ry=ref_start1.y, by=BChk(ry,m_ref_data2.LengthY()),by1=BChk(ry+1,m_ref_data2.LengthY());
+ y>0;
+ --y, pic_curr+=pic_next, ry+=2 , by=BChk(ry,m_ref_data2.LengthY()),by1=BChk(ry+1,m_ref_data2.LengthY()))
{
- for(int x = dparams.Xl() , rx = ref_start1.x , bx = BChk(rx, m_ref_data2.LengthX()), bx1 = BChk(rx + 1, m_ref_data2.LengthX());
- x > 0 ;
- --x, ++pic_curr, rx += 2 , ++diff_curr, bx = BChk(rx, m_ref_data2.LengthX()), bx1 = BChk(rx + 1, m_ref_data2.LengthX()))
- {
- temp = (linear_wts2[0] * CalcValueType(m_ref_data2[by][bx]) +
- linear_wts2[1] * CalcValueType(m_ref_data2[by][bx1]) +
- linear_wts2[2] * CalcValueType(m_ref_data2[by1][bx]) +
- linear_wts2[3] * CalcValueType(m_ref_data2[by1][bx1]) +
- 8
- ) >> 4;
- sum += std::abs((*diff_curr - temp) >> 1);
- }// x
+ for( int x=dparams.Xl() , rx=ref_start1.x , bx=BChk(rx,m_ref_data2.LengthX()), bx1=BChk(rx+1,m_ref_data2.LengthX());
+ x>0 ;
+ --x, ++pic_curr, rx+=2 , ++diff_curr, bx=BChk(rx,m_ref_data2.LengthX()), bx1=BChk(rx+1,m_ref_data2.LengthX()))
+ {
+ temp = ( linear_wts2[0] * CalcValueType( m_ref_data2[by][bx] ) +
+ linear_wts2[1] * CalcValueType( m_ref_data2[by][bx1] ) +
+ linear_wts2[2] * CalcValueType( m_ref_data2[by1][bx] )+
+ linear_wts2[3] * CalcValueType( m_ref_data2[by1][bx1] ) +
+ 8
+ ) >> 4;
+ sum += std::abs( (*diff_curr - temp)>>1 );
+ }// x
}// y
}
diff --git a/src/filters/parser/DiracSplitter/libdirac/libdirac_motionest/me_utils.h b/src/filters/parser/DiracSplitter/libdirac/libdirac_motionest/me_utils.h
index 17bdb9a6f..51c464b7b 100644
--- a/src/filters/parser/DiracSplitter/libdirac/libdirac_motionest/me_utils.h
+++ b/src/filters/parser/DiracSplitter/libdirac/libdirac_motionest/me_utils.h
@@ -44,532 +44,514 @@
namespace dirac
{
-///////////////////////////////////
-//Utilities for motion estimation//
-//-------------------------------//
-///////////////////////////////////
+ ///////////////////////////////////
+ //Utilities for motion estimation//
+ //-------------------------------//
+ ///////////////////////////////////
-//! A class encapsulating parameters for calculating a block difference value (a single instance of matching)
-class BlockDiffParams
-{
+ //! A class encapsulating parameters for calculating a block difference value (a single instance of matching)
+ class BlockDiffParams
+ {
-public:
- //! Constructor
- BlockDiffParams() {}
+ public:
+ //! Constructor
+ BlockDiffParams(){}
- //! Constructor
- BlockDiffParams(const int x_p , const int y_p , const int x_l , const int y_l):
- m_xp(x_p),
- m_yp(y_p),
- m_xl(x_l),
- m_yl(y_l),
- m_xend(x_l + x_p),
- m_yend(y_l + y_p)
- {}
+ //! Constructor
+ BlockDiffParams( const int x_p , const int y_p , const int x_l , const int y_l):
+ m_xp(x_p),
+ m_yp(y_p),
+ m_xl(x_l),
+ m_yl(y_l),
+ m_xend(x_l+x_p),
+ m_yend(y_l+y_p)
+ {}
- ////////////////////////////////////////////////////////////////////
- //NB: Assume default copy constructor, assignment = and destructor//
- ////////////////////////////////////////////////////////////////////
+ ////////////////////////////////////////////////////////////////////
+ //NB: Assume default copy constructor, assignment = and destructor//
+ ////////////////////////////////////////////////////////////////////
- // Sets ...
+ // Sets ...
- //! Set the limits of the block to fit in a picture
+ //! Set the limits of the block to fit in a picture
+
+ void SetBlockLimits( const OLBParams& bparams ,
+ const PicArray& pic_data ,
+ const int xbpos , const int ybpos);
- void SetBlockLimits(const OLBParams& bparams ,
- const PicArray& pic_data ,
- const int xbpos , const int ybpos);
+ // ... and gets
- // ... and gets
+ //! Return the x-position of the top-left block corner
+ int Xp() const {return m_xp;}
- //! Return the x-position of the top-left block corner
- int Xp() const
- {
- return m_xp;
- }
+ //! Return the y-position of the top-left block corner
+ int Yp() const {return m_yp;}
- //! Return the y-position of the top-left block corner
- int Yp() const
- {
- return m_yp;
- }
+ //! Return the block width
+ int Xl() const {return m_xl;}
- //! Return the block width
- int Xl() const
- {
- return m_xl;
- }
+ //! Return the block height
+ int Yl() const {return m_yl;}
- //! Return the block height
- int Yl() const
- {
- return m_yl;
- }
+ //! Return the block horizontal endpoint
+ int Xend() const {return m_xend;}
- //! Return the block horizontal endpoint
- int Xend() const
- {
- return m_xend;
- }
+ //! Return the block vertical endpoint
+ int Yend() const {return m_yend;}
- //! Return the block vertical endpoint
- int Yend() const
- {
- return m_yend;
- }
-
-private:
-
- int m_xp;
- int m_yp;
- int m_xl;
- int m_yl;
- int m_xend;
- int m_yend;
-};
-
-//////////////////////////////////////////////////
-//----Different difference classes, so that-----//
-//bounds-checking need only be done as necessary//
-//////////////////////////////////////////////////
-
-//! An abstract class for doing block difference calculations
-class BlockDiff
-{
-public:
- //! Constructor, initialising the reference and picture data
- /*
- Constructor, initialising the reference and picture data
- \param ref the reference picture
- \param pic the picture being matched
- */
- BlockDiff(const PicArray& ref , const PicArray& pic);
-
- //! Destructor
- virtual ~BlockDiff() {}
-
- //! Do the difference, returning SAD
- /*!
- Do the difference, returning SAD
- \param dparams block parameters
- \param mv the motion vector being used
- */
- virtual float Diff(const BlockDiffParams& dparams , const MVector& mv) = 0;
-
-protected:
-
- const PicArray& m_pic_data;
- const PicArray& m_ref_data;
-
-private:
- //! Private, bodyless copy-constructor: class should not be copied
- BlockDiff(const BlockDiff& cpy);
-
- //! Private, bodyless assignment=: class should not be assigned
- BlockDiff& operator=(const BlockDiff& rhs);
-};
-
-//! A class for doing block differences to pixel accuracy, inherited from BlockDiff
-class PelBlockDiff: public BlockDiff
-{
-public:
- //! Constructor, initialising the reference and picture data
- /*
- Constructor, initialising the reference and picture data
- \param ref the reference picture
- \param pic the picture being matched
- */
- PelBlockDiff(const PicArray& ref , const PicArray& pic);
-
- //! Do the difference, returning SAD
- /*!
- Do the difference, returning SAD
- \param dparams block parameters
- \param mv the motion vector being used
- */
- float Diff(const BlockDiffParams& dparams , const MVector& mv);
-
- //! Do the difference, overwriting the best MV so far if appropriate
- /*!
- Do the difference, overwriting the best MV so far if appropriate,
- and bailing out if we do worse
- \param dparams block parameters
- \param mv the motion vector being used
- \param best_sum the best SAD value obtain yet
- \param best_mv the MV giving the best SAD value so far
- */
- void Diff(const BlockDiffParams& dparams ,
- const MVector& mv ,
- float& best_sum ,
- MVector& best_mv);
-
-private:
- //! Private, bodyless copy-constructor: class should not be copied
- PelBlockDiff(const PelBlockDiff& cpy);
-
- //! Private, bodyless assignment=: class should not be assigned
- PelBlockDiff& operator=(const PelBlockDiff& rhs);
-};
-
-
-//! A class for calculating the difference between a block and its DC value (average)
-class IntraBlockDiff
-{
-public:
- //! Constructor, initialising the picture data
- /*
- Constructor, initialising the picture data
- \param pic the picture being matched
- */
- IntraBlockDiff(const PicArray& pic);
-
- //! Do the difference, calculating the DC value and returning SAD
- /*!
- Do the difference, calculating the DC value and returning SAD
- \param dparams block parameters
- \param dc_val DC value
- */
- float Diff(const BlockDiffParams& dparams , ValueType& dc_val);
-
- //! Calculate a DC value
- ValueType CalcDC(const BlockDiffParams& dparams);
-
-private:
- //! Private, bodyless copy-constructor: class should not be copied
- IntraBlockDiff(const IntraBlockDiff& cpy);
-
- //! Private, bodyless assignment=: class should not be assigned
- IntraBlockDiff& operator=(const IntraBlockDiff& rhs);
-
- const PicArray& m_pic_data;
-};
-
-//! A virtual class for bi-directional differences
-class BiBlockDiff
-{
-public:
- //! Constructor, initialising the references and picture data
- /*
- Constructor, initialising the references and picture data
- \param ref1 the first reference picture
- \param ref2 the second reference picture
- \param pic the picture being matched
- */
- BiBlockDiff(const PicArray& ref1 , const PicArray& ref2 , const PicArray& pic);
-
- //! Virtual destructor
- virtual ~BiBlockDiff() {}
-
- //! Do the difference, returning SAD
- /*!
- Do the difference, returning SAD
- \param dparams block parameters
- \param mv1 the motion vector being used for reference 1
- \param mv2 the motion vector being used for reference 2
- */
- virtual float Diff(const BlockDiffParams& dparams , const MVector& mv1 , const MVector& mv2) = 0;
-
-protected:
- const PicArray& m_pic_data;
- const PicArray& m_ref_data1;
- const PicArray& m_ref_data2;
-
-private:
- //! Private, bodyless copy-constructor: class should not be copied
- BiBlockDiff(const BiBlockDiff& cpy);
-
- //! Private, bodyless assignment=: class should not be assigned
- BiBlockDiff& operator=(const BiBlockDiff& rhs);
-};
-
-// Classes where the reference is upconverted //
-////////////////////////////////////////////////
-//! A virtual class for doing differences with sub-pixel vectors
-class BlockDiffUp: public BlockDiff
-{
+ private:
-public:
-
- //! Constructor, initialising the reference and picture data
- /*
- Constructor, initialising the reference and picture data
- \param ref the reference picture
- \param pic the picture being matched
- */
- BlockDiffUp(const PicArray& ref , const PicArray& pic);
-
- //! Destructor
- virtual ~BlockDiffUp() {}
-
- //! Do the difference, returning SAD
- /*!
- Do the difference, returning SAD
- \param dparams block parameters
- \param mv the motion vector being used
- */
- virtual float Diff(const BlockDiffParams& dparams , const MVector& mv) = 0;
-
- //! Do the actual difference, overwriting the best MV so far if appropriate
- /*!
- Do the actual difference, overwriting the best MV so far if appropriate,
- and bailing out if we do worse
- \param dparams block parameters
- \param mv the motion vector being used
- \param mvcost the (prediction) cost of the motion vector mv
- \param lambda the weighting to be given to mvcost
- \param best_costs the best Lagrangian costs obtained yet
- \param best_mv the MV giving the best Lagrangian costs so far
- */
- virtual void Diff(const BlockDiffParams& dparams,
- const MVector& mv ,
- const float mvcost,
- const float lambda,
- MvCostData& best_costs ,
- MVector& best_mv) = 0;
-private:
- //! Private, bodyless copy-constructor: class should not be copied
- BlockDiffUp(const BlockDiffUp& cpy);
-
- //! Private, bodyless assignment=: class should not be assigned
- BlockDiffUp& operator=(const BlockDiffUp& rhs);
-};
-
-//! A class for doing differences with half-pixel accurate vectors
-class BlockDiffHalfPel: public BlockDiffUp
-{
+ int m_xp;
+ int m_yp;
+ int m_xl;
+ int m_yl;
+ int m_xend;
+ int m_yend;
+ };
-public:
- //! Constructor, initialising the reference and picture data
- /*
- Constructor, initialising the reference and picture data
- \param ref the reference picture
- \param pic the picture being matched
- */
- BlockDiffHalfPel(const PicArray& ref , const PicArray& pic);
-
- //! Destructor
- ~BlockDiffHalfPel() {}
-
- //! Do the difference, returning SAD
- /*!
- Do the difference, returning SAD
- \param dparams block parameters
- \param mv the motion vector being used
- */
- float Diff(const BlockDiffParams& dparams , const MVector& mv);
-
- //! Do the actual difference, overwriting the best MV so far if appropriate
- /*!
- Do the actual difference, overwriting the best MV so far if appropriate,
- and bailing out if we do worse
- \param dparams block parameters
- \param mv the motion vector being used
- \param mvcost the (prediction) cost of the motion vector mv
- \param lambda the weighting to be given to mvcost
- \param best_costs the best Lagrangian costs obtained yet
- \param best_mv the MV giving the best Lagrangian costs so far
- */
- void Diff(const BlockDiffParams& dparams,
- const MVector& mv ,
- const float mvcost,
- const float lambda,
- MvCostData& best_costs ,
- MVector& best_mv);
-
-private:
- //! Private, bodyless copy-constructor: class should not be copied
- BlockDiffHalfPel(const BlockDiffHalfPel& cpy);
-
- //! Private, bodyless assignment=: class should not be assigned
- BlockDiffHalfPel& operator=(const BlockDiffHalfPel& rhs);
-
-};
-
-//! A class for doing differences with quarter-pixel accurate vectors
-class BlockDiffQuarterPel: public BlockDiffUp
-{
-public:
- //! Constructor, initialising the reference and picture data
- /*
- Constructor, initialising the reference and picture data
- \param ref the reference picture
- \param pic the picture being matched
- */
- BlockDiffQuarterPel(const PicArray& ref , const PicArray& pic);
-
- //! Destructor
- ~BlockDiffQuarterPel() {}
-
- //! Do the difference, returning SAD
- /*!
- Do the difference, returning SAD
- \param dparams block parameters
- \param mv the motion vector being used
- */
- float Diff(const BlockDiffParams& dparams , const MVector& mv);
-
- //! Do the actual difference, overwriting the best MV so far if appropriate
- /*!
- Do the actual difference, overwriting the best MV so far if appropriate,
- and bailing out if we do worse
- \param dparams block parameters
- \param mv the motion vector being used
- \param mvcost the (prediction) cost of the motion vector mv
- \param lambda the weighting to be given to mvcost
- \param best_costs the best Lagrangian costs obtained yet
- \param best_mv the MV giving the best Lagrangian costs so far
- */
- void Diff(const BlockDiffParams& dparams,
- const MVector& mv ,
- const float mvcost,
- const float lambda,
- MvCostData& best_costs ,
- MVector& best_mv);
-
-private:
- //! Private, bodyless copy-constructor: class should not be copied
- BlockDiffQuarterPel(const BlockDiffQuarterPel& cpy);
-
- //! Private, bodyless assignment=: class should not be assigned
- BlockDiffQuarterPel& operator=(const BlockDiffQuarterPel& rhs);
-};
-
-//! A class for doing differences with eighth-pixel accurate vectors
-class BlockDiffEighthPel: public BlockDiffUp
-{
-public:
- //! Constructor, initialising the reference and picture data
- /*
- Constructor, initialising the reference and picture data
- \param ref the reference picture
- \param pic the picture being matched
- */
- BlockDiffEighthPel(const PicArray& ref , const PicArray& pic);
-
- //! Destructor
- ~BlockDiffEighthPel() {}
-
- //! Do the difference, returning SAD
- /*!
- Do the difference, returning SAD
- \param dparams block parameters
- \param mv the motion vector being used
- */
- float Diff(const BlockDiffParams& dparams , const MVector& mv);
-
- //! Do the actual difference, overwriting the best MV so far if appropriate
- /*!
- Do the actual difference, overwriting the best MV so far if appropriate,
- and bailing out if we do worse
- \param dparams block parameters
- \param mv the motion vector being used
- \param mvcost the (prediction) cost of the motion vector mv
- \param lambda the weighting to be given to mvcost
- \param best_costs the best Lagrangian costs obtained yet
- \param best_mv the MV giving the best Lagrangian costs so far
- */
- void Diff(const BlockDiffParams& dparams,
- const MVector& mv ,
- const float mvcost,
- const float lambda,
- MvCostData& best_costs ,
- MVector& best_mv);
-
-private:
- //! Private, bodyless copy-constructor: class should not be copied
- BlockDiffEighthPel(const BlockDiffEighthPel& cpy);
-
- //! Private, bodyless assignment=: class should not be assigned
- BlockDiffEighthPel& operator=(const BlockDiffEighthPel& rhs);
-};
-
-//! A class for computing a bidirection difference for half-pel vectors
-class BiBlockHalfPel: public BiBlockDiff
-{
-public:
- //! Constructor, initialising the references and picture data
- /*
- Constructor, initialising the reference and picture data
- \param ref1 the first reference picture
- \param ref2 the second reference picture
- \param pic the picture being matched
- */
- BiBlockHalfPel(const PicArray& ref1 , const PicArray& ref2 , const PicArray& pic);
-
- //! Do the difference, returning SAD
- /*!
- Do the difference, returning SAD
- \param dparams block parameters
- \param mv1 the motion vector being used for reference 1
- \param mv2 the motion vector being used for reference 2
- */
- float Diff(const BlockDiffParams& dparams , const MVector& mv1 , const MVector& mv2);
-private:
- //! Private, bodyless copy-constructor: class should not be copied
- BiBlockHalfPel(const BiBlockHalfPel& cpy);
-
- //! Private, bodyless assignment=: class should not be assigned
- BiBlockHalfPel& operator=(const BiBlockHalfPel& rhs);
-};
-
-//! A class for computing a bidirection difference for quarter-pel vectors
-class BiBlockQuarterPel: public BiBlockDiff
-{
-public:
- //! Constructor, initialising the references and picture data
- /*
- Constructor, initialising the reference and picture data
- \param ref1 the first reference picture
- \param ref2 the second reference picture
- \param pic the picture being matched
- */
- BiBlockQuarterPel(const PicArray& ref1 , const PicArray& ref2 , const PicArray& pic);
-
- //! Do the difference, returning SAD
- /*!
- Do the difference, returning SAD
- \param dparams block parameters
- \param mv1 the motion vector being used for reference 1
- \param mv2 the motion vector being used for reference 2
- */
- float Diff(const BlockDiffParams& dparams , const MVector& mv1 , const MVector& mv2);
-
-private:
- //! Private, bodyless copy-constructor: class should not be copied
- BiBlockQuarterPel(const BiBlockQuarterPel& cpy);
-
- //! Private, bodyless assignment=: class should not be assigned
- BiBlockQuarterPel& operator=(const BiBlockQuarterPel& rhs);
-};
-
-//! A class for computing a bidirection difference for eighth-pel vectors
-class BiBlockEighthPel: public BiBlockDiff
-{
-public:
- //! Constructor, initialising the references and picture data
- /*
- Constructor, initialising the reference and picture data
- \param ref1 the first reference picture
- \param ref2 the second reference picture
- \param pic the picture being matched
- */
- BiBlockEighthPel(const PicArray& ref1 , const PicArray& ref2 , const PicArray& pic);
-
- //! Do the difference, returning SAD
- /*!
- Do the difference, returning SAD
- \param dparams block parameters
- \param mv1 the motion vector being used for reference 1
- \param mv2 the motion vector being used for reference 2
- */
- float Diff(const BlockDiffParams& dparams , const MVector& mv1 , const MVector& mv2);
-private:
- //! Private, bodyless copy-constructor: class should not be copied
- BiBlockEighthPel(const BiBlockEighthPel& cpy);
-
- //! Private, bodyless assignment=: class should not be assigned
- BiBlockEighthPel& operator=(const BiBlockEighthPel& rhs);
-};
+ //////////////////////////////////////////////////
+ //----Different difference classes, so that-----//
+ //bounds-checking need only be done as necessary//
+ //////////////////////////////////////////////////
+
+ //! An abstract class for doing block difference calculations
+ class BlockDiff
+ {
+ public:
+ //! Constructor, initialising the reference and picture data
+ /*
+ Constructor, initialising the reference and picture data
+ \param ref the reference picture
+ \param pic the picture being matched
+ */
+ BlockDiff( const PicArray& ref , const PicArray& pic );
+
+ //! Destructor
+ virtual ~BlockDiff(){}
+
+ //! Do the difference, returning SAD
+ /*!
+ Do the difference, returning SAD
+ \param dparams block parameters
+ \param mv the motion vector being used
+ */
+ virtual float Diff( const BlockDiffParams& dparams , const MVector& mv )=0;
+
+ protected:
+
+ const PicArray& m_pic_data;
+ const PicArray& m_ref_data;
+
+ private:
+ //! Private, bodyless copy-constructor: class should not be copied
+ BlockDiff( const BlockDiff& cpy );
+
+ //! Private, bodyless assignment=: class should not be assigned
+ BlockDiff& operator=( const BlockDiff& rhs );
+ };
+
+ //! A class for doing block differences to pixel accuracy, inherited from BlockDiff
+ class PelBlockDiff: public BlockDiff
+ {
+ public:
+ //! Constructor, initialising the reference and picture data
+ /*
+ Constructor, initialising the reference and picture data
+ \param ref the reference picture
+ \param pic the picture being matched
+ */
+ PelBlockDiff( const PicArray& ref , const PicArray& pic );
+
+ //! Do the difference, returning SAD
+ /*!
+ Do the difference, returning SAD
+ \param dparams block parameters
+ \param mv the motion vector being used
+ */
+ float Diff( const BlockDiffParams& dparams , const MVector& mv );
+
+ //! Do the difference, overwriting the best MV so far if appropriate
+ /*!
+ Do the difference, overwriting the best MV so far if appropriate,
+ and bailing out if we do worse
+ \param dparams block parameters
+ \param mv the motion vector being used
+ \param best_sum the best SAD value obtain yet
+ \param best_mv the MV giving the best SAD value so far
+ */
+ void Diff( const BlockDiffParams& dparams ,
+ const MVector& mv ,
+ float& best_sum ,
+ MVector& best_mv );
+
+ private:
+ //! Private, bodyless copy-constructor: class should not be copied
+ PelBlockDiff(const PelBlockDiff& cpy);
+
+ //! Private, bodyless assignment=: class should not be assigned
+ PelBlockDiff& operator=(const PelBlockDiff& rhs);
+ };
+
+
+ //! A class for calculating the difference between a block and its DC value (average)
+ class IntraBlockDiff
+ {
+ public:
+ //! Constructor, initialising the picture data
+ /*
+ Constructor, initialising the picture data
+ \param pic the picture being matched
+ */
+ IntraBlockDiff( const PicArray& pic );
+
+ //! Do the difference, calculating the DC value and returning SAD
+ /*!
+ Do the difference, calculating the DC value and returning SAD
+ \param dparams block parameters
+ \param dc_val DC value
+ */
+ float Diff( const BlockDiffParams& dparams , ValueType& dc_val );
+
+ //! Calculate a DC value
+ ValueType CalcDC( const BlockDiffParams& dparams);
+
+ private:
+ //! Private, bodyless copy-constructor: class should not be copied
+ IntraBlockDiff(const IntraBlockDiff& cpy);
+
+ //! Private, bodyless assignment=: class should not be assigned
+ IntraBlockDiff& operator=(const IntraBlockDiff& rhs);
+
+ const PicArray& m_pic_data;
+ };
+
+ //! A virtual class for bi-directional differences
+ class BiBlockDiff
+ {
+ public:
+ //! Constructor, initialising the references and picture data
+ /*
+ Constructor, initialising the references and picture data
+ \param ref1 the first reference picture
+ \param ref2 the second reference picture
+ \param pic the picture being matched
+ */
+ BiBlockDiff( const PicArray& ref1 , const PicArray& ref2 , const PicArray& pic);
+
+ //! Virtual destructor
+ virtual ~BiBlockDiff( ) {}
+
+ //! Do the difference, returning SAD
+ /*!
+ Do the difference, returning SAD
+ \param dparams block parameters
+ \param mv1 the motion vector being used for reference 1
+ \param mv2 the motion vector being used for reference 2
+ */
+ virtual float Diff( const BlockDiffParams& dparams , const MVector& mv1 , const MVector& mv2 )=0;
+
+ protected:
+ const PicArray& m_pic_data;
+ const PicArray& m_ref_data1;
+ const PicArray& m_ref_data2;
+
+ private:
+ //! Private, bodyless copy-constructor: class should not be copied
+ BiBlockDiff(const BiBlockDiff& cpy);
+
+ //! Private, bodyless assignment=: class should not be assigned
+ BiBlockDiff& operator=(const BiBlockDiff& rhs);
+ };
+
+ // Classes where the reference is upconverted //
+ ////////////////////////////////////////////////
+ //! A virtual class for doing differences with sub-pixel vectors
+ class BlockDiffUp: public BlockDiff
+ {
+
+ public:
+
+ //! Constructor, initialising the reference and picture data
+ /*
+ Constructor, initialising the reference and picture data
+ \param ref the reference picture
+ \param pic the picture being matched
+ */
+ BlockDiffUp( const PicArray& ref , const PicArray& pic );
+
+ //! Destructor
+ virtual ~BlockDiffUp(){}
+
+ //! Do the difference, returning SAD
+ /*!
+ Do the difference, returning SAD
+ \param dparams block parameters
+ \param mv the motion vector being used
+ */
+ virtual float Diff( const BlockDiffParams& dparams , const MVector& mv )=0;
+
+ //! Do the actual difference, overwriting the best MV so far if appropriate
+ /*!
+ Do the actual difference, overwriting the best MV so far if appropriate,
+ and bailing out if we do worse
+ \param dparams block parameters
+ \param mv the motion vector being used
+ \param mvcost the (prediction) cost of the motion vector mv
+ \param lambda the weighting to be given to mvcost
+ \param best_costs the best Lagrangian costs obtained yet
+ \param best_mv the MV giving the best Lagrangian costs so far
+ */
+ virtual void Diff( const BlockDiffParams& dparams,
+ const MVector& mv ,
+ const float mvcost,
+ const float lambda,
+ MvCostData& best_costs ,
+ MVector& best_mv)=0;
+ private:
+ //! Private, bodyless copy-constructor: class should not be copied
+ BlockDiffUp(const BlockDiffUp& cpy);
+
+ //! Private, bodyless assignment=: class should not be assigned
+ BlockDiffUp& operator=(const BlockDiffUp& rhs);
+ };
+
+ //! A class for doing differences with half-pixel accurate vectors
+ class BlockDiffHalfPel: public BlockDiffUp
+ {
+
+ public:
+ //! Constructor, initialising the reference and picture data
+ /*
+ Constructor, initialising the reference and picture data
+ \param ref the reference picture
+ \param pic the picture being matched
+ */
+ BlockDiffHalfPel( const PicArray& ref , const PicArray& pic );
+
+ //! Destructor
+ ~BlockDiffHalfPel(){}
+
+ //! Do the difference, returning SAD
+ /*!
+ Do the difference, returning SAD
+ \param dparams block parameters
+ \param mv the motion vector being used
+ */
+ float Diff( const BlockDiffParams& dparams , const MVector& mv );
+
+ //! Do the actual difference, overwriting the best MV so far if appropriate
+ /*!
+ Do the actual difference, overwriting the best MV so far if appropriate,
+ and bailing out if we do worse
+ \param dparams block parameters
+ \param mv the motion vector being used
+ \param mvcost the (prediction) cost of the motion vector mv
+ \param lambda the weighting to be given to mvcost
+ \param best_costs the best Lagrangian costs obtained yet
+ \param best_mv the MV giving the best Lagrangian costs so far
+ */
+ void Diff( const BlockDiffParams& dparams,
+ const MVector& mv ,
+ const float mvcost,
+ const float lambda,
+ MvCostData& best_costs ,
+ MVector& best_mv);
+
+ private:
+ //! Private, bodyless copy-constructor: class should not be copied
+ BlockDiffHalfPel(const BlockDiffHalfPel& cpy);
+
+ //! Private, bodyless assignment=: class should not be assigned
+ BlockDiffHalfPel& operator=(const BlockDiffHalfPel& rhs);
+
+ };
+
+ //! A class for doing differences with quarter-pixel accurate vectors
+ class BlockDiffQuarterPel: public BlockDiffUp
+ {
+ public:
+ //! Constructor, initialising the reference and picture data
+ /*
+ Constructor, initialising the reference and picture data
+ \param ref the reference picture
+ \param pic the picture being matched
+ */
+ BlockDiffQuarterPel( const PicArray& ref , const PicArray& pic );
+
+ //! Destructor
+ ~BlockDiffQuarterPel(){}
+
+ //! Do the difference, returning SAD
+ /*!
+ Do the difference, returning SAD
+ \param dparams block parameters
+ \param mv the motion vector being used
+ */
+ float Diff( const BlockDiffParams& dparams , const MVector& mv );
+
+ //! Do the actual difference, overwriting the best MV so far if appropriate
+ /*!
+ Do the actual difference, overwriting the best MV so far if appropriate,
+ and bailing out if we do worse
+ \param dparams block parameters
+ \param mv the motion vector being used
+ \param mvcost the (prediction) cost of the motion vector mv
+ \param lambda the weighting to be given to mvcost
+ \param best_costs the best Lagrangian costs obtained yet
+ \param best_mv the MV giving the best Lagrangian costs so far
+ */
+ void Diff( const BlockDiffParams& dparams,
+ const MVector& mv ,
+ const float mvcost,
+ const float lambda,
+ MvCostData& best_costs ,
+ MVector& best_mv);
+
+ private:
+ //! Private, bodyless copy-constructor: class should not be copied
+ BlockDiffQuarterPel(const BlockDiffQuarterPel& cpy);
+
+ //! Private, bodyless assignment=: class should not be assigned
+ BlockDiffQuarterPel& operator=(const BlockDiffQuarterPel& rhs);
+ };
+
+ //! A class for doing differences with eighth-pixel accurate vectors
+ class BlockDiffEighthPel: public BlockDiffUp
+ {
+ public:
+ //! Constructor, initialising the reference and picture data
+ /*
+ Constructor, initialising the reference and picture data
+ \param ref the reference picture
+ \param pic the picture being matched
+ */
+ BlockDiffEighthPel( const PicArray& ref , const PicArray& pic );
+
+ //! Destructor
+ ~BlockDiffEighthPel(){}
+
+ //! Do the difference, returning SAD
+ /*!
+ Do the difference, returning SAD
+ \param dparams block parameters
+ \param mv the motion vector being used
+ */
+ float Diff( const BlockDiffParams& dparams , const MVector& mv );
+
+ //! Do the actual difference, overwriting the best MV so far if appropriate
+ /*!
+ Do the actual difference, overwriting the best MV so far if appropriate,
+ and bailing out if we do worse
+ \param dparams block parameters
+ \param mv the motion vector being used
+ \param mvcost the (prediction) cost of the motion vector mv
+ \param lambda the weighting to be given to mvcost
+ \param best_costs the best Lagrangian costs obtained yet
+ \param best_mv the MV giving the best Lagrangian costs so far
+ */
+ void Diff( const BlockDiffParams& dparams,
+ const MVector& mv ,
+ const float mvcost,
+ const float lambda,
+ MvCostData& best_costs ,
+ MVector& best_mv);
+
+ private:
+ //! Private, bodyless copy-constructor: class should not be copied
+ BlockDiffEighthPel(const BlockDiffEighthPel& cpy);
+
+ //! Private, bodyless assignment=: class should not be assigned
+ BlockDiffEighthPel& operator=(const BlockDiffEighthPel& rhs);
+ };
+
+ //! A class for computing a bidirection difference for half-pel vectors
+ class BiBlockHalfPel: public BiBlockDiff
+ {
+ public:
+ //! Constructor, initialising the references and picture data
+ /*
+ Constructor, initialising the reference and picture data
+ \param ref1 the first reference picture
+ \param ref2 the second reference picture
+ \param pic the picture being matched
+ */
+ BiBlockHalfPel( const PicArray& ref1 , const PicArray& ref2 , const PicArray& pic );
+
+ //! Do the difference, returning SAD
+ /*!
+ Do the difference, returning SAD
+ \param dparams block parameters
+ \param mv1 the motion vector being used for reference 1
+ \param mv2 the motion vector being used for reference 2
+ */
+ float Diff( const BlockDiffParams& dparams , const MVector& mv1 , const MVector& mv2 );
+ private:
+ //! Private, bodyless copy-constructor: class should not be copied
+ BiBlockHalfPel(const BiBlockHalfPel& cpy);
+
+ //! Private, bodyless assignment=: class should not be assigned
+ BiBlockHalfPel& operator=(const BiBlockHalfPel& rhs);
+ };
+
+ //! A class for computing a bidirection difference for quarter-pel vectors
+ class BiBlockQuarterPel: public BiBlockDiff
+ {
+ public:
+ //! Constructor, initialising the references and picture data
+ /*
+ Constructor, initialising the reference and picture data
+ \param ref1 the first reference picture
+ \param ref2 the second reference picture
+ \param pic the picture being matched
+ */
+ BiBlockQuarterPel( const PicArray& ref1 , const PicArray& ref2 , const PicArray& pic );
+
+ //! Do the difference, returning SAD
+ /*!
+ Do the difference, returning SAD
+ \param dparams block parameters
+ \param mv1 the motion vector being used for reference 1
+ \param mv2 the motion vector being used for reference 2
+ */
+ float Diff( const BlockDiffParams& dparams , const MVector& mv1 , const MVector& mv2 );
+
+ private:
+ //! Private, bodyless copy-constructor: class should not be copied
+ BiBlockQuarterPel(const BiBlockQuarterPel& cpy);
+
+ //! Private, bodyless assignment=: class should not be assigned
+ BiBlockQuarterPel& operator=(const BiBlockQuarterPel& rhs);
+ };
+
+ //! A class for computing a bidirection difference for eighth-pel vectors
+ class BiBlockEighthPel: public BiBlockDiff
+ {
+ public:
+ //! Constructor, initialising the references and picture data
+ /*
+ Constructor, initialising the reference and picture data
+ \param ref1 the first reference picture
+ \param ref2 the second reference picture
+ \param pic the picture being matched
+ */
+ BiBlockEighthPel( const PicArray& ref1 , const PicArray& ref2 , const PicArray& pic );
+
+ //! Do the difference, returning SAD
+ /*!
+ Do the difference, returning SAD
+ \param dparams block parameters
+ \param mv1 the motion vector being used for reference 1
+ \param mv2 the motion vector being used for reference 2
+ */
+ float Diff( const BlockDiffParams& dparams , const MVector& mv1 , const MVector& mv2 );
+ private:
+ //! Private, bodyless copy-constructor: class should not be copied
+ BiBlockEighthPel(const BiBlockEighthPel& cpy);
+
+ //! Private, bodyless assignment=: class should not be assigned
+ BiBlockEighthPel& operator=(const BiBlockEighthPel& rhs);
+ };
} // namespace dirac
#endif
diff --git a/src/filters/parser/DiracSplitter/libdirac/libdirac_motionest/me_utils_mmx.cpp b/src/filters/parser/DiracSplitter/libdirac/libdirac_motionest/me_utils_mmx.cpp
index b3c1d1836..692b9c148 100644
--- a/src/filters/parser/DiracSplitter/libdirac/libdirac_motionest/me_utils_mmx.cpp
+++ b/src/filters/parser/DiracSplitter/libdirac/libdirac_motionest/me_utils_mmx.cpp
@@ -43,1093 +43,1092 @@ using namespace dirac;
namespace dirac
{
-typedef union
-{
- int i[2];
- short h[4];
- __m64 m;
-} u_mmx_val;
-
-CalcValueType simple_block_diff_mmx_4(
- const BlockDiffParams& dparams, const MVector& mv,
- const PicArray& pic_data, const PicArray& ref_data,
- CalcValueType i_best_sum)
-{
- u_mmx_val u_sum;
-
- u_sum.i[0] = u_sum.i[1] = 0;
-
- ValueType *src = &(pic_data[dparams.Yp()][dparams.Xp()]);
- ValueType *refd = &(ref_data[dparams.Yp()+mv.y][dparams.Xp()+mv.x]);
-
- int height = dparams.Yl();
- int width = dparams.Xl();
- int stopX = (width >> 2) << 2;
- int pic_next = (pic_data.LengthX() - width);
- int ref_next = (ref_data.LengthX() - width);
- CalcValueType mop_sum = 0;
- for(int j = 0; j < height; j++)
+ typedef union
{
- for(int i = 0; i < stopX; i += 4)
- {
- // pic - ref
- __m64 pic = _mm_sub_pi16(*(__m64 *)src, *(__m64 *)refd);
- // abs (pic - ref)
- __m64 ref = _mm_srai_pi16(pic, 15);
- pic = _mm_xor_si64(pic, ref);
- pic = _mm_sub_pi16(pic, ref);
- // sum += abs(pic -ref)
- ref = _mm_xor_si64(ref, ref);
- ref = _mm_unpackhi_pi16(pic, ref);
- pic = _mm_unpacklo_pi16(pic, pic);
- pic = _mm_srai_pi32(pic, 16);
- pic = _mm_add_pi32(pic, ref);
- u_sum.m = _mm_add_pi32(u_sum.m, pic);
- src += 4;
- refd += 4;
- }
- for(int i = stopX; i < width; i++)
- {
- mop_sum += std::abs(*src - *refd);
- src++;
- refd++;
- }
- if((u_sum.i[0] + u_sum.i[1] + mop_sum) >= i_best_sum)
- {
- _mm_empty();
- return i_best_sum;
- }
- src += pic_next;
- refd += ref_next;
- }
- _mm_empty();
-
- return u_sum.i[0] + u_sum.i[1] + mop_sum;
-}
-
-
-CalcValueType simple_intra_block_diff_mmx_4(
- const BlockDiffParams& dparams,
- const PicArray& pic_data, ValueType &dc_val)
-{
- __m64 tmp = _mm_set_pi16(0, 0, 0, 0);
- u_mmx_val u_sum;
- u_sum.i[0] = u_sum.i[1] = 0;
-
- ValueType *src = &(pic_data[dparams.Yp()][dparams.Xp()]);
-
- int height = dparams.Yl();
- int width = dparams.Xl();
- int stopX = (width >> 2) << 2;
- int pic_next = (pic_data.LengthX() - width);
- CalcValueType mop_sum = 0;
- for(int j = 0; j < height; j++)
+ int i[2];
+ short h[4];
+ __m64 m;
+ } u_mmx_val;
+
+ CalcValueType simple_block_diff_mmx_4 (
+ const BlockDiffParams& dparams, const MVector& mv,
+ const PicArray& pic_data, const PicArray& ref_data,
+ CalcValueType i_best_sum)
{
- for(int i = 0; i < stopX; i += 4)
- {
- __m64 pic = *(__m64 *)src;
- // sum += (pic)
- tmp = _mm_xor_si64(tmp, tmp);
- tmp = _mm_unpackhi_pi16(pic, tmp);
- tmp = _mm_slli_pi32(tmp, 16);
- tmp = _mm_srai_pi32(tmp, 16);
- pic = _mm_unpacklo_pi16(pic, pic);
- pic = _mm_srai_pi32(pic, 16);
- pic = _mm_add_pi32(pic, tmp);
- u_sum.m = _mm_add_pi32(u_sum.m, pic);
- src += 4;
- }
- // Mop up
- for(int i = stopX; i < width; ++i)
- {
- mop_sum += *src;
- src++;
- }
- src += pic_next;
- }
+ u_mmx_val u_sum;
- CalcValueType int_dc = (u_sum.i[0] + u_sum.i[1] + mop_sum) / (width * height);
+ u_sum.i[0] = u_sum.i[1] = 0;
- dc_val = static_cast<ValueType>(int_dc);
+ ValueType *src = &(pic_data[dparams.Yp()][dparams.Xp()]);
+ ValueType *refd = &(ref_data[dparams.Yp()+mv.y][dparams.Xp()+mv.x]);
- // Now compute the resulting SAD
- __m64 dc = _mm_set_pi16(dc_val, dc_val , dc_val , dc_val);
- u_sum.m = _mm_xor_si64(u_sum.m, u_sum.m); // initialise sum to 0
- mop_sum = 0;
-
- src = &(pic_data[dparams.Yp()][dparams.Xp()]);
- for(int j = 0; j < height; ++j)
- {
- for(int i = 0; i < stopX; i += 4)
+ int height = dparams.Yl();
+ int width = dparams.Xl();
+ int stopX = (width>>2)<<2;
+ int pic_next = (pic_data.LengthX() - width);
+ int ref_next = (ref_data.LengthX() - width);
+ CalcValueType mop_sum = 0;
+ for (int j = 0; j < height; j++)
{
- __m64 pic = *(__m64 *)src;
- // pic - dc
- pic = _mm_sub_pi16(pic, dc);
- // abs (pic - dc)
- tmp = _mm_srai_pi16(pic, 15);
- pic = _mm_xor_si64(pic, tmp);
- pic = _mm_sub_pi16(pic, tmp);
- // sum += abs(pic -dc)
- tmp = _mm_xor_si64(tmp, tmp);
- tmp = _mm_unpackhi_pi16(pic, tmp);
- pic = _mm_unpacklo_pi16(pic, pic);
- pic = _mm_srai_pi32(pic, 16);
- pic = _mm_add_pi32(pic, tmp);
- u_sum.m = _mm_add_pi32(u_sum.m, pic);
- src += 4;
- }
- // Mop up
- for(int i = stopX; i < width; ++i)
- {
- mop_sum += std::abs(*src - dc_val);
- src++;
- }
- src += pic_next;
- }
- CalcValueType intra_cost = u_sum.i[0] + u_sum.i[1] + mop_sum;
- _mm_empty();
-
- return intra_cost;
-
-}
-
-/*
-* NOTE: we are not doing any bounds checks here. This function must
-* be invoked only when the reference images start and stop fall
-* withing bounds
-*/
-float simple_block_diff_up_mmx_4(
- const PicArray& pic_data, const PicArray& ref_data,
- const ImageCoords& start_pos, const ImageCoords& end_pos,
- const ImageCoords& ref_start, const ImageCoords& ref_stop,
- const MVector& rmdr, float cost_so_far,
- float best_total_cost_so_far)
-{
- ValueType *pic_curr = &pic_data[start_pos.y][start_pos.x];
- ValueType *ref_curr = &ref_data[ref_start.y][ref_start.x];
-
- const int width = end_pos.x - start_pos.x;
- int height = end_pos.y - start_pos.y;
- const int ref_stride = ref_data.LengthX();
-
- // go down a row and back up
- const int pic_next = pic_data.LengthX() - width;
- // go down 2 rows and back up
- const int ref_next = ref_data.LengthX() * 2 - width * 2;
-
- REPORTM(ref_start.x >= 0 && ref_stop.x < ref_data.LengthX() &&
- ref_start.y >= 0 && ref_stop.y < ref_data.LengthY(),
- "Reference image coordinates within bounds");
-
- CalcValueType sum = 0;
- CalcValueType mop_sum(0);
- int stopX = (width >> 2) << 2;
- __m64 m_sum = _mm_set_pi16(0, 0, 0, 0);
- u_mmx_val u_sum;
- if(rmdr.x == 0 && rmdr.y == 0)
- {
- //std::cerr << "Inmmx routine rmdr.x = rmdr.y = 0" << std::endl;
-#if 1
- for(int y = 0; y < height; y++, pic_curr += pic_next, ref_curr += ref_next)
- {
- m_sum = _mm_xor_si64(m_sum, m_sum);
- mop_sum = 0;
- for(int x = 0; x < stopX; x += 4, pic_curr += 4, ref_curr += 8)
+ for (int i = 0; i < stopX; i+=4)
{
- __m64 pic = *(__m64 *)pic_curr;
- __m64 ref = _mm_unpacklo_pi16(*(__m64 *)ref_curr, *(__m64 *)(ref_curr + 4));
- __m64 ref2 = _mm_unpackhi_pi16(*(__m64 *)ref_curr, *(__m64 *)(ref_curr + 4));
- ref = _mm_unpacklo_pi16(ref, ref2);
- // ref - pic
- pic = _mm_sub_pi16(pic, ref);
- // abs (ref - pic)
- ref = _mm_srai_pi16(pic, 15);
+ // pic - ref
+ __m64 pic = _mm_sub_pi16 (*(__m64 *)src, *(__m64 *)refd);
+ // abs (pic - ref)
+ __m64 ref = _mm_srai_pi16(pic, 15);
pic = _mm_xor_si64(pic, ref);
- pic = _mm_sub_pi16(pic, ref);
- // sum += abs(ref -pic)
- /**
- * Since we are re-initialising m_sum with every loop
- * maybe we don't need the following since overflow may
- * not occur
+ pic = _mm_sub_pi16 (pic, ref);
+ // sum += abs(pic -ref)
ref = _mm_xor_si64(ref, ref);
ref = _mm_unpackhi_pi16(pic, ref);
pic = _mm_unpacklo_pi16(pic, pic);
pic = _mm_srai_pi32 (pic, 16);
pic = _mm_add_pi32 (pic, ref);
- m_sum = _mm_add_pi32 (m_sum, pic);
- **/
- m_sum = _mm_add_pi16(m_sum, pic);
+ u_sum.m = _mm_add_pi32 (u_sum.m, pic);
+ src += 4;
+ refd += 4;
}
- // mopup;
- for(int x = stopX; x < width; ++x, ++pic_curr, ref_curr += 2)
+ for (int i = stopX; i < width; i++)
{
- mop_sum += std::abs(*ref_curr - *pic_curr);
+ mop_sum += std::abs(*src - *refd);
+ src++;
+ refd++;
}
- u_sum.m = m_sum;
- //sum += (u_sum.i[0] + u_sum.i[1] + mop_sum);
- sum += (u_sum.h[0] + u_sum.h[1] + u_sum.h[2] + u_sum.h[3] + mop_sum);
- _mm_empty();
- if((sum + cost_so_far) >= best_total_cost_so_far)
+ if ((u_sum.i[0] + u_sum.i[1] + mop_sum) >= i_best_sum)
{
- return best_total_cost_so_far;
+ _mm_empty();
+ return i_best_sum;
}
+ src += pic_next;
+ refd += ref_next;
}
_mm_empty();
- return sum + cost_so_far;
-#else
- float sum = cost_so_far;
- for(int y = 0; y < height; ++y, pic_curr += pic_next, ref_curr += ref_next)
- {
- for(int x = 0; x < width; ++x, ++pic_curr, ref_curr += 2)
- {
- sum += std::abs(*ref_curr - *pic_curr);
- }// x
- if(sum >= best_total_cost_so_far)
- return best_total_cost_so_far;
+ return u_sum.i[0] + u_sum.i[1] + mop_sum;
+ }
- }// y
- return sum;
-#endif
- }
- else if(rmdr.y == 0)
+ CalcValueType simple_intra_block_diff_mmx_4 (
+ const BlockDiffParams& dparams,
+ const PicArray& pic_data, ValueType &dc_val)
{
-#if 1
- __m64 m_one = _mm_set_pi16(1, 1, 1, 1);
- for(int y = 0; y < height; y++, pic_curr += pic_next, ref_curr += ref_next)
+ __m64 tmp = _mm_set_pi16(0, 0, 0, 0);
+ u_mmx_val u_sum;
+ u_sum.i[0] = u_sum.i[1] = 0;
+
+ ValueType *src = &(pic_data[dparams.Yp()][dparams.Xp()]);
+
+ int height = dparams.Yl();
+ int width = dparams.Xl();
+ int stopX = (width>>2)<<2;
+ int pic_next = (pic_data.LengthX() - width);
+ CalcValueType mop_sum = 0;
+ for (int j = 0; j < height; j++)
{
- m_sum = _mm_xor_si64(m_sum, m_sum);
- mop_sum = 0;
- for(int x = 0; x < stopX; x += 4, pic_curr += 4, ref_curr += 8)
+ for (int i = 0; i < stopX; i+=4)
{
- // Load ref
- __m64 m1 = _mm_unpacklo_pi16(*(__m64 *)ref_curr, *(__m64 *)(ref_curr + 4));
- __m64 m2 = _mm_unpackhi_pi16(*(__m64 *)ref_curr, *(__m64 *)(ref_curr + 4));
- // m3 = words 0 2 4 6 of ref_curr
- __m64 m3 = _mm_unpacklo_pi16(m1, m2);
- // m2 = words 1 3 5 7 of ref_curr
- m2 = _mm_unpackhi_pi16(m1, m2);
- // (ref_curr[0] + ref_curr[1] + 1)>>1
- m3 = _mm_add_pi16(m3, m2);
- m3 = _mm_add_pi16(m3, m_one);
- m3 = _mm_srai_pi16(m3, 1);
- // ref - pic
- m1 = _mm_sub_pi16(*(__m64 *)pic_curr, m3);
- // abs (ref - pic)
- m3 = _mm_srai_pi16(m1, 15);
- m1 = _mm_xor_si64(m1, m3);
- m1 = _mm_sub_pi16(m1, m3);
- // sum += abs(ref -pic)
- /**
- * Since we are re-initialising m_sum with every loop
- * maybe we don't need the following since overflow may
- * not occur
- ref = _mm_xor_si64(ref, ref);
- ref = _mm_unpackhi_pi16(pic, ref);
+ __m64 pic = *(__m64 *)src;
+ // sum += (pic)
+ tmp = _mm_xor_si64(tmp, tmp);
+ tmp = _mm_unpackhi_pi16(pic, tmp);
+ tmp = _mm_slli_pi32 (tmp, 16);
+ tmp = _mm_srai_pi32 (tmp, 16);
pic = _mm_unpacklo_pi16(pic, pic);
pic = _mm_srai_pi32 (pic, 16);
- pic = _mm_add_pi32 (pic, ref);
- m_sum = _mm_add_pi32 (m_sum, pic);
- **/
- m_sum = _mm_add_pi16(m_sum, m1);
- }
- // mopup;
- for(int x = stopX; x < width; ++x, ++pic_curr, ref_curr += 2)
- {
- CalcValueType temp = (ref_curr[0] + ref_curr[1] + 1) >> 1;
- mop_sum += std::abs(temp - *pic_curr);
+ pic = _mm_add_pi32 (pic, tmp);
+ u_sum.m = _mm_add_pi32 (u_sum.m, pic);
+ src += 4;
}
- u_sum.m = m_sum;
- //sum += (u_sum.i[0] + u_sum.i[1] + mop_sum);
- sum += (u_sum.h[0] + u_sum.h[1] + u_sum.h[2] + u_sum.h[3] + mop_sum);
- _mm_empty();
- if((sum + cost_so_far) >= best_total_cost_so_far)
+ // Mop up
+ for (int i = stopX; i < width; ++i)
{
- return best_total_cost_so_far;
+ mop_sum += *src;
+ src++;
}
+ src += pic_next;
}
- _mm_empty();
- return sum + cost_so_far;
-#else
- //std::cerr << "Inmmx routine rmdr.y == 0" << std::endl;
- CalcValueType sum(0);
- for(int y = 0; y < height; ++y, pic_curr += pic_next, ref_curr += ref_next)
- {
- for(int x = 0; x < width; ++x, ++pic_curr, ref_curr += 2)
- {
- CalcValueType temp = (CalcValueType(ref_curr[0]) +
- CalcValueType(ref_curr[1]) +
- 1
- ) >> 1;
- sum += std::abs(temp - *pic_curr);
- }// x
- if((sum + cost_so_far) >= best_total_cost_so_far)
- return best_total_cost_so_far;
+ CalcValueType int_dc = (u_sum.i[0] + u_sum.i[1] + mop_sum)/(width*height);
- }// y
- return sum + cost_so_far;
-#endif
- }
- else if(rmdr.x == 0)
- {
-#if 1
- __m64 m_one = _mm_set_pi16(1, 1, 1, 1);
- for(int y = 0; y < height; y++, pic_curr += pic_next, ref_curr += ref_next)
- {
- m_sum = _mm_xor_si64(m_sum, m_sum);
- mop_sum = 0;
- for(int x = 0; x < stopX; x += 4, pic_curr += 4, ref_curr += 8)
- {
- // Load ref
- __m64 m1 = _mm_unpacklo_pi16(*(__m64 *)ref_curr, *(__m64 *)(ref_curr + 4));
- __m64 m2 = _mm_unpackhi_pi16(*(__m64 *)ref_curr, *(__m64 *)(ref_curr + 4));
- // m1 = words 0 2 4 6 of ref_curr
- m1 = _mm_unpacklo_pi16(m1, m2);
- // m2 = words 0 2 4 6 of ref_curr+ref_stride
- m2 = _mm_unpacklo_pi16(*(__m64 *)(ref_curr + ref_stride), *(__m64 *)(ref_curr + ref_stride + 4));
- __m64 m3 = _mm_unpackhi_pi16(*(__m64 *)(ref_curr + ref_stride), *(__m64 *)(ref_curr + ref_stride + 4));
- m2 = _mm_unpacklo_pi16(m2, m3);
+ dc_val = static_cast<ValueType>( int_dc );
- // (ref_curr[0] + ref_curr[ref_stride] + 1)>>1
- m1 = _mm_add_pi16(m1, m2);
- m1 = _mm_add_pi16(m1, m_one);
- m1 = _mm_srai_pi16(m1, 1);
- // ref - pic
- m1 = _mm_sub_pi16(*(__m64 *)pic_curr, m1);
- // abs (ref - pic)
- m3 = _mm_srai_pi16(m1, 15);
- m1 = _mm_xor_si64(m1, m3);
- m1 = _mm_sub_pi16(m1, m3);
- // sum += abs(ref -pic)
- m_sum = _mm_add_pi16(m_sum, m1);
- }
- // mopup;
- for(int x = stopX; x < width; ++x, ++pic_curr, ref_curr += 2)
+ // Now compute the resulting SAD
+ __m64 dc = _mm_set_pi16 ( dc_val, dc_val , dc_val , dc_val);
+ u_sum.m = _mm_xor_si64(u_sum.m, u_sum.m); // initialise sum to 0
+ mop_sum = 0;
+
+ src = &(pic_data[dparams.Yp()][dparams.Xp()]);
+ for (int j = 0; j < height; ++j)
+ {
+ for (int i = 0; i < stopX; i+=4)
{
- CalcValueType temp = (ref_curr[0] + ref_curr[ref_stride] + 1) >> 1;
- mop_sum += std::abs(temp - *pic_curr);
+ __m64 pic = *(__m64 *)src;
+ // pic - dc
+ pic = _mm_sub_pi16 (pic, dc);
+ // abs (pic - dc)
+ tmp = _mm_srai_pi16(pic, 15);
+ pic = _mm_xor_si64(pic, tmp);
+ pic = _mm_sub_pi16 (pic, tmp);
+ // sum += abs(pic -dc)
+ tmp = _mm_xor_si64(tmp, tmp);
+ tmp = _mm_unpackhi_pi16(pic, tmp);
+ pic = _mm_unpacklo_pi16(pic, pic);
+ pic = _mm_srai_pi32 (pic, 16);
+ pic = _mm_add_pi32 (pic, tmp);
+ u_sum.m = _mm_add_pi32 (u_sum.m, pic);
+ src += 4;
}
- u_sum.m = m_sum;
- //sum += (u_sum.i[0] + u_sum.i[1] + mop_sum);
- sum += (u_sum.h[0] + u_sum.h[1] + u_sum.h[2] + u_sum.h[3] + mop_sum);
- _mm_empty();
- if((sum + cost_so_far) >= best_total_cost_so_far)
+ // Mop up
+ for (int i = stopX; i < width; ++i)
{
- return best_total_cost_so_far;
+ mop_sum += std::abs(*src - dc_val);
+ src++;
}
+ src += pic_next;
}
+ CalcValueType intra_cost = u_sum.i[0] + u_sum.i[1] + mop_sum;
_mm_empty();
- return sum + cost_so_far;
-#else
- CalcValueType sum(0);
- for(int y = 0; y < height; ++y, pic_curr += pic_next, ref_curr += ref_next)
- {
- for(int x = 0; x < width; ++x, ++pic_curr, ref_curr += 2)
- {
- CalcValueType temp = (ref_curr[0] + ref_curr[ref_stride] + 1) >> 1;
- sum += std::abs(temp - *pic_curr);
- }// x
- if((sum + cost_so_far) >= best_total_cost_so_far)
- return best_total_cost_so_far;
+ return intra_cost;
- }// y
- return sum + cost_so_far;
-#endif
}
- else
+
+ /*
+ * NOTE: we are not doing any bounds checks here. This function must
+ * be invoked only when the reference images start and stop fall
+ * withing bounds
+ */
+ float simple_block_diff_up_mmx_4(
+ const PicArray& pic_data, const PicArray& ref_data,
+ const ImageCoords& start_pos, const ImageCoords& end_pos,
+ const ImageCoords& ref_start, const ImageCoords& ref_stop,
+ const MVector& rmdr, float cost_so_far,
+ float best_total_cost_so_far)
{
-#if 1
- __m64 m_two = _mm_set_pi32(2, 2);
- __m64 m_one = _mm_set_pi16(1, 1, 1, 1);
- // processing four pic_data values at a time
- for(int y = 0; y < height; y++, pic_curr += pic_next, ref_curr += ref_next)
+ ValueType *pic_curr = &pic_data[start_pos.y][start_pos.x];
+ ValueType *ref_curr = &ref_data[ref_start.y][ref_start.x];
+
+ const int width = end_pos.x - start_pos.x;
+ int height = end_pos.y - start_pos.y;
+ const int ref_stride = ref_data.LengthX();
+
+ // go down a row and back up
+ const int pic_next = pic_data.LengthX() - width;
+ // go down 2 rows and back up
+ const int ref_next = ref_data.LengthX()*2 - width*2;
+
+ REPORTM (ref_start.x>=0 && ref_stop.x < ref_data.LengthX() &&
+ ref_start.y>=0 && ref_stop.y < ref_data.LengthY(),
+ "Reference image coordinates within bounds");
+
+ CalcValueType sum = 0;
+ CalcValueType mop_sum(0);
+ int stopX = (width>>2)<<2;
+ __m64 m_sum = _mm_set_pi16(0, 0, 0, 0);
+ u_mmx_val u_sum;
+ if (rmdr.x == 0 && rmdr.y == 0 )
{
- m_sum = _mm_xor_si64(m_sum, m_sum);
- mop_sum = 0;
- for(int x = 0; x < stopX; x += 4, pic_curr += 4, ref_curr += 8)
+ //std::cerr << "Inmmx routine rmdr.x = rmdr.y = 0" << std::endl;
+#if 1
+ for( int y=0; y < height; y++, pic_curr+=pic_next, ref_curr+=ref_next )
{
- // Load ref
- // m1 = words 0 1 2 3 of line 0 ref_curr
- __m64 m1 = *(__m64 *)ref_curr;
- // m1 = words 0 1 2 3 of line 1 of ref_curr
- __m64 m2 = *(__m64 *)(ref_curr + ref_stride);
- // (ref_curr[0] + ref_curr[1] +
- // ref_curr[ref_stride] + ref_curr[ref_stride+1] + 2) >>2
- m1 = _mm_add_pi16(m1, m2);
- m1 = _mm_madd_pi16(m1, m_one);
- m1 = _mm_add_pi32(m1, m_two);
- m1 = _mm_srai_pi32(m1, 2);
-
-
- // m2 = words 4 5 6 7 of line 0 ref_curr
- __m64 m3 = *(__m64 *)(ref_curr + 4);
- // m1 = words 4 5 6 7 of line 1 of ref_curr
- m2 = *(__m64 *)(ref_curr + 4 + ref_stride);
- // (ref_curr[0] + ref_curr[1] +
- // ref_curr[ref_stride] + ref_curr[ref_stride+1] + 2) >>2
- m3 = _mm_add_pi16(m3, m2);
- m3 = _mm_madd_pi16(m3, m_one);
- m3 = _mm_add_pi32(m3, m_two);
- m3 = _mm_srai_pi32(m3, 2);
-
- m1 = _mm_packs_pi32(m1, m3);
-
- // load first four values pic_data
- m2 = *(__m64 *)pic_curr;
-
- // ref - pic
- m1 = _mm_sub_pi16(m1, m2);
- // abs (ref - pic)
- m2 = _mm_srai_pi16(m1, 15);
- m1 = _mm_xor_si64(m1, m2);
- m1 = _mm_sub_pi16(m1, m2);
- // sum += abs(ref -pic)
- m_sum = _mm_add_pi16(m_sum, m1);
+ m_sum = _mm_xor_si64 (m_sum, m_sum);
+ mop_sum= 0;
+ for( int x=0; x < stopX; x+=4, pic_curr+=4, ref_curr+=8 )
+ {
+ __m64 pic = *(__m64 *)pic_curr;
+ __m64 ref = _mm_unpacklo_pi16 (*(__m64 *)ref_curr, *(__m64 *)(ref_curr+4));
+ __m64 ref2 = _mm_unpackhi_pi16 (*(__m64 *)ref_curr, *(__m64 *)(ref_curr+4));
+ ref = _mm_unpacklo_pi16 ( ref, ref2);
+ // ref - pic
+ pic = _mm_sub_pi16 (pic, ref);
+ // abs (ref - pic)
+ ref = _mm_srai_pi16(pic, 15);
+ pic = _mm_xor_si64(pic, ref);
+ pic = _mm_sub_pi16 (pic, ref);
+ // sum += abs(ref -pic)
+ /**
+ * Since we are re-initialising m_sum with every loop
+ * maybe we don't need the following since overflow may
+ * not occur
+ ref = _mm_xor_si64(ref, ref);
+ ref = _mm_unpackhi_pi16(pic, ref);
+ pic = _mm_unpacklo_pi16(pic, pic);
+ pic = _mm_srai_pi32 (pic, 16);
+ pic = _mm_add_pi32 (pic, ref);
+ m_sum = _mm_add_pi32 (m_sum, pic);
+ **/
+ m_sum = _mm_add_pi16 (m_sum, pic);
+ }
+ // mopup;
+ for (int x = stopX; x < width; ++x, ++pic_curr,ref_curr+=2)
+ {
+ mop_sum += std::abs (*ref_curr - *pic_curr);
+ }
+ u_sum.m = m_sum;
+ //sum += (u_sum.i[0] + u_sum.i[1] + mop_sum);
+ sum += (u_sum.h[0] + u_sum.h[1] + u_sum.h[2] + u_sum.h[3] + mop_sum);
+ _mm_empty();
+ if ((sum + cost_so_far )>= best_total_cost_so_far)
+ {
+ return best_total_cost_so_far;
+ }
}
- // mopup;
- for(int x = stopX; x < width; ++x, ++pic_curr, ref_curr += 2)
+ _mm_empty();
+ return sum + cost_so_far;
+#else
+ float sum = cost_so_far;
+ for( int y=0; y < height; ++y, pic_curr+=pic_next, ref_curr+=ref_next )
+ {
+ for( int x=0; x < width; ++x, ++pic_curr, ref_curr+=2 )
+ {
+ sum += std::abs( *ref_curr - *pic_curr );
+ }// x
+
+ if ( sum>= best_total_cost_so_far)
+ return best_total_cost_so_far;
+
+ }// y
+ return sum;
+#endif
+
+ }
+ else if( rmdr.y == 0 )
+ {
+#if 1
+ __m64 m_one = _mm_set_pi16(1, 1, 1, 1);
+ for( int y=0; y < height; y++, pic_curr+=pic_next, ref_curr+=ref_next )
{
- CalcValueType temp = (ref_curr[0] + ref_curr[1] +
- ref_curr[ref_stride] + ref_curr[ref_stride+1] + 2) >> 2;
- mop_sum += std::abs(temp - *pic_curr);
+ m_sum = _mm_xor_si64 (m_sum, m_sum);
+ mop_sum= 0;
+ for( int x=0; x < stopX; x+=4, pic_curr+=4, ref_curr+=8 )
+ {
+ // Load ref
+ __m64 m1 = _mm_unpacklo_pi16 (*(__m64 *)ref_curr, *(__m64 *)(ref_curr+4));
+ __m64 m2 = _mm_unpackhi_pi16 (*(__m64 *)ref_curr, *(__m64 *)(ref_curr+4));
+ // m3 = words 0 2 4 6 of ref_curr
+ __m64 m3 = _mm_unpacklo_pi16 ( m1, m2);
+ // m2 = words 1 3 5 7 of ref_curr
+ m2 = _mm_unpackhi_pi16 ( m1, m2);
+ // (ref_curr[0] + ref_curr[1] + 1)>>1
+ m3 = _mm_add_pi16 (m3, m2);
+ m3 = _mm_add_pi16 (m3, m_one);
+ m3 = _mm_srai_pi16 (m3, 1);
+ // ref - pic
+ m1 = _mm_sub_pi16 (*(__m64 *)pic_curr, m3);
+ // abs (ref - pic)
+ m3 = _mm_srai_pi16(m1, 15);
+ m1 = _mm_xor_si64(m1, m3);
+ m1 = _mm_sub_pi16 (m1, m3);
+ // sum += abs(ref -pic)
+ /**
+ * Since we are re-initialising m_sum with every loop
+ * maybe we don't need the following since overflow may
+ * not occur
+ ref = _mm_xor_si64(ref, ref);
+ ref = _mm_unpackhi_pi16(pic, ref);
+ pic = _mm_unpacklo_pi16(pic, pic);
+ pic = _mm_srai_pi32 (pic, 16);
+ pic = _mm_add_pi32 (pic, ref);
+ m_sum = _mm_add_pi32 (m_sum, pic);
+ **/
+ m_sum = _mm_add_pi16 (m_sum, m1);
+ }
+ // mopup;
+ for (int x = stopX; x < width; ++x, ++pic_curr,ref_curr+=2)
+ {
+ CalcValueType temp = (ref_curr[0] + ref_curr[1]+1)>>1;
+ mop_sum += std::abs (temp - *pic_curr);
+ }
+ u_sum.m = m_sum;
+ //sum += (u_sum.i[0] + u_sum.i[1] + mop_sum);
+ sum += (u_sum.h[0] + u_sum.h[1] + u_sum.h[2] + u_sum.h[3] + mop_sum);
+ _mm_empty();
+ if ((sum + cost_so_far )>= best_total_cost_so_far)
+ {
+ return best_total_cost_so_far;
+ }
}
- u_sum.m = m_sum;
- sum += (u_sum.h[0] + u_sum.h[1] + u_sum.h[2] + u_sum.h[3] + mop_sum);
_mm_empty();
- if((sum + cost_so_far) >= best_total_cost_so_far)
+ return sum + cost_so_far;
+#else
+ //std::cerr << "Inmmx routine rmdr.y == 0" << std::endl;
+ CalcValueType sum(0);
+ for( int y=0; y < height; ++y, pic_curr+=pic_next, ref_curr+=ref_next )
{
- return best_total_cost_so_far;
- }
+ for( int x=0; x < width; ++x, ++pic_curr, ref_curr+=2 )
+ {
+ CalcValueType temp = ( CalcValueType( ref_curr[0] ) +
+ CalcValueType( ref_curr[1] ) +
+ 1
+ ) >> 1;
+ sum += std::abs( temp - *pic_curr );
+ }// x
+
+ if ( (sum+cost_so_far)>=best_total_cost_so_far)
+ return best_total_cost_so_far;
+
+ }// y
+ return sum+cost_so_far;
+#endif
}
- _mm_empty();
- return sum + cost_so_far;
+ else if( rmdr.x == 0 )
+ {
+#if 1
+ __m64 m_one = _mm_set_pi16(1, 1, 1, 1);
+ for( int y=0; y < height; y++, pic_curr+=pic_next, ref_curr+=ref_next )
+ {
+ m_sum = _mm_xor_si64 (m_sum, m_sum);
+ mop_sum= 0;
+ for( int x=0; x < stopX; x+=4, pic_curr+=4, ref_curr+=8 )
+ {
+ // Load ref
+ __m64 m1 = _mm_unpacklo_pi16 (*(__m64 *)ref_curr, *(__m64 *)(ref_curr+4));
+ __m64 m2 = _mm_unpackhi_pi16 (*(__m64 *)ref_curr, *(__m64 *)(ref_curr+4));
+ // m1 = words 0 2 4 6 of ref_curr
+ m1 = _mm_unpacklo_pi16 ( m1, m2);
+ // m2 = words 0 2 4 6 of ref_curr+ref_stride
+ m2 = _mm_unpacklo_pi16 (*(__m64 *)(ref_curr+ref_stride), *(__m64 *)(ref_curr+ref_stride+4));
+ __m64 m3 = _mm_unpackhi_pi16 (*(__m64 *)(ref_curr+ref_stride), *(__m64 *)(ref_curr+ref_stride+4));
+ m2 = _mm_unpacklo_pi16 (m2, m3);
+
+ // (ref_curr[0] + ref_curr[ref_stride] + 1)>>1
+ m1 = _mm_add_pi16 (m1, m2);
+ m1 = _mm_add_pi16 (m1, m_one);
+ m1 = _mm_srai_pi16 (m1, 1);
+ // ref - pic
+ m1 = _mm_sub_pi16 (*(__m64 *)pic_curr, m1);
+ // abs (ref - pic)
+ m3 = _mm_srai_pi16(m1, 15);
+ m1 = _mm_xor_si64(m1, m3);
+ m1 = _mm_sub_pi16 (m1, m3);
+ // sum += abs(ref -pic)
+ m_sum = _mm_add_pi16 (m_sum, m1);
+ }
+ // mopup;
+ for (int x = stopX; x < width; ++x, ++pic_curr,ref_curr+=2)
+ {
+ CalcValueType temp = (ref_curr[0] + ref_curr[ref_stride]+1)>>1;
+ mop_sum += std::abs (temp - *pic_curr);
+ }
+ u_sum.m = m_sum;
+ //sum += (u_sum.i[0] + u_sum.i[1] + mop_sum);
+ sum += (u_sum.h[0] + u_sum.h[1] + u_sum.h[2] + u_sum.h[3] + mop_sum);
+ _mm_empty();
+ if ((sum + cost_so_far )>= best_total_cost_so_far)
+ {
+ return best_total_cost_so_far;
+ }
+ }
+ _mm_empty();
+ return sum + cost_so_far;
#else
- //std::cerr << "Inmmx routine rmdr.y == 0" << std::endl;
- CalcValueType sum(0);
- for(int y = 0; y < height; ++y, pic_curr += pic_next, ref_curr += ref_next)
+ CalcValueType sum(0);
+ for( int y=0; y < height; ++y, pic_curr+=pic_next, ref_curr+=ref_next )
+ {
+ for( int x=0; x < width; ++x, ++pic_curr, ref_curr+=2 )
+ {
+ CalcValueType temp = (ref_curr[0] + ref_curr[ref_stride]+1)>>1;
+ sum += std::abs (temp - *pic_curr);
+ }// x
+
+ if ( (sum+cost_so_far)>=best_total_cost_so_far)
+ return best_total_cost_so_far;
+
+ }// y
+ return sum+cost_so_far;
+#endif
+ }
+ else
{
- for(int x = 0; x < width; ++x, ++pic_curr, ref_curr += 2)
+#if 1
+ __m64 m_two = _mm_set_pi32(2, 2);
+ __m64 m_one = _mm_set_pi16(1, 1, 1, 1);
+ // processing four pic_data values at a time
+ for( int y=0; y < height; y++, pic_curr+=pic_next, ref_curr+=ref_next )
{
- CalcValueType temp = (CalcValueType(ref_curr[0]) +
- CalcValueType(ref_curr[1]) +
- CalcValueType(ref_curr[ref_stride]) +
- CalcValueType(ref_curr[ref_stride+1]) +
- 2
- ) >> 2;
- sum += std::abs(temp - *pic_curr);
- }// x
-
- if((sum + cost_so_far) >= best_total_cost_so_far)
- return best_total_cost_so_far;
-
- }// y
- return sum + cost_so_far;
+ m_sum = _mm_xor_si64 (m_sum, m_sum);
+ mop_sum= 0;
+ for( int x=0; x < stopX; x+=4, pic_curr+=4, ref_curr+=8 )
+ {
+ // Load ref
+ // m1 = words 0 1 2 3 of line 0 ref_curr
+ __m64 m1 = *(__m64 *)ref_curr;
+ // m1 = words 0 1 2 3 of line 1 of ref_curr
+ __m64 m2 = *(__m64 *)(ref_curr+ref_stride);
+ // (ref_curr[0] + ref_curr[1] +
+ // ref_curr[ref_stride] + ref_curr[ref_stride+1] + 2) >>2
+ m1 = _mm_add_pi16 (m1, m2);
+ m1 = _mm_madd_pi16 (m1, m_one);
+ m1 = _mm_add_pi32 (m1, m_two);
+ m1 = _mm_srai_pi32 (m1, 2);
+
+
+ // m2 = words 4 5 6 7 of line 0 ref_curr
+ __m64 m3 = *(__m64 *)(ref_curr+4);
+ // m1 = words 4 5 6 7 of line 1 of ref_curr
+ m2 = *(__m64 *)(ref_curr+4+ref_stride);
+ // (ref_curr[0] + ref_curr[1] +
+ // ref_curr[ref_stride] + ref_curr[ref_stride+1] + 2) >>2
+ m3 = _mm_add_pi16 (m3, m2);
+ m3 = _mm_madd_pi16 (m3, m_one);
+ m3 = _mm_add_pi32 (m3, m_two);
+ m3 = _mm_srai_pi32 (m3, 2);
+
+ m1 = _mm_packs_pi32 (m1, m3);
+
+ // load first four values pic_data
+ m2 = *(__m64 *)pic_curr;
+
+ // ref - pic
+ m1 = _mm_sub_pi16 (m1, m2);
+ // abs (ref - pic)
+ m2 = _mm_srai_pi16(m1, 15);
+ m1 = _mm_xor_si64(m1, m2);
+ m1 = _mm_sub_pi16(m1, m2);
+ // sum += abs(ref -pic)
+ m_sum = _mm_add_pi16 (m_sum, m1);
+ }
+ // mopup;
+ for (int x = stopX; x < width; ++x, ++pic_curr,ref_curr+=2)
+ {
+ CalcValueType temp = (ref_curr[0] + ref_curr[1] +
+ ref_curr[ref_stride] + ref_curr[ref_stride+1]+2)>>2;
+ mop_sum += std::abs (temp - *pic_curr);
+ }
+ u_sum.m = m_sum;
+ sum += (u_sum.h[0] + u_sum.h[1] + u_sum.h[2] + u_sum.h[3] + mop_sum);
+ _mm_empty();
+ if ((sum + cost_so_far )>= best_total_cost_so_far)
+ {
+ return best_total_cost_so_far;
+ }
+ }
+ _mm_empty();
+ return sum + cost_so_far;
+#else
+ //std::cerr << "Inmmx routine rmdr.y == 0" << std::endl;
+ CalcValueType sum(0);
+ for( int y=0; y < height; ++y, pic_curr+=pic_next, ref_curr+=ref_next )
+ {
+ for( int x=0; x < width; ++x, ++pic_curr, ref_curr+=2 )
+ {
+ CalcValueType temp = ( CalcValueType( ref_curr[0] ) +
+ CalcValueType( ref_curr[1] ) +
+ CalcValueType( ref_curr[ref_stride] ) +
+ CalcValueType( ref_curr[ref_stride+1] ) +
+ 2
+ ) >> 2;
+ sum += std::abs( temp - *pic_curr );
+ }// x
+
+ if ( (sum+cost_so_far)>=best_total_cost_so_far)
+ return best_total_cost_so_far;
+
+ }// y
+ return sum+cost_so_far;
#endif
- }
+ }
return cost_so_far;
-}
+ }
-/*
-* NOTE: we are not doing any bounds checks here. This function must
-* be invoked only when the reference images start and stop fall
-* withing bounds
-*/
-void simple_biblock_diff_pic_mmx_4(
- const PicArray& pic_data, const PicArray& ref_data,
- TwoDArray<ValueType>& diff,
- const ImageCoords& start_pos, const ImageCoords& end_pos,
- const ImageCoords& ref_start, const ImageCoords& ref_stop,
- const MVector& rmdr)
-{
- ValueType *pic_curr = &pic_data[start_pos.y][start_pos.x];
- ValueType *ref_curr = &ref_data[ref_start.y][ref_start.x];
- ValueType *diff_curr = &diff[0][0];
+ /*
+ * NOTE: we are not doing any bounds checks here. This function must
+ * be invoked only when the reference images start and stop fall
+ * withing bounds
+ */
+ void simple_biblock_diff_pic_mmx_4(
+ const PicArray& pic_data, const PicArray& ref_data,
+ TwoDArray<ValueType>& diff,
+ const ImageCoords& start_pos, const ImageCoords& end_pos,
+ const ImageCoords& ref_start, const ImageCoords& ref_stop,
+ const MVector& rmdr)
+ {
+ ValueType *pic_curr = &pic_data[start_pos.y][start_pos.x];
+ ValueType *ref_curr = &ref_data[ref_start.y][ref_start.x];
+ ValueType *diff_curr = &diff[0][0];
- const int width = end_pos.x - start_pos.x;
- int height = end_pos.y - start_pos.y;
- const int ref_stride = ref_data.LengthX();
+ const int width = end_pos.x - start_pos.x;
+ int height = end_pos.y - start_pos.y;
+ const int ref_stride = ref_data.LengthX();
- // go down a row and back up
- const int pic_next = pic_data.LengthX() - width;
- // go down 2 rows and back up
- const int ref_next = ref_data.LengthX() * 2 - width * 2;
+ // go down a row and back up
+ const int pic_next = pic_data.LengthX() - width;
+ // go down 2 rows and back up
+ const int ref_next = ref_data.LengthX()*2 - width*2;
- REPORTM(ref_start.x >= 0 && ref_stop.x < ref_data.LengthX() &&
- ref_start.y >= 0 && ref_stop.y < ref_data.LengthY(),
- "Reference image coordinates withing bounds");
+ REPORTM (ref_start.x>=0 && ref_stop.x < ref_data.LengthX() &&
+ ref_start.y>=0 && ref_stop.y < ref_data.LengthY(),
+ "Reference image coordinates withing bounds");
- int stopX = (width >> 2) << 2;
- if(rmdr.x == 0 && rmdr.y == 0)
- {
- //std::cerr << "Inmmx routine rmdr.x = rmdr.y = 0" << std::endl;
-#if 1
- for(int y = 0; y < height; y++, pic_curr += pic_next, ref_curr += ref_next)
+ int stopX = (width>>2)<<2;
+ if (rmdr.x == 0 && rmdr.y == 0 )
{
- for(int x = 0; x < stopX; x += 4, pic_curr += 4, ref_curr += 8, diff_curr += 4)
- {
- __m64 pic = *(__m64 *)pic_curr;
- // pic << 1
- pic = _mm_slli_pi16(pic, 1);
- // load ref
- __m64 ref = _mm_unpacklo_pi16(*(__m64 *)ref_curr, *(__m64 *)(ref_curr + 4));
- __m64 ref2 = _mm_unpackhi_pi16(*(__m64 *)ref_curr, *(__m64 *)(ref_curr + 4));
- ref = _mm_unpacklo_pi16(ref, ref2);
- // pic<<1 - ref
- *(__m64 *)diff_curr = _mm_sub_pi16(pic, ref);
- }
- // mopup;
- for(int x = stopX; x < width; ++x, ++pic_curr, ++diff_curr, ref_curr += 2)
+ //std::cerr << "Inmmx routine rmdr.x = rmdr.y = 0" << std::endl;
+#if 1
+ for( int y=0; y < height; y++, pic_curr+=pic_next, ref_curr+=ref_next)
{
- *diff_curr = ((*pic_curr) << 1) - *ref_curr;
+ for( int x=0; x < stopX; x+=4, pic_curr+=4, ref_curr+=8, diff_curr += 4 )
+ {
+ __m64 pic = *(__m64 *)pic_curr;
+ // pic << 1
+ pic = _mm_slli_pi16(pic, 1);
+ // load ref
+ __m64 ref = _mm_unpacklo_pi16 (*(__m64 *)ref_curr, *(__m64 *)(ref_curr+4));
+ __m64 ref2 = _mm_unpackhi_pi16 (*(__m64 *)ref_curr, *(__m64 *)(ref_curr+4));
+ ref = _mm_unpacklo_pi16 ( ref, ref2);
+ // pic<<1 - ref
+ *(__m64 *)diff_curr = _mm_sub_pi16 (pic, ref);
+ }
+ // mopup;
+ for (int x = stopX; x < width; ++x, ++pic_curr, ++diff_curr, ref_curr+=2)
+ {
+ *diff_curr = ((*pic_curr)<<1) - *ref_curr;
+ }
}
- }
#else
- for(int y = 0; y < height; ++y, pic_curr += pic_next, ref_curr += ref_next)
- {
- for(int x = 0; x < width; ++x, ++pic_curr, ++diff_curr, ref_curr += 2)
+ for( int y=0; y < height; ++y, pic_curr+=pic_next, ref_curr+=ref_next )
{
- *diff_curr = ((*pic_curr) << 1) - *ref_curr;
- }// x
- }// y
+ for( int x=0; x < width; ++x, ++pic_curr, ++diff_curr, ref_curr+=2 )
+ {
+ *diff_curr = ((*pic_curr)<<1) - *ref_curr;
+ }// x
+ }// y
#endif
- }
- else if(rmdr.y == 0)
- {
-#if 1
- __m64 m_one = _mm_set_pi16(1, 1, 1, 1);
- for(int y = 0; y < height; y++, pic_curr += pic_next, ref_curr += ref_next)
+ }
+ else if( rmdr.y == 0 )
{
- for(int x = 0; x < stopX; x += 4, pic_curr += 4, diff_curr += 4, ref_curr += 8)
- {
- // Load ref
- __m64 m1 = _mm_unpacklo_pi16(*(__m64 *)ref_curr, *(__m64 *)(ref_curr + 4));
- __m64 m2 = _mm_unpackhi_pi16(*(__m64 *)ref_curr, *(__m64 *)(ref_curr + 4));
- // m3 = words 0 2 4 6 of ref_curr
- __m64 m3 = _mm_unpacklo_pi16(m1, m2);
- // m2 = words 1 3 5 7 of ref_curr
- m2 = _mm_unpackhi_pi16(m1, m2);
- // (ref_curr[0] + ref_curr[1] + 1)>>1
- m3 = _mm_add_pi16(m3, m2);
- m3 = _mm_add_pi16(m3, m_one);
- m3 = _mm_srai_pi16(m3, 1);
- // pic << 1
- m1 = _mm_slli_pi16(*(__m64 *)pic_curr, 1);
- // diff = pic - ref
- *(__m64 *)diff_curr = _mm_sub_pi16(m1, m3);
- }
- // mopup;
- for(int x = stopX; x < width; ++x, ++pic_curr, ++diff_curr, ref_curr += 2)
+#if 1
+ __m64 m_one = _mm_set_pi16(1, 1, 1, 1);
+ for( int y=0; y < height; y++, pic_curr+=pic_next, ref_curr+=ref_next )
{
- CalcValueType temp = (ref_curr[0] + ref_curr[1] + 1) >> 1;
- *diff_curr = ((*pic_curr) << 1) - temp;
+ for( int x=0; x < stopX; x+=4, pic_curr+=4, diff_curr += 4, ref_curr+=8 )
+ {
+ // Load ref
+ __m64 m1 = _mm_unpacklo_pi16 (*(__m64 *)ref_curr, *(__m64 *)(ref_curr+4));
+ __m64 m2 = _mm_unpackhi_pi16 (*(__m64 *)ref_curr, *(__m64 *)(ref_curr+4));
+ // m3 = words 0 2 4 6 of ref_curr
+ __m64 m3 = _mm_unpacklo_pi16 ( m1, m2);
+ // m2 = words 1 3 5 7 of ref_curr
+ m2 = _mm_unpackhi_pi16 ( m1, m2);
+ // (ref_curr[0] + ref_curr[1] + 1)>>1
+ m3 = _mm_add_pi16 (m3, m2);
+ m3 = _mm_add_pi16 (m3, m_one);
+ m3 = _mm_srai_pi16 (m3, 1);
+ // pic << 1
+ m1 = _mm_slli_pi16(*(__m64 *)pic_curr, 1);
+ // diff = pic - ref
+ *(__m64 *)diff_curr = _mm_sub_pi16 (m1, m3);
+ }
+ // mopup;
+ for (int x = stopX; x < width; ++x, ++pic_curr, ++diff_curr, ref_curr+=2)
+ {
+ CalcValueType temp = (ref_curr[0] + ref_curr[1]+1)>>1;
+ *diff_curr = ((*pic_curr)<<1) - temp;
+ }
}
- }
#else
- //std::cerr << "Inmmx routine rmdr.y == 0" << std::endl;
- for(int y = 0; y < height; ++y, pic_curr += pic_next, ref_curr += ref_next)
- {
- for(int x = 0; x < width; ++x, ++pic_curr, ++diff_curr, ref_curr += 2)
+ //std::cerr << "Inmmx routine rmdr.y == 0" << std::endl;
+ for( int y=0; y < height; ++y, pic_curr+=pic_next, ref_curr+=ref_next )
{
- CalcValueType temp = (CalcValueType(ref_curr[0]) +
- CalcValueType(ref_curr[1]) +
- 1
- ) >> 1;
- *diff_curr = ((*pic_curr) << 1) - temp;
- }// x
-
- }// y
+ for( int x=0; x < width; ++x, ++pic_curr, ++diff_curr, ref_curr+=2 )
+ {
+ CalcValueType temp = ( CalcValueType( ref_curr[0] ) +
+ CalcValueType( ref_curr[1] ) +
+ 1
+ ) >> 1;
+ *diff_curr = ((*pic_curr)<<1) - temp;
+ }// x
+
+ }// y
#endif
- }
- else if(rmdr.x == 0)
- {
-#if 1
- __m64 m_one = _mm_set_pi16(1, 1, 1, 1);
- for(int y = 0; y < height; y++, pic_curr += pic_next, ref_curr += ref_next)
+ }
+ else if( rmdr.x == 0 )
{
- for(int x = 0; x < stopX; x += 4, pic_curr += 4, diff_curr += 4, ref_curr += 8)
- {
- // Load ref
- __m64 m1 = _mm_unpacklo_pi16(*(__m64 *)ref_curr, *(__m64 *)(ref_curr + 4));
- __m64 m2 = _mm_unpackhi_pi16(*(__m64 *)ref_curr, *(__m64 *)(ref_curr + 4));
- // m1 = words 0 2 4 6 of ref_curr
- m1 = _mm_unpacklo_pi16(m1, m2);
- // m2 = words 0 2 4 6 of ref_curr+ref_stride
- m2 = _mm_unpacklo_pi16(*(__m64 *)(ref_curr + ref_stride), *(__m64 *)(ref_curr + ref_stride + 4));
- __m64 m3 = _mm_unpackhi_pi16(*(__m64 *)(ref_curr + ref_stride), *(__m64 *)(ref_curr + ref_stride + 4));
- m2 = _mm_unpacklo_pi16(m2, m3);
-
- // (ref_curr[0] + ref_curr[ref_stride] + 1)>>1
- m1 = _mm_add_pi16(m1, m2);
- m1 = _mm_add_pi16(m1, m_one);
- m1 = _mm_srai_pi16(m1, 1);
- // pic << 1
- m2 = _mm_slli_pi16(*(__m64 *)pic_curr, 1);
- // diff = pic<<1 - ref)
- *(__m64 *)diff_curr = _mm_sub_pi16(m2, m1);
- }
- // mopup;
- for(int x = stopX; x < width; ++x, ++pic_curr, ++diff_curr, ref_curr += 2)
+#if 1
+ __m64 m_one = _mm_set_pi16(1, 1, 1, 1);
+ for( int y=0; y < height; y++, pic_curr+=pic_next, ref_curr+=ref_next )
{
- CalcValueType temp = (ref_curr[0] + ref_curr[ref_stride] + 1) >> 1;
- *diff_curr = ((*pic_curr) << 1) - temp;
+ for( int x=0; x < stopX; x+=4, pic_curr+=4, diff_curr +=4, ref_curr+=8 )
+ {
+ // Load ref
+ __m64 m1 = _mm_unpacklo_pi16 (*(__m64 *)ref_curr, *(__m64 *)(ref_curr+4));
+ __m64 m2 = _mm_unpackhi_pi16 (*(__m64 *)ref_curr, *(__m64 *)(ref_curr+4));
+ // m1 = words 0 2 4 6 of ref_curr
+ m1 = _mm_unpacklo_pi16 ( m1, m2);
+ // m2 = words 0 2 4 6 of ref_curr+ref_stride
+ m2 = _mm_unpacklo_pi16 (*(__m64 *)(ref_curr+ref_stride), *(__m64 *)(ref_curr+ref_stride+4));
+ __m64 m3 = _mm_unpackhi_pi16 (*(__m64 *)(ref_curr+ref_stride), *(__m64 *)(ref_curr+ref_stride+4));
+ m2 = _mm_unpacklo_pi16 (m2, m3);
+
+ // (ref_curr[0] + ref_curr[ref_stride] + 1)>>1
+ m1 = _mm_add_pi16 (m1, m2);
+ m1 = _mm_add_pi16 (m1, m_one);
+ m1 = _mm_srai_pi16 (m1, 1);
+ // pic << 1
+ m2 = _mm_slli_pi16 (*(__m64 *)pic_curr, 1);
+ // diff = pic<<1 - ref)
+ *(__m64 *)diff_curr = _mm_sub_pi16(m2, m1 );
+ }
+ // mopup;
+ for (int x = stopX; x < width; ++x, ++pic_curr, ++diff_curr, ref_curr+=2)
+ {
+ CalcValueType temp = (ref_curr[0] + ref_curr[ref_stride]+1)>>1;
+ *diff_curr = ((*pic_curr)<<1) - temp;
+ }
}
- }
#else
- //std::cerr << "Inmmx routine rmdr.y == 0" << std::endl;
- for(int y = 0; y < height; ++y, pic_curr += pic_next, ref_curr += ref_next)
- {
- for(int x = 0; x < width; ++x, ++pic_curr, ++diff_curr, ref_curr += 2)
+ //std::cerr << "Inmmx routine rmdr.y == 0" << std::endl;
+ for( int y=0; y < height; ++y, pic_curr+=pic_next, ref_curr+=ref_next )
{
- CalcValueType temp = (CalcValueType(ref_curr[0]) +
- CalcValueType(ref_curr[1]) +
- 1
- ) >> 1;
- *diff_curr = ((*pic_curr) << 1) - temp;
- }// x
- }// y
+ for( int x=0; x < width; ++x, ++pic_curr, ++diff_curr, ref_curr+=2 )
+ {
+ CalcValueType temp = ( CalcValueType( ref_curr[0] ) +
+ CalcValueType( ref_curr[1] ) +
+ 1
+ ) >> 1;
+ *diff_curr = ((*pic_curr)<<1) - temp;
+ }// x
+ }// y
#endif
- }
- else
- {
-#if 1
- __m64 m_two = _mm_set_pi32(2, 2);
- __m64 m_one = _mm_set_pi16(1, 1, 1, 1);
- // processing four pic_data values at a time
- for(int y = 0; y < height; y++, pic_curr += pic_next, ref_curr += ref_next)
+ }
+ else
{
- for(int x = 0; x < stopX; x += 4, pic_curr += 4, diff_curr += 4, ref_curr += 8)
- {
- // Load ref
- // m1 = words 0 1 2 3 of line 0 ref_curr
- __m64 m1 = *(__m64 *)ref_curr;
- // m1 = words 0 1 2 3 of line 1 of ref_curr
- __m64 m2 = *(__m64 *)(ref_curr + ref_stride);
- // (ref_curr[0] + ref_curr[1] +
- // ref_curr[ref_stride] + ref_curr[ref_stride+1] + 2) >>2
- m1 = _mm_add_pi16(m1, m2);
- m1 = _mm_madd_pi16(m1, m_one);
- m1 = _mm_add_pi32(m1, m_two);
- m1 = _mm_srai_pi32(m1, 2);
-
- // m2 = words 4 5 6 7 of line 0 ref_curr
- __m64 m3 = *(__m64 *)(ref_curr + 4);
- // m1 = words 4 5 6 7 of line 1 of ref_curr
- m2 = *(__m64 *)(ref_curr + 4 + ref_stride);
- // (ref_curr[0] + ref_curr[1] +
- // ref_curr[ref_stride] + ref_curr[ref_stride+1] + 2) >>2
- m3 = _mm_add_pi16(m3, m2);
- m3 = _mm_madd_pi16(m3, m_one);
- m3 = _mm_add_pi32(m3, m_two);
- m3 = _mm_srai_pi32(m3, 2);
-
- m1 = _mm_packs_pi32(m1, m3);
-
- // load first four values pic_data and <<1
- m2 = _mm_slli_pi16(*(__m64 *)pic_curr, 1);
-
- // pic<<1 - ref
- *(__m64 *)diff_curr = _mm_sub_pi16(m2, m1);
- }
- // mopup;
- for(int x = stopX; x < width; ++x, ++pic_curr, ++diff_curr, ref_curr += 2)
+#if 1
+ __m64 m_two = _mm_set_pi32(2, 2);
+ __m64 m_one = _mm_set_pi16(1, 1, 1, 1);
+ // processing four pic_data values at a time
+ for( int y=0; y < height; y++, pic_curr+=pic_next, ref_curr+=ref_next )
{
- CalcValueType temp = (ref_curr[0] + ref_curr[1] +
- ref_curr[ref_stride] + ref_curr[ref_stride+1] + 2) >> 2;
- *diff_curr = ((*pic_curr) << 1) - temp;
+ for( int x=0; x < stopX; x+=4, pic_curr+=4, diff_curr+=4, ref_curr+=8 )
+ {
+ // Load ref
+ // m1 = words 0 1 2 3 of line 0 ref_curr
+ __m64 m1 = *(__m64 *)ref_curr;
+ // m1 = words 0 1 2 3 of line 1 of ref_curr
+ __m64 m2 = *(__m64 *)(ref_curr+ref_stride);
+ // (ref_curr[0] + ref_curr[1] +
+ // ref_curr[ref_stride] + ref_curr[ref_stride+1] + 2) >>2
+ m1 = _mm_add_pi16 (m1, m2);
+ m1 = _mm_madd_pi16 (m1, m_one);
+ m1 = _mm_add_pi32 (m1, m_two);
+ m1 = _mm_srai_pi32 (m1, 2);
+
+ // m2 = words 4 5 6 7 of line 0 ref_curr
+ __m64 m3 = *(__m64 *)(ref_curr+4);
+ // m1 = words 4 5 6 7 of line 1 of ref_curr
+ m2 = *(__m64 *)(ref_curr+4+ref_stride);
+ // (ref_curr[0] + ref_curr[1] +
+ // ref_curr[ref_stride] + ref_curr[ref_stride+1] + 2) >>2
+ m3 = _mm_add_pi16 (m3, m2);
+ m3 = _mm_madd_pi16 (m3, m_one);
+ m3 = _mm_add_pi32 (m3, m_two);
+ m3 = _mm_srai_pi32 (m3, 2);
+
+ m1 = _mm_packs_pi32 (m1, m3);
+
+ // load first four values pic_data and <<1
+ m2 = _mm_slli_pi16 (*(__m64 *)pic_curr, 1);
+
+ // pic<<1 - ref
+ *(__m64 *)diff_curr = _mm_sub_pi16 (m2, m1);
+ }
+ // mopup;
+ for (int x = stopX; x < width; ++x, ++pic_curr,++diff_curr, ref_curr+=2)
+ {
+ CalcValueType temp = (ref_curr[0] + ref_curr[1] +
+ ref_curr[ref_stride] + ref_curr[ref_stride+1]+2)>>2;
+ *diff_curr = ((*pic_curr)<<1) - temp;
+ }
}
- }
#else
- //std::cerr << "Inmmx routine rmdr.y == 0" << std::endl;
- CalcValueType sum(0);
- for(int y = 0; y < height; ++y, pic_curr += pic_next, ref_curr += ref_next)
- {
- for(int x = 0; x < width; ++x, ++pic_curr, ++diff_curr, ref_curr += 2)
+ //std::cerr << "Inmmx routine rmdr.y == 0" << std::endl;
+ CalcValueType sum(0);
+ for( int y=0; y < height; ++y, pic_curr+=pic_next, ref_curr+=ref_next )
{
- CalcValueType temp = (CalcValueType(ref_curr[0]) +
- CalcValueType(ref_curr[1]) +
- CalcValueType(ref_curr[ref_stride]) +
- CalcValueType(ref_curr[ref_stride+1]) +
- 2
- ) >> 2;
- *diff_curr = ((*pic_curr) << 1) - temp;
- }// x
-
- }// y
+ for( int x=0; x < width; ++x, ++pic_curr, ++diff_curr, ref_curr+=2 )
+ {
+ CalcValueType temp = ( CalcValueType( ref_curr[0] ) +
+ CalcValueType( ref_curr[1] ) +
+ CalcValueType( ref_curr[ref_stride] ) +
+ CalcValueType( ref_curr[ref_stride+1] ) +
+ 2
+ ) >> 2;
+ *diff_curr = ((*pic_curr)<<1) - temp;
+ }// x
+
+ }// y
#endif
- }
+ }
_mm_empty();
return;
-}
+ }
-/*
-* NOTE: we are not doing any bounds checks here. This function must
-* be invoked only when the reference images start and stop fall
-* withing bounds
-*/
-CalcValueType simple_biblock_diff_up_mmx_4(
- const TwoDArray<ValueType>& diff_data, const PicArray& ref_data,
- const ImageCoords& ref_start, const ImageCoords& ref_stop,
- const MVector& rmdr)
-{
- ValueType *diff_curr = &diff_data[0][0];
- ValueType *ref_curr = &ref_data[ref_start.y][ref_start.x];
+ /*
+ * NOTE: we are not doing any bounds checks here. This function must
+ * be invoked only when the reference images start and stop fall
+ * withing bounds
+ */
+ CalcValueType simple_biblock_diff_up_mmx_4(
+ const TwoDArray<ValueType>& diff_data, const PicArray& ref_data,
+ const ImageCoords& ref_start, const ImageCoords& ref_stop,
+ const MVector& rmdr)
+ {
+ ValueType *diff_curr = &diff_data[0][0];
+ ValueType *ref_curr = &ref_data[ref_start.y][ref_start.x];
- const int width = diff_data.LengthX();
- int height = diff_data.LengthY();
- const int ref_stride = ref_data.LengthX();
+ const int width = diff_data.LengthX();
+ int height = diff_data.LengthY();
+ const int ref_stride = ref_data.LengthX();
- // go down 2 rows and back up
- const int ref_next = ref_data.LengthX() * 2 - width * 2;
+ // go down 2 rows and back up
+ const int ref_next = ref_data.LengthX()*2 - width*2;
- REPORTM(ref_start.x >= 0 && ref_stop.x < ref_data.LengthX() &&
- ref_start.y >= 0 && ref_stop.y < ref_data.LengthY(),
- "Reference image coordinates withing bounds");
+ REPORTM (ref_start.x>=0 && ref_stop.x < ref_data.LengthX() &&
+ ref_start.y>=0 && ref_stop.y < ref_data.LengthY(),
+ "Reference image coordinates withing bounds");
- CalcValueType mop_sum(0);
- int stopX = (width >> 2) << 2;
- __m64 m_sum = _mm_set_pi16(0, 0, 0, 0);
- u_mmx_val u_sum;
- if(rmdr.x == 0 && rmdr.y == 0)
- {
- //std::cerr << "Inmmx routine rmdr.x = rmdr.y = 0" << std::endl;
-#if 1
- for(int y = 0; y < height; y++, ref_curr += ref_next)
+ CalcValueType mop_sum(0);
+ int stopX = (width>>2)<<2;
+ __m64 m_sum = _mm_set_pi16(0, 0, 0, 0);
+ u_mmx_val u_sum;
+ if (rmdr.x == 0 && rmdr.y == 0 )
{
- for(int x = 0; x < stopX; x += 4, diff_curr += 4, ref_curr += 8)
- {
- u_mmx_val diff = *(u_mmx_val *)diff_curr;
- __m64 ref = _mm_unpacklo_pi16(*(__m64 *)ref_curr, *(__m64 *)(ref_curr + 4));
- __m64 ref2 = _mm_unpackhi_pi16(*(__m64 *)ref_curr, *(__m64 *)(ref_curr + 4));
- ref = _mm_unpacklo_pi16(ref, ref2);
- // diff - ref
- diff.m = _mm_sub_pi16(diff.m, ref);
- // (diff - ref)>>1
- diff.m = _mm_srai_pi16(diff.m, 1);
- // abs (diff - ref)
- ref = _mm_srai_pi16(diff.m, 15);
- diff.m = _mm_xor_si64(diff.m, ref);
- diff.m = _mm_sub_pi16(diff.m, ref);
- // sum += abs(ref -pic)
- ref = _mm_xor_si64(ref, ref);
- ref = _mm_unpackhi_pi16(diff.m, ref);
- diff.m = _mm_unpacklo_pi16(diff.m, diff.m);
- diff.m = _mm_srai_pi32(diff.m, 16);
- diff.m = _mm_add_pi32(diff.m, ref);
- m_sum = _mm_add_pi32(m_sum, diff.m);
- }
- // mopup;
- for(int x = stopX; x < width; ++x, ++diff_curr, ref_curr += 2)
+ //std::cerr << "Inmmx routine rmdr.x = rmdr.y = 0" << std::endl;
+#if 1
+ for( int y=0; y < height; y++, ref_curr+=ref_next )
{
- mop_sum += std::abs((*diff_curr - *ref_curr) >> 1);
+ for( int x=0; x < stopX; x+=4, diff_curr+=4, ref_curr+=8 )
+ {
+ u_mmx_val diff = *(u_mmx_val *)diff_curr;
+ __m64 ref = _mm_unpacklo_pi16 (*(__m64 *)ref_curr, *(__m64 *)(ref_curr+4));
+ __m64 ref2 = _mm_unpackhi_pi16 (*(__m64 *)ref_curr, *(__m64 *)(ref_curr+4));
+ ref = _mm_unpacklo_pi16 ( ref, ref2);
+ // diff - ref
+ diff.m = _mm_sub_pi16 (diff.m, ref);
+ // (diff - ref)>>1
+ diff.m = _mm_srai_pi16 (diff.m, 1);
+ // abs (diff - ref)
+ ref = _mm_srai_pi16(diff.m, 15);
+ diff.m = _mm_xor_si64(diff.m, ref);
+ diff.m = _mm_sub_pi16 (diff.m, ref);
+ // sum += abs(ref -pic)
+ ref = _mm_xor_si64(ref, ref);
+ ref = _mm_unpackhi_pi16(diff.m, ref);
+ diff.m = _mm_unpacklo_pi16(diff.m, diff.m);
+ diff.m = _mm_srai_pi32 (diff.m, 16);
+ diff.m = _mm_add_pi32 (diff.m, ref);
+ m_sum = _mm_add_pi32 (m_sum, diff.m);
+ }
+ // mopup;
+ for (int x = stopX; x < width; ++x, ++diff_curr,ref_curr+=2)
+ {
+ mop_sum += std::abs ((*diff_curr - *ref_curr)>>1);
+ }
}
- }
- u_sum.m = m_sum;
- _mm_empty();
- return u_sum.i[0] + u_sum.i[1] + mop_sum;
+ u_sum.m = m_sum;
+ _mm_empty();
+ return u_sum.i[0] + u_sum.i[1] + mop_sum;
#else
- CalcValueType sum(0);
- for(int y = 0; y < height; ++y, ref_curr += ref_next)
- {
- for(int x = 0; x < width; ++x, ++diff_curr, ref_curr += 2)
+ CalcValueType sum(0);
+ for( int y=0; y < height; ++y, ref_curr+=ref_next )
{
- sum += std::abs((*diff_curr - *ref_curr) >> 1);
- }// x
-
- }// y
- return sum;
+ for( int x=0; x < width; ++x, ++diff_curr, ref_curr+=2 )
+ {
+ sum += std::abs( (*diff_curr - *ref_curr)>>1 );
+ }// x
+
+ }// y
+ return sum;
#endif
- }
- else if(rmdr.y == 0)
- {
-#if 1
- __m64 m_one = _mm_set_pi16(1, 1, 1, 1);
- for(int y = 0; y < height; y++, ref_curr += ref_next)
+ }
+ else if( rmdr.y == 0 )
{
- for(int x = 0; x < stopX; x += 4, diff_curr += 4, ref_curr += 8)
- {
- // Load ref
- __m64 m1 = _mm_unpacklo_pi16(((u_mmx_val *)ref_curr)->m, ((u_mmx_val *)(ref_curr + 4))->m);
- __m64 m2 = _mm_unpackhi_pi16(*(__m64 *)ref_curr, *(__m64 *)(ref_curr + 4));
- // m3 = words 0 2 4 6 of ref_curr
- __m64 m3 = _mm_unpacklo_pi16(m1, m2);
- // m2 = words 1 3 5 7 of ref_curr
- m2 = _mm_unpackhi_pi16(m1, m2);
- // (ref_curr[0] + ref_curr[1] + 1)>>1
- m3 = _mm_add_pi16(m3, m2);
- m3 = _mm_add_pi16(m3, m_one);
- m3 = _mm_srai_pi16(m3, 1);
- // diff - pic
- m1 = _mm_sub_pi16(*(__m64 *)diff_curr, m3);
- // (diff - pic)>>1
- m1 = _mm_srai_pi16(m1, 1);
- // abs (diff-ref)>>1
- m3 = _mm_srai_pi16(m1, 15);
- m1 = _mm_xor_si64(m1, m3);
- m1 = _mm_sub_pi16(m1, m3);
- // sum += abs(diff-ref)>>1
- m2 = _mm_xor_si64(m2, m2);
- m2 = _mm_unpackhi_pi16(m1, m2);
- m1 = _mm_unpacklo_pi16(m1, m1);
- m1 = _mm_srai_pi32(m1, 16);
- m1 = _mm_add_pi32(m1, m2);
- m_sum = _mm_add_pi32(m_sum, m1);
- }
- // mopup;
- for(int x = stopX; x < width; ++x, ++diff_curr, ref_curr += 2)
+#if 1
+ __m64 m_one = _mm_set_pi16(1, 1, 1, 1);
+ for( int y=0; y < height; y++, ref_curr+=ref_next )
{
- CalcValueType temp = (ref_curr[0] + ref_curr[1] + 1) >> 1;
- mop_sum += std::abs((*diff_curr - temp) >> 1);
+ for( int x=0; x < stopX; x+=4, diff_curr+=4, ref_curr+=8 )
+ {
+ // Load ref
+ __m64 m1 = _mm_unpacklo_pi16 (((u_mmx_val *)ref_curr)->m, ((u_mmx_val *)(ref_curr+4))->m);
+ __m64 m2 = _mm_unpackhi_pi16 (*(__m64 *)ref_curr, *(__m64 *)(ref_curr+4));
+ // m3 = words 0 2 4 6 of ref_curr
+ __m64 m3 = _mm_unpacklo_pi16 ( m1, m2);
+ // m2 = words 1 3 5 7 of ref_curr
+ m2 = _mm_unpackhi_pi16 ( m1, m2);
+ // (ref_curr[0] + ref_curr[1] + 1)>>1
+ m3 = _mm_add_pi16 (m3, m2);
+ m3 = _mm_add_pi16 (m3, m_one);
+ m3 = _mm_srai_pi16 (m3, 1);
+ // diff - pic
+ m1 = _mm_sub_pi16 (*(__m64 *)diff_curr, m3);
+ // (diff - pic)>>1
+ m1 = _mm_srai_pi16 (m1, 1);
+ // abs (diff-ref)>>1
+ m3 = _mm_srai_pi16(m1, 15);
+ m1 = _mm_xor_si64(m1, m3);
+ m1 = _mm_sub_pi16 (m1, m3);
+ // sum += abs(diff-ref)>>1
+ m2 = _mm_xor_si64(m2, m2);
+ m2 = _mm_unpackhi_pi16(m1, m2);
+ m1 = _mm_unpacklo_pi16(m1, m1);
+ m1 = _mm_srai_pi32 (m1, 16);
+ m1 = _mm_add_pi32 (m1, m2);
+ m_sum = _mm_add_pi32 (m_sum, m1);
+ }
+ // mopup;
+ for (int x = stopX; x < width; ++x, ++diff_curr,ref_curr+=2)
+ {
+ CalcValueType temp = (ref_curr[0] + ref_curr[1]+1)>>1;
+ mop_sum += std::abs ((*diff_curr - temp)>>1);
+ }
}
- }
- u_sum.m = m_sum;
- _mm_empty();
- return (u_sum.i[0] + u_sum.i[1] + mop_sum);
+ u_sum.m = m_sum;
+ _mm_empty();
+ return (u_sum.i[0] + u_sum.i[1] + mop_sum);
#else
- //std::cerr << "Inmmx routine rmdr.y == 0" << std::endl;
- CalcValueType sum(0);
- for(int y = 0; y < height; ++y, ref_curr += ref_next)
- {
- for(int x = 0; x < width; ++x, ++diff_curr, ref_curr += 2)
+ //std::cerr << "Inmmx routine rmdr.y == 0" << std::endl;
+ CalcValueType sum(0);
+ for( int y=0; y < height; ++y, ref_curr+=ref_next )
{
- CalcValueType temp = (CalcValueType(ref_curr[0]) +
- CalcValueType(ref_curr[1]) +
- 1
- ) >> 1;
- sum += std::abs((*diff_curr - temp) >> 1);
- }// x
- }// y
- return sum;
+ for( int x=0; x < width; ++x, ++diff_curr, ref_curr+=2 )
+ {
+ CalcValueType temp = ( CalcValueType( ref_curr[0] ) +
+ CalcValueType( ref_curr[1] ) +
+ 1
+ ) >> 1;
+ sum += std::abs( (*diff_curr - temp)>>1 );
+ }// x
+ }// y
+ return sum;
#endif
- }
- else if(rmdr.x == 0)
- {
-#if 1
- __m64 m_one = _mm_set_pi16(1, 1, 1, 1);
- for(int y = 0; y < height; y++, ref_curr += ref_next)
+ }
+ else if( rmdr.x == 0 )
{
- for(int x = 0; x < stopX; x += 4, diff_curr += 4, ref_curr += 8)
- {
- // Load ref
- __m64 m1 = _mm_unpacklo_pi16(*(__m64 *)ref_curr, *(__m64 *)(ref_curr + 4));
- __m64 m2 = _mm_unpackhi_pi16(*(__m64 *)ref_curr, *(__m64 *)(ref_curr + 4));
- // m1 = words 0 2 4 6 of ref_curr
- m1 = _mm_unpacklo_pi16(m1, m2);
- // m2 = words 0 2 4 6 of ref_curr+ref_stride
- m2 = _mm_unpacklo_pi16(*(__m64 *)(ref_curr + ref_stride), *(__m64 *)(ref_curr + ref_stride + 4));
- __m64 m3 = _mm_unpackhi_pi16(*(__m64 *)(ref_curr + ref_stride), *(__m64 *)(ref_curr + ref_stride + 4));
- m2 = _mm_unpacklo_pi16(m2, m3);
-
- // (ref_curr[0] + ref_curr[ref_stride] + 1)>>1
- m1 = _mm_add_pi16(m1, m2);
- m1 = _mm_add_pi16(m1, m_one);
- m1 = _mm_srai_pi16(m1, 1);
- // diff - ref
- m1 = _mm_sub_pi16(*(__m64 *)diff_curr, m1);
- // (diff - ref)>>1
- m1 = _mm_srai_pi16(m1, 1);
- // abs ((diff - pic)>>1)
- m3 = _mm_srai_pi16(m1, 15);
- m1 = _mm_xor_si64(m1, m3);
- m1 = _mm_sub_pi16(m1, m3);
- // sum += abs(ref -pic)
- m2 = _mm_xor_si64(m2, m2);
- m2 = _mm_unpackhi_pi16(m1, m2);
- m1 = _mm_unpacklo_pi16(m1, m1);
- m1 = _mm_srai_pi32(m1, 16);
- m1 = _mm_add_pi32(m1, m2);
- m_sum = _mm_add_pi32(m_sum, m1);
- }
- // mopup;
- for(int x = stopX; x < width; ++x, ++diff_curr, ref_curr += 2)
+#if 1
+ __m64 m_one = _mm_set_pi16(1, 1, 1, 1);
+ for( int y=0; y < height; y++, ref_curr+=ref_next )
{
- CalcValueType temp = (ref_curr[0] + ref_curr[ref_stride] + 1) >> 1;
- mop_sum += std::abs((*diff_curr - temp) >> 1);
+ for( int x=0; x < stopX; x+=4, diff_curr+=4, ref_curr+=8 )
+ {
+ // Load ref
+ __m64 m1 = _mm_unpacklo_pi16 (*(__m64 *)ref_curr, *(__m64 *)(ref_curr+4));
+ __m64 m2 = _mm_unpackhi_pi16 (*(__m64 *)ref_curr, *(__m64 *)(ref_curr+4));
+ // m1 = words 0 2 4 6 of ref_curr
+ m1 = _mm_unpacklo_pi16 ( m1, m2);
+ // m2 = words 0 2 4 6 of ref_curr+ref_stride
+ m2 = _mm_unpacklo_pi16 (*(__m64 *)(ref_curr+ref_stride), *(__m64 *)(ref_curr+ref_stride+4));
+ __m64 m3 = _mm_unpackhi_pi16 (*(__m64 *)(ref_curr+ref_stride), *(__m64 *)(ref_curr+ref_stride+4));
+ m2 = _mm_unpacklo_pi16 (m2, m3);
+
+ // (ref_curr[0] + ref_curr[ref_stride] + 1)>>1
+ m1 = _mm_add_pi16 (m1, m2);
+ m1 = _mm_add_pi16 (m1, m_one);
+ m1 = _mm_srai_pi16 (m1, 1);
+ // diff - ref
+ m1 = _mm_sub_pi16 (*(__m64 *)diff_curr, m1);
+ // (diff - ref)>>1
+ m1 = _mm_srai_pi16 (m1, 1);
+ // abs ((diff - pic)>>1)
+ m3 = _mm_srai_pi16(m1, 15);
+ m1 = _mm_xor_si64(m1, m3);
+ m1 = _mm_sub_pi16 (m1, m3);
+ // sum += abs(ref -pic)
+ m2 = _mm_xor_si64(m2, m2);
+ m2 = _mm_unpackhi_pi16(m1, m2);
+ m1 = _mm_unpacklo_pi16(m1, m1);
+ m1 = _mm_srai_pi32 (m1, 16);
+ m1 = _mm_add_pi32 (m1, m2);
+ m_sum = _mm_add_pi32 (m_sum, m1);
+ }
+ // mopup;
+ for (int x = stopX; x < width; ++x, ++diff_curr,ref_curr+=2)
+ {
+ CalcValueType temp = (ref_curr[0] + ref_curr[ref_stride]+1)>>1;
+ mop_sum += std::abs ( (*diff_curr - temp)>>1 );
+ }
}
- }
- u_sum.m = m_sum;
- _mm_empty();
- return (u_sum.i[0] + u_sum.i[1] + mop_sum);
+ u_sum.m = m_sum;
+ _mm_empty();
+ return (u_sum.i[0] + u_sum.i[1] + mop_sum);
#else
- CalcValueType sum(0);
- for(int y = 0; y < height; ++y, ref_curr += ref_next)
- {
- for(int x = 0; x < width; ++x, ++diff_curr, ref_curr += 2)
+ CalcValueType sum(0);
+ for( int y=0; y < height; ++y, ref_curr+=ref_next )
{
- CalcValueType temp = (ref_curr[0] + ref_curr[ref_stride] + 1) >> 1;
- sum += std::abs((*diff_curr - temp) >> 1);
- }// x
- }// y
- return sum;
+ for( int x=0; x < width; ++x, ++diff_curr, ref_curr+=2 )
+ {
+ CalcValueType temp = (ref_curr[0] + ref_curr[ref_stride]+1)>>1;
+ sum += std::abs ( (*diff_curr - temp)>>1 );
+ }// x
+ }// y
+ return sum;
#endif
- }
- else
- {
-#if 1
- __m64 m_two = _mm_set_pi32(2, 2);
- __m64 m_one = _mm_set_pi16(1, 1, 1, 1);
- // processing four pic_data values at a time
- for(int y = 0; y < height; y++, ref_curr += ref_next)
+ }
+ else
{
- for(int x = 0; x < stopX; x += 4, diff_curr += 4, ref_curr += 8)
- {
- // Load ref
- // m1 = words 0 1 2 3 of line 0 ref_curr
- __m64 m1 = *(__m64 *)ref_curr;
- // m1 = words 0 1 2 3 of line 1 of ref_curr
- __m64 m2 = *(__m64 *)(ref_curr + ref_stride);
- // (ref_curr[0] + ref_curr[1] +
- // ref_curr[ref_stride] + ref_curr[ref_stride+1] + 2) >>2
- m1 = _mm_add_pi16(m1, m2);
- m1 = _mm_madd_pi16(m1, m_one);
- m1 = _mm_add_pi32(m1, m_two);
- m1 = _mm_srai_pi32(m1, 2);
-
- // m2 = words 4 5 6 7 of line 0 ref_curr
- __m64 m3 = *(__m64 *)(ref_curr + 4);
- // m1 = words 4 5 6 7 of line 1 of ref_curr
- m2 = *(__m64 *)(ref_curr + 4 + ref_stride);
- // (ref_curr[0] + ref_curr[1] +
- // ref_curr[ref_stride] + ref_curr[ref_stride+1] + 2) >>2
- m3 = _mm_add_pi16(m3, m2);
- m3 = _mm_madd_pi16(m3, m_one);
- m3 = _mm_add_pi32(m3, m_two);
- m3 = _mm_srai_pi32(m3, 2);
- m1 = _mm_packs_pi32(m1, m3);
-
- // load first four values pic_data
- m2 = *(__m64 *)diff_curr;
-
- // diff - ref
- m1 = _mm_sub_pi16(m2, m1);
- // (diff - ref)>>1
- m1 = _mm_srai_pi16(m1, 1);
- // abs (diff - ref)>>1
- m2 = _mm_srai_pi16(m1, 15);
- m1 = _mm_xor_si64(m1, m2);
- m1 = _mm_sub_pi16(m1, m2);
- // sum += abs(ref -pic)>>1
- m1 = _mm_madd_pi16(m1, m_one);
- m_sum = _mm_add_pi32(m_sum, m1);
- }
- // mopup;
- for(int x = stopX; x < width; ++x, ++diff_curr, ref_curr += 2)
+#if 1
+ __m64 m_two = _mm_set_pi32(2, 2);
+ __m64 m_one = _mm_set_pi16(1, 1, 1, 1);
+ // processing four pic_data values at a time
+ for( int y=0; y < height; y++, ref_curr+=ref_next )
{
- CalcValueType temp = (ref_curr[0] + ref_curr[1] +
- ref_curr[ref_stride] + ref_curr[ref_stride+1] + 2) >> 2;
- mop_sum += std::abs((*diff_curr - temp) >> 1);
+ for( int x=0; x < stopX; x+=4, diff_curr+=4, ref_curr+=8 )
+ {
+ // Load ref
+ // m1 = words 0 1 2 3 of line 0 ref_curr
+ __m64 m1 = *(__m64 *)ref_curr;
+ // m1 = words 0 1 2 3 of line 1 of ref_curr
+ __m64 m2 = *(__m64 *)(ref_curr+ref_stride);
+ // (ref_curr[0] + ref_curr[1] +
+ // ref_curr[ref_stride] + ref_curr[ref_stride+1] + 2) >>2
+ m1 = _mm_add_pi16 (m1, m2);
+ m1 = _mm_madd_pi16 (m1, m_one);
+ m1 = _mm_add_pi32 (m1, m_two);
+ m1 = _mm_srai_pi32 (m1, 2);
+
+ // m2 = words 4 5 6 7 of line 0 ref_curr
+ __m64 m3 = *(__m64 *)(ref_curr+4);
+ // m1 = words 4 5 6 7 of line 1 of ref_curr
+ m2 = *(__m64 *)(ref_curr+4+ref_stride);
+ // (ref_curr[0] + ref_curr[1] +
+ // ref_curr[ref_stride] + ref_curr[ref_stride+1] + 2) >>2
+ m3 = _mm_add_pi16 (m3, m2);
+ m3 = _mm_madd_pi16 (m3, m_one);
+ m3 = _mm_add_pi32 (m3, m_two);
+ m3 = _mm_srai_pi32 (m3, 2);
+ m1 = _mm_packs_pi32 (m1, m3);
+
+ // load first four values pic_data
+ m2 = *(__m64 *)diff_curr;
+
+ // diff - ref
+ m1 = _mm_sub_pi16 (m2, m1);
+ // (diff - ref)>>1
+ m1 = _mm_srai_pi16 (m1, 1);
+ // abs (diff - ref)>>1
+ m2 = _mm_srai_pi16(m1, 15);
+ m1 = _mm_xor_si64(m1, m2);
+ m1 = _mm_sub_pi16(m1, m2);
+ // sum += abs(ref -pic)>>1
+ m1 = _mm_madd_pi16(m1, m_one);
+ m_sum = _mm_add_pi32 (m_sum, m1);
+ }
+ // mopup;
+ for (int x = stopX; x < width; ++x, ++diff_curr,ref_curr+=2)
+ {
+ CalcValueType temp = (ref_curr[0] + ref_curr[1] +
+ ref_curr[ref_stride] + ref_curr[ref_stride+1]+2)>>2;
+ mop_sum += std::abs ( (*diff_curr - temp)>>1 );
+ }
}
- }
- u_sum.m = m_sum;
- _mm_empty();
- return (u_sum.i[0] + u_sum.i[1] + mop_sum);
+ u_sum.m = m_sum;
+ _mm_empty();
+ return (u_sum.i[0] + u_sum.i[1] + mop_sum);
#else
- CalcValueType sum(0);
- for(int y = 0; y < height; ++y, ref_curr += ref_next)
- {
- for(int x = 0; x < width; ++x, ++diff_curr, ref_curr += 2)
+ CalcValueType sum(0);
+ for( int y=0; y < height; ++y, ref_curr+=ref_next )
{
- CalcValueType temp = (CalcValueType(ref_curr[0]) +
- CalcValueType(ref_curr[1]) +
- CalcValueType(ref_curr[ref_stride]) +
- CalcValueType(ref_curr[ref_stride+1]) +
- 2
- ) >> 2;
- sum += std::abs((*diff_curr - temp) >> 1);
- }// x
- }// y
- return sum;
+ for( int x=0; x < width; ++x, ++diff_curr, ref_curr+=2 )
+ {
+ CalcValueType temp = ( CalcValueType( ref_curr[0] ) +
+ CalcValueType( ref_curr[1] ) +
+ CalcValueType( ref_curr[ref_stride] ) +
+ CalcValueType( ref_curr[ref_stride+1] ) +
+ 2
+ ) >> 2;
+ sum += std::abs( (*diff_curr - temp)>>1 );
+ }// x
+ }// y
+ return sum;
#endif
- }
+ }
return 0;
-}
-
-inline void check_active_columns(
- int x, int xmax, ValueType act_cols1[4], ValueType *row1)
-{
- // check if we need any clipping
- if(x >= 0 && (x + 3) < xmax)
- {
- // special case, nothing to do
- memcpy(act_cols1, &row1[x], 4 * sizeof(ValueType));
}
- else if(x < 0)
+
+ inline void check_active_columns(
+ int x, int xmax, ValueType act_cols1[4],ValueType *row1)
{
- act_cols1[0] = row1[0];
- //act_cols1[1] = (x + 1) < 0 ? row1[0] : row1[x+1];
- //act_cols1[2] = (x + 2) < 0 ? row1[0] : row1[x+2];
- //act_cols1[3] = (x + 3) < 0 ? row1[0] : row1[x+3];
- for(int i = 1; i < 4; ++i)
+ // check if we need any clipping
+ if (x >= 0 && (x+3) < xmax) {
+ // special case, nothing to do
+ memcpy(act_cols1, &row1[x], 4 * sizeof(ValueType));
+ }
+ else if (x < 0)
{
- act_cols1[i] = (x + i) < 0 ? row1[0] : row1[x+i];
+ act_cols1[0] = row1[0];
+ //act_cols1[1] = (x + 1) < 0 ? row1[0] : row1[x+1];
+ //act_cols1[2] = (x + 2) < 0 ? row1[0] : row1[x+2];
+ //act_cols1[3] = (x + 3) < 0 ? row1[0] : row1[x+3];
+ for (int i = 1; i < 4; ++i)
+ {
+ act_cols1[i] = (x + i) < 0 ? row1[0] : row1[x+i];
+ }
}
- }
- else
- {
- for(int i = 0; i < 3; ++i)
+ else
{
- act_cols1[i] = (x + i) < xmax ? row1[x+i] : row1[xmax-1];
+ for (int i = 0; i < 3; ++i)
+ {
+ act_cols1[i] = (x + i) < xmax ? row1[x+i] : row1[xmax-1];
+ }
+ act_cols1[3] = row1[xmax-1];
}
- act_cols1[3] = row1[xmax-1];
}
-}
-
-CalcValueType bchk_simple_block_diff_mmx_4(
- const BlockDiffParams& dparams, const MVector& mv,
- const PicArray& pic_data, const PicArray& ref_data,
- CalcValueType i_best_sum)
-{
- u_mmx_val u_sum;
- u_mmx_val u_ref;
- u_sum.i[0] = u_sum.i[1] = 0;
-
- ValueType *src = &(pic_data[dparams.Yp()][dparams.Xp()]);
- ImageCoords ref_start(dparams.Xp() + mv.x, dparams.Yp() + mv.y);
-
- int height = dparams.Yl();
- int width = dparams.Xl();
- int stopX = (width >> 2) << 2;
- int pic_next = (pic_data.LengthX() - width);
- CalcValueType mop_sum = 0;
- for(int j = 0; j < height; j++)
+
+ CalcValueType bchk_simple_block_diff_mmx_4 (
+ const BlockDiffParams& dparams, const MVector& mv,
+ const PicArray& pic_data, const PicArray& ref_data,
+ CalcValueType i_best_sum)
{
- for(int i = 0; i < stopX; i += 4)
- {
- check_active_columns(ref_start.x + i, ref_data.LengthX(), u_ref.h, ref_data[BChk(ref_start.y+j, ref_data.LengthY())]);
- // pic - ref
- __m64 pic = _mm_sub_pi16(*(__m64 *)src, u_ref.m);
- // abs (pic - ref)
- u_ref.m = _mm_srai_pi16(pic, 15);
- pic = _mm_xor_si64(pic, u_ref.m);
- pic = _mm_sub_pi16(pic, u_ref.m);
- // sum += abs(pic -ref)
- u_ref.m = _mm_xor_si64(u_ref.m, u_ref.m);
- u_ref.m = _mm_unpackhi_pi16(pic, u_ref.m);
- pic = _mm_unpacklo_pi16(pic, pic);
- pic = _mm_srai_pi32(pic, 16);
- pic = _mm_add_pi32(pic, u_ref.m);
- u_sum.m = _mm_add_pi32(u_sum.m, pic);
- src += 4;
- }
- for(int i = stopX; i < width; i++)
+ u_mmx_val u_sum;
+ u_mmx_val u_ref;
+ u_sum.i[0] = u_sum.i[1]= 0;
+
+ ValueType *src = &(pic_data[dparams.Yp()][dparams.Xp()]);
+ ImageCoords ref_start(dparams.Xp()+mv.x, dparams.Yp()+mv.y);
+
+ int height = dparams.Yl();
+ int width = dparams.Xl();
+ int stopX = (width>>2)<<2;
+ int pic_next = (pic_data.LengthX() - width);
+ CalcValueType mop_sum = 0;
+ for (int j = 0; j < height; j++)
{
- mop_sum += std::abs(*src -
- ref_data[BChk(j+ref_start.y , ref_data.LengthY())][BChk(i+ref_start.x , ref_data.LengthX())]);
- src++;
- }
- if((u_sum.i[0] + u_sum.i[1] + mop_sum) >= i_best_sum)
- {
- _mm_empty();
- return i_best_sum;
+ for (int i = 0; i < stopX; i+=4)
+ {
+ check_active_columns(ref_start.x+i, ref_data.LengthX(), u_ref.h, ref_data[BChk(ref_start.y+j, ref_data.LengthY())]);
+ // pic - ref
+ __m64 pic = _mm_sub_pi16 (*(__m64 *)src, u_ref.m);
+ // abs (pic - ref)
+ u_ref.m = _mm_srai_pi16(pic, 15);
+ pic = _mm_xor_si64(pic, u_ref.m);
+ pic = _mm_sub_pi16 (pic, u_ref.m);
+ // sum += abs(pic -ref)
+ u_ref.m = _mm_xor_si64(u_ref.m, u_ref.m);
+ u_ref.m = _mm_unpackhi_pi16(pic, u_ref.m);
+ pic = _mm_unpacklo_pi16(pic, pic);
+ pic = _mm_srai_pi32 (pic, 16);
+ pic = _mm_add_pi32 (pic, u_ref.m);
+ u_sum.m = _mm_add_pi32 (u_sum.m, pic);
+ src += 4;
+ }
+ for (int i = stopX; i < width; i++)
+ {
+ mop_sum += std::abs(*src -
+ ref_data[BChk(j+ref_start.y , ref_data.LengthY())][BChk(i+ref_start.x , ref_data.LengthX())]);
+ src++;
+ }
+ if ((u_sum.i[0] + u_sum.i[1] + mop_sum) >= i_best_sum)
+ {
+ _mm_empty();
+ return i_best_sum;
+ }
+ src += pic_next;
}
- src += pic_next;
- }
- _mm_empty();
+ _mm_empty();
- return u_sum.i[0] + u_sum.i[1] + mop_sum;
-}
+ return u_sum.i[0] + u_sum.i[1] + mop_sum;
+ }
}
#endif
diff --git a/src/filters/parser/DiracSplitter/libdirac/libdirac_motionest/me_utils_mmx.h b/src/filters/parser/DiracSplitter/libdirac/libdirac_motionest/me_utils_mmx.h
index 8d702dd6a..855fc4a75 100644
--- a/src/filters/parser/DiracSplitter/libdirac/libdirac_motionest/me_utils_mmx.h
+++ b/src/filters/parser/DiracSplitter/libdirac/libdirac_motionest/me_utils_mmx.h
@@ -48,33 +48,33 @@
namespace dirac
{
-CalcValueType simple_block_diff_mmx_4(const BlockDiffParams& dparams, const MVector& mv, const PicArray& pic_data, const PicArray& ref_data, CalcValueType i_best_sum);
-CalcValueType simple_intra_block_diff_mmx_4(const BlockDiffParams& dparams, const PicArray& pic_data, ValueType &dc_val);
+ CalcValueType simple_block_diff_mmx_4(const BlockDiffParams& dparams, const MVector& mv, const PicArray& pic_data, const PicArray& ref_data, CalcValueType i_best_sum);
+ CalcValueType simple_intra_block_diff_mmx_4 ( const BlockDiffParams& dparams, const PicArray& pic_data, ValueType &dc_val);
-CalcValueType bchk_simple_block_diff_mmx_4(
- const BlockDiffParams& dparams, const MVector& mv,
- const PicArray& pic_data, const PicArray& ref_data,
- CalcValueType i_best_sum);
+ CalcValueType bchk_simple_block_diff_mmx_4 (
+ const BlockDiffParams& dparams, const MVector& mv,
+ const PicArray& pic_data, const PicArray& ref_data,
+ CalcValueType i_best_sum);
-float simple_block_diff_up_mmx_4(
- const PicArray& pic_data, const PicArray& ref_data,
- const ImageCoords& start_pos, const ImageCoords& end_pos,
- const ImageCoords& ref_start, const ImageCoords& ref_stop,
- const MVector& rmdr, float cost_so_far,
- float best_cost_so_far);
+ float simple_block_diff_up_mmx_4(
+ const PicArray& pic_data, const PicArray& ref_data,
+ const ImageCoords& start_pos, const ImageCoords& end_pos,
+ const ImageCoords& ref_start, const ImageCoords& ref_stop,
+ const MVector& rmdr, float cost_so_far,
+ float best_cost_so_far);
-void simple_biblock_diff_pic_mmx_4(
- const PicArray& pic_data, const PicArray& ref_data,
- TwoDArray<ValueType>& diff,
- const ImageCoords& start_pos, const ImageCoords& end_pos,
- const ImageCoords& ref_start, const ImageCoords& ref_stop,
- const MVector& rmdr);
+ void simple_biblock_diff_pic_mmx_4(
+ const PicArray& pic_data, const PicArray& ref_data,
+ TwoDArray<ValueType>& diff,
+ const ImageCoords& start_pos, const ImageCoords& end_pos,
+ const ImageCoords& ref_start, const ImageCoords& ref_stop,
+ const MVector& rmdr);
-CalcValueType simple_biblock_diff_up_mmx_4(
- const TwoDArray<ValueType>& diff_data, const PicArray& ref_data,
- const ImageCoords& ref_start, const ImageCoords& ref_stop,
- const MVector& rmdr);
+ CalcValueType simple_biblock_diff_up_mmx_4(
+ const TwoDArray<ValueType>& diff_data, const PicArray& ref_data,
+ const ImageCoords& ref_start, const ImageCoords& ref_stop,
+ const MVector& rmdr);
}
#endif /* HAVE_MMX */
diff --git a/src/filters/parser/DiracSplitter/libdirac/libdirac_motionest/motion_estimate.cpp b/src/filters/parser/DiracSplitter/libdirac/libdirac_motionest/motion_estimate.cpp
index 48d7f9e10..bdde41891 100644
--- a/src/filters/parser/DiracSplitter/libdirac/libdirac_motionest/motion_estimate.cpp
+++ b/src/filters/parser/DiracSplitter/libdirac/libdirac_motionest/motion_estimate.cpp
@@ -46,44 +46,44 @@ using namespace dirac;
#include <cmath>
#include <vector>
-MotionEstimator::MotionEstimator(const EncoderParams& encp):
- m_encparams(encp)
+MotionEstimator::MotionEstimator( const EncoderParams& encp ):
+ m_encparams( encp )
{}
-void MotionEstimator::DoME(EncQueue& my_buffer, int pic_num)
+void MotionEstimator::DoME( EncQueue& my_buffer, int pic_num )
{
- MEData& me_data = my_buffer.GetPicture(pic_num).GetMEData();
+ MEData& me_data = my_buffer.GetPicture( pic_num ).GetMEData();
const PictureParams& pparams = my_buffer.GetPicture(pic_num).GetPparams();
- // Step 1.
- //Initial search gives vectors for each reference accurate to 1 pixel
+ // Step 1.
+ //Initial search gives vectors for each reference accurate to 1 pixel
- PixelMatcher pix_match(m_encparams);
- pix_match.DoSearch(my_buffer , pic_num);
+ PixelMatcher pix_match( m_encparams );
+ pix_match.DoSearch( my_buffer , pic_num );
float lambda;
// Get the references
const std::vector<int>& refs = my_buffer.GetPicture(pic_num).GetPparams().Refs();
const int num_refs = refs.size();
- if(pparams.IsBPicture())
+ if ( pparams.IsBPicture())
lambda = m_encparams.L2MELambda();
else
lambda = m_encparams.L1MELambda();
// Set up the lambda to be used
- me_data.SetLambdaMap(num_refs , lambda);
+ me_data.SetLambdaMap( num_refs , lambda );
MVPrecisionType orig_prec = m_encparams.GetPicPredParams().MVPrecision();
- // Step 2.
+ // Step 2.
// Pixel accurate vectors are then refined to sub-pixel accuracy
- if(orig_prec != MV_PRECISION_PIXEL)
+ if (orig_prec != MV_PRECISION_PIXEL)
{
- SubpelRefine pelrefine(m_encparams);
- pelrefine.DoSubpel(my_buffer , pic_num);
+ SubpelRefine pelrefine( m_encparams );
+ pelrefine.DoSubpel( my_buffer , pic_num );
}
else
{
@@ -91,17 +91,17 @@ void MotionEstimator::DoME(EncQueue& my_buffer, int pic_num)
// Mutiplying the motion vectors by 2 and setting MV precision to
// HALF_PIXEL to implement pixel accurate motion estimate
MvArray &mv_arr1 = me_data.Vectors(1);
- for(int j = 0; j < mv_arr1.LengthY(); ++j)
+ for (int j = 0; j < mv_arr1.LengthY(); ++j)
{
- for(int i = 0; i < mv_arr1.LengthX(); ++i)
+ for (int i = 0; i < mv_arr1.LengthX(); ++i)
mv_arr1[j][i] = mv_arr1[j][i] << 1;
}
- if(num_refs > 1)
+ if (num_refs > 1)
{
MvArray &mv_arr2 = me_data.Vectors(2);
- for(int j = 0; j < mv_arr2.LengthY(); ++j)
+ for (int j = 0; j < mv_arr2.LengthY(); ++j)
{
- for(int i = 0; i < mv_arr2.LengthX(); ++i)
+ for (int i = 0; i < mv_arr2.LengthX(); ++i)
mv_arr2[j][i] = mv_arr2[j][i] << 1;
}
}
@@ -109,31 +109,31 @@ void MotionEstimator::DoME(EncQueue& my_buffer, int pic_num)
}
// Step3.
- // We now have to decide how each superblock should be split
+ // We now have to decide how each superblock should be split
// and which references should be used, and so on.
- ModeDecider my_mode_dec(m_encparams);
- my_mode_dec.DoModeDecn(my_buffer , pic_num);
-
- if(orig_prec == MV_PRECISION_PIXEL)
+ ModeDecider my_mode_dec( m_encparams );
+ my_mode_dec.DoModeDecn( my_buffer , pic_num );
+
+ if (orig_prec == MV_PRECISION_PIXEL)
{
// FIXME: HACK HACK
// Divide the motion vectors by 2 to convert back to pixel
// accurate motion vectors and reset MV precision to
- // PIXEL accuracy
+ // PIXEL accuracy
MvArray &mv_arr1 = me_data.Vectors(1);
- for(int j = 0; j < mv_arr1.LengthY(); ++j)
+ for (int j = 0; j < mv_arr1.LengthY(); ++j)
{
- for(int i = 0; i < mv_arr1.LengthX(); ++i)
+ for (int i = 0; i < mv_arr1.LengthX(); ++i)
mv_arr1[j][i] = mv_arr1[j][i] >> 1;
}
- if(num_refs > 1)
+ if (num_refs > 1)
{
MvArray &mv_arr2 = me_data.Vectors(2);
- for(int j = 0; j < mv_arr2.LengthY(); ++j)
+ for (int j = 0; j < mv_arr2.LengthY(); ++j)
{
- for(int i = 0; i < mv_arr2.LengthX(); ++i)
- mv_arr2[j][i] = mv_arr2[j][i] >> 1;
+ for (int i = 0; i < mv_arr2.LengthX(); ++i)
+ mv_arr2[j][i] = mv_arr2[j][i]>>1;
}
}
m_encparams.GetPicPredParams().SetMVPrecision(MV_PRECISION_PIXEL);
@@ -143,40 +143,40 @@ void MotionEstimator::DoME(EncQueue& my_buffer, int pic_num)
// we have to assign DC values for chroma components for
// blocks we're decided are intra.
- SetChromaDC(my_buffer , pic_num);
+ SetChromaDC( my_buffer , pic_num );
//return false;
}
ValueType MotionEstimator::GetChromaBlockDC(const PicArray& pic_data,
- int xunit , int yunit , int split)
+ int xunit , int yunit , int split)
{
BlockDiffParams dparams;
- dparams.SetBlockLimits(m_encparams.GetPicPredParams().ChromaBParams(split) ,
- pic_data, xunit , yunit);
+ dparams.SetBlockLimits( m_encparams.GetPicPredParams().ChromaBParams( split ) ,
+ pic_data, xunit , yunit);
ValueType dc;
- IntraBlockDiff intradiff(pic_data);
+ IntraBlockDiff intradiff( pic_data );
- intradiff.Diff(dparams , dc);
+ intradiff.Diff( dparams , dc );
return dc;
}
-void MotionEstimator::SetChromaDC(const PicArray& pic_data , MEData& me_data , CompSort csort)
+void MotionEstimator::SetChromaDC( const PicArray& pic_data , MEData& me_data , CompSort csort )
{
// Lower limit of block coords in SB
- int xtl, ytl;
+ int xtl,ytl;
// Upper limit of block coords in SB
- int xbr, ybr;
+ int xbr,ybr;
- // Ditto, for subSBs
- int xsubSBtl, ysubSBtl;
- int xsubSBbr, ysubSBbr;
+ // Ditto, for subSBs
+ int xsubSBtl,ysubSBtl;
+ int xsubSBbr,ysubSBbr;
- TwoDArray<ValueType>& dcarray = me_data.DC(csort);
+ TwoDArray<ValueType>& dcarray = me_data.DC( csort );
ValueType dc = 0;
@@ -189,58 +189,58 @@ void MotionEstimator::SetChromaDC(const PicArray& pic_data , MEData& me_data , C
int level;
- for(int ysb = 0 ; ysb < me_data.SBSplit().LengthY() ; ++ysb)
+ for ( int ysb=0 ; ysb<me_data.SBSplit().LengthY() ; ++ysb )
{
- for(int xsb = 0 ; xsb < me_data.SBSplit().LengthX() ; ++xsb)
+ for ( int xsb=0 ; xsb<me_data.SBSplit().LengthX() ; ++xsb )
{
level = me_data.SBSplit()[ysb][xsb];
- xtl = xsb << 2;
- ytl = ysb << 2;
- xbr = xtl + 4;
- ybr = ytl + 4;
+ xtl = xsb<<2;
+ ytl = ysb<<2;
+ xbr = xtl+4;
+ ybr = ytl+4;
- xsubSBtl = xsb << 1;
- ysubSBtl = ysb << 1;
- xsubSBbr = xsubSBtl + 2;
- ysubSBbr = ysubSBtl + 2;
+ xsubSBtl = xsb<<1;
+ ysubSBtl = ysb<<1;
+ xsubSBbr = xsubSBtl+2;
+ ysubSBbr = ysubSBtl+2;
- for(int j = 0 ; j < (1 << level) ; ++j)
+ for (int j = 0 ; j<(1<<level) ;++j)
{
- for(int i = 0 ; i < (1 << level) ; ++i)
- {
- xunit = (xsb << level) + i;
- yunit = (ysb << level) + j;
+ for (int i = 0 ; i<(1<<level) ;++i)
+ {
+ xunit = ( xsb<<level ) + i;
+ yunit = ( ysb<<level ) + j;
- xstart = xunit << (2 - level);
- ystart = yunit << (2 - level);
+ xstart = xunit<<( 2-level );
+ ystart = yunit<<( 2-level );
- xend = xstart + (1 << (2 - level));
- yend = ystart + (1 << (2 - level));
+ xend = xstart + ( 1<<( 2-level ) );
+ yend = ystart + ( 1<<( 2-level ) );
- if(me_data.Mode()[ystart][xstart] == INTRA)
- // Get the DC value for the unit
- dc = GetChromaBlockDC(pic_data , xunit , yunit , level);
+ if ( me_data.Mode()[ystart][xstart] == INTRA )
+ // Get the DC value for the unit
+ dc = GetChromaBlockDC( pic_data , xunit , yunit , level );
- // Copy it into the corresponding blocks
- for(int q = ystart ; q < yend ; ++q)
- for(int p = xstart ; p < xend ; ++p)
- dcarray[q][p] = dc;
+ // Copy it into the corresponding blocks
+ for ( int q=ystart ; q< yend ; ++q )
+ for ( int p=xstart ; p< xend ; ++p )
+ dcarray[q][p] = dc;
- }// i
- }// j
+ }// i
+ }// j
}// xsb
}// ysb
}
-void MotionEstimator::SetChromaDC(EncQueue& my_buffer , int pic_num)
+void MotionEstimator::SetChromaDC( EncQueue& my_buffer , int pic_num )
{
- MEData& me_data = my_buffer.GetPicture(pic_num).GetMEData();
- SetChromaDC(my_buffer.GetPicture(pic_num).OrigData(U_COMP) , me_data , U_COMP);
- SetChromaDC(my_buffer.GetPicture(pic_num).OrigData(V_COMP) , me_data , V_COMP);
+ MEData& me_data = my_buffer.GetPicture(pic_num).GetMEData();
+ SetChromaDC( my_buffer.GetPicture( pic_num ).OrigData(U_COMP) , me_data , U_COMP );
+ SetChromaDC( my_buffer.GetPicture( pic_num ).OrigData(V_COMP) , me_data , V_COMP );
}
diff --git a/src/filters/parser/DiracSplitter/libdirac/libdirac_motionest/motion_estimate.h b/src/filters/parser/DiracSplitter/libdirac/libdirac_motionest/motion_estimate.h
index 18b07b448..10129dd3e 100644
--- a/src/filters/parser/DiracSplitter/libdirac/libdirac_motionest/motion_estimate.h
+++ b/src/filters/parser/DiracSplitter/libdirac/libdirac_motionest/motion_estimate.h
@@ -43,63 +43,62 @@
namespace dirac
{
-class EncQueue;
-
-
-//! Class to handle the whole motion estimation process.
-/*!
-
- Class to handle the whole motion estimation process, which works in
- three stages.
-
- First a pixel-accurate estimate is formed by looking at the current
- picture data and the data from the reference picture(s). Motion vectors
- are found for every block.
-
- Second, these pixel-accurate motion vectors are refined to sub-pixel
- accuracy. This means some sort of upconversion needs to be applied to
- the reference. This can be done by actually upconverting the reference
- to create a bigger picture or by doing some interpolation of values
- on the fly.
-
- Third, mode decisions have to be made. This means choosing which (if
- any) reference to use for each block, and whether to use the same
- motion vectors for groups of blocks together. A 2x2 group of blocks is
- called a sub-MB and a 4x4 group of blocks is a MB (Macroblock). All
- the MV data is organised by MB.
-*/
-class MotionEstimator
-{
-public:
- //! Constructor
- MotionEstimator(const EncoderParams& encp);
- //! Destructor
- ~MotionEstimator() {}
-
- //! Do the motion estimation
- void DoME(EncQueue& my_buffer , int pic_num);
-
-private:
- //! Copy constructor: private, body-less - class should not be copied
- MotionEstimator(const MotionEstimator& cpy);
-
- //! Assignment= : //private, body-less - class should not be assigned
- MotionEstimator& operator=(const MotionEstimator& rhs);
-
- //! Go through all the intra blocks and extract the chroma dc values to be coded
- void SetChromaDC(EncQueue& my_buffer, int pic_num);
-
- //! Called by previous fn for each component
- void SetChromaDC(const PicArray& pic_data, MEData& me_data, CompSort csort);
-
- //! Called by previous fn for each block
- ValueType GetChromaBlockDC(const PicArray& pic_data, int xloc, int yloc, int split);
-
- // Member variables
-
- //! A local reference to the encoder parameters
- const EncoderParams& m_encparams;
-};
+ class EncQueue;
+
+
+ //! Class to handle the whole motion estimation process.
+ /*!
+
+ Class to handle the whole motion estimation process, which works in
+ three stages.
+
+ First a pixel-accurate estimate is formed by looking at the current
+ picture data and the data from the reference picture(s). Motion vectors
+ are found for every block.
+
+ Second, these pixel-accurate motion vectors are refined to sub-pixel
+ accuracy. This means some sort of upconversion needs to be applied to
+ the reference. This can be done by actually upconverting the reference
+ to create a bigger picture or by doing some interpolation of values
+ on the fly.
+
+ Third, mode decisions have to be made. This means choosing which (if
+ any) reference to use for each block, and whether to use the same
+ motion vectors for groups of blocks together. A 2x2 group of blocks is
+ called a sub-MB and a 4x4 group of blocks is a MB (Macroblock). All
+ the MV data is organised by MB.
+ */
+ class MotionEstimator{
+ public:
+ //! Constructor
+ MotionEstimator( const EncoderParams& encp );
+ //! Destructor
+ ~MotionEstimator(){}
+
+ //! Do the motion estimation
+ void DoME( EncQueue& my_buffer , int pic_num );
+
+ private:
+ //! Copy constructor: private, body-less - class should not be copied
+ MotionEstimator( const MotionEstimator& cpy );
+
+ //! Assignment= : //private, body-less - class should not be assigned
+ MotionEstimator& operator=( const MotionEstimator& rhs );
+
+ //! Go through all the intra blocks and extract the chroma dc values to be coded
+ void SetChromaDC( EncQueue& my_buffer, int pic_num);
+
+ //! Called by previous fn for each component
+ void SetChromaDC(const PicArray& pic_data, MEData& me_data,CompSort csort);
+
+ //! Called by previous fn for each block
+ ValueType GetChromaBlockDC(const PicArray& pic_data, int xloc,int yloc,int split);
+
+ // Member variables
+
+ //! A local reference to the encoder parameters
+ const EncoderParams& m_encparams;
+ };
} // namespace dirac
diff --git a/src/filters/parser/DiracSplitter/libdirac/libdirac_motionest/pixel_match.cpp b/src/filters/parser/DiracSplitter/libdirac/libdirac_motionest/pixel_match.cpp
index 652f75fad..7ac7f74ed 100644
--- a/src/filters/parser/DiracSplitter/libdirac/libdirac_motionest/pixel_match.cpp
+++ b/src/filters/parser/DiracSplitter/libdirac/libdirac_motionest/pixel_match.cpp
@@ -51,34 +51,34 @@ using namespace dirac;
using std::vector;
using std::log;
-PixelMatcher::PixelMatcher(const EncoderParams& encp):
+PixelMatcher::PixelMatcher( const EncoderParams& encp):
m_encparams(encp)
{}
-void PixelMatcher::DoSearch(EncQueue& my_buffer, int pic_num)
+void PixelMatcher::DoSearch( EncQueue& my_buffer, int pic_num )
{
- m_predparams = &(my_buffer.GetPicture(pic_num).GetMEData().GetPicPredParams());
+ m_predparams = &(my_buffer.GetPicture(pic_num).GetMEData().GetPicPredParams() );
//does an initial search using hierarchical matching to get guide vectors
// Picture numbers of references
- int ref1, ref2;
+ int ref1,ref2;
// Use the luminance only for motion estimating
- const PicArray& pic_data = my_buffer.GetPicture(pic_num).DataForME(m_encparams.CombinedME());
+ const PicArray& pic_data = my_buffer.GetPicture( pic_num ).DataForME(m_encparams.CombinedME());
- const vector<int>& refs = my_buffer.GetPicture(pic_num).GetPparams().Refs();
+ const vector<int>& refs = my_buffer.GetPicture( pic_num ).GetPparams().Refs();
ref1 = refs[0];
- if(refs.size() > 1)
+ if (refs.size()>1)
ref2 = refs[1];
else
ref2 = ref1;
// Record temporal distances
- m_tdiff[0] = std::abs(ref1 - pic_num);
- m_tdiff[1] = std::abs(ref2 - pic_num);
+ m_tdiff[0] = std::abs( ref1 - pic_num );
+ m_tdiff[1] = std::abs( ref2 - pic_num );
// Obtain C++ references to the reference picture luma components
const PicArray& ref1_data = my_buffer.GetPicture(ref1).DataForME(m_encparams.CombinedME());
@@ -88,70 +88,70 @@ void PixelMatcher::DoSearch(EncQueue& my_buffer, int pic_num)
m_psort = my_buffer.GetPicture(pic_num).GetPparams().PicSort();
- if(m_encparams.FullSearch() == false)
+ if ( m_encparams.FullSearch() == false )
{
// Set the number of downconversion levels - not too many or we run out of picture!
- m_depth = (int) std::min(log(((double) pic_data.LengthX()) / 12.0) / log(2.0) ,
- log(((double) pic_data.LengthY()) / 12.0) / log(2.0));
+ m_depth = ( int) std::min( log(((double) pic_data.LengthX())/12.0)/log(2.0) ,
+ log(((double) pic_data.LengthY())/12.0)/log(2.0) );
// These arrays will contain the downconverted picture and MvData hierarchy
- OneDArray<PicArray*> ref1_down(Range(1 , m_depth));
- OneDArray<PicArray*> ref2_down(Range(1 , m_depth));
- OneDArray<PicArray*> pic_down(Range(1 , m_depth));
- OneDArray<MEData*> me_data_set(Range(1 , m_depth));
+ OneDArray<PicArray*> ref1_down( Range( 1 , m_depth ) );
+ OneDArray<PicArray*> ref2_down( Range( 1 , m_depth ) );
+ OneDArray<PicArray*> pic_down( Range( 1 , m_depth ) );
+ OneDArray<MEData*> me_data_set( Range( 1 , m_depth ) );
// Populate the hierarchies
- MakePicHierarchy(pic_data , pic_down);
- MakePicHierarchy(ref1_data , ref1_down);
- if(ref1 != ref2)
- MakePicHierarchy(ref2_data , ref2_down);
+ MakePicHierarchy( pic_data , pic_down );
+ MakePicHierarchy( ref1_data , ref1_down );
+ if (ref1 != ref2)
+ MakePicHierarchy( ref2_data , ref2_down );
- MakeMEDataHierarchy(pic_down , me_data_set);
+ MakeMEDataHierarchy( pic_down , me_data_set );
- // Now do the work! //
+ // Now do the work! //
//////////////////////
// Start with motion estimating at the very lowest level
m_level = m_depth;
- MatchPic(*(pic_down[m_depth]) , *(ref1_down[m_depth]) , *(me_data_set[m_depth]) ,
- *(me_data_set[m_depth]) , 1);
- if(ref1 != ref2)
- MatchPic(*(pic_down[m_depth]) , *(ref2_down[m_depth]) , *(me_data_set[m_depth]) ,
- *(me_data_set[m_depth]) , 2);
+ MatchPic( *(pic_down[m_depth]) , *(ref1_down[m_depth]) , *(me_data_set[m_depth]) ,
+ *(me_data_set[m_depth]) , 1 );
+ if ( ref1 != ref2 )
+ MatchPic( *(pic_down[m_depth]) , *(ref2_down[m_depth]) , *(me_data_set[m_depth]) ,
+ *(me_data_set[m_depth]) , 2 );
- // Do the intervening levels - here we can have a genuine set of guide vectors
- for(m_level = m_depth - 1 ; m_level >= 1 ; --m_level)
+ // Do the intervening levels - here we can have a genuine set of guide vectors
+ for ( m_level=m_depth-1 ; m_level>=1 ; --m_level )
{
- MatchPic(*(pic_down[m_level]) , *(ref1_down[m_level]) , *(me_data_set[m_level]) ,
- *(me_data_set[m_level+1]) , 1);
- if(ref1 != ref2)
- MatchPic(*(pic_down[m_level]) , *(ref2_down[m_level]) , *(me_data_set[m_level]) ,
- *(me_data_set[m_level+1]) , 2);
+ MatchPic( *(pic_down[m_level]) , *(ref1_down[m_level]) , *(me_data_set[m_level]) ,
+ *(me_data_set[m_level+1]) , 1 );
+ if (ref1!=ref2)
+ MatchPic( *(pic_down[m_level]) , *(ref2_down[m_level]) , *(me_data_set[m_level]) ,
+ *(me_data_set[m_level+1]) , 2 );
}// level
// Finally, do the top level, with the pictures themselves
m_level = 0;
- MEData& me_data = my_buffer.GetPicture(pic_num).GetMEData();
- MatchPic(pic_data , ref1_data, me_data , *(me_data_set[1]) , 1);
- if(ref1 != ref2)
- MatchPic(pic_data , ref2_data , me_data , *(me_data_set[1]) , 2);
+ MEData& me_data = my_buffer.GetPicture(pic_num).GetMEData();
+ MatchPic( pic_data , ref1_data, me_data , *(me_data_set[1]) , 1 );
+ if ( ref1 != ref2 )
+ MatchPic( pic_data , ref2_data , me_data , *(me_data_set[1]) , 2 );
// Now we're finished, tidy everything up ...
- TidyPics(pic_down);
- TidyPics(ref1_down);
- if(ref1 != ref2)
- TidyPics(ref2_down);
- TidyMEData(me_data_set);
+ TidyPics( pic_down );
+ TidyPics( ref1_down );
+ if (ref1 != ref2)
+ TidyPics( ref2_down );
+ TidyMEData( me_data_set );
}
else
{
m_depth = 0;
m_level = 0;
- MEData& me_data = my_buffer.GetPicture(pic_num).GetMEData();
- MatchPic(pic_data , ref1_data, me_data , me_data , 1);
- if(ref1 != ref2)
- MatchPic(pic_data , ref2_data , me_data , me_data , 2);
+ MEData& me_data = my_buffer.GetPicture(pic_num).GetMEData();
+ MatchPic( pic_data , ref1_data, me_data , me_data , 1 );
+ if ( ref1 != ref2 )
+ MatchPic( pic_data , ref2_data , me_data , me_data , 2 );
}
}
@@ -164,26 +164,26 @@ void PixelMatcher::MakePicHierarchy(const PicArray& data ,
// Allocate
int scale_factor = 1;
- for(int i = 1 ; i <= m_depth; ++i)
+ for (int i=1 ; i<=m_depth;++i)
{
// Dimensions of pic_down[i] will be shrunk by a factor 2**i
- scale_factor *= 2;
- down_data[i] = new PicArray(data.LengthY() / scale_factor , data.LengthX() / scale_factor);
+ scale_factor*=2;
+ down_data[i] = new PicArray( data.LengthY()/scale_factor , data.LengthX()/scale_factor);
}
//do all the downconversions
- if(m_depth > 0)
+ if (m_depth>0)
{
- mydcon.DoDownConvert(data , *(down_data[1]));
+ mydcon.DoDownConvert( data , *(down_data[1]) );
- for(int i = 1 ; i < m_depth ; ++i)
- mydcon.DoDownConvert(*(down_data[i]) , *(down_data[i+1]));
+ for (int i=1 ; i<m_depth ; ++i)
+ mydcon.DoDownConvert( *(down_data[i]) , *(down_data[i+1]) );
}
}
void PixelMatcher::MakeMEDataHierarchy(const OneDArray< PicArray*>& down_data,
- OneDArray< MEData* >& me_data_set)
+ OneDArray< MEData* >& me_data_set )
{
int xnumblocks , ynumblocks;
@@ -199,38 +199,38 @@ void PixelMatcher::MakeMEDataHierarchy(const OneDArray< PicArray*>& down_data,
PicturePredParams predparams = *m_predparams;
predparams.SetXNumSB(0);
predparams.SetYNumSB(0);
- for(int i = 1 ; i <= m_depth; ++i)
+ for (int i=1 ; i<=m_depth;++i)
{
- xnumblocks = xnumblocks >> 1;
- ynumblocks = ynumblocks >> 1;
+ xnumblocks = xnumblocks>>1;
+ ynumblocks = ynumblocks>>1;
- if((down_data[i]->LengthX()) % bparams.Xbsep() != 0)
+ if (( down_data[i]->LengthX() )%bparams.Xbsep() != 0)
xnumblocks++;
- if((down_data[i]->LengthY()) % bparams.Ybsep() != 0)
+ if (( down_data[i]->LengthY() )%bparams.Ybsep() != 0)
ynumblocks++;
- predparams.SetXNumBlocks(xnumblocks);
- predparams.SetYNumBlocks(ynumblocks);
+ predparams.SetXNumBlocks( xnumblocks );
+ predparams.SetYNumBlocks( ynumblocks );
- me_data_set[i] = new MEData(predparams, 2);
+ me_data_set[i] = new MEData( predparams, 2 );
}// i
}
-void PixelMatcher::TidyPics(OneDArray< PicArray*>& down_data)
+void PixelMatcher::TidyPics( OneDArray< PicArray*>& down_data )
{
- for(int i = 1 ; i <= m_depth ; ++i)
+ for (int i=1 ; i <= m_depth ; ++i)
{
delete down_data[i];
}// i
}
-void PixelMatcher::TidyMEData(OneDArray< MEData*>& me_data_set)
+void PixelMatcher::TidyMEData( OneDArray< MEData*>& me_data_set )
{
- for(int i = 1 ; i <= m_depth ; ++i)
+ for (int i=1 ; i <= m_depth ; ++i)
{
delete me_data_set[i];
}// i
@@ -246,17 +246,17 @@ void PixelMatcher::MatchPic(const PicArray& pic_data , const PicArray& ref_data
// Initialisation //
////////////////////
- m_big_xr = std::min(m_tdiff[ref_id-1], 3) * m_encparams.XRangeME();
- m_big_yr = std::min(m_tdiff[ref_id-1], 3) * m_encparams.YRangeME();
+ m_big_xr = std::min( m_tdiff[ref_id-1], 3 )*m_encparams.XRangeME();
+ m_big_yr = std::min( m_tdiff[ref_id-1], 3 )*m_encparams.YRangeME();
// Set the search ranges according to the level
- if(m_encparams.FullSearch() == false)
+ if ( m_encparams.FullSearch() == false )
{
m_cost_mean = 0.0;
m_cost_mean_sq = 0.0;
- m_xr = std::min(m_level + 1, 5);
- m_yr = std::min(m_level + 1, 5);
+ m_xr = std::min( m_level+1, 5);
+ m_yr = std::min( m_level+1, 5);
}
else
{
@@ -266,14 +266,14 @@ void PixelMatcher::MatchPic(const PicArray& pic_data , const PicArray& ref_data
// Provide aliases for the appropriate motion vector data components
- MvArray& mv_array = me_data.Vectors(ref_id);
- const MvArray& guide_array = guide_data.Vectors(ref_id);
- TwoDArray<MvCostData>& pred_costs = me_data.PredCosts(ref_id);
+ MvArray& mv_array = me_data.Vectors( ref_id );
+ const MvArray& guide_array = guide_data.Vectors( ref_id );
+ TwoDArray<MvCostData>& pred_costs = me_data.PredCosts( ref_id );
// Initialise the arrays
- for(int y = 0; y < mv_array.LengthY(); ++y)
+ for (int y=0; y<mv_array.LengthY(); ++y)
{
- for(int x = 0; x < mv_array.LengthX(); ++x)
+ for (int x=0; x<mv_array.LengthX(); ++x)
{
mv_array[y][x].x = 0;
mv_array[y][x].y = 0;
@@ -282,9 +282,9 @@ void PixelMatcher::MatchPic(const PicArray& pic_data , const PicArray& ref_data
}// y
// Provide a block matching object to do the work
- BlockMatcher my_bmatch(pic_data , ref_data ,
- m_predparams->LumaBParams(2) , m_predparams->MVPrecision() ,
- mv_array , pred_costs);
+ BlockMatcher my_bmatch( pic_data , ref_data ,
+ m_predparams->LumaBParams(2) , m_predparams->MVPrecision() ,
+ mv_array , pred_costs );
// Do the work - loop over all the blocks, finding the best match //
////////////////////////////////////////////////////////////////////
@@ -299,9 +299,9 @@ void PixelMatcher::MatchPic(const PicArray& pic_data , const PicArray& ref_data
// Make a zero-based list that is always used
m_cand_list.clear();
- MVector zero_mv(0 , 0);
+ MVector zero_mv( 0 , 0 );
- AddNewVlist(m_cand_list , zero_mv , m_xr , m_yr);
+ AddNewVlist( m_cand_list , zero_mv , m_xr , m_yr);
// Now loop over the blocks and find the best matches.
// The loop is unrolled because predictions are different at picture edges.
@@ -316,34 +316,34 @@ void PixelMatcher::MatchPic(const PicArray& pic_data , const PicArray& ref_data
DoBlock(0, 0 , guide_array , my_bmatch);
// The rest of the first row
- for(int xpos = 1 ; xpos < mv_array.LengthX() ; ++xpos)
+ for ( int xpos=1 ; xpos<mv_array.LengthX() ; ++xpos )
{
m_mv_prediction = mv_array[0][xpos-1];
DoBlock(xpos, 0 , guide_array , my_bmatch);
}// xpos
// All the remaining rows except the last
- for(int ypos = 1 ; ypos < mv_array.LengthY() ; ++ypos)
+ for ( int ypos=1 ; ypos<mv_array.LengthY() ; ++ypos )
{
// The first element of each row
m_mv_prediction = mv_array[ypos-1][0];
- DoBlock(0, ypos , guide_array , my_bmatch);
+ DoBlock(0, ypos , guide_array , my_bmatch );
- // The middle elements of each row
- for(int xpos = 1 ; xpos < mv_array.LastX() ; ++xpos)
+ // The middle elements of each row
+ for ( int xpos=1 ; xpos<mv_array.LastX() ; ++xpos )
{
- m_mv_prediction = MvMedian(mv_array[ypos][xpos-1],
- mv_array[ypos-1][xpos],
- mv_array[ypos-1][xpos+1]);
- DoBlock(xpos, ypos , guide_array , my_bmatch);
+ m_mv_prediction = MvMedian( mv_array[ypos][xpos-1],
+ mv_array[ypos-1][xpos],
+ mv_array[ypos-1][xpos+1]);
+ DoBlock(xpos, ypos , guide_array , my_bmatch );
}// xpos
- // The last element in each row
- m_mv_prediction = MvMean(mv_array[ypos-1][ mv_array.LastX()],
- mv_array[ypos][ mv_array.LastX()-1 ]);
- DoBlock(mv_array.LastX() , ypos , guide_array , my_bmatch);
+ // The last element in each row
+ m_mv_prediction = MvMean( mv_array[ypos-1][ mv_array.LastX() ],
+ mv_array[ypos][ mv_array.LastX()-1 ]);
+ DoBlock(mv_array.LastX() , ypos , guide_array , my_bmatch );
}//ypos
}
@@ -355,26 +355,26 @@ void PixelMatcher::DoBlock(const int xpos, const int ypos ,
// Find the best match for each block ...
// Use guide from lower down if one exists
- if(m_level < m_depth)
+ if ( m_level<m_depth )
{
- int xdown = BChk(xpos >> 1, guide_array.LengthX());
- int ydown = BChk(ypos >> 1, guide_array.LengthY());
- AddNewVlist(m_cand_list , guide_array[ydown][xdown] * 2 , m_xr , m_yr);
+ int xdown = BChk(xpos>>1, guide_array.LengthX());
+ int ydown = BChk(ypos>>1, guide_array.LengthY());
+ AddNewVlist( m_cand_list , guide_array[ydown][xdown] * 2 , m_xr , m_yr );
}
// use the spatial prediction, also, as a guide
- if(m_encparams.FullSearch() == false)
- AddNewVlist(m_cand_list , m_mv_prediction , m_xr , m_yr);
+ if (m_encparams.FullSearch()==false )
+ AddNewVlist( m_cand_list , m_mv_prediction , m_xr , m_yr );
else
- AddNewVlist(m_cand_list , m_mv_prediction , 1 , 1);
+ AddNewVlist( m_cand_list , m_mv_prediction , 1 , 1);
// Find the best motion vector //
/////////////////////////////////
- block_match.FindBestMatchPel(xpos , ypos , m_cand_list, m_mv_prediction, 0);
+ block_match.FindBestMatchPel( xpos , ypos , m_cand_list, m_mv_prediction, 0 );
// Reset the lists ready for the next block (don't erase the first sublist as
// this is a neighbourhood of zero, which we always look at)
- m_cand_list.erase(m_cand_list.begin() + 1 , m_cand_list.end());
+ m_cand_list.erase( m_cand_list.begin()+1 , m_cand_list.end() );
}
diff --git a/src/filters/parser/DiracSplitter/libdirac/libdirac_motionest/pixel_match.h b/src/filters/parser/DiracSplitter/libdirac/libdirac_motionest/pixel_match.h
index 15a9f61ae..f860882fb 100644
--- a/src/filters/parser/DiracSplitter/libdirac/libdirac_motionest/pixel_match.h
+++ b/src/filters/parser/DiracSplitter/libdirac/libdirac_motionest/pixel_match.h
@@ -57,100 +57,100 @@
#include <libdirac_motionest/block_match.h>
namespace dirac
{
-class EncQueue;
-class MvData;
-class EncoderParams;
-class PicArray;
+ class EncQueue;
+ class MvData;
+ class EncoderParams;
+ class PicArray;
-class PixelMatcher
-{
-public:
-
- //! Constructor
- PixelMatcher(const EncoderParams& encp);
-
- //! Do the actual search
- /* Do the searching.
-
- \param my_buffer the buffer of pictures from which pictures are taken
- \param pic_num the number of the picture for which motion is to be estimated
- \param mv_data class in which the measured motion vectors are stored, together with costs
-
- */
- void DoSearch(EncQueue& my_buffer, int pic_num);
-
-private:
-
- // Member variables
-
- //! Local reference to the encoder params
- const EncoderParams& m_encparams;
+ class PixelMatcher
+ {
+ public:
- //! Local reference to the picture pred params
- const PicturePredParams* m_predparams;
+ //! Constructor
+ PixelMatcher( const EncoderParams& encp);
- // the depth of the hierarchical match
- int m_depth;
+ //! Do the actual search
+ /* Do the searching.
- // the level we're at (from 0 to depth)
- int m_level;
+ \param my_buffer the buffer of pictures from which pictures are taken
+ \param pic_num the number of the picture for which motion is to be estimated
+ \param mv_data class in which the measured motion vectors are stored, together with costs
+
+ */
+ void DoSearch( EncQueue& my_buffer, int pic_num );
- // the search-range sizes for the hierarchical match
- int m_xr, m_yr;
+ private:
- // the search-range sizes for when hierarchical match fails
- int m_big_xr, m_big_yr;
+ // Member variables
- // the temporal distances to the reference pictures
- int m_tdiff[2];
+ //! Local reference to the encoder params
+ const EncoderParams& m_encparams;
- // the picture sort - I, L1 or L2
- PictureSort m_psort;
+ //! Local reference to the picture pred params
+ const PicturePredParams* m_predparams;
- // list of candidate vectors for checking
- CandidateList m_cand_list;
+ // the depth of the hierarchical match
+ int m_depth;
- // Prediction used for each block. This is derived from neighbouring blocks
- // and is used to control the variation in the motion vector field.
- MVector m_mv_prediction;
+ // the level we're at (from 0 to depth)
+ int m_level;
- // The value used in computing block cost means with a simple recursive filter
- double m_rho;
+ // the search-range sizes for the hierarchical match
+ int m_xr, m_yr;
+
+ // the search-range sizes for when hierarchical match fails
+ int m_big_xr, m_big_yr;
+
+ // the temporal distances to the reference pictures
+ int m_tdiff[2];
- // The mean of the block cost
- double m_cost_mean;
+ // the picture sort - I, L1 or L2
+ PictureSort m_psort;
- // The mean of the square of the block cost
- double m_cost_mean_sq;
+ // list of candidate vectors for checking
+ CandidateList m_cand_list;
-private:
+ // Prediction used for each block. This is derived from neighbouring blocks
+ // and is used to control the variation in the motion vector field.
+ MVector m_mv_prediction;
+
+ // The value used in computing block cost means with a simple recursive filter
+ double m_rho;
+
+ // The mean of the block cost
+ double m_cost_mean;
+
+ // The mean of the square of the block cost
+ double m_cost_mean_sq;
+
+ private:
- // Functions
+ // Functions
- //! Make down-converted pictures
- void MakePicHierarchy(const PicArray& data, OneDArray< PicArray* >& down_data);
+ //! Make down-converted pictures
+ void MakePicHierarchy(const PicArray& data, OneDArray< PicArray* >& down_data);
- //! Make a hierarchy of MvData structures
- void MakeMEDataHierarchy(const OneDArray< PicArray*>& down_data,
- OneDArray< MEData* >& me_data_set);
+ //! Make a hierarchy of MvData structures
+ void MakeMEDataHierarchy(const OneDArray< PicArray*>& down_data,
+ OneDArray< MEData* >& me_data_set );
- //! Tidy up the allocations made in building the picture hirearchy
- void TidyPics(OneDArray< PicArray*>& down_data);
+ //! Tidy up the allocations made in building the picture hirearchy
+ void TidyPics( OneDArray< PicArray*>& down_data );
- //! Tidy up the allocations made in building the MV data hirearchy
- void TidyMEData(OneDArray< MEData*>& me_data_set);
+ //! Tidy up the allocations made in building the MV data hirearchy
+ void TidyMEData( OneDArray< MEData*>& me_data_set );
- //! Match the picture data
- void MatchPic(const PicArray& ref_data , const PicArray& pic_data , MEData& me_data ,
- const MvData& guide_data, const int ref_id);
+ //! Match the picture data
+ void MatchPic(const PicArray& ref_data , const PicArray& pic_data , MEData& me_data ,
+ const MvData& guide_data, const int ref_id);
- //! Do a given block
- void DoBlock(const int xpos, const int ypos ,
- const MvArray& guide_array,
- BlockMatcher& block_match);
+ //! Do a given block
+ void DoBlock(const int xpos, const int ypos ,
+ const MvArray& guide_array,
+ BlockMatcher& block_match);
-};
+ };
} // namespace dirac
diff --git a/src/filters/parser/DiracSplitter/resource.h b/src/filters/parser/DiracSplitter/resource.h
index 2436d0286..bdcfbe8c4 100644
--- a/src/filters/parser/DiracSplitter/resource.h
+++ b/src/filters/parser/DiracSplitter/resource.h
@@ -4,7 +4,7 @@
//
// Next default values for new objects
-//
+//
#ifdef APSTUDIO_INVOKED
#ifndef APSTUDIO_READONLY_SYMBOLS
#define _APS_NEXT_RESOURCE_VALUE 101
diff --git a/src/filters/parser/DiracSplitter/stdafx.cpp b/src/filters/parser/DiracSplitter/stdafx.cpp
index 58d59d65a..8d2e22fce 100644
--- a/src/filters/parser/DiracSplitter/stdafx.cpp
+++ b/src/filters/parser/DiracSplitter/stdafx.cpp
@@ -1,4 +1,4 @@
-/*
+/*
* Copyright (C) 2003-2006 Gabest
* http://www.gabest.org
*
@@ -6,15 +6,15 @@
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2, or (at your option)
* any later version.
- *
+ *
* This Program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with GNU Make; see the file COPYING. If not, write to
- * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
+ * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
* http://www.gnu.org/copyleft/gpl.html
*
*/
diff --git a/src/filters/parser/DiracSplitter/stdafx.h b/src/filters/parser/DiracSplitter/stdafx.h
index 5a1eb906e..b76a35484 100644
--- a/src/filters/parser/DiracSplitter/stdafx.h
+++ b/src/filters/parser/DiracSplitter/stdafx.h
@@ -1,4 +1,4 @@
-/*
+/*
* Copyright (C) 2003-2006 Gabest
* http://www.gabest.org
*
@@ -6,15 +6,15 @@
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2, or (at your option)
* any later version.
- *
+ *
* This Program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with GNU Make; see the file COPYING. If not, write to
- * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
+ * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
* http://www.gnu.org/copyleft/gpl.html
*
*/
@@ -62,18 +62,18 @@ using namespace dirac;
// === Imported from Dirac library
#define isFrameStartCode(c) ((c) == 0x00 || (c) == 0x0C || (c) == 0x08 || (c) == 0x0D || (c) == 0x0E || (c) == 0x09 || (c) == 0x0A || (c) == 0x10)
-const unsigned int START_CODE_PREFIX = 0x42424344; //BBCD
-const unsigned int START_CODE_PREFIX_BYTE0 =
- (START_CODE_PREFIX >> 24) & 0xFF;
-const unsigned int START_CODE_PREFIX_BYTE1 =
- (START_CODE_PREFIX >> 16) & 0xFF;
-const unsigned int START_CODE_PREFIX_BYTE2 =
- (START_CODE_PREFIX >> 8) & 0xFF;
-const unsigned int START_CODE_PREFIX_BYTE3 =
- START_CODE_PREFIX & 0xFF;
-
-//! Access unit start code
-const unsigned char AU_START_CODE = 0x00;
-//! Sequence end code
-const unsigned char SEQ_END_CODE = 0x10;
+ const unsigned int START_CODE_PREFIX = 0x42424344; //BBCD
+ const unsigned int START_CODE_PREFIX_BYTE0 =
+ (START_CODE_PREFIX >> 24) & 0xFF;
+ const unsigned int START_CODE_PREFIX_BYTE1 =
+ (START_CODE_PREFIX >> 16) & 0xFF;
+ const unsigned int START_CODE_PREFIX_BYTE2 =
+ (START_CODE_PREFIX >> 8) & 0xFF;
+ const unsigned int START_CODE_PREFIX_BYTE3 =
+ START_CODE_PREFIX & 0xFF;
+
+ //! Access unit start code
+ const unsigned char AU_START_CODE = 0x00;
+ //! Sequence end code
+ const unsigned char SEQ_END_CODE = 0x10;
diff --git a/src/filters/parser/FLVSplitter/FLVSplitter.cpp b/src/filters/parser/FLVSplitter/FLVSplitter.cpp
index a90d373bf..98fdbcbef 100644
--- a/src/filters/parser/FLVSplitter/FLVSplitter.cpp
+++ b/src/filters/parser/FLVSplitter/FLVSplitter.cpp
@@ -1,4 +1,4 @@
-/*
+/*
* Copyright (C) 2003-2006 Gabest
* http://www.gabest.org
*
@@ -6,15 +6,15 @@
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2, or (at your option)
* any later version.
- *
+ *
* This Program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with GNU Make; see the file COPYING. If not, write to
- * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
+ * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
* http://www.gnu.org/copyleft/gpl.html
*
*/
@@ -30,49 +30,49 @@
const AMOVIESETUP_MEDIATYPE sudPinTypesIn[] =
{
- {&MEDIATYPE_Stream, &MEDIASUBTYPE_FLV},
- {&MEDIATYPE_Stream, &MEDIASUBTYPE_NULL},
+ {&MEDIATYPE_Stream, &MEDIASUBTYPE_FLV},
+ {&MEDIATYPE_Stream, &MEDIASUBTYPE_NULL},
};
const AMOVIESETUP_PIN sudpPins[] =
{
- {L"Input", FALSE, FALSE, FALSE, FALSE, &CLSID_NULL, NULL, countof(sudPinTypesIn), sudPinTypesIn},
- {L"Output", FALSE, TRUE, FALSE, FALSE, &CLSID_NULL, NULL, 0, NULL}
+ {L"Input", FALSE, FALSE, FALSE, FALSE, &CLSID_NULL, NULL, countof(sudPinTypesIn), sudPinTypesIn},
+ {L"Output", FALSE, TRUE, FALSE, FALSE, &CLSID_NULL, NULL, 0, NULL}
};
const AMOVIESETUP_MEDIATYPE sudPinTypesOut2[] =
{
- {&MEDIATYPE_Video, &MEDIASUBTYPE_NULL},
+ {&MEDIATYPE_Video, &MEDIASUBTYPE_NULL},
};
const AMOVIESETUP_FILTER sudFilter[] =
{
- {&__uuidof(CFLVSplitterFilter), L"MPC - FLV Splitter (Gabest)", MERIT_NORMAL, countof(sudpPins), sudpPins, CLSID_LegacyAmFilterCategory},
- {&__uuidof(CFLVSourceFilter), L"MPC - FLV Source (Gabest)", MERIT_NORMAL, 0, NULL, CLSID_LegacyAmFilterCategory},
+ {&__uuidof(CFLVSplitterFilter), L"MPC - FLV Splitter (Gabest)", MERIT_NORMAL, countof(sudpPins), sudpPins, CLSID_LegacyAmFilterCategory},
+ {&__uuidof(CFLVSourceFilter), L"MPC - FLV Source (Gabest)", MERIT_NORMAL, 0, NULL, CLSID_LegacyAmFilterCategory},
};
CFactoryTemplate g_Templates[] =
{
- {sudFilter[0].strName, sudFilter[0].clsID, CreateInstance<CFLVSplitterFilter>, NULL, &sudFilter[0]},
- {sudFilter[1].strName, sudFilter[1].clsID, CreateInstance<CFLVSourceFilter>, NULL, &sudFilter[1]},
+ {sudFilter[0].strName, sudFilter[0].clsID, CreateInstance<CFLVSplitterFilter>, NULL, &sudFilter[0]},
+ {sudFilter[1].strName, sudFilter[1].clsID, CreateInstance<CFLVSourceFilter>, NULL, &sudFilter[1]},
};
int g_cTemplates = countof(g_Templates);
STDAPI DllRegisterServer()
{
- DeleteRegKey(_T("Media Type\\Extensions\\"), _T(".flv"));
+ DeleteRegKey(_T("Media Type\\Extensions\\"), _T(".flv"));
- RegisterSourceFilter(CLSID_AsyncReader, MEDIASUBTYPE_FLV, _T("0,4,,464C5601"), NULL);
+ RegisterSourceFilter(CLSID_AsyncReader, MEDIASUBTYPE_FLV, _T("0,4,,464C5601"), NULL);
- return AMovieDllRegisterServer2(TRUE);
+ return AMovieDllRegisterServer2(TRUE);
}
STDAPI DllUnregisterServer()
{
- UnRegisterSourceFilter(MEDIASUBTYPE_FLV);
+ UnRegisterSourceFilter(MEDIASUBTYPE_FLV);
- return AMovieDllRegisterServer2(FALSE);
+ return AMovieDllRegisterServer2(FALSE);
}
#include "../../FilterApp.h"
@@ -86,705 +86,659 @@ CFilterApp theApp;
//
CFLVSplitterFilter::CFLVSplitterFilter(LPUNKNOWN pUnk, HRESULT* phr)
- : CBaseSplitterFilter(NAME("CFLVSplitterFilter"), pUnk, phr, __uuidof(this))
+ : CBaseSplitterFilter(NAME("CFLVSplitterFilter"), pUnk, phr, __uuidof(this))
{
}
bool CFLVSplitterFilter::ReadTag(Tag& t)
{
- if(m_pFile->GetRemaining() < 15)
- return false;
+ if(m_pFile->GetRemaining() < 15)
+ return false;
- t.PreviousTagSize = (UINT32)m_pFile->BitRead(32);
- t.TagType = (BYTE)m_pFile->BitRead(8);
- t.DataSize = (UINT32)m_pFile->BitRead(24);
- t.TimeStamp = (UINT32)m_pFile->BitRead(24);
- t.TimeStamp |= (UINT32)m_pFile->BitRead(8) << 24;
- t.StreamID = (UINT32)m_pFile->BitRead(24);
+ t.PreviousTagSize = (UINT32)m_pFile->BitRead(32);
+ t.TagType = (BYTE)m_pFile->BitRead(8);
+ t.DataSize = (UINT32)m_pFile->BitRead(24);
+ t.TimeStamp = (UINT32)m_pFile->BitRead(24);
+ t.TimeStamp |= (UINT32)m_pFile->BitRead(8) << 24;
+ t.StreamID = (UINT32)m_pFile->BitRead(24);
- return m_pFile->GetRemaining() >= t.DataSize;
+ return m_pFile->GetRemaining() >= t.DataSize;
}
bool CFLVSplitterFilter::ReadTag(AudioTag& at)
{
- if(!m_pFile->GetRemaining())
- return false;
+ if(!m_pFile->GetRemaining())
+ return false;
- at.SoundFormat = (BYTE)m_pFile->BitRead(4);
- at.SoundRate = (BYTE)m_pFile->BitRead(2);
- at.SoundSize = (BYTE)m_pFile->BitRead(1);
- at.SoundType = (BYTE)m_pFile->BitRead(1);
+ at.SoundFormat = (BYTE)m_pFile->BitRead(4);
+ at.SoundRate = (BYTE)m_pFile->BitRead(2);
+ at.SoundSize = (BYTE)m_pFile->BitRead(1);
+ at.SoundType = (BYTE)m_pFile->BitRead(1);
- return true;
+ return true;
}
bool CFLVSplitterFilter::ReadTag(VideoTag& vt)
{
- if(!m_pFile->GetRemaining())
- return false;
+ if(!m_pFile->GetRemaining())
+ return false;
- vt.FrameType = (BYTE)m_pFile->BitRead(4);
- vt.CodecID = (BYTE)m_pFile->BitRead(4);
+ vt.FrameType = (BYTE)m_pFile->BitRead(4);
+ vt.CodecID = (BYTE)m_pFile->BitRead(4);
- return true;
+ return true;
}
#ifndef NOVIDEOTWEAK
bool CFLVSplitterFilter::ReadTag(VideoTweak& vt)
{
- if(!m_pFile->GetRemaining())
- return false;
+ if(!m_pFile->GetRemaining())
+ return false;
- vt.x = (BYTE)m_pFile->BitRead(4);
- vt.y = (BYTE)m_pFile->BitRead(4);
+ vt.x = (BYTE)m_pFile->BitRead(4);
+ vt.y = (BYTE)m_pFile->BitRead(4);
- return true;
+ return true;
}
#endif
bool CFLVSplitterFilter::Sync(__int64& pos)
{
- m_pFile->Seek(pos);
-
- while(m_pFile->GetRemaining() >= 15)
- {
- __int64 limit = m_pFile->GetRemaining();
- while(true)
- {
- BYTE b = m_pFile->BitRead(8);
- if(b == 8 || b == 9) break;
- if(--limit < 15) return false;
- }
-
- pos = m_pFile->GetPos() - 5;
- m_pFile->Seek(pos);
-
- Tag ct;
- if(ReadTag(ct))
- {
- __int64 next = m_pFile->GetPos() + ct.DataSize;
- if(next == m_pFile->GetLength() - 4)
- {
- m_pFile->Seek(pos);
- return true;
- }
- else if(next <= m_pFile->GetLength() - 19)
- {
- m_pFile->Seek(next);
- Tag nt;
- if(ReadTag(nt) && (nt.TagType == 8 || nt.TagType == 9 || nt.TagType == 18))
- {
- if((nt.PreviousTagSize == ct.DataSize + 11) ||
- (m_IgnorePrevSizes &&
- nt.TimeStamp >= ct.TimeStamp &&
- nt.TimeStamp - ct.TimeStamp <= 1000))
- {
- m_pFile->Seek(pos);
- return true;
- }
- }
- }
- }
-
- m_pFile->Seek(pos + 5);
- }
-
- return false;
+ m_pFile->Seek(pos);
+
+ while(m_pFile->GetRemaining() >= 15)
+ {
+ __int64 limit = m_pFile->GetRemaining();
+ while (true) {
+ BYTE b = m_pFile->BitRead(8);
+ if (b == 8 || b == 9) break;
+ if (--limit < 15) return false;
+ }
+
+ pos = m_pFile->GetPos() - 5;
+ m_pFile->Seek(pos);
+
+ Tag ct;
+ if (ReadTag(ct)) {
+ __int64 next = m_pFile->GetPos() + ct.DataSize;
+ if(next == m_pFile->GetLength() - 4) {
+ m_pFile->Seek(pos);
+ return true;
+ }
+ else if (next <= m_pFile->GetLength() - 19) {
+ m_pFile->Seek(next);
+ Tag nt;
+ if (ReadTag(nt) && (nt.TagType == 8 || nt.TagType == 9 || nt.TagType == 18)) {
+ if ((nt.PreviousTagSize == ct.DataSize + 11) ||
+ (m_IgnorePrevSizes &&
+ nt.TimeStamp >= ct.TimeStamp &&
+ nt.TimeStamp - ct.TimeStamp <= 1000))
+ {
+ m_pFile->Seek(pos);
+ return true;
+ }
+ }
+ }
+ }
+
+ m_pFile->Seek(pos + 5);
+ }
+
+ return false;
}
HRESULT CFLVSplitterFilter::CreateOutputs(IAsyncReader* pAsyncReader)
{
- CheckPointer(pAsyncReader, E_POINTER);
-
- HRESULT hr = E_FAIL;
-
- m_pFile.Free();
- m_pFile.Attach(DNew CBaseSplitterFileEx(pAsyncReader, hr, DEFAULT_CACHE_LENGTH, false));
- if(!m_pFile) return E_OUTOFMEMORY;
- if(FAILED(hr))
- {
- m_pFile.Free();
- return hr;
- }
-
- m_rtNewStart = m_rtCurrent = 0;
- m_rtNewStop = m_rtStop = m_rtDuration = 0;
-
- if(m_pFile->BitRead(24) != 'FLV' || m_pFile->BitRead(8) != 1)
- return E_FAIL;
-
- EXECUTE_ASSERT(m_pFile->BitRead(5) == 0); // TypeFlagsReserved
- bool fTypeFlagsAudio = !!m_pFile->BitRead(1);
- EXECUTE_ASSERT(m_pFile->BitRead(1) == 0); // TypeFlagsReserved
- bool fTypeFlagsVideo = !!m_pFile->BitRead(1);
- m_DataOffset = (UINT32)m_pFile->BitRead(32);
-
- // doh, these flags aren't always telling the truth
- fTypeFlagsAudio = fTypeFlagsVideo = true;
-
- Tag t;
- AudioTag at;
- VideoTag vt;
-
- UINT32 prevTagSize = 0;
- m_IgnorePrevSizes = false;
-
- m_pFile->Seek(m_DataOffset);
-
- for(int i = 0; ReadTag(t) && (fTypeFlagsVideo || fTypeFlagsAudio) && i < 100; i++)
- {
- UINT64 next = m_pFile->GetPos() + t.DataSize;
-
- CStringW name;
-
- CMediaType mt;
- mt.SetSampleSize(1);
- mt.subtype = GUID_NULL;
-
- if(i != 0 && t.PreviousTagSize != prevTagSize)
- {
- m_IgnorePrevSizes = true;
- }
- prevTagSize = t.DataSize + 11;
-
- if(t.TagType == 8 && t.DataSize != 0 && fTypeFlagsAudio)
- {
- UNREFERENCED_PARAMETER(at);
- AudioTag at;
- name = L"Audio";
-
- if(ReadTag(at))
- {
- int dataSize = t.DataSize - 1;
-
- fTypeFlagsAudio = false;
-
- mt.majortype = MEDIATYPE_Audio;
- mt.formattype = FORMAT_WaveFormatEx;
- WAVEFORMATEX* wfe = (WAVEFORMATEX*)mt.AllocFormatBuffer(sizeof(WAVEFORMATEX));
- memset(wfe, 0, sizeof(WAVEFORMATEX));
- wfe->nSamplesPerSec = 44100 * (1 << at.SoundRate) / 8;
- wfe->wBitsPerSample = 8 * (at.SoundSize + 1);
- wfe->nChannels = 1 * (at.SoundType + 1);
-
- switch(at.SoundFormat)
- {
- case 0: // FLV_CODECID_PCM_BE
- mt.subtype = FOURCCMap(wfe->wFormatTag = WAVE_FORMAT_PCM);
- break;
- case 1: // FLV_CODECID_ADPCM
- mt.subtype = FOURCCMap(MAKEFOURCC('A', 'S', 'W', 'F'));
- break;
- case 2: // FLV_CODECID_MP3
- mt.subtype = FOURCCMap(wfe->wFormatTag = WAVE_FORMAT_MP3);
-
- {
- CBaseSplitterFileEx::mpahdr h;
- CMediaType mt2;
- if(m_pFile->Read(h, 4, false, &mt2))
- mt = mt2;
- }
- break;
- case 3 : // FLV_CODECID_PCM_LE
- // ToDo
- break;
- case 4 : // unknown
- break;
- case 5 : // FLV_CODECID_NELLYMOSER_8HZ_MONO
- mt.subtype = FOURCCMap(MAKEFOURCC('N', 'E', 'L', 'L'));
- wfe->nSamplesPerSec = 8000;
- break;
- case 6 : // FLV_CODECID_NELLYMOSER
- mt.subtype = FOURCCMap(MAKEFOURCC('N', 'E', 'L', 'L'));
- break;
- case 10: // FLV_CODECID_AAC
- {
- if(dataSize < 1 || m_pFile->BitRead(8) != 0) // packet type 0 == aac header
- {
- fTypeFlagsAudio = true;
- break;
- }
-
- const int sampleRates[] =
- {
- 96000, 88200, 64000, 48000, 44100, 32000, 24000,
- 22050, 16000, 12000, 11025, 8000, 7350
- };
- const int channels[] =
- {
- 0, 1, 2, 3, 4, 5, 6, 8
- };
-
- __int64 configOffset = m_pFile->GetPos();
- UINT32 configSize = dataSize - 1;
- if(configSize < 2) break;
-
- // Might break depending on the AAC profile, see ff_mpeg4audio_get_config in ffmpeg's mpeg4audio.c
- m_pFile->BitRead(5);
- int iSampleRate = m_pFile->BitRead(4);
- int iChannels = m_pFile->BitRead(4);
- if(iSampleRate > 12 || iChannels > 7) break;
-
- wfe = (WAVEFORMATEX*)mt.AllocFormatBuffer(sizeof(WAVEFORMATEX) + configSize);
- memset(wfe, 0, mt.FormatLength());
- wfe->nSamplesPerSec = sampleRates[iSampleRate];
- wfe->wBitsPerSample = 16;
- wfe->nChannels = channels[iChannels];
- wfe->cbSize = configSize;
-
- m_pFile->Seek(configOffset);
- m_pFile->ByteRead((BYTE*)(wfe + 1), configSize);
-
- mt.subtype = FOURCCMap(wfe->wFormatTag = WAVE_FORMAT_AAC);
- }
-
- }
- }
- }
- else if(t.TagType == 9 && t.DataSize != 0 && fTypeFlagsVideo)
- {
- UNREFERENCED_PARAMETER(vt);
- VideoTag vt;
- if(ReadTag(vt) && vt.FrameType == 1)
- {
- int dataSize = t.DataSize - 1;
-
- fTypeFlagsVideo = false;
- name = L"Video";
-
- mt.majortype = MEDIATYPE_Video;
- mt.formattype = FORMAT_VideoInfo;
- VIDEOINFOHEADER* vih = (VIDEOINFOHEADER*)mt.AllocFormatBuffer(sizeof(VIDEOINFOHEADER));
- memset(vih, 0, sizeof(VIDEOINFOHEADER));
-
- BITMAPINFOHEADER* bih = &vih->bmiHeader;
-
- int w, h, arx, ary;
-
- switch(vt.CodecID)
- {
- case 2: // H.263
- if(m_pFile->BitRead(17) != 1) break;
-
- m_pFile->BitRead(13); // Version (5), TemporalReference (8)
-
- switch(BYTE PictureSize = (BYTE)m_pFile->BitRead(3)) // w00t
- {
- case 0:
- case 1:
- vih->bmiHeader.biWidth = (WORD)m_pFile->BitRead(8 * (PictureSize + 1));
- vih->bmiHeader.biHeight = (WORD)m_pFile->BitRead(8 * (PictureSize + 1));
- break;
- case 2:
- case 3:
- case 4:
- vih->bmiHeader.biWidth = 704 / PictureSize;
- vih->bmiHeader.biHeight = 576 / PictureSize;
- break;
- case 5:
- case 6:
- PictureSize -= 3;
- vih->bmiHeader.biWidth = 640 / PictureSize;
- vih->bmiHeader.biHeight = 480 / PictureSize;
- break;
- }
-
- if(!vih->bmiHeader.biWidth || !vih->bmiHeader.biHeight) break;
-
- mt.subtype = FOURCCMap(vih->bmiHeader.biCompression = '1VLF');
-
- break;
-
- case 5: // VP6 with alpha
- m_pFile->BitRead(24);
- case 4: // VP6
- {
-#ifdef NOVIDEOTWEAK
- m_pFile->BitRead(8);
-#else
- VideoTweak fudge;
- ReadTag(fudge);
-#endif
-
- if(m_pFile->BitRead(1))
- {
- // Delta (inter) frame
- fTypeFlagsVideo = true;
- break;
- }
- m_pFile->BitRead(6);
- bool fSeparatedCoeff = !!m_pFile->BitRead(1);
- m_pFile->BitRead(5);
- int filterHeader = m_pFile->BitRead(2);
- m_pFile->BitRead(1);
- if(fSeparatedCoeff || !filterHeader)
- {
- m_pFile->BitRead(16);
- }
-
- h = m_pFile->BitRead(8) * 16;
- w = m_pFile->BitRead(8) * 16;
-
- ary = m_pFile->BitRead(8) * 16;
- arx = m_pFile->BitRead(8) * 16;
-
- if(arx && arx != w || ary && ary != h)
- {
- VIDEOINFOHEADER2* vih2 = (VIDEOINFOHEADER2*)mt.AllocFormatBuffer(sizeof(VIDEOINFOHEADER2));
- memset(vih2, 0, sizeof(VIDEOINFOHEADER2));
- vih2->dwPictAspectRatioX = arx;
- vih2->dwPictAspectRatioY = ary;
- bih = &vih2->bmiHeader;
- mt.formattype = FORMAT_VideoInfo2;
- vih = (VIDEOINFOHEADER *)vih2;
- }
-
- bih->biWidth = w;
- bih->biHeight = h;
-#ifndef NOVIDEOTWEAK
- SetRect(&vih->rcSource, 0, 0, w - fudge.x, h - fudge.y);
- SetRect(&vih->rcTarget, 0, 0, w - fudge.x, h - fudge.y);
-#endif
-
- mt.subtype = FOURCCMap(bih->biCompression = '4VLF');
-
- break;
- }
- case 7: // H.264
- {
- if(dataSize < 4 || m_pFile->BitRead(8) != 0) // packet type 0 == avc header
- {
- fTypeFlagsVideo = true;
- break;
- }
- m_pFile->BitRead(24); // composition time
-
- __int64 headerOffset = m_pFile->GetPos();
- UINT32 headerSize = dataSize - 4;
- BYTE *headerData = DNew BYTE[headerSize];
-
- m_pFile->ByteRead(headerData, headerSize);
-
- m_pFile->Seek(headerOffset + 9);
-
- mt.formattype = FORMAT_MPEG2Video;
- MPEG2VIDEOINFO* vih = (MPEG2VIDEOINFO*)mt.AllocFormatBuffer(FIELD_OFFSET(MPEG2VIDEOINFO, dwSequenceHeader) + headerSize);
- memset(vih, 0, mt.FormatLength());
- vih->hdr.bmiHeader.biSize = sizeof(vih->hdr.bmiHeader);
- vih->hdr.bmiHeader.biPlanes = 1;
- vih->hdr.bmiHeader.biBitCount = 24;
- vih->dwFlags = (headerData[4] & 0x03) + 1; // nal length size
-
- vih->dwProfile = (BYTE)m_pFile->BitRead(8);
- m_pFile->BitRead(8);
- vih->dwLevel = (BYTE)m_pFile->BitRead(8);
- m_pFile->UExpGolombRead(); // seq_parameter_set_id
- if(vih->dwProfile >= 100) // high profile
- {
- if(m_pFile->UExpGolombRead() == 3) // chroma_format_idc
- m_pFile->BitRead(1); // residue_transform_flag
- m_pFile->UExpGolombRead(); // bit_depth_luma_minus8
- m_pFile->UExpGolombRead(); // bit_depth_chroma_minus8
- m_pFile->BitRead(1); // qpprime_y_zero_transform_bypass_flag
- if(m_pFile->BitRead(1)) // seq_scaling_matrix_present_flag
- for(int i = 0; i < 8; i++)
- if(m_pFile->BitRead(1)) // seq_scaling_list_present_flag
- for(int j = 0, size = i < 6 ? 16 : 64, next = 8; j < size && next != 0; ++j)
- next = (next + m_pFile->SExpGolombRead() + 256) & 255;
- }
- m_pFile->UExpGolombRead(); // log2_max_frame_num_minus4
- UINT64 pic_order_cnt_type = m_pFile->UExpGolombRead();
- if(pic_order_cnt_type == 0)
- {
- m_pFile->UExpGolombRead(); // log2_max_pic_order_cnt_lsb_minus4
- }
- else if(pic_order_cnt_type == 1)
- {
- m_pFile->BitRead(1); // delta_pic_order_always_zero_flag
- m_pFile->SExpGolombRead(); // offset_for_non_ref_pic
- m_pFile->SExpGolombRead(); // offset_for_top_to_bottom_field
- UINT64 num_ref_frames_in_pic_order_cnt_cycle = m_pFile->UExpGolombRead();
- for(int i = 0; i < num_ref_frames_in_pic_order_cnt_cycle; i++)
- m_pFile->SExpGolombRead(); // offset_for_ref_frame[i]
- }
- m_pFile->UExpGolombRead(); // num_ref_frames
- m_pFile->BitRead(1); // gaps_in_frame_num_value_allowed_flag
- UINT64 pic_width_in_mbs_minus1 = m_pFile->UExpGolombRead();
- UINT64 pic_height_in_map_units_minus1 = m_pFile->UExpGolombRead();
- BYTE frame_mbs_only_flag = (BYTE)m_pFile->BitRead(1);
- vih->hdr.bmiHeader.biWidth = vih->hdr.dwPictAspectRatioX = (LONG)((pic_width_in_mbs_minus1 + 1) * 16);
- vih->hdr.bmiHeader.biHeight = vih->hdr.dwPictAspectRatioY = (LONG)((2 - frame_mbs_only_flag) * (pic_height_in_map_units_minus1 + 1) * 16);
-
- BYTE* src = (BYTE*)headerData + 5;
- BYTE* dst = (BYTE*)vih->dwSequenceHeader;
- BYTE* src_end = (BYTE*)headerData + headerSize;
- BYTE* dst_end = (BYTE*)vih->dwSequenceHeader + headerSize;
- int spsCount = *(src++) & 0x1F;
- int ppsCount = -1;
-
- vih->cbSequenceHeader = 0;
-
- while(src < src_end - 1)
- {
- if(spsCount == 0 && ppsCount == -1)
- {
- ppsCount = *(src++);
- continue;
- }
-
- if(spsCount > 0) spsCount--;
- else if(ppsCount > 0) ppsCount--;
- else break;
-
- int len = ((src[0] << 8) | src[1]) + 2;
- if(src + len > src_end || dst + len > dst_end)
- {
- ASSERT(0);
- break;
- }
- memcpy(dst, src, len);
- src += len;
- dst += len;
- vih->cbSequenceHeader += len;
- }
-
- delete[] headerData;
-
- mt.subtype = FOURCCMap(vih->hdr.bmiHeader.biCompression = '1CVA');
-
- break;
- }
- default:
- fTypeFlagsVideo = true;
- }
- }
- }
-
- if(mt.subtype != GUID_NULL)
- {
- CAtlArray<CMediaType> mts;
- mts.Add(mt);
- CAutoPtr<CBaseSplitterOutputPin> pPinOut(DNew CBaseSplitterOutputPin(mts, name, this, this, &hr));
- EXECUTE_ASSERT(SUCCEEDED(AddOutputPin(t.TagType, pPinOut)));
- }
-
- m_pFile->Seek(next);
- }
-
- if(m_pFile->IsRandomAccess())
- {
- __int64 pos = max(m_DataOffset, m_pFile->GetLength() - 256 * 1024);
-
- if(Sync(pos))
- {
- Tag t;
- AudioTag at;
- VideoTag vt;
-
- while(ReadTag(t))
- {
- UINT64 next = m_pFile->GetPos() + t.DataSize;
-
- if(t.TagType == 8 && ReadTag(at) || t.TagType == 9 && ReadTag(vt))
- {
- m_rtDuration = max(m_rtDuration, 10000i64 * t.TimeStamp);
- }
-
- m_pFile->Seek(next);
- }
- }
- }
-
- m_rtNewStop = m_rtStop = m_rtDuration;
-
- return m_pOutputs.GetCount() > 0 ? S_OK : E_FAIL;
+ CheckPointer(pAsyncReader, E_POINTER);
+
+ HRESULT hr = E_FAIL;
+
+ m_pFile.Free();
+ m_pFile.Attach(DNew CBaseSplitterFileEx(pAsyncReader, hr, DEFAULT_CACHE_LENGTH, false));
+ if(!m_pFile) return E_OUTOFMEMORY;
+ if(FAILED(hr)) {m_pFile.Free(); return hr;}
+
+ m_rtNewStart = m_rtCurrent = 0;
+ m_rtNewStop = m_rtStop = m_rtDuration = 0;
+
+ if(m_pFile->BitRead(24) != 'FLV' || m_pFile->BitRead(8) != 1)
+ return E_FAIL;
+
+ EXECUTE_ASSERT(m_pFile->BitRead(5) == 0); // TypeFlagsReserved
+ bool fTypeFlagsAudio = !!m_pFile->BitRead(1);
+ EXECUTE_ASSERT(m_pFile->BitRead(1) == 0); // TypeFlagsReserved
+ bool fTypeFlagsVideo = !!m_pFile->BitRead(1);
+ m_DataOffset = (UINT32)m_pFile->BitRead(32);
+
+ // doh, these flags aren't always telling the truth
+ fTypeFlagsAudio = fTypeFlagsVideo = true;
+
+ Tag t;
+ AudioTag at;
+ VideoTag vt;
+
+ UINT32 prevTagSize = 0;
+ m_IgnorePrevSizes = false;
+
+ m_pFile->Seek(m_DataOffset);
+
+ for(int i = 0; ReadTag(t) && (fTypeFlagsVideo || fTypeFlagsAudio) && i < 100; i++)
+ {
+ UINT64 next = m_pFile->GetPos() + t.DataSize;
+
+ CStringW name;
+
+ CMediaType mt;
+ mt.SetSampleSize(1);
+ mt.subtype = GUID_NULL;
+
+ if (i != 0 && t.PreviousTagSize != prevTagSize) {
+ m_IgnorePrevSizes = true;
+ }
+ prevTagSize = t.DataSize + 11;
+
+ if(t.TagType == 8 && t.DataSize != 0 && fTypeFlagsAudio)
+ {
+ UNREFERENCED_PARAMETER(at);
+ AudioTag at;
+ name = L"Audio";
+
+ if(ReadTag(at))
+ {
+ int dataSize = t.DataSize - 1;
+
+ fTypeFlagsAudio = false;
+
+ mt.majortype = MEDIATYPE_Audio;
+ mt.formattype = FORMAT_WaveFormatEx;
+ WAVEFORMATEX* wfe = (WAVEFORMATEX*)mt.AllocFormatBuffer(sizeof(WAVEFORMATEX));
+ memset(wfe, 0, sizeof(WAVEFORMATEX));
+ wfe->nSamplesPerSec = 44100*(1<<at.SoundRate)/8;
+ wfe->wBitsPerSample = 8*(at.SoundSize+1);
+ wfe->nChannels = 1*(at.SoundType+1);
+
+ switch(at.SoundFormat)
+ {
+ case 0: // FLV_CODECID_PCM_BE
+ mt.subtype = FOURCCMap(wfe->wFormatTag = WAVE_FORMAT_PCM);
+ break;
+ case 1: // FLV_CODECID_ADPCM
+ mt.subtype = FOURCCMap(MAKEFOURCC('A','S','W','F'));
+ break;
+ case 2: // FLV_CODECID_MP3
+ mt.subtype = FOURCCMap(wfe->wFormatTag = WAVE_FORMAT_MP3);
+
+ {
+ CBaseSplitterFileEx::mpahdr h;
+ CMediaType mt2;
+ if(m_pFile->Read(h, 4, false, &mt2))
+ mt = mt2;
+ }
+ break;
+ case 3 : // FLV_CODECID_PCM_LE
+ // ToDo
+ break;
+ case 4 : // unknown
+ break;
+ case 5 : // FLV_CODECID_NELLYMOSER_8HZ_MONO
+ mt.subtype = FOURCCMap(MAKEFOURCC('N','E','L','L'));
+ wfe->nSamplesPerSec = 8000;
+ break;
+ case 6 : // FLV_CODECID_NELLYMOSER
+ mt.subtype = FOURCCMap(MAKEFOURCC('N','E','L','L'));
+ break;
+ case 10: { // FLV_CODECID_AAC
+ if (dataSize < 1 || m_pFile->BitRead(8) != 0) { // packet type 0 == aac header
+ fTypeFlagsAudio = true;
+ break;
+ }
+
+ const int sampleRates[] = {
+ 96000, 88200, 64000, 48000, 44100, 32000, 24000,
+ 22050, 16000, 12000, 11025, 8000, 7350
+ };
+ const int channels[] = {
+ 0, 1, 2, 3, 4, 5, 6, 8
+ };
+
+ __int64 configOffset = m_pFile->GetPos();
+ UINT32 configSize = dataSize - 1;
+ if (configSize < 2) break;
+
+ // Might break depending on the AAC profile, see ff_mpeg4audio_get_config in ffmpeg's mpeg4audio.c
+ m_pFile->BitRead(5);
+ int iSampleRate = m_pFile->BitRead(4);
+ int iChannels = m_pFile->BitRead(4);
+ if (iSampleRate > 12 || iChannels > 7) break;
+
+ wfe = (WAVEFORMATEX*)mt.AllocFormatBuffer(sizeof(WAVEFORMATEX) + configSize);
+ memset(wfe, 0, mt.FormatLength());
+ wfe->nSamplesPerSec = sampleRates[iSampleRate];
+ wfe->wBitsPerSample = 16;
+ wfe->nChannels = channels[iChannels];
+ wfe->cbSize = configSize;
+
+ m_pFile->Seek(configOffset);
+ m_pFile->ByteRead((BYTE*)(wfe+1), configSize);
+
+ mt.subtype = FOURCCMap(wfe->wFormatTag = WAVE_FORMAT_AAC);
+ }
+
+ }
+ }
+ }
+ else if(t.TagType == 9 && t.DataSize != 0 && fTypeFlagsVideo)
+ {
+ UNREFERENCED_PARAMETER(vt);
+ VideoTag vt;
+ if(ReadTag(vt) && vt.FrameType == 1)
+ {
+ int dataSize = t.DataSize - 1;
+
+ fTypeFlagsVideo = false;
+ name = L"Video";
+
+ mt.majortype = MEDIATYPE_Video;
+ mt.formattype = FORMAT_VideoInfo;
+ VIDEOINFOHEADER* vih = (VIDEOINFOHEADER*)mt.AllocFormatBuffer(sizeof(VIDEOINFOHEADER));
+ memset(vih, 0, sizeof(VIDEOINFOHEADER));
+
+ BITMAPINFOHEADER* bih = &vih->bmiHeader;
+
+ int w, h, arx, ary;
+
+ switch(vt.CodecID)
+ {
+ case 2: // H.263
+ if(m_pFile->BitRead(17) != 1) break;
+
+ m_pFile->BitRead(13); // Version (5), TemporalReference (8)
+
+ switch(BYTE PictureSize = (BYTE)m_pFile->BitRead(3)) // w00t
+ {
+ case 0: case 1:
+ vih->bmiHeader.biWidth = (WORD)m_pFile->BitRead(8*(PictureSize+1));
+ vih->bmiHeader.biHeight = (WORD)m_pFile->BitRead(8*(PictureSize+1));
+ break;
+ case 2: case 3: case 4:
+ vih->bmiHeader.biWidth = 704 / PictureSize;
+ vih->bmiHeader.biHeight = 576 / PictureSize;
+ break;
+ case 5: case 6:
+ PictureSize -= 3;
+ vih->bmiHeader.biWidth = 640 / PictureSize;
+ vih->bmiHeader.biHeight = 480 / PictureSize;
+ break;
+ }
+
+ if(!vih->bmiHeader.biWidth || !vih->bmiHeader.biHeight) break;
+
+ mt.subtype = FOURCCMap(vih->bmiHeader.biCompression = '1VLF');
+
+ break;
+
+ case 5: // VP6 with alpha
+ m_pFile->BitRead(24);
+ case 4: { // VP6
+ #ifdef NOVIDEOTWEAK
+ m_pFile->BitRead(8);
+ #else
+ VideoTweak fudge;
+ ReadTag(fudge);
+ #endif
+
+ if (m_pFile->BitRead(1)) {
+ // Delta (inter) frame
+ fTypeFlagsVideo = true;
+ break;
+ }
+ m_pFile->BitRead(6);
+ bool fSeparatedCoeff = !!m_pFile->BitRead(1);
+ m_pFile->BitRead(5);
+ int filterHeader = m_pFile->BitRead(2);
+ m_pFile->BitRead(1);
+ if (fSeparatedCoeff || !filterHeader) {
+ m_pFile->BitRead(16);
+ }
+
+ h = m_pFile->BitRead(8) * 16;
+ w = m_pFile->BitRead(8) * 16;
+
+ ary = m_pFile->BitRead(8) * 16;
+ arx = m_pFile->BitRead(8) * 16;
+
+ if(arx && arx != w || ary && ary != h) {
+ VIDEOINFOHEADER2* vih2 = (VIDEOINFOHEADER2*)mt.AllocFormatBuffer(sizeof(VIDEOINFOHEADER2));
+ memset(vih2, 0, sizeof(VIDEOINFOHEADER2));
+ vih2->dwPictAspectRatioX = arx;
+ vih2->dwPictAspectRatioY = ary;
+ bih = &vih2->bmiHeader;
+ mt.formattype = FORMAT_VideoInfo2;
+ vih = (VIDEOINFOHEADER *)vih2;
+ }
+
+ bih->biWidth = w;
+ bih->biHeight = h;
+ #ifndef NOVIDEOTWEAK
+ SetRect(&vih->rcSource, 0, 0, w - fudge.x, h - fudge.y);
+ SetRect(&vih->rcTarget, 0, 0, w - fudge.x, h - fudge.y);
+ #endif
+
+ mt.subtype = FOURCCMap(bih->biCompression = '4VLF');
+
+ break;
+ }
+ case 7: { // H.264
+ if (dataSize < 4 || m_pFile->BitRead(8) != 0) { // packet type 0 == avc header
+ fTypeFlagsVideo = true;
+ break;
+ }
+ m_pFile->BitRead(24); // composition time
+
+ __int64 headerOffset = m_pFile->GetPos();
+ UINT32 headerSize = dataSize - 4;
+ BYTE *headerData = DNew BYTE[headerSize];
+
+ m_pFile->ByteRead(headerData, headerSize);
+
+ m_pFile->Seek(headerOffset + 9);
+
+ mt.formattype = FORMAT_MPEG2Video;
+ MPEG2VIDEOINFO* vih = (MPEG2VIDEOINFO*)mt.AllocFormatBuffer(FIELD_OFFSET(MPEG2VIDEOINFO, dwSequenceHeader) + headerSize);
+ memset(vih, 0, mt.FormatLength());
+ vih->hdr.bmiHeader.biSize = sizeof(vih->hdr.bmiHeader);
+ vih->hdr.bmiHeader.biPlanes = 1;
+ vih->hdr.bmiHeader.biBitCount = 24;
+ vih->dwFlags = (headerData[4] & 0x03) + 1; // nal length size
+
+ vih->dwProfile = (BYTE)m_pFile->BitRead(8);
+ m_pFile->BitRead(8);
+ vih->dwLevel = (BYTE)m_pFile->BitRead(8);
+ m_pFile->UExpGolombRead(); // seq_parameter_set_id
+ if(vih->dwProfile >= 100) { // high profile
+ if(m_pFile->UExpGolombRead() == 3) // chroma_format_idc
+ m_pFile->BitRead(1); // residue_transform_flag
+ m_pFile->UExpGolombRead(); // bit_depth_luma_minus8
+ m_pFile->UExpGolombRead(); // bit_depth_chroma_minus8
+ m_pFile->BitRead(1); // qpprime_y_zero_transform_bypass_flag
+ if(m_pFile->BitRead(1)) // seq_scaling_matrix_present_flag
+ for(int i = 0; i < 8; i++)
+ if(m_pFile->BitRead(1)) // seq_scaling_list_present_flag
+ for(int j = 0, size = i < 6 ? 16 : 64, next = 8; j < size && next != 0; ++j)
+ next = (next + m_pFile->SExpGolombRead() + 256) & 255;
+ }
+ m_pFile->UExpGolombRead(); // log2_max_frame_num_minus4
+ UINT64 pic_order_cnt_type = m_pFile->UExpGolombRead();
+ if(pic_order_cnt_type == 0) {
+ m_pFile->UExpGolombRead(); // log2_max_pic_order_cnt_lsb_minus4
+ }
+ else if(pic_order_cnt_type == 1) {
+ m_pFile->BitRead(1); // delta_pic_order_always_zero_flag
+ m_pFile->SExpGolombRead(); // offset_for_non_ref_pic
+ m_pFile->SExpGolombRead(); // offset_for_top_to_bottom_field
+ UINT64 num_ref_frames_in_pic_order_cnt_cycle = m_pFile->UExpGolombRead();
+ for(int i = 0; i < num_ref_frames_in_pic_order_cnt_cycle; i++)
+ m_pFile->SExpGolombRead(); // offset_for_ref_frame[i]
+ }
+ m_pFile->UExpGolombRead(); // num_ref_frames
+ m_pFile->BitRead(1); // gaps_in_frame_num_value_allowed_flag
+ UINT64 pic_width_in_mbs_minus1 = m_pFile->UExpGolombRead();
+ UINT64 pic_height_in_map_units_minus1 = m_pFile->UExpGolombRead();
+ BYTE frame_mbs_only_flag = (BYTE)m_pFile->BitRead(1);
+ vih->hdr.bmiHeader.biWidth = vih->hdr.dwPictAspectRatioX = (LONG)((pic_width_in_mbs_minus1 + 1) * 16);
+ vih->hdr.bmiHeader.biHeight = vih->hdr.dwPictAspectRatioY = (LONG)((2 - frame_mbs_only_flag) * (pic_height_in_map_units_minus1 + 1) * 16);
+
+ BYTE* src = (BYTE*)headerData + 5;
+ BYTE* dst = (BYTE*)vih->dwSequenceHeader;
+ BYTE* src_end = (BYTE*)headerData + headerSize;
+ BYTE* dst_end = (BYTE*)vih->dwSequenceHeader + headerSize;
+ int spsCount = *(src++) & 0x1F;
+ int ppsCount = -1;
+
+ vih->cbSequenceHeader = 0;
+
+ while (src < src_end - 1) {
+ if (spsCount == 0 && ppsCount == -1) {
+ ppsCount = *(src++);
+ continue;
+ }
+
+ if (spsCount > 0) spsCount--;
+ else if (ppsCount > 0) ppsCount--;
+ else break;
+
+ int len = ((src[0] << 8) | src[1]) + 2;
+ if(src + len > src_end || dst + len > dst_end) {ASSERT(0); break;}
+ memcpy(dst, src, len);
+ src += len;
+ dst += len;
+ vih->cbSequenceHeader += len;
+ }
+
+ delete[] headerData;
+
+ mt.subtype = FOURCCMap(vih->hdr.bmiHeader.biCompression = '1CVA');
+
+ break;
+ }
+ default:
+ fTypeFlagsVideo = true;
+ }
+ }
+ }
+
+ if(mt.subtype != GUID_NULL)
+ {
+ CAtlArray<CMediaType> mts;
+ mts.Add(mt);
+ CAutoPtr<CBaseSplitterOutputPin> pPinOut(DNew CBaseSplitterOutputPin(mts, name, this, this, &hr));
+ EXECUTE_ASSERT(SUCCEEDED(AddOutputPin(t.TagType, pPinOut)));
+ }
+
+ m_pFile->Seek(next);
+ }
+
+ if(m_pFile->IsRandomAccess())
+ {
+ __int64 pos = max(m_DataOffset, m_pFile->GetLength() - 256 * 1024);
+
+ if(Sync(pos))
+ {
+ Tag t;
+ AudioTag at;
+ VideoTag vt;
+
+ while(ReadTag(t))
+ {
+ UINT64 next = m_pFile->GetPos() + t.DataSize;
+
+ if(t.TagType == 8 && ReadTag(at) || t.TagType == 9 && ReadTag(vt))
+ {
+ m_rtDuration = max(m_rtDuration, 10000i64 * t.TimeStamp);
+ }
+
+ m_pFile->Seek(next);
+ }
+ }
+ }
+
+ m_rtNewStop = m_rtStop = m_rtDuration;
+
+ return m_pOutputs.GetCount() > 0 ? S_OK : E_FAIL;
}
bool CFLVSplitterFilter::DemuxInit()
{
- return true;
+ return true;
}
void CFLVSplitterFilter::DemuxSeek(REFERENCE_TIME rt)
{
- if(!m_rtDuration || rt <= 0)
- {
- m_pFile->Seek(m_DataOffset);
- }
- else if(!m_IgnorePrevSizes)
- {
- NormalSeek(rt);
- }
- else
- {
- AlternateSeek(rt);
- }
+ if(!m_rtDuration || rt <= 0) {
+ m_pFile->Seek(m_DataOffset);
+ }
+ else if (!m_IgnorePrevSizes) {
+ NormalSeek(rt);
+ }
+ else {
+ AlternateSeek(rt);
+ }
}
void CFLVSplitterFilter::NormalSeek(REFERENCE_TIME rt)
{
- bool fAudio = !!GetOutputPin(8);
- bool fVideo = !!GetOutputPin(9);
-
- __int64 pos = m_DataOffset + 1.0 * rt / m_rtDuration * (m_pFile->GetLength() - m_DataOffset);
-
- if(!Sync(pos))
- {
- ASSERT(0);
- m_pFile->Seek(m_DataOffset);
- return;
- }
-
- Tag t;
- AudioTag at;
- VideoTag vt;
-
- while(ReadTag(t))
- {
- if(10000i64 * t.TimeStamp >= rt)
- {
- m_pFile->Seek(m_pFile->GetPos() - 15);
- break;
- }
-
- m_pFile->Seek(m_pFile->GetPos() + t.DataSize);
- }
-
- while(m_pFile->GetPos() >= m_DataOffset && (fAudio || fVideo) && ReadTag(t))
- {
- UINT64 prev = m_pFile->GetPos() - 15 - t.PreviousTagSize - 4;
-
- if(10000i64 * t.TimeStamp <= rt)
- {
- if(t.TagType == 8 && ReadTag(at))
- {
- fAudio = false;
- }
- else if(t.TagType == 9 && ReadTag(vt) && vt.FrameType == 1)
- {
- fVideo = false;
- }
- }
-
- m_pFile->Seek(prev);
- }
-
- if(fAudio || fVideo)
- {
- ASSERT(0);
- m_pFile->Seek(m_DataOffset);
- }
+ bool fAudio = !!GetOutputPin(8);
+ bool fVideo = !!GetOutputPin(9);
+
+ __int64 pos = m_DataOffset + 1.0 * rt / m_rtDuration * (m_pFile->GetLength() - m_DataOffset);
+
+ if(!Sync(pos))
+ {
+ ASSERT(0);
+ m_pFile->Seek(m_DataOffset);
+ return;
+ }
+
+ Tag t;
+ AudioTag at;
+ VideoTag vt;
+
+ while(ReadTag(t))
+ {
+ if(10000i64 * t.TimeStamp >= rt)
+ {
+ m_pFile->Seek(m_pFile->GetPos() - 15);
+ break;
+ }
+
+ m_pFile->Seek(m_pFile->GetPos() + t.DataSize);
+ }
+
+ while(m_pFile->GetPos() >= m_DataOffset && (fAudio || fVideo) && ReadTag(t))
+ {
+ UINT64 prev = m_pFile->GetPos() - 15 - t.PreviousTagSize - 4;
+
+ if(10000i64 * t.TimeStamp <= rt)
+ {
+ if(t.TagType == 8 && ReadTag(at))
+ {
+ fAudio = false;
+ }
+ else if(t.TagType == 9 && ReadTag(vt) && vt.FrameType == 1)
+ {
+ fVideo = false;
+ }
+ }
+
+ m_pFile->Seek(prev);
+ }
+
+ if(fAudio || fVideo)
+ {
+ ASSERT(0);
+ m_pFile->Seek(m_DataOffset);
+ }
}
void CFLVSplitterFilter::AlternateSeek(REFERENCE_TIME rt)
{
- bool hasAudio = !!GetOutputPin(8);
- bool hasVideo = !!GetOutputPin(9);
-
- __int64 estimPos = m_DataOffset + 1.0 * rt / m_rtDuration * (m_pFile->GetLength() - m_DataOffset);
- __int64 seekBack = 256 * 1024;
-
- while(true)
- {
- bool foundAudio = false;
- bool foundVideo = false;
- __int64 bestPos;
-
- estimPos = max(estimPos - seekBack, m_DataOffset);
- seekBack *= 2;
-
- if(Sync(estimPos))
- {
- Tag t;
- AudioTag at;
- VideoTag vt;
-
- while(ReadTag(t) && t.TimeStamp * 10000i64 < rt)
- {
- __int64 cur = m_pFile->GetPos() - 15;
- __int64 next = cur + 15 + t.DataSize;
-
- if(hasAudio && t.TagType == 8 && ReadTag(at))
- {
- foundAudio = true;
- if(!hasVideo) bestPos = cur;
- }
- else if(hasVideo && t.TagType == 9 && ReadTag(vt) && vt.FrameType == 1)
- {
- foundVideo = true;
- bestPos = cur;
- }
-
- m_pFile->Seek(next);
- }
- }
-
- if((hasAudio && !foundAudio) || (hasVideo && !foundVideo))
- {
- if(estimPos == m_DataOffset)
- {
- m_pFile->Seek(m_DataOffset);
- return;
- }
- }
- else
- {
- m_pFile->Seek(bestPos);
- return;
- }
- }
+ bool hasAudio = !!GetOutputPin(8);
+ bool hasVideo = !!GetOutputPin(9);
+
+ __int64 estimPos = m_DataOffset + 1.0 * rt / m_rtDuration * (m_pFile->GetLength() - m_DataOffset);
+ __int64 seekBack = 256 * 1024;
+
+ while (true) {
+ bool foundAudio = false;
+ bool foundVideo = false;
+ __int64 bestPos;
+
+ estimPos = max(estimPos - seekBack, m_DataOffset);
+ seekBack *= 2;
+
+ if (Sync(estimPos)) {
+ Tag t;
+ AudioTag at;
+ VideoTag vt;
+
+ while (ReadTag(t) && t.TimeStamp * 10000i64 < rt) {
+ __int64 cur = m_pFile->GetPos() - 15;
+ __int64 next = cur + 15 + t.DataSize;
+
+ if (hasAudio && t.TagType == 8 && ReadTag(at)) {
+ foundAudio = true;
+ if (!hasVideo) bestPos = cur;
+ }
+ else if (hasVideo && t.TagType == 9 && ReadTag(vt) && vt.FrameType == 1) {
+ foundVideo = true;
+ bestPos = cur;
+ }
+
+ m_pFile->Seek(next);
+ }
+ }
+
+ if ((hasAudio && !foundAudio) || (hasVideo && !foundVideo)) {
+ if (estimPos == m_DataOffset) {
+ m_pFile->Seek(m_DataOffset);
+ return;
+ }
+ }
+ else {
+ m_pFile->Seek(bestPos);
+ return;
+ }
+ }
}
bool CFLVSplitterFilter::DemuxLoop()
{
- HRESULT hr = S_OK;
-
- CAutoPtr<Packet> p;
-
- Tag t;
- AudioTag at;
- VideoTag vt;
-
- while(SUCCEEDED(hr) && !CheckRequest(NULL) && m_pFile->GetRemaining())
- {
- if(!ReadTag(t)) break;
-
- __int64 next = m_pFile->GetPos() + t.DataSize;
-
- if((t.DataSize > 0) && (t.TagType == 8 && ReadTag(at) || t.TagType == 9 && ReadTag(vt)))
- {
- UINT32 tsOffset = 0;
- if(t.TagType == 9 && vt.FrameType == 5) goto NextTag; // video info/command frame
- if(t.TagType == 9 && vt.CodecID == 4) m_pFile->BitRead(8);
- if(t.TagType == 9 && vt.CodecID == 5) m_pFile->BitRead(32);
- if(t.TagType == 9 && vt.CodecID == 7)
- {
- if(m_pFile->BitRead(8) != 1) goto NextTag;
- // Tag timestamps specify decode time, this is the display time offset
- tsOffset = m_pFile->BitRead(24);
- tsOffset = (tsOffset + 0xff800000) ^ 0xff800000; // sign extension
- }
- if(t.TagType == 8 && at.SoundFormat == 10)
- {
- if(m_pFile->BitRead(8) != 1) goto NextTag;
- }
- __int64 dataSize = next - m_pFile->GetPos();
- if(dataSize <= 0) goto NextTag;
- p.Attach(DNew Packet());
- p->TrackNumber = t.TagType;
- p->rtStart = 10000i64 * (t.TimeStamp + tsOffset);
- p->rtStop = p->rtStart + 1;
- p->bSyncPoint = t.TagType == 9 ? vt.FrameType == 1 : true;
- p->SetCount(dataSize);
- m_pFile->ByteRead(p->GetData(), p->GetCount());
- hr = DeliverPacket(p);
- }
+ HRESULT hr = S_OK;
+
+ CAutoPtr<Packet> p;
+
+ Tag t;
+ AudioTag at;
+ VideoTag vt;
+
+ while(SUCCEEDED(hr) && !CheckRequest(NULL) && m_pFile->GetRemaining())
+ {
+ if(!ReadTag(t)) break;
+
+ __int64 next = m_pFile->GetPos() + t.DataSize;
+
+ if((t.DataSize > 0) && (t.TagType == 8 && ReadTag(at) || t.TagType == 9 && ReadTag(vt)))
+ {
+ UINT32 tsOffset = 0;
+ if(t.TagType == 9 && vt.FrameType == 5) goto NextTag; // video info/command frame
+ if(t.TagType == 9 && vt.CodecID == 4) m_pFile->BitRead(8);
+ if(t.TagType == 9 && vt.CodecID == 5) m_pFile->BitRead(32);
+ if(t.TagType == 9 && vt.CodecID == 7) {
+ if (m_pFile->BitRead(8) != 1) goto NextTag;
+ // Tag timestamps specify decode time, this is the display time offset
+ tsOffset = m_pFile->BitRead(24);
+ tsOffset = (tsOffset + 0xff800000) ^ 0xff800000; // sign extension
+ }
+ if(t.TagType == 8 && at.SoundFormat == 10) {
+ if (m_pFile->BitRead(8) != 1) goto NextTag;
+ }
+ __int64 dataSize = next - m_pFile->GetPos();
+ if (dataSize <= 0) goto NextTag;
+ p.Attach(DNew Packet());
+ p->TrackNumber = t.TagType;
+ p->rtStart = 10000i64 * (t.TimeStamp + tsOffset);
+ p->rtStop = p->rtStart + 1;
+ p->bSyncPoint = t.TagType == 9 ? vt.FrameType == 1 : true;
+ p->SetCount(dataSize);
+ m_pFile->ByteRead(p->GetData(), p->GetCount());
+ hr = DeliverPacket(p);
+ }
NextTag:
- m_pFile->Seek(next);
- }
+ m_pFile->Seek(next);
+ }
- return true;
+ return true;
}
//
@@ -792,10 +746,10 @@ NextTag:
//
CFLVSourceFilter::CFLVSourceFilter(LPUNKNOWN pUnk, HRESULT* phr)
- : CFLVSplitterFilter(pUnk, phr)
+ : CFLVSplitterFilter(pUnk, phr)
{
- m_clsid = __uuidof(this);
- m_pInput.Free();
+ m_clsid = __uuidof(this);
+ m_pInput.Free();
}
diff --git a/src/filters/parser/FLVSplitter/FLVSplitter.h b/src/filters/parser/FLVSplitter/FLVSplitter.h
index 3b3b98c40..62ab89abc 100644
--- a/src/filters/parser/FLVSplitter/FLVSplitter.h
+++ b/src/filters/parser/FLVSplitter/FLVSplitter.h
@@ -1,4 +1,4 @@
-/*
+/*
* Copyright (C) 2003-2006 Gabest
* http://www.gabest.org
*
@@ -6,15 +6,15 @@
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2, or (at your option)
* any later version.
- *
+ *
* This Program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with GNU Make; see the file COPYING. If not, write to
- * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
+ * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
* http://www.gnu.org/copyleft/gpl.html
*
*/
@@ -27,68 +27,68 @@
[uuid("47E792CF-0BBE-4F7A-859C-194B0768650A")]
class CFLVSplitterFilter : public CBaseSplitterFilter
{
- UINT32 m_DataOffset;
- bool m_IgnorePrevSizes;
-
- bool Sync(__int64& pos);
-
- struct VideoTweak
- {
- BYTE x;
- BYTE y;
- };
-
- bool ReadTag(VideoTweak& t);
-
- struct Tag
- {
- UINT32 PreviousTagSize;
- BYTE TagType;
- UINT32 DataSize;
- UINT32 TimeStamp;
- UINT32 StreamID;
- };
-
- bool ReadTag(Tag& t);
-
- struct AudioTag
- {
- BYTE SoundFormat;
- BYTE SoundRate;
- BYTE SoundSize;
- BYTE SoundType;
- };
-
- bool ReadTag(AudioTag& at);
-
- struct VideoTag
- {
- BYTE FrameType;
- BYTE CodecID;
- };
-
- bool ReadTag(VideoTag& vt);
-
- void NormalSeek(REFERENCE_TIME rt);
- void AlternateSeek(REFERENCE_TIME rt);
+ UINT32 m_DataOffset;
+ bool m_IgnorePrevSizes;
+
+ bool Sync(__int64& pos);
+
+ struct VideoTweak
+ {
+ BYTE x;
+ BYTE y;
+ };
+
+ bool ReadTag(VideoTweak& t);
+
+ struct Tag
+ {
+ UINT32 PreviousTagSize;
+ BYTE TagType;
+ UINT32 DataSize;
+ UINT32 TimeStamp;
+ UINT32 StreamID;
+ };
+
+ bool ReadTag(Tag& t);
+
+ struct AudioTag
+ {
+ BYTE SoundFormat;
+ BYTE SoundRate;
+ BYTE SoundSize;
+ BYTE SoundType;
+ };
+
+ bool ReadTag(AudioTag& at);
+
+ struct VideoTag
+ {
+ BYTE FrameType;
+ BYTE CodecID;
+ };
+
+ bool ReadTag(VideoTag& vt);
+
+ void NormalSeek(REFERENCE_TIME rt);
+ void AlternateSeek(REFERENCE_TIME rt);
protected:
- CAutoPtr<CBaseSplitterFileEx> m_pFile;
- HRESULT CreateOutputs(IAsyncReader* pAsyncReader);
+ CAutoPtr<CBaseSplitterFileEx> m_pFile;
+ HRESULT CreateOutputs(IAsyncReader* pAsyncReader);
- bool DemuxInit();
- void DemuxSeek(REFERENCE_TIME rt);
- bool DemuxLoop();
+ bool DemuxInit();
+ void DemuxSeek(REFERENCE_TIME rt);
+ bool DemuxLoop();
public:
- CFLVSplitterFilter(LPUNKNOWN pUnk, HRESULT* phr);
+ CFLVSplitterFilter(LPUNKNOWN pUnk, HRESULT* phr);
};
[uuid("C9ECE7B3-1D8E-41F5-9F24-B255DF16C087")]
class CFLVSourceFilter : public CFLVSplitterFilter
{
public:
- CFLVSourceFilter(LPUNKNOWN pUnk, HRESULT* phr);
+ CFLVSourceFilter(LPUNKNOWN pUnk, HRESULT* phr);
};
#include "../../transform/BaseVideoFilter/BaseVideoFilter.h"
diff --git a/src/filters/parser/FLVSplitter/resource.h b/src/filters/parser/FLVSplitter/resource.h
index 1e1d455b0..cf17d77a9 100644
--- a/src/filters/parser/FLVSplitter/resource.h
+++ b/src/filters/parser/FLVSplitter/resource.h
@@ -3,7 +3,7 @@
// Used by FLVSplitter.rc
// Next default values for new objects
-//
+//
#ifdef APSTUDIO_INVOKED
#ifndef APSTUDIO_READONLY_SYMBOLS
#define _APS_NEXT_RESOURCE_VALUE 101
diff --git a/src/filters/parser/FLVSplitter/stdafx.cpp b/src/filters/parser/FLVSplitter/stdafx.cpp
index eb61fa0cc..d6ab481ba 100644
--- a/src/filters/parser/FLVSplitter/stdafx.cpp
+++ b/src/filters/parser/FLVSplitter/stdafx.cpp
@@ -1,4 +1,4 @@
-/*
+/*
* Copyright (C) 2003-2006 Gabest
* http://www.gabest.org
*
@@ -6,15 +6,15 @@
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2, or (at your option)
* any later version.
- *
+ *
* This Program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with GNU Make; see the file COPYING. If not, write to
- * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
+ * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
* http://www.gnu.org/copyleft/gpl.html
*
*/
diff --git a/src/filters/parser/FLVSplitter/stdafx.h b/src/filters/parser/FLVSplitter/stdafx.h
index 089cf8fa0..e8beccd47 100644
--- a/src/filters/parser/FLVSplitter/stdafx.h
+++ b/src/filters/parser/FLVSplitter/stdafx.h
@@ -1,4 +1,4 @@
-/*
+/*
* Copyright (C) 2003-2006 Gabest
* http://www.gabest.org
*
@@ -6,15 +6,15 @@
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2, or (at your option)
* any later version.
- *
+ *
* This Program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with GNU Make; see the file COPYING. If not, write to
- * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
+ * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
* http://www.gnu.org/copyleft/gpl.html
*
*/
diff --git a/src/filters/parser/MP4Splitter/AP4/Source/Codecs/Ap4AdtsParser.cpp b/src/filters/parser/MP4Splitter/AP4/Source/Codecs/Ap4AdtsParser.cpp
index 0a1aaf518..1e46bbcee 100644
--- a/src/filters/parser/MP4Splitter/AP4/Source/Codecs/Ap4AdtsParser.cpp
+++ b/src/filters/parser/MP4Splitter/AP4/Source/Codecs/Ap4AdtsParser.cpp
@@ -40,7 +40,7 @@
#define AP4_ADTS_SYNC_MASK 0xFFF6 /* 12 sync bits plus 2 layer bits */
#define AP4_ADTS_SYNC_PATTERN 0xFFF0 /* 12 sync bits=1 layer=0 */
-const unsigned long
+const unsigned long
AP4_AdtsSamplingFrequencyTable[16] =
{
96000,
@@ -67,15 +67,15 @@ AP4_AdtsSamplingFrequencyTable[16] =
AP4_AdtsHeader::AP4_AdtsHeader(const AP4_UI08* bytes)
{
// fixed part
- m_Id = (bytes[1] & 0x08) >> 3;
+ m_Id = ( bytes[1] & 0x08) >> 3;
m_ProtectionAbsent = bytes[1] & 0x01;
- m_ProfileObjectType = (bytes[2] & 0xC0) >> 6;
- m_SamplingFrequencyIndex = (bytes[2] & 0x3C) >> 2;
- m_ChannelConfiguration = ((bytes[2] & 0x01) << 2) |
+ m_ProfileObjectType = ( bytes[2] & 0xC0) >> 6;
+ m_SamplingFrequencyIndex = ( bytes[2] & 0x3C) >> 2;
+ m_ChannelConfiguration = ((bytes[2] & 0x01) << 2) |
((bytes[3] & 0xC0) >> 6);
// variable part
m_FrameLength = ((unsigned int)(bytes[3] & 0x03) << 11) |
- ((unsigned int)(bytes[4]) << 3) |
+ ((unsigned int)(bytes[4] ) << 3) |
((unsigned int)(bytes[5] & 0xE0) >> 5);
m_RawDataBlocks = bytes[6] & 0x03;
}
@@ -89,15 +89,12 @@ AP4_AdtsHeader::AP4_AdtsHeader(const AP4_UI08* bytes)
bool
AP4_AdtsHeader::MatchFixed(unsigned char* a, unsigned char* b)
{
- if(a[0] == b[0] &&
- a[1] == b[1] &&
- a[2] == b[2] &&
- (a[3] & 0xF0) == (b[3] & 0xF0))
- {
+ if (a[0] == b[0] &&
+ a[1] == b[1] &&
+ a[2] == b[2] &&
+ (a[3] & 0xF0) == (b[3] & 0xF0)) {
return true;
- }
- else
- {
+ } else {
return false;
}
}
@@ -109,14 +106,12 @@ AP4_Result
AP4_AdtsHeader::Check()
{
// check that the sampling frequency index is valid
- if(m_SamplingFrequencyIndex >= 0xD)
- {
+ if (m_SamplingFrequencyIndex >= 0xD) {
return AP4_FAILURE;
}
/* MPEG2 does not use all profiles */
- if(m_Id == 1 && m_ProfileObjectType == 3)
- {
+ if (m_Id == 1 && m_ProfileObjectType == 3) {
return AP4_FAILURE;
}
@@ -152,7 +147,7 @@ AP4_AdtsParser::Reset()
| AP4_AdtsParser::Feed
+----------------------------------------------------------------------*/
AP4_Result
-AP4_AdtsParser::Feed(const AP4_UI08* buffer,
+AP4_AdtsParser::Feed(const AP4_UI08* buffer,
AP4_Size* buffer_size,
AP4_Flags flags)
{
@@ -162,19 +157,18 @@ AP4_AdtsParser::Feed(const AP4_UI08* buffer,
m_Bits.m_Flags = flags;
/* possible shortcut */
- if(buffer == NULL ||
- buffer_size == NULL ||
- *buffer_size == 0)
- {
+ if (buffer == NULL ||
+ buffer_size == NULL ||
+ *buffer_size == 0) {
return AP4_SUCCESS;
}
/* see how much data we can write */
free_space = m_Bits.GetBytesFree();
- if(*buffer_size > free_space) *buffer_size = free_space;
+ if (*buffer_size > free_space) *buffer_size = free_space;
/* write the data */
- return m_Bits.WriteBytes(buffer, *buffer_size);
+ return m_Bits.WriteBytes(buffer, *buffer_size);
}
/*----------------------------------------------------------------------+
@@ -183,30 +177,26 @@ AP4_AdtsParser::Feed(const AP4_UI08* buffer,
AP4_Result
AP4_AdtsParser::FindHeader(AP4_UI08* header)
{
- int available = m_Bits.GetBytesAvailable();
- unsigned int sync = 0;
- long nbr_skipped_bytes = 0;
-
- /* look for the sync pattern */
- while(available-- >= AP4_ADTS_HEADER_SIZE)
- {
- sync = (m_Bits.ReadByte() << 8) | m_Bits.PeekByte();
-
- if((sync & AP4_ADTS_SYNC_MASK) == AP4_ADTS_SYNC_PATTERN)
- {
- /* found a sync pattern, read the rest of the header */
- header[0] = (sync >> 8) & 0xFF;
- m_Bits.ReadBytes(&header[1], AP4_ADTS_HEADER_SIZE - 1);
-
- return AP4_SUCCESS;
- }
- else
- {
- ++ nbr_skipped_bytes;
- }
- }
-
- return AP4_ERROR_NOT_ENOUGH_DATA;
+ int available = m_Bits.GetBytesAvailable();
+ unsigned int sync = 0;
+ long nbr_skipped_bytes = 0;
+
+ /* look for the sync pattern */
+ while (available-- >= AP4_ADTS_HEADER_SIZE) {
+ sync = (m_Bits.ReadByte() << 8) | m_Bits.PeekByte();
+
+ if ((sync & AP4_ADTS_SYNC_MASK) == AP4_ADTS_SYNC_PATTERN) {
+ /* found a sync pattern, read the rest of the header */
+ header[0] = (sync >> 8) & 0xFF;
+ m_Bits.ReadBytes(&header[1], AP4_ADTS_HEADER_SIZE-1);
+
+ return AP4_SUCCESS;
+ } else {
+ ++ nbr_skipped_bytes;
+ }
+ }
+
+ return AP4_ERROR_NOT_ENOUGH_DATA;
}
/*----------------------------------------------------------------------+
@@ -221,85 +211,77 @@ AP4_AdtsParser::FindFrame(AP4_AacFrame& frame)
/* align to the start of the next byte */
m_Bits.ByteAlign();
-
+
/* find a frame header */
result = FindHeader(raw_header);
- if(AP4_FAILED(result)) return result;
+ if (AP4_FAILED(result)) return result;
/* parse the header */
AP4_AdtsHeader adts_header(raw_header);
/* check the header */
result = adts_header.Check();
- if(AP4_FAILED(result)) goto fail;
-
+ if (AP4_FAILED(result)) goto fail;
+
/* check that we have enough data to peek at the next header */
available = AP4_ADTS_HEADER_SIZE + m_Bits.GetBytesAvailable();
- if(m_Bits.m_Flags & AP4_BITSTREAM_FLAG_EOS)
- {
+ if (m_Bits.m_Flags & AP4_BITSTREAM_FLAG_EOS) {
/* we're at the end of the stream, we only need the entire frame */
- if(available < adts_header.m_FrameLength)
- {
+ if (available < adts_header.m_FrameLength) {
return AP4_ERROR_NOT_ENOUGH_DATA;
- }
- }
- else
- {
+ }
+ } else {
/* peek at the header of the next frame */
unsigned char peek_raw_header[AP4_ADTS_HEADER_SIZE];
- if(available < adts_header.m_FrameLength + AP4_ADTS_HEADER_SIZE)
- {
+ if (available < adts_header.m_FrameLength+AP4_ADTS_HEADER_SIZE) {
return AP4_ERROR_NOT_ENOUGH_DATA;
- }
- m_Bits.SkipBytes(adts_header.m_FrameLength - AP4_ADTS_HEADER_SIZE);
+ }
+ m_Bits.SkipBytes(adts_header.m_FrameLength-AP4_ADTS_HEADER_SIZE);
m_Bits.PeekBytes(peek_raw_header, AP4_ADTS_HEADER_SIZE);
- m_Bits.SkipBytes(-((int)adts_header.m_FrameLength - AP4_ADTS_HEADER_SIZE));
+ m_Bits.SkipBytes(-((int)adts_header.m_FrameLength-AP4_ADTS_HEADER_SIZE));
/* check the header */
AP4_AdtsHeader peek_adts_header(peek_raw_header);
result = peek_adts_header.Check();
- if(AP4_FAILED(result)) goto fail;
+ if (AP4_FAILED(result)) goto fail;
/* check that the fixed part of this header is the same as the */
/* fixed part of the previous header */
- if(!AP4_AdtsHeader::MatchFixed(peek_raw_header, raw_header))
- {
+ if (!AP4_AdtsHeader::MatchFixed(peek_raw_header, raw_header)) {
goto fail;
}
}
/* fill in the frame info */
- frame.m_Info.m_Standard = (adts_header.m_Id == 1 ?
- AP4_AAC_STANDARD_MPEG2 :
- AP4_AAC_STANDARD_MPEG4);
- switch(adts_header.m_ProfileObjectType)
- {
- case 0:
- frame.m_Info.m_Profile = AP4_AAC_PROFILE_MAIN;
- break;
-
- case 1:
- frame.m_Info.m_Profile = AP4_AAC_PROFILE_LC;
- break;
-
- case 2:
- frame.m_Info.m_Profile = AP4_AAC_PROFILE_SSR;
- break;
-
- case 3:
- frame.m_Info.m_Profile = AP4_AAC_PROFILE_LTP;
+ frame.m_Info.m_Standard = (adts_header.m_Id == 1 ?
+ AP4_AAC_STANDARD_MPEG2 :
+ AP4_AAC_STANDARD_MPEG4);
+ switch (adts_header.m_ProfileObjectType) {
+ case 0:
+ frame.m_Info.m_Profile = AP4_AAC_PROFILE_MAIN;
+ break;
+
+ case 1:
+ frame.m_Info.m_Profile = AP4_AAC_PROFILE_LC;
+ break;
+
+ case 2:
+ frame.m_Info.m_Profile = AP4_AAC_PROFILE_SSR;
+ break;
+
+ case 3:
+ frame.m_Info.m_Profile = AP4_AAC_PROFILE_LTP;
}
- frame.m_Info.m_FrameLength = adts_header.m_FrameLength - AP4_ADTS_HEADER_SIZE;
+ frame.m_Info.m_FrameLength = adts_header.m_FrameLength-AP4_ADTS_HEADER_SIZE;
frame.m_Info.m_ChannelConfiguration = adts_header.m_ChannelConfiguration;
frame.m_Info.m_SamplingFrequencyIndex = adts_header.m_SamplingFrequencyIndex;
frame.m_Info.m_SamplingFrequency = AP4_AdtsSamplingFrequencyTable[adts_header.m_SamplingFrequencyIndex];
/* skip crc if present */
- if(adts_header.m_ProtectionAbsent == 0)
- {
+ if (adts_header.m_ProtectionAbsent == 0) {
m_Bits.SkipBits(16);
- }
+ }
/* set the frame source */
frame.m_Source = &m_Bits;
@@ -319,7 +301,7 @@ fail:
AP4_Size
AP4_AdtsParser::GetBytesFree()
{
- return (m_Bits.GetBytesFree());
+ return (m_Bits.GetBytesFree());
}
@@ -327,10 +309,10 @@ AP4_AdtsParser::GetBytesFree()
/*----------------------------------------------------------------------+
| AP4_AdtsParser::GetBytesAvailable
+----------------------------------------------------------------------*/
-AP4_Size
+AP4_Size
AP4_AdtsParser::GetBytesAvailable()
{
- return (m_Bits.GetBytesAvailable());
+ return (m_Bits.GetBytesAvailable());
}
diff --git a/src/filters/parser/MP4Splitter/AP4/Source/Codecs/Ap4AdtsParser.h b/src/filters/parser/MP4Splitter/AP4/Source/Codecs/Ap4AdtsParser.h
index 8b5b4e8da..1db5f27b4 100644
--- a/src/filters/parser/MP4Splitter/AP4/Source/Codecs/Ap4AdtsParser.h
+++ b/src/filters/parser/MP4Splitter/AP4/Source/Codecs/Ap4AdtsParser.h
@@ -43,12 +43,11 @@ extern const unsigned long AP4_AdtsSamplingFrequencyTable[16];
/*----------------------------------------------------------------------
| types
+---------------------------------------------------------------------*/
-class AP4_AdtsHeader
-{
+class AP4_AdtsHeader {
public:
// constructor
AP4_AdtsHeader(const AP4_UI08* bytes);
-
+
// methods
AP4_Result Check();
@@ -69,38 +68,33 @@ public:
static bool MatchFixed(unsigned char* a, unsigned char* b);
};
-typedef enum
-{
+typedef enum {
AP4_AAC_STANDARD_MPEG2,
AP4_AAC_STANDARD_MPEG4
} AP4_AacStandard;
-typedef enum
-{
+typedef enum {
AP4_AAC_PROFILE_MAIN,
AP4_AAC_PROFILE_LC,
AP4_AAC_PROFILE_SSR,
AP4_AAC_PROFILE_LTP
} AP4_AacProfile;
-typedef struct
-{
+typedef struct {
AP4_AacStandard m_Standard;
AP4_AacProfile m_Profile;
unsigned int m_SamplingFrequencyIndex;
unsigned long m_SamplingFrequency;
unsigned int m_ChannelConfiguration;
- unsigned int m_FrameLength;
+ unsigned int m_FrameLength;
} AP4_AacFrameInfo;
-typedef struct
-{
+typedef struct {
AP4_BitStream* m_Source;
AP4_AacFrameInfo m_Info;
} AP4_AacFrame;
-class AP4_AdtsParser
-{
+class AP4_AdtsParser {
public:
// constructor and destructor
AP4_AdtsParser();
@@ -108,7 +102,7 @@ public:
// methods
AP4_Result Reset();
- AP4_Result Feed(const AP4_UI08* buffer,
+ AP4_Result Feed(const AP4_UI08* buffer,
AP4_Size* buffer_size,
AP4_Flags flags = 0);
AP4_Result FindFrame(AP4_AacFrame& frame);
diff --git a/src/filters/parser/MP4Splitter/AP4/Source/Codecs/Ap4AvcParser.cpp b/src/filters/parser/MP4Splitter/AP4/Source/Codecs/Ap4AvcParser.cpp
index 3d7608c39..ad568459d 100644
--- a/src/filters/parser/MP4Splitter/AP4/Source/Codecs/Ap4AvcParser.cpp
+++ b/src/filters/parser/MP4Splitter/AP4/Source/Codecs/Ap4AvcParser.cpp
@@ -38,46 +38,26 @@
const char*
AP4_AvcParser::NaluTypeName(unsigned int nalu_type)
{
- switch(nalu_type)
- {
- case 0:
- return "Unspecified";
- case 1:
- return "Coded slice of a non-IDR picture";
- case 2:
- return "Coded slice data partition A";
- case 3:
- return "Coded slice data partition B";
- case 4:
- return "Coded slice data partition C";
- case 5:
- return "Coded slice of an IDR picture";
- case 6:
- return "Supplemental enhancement information (SEI)";
- case 7:
- return "Sequence parameter set";
- case 8:
- return "Picture parameter set";
- case 9:
- return "Access unit delimiter";
- case 10:
- return "End of sequence";
- case 11:
- return "End of stream";
- case 12:
- return "Filler data";
- case 13:
- return "Sequence parameter set extension";
- case 14:
- return "Prefix NAL unit in scalable extension";
- case 15:
- return "Subset sequence parameter set";
- case 19:
- return "Coded slice of an auxiliary coded picture without partitioning";
- case 20:
- return "Coded slice in scalable extension";
- default:
- return NULL;
+ switch (nalu_type) {
+ case 0: return "Unspecified";
+ case 1: return "Coded slice of a non-IDR picture";
+ case 2: return "Coded slice data partition A";
+ case 3: return "Coded slice data partition B";
+ case 4: return "Coded slice data partition C";
+ case 5: return "Coded slice of an IDR picture";
+ case 6: return "Supplemental enhancement information (SEI)";
+ case 7: return "Sequence parameter set";
+ case 8: return "Picture parameter set";
+ case 9: return "Access unit delimiter";
+ case 10: return "End of sequence";
+ case 11: return "End of stream";
+ case 12: return "Filler data";
+ case 13: return "Sequence parameter set extension";
+ case 14: return "Prefix NAL unit in scalable extension";
+ case 15: return "Subset sequence parameter set";
+ case 19: return "Coded slice of an auxiliary coded picture without partitioning";
+ case 20: return "Coded slice in scalable extension";
+ default: return NULL;
}
}
@@ -87,26 +67,16 @@ AP4_AvcParser::NaluTypeName(unsigned int nalu_type)
const char*
AP4_AvcParser::PrimaryPicTypeName(unsigned int primary_pic_type)
{
- switch(primary_pic_type)
- {
- case 0:
- return "I";
- case 1:
- return "I, P";
- case 2:
- return "I, P, B";
- case 3:
- return "SI";
- case 4:
- return "SI, SP";
- case 5:
- return "I, SI";
- case 6:
- return "I, SI, P, SP";
- case 7:
- return "I, SI, P, SP, B";
- default:
- return NULL;
+ switch (primary_pic_type) {
+ case 0: return "I";
+ case 1: return "I, P";
+ case 2: return "I, P, B";
+ case 3: return "SI";
+ case 4: return "SI, SP";
+ case 5: return "I, SI";
+ case 6: return "I, SI, P, SP";
+ case 7: return "I, SI, P, SP, B";
+ default: return NULL;
}
}
@@ -116,30 +86,18 @@ AP4_AvcParser::PrimaryPicTypeName(unsigned int primary_pic_type)
const char*
AP4_AvcParser::SliceTypeName(unsigned int slice_type)
{
- switch(slice_type)
- {
- case 0:
- return "P";
- case 1:
- return "B";
- case 2:
- return "I";
- case 3:
- return "SP";
- case 4:
- return "SI";
- case 5:
- return "P";
- case 6:
- return "B";
- case 7:
- return "I";
- case 8:
- return "SP";
- case 9:
- return "SI";
- default:
- return NULL;
+ switch (slice_type) {
+ case 0: return "P";
+ case 1: return "B";
+ case 2: return "I";
+ case 3: return "SP";
+ case 4: return "SI";
+ case 5: return "P";
+ case 6: return "B";
+ case 7: return "I";
+ case 8: return "SP";
+ case 9: return "SI";
+ default: return NULL;
}
}
@@ -155,9 +113,9 @@ AP4_AvcParser::AP4_AvcParser() :
/*----------------------------------------------------------------------
| AP4_AvcParser::Feed
+---------------------------------------------------------------------*/
-AP4_Result
-AP4_AvcParser::Feed(const void* data,
- AP4_Size data_size,
+AP4_Result
+AP4_AvcParser::Feed(const void* data,
+ AP4_Size data_size,
AP4_Size& bytes_consumed,
const AP4_DataBuffer*& nalu,
bool is_eos)
@@ -165,113 +123,95 @@ AP4_AvcParser::Feed(const void* data,
// default return values
nalu = NULL;
bytes_consumed = 0;
-
+
// iterate the state machine
unsigned int data_offset;
unsigned int payload_start = 0;
unsigned int payload_end = 0;
bool found_nalu = false;
- for(data_offset = 0; data_offset < data_size && !found_nalu; data_offset++)
- {
+ for (data_offset=0; data_offset<data_size && !found_nalu; data_offset++) {
unsigned char byte = ((const unsigned char*)data)[data_offset];
- switch(m_State)
- {
- case STATE_RESET:
- if(byte == 0)
- {
- m_State = STATE_START_CODE_1;
- }
- break;
-
- case STATE_START_CODE_1:
- if(byte == 0)
- {
- m_State = STATE_START_CODE_2;
- }
- else
- {
- m_State = STATE_RESET;
- }
- break;
-
- case STATE_START_CODE_2:
- if(byte == 0) break;
- if(byte == 1)
- {
- m_State = STATE_START_NALU;
- }
- else
- {
- m_State = STATE_RESET;
- }
- break;
-
- case STATE_START_NALU:
- m_Buffer.SetDataSize(0);
- m_ZeroTrail = 0;
- payload_start = payload_end = data_offset;
- m_State = STATE_IN_NALU;
- // FALLTHROUGH
-
- case STATE_IN_NALU:
- if(byte == 0)
- {
- m_ZeroTrail++;
+ switch (m_State) {
+ case STATE_RESET:
+ if (byte == 0) {
+ m_State = STATE_START_CODE_1;
+ }
+ break;
+
+ case STATE_START_CODE_1:
+ if (byte == 0) {
+ m_State = STATE_START_CODE_2;
+ } else {
+ m_State = STATE_RESET;
+ }
break;
- }
- if(m_ZeroTrail >= 2)
- {
- if(byte == 1)
- {
- found_nalu = true;
+
+ case STATE_START_CODE_2:
+ if (byte == 0) break;
+ if (byte == 1) {
m_State = STATE_START_NALU;
+ } else {
+ m_State = STATE_RESET;
}
- else
- {
- payload_end += m_ZeroTrail + 1;
+ break;
+
+ case STATE_START_NALU:
+ m_Buffer.SetDataSize(0);
+ m_ZeroTrail = 0;
+ payload_start = payload_end = data_offset;
+ m_State = STATE_IN_NALU;
+ // FALLTHROUGH
+
+ case STATE_IN_NALU:
+ if (byte == 0) {
+ m_ZeroTrail++;
+ break;
+ }
+ if (m_ZeroTrail >= 2) {
+ if (byte == 1) {
+ found_nalu = true;
+ m_State = STATE_START_NALU;
+ } else {
+ payload_end += m_ZeroTrail+1;
+ }
+ } else {
+ payload_end += m_ZeroTrail+1;
}
- }
- else
- {
- payload_end += m_ZeroTrail + 1;
- }
- m_ZeroTrail = 0;
- break;
+ m_ZeroTrail = 0;
+ break;
}
}
- if(is_eos && m_State == STATE_IN_NALU && data_offset == data_size)
- {
+ if (is_eos && m_State == STATE_IN_NALU && data_offset == data_size) {
found_nalu = true;
m_ZeroTrail = 0;
m_State = STATE_RESET;
}
- if(payload_end > payload_start)
- {
+ if (payload_end > payload_start) {
AP4_Size current_payload_size = m_Buffer.GetDataSize();
- m_Buffer.SetDataSize(m_Buffer.GetDataSize() + (payload_end - payload_start));
- AP4_CopyMemory(((unsigned char *)m_Buffer.UseData()) + current_payload_size,
- ((const unsigned char*)data) + payload_start,
- payload_end - payload_start);
+ m_Buffer.SetDataSize(m_Buffer.GetDataSize()+(payload_end-payload_start));
+ AP4_CopyMemory(((unsigned char *)m_Buffer.UseData())+current_payload_size,
+ ((const unsigned char*)data)+payload_start,
+ payload_end-payload_start);
}
-
+
// compute how many bytes we have consumed
bytes_consumed = data_offset;
-
+
// return the NALU if we found one
- if(found_nalu) nalu = &m_Buffer;
-
+ if (found_nalu) nalu = &m_Buffer;
+
return AP4_SUCCESS;
}
/*----------------------------------------------------------------------
| AP4_AvcParser::Reset
+---------------------------------------------------------------------*/
-AP4_Result
+AP4_Result
AP4_AvcParser::Reset()
{
m_State = STATE_RESET;
m_ZeroTrail = 0;
m_Buffer.SetDataSize(0);
-
+
return AP4_SUCCESS;
}
diff --git a/src/filters/parser/MP4Splitter/AP4/Source/Codecs/Ap4AvcParser.h b/src/filters/parser/MP4Splitter/AP4/Source/Codecs/Ap4AvcParser.h
index 3f9aac33f..ffb626c94 100644
--- a/src/filters/parser/MP4Splitter/AP4/Source/Codecs/Ap4AvcParser.h
+++ b/src/filters/parser/MP4Splitter/AP4/Source/Codecs/Ap4AvcParser.h
@@ -39,15 +39,14 @@
/*----------------------------------------------------------------------
| AP4_AvcParser
+---------------------------------------------------------------------*/
-class AP4_AvcParser
-{
+class AP4_AvcParser {
public:
static const char* NaluTypeName(unsigned int nalu_type);
static const char* PrimaryPicTypeName(unsigned int primary_pic_type);
static const char* SliceTypeName(unsigned int slice_type);
-
+
AP4_AvcParser();
-
+
/**
* Feed some data to the parser and look for the next NAL Unit.
*
@@ -57,34 +56,33 @@ public:
* @param bytes_consumed: Number of bytes from the data buffer that were
* consumed and stored by the parser.
* @param nalu: Reference to a pointer to a buffer object that contains
- * a NAL unit found in the previously fed data, or a NULL pointer if no
+ * a NAL unit found in the previously fed data, or a NULL pointer if no
* NAL unit can be found so far.
* @param eos: Boolean flag that indicates if this buffer is the last
* buffer in the stream/file (End Of Stream).
*
* @result: AP4_SUCCESS is the call succeeds, or an error code if it
* fails.
- *
+ *
* The caller must not feed the same data twice. When this method
* returns, the caller should inspect the value of bytes_consumed and
* advance the input stream source accordingly, such that the next
* buffer passed to this method will be exactly bytes_consumed bytes
* after what was passed in this call.
*/
- AP4_Result Feed(const void* data,
- AP4_Size data_size,
+ AP4_Result Feed(const void* data,
+ AP4_Size data_size,
AP4_Size& bytes_consumed,
const AP4_DataBuffer*& nalu,
- bool eos = false);
-
+ bool eos=false);
+
/**
* Reset the state of the parser (for example, to parse a new stream).
*/
AP4_Result Reset();
-
+
private:
- enum
- {
+ enum {
STATE_RESET,
STATE_START_CODE_1,
STATE_START_CODE_2,
diff --git a/src/filters/parser/MP4Splitter/AP4/Source/Codecs/Ap4BitStream.cpp b/src/filters/parser/MP4Splitter/AP4/Source/Codecs/Ap4BitStream.cpp
index 57a1d8afe..0e1ebd596 100644
--- a/src/filters/parser/MP4Splitter/AP4/Source/Codecs/Ap4BitStream.cpp
+++ b/src/filters/parser/MP4Splitter/AP4/Source/Codecs/Ap4BitStream.cpp
@@ -72,11 +72,11 @@ AP4_BitStream::Reset()
/*----------------------------------------------------------------------
| AP4_BitStream::ByteAlign
+---------------------------------------------------------------------*/
-AP4_Result
+AP4_Result
AP4_BitStream::ByteAlign()
{
unsigned int to_flush = m_BitsCached & 7;
- if(to_flush > 0) SkipBits(to_flush);
+ if (to_flush > 0) SkipBits(to_flush);
return AP4_SUCCESS;
}
@@ -87,11 +87,11 @@ AP4_BitStream::ByteAlign()
AP4_Size
AP4_BitStream::GetContiguousBytesFree()
{
- return
+ return
(m_In < m_Out) ?
(m_Out - m_In - 1) :
(m_Out == 0 ? (AP4_BITSTREAM_BUFFER_SIZE - m_In - 1) :
- (AP4_BITSTREAM_BUFFER_SIZE - m_In));
+ (AP4_BITSTREAM_BUFFER_SIZE - m_In));
}
/*----------------------------------------------------------------------
@@ -100,9 +100,9 @@ AP4_BitStream::GetContiguousBytesFree()
AP4_Size
AP4_BitStream::GetBytesFree()
{
- return
- (m_In < m_Out) ?
- (m_Out - m_In - 1) :
+ return
+ (m_In < m_Out) ?
+ (m_Out - m_In - 1) :
(AP4_BITSTREAM_BUFFER_SIZE + (m_Out - m_In) - 1);
}
@@ -110,38 +110,33 @@ AP4_BitStream::GetBytesFree()
| AP4_BitStream::WriteBytes
+----------------------------------------------------------------------*/
AP4_Result
-AP4_BitStream::WriteBytes(const AP4_UI08* bytes,
+AP4_BitStream::WriteBytes(const AP4_UI08* bytes,
AP4_Size byte_count)
{
/* check parameters */
- if(byte_count == 0) return AP4_SUCCESS;
- if(bytes == NULL) return AP4_ERROR_INVALID_PARAMETERS;
+ if (byte_count == 0) return AP4_SUCCESS;
+ if (bytes == NULL) return AP4_ERROR_INVALID_PARAMETERS;
/* check that we have enough space */
- if(GetBytesFree() < byte_count)
- {
+ if (GetBytesFree() < byte_count) {
return AP4_FAILURE;
}
/* write the bytes */
- if(m_In < m_Out)
- {
- AP4_CopyMemory(m_Buffer + m_In, bytes, byte_count);
+ if (m_In < m_Out) {
+ AP4_CopyMemory(m_Buffer+m_In, bytes, byte_count);
AP4_BITSTREAM_POINTER_ADD(m_In, byte_count);
- }
- else
- {
+ } else {
unsigned int chunk = AP4_BITSTREAM_BUFFER_SIZE - m_In;
- if(chunk > byte_count) chunk = byte_count;
+ if (chunk > byte_count) chunk = byte_count;
- AP4_CopyMemory(m_Buffer + m_In, bytes, chunk);
+ AP4_CopyMemory(m_Buffer+m_In, bytes, chunk);
AP4_BITSTREAM_POINTER_ADD(m_In, chunk);
- if(chunk != byte_count)
- {
- AP4_CopyMemory(m_Buffer + m_In,
- bytes + chunk, byte_count - chunk);
- AP4_BITSTREAM_POINTER_ADD(m_In, byte_count - chunk);
+ if (chunk != byte_count) {
+ AP4_CopyMemory(m_Buffer+m_In,
+ bytes+chunk, byte_count-chunk);
+ AP4_BITSTREAM_POINTER_ADD(m_In, byte_count-chunk);
}
}
@@ -154,8 +149,8 @@ AP4_BitStream::WriteBytes(const AP4_UI08* bytes,
AP4_Size
AP4_BitStream::GetContiguousBytesAvailable()
{
- return
- (m_Out <= m_In) ?
+ return
+ (m_Out <= m_In) ?
(m_In - m_Out) :
(AP4_BITSTREAM_BUFFER_SIZE - m_Out);
}
@@ -166,8 +161,8 @@ AP4_BitStream::GetContiguousBytesAvailable()
AP4_Size
AP4_BitStream::GetBytesAvailable()
{
- return
- (m_Out <= m_In) ?
+ return
+ (m_Out <= m_In) ?
(m_In - m_Out) :
(m_In + (AP4_BITSTREAM_BUFFER_SIZE - m_Out));
}
@@ -176,105 +171,90 @@ AP4_BitStream::GetBytesAvailable()
| AP4_BitStream::ReadBytes
+----------------------------------------------------------------------*/
AP4_Result
-AP4_BitStream::ReadBytes(AP4_UI08* bytes,
+AP4_BitStream::ReadBytes(AP4_UI08* bytes,
AP4_Size byte_count)
{
- if(byte_count == 0 || bytes == NULL)
- {
- return AP4_ERROR_INVALID_PARAMETERS;
- }
-
- /* Gets bytes from the cache */
- ByteAlign();
- while(m_BitsCached > 0 && byte_count > 0)
- {
- *bytes = ReadBits(8);
- ++ bytes;
- -- byte_count;
- }
-
- /* Get other bytes */
- if(byte_count > 0)
- {
- if(m_Out < m_In)
- {
- AP4_CopyMemory(bytes, m_Buffer + m_Out, byte_count);
- AP4_BITSTREAM_POINTER_ADD(m_Out, byte_count);
- }
- else
- {
- unsigned int chunk = AP4_BITSTREAM_BUFFER_SIZE - m_Out;
- if(chunk >= byte_count) chunk = byte_count;
-
- AP4_CopyMemory(bytes, m_Buffer + m_Out, chunk);
- AP4_BITSTREAM_POINTER_ADD(m_Out, chunk);
-
- if(chunk != byte_count)
- {
- AP4_CopyMemory(bytes + chunk,
- m_Buffer + m_Out,
- byte_count - chunk);
- AP4_BITSTREAM_POINTER_ADD(m_Out, byte_count - chunk);
- }
- }
- }
-
- return AP4_SUCCESS;
+ if (byte_count == 0 || bytes == NULL) {
+ return AP4_ERROR_INVALID_PARAMETERS;
+ }
+
+ /* Gets bytes from the cache */
+ ByteAlign();
+ while (m_BitsCached > 0 && byte_count > 0) {
+ *bytes = ReadBits(8);
+ ++ bytes;
+ -- byte_count;
+ }
+
+ /* Get other bytes */
+ if (byte_count > 0) {
+ if (m_Out < m_In) {
+ AP4_CopyMemory(bytes, m_Buffer + m_Out, byte_count);
+ AP4_BITSTREAM_POINTER_ADD(m_Out, byte_count);
+ } else {
+ unsigned int chunk = AP4_BITSTREAM_BUFFER_SIZE - m_Out;
+ if (chunk >= byte_count) chunk = byte_count;
+
+ AP4_CopyMemory(bytes, m_Buffer+m_Out, chunk);
+ AP4_BITSTREAM_POINTER_ADD(m_Out, chunk);
+
+ if (chunk != byte_count) {
+ AP4_CopyMemory(bytes+chunk,
+ m_Buffer+m_Out,
+ byte_count-chunk);
+ AP4_BITSTREAM_POINTER_ADD(m_Out, byte_count-chunk);
+ }
+ }
+ }
+
+ return AP4_SUCCESS;
}
/*----------------------------------------------------------------------+
| AP4_BitStream::PeekBytes
+----------------------------------------------------------------------*/
AP4_Result
-AP4_BitStream::PeekBytes(AP4_UI08* bytes,
+AP4_BitStream::PeekBytes(AP4_UI08* bytes,
AP4_Size byte_count)
{
- int bits_cached_byte;
-
- if(byte_count == 0 || bytes == NULL)
- {
- return AP4_ERROR_INVALID_PARAMETERS;
- }
-
- /* Gets bytes from the cache */
- bits_cached_byte = m_BitsCached & ~7;
- while(bits_cached_byte > 0 && byte_count > 0)
- {
- *bytes = (m_Cache >> bits_cached_byte) & 0xFF;
- ++ bytes;
- -- byte_count;
- bits_cached_byte -= 8;
- }
-
- /* Get other bytes */
- if(byte_count > 0)
- {
- if(m_In > m_Out)
- {
- AP4_CopyMemory(bytes, m_Buffer + m_Out, byte_count);
- }
- else
- {
- unsigned int out = m_Out;
- unsigned int chunk = AP4_BITSTREAM_BUFFER_SIZE - out;
- if(chunk >= byte_count)
- {
- chunk = byte_count;
- }
-
- AP4_CopyMemory(bytes, m_Buffer + out, chunk);
- AP4_BITSTREAM_POINTER_ADD(out, chunk);
-
- if(chunk != byte_count)
- {
- AP4_CopyMemory(bytes + chunk,
- m_Buffer + out,
- byte_count - chunk);
- }
- }
- }
-
- return AP4_SUCCESS;
+ int bits_cached_byte;
+
+ if (byte_count == 0 || bytes == NULL) {
+ return AP4_ERROR_INVALID_PARAMETERS;
+ }
+
+ /* Gets bytes from the cache */
+ bits_cached_byte = m_BitsCached & ~7;
+ while (bits_cached_byte > 0 && byte_count > 0) {
+ *bytes = (m_Cache >> bits_cached_byte) & 0xFF;
+ ++ bytes;
+ -- byte_count;
+ bits_cached_byte -= 8;
+ }
+
+ /* Get other bytes */
+ if (byte_count > 0) {
+ if (m_In > m_Out) {
+ AP4_CopyMemory(bytes, m_Buffer + m_Out, byte_count);
+ } else {
+ unsigned int out = m_Out;
+ unsigned int chunk = AP4_BITSTREAM_BUFFER_SIZE - out;
+ if (chunk >= byte_count) {
+ chunk = byte_count;
+ }
+
+ AP4_CopyMemory(bytes, m_Buffer+out, chunk);
+ AP4_BITSTREAM_POINTER_ADD(out, chunk);
+
+ if (chunk != byte_count) {
+ AP4_CopyMemory(bytes+chunk,
+ m_Buffer+out,
+ byte_count-chunk);
+ }
+ }
+ }
+
+ return AP4_SUCCESS;
}
/*----------------------------------------------------------------------+
diff --git a/src/filters/parser/MP4Splitter/AP4/Source/Codecs/Ap4BitStream.h b/src/filters/parser/MP4Splitter/AP4/Source/Codecs/Ap4BitStream.h
index 5697e86d9..c0bb0566e 100644
--- a/src/filters/parser/MP4Splitter/AP4/Source/Codecs/Ap4BitStream.h
+++ b/src/filters/parser/MP4Splitter/AP4/Source/Codecs/Ap4BitStream.h
@@ -40,7 +40,7 @@
+---------------------------------------------------------------------*/
const int AP4_ERROR_BASE_BITSTREAM = -10000;
-// the max frame size we can handle
+// the max frame size we can handle
const unsigned int AP4_BITSTREAM_BUFFER_SIZE = 8192;
// flags
@@ -100,7 +100,7 @@ private:
// methods
AP4_BitsWord ReadCache() const;
};
-
+
/*----------------------------------------------------------------------
| macros
+---------------------------------------------------------------------*/
@@ -121,31 +121,28 @@ private:
inline AP4_BitsWord
AP4_BitStream::ReadCache() const
{
- unsigned int pos = m_Out;
- AP4_BitsWord cache;
+ unsigned int pos = m_Out;
+ AP4_BitsWord cache;
#if AP4_WORD_BITS != 32
#error unsupported word size /* 64 and other word size not yet implemented */
#endif
- if(pos <= AP4_BITSTREAM_BUFFER_SIZE - AP4_WORD_BYTES)
- {
- unsigned char* out_ptr = &m_Buffer[pos];
- cache = (((AP4_BitsWord) out_ptr[0]) << 24)
- | (((AP4_BitsWord) out_ptr[1]) << 16)
- | (((AP4_BitsWord) out_ptr[2]) << 8)
- | (((AP4_BitsWord) out_ptr[3]));
- }
- else
- {
- unsigned char* buf_ptr = m_Buffer;
- cache = (((AP4_BitsWord) buf_ptr[ pos ]) << 24)
- | (((AP4_BitsWord) buf_ptr[AP4_BITSTREAM_POINTER_OFFSET(pos, 1)]) << 16)
- | (((AP4_BitsWord) buf_ptr[AP4_BITSTREAM_POINTER_OFFSET(pos, 2)]) << 8)
- | (((AP4_BitsWord) buf_ptr[AP4_BITSTREAM_POINTER_OFFSET(pos, 3)]));
- }
-
- return cache;
+ if (pos <= AP4_BITSTREAM_BUFFER_SIZE - AP4_WORD_BYTES) {
+ unsigned char* out_ptr = &m_Buffer[pos];
+ cache = (((AP4_BitsWord) out_ptr[0]) << 24)
+ | (((AP4_BitsWord) out_ptr[1]) << 16)
+ | (((AP4_BitsWord) out_ptr[2]) << 8)
+ | (((AP4_BitsWord) out_ptr[3]) );
+ } else {
+ unsigned char* buf_ptr = m_Buffer;
+ cache = (((AP4_BitsWord) buf_ptr[ pos ]) << 24)
+ | (((AP4_BitsWord) buf_ptr[AP4_BITSTREAM_POINTER_OFFSET (pos, 1)]) << 16)
+ | (((AP4_BitsWord) buf_ptr[AP4_BITSTREAM_POINTER_OFFSET (pos, 2)]) << 8)
+ | (((AP4_BitsWord) buf_ptr[AP4_BITSTREAM_POINTER_OFFSET (pos, 3)]) );
+ }
+
+ return cache;
}
/*----------------------------------------------------------------------
@@ -155,14 +152,11 @@ inline AP4_UI32
AP4_BitStream::ReadBits(unsigned int n)
{
AP4_BitsWord result;
- if(m_BitsCached >= n)
- {
+ if (m_BitsCached >= n) {
/* we have enough bits in the cache to satisfy the request */
m_BitsCached -= n;
result = (m_Cache >> m_BitsCached) & AP4_BIT_MASK(n);
- }
- else
- {
+ } else {
/* not enough bits in the cache */
AP4_BitsWord word;
@@ -192,8 +186,7 @@ inline int
AP4_BitStream::ReadBit()
{
AP4_BitsWord result;
- if(m_BitsCached == 0)
- {
+ if (m_BitsCached == 0) {
/* the cache is empty */
/* read the next word into the cache */
@@ -203,9 +196,7 @@ AP4_BitStream::ReadBit()
/* return the first bit */
result = m_Cache >> (AP4_WORD_BITS - 1);
- }
- else
- {
+ } else {
/* get the bit from the cache */
result = (m_Cache >> (--m_BitsCached)) & 1;
}
@@ -218,21 +209,18 @@ AP4_BitStream::ReadBit()
inline AP4_UI32
AP4_BitStream::PeekBits(unsigned int n)
{
- /* we have enough bits in the cache to satisfy the request */
- if(m_BitsCached >= n)
- {
- return (m_Cache >> (m_BitsCached - n)) & AP4_BIT_MASK(n);
- }
- else
- {
- /* not enough bits in the cache, read the next word */
- AP4_BitsWord word = ReadCache();
-
- /* combine the new word and the cache, and update the state */
- AP4_BitsWord cache = m_Cache & AP4_BIT_MASK(m_BitsCached);
- n -= m_BitsCached;
- return (word >> (AP4_WORD_BITS - n)) | (cache << n);
- }
+ /* we have enough bits in the cache to satisfy the request */
+ if (m_BitsCached >= n) {
+ return (m_Cache >> (m_BitsCached - n)) & AP4_BIT_MASK(n);
+ } else {
+ /* not enough bits in the cache, read the next word */
+ AP4_BitsWord word = ReadCache();
+
+ /* combine the new word and the cache, and update the state */
+ AP4_BitsWord cache = m_Cache & AP4_BIT_MASK(m_BitsCached);
+ n -= m_BitsCached;
+ return (word >> (AP4_WORD_BITS - n)) | (cache << n);
+ }
}
/*----------------------------------------------------------------------
@@ -241,20 +229,17 @@ AP4_BitStream::PeekBits(unsigned int n)
inline int
AP4_BitStream::PeekBit()
{
- /* the cache is empty */
- if(m_BitsCached == 0)
- {
- /* read the next word into the cache */
- AP4_BitsWord cache = ReadCache();
-
- /* return the first bit */
- return cache >> (AP4_WORD_BITS - 1);
- }
- else
- {
- /* get the bit from the cache */
- return (m_Cache >> (m_BitsCached - 1)) & 1;
- }
+ /* the cache is empty */
+ if (m_BitsCached == 0) {
+ /* read the next word into the cache */
+ AP4_BitsWord cache = ReadCache();
+
+ /* return the first bit */
+ return cache >> (AP4_WORD_BITS - 1);
+ } else {
+ /* get the bit from the cache */
+ return (m_Cache >> (m_BitsCached-1)) & 1;
+ }
}
/*----------------------------------------------------------------------
@@ -263,30 +248,23 @@ AP4_BitStream::PeekBit()
inline void
AP4_BitStream::SkipBits(unsigned int n)
{
- if(n <= m_BitsCached)
- {
- m_BitsCached -= n;
- }
- else
- {
- n -= m_BitsCached;
- while(n >= AP4_WORD_BITS)
- {
- m_Out = AP4_BITSTREAM_POINTER_OFFSET(m_Out, AP4_WORD_BYTES);
- n -= AP4_WORD_BITS;
- }
- if(n)
- {
- m_Cache = ReadCache();
- m_BitsCached = AP4_WORD_BITS - n;
- m_Out = AP4_BITSTREAM_POINTER_OFFSET(m_Out, AP4_WORD_BYTES);
- }
- else
- {
- m_BitsCached = 0;
- m_Cache = 0;
- }
- }
+ if (n <= m_BitsCached) {
+ m_BitsCached -= n;
+ } else {
+ n -= m_BitsCached;
+ while (n >= AP4_WORD_BITS) {
+ m_Out = AP4_BITSTREAM_POINTER_OFFSET(m_Out, AP4_WORD_BYTES);
+ n -= AP4_WORD_BITS;
+ }
+ if (n) {
+ m_Cache = ReadCache();
+ m_BitsCached = AP4_WORD_BITS-n;
+ m_Out = AP4_BITSTREAM_POINTER_OFFSET(m_Out, AP4_WORD_BYTES);
+ } else {
+ m_BitsCached = 0;
+ m_Cache = 0;
+ }
+ }
}
/*----------------------------------------------------------------------
@@ -295,16 +273,13 @@ AP4_BitStream::SkipBits(unsigned int n)
inline void
AP4_BitStream::SkipBit()
{
- if(m_BitsCached == 0)
- {
- m_Cache = ReadCache();
- m_Out = AP4_BITSTREAM_POINTER_OFFSET(m_Out, AP4_WORD_BYTES);
- m_BitsCached = AP4_WORD_BITS - 1;
- }
- else
- {
- --m_BitsCached;
- }
+ if (m_BitsCached == 0) {
+ m_Cache = ReadCache();
+ m_Out = AP4_BITSTREAM_POINTER_OFFSET(m_Out, AP4_WORD_BYTES);
+ m_BitsCached = AP4_WORD_BITS - 1;
+ } else {
+ --m_BitsCached;
+ }
}
/*----------------------------------------------------------------------
@@ -313,8 +288,8 @@ AP4_BitStream::SkipBit()
inline AP4_UI08
AP4_BitStream::ReadByte()
{
- SkipBits(m_BitsCached & 7);
- return ReadBits(8);
+ SkipBits(m_BitsCached & 7);
+ return ReadBits(8);
}
/*----------------------------------------------------------------------
@@ -323,11 +298,11 @@ AP4_BitStream::ReadByte()
inline AP4_UI08
AP4_BitStream::PeekByte()
{
- int extra_bits = m_BitsCached & 7;
- int data = PeekBits(extra_bits + 8);
- int byte = data & 0xFF;
+ int extra_bits = m_BitsCached & 7;
+ int data = PeekBits(extra_bits + 8);
+ int byte = data & 0xFF;
- return byte;
+ return byte;
}
#endif // _AP4_BIT_STREAM_H_
diff --git a/src/filters/parser/MP4Splitter/AP4/Source/Codecs/Ap4Mp4AudioInfo.cpp b/src/filters/parser/MP4Splitter/AP4/Source/Codecs/Ap4Mp4AudioInfo.cpp
index b08f13cf7..a054f0c97 100644
--- a/src/filters/parser/MP4Splitter/AP4/Source/Codecs/Ap4Mp4AudioInfo.cpp
+++ b/src/filters/parser/MP4Splitter/AP4/Source/Codecs/Ap4Mp4AudioInfo.cpp
@@ -40,9 +40,9 @@
const unsigned int AP4_AAC_MAX_SAMPLING_FREQUENCY_INDEX = 12;
static const unsigned int AP4_AacSamplingFreqTable[13] =
{
- 96000, 88200, 64000, 48000,
- 44100, 32000, 24000, 22050,
- 16000, 12000, 11025, 8000,
+ 96000, 88200, 64000, 48000,
+ 44100, 32000, 24000, 22050,
+ 16000, 12000, 11025, 8000,
7350
};
@@ -53,30 +53,25 @@ class AP4_Mp4AudioDsiParser
{
public:
AP4_Mp4AudioDsiParser(const AP4_UI08* data, AP4_Size data_size) :
- m_Data(data, data_size),
+ m_Data(data, data_size),
m_Position(0) {}
-
- AP4_Size BitsLeft()
- {
- return 8 * m_Data.GetDataSize() - m_Position;
- }
- AP4_UI32 ReadBits(unsigned int n)
- {
+
+ AP4_Size BitsLeft() { return 8*m_Data.GetDataSize()-m_Position; }
+ AP4_UI32 ReadBits(unsigned int n) {
AP4_UI32 result = 0;
const AP4_UI08* data = m_Data.GetData();
- while(n)
- {
- unsigned int bits_avail = 8 - (m_Position % 8);
+ while (n) {
+ unsigned int bits_avail = 8-(m_Position%8);
unsigned int chunk_size = bits_avail >= n ? n : bits_avail;
- unsigned int chunk_bits = (((unsigned int)(data[m_Position/8])) >> (bits_avail - chunk_size)) & ((1 << chunk_size) - 1);
+ unsigned int chunk_bits = (((unsigned int)(data[m_Position/8]))>>(bits_avail-chunk_size))&((1<<chunk_size)-1);
result = (result << chunk_size) | chunk_bits;
n -= chunk_size;
m_Position += chunk_size;
}
-
+
return result;
}
-
+
private:
AP4_DataBuffer m_Data;
unsigned int m_Position;
@@ -117,14 +112,13 @@ AP4_Mp4AudioDecoderConfig::Reset()
AP4_Result
AP4_Mp4AudioDecoderConfig::ParseAudioObjectType(AP4_Mp4AudioDsiParser& parser, AP4_UI08& object_type)
{
- if(parser.BitsLeft() < 5) return AP4_ERROR_INVALID_FORMAT;
+ if (parser.BitsLeft() < 5) return AP4_ERROR_INVALID_FORMAT;
object_type = (AP4_UI08)parser.ReadBits(5);
- if((int)object_type == 31)
- {
- if(parser.BitsLeft() < 6) return AP4_ERROR_INVALID_FORMAT;
- object_type = (AP4_UI08)(32 + parser.ReadBits(6));
- }
- return AP4_SUCCESS;
+ if ((int)object_type == 31) {
+ if (parser.BitsLeft() < 6) return AP4_ERROR_INVALID_FORMAT;
+ object_type = (AP4_UI08)(32 + parser.ReadBits(6));
+ }
+ return AP4_SUCCESS;
}
/*----------------------------------------------------------------------
@@ -133,24 +127,20 @@ AP4_Mp4AudioDecoderConfig::ParseAudioObjectType(AP4_Mp4AudioDsiParser& parser, A
AP4_Result
AP4_Mp4AudioDecoderConfig::ParseGASpecificInfo(AP4_Mp4AudioDsiParser& parser)
{
- if(parser.BitsLeft() < 2) return AP4_ERROR_INVALID_FORMAT;
- m_FrameLengthFlag = (parser.ReadBits(1) == 1);
- m_DependsOnCoreCoder = (parser.ReadBits(1) == 1);
- if(m_DependsOnCoreCoder)
- {
- if(parser.BitsLeft() < 14) return AP4_ERROR_INVALID_FORMAT;
- m_CoreCoderDelay = parser.ReadBits(14);
- }
- else
- {
+ if (parser.BitsLeft() < 2) return AP4_ERROR_INVALID_FORMAT;
+ m_FrameLengthFlag = (parser.ReadBits(1) == 1);
+ m_DependsOnCoreCoder = (parser.ReadBits(1) == 1);
+ if (m_DependsOnCoreCoder) {
+ if (parser.BitsLeft() < 14) return AP4_ERROR_INVALID_FORMAT;
+ m_CoreCoderDelay = parser.ReadBits(14);
+ } else {
m_CoreCoderDelay = 0;
}
- if(parser.BitsLeft() < 1) return AP4_ERROR_INVALID_FORMAT;
- parser.ReadBits(1); /* extensionFlag */
- if(m_ChannelConfiguration == CHANNEL_CONFIG_NONE)
- {
- /*program_config_element (); */
- }
+ if (parser.BitsLeft() < 1) return AP4_ERROR_INVALID_FORMAT;
+ parser.ReadBits(1); /* extensionFlag */
+ if (m_ChannelConfiguration == CHANNEL_CONFIG_NONE) {
+ /*program_config_element (); */
+ }
return AP4_SUCCESS;
}
@@ -159,30 +149,23 @@ AP4_Mp4AudioDecoderConfig::ParseGASpecificInfo(AP4_Mp4AudioDsiParser& parser)
| AP4_Mp4AudioDecoderConfig::ParseSamplingFrequency
+---------------------------------------------------------------------*/
AP4_Result
-AP4_Mp4AudioDecoderConfig::ParseSamplingFrequency(AP4_Mp4AudioDsiParser& parser,
- unsigned int& sampling_frequency_index,
- unsigned int& sampling_frequency)
+AP4_Mp4AudioDecoderConfig::ParseSamplingFrequency(AP4_Mp4AudioDsiParser& parser,
+ unsigned int& sampling_frequency_index,
+ unsigned int& sampling_frequency)
{
- if(parser.BitsLeft() < 4)
- {
+ if (parser.BitsLeft() < 4) {
return AP4_ERROR_INVALID_FORMAT;
}
sampling_frequency_index = parser.ReadBits(4);
- if(sampling_frequency_index == 0xF)
- {
- if(parser.BitsLeft() < 24)
- {
+ if (sampling_frequency_index == 0xF) {
+ if (parser.BitsLeft() < 24) {
return AP4_ERROR_INVALID_FORMAT;
}
sampling_frequency = parser.ReadBits(24);
- }
- else if(sampling_frequency_index <= AP4_AAC_MAX_SAMPLING_FREQUENCY_INDEX)
- {
+ } else if (sampling_frequency_index <= AP4_AAC_MAX_SAMPLING_FREQUENCY_INDEX) {
sampling_frequency = AP4_AacSamplingFreqTable[sampling_frequency_index];
- }
- else
- {
+ } else {
sampling_frequency = 0;
return AP4_ERROR_INVALID_FORMAT;
}
@@ -194,7 +177,7 @@ AP4_Mp4AudioDecoderConfig::ParseSamplingFrequency(AP4_Mp4AudioDsiParser& parser,
| AP4_Mp4AudioDecoderConfig::Parse
+---------------------------------------------------------------------*/
AP4_Result
-AP4_Mp4AudioDecoderConfig::Parse(const unsigned char* data,
+AP4_Mp4AudioDecoderConfig::Parse(const unsigned char* data,
AP4_Size data_size)
{
AP4_Result result;
@@ -202,73 +185,65 @@ AP4_Mp4AudioDecoderConfig::Parse(const unsigned char* data,
// default config
Reset();
-
+
// parse the audio object type
- result = ParseAudioObjectType(bits, m_ObjectType);
- if(AP4_FAILED(result)) return result;
+ result = ParseAudioObjectType(bits, m_ObjectType);
+ if (AP4_FAILED(result)) return result;
// parse the sampling frequency
- result = ParseSamplingFrequency(bits,
- m_SamplingFrequencyIndex,
+ result = ParseSamplingFrequency(bits,
+ m_SamplingFrequencyIndex,
m_SamplingFrequency);
- if(AP4_FAILED(result)) return result;
+ if (AP4_FAILED(result)) return result;
- if(bits.BitsLeft() < 4)
- {
+ if (bits.BitsLeft() < 4) {
return AP4_ERROR_INVALID_FORMAT;
}
- m_ChannelConfiguration = (ChannelConfiguration)bits.ReadBits(4);
+ m_ChannelConfiguration = (ChannelConfiguration)bits.ReadBits(4);
m_ChannelCount = (unsigned int)m_ChannelConfiguration;
- if(m_ChannelCount == 7)
- {
+ if (m_ChannelCount == 7) {
m_ChannelCount = 8;
- }
- else if(m_ChannelCount > 7)
- {
+ } else if (m_ChannelCount > 7) {
m_ChannelCount = 0;
}
-
- if(m_ObjectType == AP4_MPEG4_AUDIO_OBJECT_TYPE_SBR ||
- m_ObjectType == AP4_MPEG4_AUDIO_OBJECT_TYPE_PS)
- {
- m_Extension.m_ObjectType = AP4_MPEG4_AUDIO_OBJECT_TYPE_SBR;
- m_Extension.m_SbrPresent = true;
+
+ if (m_ObjectType == AP4_MPEG4_AUDIO_OBJECT_TYPE_SBR ||
+ m_ObjectType == AP4_MPEG4_AUDIO_OBJECT_TYPE_PS) {
+ m_Extension.m_ObjectType = AP4_MPEG4_AUDIO_OBJECT_TYPE_SBR;
+ m_Extension.m_SbrPresent = true;
m_Extension.m_PsPresent = m_ObjectType == AP4_MPEG4_AUDIO_OBJECT_TYPE_PS;
- result = ParseSamplingFrequency(bits,
- m_Extension.m_SamplingFrequencyIndex,
+ result = ParseSamplingFrequency(bits,
+ m_Extension.m_SamplingFrequencyIndex,
m_Extension.m_SamplingFrequency);
- if(AP4_FAILED(result)) return result;
- result = ParseAudioObjectType(bits, m_ObjectType);
- if(AP4_FAILED(result)) return result;
- }
- else
- {
+ if (AP4_FAILED(result)) return result;
+ result = ParseAudioObjectType(bits, m_ObjectType);
+ if (AP4_FAILED(result)) return result;
+ } else {
m_Extension.m_ObjectType = 0;
m_Extension.m_SamplingFrequency = 0;
m_Extension.m_SamplingFrequencyIndex = 0;
m_Extension.m_SbrPresent = false;
m_Extension.m_PsPresent = false;
}
-
- switch(m_ObjectType)
- {
- case AP4_MPEG4_AUDIO_OBJECT_TYPE_AAC_MAIN:
- case AP4_MPEG4_AUDIO_OBJECT_TYPE_AAC_LC:
- case AP4_MPEG4_AUDIO_OBJECT_TYPE_AAC_SSR:
- case AP4_MPEG4_AUDIO_OBJECT_TYPE_AAC_LTP:
- case AP4_MPEG4_AUDIO_OBJECT_TYPE_AAC_SCALABLE:
- case AP4_MPEG4_AUDIO_OBJECT_TYPE_TWINVQ:
- case AP4_MPEG4_AUDIO_OBJECT_TYPE_ER_AAC_LC:
- case AP4_MPEG4_AUDIO_OBJECT_TYPE_ER_AAC_LTP:
- case AP4_MPEG4_AUDIO_OBJECT_TYPE_ER_AAC_SCALABLE:
- case AP4_MPEG4_AUDIO_OBJECT_TYPE_ER_AAC_LD:
- case AP4_MPEG4_AUDIO_OBJECT_TYPE_ER_TWINVQ:
- case AP4_MPEG4_AUDIO_OBJECT_TYPE_ER_BSAC:
- result = ParseGASpecificInfo(bits);
- break;
-
- default:
- return AP4_ERROR_NOT_SUPPORTED;
+
+ switch (m_ObjectType) {
+ case AP4_MPEG4_AUDIO_OBJECT_TYPE_AAC_MAIN:
+ case AP4_MPEG4_AUDIO_OBJECT_TYPE_AAC_LC:
+ case AP4_MPEG4_AUDIO_OBJECT_TYPE_AAC_SSR:
+ case AP4_MPEG4_AUDIO_OBJECT_TYPE_AAC_LTP:
+ case AP4_MPEG4_AUDIO_OBJECT_TYPE_AAC_SCALABLE:
+ case AP4_MPEG4_AUDIO_OBJECT_TYPE_TWINVQ:
+ case AP4_MPEG4_AUDIO_OBJECT_TYPE_ER_AAC_LC:
+ case AP4_MPEG4_AUDIO_OBJECT_TYPE_ER_AAC_LTP:
+ case AP4_MPEG4_AUDIO_OBJECT_TYPE_ER_AAC_SCALABLE:
+ case AP4_MPEG4_AUDIO_OBJECT_TYPE_ER_AAC_LD:
+ case AP4_MPEG4_AUDIO_OBJECT_TYPE_ER_TWINVQ:
+ case AP4_MPEG4_AUDIO_OBJECT_TYPE_ER_BSAC:
+ result = ParseGASpecificInfo(bits);
+ break;
+
+ default:
+ return AP4_ERROR_NOT_SUPPORTED;
}
return AP4_SUCCESS;
diff --git a/src/filters/parser/MP4Splitter/AP4/Source/Codecs/Ap4Mp4AudioInfo.h b/src/filters/parser/MP4Splitter/AP4/Source/Codecs/Ap4Mp4AudioInfo.h
index 337c125a8..eeb629069 100644
--- a/src/filters/parser/MP4Splitter/AP4/Source/Codecs/Ap4Mp4AudioInfo.h
+++ b/src/filters/parser/MP4Splitter/AP4/Source/Codecs/Ap4Mp4AudioInfo.h
@@ -44,14 +44,12 @@ class AP4_Mp4AudioDsiParser;
* DecoderConfigDescriptor descriptor carried in the sample description
* for the audio samples. See 14496-1, subpart 2, p 2.6.6 for details.
*/
-class AP4_Mp4AudioDecoderConfig
-{
+class AP4_Mp4AudioDecoderConfig {
public:
/**
* Channel configuration for multichannel audio buffers.
*/
- typedef enum
- {
+ typedef enum {
CHANNEL_CONFIG_NONE = 0, /**< No channel (not used) */
CHANNEL_CONFIG_MONO = 1, /**< Mono (single audio channel) */
CHANNEL_CONFIG_STEREO = 2, /**< Stereo (Two audio channels) */
@@ -65,17 +63,17 @@ public:
// constructor
AP4_Mp4AudioDecoderConfig();
-
+
/**
* Parser a DecoderSpecificInfo buffer
*/
AP4_Result Parse(const AP4_UI08* data, AP4_Size data_size);
-
+
/**
* Reset all members to default values (0)
*/
void Reset();
-
+
// members
AP4_UI08 m_ObjectType; /**< Type identifier for the audio data */
unsigned int m_SamplingFrequencyIndex; /**< Index of the sampling frequency in the sampling frequency table */
@@ -86,19 +84,18 @@ public:
bool m_DependsOnCoreCoder; /**< Depends on Core Coder */
unsigned int m_CoreCoderDelay; /**< Core Code delay */
/** Extension details */
- struct
- {
+ struct {
bool m_SbrPresent; /**< SBR is present */
bool m_PsPresent; /**< PS is present */
AP4_UI08 m_ObjectType; /**< Extension object type */
unsigned int m_SamplingFrequencyIndex; /**< Sampling frequency index of the extension */
unsigned int m_SamplingFrequency; /**< Sampling frequency of the extension */
} m_Extension;
-
+
private:
AP4_Result ParseAudioObjectType(AP4_Mp4AudioDsiParser& parser, AP4_UI08& object_type);
AP4_Result ParseGASpecificInfo(AP4_Mp4AudioDsiParser& parser);
- AP4_Result ParseSamplingFrequency(AP4_Mp4AudioDsiParser& parser,
+ AP4_Result ParseSamplingFrequency(AP4_Mp4AudioDsiParser& parser,
unsigned int& sampling_frequency_index,
unsigned int& sampling_frequency);
};
diff --git a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4.h b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4.h
index b7648bca3..aa81266d4 100644
--- a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4.h
+++ b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4.h
@@ -25,7 +25,7 @@
| 02111-1307, USA.
|
****************************************************************/
-/**
+/**
* @file
* @brief Top Level include file
*
@@ -37,23 +37,23 @@
*
* @section intro_sec Introduction
* Bento4/AP4 is a C++ class library designed to read and write ISO-MP4 files.
-* This format is defined in ISO/IEC 14496-12, 14496-14 and 14496-15.
-* The format is a derivative of the Apple Quicktime file format.
-* Because of that, Bento4 can be used to read and write a number of Quicktime files
+* This format is defined in ISO/IEC 14496-12, 14496-14 and 14496-15.
+* The format is a derivative of the Apple Quicktime file format.
+* Because of that, Bento4 can be used to read and write a number of Quicktime files
* as well, even though some Quicktime specific features are not supported.
* In addition, Bento4 supports a number of extensions as defined in various
* other specifications. This includes some support for ISMA Encrytion and
-* Decryption as defined in the ISMA E&A specification (http://www.isma.tv),
+* Decryption as defined in the ISMA E&A specification (http://www.isma.tv),
* OMA 2.0 PDCF Encryption and Decryption as defined in the OMA 2.0 PDCF
* specification (http://www.openmobilealliance.org) and iTunes compatible
* metadata.
* The SDK includes a number of command line tools, built using the class library,
* that serve as general purpose tools as well as examples of how to use the API.
-*
+*
* The SDK is designed to be cross-platform. The code is very portable; it can
* be compiled with any sufficiently modern C++ compiler. The code does not rely
* on any external library; all the code necessary to compile the SDK and its
-* tools is included in the standard distribution. The standard distribution
+* tools is included in the standard distribution. The standard distribution
* contains makefiles for unix-like operating systems, including Linux, project
* files for Microsoft Visual Studio, and an XCode project for MacOS X. There is
* also support for building the library with the SCons build system.
@@ -71,9 +71,9 @@
* will create the SDK directory structure as described above.
*
* @subsection build_linux Linux
-* Go to Build/Targets/x86-unknown-linux or Build/Targets/<target-name>
+* Go to Build/Targets/x86-unknown-linux or Build/Targets/<target-name>
* for any linux-based target, and use the 'make'
-* command to build the library and tools, or 'make sdk' to build the SDK
+* command to build the library and tools, or 'make sdk' to build the SDK
* directory structure.
*
* @subsection build_cygwin Cygwin
@@ -85,37 +85,37 @@
*
* @subsection build_scons Using SCons
* There is experimental support for building the SDK using the python-based
-* SCons tool (http://www.scons.org). The top level configuration is located
+* SCons tool (http://www.scons.org). The top level configuration is located
* at the root of the SDK, and will output all the object files and binaries
* to a sub-directory under Build/SCons/Targets/<target-name>/<config-name>.
*
* @subsection build_others Other Platforms
* Other plaftorms can be built by adapting the makefiles for the generic
-* gcc-based configurations.
+* gcc-based configurations.
*
* @section mp4_structure Structure of an MP4 file
*
* An MP4 file consists of a tree of atoms (also known as boxes). The atoms
* contain the information about the different media tracks for the file, as
* well as other information, such as metadata.
-* The Bento4 class library parses files an constructs an in-memory representation
+* The Bento4 class library parses files an constructs an in-memory representation
* of the atoms, and provides an API that is an abstraction layer for the
* way the information is actually encoded in those atoms.
*
* @section reading Reading Files
*
* The class #AP4_File represents all the information about an MP4 file.
-* Internally, a tree of #AP4_Atom objects plus other helper objects holds
+* Internally, a tree of #AP4_Atom objects plus other helper objects holds
* the actual information.
-* To create an instance of the class, the caller must pass a reference to
+* To create an instance of the class, the caller must pass a reference to
* an #AP4_ByteStream object that represents the file data storage. The SDK
-* includes two subclasses of the abstract #AP4_ByteStream class:
+* includes two subclasses of the abstract #AP4_ByteStream class:
* #AP4_FileByteStream for reading/writing disk-based files and
* #AP4_MemoryByteStream for working with in-memory file images.
* Once you have created an #AP4_File object, you can get to the media data by
* accessing the #AP4_Track objects of its #AP4_Movie (see #AP4_File::GetMovie).
* The #AP4_Track exposes the necessary methods for you to get the
-* #AP4_SampleDescription (typically to initialize your decoder) and to get the
+* #AP4_SampleDescription (typically to initialize your decoder) and to get the
* #AP4_Sample objects from the track.
* These #AP4_Sample objects give you the meta information you need (such as
* timestamps) as well as the sample data that they point to.
@@ -124,16 +124,16 @@
* base class for a visitor of the tree of #AP4_Atom objects. The SDK includes
* an concrete subclass, #AP4_PrintInspector, can be used to print out a text
* representation of the atoms as they are visited. See the Mp4Dump command line
-* application for an example.
-*
+* application for an example.
+*
* @section writing Writing Files
*
* To create a new MP4 file, you first create an #AP4_SyntheticSampleTable
* sample table for each track in your file. You specify the sample description
* for the media samples in each track by calling #AP4_SyntheticSampleTable::AddSampleDescription
* with the description for the samples of that track. Samples can then be added
-* to the sample table with the #AP4_SyntheticSampleTable::AddSample method.
-* Once all the samples of all the tracks have been added to the sample tables,
+* to the sample table with the #AP4_SyntheticSampleTable::AddSample method.
+* Once all the samples of all the tracks have been added to the sample tables,
* you can create an #AP4_Movie, and an #AP4_Track from each sample table, add the track
* to the movie, and finally create an #AP4_File from the movie object.
* Finally, the #AP4_File object can be serialized to a byte stream (such as an
@@ -141,20 +141,20 @@
* See the Aac2Mp4 application for an example.
*
* @section tracks Tracks
-*
+*
* The #AP4_Movie object of an #AP4_File has a list of #AP4_Track objects. Each
-* #AP4_Track represents a media track in the file. From this object, you can
+* #AP4_Track represents a media track in the file. From this object, you can
* obtain the type, duration, etc.. of the tracks. This object also provides
* access to the media samples in the track. Tracks are made up of media samples,
* stored in an 'mdat' atom (media data) and a sample table that provides all the
* information about the individual samples, such as size, timestamps, sample
-* description, etc... Media samples are represented by #AP4_Sample objects.
-* You can obtain a track's samples by calling the #AP4_Track::GetSample method.
+* description, etc... Media samples are represented by #AP4_Sample objects.
+* You can obtain a track's samples by calling the #AP4_Track::GetSample method.
* You can also directly read the payload of a media sample by calling the
* #AP4_Track::ReadSample method if you want to bypass the intermediate step of
* going through an #AP4_Sample object.
* The information about the samples in a track is represented by subclasses of
-* the #AP4_SampleDescription class. The sample descriptions contain information
+* the #AP4_SampleDescription class. The sample descriptions contain information
* about media-specific parameters, such as video resolution, audio sampling rates
* and others.
* See the Mp4Info and Mp42Aac command line applications as examples.
@@ -164,15 +164,15 @@
* @subsection factory Custom Atoms
*
* The SDK has built-in support for most of the standard atom types as defined
-* in the spec. But an application may want to extend the library to support
+* in the spec. But an application may want to extend the library to support
* non-standard atom type, such as custom atoms whose definition is proprietary.
* The base class for all atoms is #AP4_Atom. Instances of subclasses of this class
-* are created by the #AP4_AtomFactory object. The factory knows about all the
-* #AP4_Atom subclasses included in the SDK, and maintains a list of
+* are created by the #AP4_AtomFactory object. The factory knows about all the
+* #AP4_Atom subclasses included in the SDK, and maintains a list of
* #AP4_AtomFactory::TypeHandler type handlers. When the factory encounters an atom
* that is not one of the built-in atom type, it calls all the registered type
-* handlers, in turn, until one of them accept to handle the type and create the
-* corresponding atom. The custom atoms must be implemented as subclasses of
+* handlers, in turn, until one of them accept to handle the type and create the
+* corresponding atom. The custom atoms must be implemented as subclasses of
* #AP4_Atom and override at least the #AP4_Atom::WriteFields method. The custom
* atoms should also override #AP4_Atom::InspectFields if they want to provide
* meaningful information when inspected.
@@ -180,7 +180,7 @@
* @subsection tranformations Transformations
* The SDK provides support for transforming MP4 files. Transformations are useful
* to perform tasks such as editing (removing or adding atoms) and encryption or
-* decryption. When the atom tree for the file changes, the entire file needs to
+* decryption. When the atom tree for the file changes, the entire file needs to
* change, because in most cases, the size of the 'moov' atom will change, and
* thus change the offset of the media samples in the 'mdat' atom.
* To facilitate this operation, the class #AP4_Processor provides the base
@@ -192,18 +192,18 @@
* of #AP4_Processor may create such an #AP4_Processor::TrackHandler subclass instance
* when is #AP4_Processor::CreateTrackHandler is called for one of the tracks in the
* file.
-* See the sample applications Mp4Edit, Mp4Encrpt and Mp4Decrypt as examples.
+* See the sample applications Mp4Edit, Mp4Encrpt and Mp4Decrypt as examples.
*
* @subsection encryption Encryption and Decryption
*
* The SDK has support for encrypting and decrypting tracks as specified by the
-* ISMA Encryption and Authentication specification as well as OMA 2.0 and 2.1 DCF and PDCF.
+* ISMA Encryption and Authentication specification as well as OMA 2.0 and 2.1 DCF and PDCF.
* The supporting classes found in Ap4IsmaCryp.h and AP4_OmaDcf.h provide a subclass
-* of #AP4_Processor for encrypting or decrypting entire files.
+* of #AP4_Processor for encrypting or decrypting entire files.
* The class #AP4_IsmaCipher and #AP4_OmaDcfSampleDecrypter implement the generic
* #AP4_SampleDecrypter interface that provides support for decrypting individual samples.
-* The parameters necessary to instantiate an #AP4_IsmaCipher or an #AP4_OmaDcfSampleDecrypter
-* can be retrieved from an encrypted track by accessing the track's sample descriptions,
+* The parameters necessary to instantiate an #AP4_IsmaCipher or an #AP4_OmaDcfSampleDecrypter
+* can be retrieved from an encrypted track by accessing the track's sample descriptions,
* which are instances of the #AP4_ProtectedSampleDescription class. A more general factory
* method, #AP4_SampleDecrypter::Create can be called, passing an instance of
* #AP4_ProtectedSampleDescription and the cipher key, and the correct concrete class will
@@ -213,7 +213,7 @@
*
* For files that contain hint tracks, the SDK provides support for generating
* RTP packets that can be used to stream the media using the RTP and RTSP protocols.
-* See the application Mp4RtpHintInfo for an example of how to generate the create
+* See the application Mp4RtpHintInfo for an example of how to generate the create
* RTP packets from a file and generate the SDP information for the RTSP protocol.
*/
diff --git a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap48bdlAtom.cpp b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap48bdlAtom.cpp
index a7b671d39..99828d98b 100644
--- a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap48bdlAtom.cpp
+++ b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap48bdlAtom.cpp
@@ -1,6 +1,6 @@
/*****************************************************************
|
-| AP4 - 8bdl Atoms
+| AP4 - 8bdl Atoms
|
| Copyright 2002-2009 Axiomatic Systems, LLC
|
@@ -25,7 +25,7 @@
| 02111-1307, USA.
|
****************************************************************/
-
+
/*----------------------------------------------------------------------
| includes
+---------------------------------------------------------------------*/
@@ -44,7 +44,7 @@ AP4_8bdlAtom::AP4_8bdlAtom(AP4_UI32 encoding,
AP4_UI32 encoding_version,
const AP4_Byte* data,
AP4_Size data_size) :
- AP4_Atom(AP4_ATOM_TYPE_8BDL, (AP4_UI32)(AP4_ATOM_HEADER_SIZE + 8 + data_size)),
+ AP4_Atom(AP4_ATOM_TYPE_8BDL, (AP4_UI32)(AP4_ATOM_HEADER_SIZE+8+data_size)),
m_Encoding(encoding),
m_EncodingVersion(encoding_version),
m_BundleData(data, data_size)
@@ -58,12 +58,9 @@ AP4_8bdlAtom*
AP4_8bdlAtom::Create(AP4_Size size, AP4_ByteStream& stream)
{
// make sure we have enough data
- if(size < AP4_ATOM_HEADER_SIZE + 8)
- {
+ if (size < AP4_ATOM_HEADER_SIZE+8) {
return NULL;
- }
- else
- {
+ } else {
return new AP4_8bdlAtom(size, stream);
}
}
@@ -74,7 +71,7 @@ AP4_8bdlAtom::Create(AP4_Size size, AP4_ByteStream& stream)
AP4_8bdlAtom::AP4_8bdlAtom(AP4_Size size,
AP4_ByteStream& stream) :
AP4_Atom(AP4_ATOM_TYPE_8BDL, (AP4_UI32)(size)),
- m_BundleData(size - AP4_ATOM_HEADER_SIZE - 8)
+ m_BundleData(size-AP4_ATOM_HEADER_SIZE-8)
{
stream.ReadUI32(m_Encoding);
stream.ReadUI32(m_EncodingVersion);
@@ -92,15 +89,15 @@ AP4_8bdlAtom::WriteFields(AP4_ByteStream& stream)
// encoding
result = stream.WriteUI32(m_Encoding);
- if(AP4_FAILED(result)) return result;
+ if (AP4_FAILED(result)) return result;
// encoding version
result = stream.WriteUI32(m_EncodingVersion);
- if(AP4_FAILED(result)) return result;
+ if (AP4_FAILED(result)) return result;
// bundle_data
result = stream.Write(m_BundleData.GetData(), m_BundleData.GetDataSize());
- if(AP4_FAILED(result)) return result;
+ if (AP4_FAILED(result)) return result;
return result;
}
@@ -115,14 +112,11 @@ AP4_8bdlAtom::InspectFields(AP4_AtomInspector& inspector)
AP4_FormatFourChars(enc, m_Encoding);
inspector.AddField("encoding", enc);
inspector.AddField("encoding_version", m_EncodingVersion);
- if(m_Encoding == AP4_8BDL_XML_DATA_ENCODING)
- {
+ if (m_Encoding == AP4_8BDL_XML_DATA_ENCODING) {
// we, in fact have an xml string
AP4_String xml((const char*)m_BundleData.GetData(), m_BundleData.GetDataSize());
inspector.AddField("bundle_data", xml.GetChars());
- }
- else
- {
+ } else {
inspector.AddField("bundle_data", m_BundleData.GetData(), m_BundleData.GetDataSize());
}
diff --git a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap48bdlAtom.h b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap48bdlAtom.h
index 6845c7b22..3c3cadd2e 100644
--- a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap48bdlAtom.h
+++ b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap48bdlAtom.h
@@ -1,6 +1,6 @@
/*****************************************************************
|
-| AP4 - 8bdl Atoms
+| AP4 - 8bdl Atoms
|
| Copyright 2002-2009 Axiomatic Systems, LLC
|
@@ -25,10 +25,10 @@
| 02111-1307, USA.
|
****************************************************************/
-
-#ifndef _AP4_8BDL_ATOM_H_
-#define _AP4_8BDL_ATOM_H_
-
+
+ #ifndef _AP4_8BDL_ATOM_H_
+ #define _AP4_8BDL_ATOM_H_
+
/*----------------------------------------------------------------------
| includes
+---------------------------------------------------------------------*/
@@ -39,7 +39,7 @@
/*----------------------------------------------------------------------
| constants
+---------------------------------------------------------------------*/
-const AP4_UI32 AP4_8BDL_XML_DATA_ENCODING = AP4_ATOM_TYPE('x', 'm', 'l', ' ');
+const AP4_UI32 AP4_8BDL_XML_DATA_ENCODING = AP4_ATOM_TYPE('x','m','l',' ');
/*----------------------------------------------------------------------
| AP4_8bdlAtom
@@ -51,7 +51,7 @@ public:
// virtual constructor
static AP4_8bdlAtom* Create(AP4_Size size, AP4_ByteStream& stream);
-
+
// constructors
AP4_8bdlAtom(AP4_UI32 encoding,
AP4_UI32 encoding_version,
@@ -63,18 +63,9 @@ public:
virtual AP4_Result WriteFields(AP4_ByteStream& stream);
// accessors
- AP4_UI32 GetEncoding()
- {
- return m_Encoding;
- }
- AP4_UI32 GetEncodingVersion()
- {
- return m_EncodingVersion;
- }
- const AP4_DataBuffer& GetBundleData()
- {
- return m_BundleData;
- }
+ AP4_UI32 GetEncoding() { return m_Encoding; }
+ AP4_UI32 GetEncodingVersion() { return m_EncodingVersion; }
+ const AP4_DataBuffer& GetBundleData() { return m_BundleData; }
private:
// methods
diff --git a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4Array.h b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4Array.h
index ebbd42748..b62bac22c 100644
--- a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4Array.h
+++ b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4Array.h
@@ -26,7 +26,7 @@
|
****************************************************************/
/**
- * @file
+ * @file
* @brief Arrays
*/
@@ -51,28 +51,19 @@ const int AP4_ARRAY_INITIAL_COUNT = 64;
/*----------------------------------------------------------------------
| AP4_Array
+---------------------------------------------------------------------*/
-template <typename T>
-class AP4_Array
+template <typename T>
+class AP4_Array
{
public:
// methods
- AP4_Array(): m_AllocatedCount(0), m_ItemCount(0), m_Items(0) {}
- AP4_Array(const T* items, AP4_Size count);
+ AP4_Array(): m_AllocatedCount(0), m_ItemCount(0), m_Items(0) {}
+ AP4_Array(const T* items, AP4_Size count);
virtual ~AP4_Array();
- AP4_Cardinal ItemCount() const
- {
- return m_ItemCount;
- }
+ AP4_Cardinal ItemCount() const { return m_ItemCount; }
AP4_Result Append(const T& item);
AP4_Result RemoveLast();
- T& operator[](unsigned long idx)
- {
- return m_Items[idx];
- }
- const T& operator[](unsigned long idx) const
- {
- return m_Items[idx];
- }
+ T& operator[](unsigned long idx) { return m_Items[idx]; }
+ const T& operator[](unsigned long idx) const { return m_Items[idx]; }
AP4_Result Clear();
AP4_Result EnsureCapacity(AP4_Cardinal count);
AP4_Result SetItemCount(AP4_Cardinal item_count);
@@ -93,9 +84,8 @@ AP4_Array<T>::AP4_Array(const T* items, AP4_Size count) :
m_ItemCount(count),
m_Items((T*)::operator new(count*sizeof(T)))
{
- for(unsigned int i = 0; i < count; i++)
- {
- new((void*)&m_Items[i]) T(items[i]);
+ for (unsigned int i=0; i<count; i++) {
+ new ((void*)&m_Items[i]) T(items[i]);
}
}
@@ -117,8 +107,7 @@ AP4_Result
AP4_Array<T>::Clear()
{
// destroy all items
- for(AP4_Ordinal i = 0; i < m_ItemCount; i++)
- {
+ for (AP4_Ordinal i=0; i<m_ItemCount; i++) {
m_Items[i].~T();
}
@@ -135,19 +124,16 @@ AP4_Result
AP4_Array<T>::EnsureCapacity(AP4_Cardinal count)
{
// check if we already have enough
- if(count <= m_AllocatedCount) return AP4_SUCCESS;
+ if (count <= m_AllocatedCount) return AP4_SUCCESS;
// (re)allocate the items
- T* new_items = (T*) ::operator new(count * sizeof(T));
- if(new_items == NULL)
- {
+ T* new_items = (T*) ::operator new (count*sizeof(T));
+ if (new_items == NULL) {
return AP4_ERROR_OUT_OF_MEMORY;
}
- if(m_ItemCount && m_Items)
- {
- for(unsigned int i = 0; i < m_ItemCount; i++)
- {
- new((void*)&new_items[i]) T(m_Items[i]);
+ if (m_ItemCount && m_Items) {
+ for (unsigned int i=0; i<m_ItemCount; i++) {
+ new ((void*)&new_items[i]) T(m_Items[i]);
m_Items[i].~T();
}
::operator delete((void*)m_Items);
@@ -162,32 +148,29 @@ AP4_Array<T>::EnsureCapacity(AP4_Cardinal count)
| AP4_Array<T>::SetItemCount
+---------------------------------------------------------------------*/
template <typename T>
-AP4_Result
+AP4_Result
AP4_Array<T>::SetItemCount(AP4_Cardinal item_count)
{
// shortcut
- if(item_count == m_ItemCount) return AP4_SUCCESS;
-
+ if (item_count == m_ItemCount) return AP4_SUCCESS;
+
// check for a reduction in the number of items
- if(item_count < m_ItemCount)
- {
+ if (item_count < m_ItemCount) {
// destruct the items that are no longer needed
- for(unsigned int i = item_count; i < m_ItemCount; i++)
- {
+ for (unsigned int i=item_count; i<m_ItemCount; i++) {
m_Items[i].~T();
}
m_ItemCount = item_count;
return AP4_SUCCESS;
}
-
+
// grow the list
AP4_Result result = EnsureCapacity(item_count);
- if(AP4_FAILED(result)) return result;
-
+ if (AP4_FAILED(result)) return result;
+
// construct the new items
- for(unsigned int i = m_ItemCount; i < item_count; i++)
- {
- new((void*)&m_Items[i]) T();
+ for (unsigned int i=m_ItemCount; i<item_count; i++) {
+ new ((void*)&m_Items[i]) T();
}
m_ItemCount = item_count;
return AP4_SUCCESS;
@@ -200,13 +183,10 @@ template <typename T>
AP4_Result
AP4_Array<T>::RemoveLast()
{
- if(m_ItemCount)
- {
+ if (m_ItemCount) {
m_Items[--m_ItemCount].~T();
return AP4_SUCCESS;
- }
- else
- {
+ } else {
return AP4_ERROR_OUT_OF_RANGE;
}
}
@@ -219,21 +199,20 @@ AP4_Result
AP4_Array<T>::Append(const T& item)
{
// ensure that we have enough space
- if(m_AllocatedCount < m_ItemCount + 1)
- {
+ if (m_AllocatedCount < m_ItemCount+1) {
// try double the size, with a minimum
- unsigned long new_count = m_AllocatedCount ? 2 * m_AllocatedCount : AP4_ARRAY_INITIAL_COUNT;
+ unsigned long new_count = m_AllocatedCount?2*m_AllocatedCount:AP4_ARRAY_INITIAL_COUNT;
// if that's still not enough, just ask for what we need
- if(new_count < m_ItemCount + 1) new_count = m_ItemCount + 1;
-
+ if (new_count < m_ItemCount+1) new_count = m_ItemCount+1;
+
// reserve the space
AP4_Result result = EnsureCapacity(new_count);
- if(result != AP4_SUCCESS) return result;
+ if (result != AP4_SUCCESS) return result;
}
-
+
// store the item
- new((void*)&m_Items[m_ItemCount++]) T(item);
+ new ((void*)&m_Items[m_ItemCount++]) T(item);
return AP4_SUCCESS;
}
diff --git a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4Atom.cpp b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4Atom.cpp
index a8876c1a8..a9bd81e6b 100644
--- a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4Atom.cpp
+++ b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4Atom.cpp
@@ -1,6 +1,6 @@
/*****************************************************************
|
-| AP4 - Atoms
+| AP4 - Atoms
|
| Copyright 2002-2008 Axiomatic Systems, LLC
|
@@ -57,16 +57,16 @@ AP4_Atom::Type
AP4_Atom::TypeFromString(const char* s)
{
// convert the name into an atom type
- return ((AP4_UI32)s[0]) << 24 |
- ((AP4_UI32)s[1]) << 16 |
- ((AP4_UI32)s[2]) << 8 |
+ return ((AP4_UI32)s[0])<<24 |
+ ((AP4_UI32)s[1])<<16 |
+ ((AP4_UI32)s[2])<< 8 |
((AP4_UI32)s[3]);
}
/*----------------------------------------------------------------------
| AP4_Atom::AP4_Atom
+---------------------------------------------------------------------*/
-AP4_Atom::AP4_Atom(Type type, AP4_UI32 size /* = AP4_ATOM_HEADER_SIZE */) :
+AP4_Atom::AP4_Atom(Type type, AP4_UI32 size /* = AP4_ATOM_HEADER_SIZE */) :
m_Type(type),
m_Size32(size),
m_Size64(0),
@@ -80,7 +80,7 @@ AP4_Atom::AP4_Atom(Type type, AP4_UI32 size /* = AP4_ATOM_HEADER_SIZE */) :
/*----------------------------------------------------------------------
| AP4_Atom::AP4_Atom
+---------------------------------------------------------------------*/
-AP4_Atom::AP4_Atom(Type type, AP4_UI64 size, bool force_64) :
+AP4_Atom::AP4_Atom(Type type, AP4_UI64 size, bool force_64) :
m_Type(type),
m_Size32(0),
m_Size64(0),
@@ -95,9 +95,9 @@ AP4_Atom::AP4_Atom(Type type, AP4_UI64 size, bool force_64) :
/*----------------------------------------------------------------------
| AP4_Atom::AP4_Atom
+---------------------------------------------------------------------*/
-AP4_Atom::AP4_Atom(Type type,
- AP4_UI32 size,
- AP4_UI32 version,
+AP4_Atom::AP4_Atom(Type type,
+ AP4_UI32 size,
+ AP4_UI32 version,
AP4_UI32 flags) :
m_Type(type),
m_Size32(size),
@@ -112,10 +112,10 @@ AP4_Atom::AP4_Atom(Type type,
/*----------------------------------------------------------------------
| AP4_Atom::AP4_Atom
+---------------------------------------------------------------------*/
-AP4_Atom::AP4_Atom(Type type,
+AP4_Atom::AP4_Atom(Type type,
AP4_UI64 size,
bool force_64,
- AP4_UI32 version,
+ AP4_UI32 version,
AP4_UI32 flags) :
m_Type(type),
m_Size32(0),
@@ -132,14 +132,14 @@ AP4_Atom::AP4_Atom(Type type,
| AP4_Atom::ReadFullHeader
+---------------------------------------------------------------------*/
AP4_Result
-AP4_Atom::ReadFullHeader(AP4_ByteStream& stream,
- AP4_UI32& version,
+AP4_Atom::ReadFullHeader(AP4_ByteStream& stream,
+ AP4_UI32& version,
AP4_UI32& flags)
{
AP4_UI32 header;
AP4_CHECK(stream.ReadUI32(header));
- version = (header >> 24) & 0x000000FF;
- flags = (header) & 0x00FFFFFF;
+ version = (header>>24)&0x000000FF;
+ flags = (header )&0x00FFFFFF;
return AP4_SUCCESS;
}
@@ -150,22 +150,17 @@ AP4_Atom::ReadFullHeader(AP4_ByteStream& stream,
void
AP4_Atom::SetSize(AP4_UI64 size, bool force_64)
{
- if(!force_64)
- {
+ if (!force_64) {
// see if we need to implicitely force 64-bit encoding
- if(m_Size32 == 1 && m_Size64 <= 0xFFFFFFFF)
- {
+ if (m_Size32 == 1 && m_Size64 <= 0xFFFFFFFF) {
// we have a forced 64-bit encoding
force_64 = true;
}
}
- if((size >> 32) == 0 && !force_64)
- {
+ if ((size >> 32) == 0 && !force_64) {
m_Size32 = (AP4_UI32)size;
m_Size64 = 0;
- }
- else
- {
+ } else {
m_Size32 = 1;
m_Size64 = size;
}
@@ -177,7 +172,7 @@ AP4_Atom::SetSize(AP4_UI64 size, bool force_64)
AP4_Size
AP4_Atom::GetHeaderSize() const
{
- return (m_IsFull ? AP4_FULL_ATOM_HEADER_SIZE : AP4_ATOM_HEADER_SIZE) + (m_Size32 == 1 ? 8 : 0);
+ return (m_IsFull ? AP4_FULL_ATOM_HEADER_SIZE : AP4_ATOM_HEADER_SIZE)+(m_Size32==1?8:0);
}
/*----------------------------------------------------------------------
@@ -190,26 +185,24 @@ AP4_Atom::WriteHeader(AP4_ByteStream& stream)
// write the size
result = stream.WriteUI32(m_Size32);
- if(AP4_FAILED(result)) return result;
+ if (AP4_FAILED(result)) return result;
// write the type
result = stream.WriteUI32(m_Type);
- if(AP4_FAILED(result)) return result;
+ if (AP4_FAILED(result)) return result;
// handle 64-bit sizes
- if(m_Size32 == 1)
- {
+ if (m_Size32 == 1) {
result = stream.WriteUI64(m_Size64);
- if(AP4_FAILED(result)) return result;
+ if (AP4_FAILED(result)) return result;
}
// for full atoms, write version and flags
- if(m_IsFull)
- {
+ if (m_IsFull) {
result = stream.WriteUI08(m_Version);
- if(AP4_FAILED(result)) return result;
+ if (AP4_FAILED(result)) return result;
result = stream.WriteUI24(m_Flags);
- if(AP4_FAILED(result)) return result;
+ if (AP4_FAILED(result)) return result;
}
return AP4_SUCCESS;
@@ -230,23 +223,21 @@ AP4_Atom::Write(AP4_ByteStream& stream)
// write the header
result = WriteHeader(stream);
- if(AP4_FAILED(result)) return result;
+ if (AP4_FAILED(result)) return result;
// write the fields
result = WriteFields(stream);
- if(AP4_FAILED(result)) return result;
+ if (AP4_FAILED(result)) return result;
#if defined(AP4_DEBUG)
AP4_Position after;
stream.Tell(after);
AP4_UI64 atom_size = GetSize();
- if(after - before != atom_size)
- {
+ if (after-before != atom_size) {
AP4_Debug("ERROR: atom size mismatch (declared size=%d, actual size=%d)\n",
- (AP4_UI32)atom_size, (AP4_UI32)(after - before));
+ (AP4_UI32)atom_size, (AP4_UI32)(after-before));
AP4_Atom* atom = this;
- while(atom)
- {
+ while (atom) {
char name[7];
name[0] = '[';
AP4_FormatFourCharsPrintable(&name[1], atom->GetType());
@@ -255,7 +246,7 @@ AP4_Atom::Write(AP4_ByteStream& stream)
AP4_Debug(" while writing %s\n", name);
atom = AP4_DYNAMIC_CAST(AP4_Atom, atom->GetParent());
}
- AP4_ASSERT(after - before == atom_size);
+ AP4_ASSERT(after-before == atom_size);
}
#endif
@@ -289,32 +280,26 @@ AP4_Atom::InspectHeader(AP4_AtomInspector& inspector)
name[6] = '\0';
char header[128];
char extra[32] = "";
- if(m_IsFull)
- {
- if(m_Version && m_Flags)
- {
- AP4_FormatString(extra, sizeof(extra),
+ if (m_IsFull) {
+ if (m_Version && m_Flags) {
+ AP4_FormatString(extra, sizeof(extra),
", version=%d, flags=%x",
m_Version,
m_Flags);
- }
- else if(m_Version)
- {
- AP4_FormatString(extra, sizeof(extra),
+ } else if (m_Version) {
+ AP4_FormatString(extra, sizeof(extra),
", version=%d",
m_Version);
- }
- else if(m_Flags)
- {
- AP4_FormatString(extra, sizeof(extra),
+ } else if (m_Flags) {
+ AP4_FormatString(extra, sizeof(extra),
", flags=%x",
m_Flags);
}
}
- AP4_FormatString(header, sizeof(header),
- "size=%ld+%lld%s",
- GetHeaderSize(),
- GetSize() - GetHeaderSize(),
+ AP4_FormatString(header, sizeof(header),
+ "size=%ld+%lld%s",
+ GetHeaderSize(),
+ GetSize()-GetHeaderSize(),
extra);
inspector.StartElement(name, header);
@@ -325,14 +310,11 @@ AP4_Atom::InspectHeader(AP4_AtomInspector& inspector)
| AP4_Atom::Detach
+---------------------------------------------------------------------*/
AP4_Result
-AP4_Atom::Detach()
+AP4_Atom::Detach()
{
- if(m_Parent)
- {
+ if (m_Parent) {
return m_Parent->RemoveChild(this);
- }
- else
- {
+ } else {
return AP4_SUCCESS;
}
}
@@ -344,21 +326,21 @@ AP4_Atom*
AP4_Atom::Clone()
{
AP4_Atom* clone = NULL;
-
+
// check the size (refuse to clone atoms that are too large)
AP4_LargeSize size = GetSize();
- if(size > AP4_ATOM_MAX_CLONE_SIZE) return NULL;
+ if (size > AP4_ATOM_MAX_CLONE_SIZE) return NULL;
// create a memory byte stream to which we can serialize
AP4_MemoryByteStream* mbs = new AP4_MemoryByteStream((AP4_Size)GetSize());
-
+
// serialize to memory
- if(AP4_FAILED(Write(*mbs))) goto end;
-
+ if (AP4_FAILED(Write(*mbs))) goto end;
+
// create the clone for the serialized form
mbs->Seek(0);
AP4_DefaultAtomFactory::Instance.CreateAtomFromStream(*mbs, clone);
-
+
end:
// release the memory stream
mbs->Release();
@@ -369,41 +351,35 @@ end:
/*----------------------------------------------------------------------
| AP4_UnknownAtom::AP4_UnknownAtom
+---------------------------------------------------------------------*/
-AP4_UnknownAtom::AP4_UnknownAtom(Type type,
+AP4_UnknownAtom::AP4_UnknownAtom(Type type,
AP4_UI64 size,
- AP4_ByteStream& stream) :
+ AP4_ByteStream& stream) :
AP4_Atom(type, size),
m_SourceStream(&stream)
{
- if(size <= AP4_UNKNOWN_ATOM_MAX_LOCAL_PAYLOAD_SIZE &&
- type != AP4_ATOM_TYPE_MDAT)
- {
+ if (size <= AP4_UNKNOWN_ATOM_MAX_LOCAL_PAYLOAD_SIZE &&
+ type != AP4_ATOM_TYPE_MDAT) {
m_SourcePosition = 0;
m_SourceStream = NULL;
- AP4_UI32 payload_size = (AP4_UI32)size - GetHeaderSize();
+ AP4_UI32 payload_size = (AP4_UI32)size-GetHeaderSize();
m_Payload.SetDataSize(payload_size);
stream.Read(m_Payload.UseData(), payload_size);
return;
}
-
+
// store source stream position
stream.Tell(m_SourcePosition);
// clamp to the file size
AP4_UI64 file_size;
- if(AP4_SUCCEEDED(stream.GetSize(file_size)))
- {
- if(m_SourcePosition - GetHeaderSize() + size > file_size)
- {
- if(m_Size32 == 1)
- {
+ if (AP4_SUCCEEDED(stream.GetSize(file_size))) {
+ if (m_SourcePosition-GetHeaderSize()+size > file_size) {
+ if (m_Size32 == 1) {
// size is encoded as a large size
- m_Size64 = file_size - m_SourcePosition;
- }
- else
- {
+ m_Size64 = file_size-m_SourcePosition;
+ } else {
AP4_ASSERT(size <= 0xFFFFFFFF);
- m_Size32 = (AP4_UI32)(file_size - m_SourcePosition);
+ m_Size32 = (AP4_UI32)(file_size-m_SourcePosition);
}
}
}
@@ -415,10 +391,10 @@ AP4_UnknownAtom::AP4_UnknownAtom(Type type,
/*----------------------------------------------------------------------
| AP4_UnknownAtom::AP4_UnknownAtom
+---------------------------------------------------------------------*/
-AP4_UnknownAtom::AP4_UnknownAtom(Type type,
+AP4_UnknownAtom::AP4_UnknownAtom(Type type,
const AP4_UI08* payload,
AP4_Size payload_size) :
- AP4_Atom(type, AP4_ATOM_HEADER_SIZE + payload_size, false),
+ AP4_Atom(type, AP4_ATOM_HEADER_SIZE+payload_size, false),
m_SourceStream(NULL),
m_SourcePosition(0)
{
@@ -436,8 +412,7 @@ AP4_UnknownAtom::AP4_UnknownAtom(const AP4_UnknownAtom& other) :
{
m_Size32 = other.m_Size32;
m_Size64 = other.m_Size64;
- if(m_SourceStream)
- {
+ if (m_SourceStream) {
m_SourceStream->AddReference();
}
}
@@ -448,8 +423,7 @@ AP4_UnknownAtom::AP4_UnknownAtom(const AP4_UnknownAtom& other) :
AP4_UnknownAtom::~AP4_UnknownAtom()
{
// release the source stream reference
- if(m_SourceStream)
- {
+ if (m_SourceStream) {
m_SourceStream->Release();
}
}
@@ -463,23 +437,22 @@ AP4_UnknownAtom::WriteFields(AP4_ByteStream& stream)
AP4_Result result;
// if we don't have a source, write from the buffered payload
- if(m_SourceStream == NULL)
- {
+ if (m_SourceStream == NULL) {
return stream.Write(m_Payload.GetData(), m_Payload.GetDataSize());
}
-
+
// remember the source position
AP4_Position position;
m_SourceStream->Tell(position);
// seek into the source at the stored offset
result = m_SourceStream->Seek(m_SourcePosition);
- if(AP4_FAILED(result)) return result;
+ if (AP4_FAILED(result)) return result;
// copy the source stream to the output
- AP4_UI64 payload_size = GetSize() - GetHeaderSize();
+ AP4_UI64 payload_size = GetSize()-GetHeaderSize();
result = m_SourceStream->CopyTo(stream, payload_size);
- if(AP4_FAILED(result)) return result;
+ if (AP4_FAILED(result)) return result;
// restore the original stream position
m_SourceStream->Seek(position);
@@ -490,7 +463,7 @@ AP4_UnknownAtom::WriteFields(AP4_ByteStream& stream)
/*----------------------------------------------------------------------
| AP4_UnknownAtom::Clone
+---------------------------------------------------------------------*/
-AP4_Atom*
+AP4_Atom*
AP4_UnknownAtom::Clone()
{
return new AP4_UnknownAtom(*this);
@@ -503,18 +476,18 @@ AP4_NullTerminatedStringAtom::AP4_NullTerminatedStringAtom(AP4_Atom::Type type,
AP4_Atom(type, AP4_ATOM_HEADER_SIZE),
m_Value(value)
{
- m_Size32 += m_Value.GetLength() + 1;
+ m_Size32 += m_Value.GetLength()+1;
}
/*----------------------------------------------------------------------
| AP4_NullTerminatedStringAtom::AP4_NullTerminatedStringAtom
+---------------------------------------------------------------------*/
-AP4_NullTerminatedStringAtom::AP4_NullTerminatedStringAtom(AP4_Atom::Type type,
- AP4_UI64 size,
- AP4_ByteStream& stream) :
+AP4_NullTerminatedStringAtom::AP4_NullTerminatedStringAtom(AP4_Atom::Type type,
+ AP4_UI64 size,
+ AP4_ByteStream& stream) :
AP4_Atom(type, size)
{
- AP4_Size str_size = (AP4_Size)size - AP4_ATOM_HEADER_SIZE;
+ AP4_Size str_size = (AP4_Size)size-AP4_ATOM_HEADER_SIZE;
char* str = new char[str_size];
stream.Read(str, str_size);
str[str_size-1] = '\0'; // force null-termination
@@ -527,14 +500,13 @@ AP4_NullTerminatedStringAtom::AP4_NullTerminatedStringAtom(AP4_Atom::Type type,
AP4_Result
AP4_NullTerminatedStringAtom::WriteFields(AP4_ByteStream& stream)
{
- if(m_Size32 > AP4_ATOM_HEADER_SIZE)
- {
- AP4_Result result = stream.Write(m_Value.GetChars(), m_Value.GetLength() + 1);
- if(AP4_FAILED(result)) return result;
+ if (m_Size32 > AP4_ATOM_HEADER_SIZE) {
+ AP4_Result result = stream.Write(m_Value.GetChars(), m_Value.GetLength()+1);
+ if (AP4_FAILED(result)) return result;
// pad with zeros if necessary
- AP4_Size padding = m_Size32 - (AP4_ATOM_HEADER_SIZE + m_Value.GetLength() + 1);
- while(padding--) stream.WriteUI08(0);
+ AP4_Size padding = m_Size32-(AP4_ATOM_HEADER_SIZE+m_Value.GetLength()+1);
+ while (padding--) stream.WriteUI08(0);
}
return AP4_SUCCESS;
@@ -566,39 +538,30 @@ AP4_Result
AP4_AtomParent::AddChild(AP4_Atom* child, int position)
{
// check that the child does not already have a parent
- if(child->GetParent() != NULL) return AP4_ERROR_INVALID_PARAMETERS;
+ if (child->GetParent() != NULL) return AP4_ERROR_INVALID_PARAMETERS;
// attach the child
AP4_Result result;
- if(position == -1)
- {
+ if (position == -1) {
// insert at the tail
result = m_Children.Add(child);
- }
- else if(position == 0)
- {
+ } else if (position == 0) {
// insert at the head
result = m_Children.Insert(NULL, child);
- }
- else
- {
+ } else {
// insert after <n-1>
AP4_List<AP4_Atom>::Item* insertion_point = m_Children.FirstItem();
unsigned int count = position;
- while(insertion_point && --count)
- {
+ while (insertion_point && --count) {
insertion_point = insertion_point->GetNext();
}
- if(insertion_point)
- {
+ if (insertion_point) {
result = m_Children.Insert(insertion_point, child);
- }
- else
- {
+ } else {
result = AP4_ERROR_OUT_OF_RANGE;
}
}
- if(AP4_FAILED(result)) return result;
+ if (AP4_FAILED(result)) return result;
// notify the child of its parent
child->SetParent(this);
@@ -616,11 +579,11 @@ AP4_Result
AP4_AtomParent::RemoveChild(AP4_Atom* child)
{
// check that this is our child
- if(child->GetParent() != this) return AP4_ERROR_INVALID_PARAMETERS;
+ if (child->GetParent() != this) return AP4_ERROR_INVALID_PARAMETERS;
// remove the child
AP4_Result result = m_Children.Remove(child);
- if(AP4_FAILED(result)) return result;
+ if (AP4_FAILED(result)) return result;
// notify that child that it is orphaned
child->SetParent(NULL);
@@ -639,11 +602,11 @@ AP4_AtomParent::DeleteChild(AP4_Atom::Type type, AP4_Ordinal index /* = 0 */)
{
// find the child
AP4_Atom* child = GetChild(type, index);
- if(child == NULL) return AP4_FAILURE;
+ if (child == NULL) return AP4_FAILURE;
// remove the child
AP4_Result result = RemoveChild(child);
- if(AP4_FAILED(result)) return result;
+ if (AP4_FAILED(result)) return result;
// delete the child
delete child;
@@ -659,12 +622,9 @@ AP4_AtomParent::GetChild(AP4_Atom::Type type, AP4_Ordinal index /* = 0 */) const
{
AP4_Atom* atom;
AP4_Result result = m_Children.Find(AP4_AtomFinder(type, index), atom);
- if(AP4_SUCCEEDED(result))
- {
+ if (AP4_SUCCEEDED(result)) {
return atom;
- }
- else
- {
+ } else {
return NULL;
}
}
@@ -675,17 +635,14 @@ AP4_AtomParent::GetChild(AP4_Atom::Type type, AP4_Ordinal index /* = 0 */) const
AP4_Atom*
AP4_AtomParent::GetChild(const AP4_UI08* uuid, AP4_Ordinal index /* = 0 */) const
{
- for(AP4_List<AP4_Atom>::Item* item = m_Children.FirstItem();
- item;
- item = item->GetNext())
- {
+ for (AP4_List<AP4_Atom>::Item* item = m_Children.FirstItem();
+ item;
+ item = item->GetNext()) {
AP4_Atom* atom = item->GetData();
- if(atom->GetType() == AP4_ATOM_TYPE_UUID)
- {
+ if (atom->GetType() == AP4_ATOM_TYPE_UUID) {
AP4_UuidAtom* uuid_atom = AP4_DYNAMIC_CAST(AP4_UuidAtom, atom);
- if(AP4_CompareMemory(uuid_atom->GetUuid(), uuid, 16) == 0)
- {
- if(index == 0) return atom;
+ if (AP4_CompareMemory(uuid_atom->GetUuid(), uuid, 16) == 0) {
+ if (index == 0) return atom;
--index;
}
}
@@ -697,7 +654,7 @@ AP4_AtomParent::GetChild(const AP4_UI08* uuid, AP4_Ordinal index /* = 0 */) cons
| AP4_AtomParent::FindChild
+---------------------------------------------------------------------*/
AP4_Atom*
-AP4_AtomParent::FindChild(const char* path,
+AP4_AtomParent::FindChild(const char* path,
bool auto_create,
bool auto_create_full)
{
@@ -705,83 +662,58 @@ AP4_AtomParent::FindChild(const char* path,
AP4_AtomParent* parent = this;
// walk the path
- while(path[0] && path[1] && path[2] && path[3])
- {
+ while (path[0] && path[1] && path[2] && path[3]) {
// we have 4 valid chars
const char* tail;
int index = 0;
- if(path[4] == '\0')
- {
+ if (path[4] == '\0') {
tail = NULL;
- }
- else if(path[4] == '/')
- {
+ } else if (path[4] == '/') {
// separator
tail = &path[5];
- }
- else if(path[4] == '[')
- {
+ } else if (path[4] == '[') {
const char* x = &path[5];
- while(*x >= '0' && *x <= '9')
- {
- index = 10 * index + (*x++ - '0');
+ while (*x >= '0' && *x <= '9') {
+ index = 10*index+(*x++ - '0');
}
- if(x[0] == ']')
- {
- if(x[1] == '\0')
- {
+ if (x[0] == ']') {
+ if (x[1] == '\0') {
tail = NULL;
+ } else {
+ tail = x+2;
}
- else
- {
- tail = x + 2;
- }
- }
- else
- {
+ } else {
// malformed path
return NULL;
}
- }
- else
- {
+ } else {
// malformed path
return NULL;
}
// look for this atom in the current list
- AP4_Atom::Type type = AP4_ATOM_TYPE(path[0], path[1], path[2], path[3]);
+ AP4_Atom::Type type = AP4_ATOM_TYPE(path[0], path[1], path[2], path[3]);
AP4_Atom* atom = parent->GetChild(type, index);
- if(atom == NULL)
- {
+ if (atom == NULL) {
// not found
- if(auto_create && (index == 0))
- {
- if(auto_create_full)
- {
+ if (auto_create && (index == 0)) {
+ if (auto_create_full) {
atom = new AP4_ContainerAtom(type, (AP4_UI32)0, (AP4_UI32)0);
- }
- else
- {
+ } else {
atom = new AP4_ContainerAtom(type);
}
parent->AddChild(atom);
- }
- else
- {
+ } else {
return NULL;
}
}
- if(tail)
- {
+ if (tail) {
path = tail;
// if this atom is an atom parent, recurse
parent = AP4_DYNAMIC_CAST(AP4_ContainerAtom, atom);
- if(parent == NULL) return NULL;
- }
- else
- {
+ if (parent == NULL) return NULL;
+ } else {
return atom;
}
}
@@ -793,7 +725,7 @@ AP4_AtomParent::FindChild(const char* path,
/*----------------------------------------------------------------------
| AP4_AtomListWriter::Action
+---------------------------------------------------------------------*/
-const unsigned int AP4_ATOM_LIST_WRITER_MAX_PADDING = 1024;
+const unsigned int AP4_ATOM_LIST_WRITER_MAX_PADDING=1024;
AP4_Result
AP4_AtomListWriter::Action(AP4_Atom* atom) const
@@ -806,21 +738,16 @@ AP4_AtomListWriter::Action(AP4_Atom* atom) const
AP4_Position after;
m_Stream.Tell(after);
- AP4_UI64 bytes_written = after - before;
+ AP4_UI64 bytes_written = after-before;
AP4_ASSERT(bytes_written <= atom->GetSize());
- if(bytes_written < atom->GetSize())
- {
+ if (bytes_written < atom->GetSize()) {
AP4_Debug("WARNING: atom serialized to fewer bytes than declared size\n");
- AP4_UI64 padding = atom->GetSize() - bytes_written;
- if(padding > AP4_ATOM_LIST_WRITER_MAX_PADDING)
- {
+ AP4_UI64 padding = atom->GetSize()-bytes_written;
+ if (padding > AP4_ATOM_LIST_WRITER_MAX_PADDING) {
AP4_Debug("WARNING: padding would be too large\n");
return AP4_FAILURE;
- }
- else
- {
- for(unsigned int i = 0; i < padding; i++)
- {
+ } else {
+ for (unsigned int i=0; i<padding; i++) {
m_Stream.WriteUI08(0);
}
}
@@ -835,19 +762,18 @@ AP4_AtomListWriter::Action(AP4_Atom* atom) const
static void
AP4_MakePrefixString(unsigned int indent, char* prefix, AP4_Size size)
{
- if(size == 0) return;
- if(indent >= size - 1) indent = size - 1;
- for(unsigned int i = 0; i < indent; i++)
- {
+ if (size == 0) return;
+ if (indent >= size-1) indent = size-1;
+ for (unsigned int i=0; i<indent; i++) {
prefix[i] = ' ';
}
- prefix[indent] = '\0';
+ prefix[indent] = '\0';
}
/*----------------------------------------------------------------------
| AP4_PrintInspector::AP4_PrintInspector
+---------------------------------------------------------------------*/
-AP4_PrintInspector::AP4_PrintInspector(AP4_ByteStream& stream, AP4_Cardinal indent) :
+ AP4_PrintInspector::AP4_PrintInspector(AP4_ByteStream& stream, AP4_Cardinal indent) :
m_Stream(&stream),
m_Indent(indent)
{
@@ -872,8 +798,7 @@ AP4_PrintInspector::StartElement(const char* name, const char* info)
AP4_MakePrefixString(m_Indent, prefix, sizeof(prefix));
m_Stream->WriteString(prefix);
m_Stream->WriteString(name);
- if(info)
- {
+ if (info) {
m_Stream->Write(" ", 1);
m_Stream->WriteString(info);
}
@@ -900,7 +825,7 @@ AP4_PrintInspector::AddField(const char* name, const char* value, FormatHint)
char prefix[256];
AP4_MakePrefixString(m_Indent, prefix, sizeof(prefix));
m_Stream->WriteString(prefix);
-
+
m_Stream->WriteString(name);
m_Stream->WriteString(" = ");
m_Stream->WriteString(value);
@@ -918,8 +843,8 @@ AP4_PrintInspector::AddField(const char* name, AP4_UI64 value, FormatHint hint)
m_Stream->WriteString(prefix);
char str[32];
- AP4_FormatString(str, sizeof(str),
- hint == HINT_HEX ? "%llx" : "%lld",
+ AP4_FormatString(str, sizeof(str),
+ hint == HINT_HEX ? "%llx":"%lld",
value);
m_Stream->WriteString(name);
m_Stream->WriteString(" = ");
@@ -938,8 +863,8 @@ AP4_PrintInspector::AddFieldF(const char* name, float value, FormatHint /*hint*/
m_Stream->WriteString(prefix);
char str[32];
- AP4_FormatString(str, sizeof(str),
- "%f",
+ AP4_FormatString(str, sizeof(str),
+ "%f",
value);
m_Stream->WriteString(name);
m_Stream->WriteString(" = ");
@@ -951,8 +876,8 @@ AP4_PrintInspector::AddFieldF(const char* name, float value, FormatHint /*hint*/
| AP4_PrintInspector::AddField
+---------------------------------------------------------------------*/
void
-AP4_PrintInspector::AddField(const char* name,
- const unsigned char* bytes,
+AP4_PrintInspector::AddField(const char* name,
+ const unsigned char* bytes,
AP4_Size byte_count,
FormatHint /* hint */)
{
@@ -964,10 +889,9 @@ AP4_PrintInspector::AddField(const char* name,
m_Stream->WriteString(" = [");
unsigned int offset = 1;
char byte[4];
- for(unsigned int i = 0; i < byte_count; i++)
- {
+ for (unsigned int i=0; i<byte_count; i++) {
AP4_FormatString(byte, 4, " %02x", bytes[i]);
- m_Stream->Write(&byte[offset], 3 - offset);
+ m_Stream->Write(&byte[offset], 3-offset);
offset = 0;
}
m_Stream->Write("]\n", 2);
diff --git a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4Atom.h b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4Atom.h
index 9685547ac..7301821a3 100644
--- a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4Atom.h
+++ b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4Atom.h
@@ -1,6 +1,6 @@
/*****************************************************************
|
-| AP4 - Atoms
+| AP4 - Atoms
|
| Copyright 2002-2008 Axiomatic Systems, LLC
|
@@ -26,7 +26,7 @@
|
****************************************************************/
/**
-* @file
+* @file
* @brief Atoms
*/
@@ -72,14 +72,12 @@ class AP4_AtomParent;
+---------------------------------------------------------------------*/
/**
* Class used in a visitor pattern to walk all the atoms in a tree of
- * #AP4_Atom objects.
+ * #AP4_Atom objects.
*/
-class AP4_AtomInspector
-{
+class AP4_AtomInspector {
public:
// types
- typedef enum
- {
+ typedef enum {
HINT_NONE = 0,
HINT_HEX = 1,
HINT_BOOLEAN = 2
@@ -90,45 +88,35 @@ public:
virtual ~AP4_AtomInspector() {}
// methods
- void SetVerbosity(AP4_Ordinal verbosity)
- {
- m_Verbosity = verbosity;
- }
- AP4_Ordinal GetVerbosity()
- {
- return m_Verbosity;
- }
-
+ void SetVerbosity(AP4_Ordinal verbosity) { m_Verbosity = verbosity; }
+ AP4_Ordinal GetVerbosity() { return m_Verbosity; }
+
// virtual methods
- virtual void StartElement(const char* /* name */,
+ virtual void StartElement(const char* /* name */,
const char* /* extra = NULL */) {}
virtual void EndElement() {}
- virtual void AddField(const char* /* name */,
- AP4_UI64 /* value */,
- FormatHint hint = HINT_NONE)
- {
+ virtual void AddField(const char* /* name */,
+ AP4_UI64 /* value */,
+ FormatHint hint = HINT_NONE) {
(void)hint; // gcc warning
}
- virtual void AddFieldF(const char* /* name */,
- float /* value */,
- FormatHint hint = HINT_NONE)
- {
+ virtual void AddFieldF(const char* /* name */,
+ float /* value */,
+ FormatHint hint = HINT_NONE) {
(void)hint; // gcc warning
}
- virtual void AddField(const char* /* name */,
- const char* /* value */,
- FormatHint hint = HINT_NONE)
- {
- (void)hint; // gcc warning
+ virtual void AddField(const char* /* name */,
+ const char* /* value */,
+ FormatHint hint = HINT_NONE) {
+ (void)hint; // gcc warning
}
- virtual void AddField(const char* /* name */,
- const unsigned char* /* bytes */,
- AP4_Size /* byte_count */,
- FormatHint hint = HINT_NONE)
- {
- (void)hint; // gcc warning
+ virtual void AddField(const char* /* name */,
+ const unsigned char* /* bytes */,
+ AP4_Size /* byte_count */,
+ FormatHint hint = HINT_NONE) {
+ (void)hint; // gcc warning
}
-
+
protected:
AP4_Ordinal m_Verbosity;
};
@@ -136,10 +124,9 @@ protected:
/*----------------------------------------------------------------------
| AP4_PrintInspector
+---------------------------------------------------------------------*/
-class AP4_PrintInspector : public AP4_AtomInspector
-{
+class AP4_PrintInspector : public AP4_AtomInspector {
public:
- AP4_PrintInspector(AP4_ByteStream& stream, AP4_Cardinal indent = 0);
+ AP4_PrintInspector(AP4_ByteStream& stream, AP4_Cardinal indent=0);
~AP4_PrintInspector();
// methods
@@ -162,18 +149,17 @@ private:
/**
* Abstract base class for all atom types.
*/
-class AP4_Atom
-{
+class AP4_Atom {
public:
- AP4_IMPLEMENT_DYNAMIC_CAST(AP4_Atom)
+ AP4_IMPLEMENT_DYNAMIC_CAST(AP4_Atom)
- // types
+ // types
typedef AP4_UI32 Type;
// class methods
static Type TypeFromString(const char* four_cc);
- static AP4_Result ReadFullHeader(AP4_ByteStream& stream,
- AP4_UI32& version,
+ static AP4_Result ReadFullHeader(AP4_ByteStream& stream,
+ AP4_UI32& version,
AP4_UI32& flags);
// constructors
@@ -185,87 +171,55 @@ public:
/**
* Create a simple atom with a specified type and 64-bit size.
*/
- explicit AP4_Atom(Type type, AP4_UI64 size, bool force_64 = false);
+ explicit AP4_Atom(Type type, AP4_UI64 size, bool force_64=false);
/**
* Create a full atom with a specified type, 32-bit size, version and flags.
*/
- explicit AP4_Atom(Type type,
+ explicit AP4_Atom(Type type,
AP4_UI32 size,
- AP4_UI32 version,
+ AP4_UI32 version,
AP4_UI32 flags);
/**
* Create a full atom with a specified type, 64-bit size, version and flags.
*/
- explicit AP4_Atom(Type type,
+ explicit AP4_Atom(Type type,
AP4_UI64 size,
bool force_64,
- AP4_UI32 version,
+ AP4_UI32 version,
AP4_UI32 flags);
// destructor
virtual ~AP4_Atom() {}
-
+
// methods
- AP4_UI32 GetFlags() const
- {
- return m_Flags;
- }
- void SetFlags(AP4_UI32 flags)
- {
- m_Flags = flags;
- }
- Type GetType() const
- {
- return m_Type;
- }
- void SetType(Type type)
- {
- m_Type = type;
- }
+ AP4_UI32 GetFlags() const { return m_Flags; }
+ void SetFlags(AP4_UI32 flags) { m_Flags = flags; }
+ Type GetType() const { return m_Type; }
+ void SetType(Type type) { m_Type = type; }
virtual AP4_Size GetHeaderSize() const;
- AP4_UI64 GetSize() const
- {
- return m_Size32 == 1 ? m_Size64 : m_Size32;
- }
+ AP4_UI64 GetSize() const { return m_Size32 == 1?m_Size64:m_Size32; }
void SetSize(AP4_UI64 size, bool force_64 = false);
- AP4_UI32 GetSize32() const
- {
- return m_Size32;
- }
- void SetSize32(AP4_UI32 size)
- {
- m_Size32 = size;
- }
- AP4_UI64 GetSize64() const
- {
- return m_Size64;
- }
- void SetSize64(AP4_UI64 size)
- {
- m_Size64 = size;
- }
+ AP4_UI32 GetSize32() const { return m_Size32; }
+ void SetSize32(AP4_UI32 size) { m_Size32 = size; }
+ AP4_UI64 GetSize64() const { return m_Size64; }
+ void SetSize64(AP4_UI64 size) { m_Size64 = size; }
virtual AP4_Result Write(AP4_ByteStream& stream);
virtual AP4_Result WriteHeader(AP4_ByteStream& stream);
virtual AP4_Result WriteFields(AP4_ByteStream& stream) = 0;
virtual AP4_Result Inspect(AP4_AtomInspector& inspector);
virtual AP4_Result InspectHeader(AP4_AtomInspector& inspector);
- virtual AP4_Result InspectFields(AP4_AtomInspector& /* inspector */)
- {
- return AP4_SUCCESS;
+ virtual AP4_Result InspectFields(AP4_AtomInspector& /* inspector */) {
+ return AP4_SUCCESS;
}
// parent/child relationship methods
- virtual AP4_Result SetParent(AP4_AtomParent* parent)
- {
+ virtual AP4_Result SetParent(AP4_AtomParent* parent) {
m_Parent = parent;
return AP4_SUCCESS;
}
- virtual AP4_AtomParent* GetParent()
- {
- return m_Parent;
- }
+ virtual AP4_AtomParent* GetParent() { return m_Parent; }
virtual AP4_Result Detach();
/**
@@ -274,15 +228,15 @@ public:
* the atom cannot be cloned.
* Override this if your want to make an atom cloneable in a more
* efficient way than the default implementation.
- */
+ */
virtual AP4_Atom* Clone();
-protected:
+ protected:
// members
Type m_Type;
- AP4_UI32 m_Size32;
+ AP4_UI32 m_Size32;
AP4_UI64 m_Size64; // this is 0 if m_Size is not 1 (encoded in 32-bits)
- // and non-zero only if m_Size is 1 (encoded in 64-bits)
+ // and non-zero only if m_Size is 1 (encoded in 64-bits)
bool m_IsFull;
AP4_UI32 m_Version;
AP4_UI32 m_Flags;
@@ -296,23 +250,19 @@ protected:
* Base class for containers of atoms.
* This class also implements the logic for finding descendents by name.
*/
-class AP4_AtomParent
-{
+class AP4_AtomParent {
public:
AP4_IMPLEMENT_DYNAMIC_CAST(AP4_AtomParent)
// base methods
virtual ~AP4_AtomParent();
- AP4_List<AP4_Atom>& GetChildren()
- {
- return m_Children;
- }
+ AP4_List<AP4_Atom>& GetChildren() { return m_Children; }
virtual AP4_Result AddChild(AP4_Atom* child, int position = -1);
virtual AP4_Result RemoveChild(AP4_Atom* child);
virtual AP4_Result DeleteChild(AP4_Atom::Type type, AP4_Ordinal index = 0);
virtual AP4_Atom* GetChild(AP4_Atom::Type type, AP4_Ordinal index = 0) const;
virtual AP4_Atom* GetChild(const AP4_UI08* uuid, AP4_Ordinal index = 0) const;
- virtual AP4_Atom* FindChild(const char* path,
+ virtual AP4_Atom* FindChild(const char* path,
bool auto_create = false,
bool auto_create_full = false);
@@ -331,18 +281,17 @@ protected:
+---------------------------------------------------------------------*/
/**
* Class that represents atoms for which there is no specific support.
- * Instances of this class keep a reference to the stream from which
+ * Instances of this class keep a reference to the stream from which
* the atom is parsed, so that it can read the atom's payload when it
* is serialized.
- * If the atom is small, its payload is actually read and stored in
+ * If the atom is small, its payload is actually read and stored in
* a data buffer, so no reference to the source stream is kept
*/
-class AP4_UnknownAtom : public AP4_Atom
-{
+class AP4_UnknownAtom : public AP4_Atom {
public:
// constructor and destructor
- AP4_UnknownAtom(AP4_Atom::Type type,
- AP4_UI64 size,
+ AP4_UnknownAtom(AP4_Atom::Type type,
+ AP4_UI64 size,
AP4_ByteStream& stream);
AP4_UnknownAtom(AP4_Atom::Type type, const AP4_UI08* payload, AP4_Size payload_size);
AP4_UnknownAtom(const AP4_UnknownAtom& other);
@@ -376,11 +325,8 @@ public:
AP4_NullTerminatedStringAtom(AP4_Atom::Type type, const char* value);
// accessors
- const AP4_String& GetValue()
- {
- return m_Value;
- }
-
+ const AP4_String& GetValue() { return m_Value; }
+
// methods
virtual AP4_Result InspectFields(AP4_AtomInspector& inspector);
virtual AP4_Result WriteFields(AP4_ByteStream& stream);
@@ -393,133 +339,133 @@ private:
/*----------------------------------------------------------------------
| atom types
+---------------------------------------------------------------------*/
-const AP4_Atom::Type AP4_ATOM_TYPE_UDTA = AP4_ATOM_TYPE('u', 'd', 't', 'a');
-const AP4_Atom::Type AP4_ATOM_TYPE_URL = AP4_ATOM_TYPE('u', 'r', 'l', ' ');
-const AP4_Atom::Type AP4_ATOM_TYPE_TRAK = AP4_ATOM_TYPE('t', 'r', 'a', 'k');
-const AP4_Atom::Type AP4_ATOM_TYPE_TRAF = AP4_ATOM_TYPE('t', 'r', 'a', 'f');
-const AP4_Atom::Type AP4_ATOM_TYPE_TKHD = AP4_ATOM_TYPE('t', 'k', 'h', 'd');
-const AP4_Atom::Type AP4_ATOM_TYPE_TFHD = AP4_ATOM_TYPE('t', 'f', 'h', 'd');
-const AP4_Atom::Type AP4_ATOM_TYPE_TRUN = AP4_ATOM_TYPE('t', 'r', 'u', 'n');
-const AP4_Atom::Type AP4_ATOM_TYPE_STTS = AP4_ATOM_TYPE('s', 't', 't', 's');
-const AP4_Atom::Type AP4_ATOM_TYPE_STSZ = AP4_ATOM_TYPE('s', 't', 's', 'z');
-const AP4_Atom::Type AP4_ATOM_TYPE_STSS = AP4_ATOM_TYPE('s', 't', 's', 's');
-const AP4_Atom::Type AP4_ATOM_TYPE_STSD = AP4_ATOM_TYPE('s', 't', 's', 'd');
-const AP4_Atom::Type AP4_ATOM_TYPE_STSC = AP4_ATOM_TYPE('s', 't', 's', 'c');
-const AP4_Atom::Type AP4_ATOM_TYPE_STCO = AP4_ATOM_TYPE('s', 't', 'c', 'o');
-const AP4_Atom::Type AP4_ATOM_TYPE_CO64 = AP4_ATOM_TYPE('c', 'o', '6', '4');
-const AP4_Atom::Type AP4_ATOM_TYPE_STBL = AP4_ATOM_TYPE('s', 't', 'b', 'l');
-const AP4_Atom::Type AP4_ATOM_TYPE_SINF = AP4_ATOM_TYPE('s', 'i', 'n', 'f');
-const AP4_Atom::Type AP4_ATOM_TYPE_SCHM = AP4_ATOM_TYPE('s', 'c', 'h', 'm');
-const AP4_Atom::Type AP4_ATOM_TYPE_SCHI = AP4_ATOM_TYPE('s', 'c', 'h', 'i');
-const AP4_Atom::Type AP4_ATOM_TYPE_MVHD = AP4_ATOM_TYPE('m', 'v', 'h', 'd');
-const AP4_Atom::Type AP4_ATOM_TYPE_MEHD = AP4_ATOM_TYPE('m', 'e', 'h', 'd');
-const AP4_Atom::Type AP4_ATOM_TYPE_MP4S = AP4_ATOM_TYPE('m', 'p', '4', 's');
-const AP4_Atom::Type AP4_ATOM_TYPE_MP4A = AP4_ATOM_TYPE('m', 'p', '4', 'a');
-const AP4_Atom::Type AP4_ATOM_TYPE_MP4V = AP4_ATOM_TYPE('m', 'p', '4', 'v');
-const AP4_Atom::Type AP4_ATOM_TYPE_AVC1 = AP4_ATOM_TYPE('a', 'v', 'c', '1');
-const AP4_Atom::Type AP4_ATOM_TYPE_ALAC = AP4_ATOM_TYPE('a', 'l', 'a', 'c');
-const AP4_Atom::Type AP4_ATOM_TYPE_ENCA = AP4_ATOM_TYPE('e', 'n', 'c', 'a');
-const AP4_Atom::Type AP4_ATOM_TYPE_ENCV = AP4_ATOM_TYPE('e', 'n', 'c', 'v');
-const AP4_Atom::Type AP4_ATOM_TYPE_MOOV = AP4_ATOM_TYPE('m', 'o', 'o', 'v');
-const AP4_Atom::Type AP4_ATOM_TYPE_MOOF = AP4_ATOM_TYPE('m', 'o', 'o', 'f');
-const AP4_Atom::Type AP4_ATOM_TYPE_MVEX = AP4_ATOM_TYPE('m', 'v', 'e', 'x');
-const AP4_Atom::Type AP4_ATOM_TYPE_TREX = AP4_ATOM_TYPE('t', 'r', 'e', 'x');
-const AP4_Atom::Type AP4_ATOM_TYPE_MINF = AP4_ATOM_TYPE('m', 'i', 'n', 'f');
-const AP4_Atom::Type AP4_ATOM_TYPE_META = AP4_ATOM_TYPE('m', 'e', 't', 'a');
-const AP4_Atom::Type AP4_ATOM_TYPE_MDHD = AP4_ATOM_TYPE('m', 'd', 'h', 'd');
-const AP4_Atom::Type AP4_ATOM_TYPE_MFHD = AP4_ATOM_TYPE('m', 'f', 'h', 'd');
-const AP4_Atom::Type AP4_ATOM_TYPE_ILST = AP4_ATOM_TYPE('i', 'l', 's', 't');
-const AP4_Atom::Type AP4_ATOM_TYPE_HDLR = AP4_ATOM_TYPE('h', 'd', 'l', 'r');
-const AP4_Atom::Type AP4_ATOM_TYPE_FTYP = AP4_ATOM_TYPE('f', 't', 'y', 'p');
-const AP4_Atom::Type AP4_ATOM_TYPE_IODS = AP4_ATOM_TYPE('i', 'o', 'd', 's');
-const AP4_Atom::Type AP4_ATOM_TYPE_ESDS = AP4_ATOM_TYPE('e', 's', 'd', 's');
-const AP4_Atom::Type AP4_ATOM_TYPE_EDTS = AP4_ATOM_TYPE('e', 'd', 't', 's');
-const AP4_Atom::Type AP4_ATOM_TYPE_DRMS = AP4_ATOM_TYPE('d', 'r', 'm', 's');
-const AP4_Atom::Type AP4_ATOM_TYPE_DRMI = AP4_ATOM_TYPE('d', 'r', 'm', 'i');
-const AP4_Atom::Type AP4_ATOM_TYPE_DREF = AP4_ATOM_TYPE('d', 'r', 'e', 'f');
-const AP4_Atom::Type AP4_ATOM_TYPE_DINF = AP4_ATOM_TYPE('d', 'i', 'n', 'f');
-const AP4_Atom::Type AP4_ATOM_TYPE_CTTS = AP4_ATOM_TYPE('c', 't', 't', 's');
-const AP4_Atom::Type AP4_ATOM_TYPE_MDIA = AP4_ATOM_TYPE('m', 'd', 'i', 'a');
-const AP4_Atom::Type AP4_ATOM_TYPE_ELST = AP4_ATOM_TYPE('e', 'l', 's', 't');
-const AP4_Atom::Type AP4_ATOM_TYPE_VMHD = AP4_ATOM_TYPE('v', 'm', 'h', 'd');
-const AP4_Atom::Type AP4_ATOM_TYPE_SMHD = AP4_ATOM_TYPE('s', 'm', 'h', 'd');
-const AP4_Atom::Type AP4_ATOM_TYPE_NMHD = AP4_ATOM_TYPE('n', 'm', 'h', 'd');
-const AP4_Atom::Type AP4_ATOM_TYPE_HMHD = AP4_ATOM_TYPE('h', 'm', 'h', 'd');
-const AP4_Atom::Type AP4_ATOM_TYPE_FRMA = AP4_ATOM_TYPE('f', 'r', 'm', 'a');
-const AP4_Atom::Type AP4_ATOM_TYPE_MDAT = AP4_ATOM_TYPE('m', 'd', 'a', 't');
-const AP4_Atom::Type AP4_ATOM_TYPE_FREE = AP4_ATOM_TYPE('f', 'r', 'e', 'e');
-const AP4_Atom::Type AP4_ATOM_TYPE_TIMS = AP4_ATOM_TYPE('t', 'i', 'm', 's');
-const AP4_Atom::Type AP4_ATOM_TYPE_RTP_ = AP4_ATOM_TYPE('r', 't', 'p', ' ');
-const AP4_Atom::Type AP4_ATOM_TYPE_HNTI = AP4_ATOM_TYPE('h', 'n', 't', 'i');
-const AP4_Atom::Type AP4_ATOM_TYPE_SDP_ = AP4_ATOM_TYPE('s', 'd', 'p', ' ');
-const AP4_Atom::Type AP4_ATOM_TYPE_IKMS = AP4_ATOM_TYPE('i', 'K', 'M', 'S');
-const AP4_Atom::Type AP4_ATOM_TYPE_ISFM = AP4_ATOM_TYPE('i', 'S', 'F', 'M');
-const AP4_Atom::Type AP4_ATOM_TYPE_ISLT = AP4_ATOM_TYPE('i', 'S', 'L', 'T');
-const AP4_Atom::Type AP4_ATOM_TYPE_TREF = AP4_ATOM_TYPE('t', 'r', 'e', 'f');
-const AP4_Atom::Type AP4_ATOM_TYPE_HINT = AP4_ATOM_TYPE('h', 'i', 'n', 't');
-const AP4_Atom::Type AP4_ATOM_TYPE_CDSC = AP4_ATOM_TYPE('c', 'd', 's', 'c');
-const AP4_Atom::Type AP4_ATOM_TYPE_MPOD = AP4_ATOM_TYPE('m', 'p', 'o', 'd');
-const AP4_Atom::Type AP4_ATOM_TYPE_IPIR = AP4_ATOM_TYPE('i', 'p', 'i', 'r');
-const AP4_Atom::Type AP4_ATOM_TYPE_CHAP = AP4_ATOM_TYPE('c', 'h', 'a', 'p');
-const AP4_Atom::Type AP4_ATOM_TYPE_ALIS = AP4_ATOM_TYPE('a', 'l', 'i', 's');
-const AP4_Atom::Type AP4_ATOM_TYPE_SYNC = AP4_ATOM_TYPE('s', 'y', 'n', 'c');
-const AP4_Atom::Type AP4_ATOM_TYPE_DPND = AP4_ATOM_TYPE('d', 'p', 'n', 'd');
-const AP4_Atom::Type AP4_ATOM_TYPE_ODRM = AP4_ATOM_TYPE('o', 'd', 'r', 'm');
-const AP4_Atom::Type AP4_ATOM_TYPE_ODKM = AP4_ATOM_TYPE('o', 'd', 'k', 'm');
-const AP4_Atom::Type AP4_ATOM_TYPE_OHDR = AP4_ATOM_TYPE('o', 'h', 'd', 'r');
-const AP4_Atom::Type AP4_ATOM_TYPE_ODDA = AP4_ATOM_TYPE('o', 'd', 'd', 'a');
-const AP4_Atom::Type AP4_ATOM_TYPE_ODHE = AP4_ATOM_TYPE('o', 'd', 'h', 'e');
-const AP4_Atom::Type AP4_ATOM_TYPE_ODAF = AP4_ATOM_TYPE('o', 'd', 'a', 'f');
-const AP4_Atom::Type AP4_ATOM_TYPE_GRPI = AP4_ATOM_TYPE('g', 'r', 'p', 'i');
-const AP4_Atom::Type AP4_ATOM_TYPE_IPRO = AP4_ATOM_TYPE('i', 'p', 'r', 'o');
-const AP4_Atom::Type AP4_ATOM_TYPE_MDRI = AP4_ATOM_TYPE('m', 'd', 'r', 'i');
-const AP4_Atom::Type AP4_ATOM_TYPE_AVCC = AP4_ATOM_TYPE('a', 'v', 'c', 'C');
-const AP4_Atom::Type AP4_ATOM_TYPE_WAVE = AP4_ATOM_TYPE('w', 'a', 'v', 'e');
-const AP4_Atom::Type AP4_ATOM_TYPE_WIDE = AP4_ATOM_TYPE('w', 'i', 'd', 'e');
-const AP4_Atom::Type AP4_ATOM_TYPE_UUID = AP4_ATOM_TYPE('u', 'u', 'i', 'd');
-const AP4_Atom::Type AP4_ATOM_TYPE_8ID_ = AP4_ATOM_TYPE('8', 'i', 'd', ' ');
-const AP4_Atom::Type AP4_ATOM_TYPE_8BDL = AP4_ATOM_TYPE('8', 'b', 'd', 'l');
-const AP4_Atom::Type AP4_ATOM_TYPE_AC_3 = AP4_ATOM_TYPE('a', 'c', '-', '3');
-const AP4_Atom::Type AP4_ATOM_TYPE_EC_3 = AP4_ATOM_TYPE('e', 'c', '-', '3');
-const AP4_Atom::Type AP4_ATOM_TYPE_MFRA = AP4_ATOM_TYPE('m', 'f', 'r', 'a');
-const AP4_Atom::Type AP4_ATOM_TYPE_TFRA = AP4_ATOM_TYPE('t', 'f', 'r', 'a');
-const AP4_Atom::Type AP4_ATOM_TYPE_MFRO = AP4_ATOM_TYPE('m', 'f', 'r', 'o');
+const AP4_Atom::Type AP4_ATOM_TYPE_UDTA = AP4_ATOM_TYPE('u','d','t','a');
+const AP4_Atom::Type AP4_ATOM_TYPE_URL = AP4_ATOM_TYPE('u','r','l',' ');
+const AP4_Atom::Type AP4_ATOM_TYPE_TRAK = AP4_ATOM_TYPE('t','r','a','k');
+const AP4_Atom::Type AP4_ATOM_TYPE_TRAF = AP4_ATOM_TYPE('t','r','a','f');
+const AP4_Atom::Type AP4_ATOM_TYPE_TKHD = AP4_ATOM_TYPE('t','k','h','d');
+const AP4_Atom::Type AP4_ATOM_TYPE_TFHD = AP4_ATOM_TYPE('t','f','h','d');
+const AP4_Atom::Type AP4_ATOM_TYPE_TRUN = AP4_ATOM_TYPE('t','r','u','n');
+const AP4_Atom::Type AP4_ATOM_TYPE_STTS = AP4_ATOM_TYPE('s','t','t','s');
+const AP4_Atom::Type AP4_ATOM_TYPE_STSZ = AP4_ATOM_TYPE('s','t','s','z');
+const AP4_Atom::Type AP4_ATOM_TYPE_STSS = AP4_ATOM_TYPE('s','t','s','s');
+const AP4_Atom::Type AP4_ATOM_TYPE_STSD = AP4_ATOM_TYPE('s','t','s','d');
+const AP4_Atom::Type AP4_ATOM_TYPE_STSC = AP4_ATOM_TYPE('s','t','s','c');
+const AP4_Atom::Type AP4_ATOM_TYPE_STCO = AP4_ATOM_TYPE('s','t','c','o');
+const AP4_Atom::Type AP4_ATOM_TYPE_CO64 = AP4_ATOM_TYPE('c','o','6','4');
+const AP4_Atom::Type AP4_ATOM_TYPE_STBL = AP4_ATOM_TYPE('s','t','b','l');
+const AP4_Atom::Type AP4_ATOM_TYPE_SINF = AP4_ATOM_TYPE('s','i','n','f');
+const AP4_Atom::Type AP4_ATOM_TYPE_SCHM = AP4_ATOM_TYPE('s','c','h','m');
+const AP4_Atom::Type AP4_ATOM_TYPE_SCHI = AP4_ATOM_TYPE('s','c','h','i');
+const AP4_Atom::Type AP4_ATOM_TYPE_MVHD = AP4_ATOM_TYPE('m','v','h','d');
+const AP4_Atom::Type AP4_ATOM_TYPE_MEHD = AP4_ATOM_TYPE('m','e','h','d');
+const AP4_Atom::Type AP4_ATOM_TYPE_MP4S = AP4_ATOM_TYPE('m','p','4','s');
+const AP4_Atom::Type AP4_ATOM_TYPE_MP4A = AP4_ATOM_TYPE('m','p','4','a');
+const AP4_Atom::Type AP4_ATOM_TYPE_MP4V = AP4_ATOM_TYPE('m','p','4','v');
+const AP4_Atom::Type AP4_ATOM_TYPE_AVC1 = AP4_ATOM_TYPE('a','v','c','1');
+const AP4_Atom::Type AP4_ATOM_TYPE_ALAC = AP4_ATOM_TYPE('a','l','a','c');
+const AP4_Atom::Type AP4_ATOM_TYPE_ENCA = AP4_ATOM_TYPE('e','n','c','a');
+const AP4_Atom::Type AP4_ATOM_TYPE_ENCV = AP4_ATOM_TYPE('e','n','c','v');
+const AP4_Atom::Type AP4_ATOM_TYPE_MOOV = AP4_ATOM_TYPE('m','o','o','v');
+const AP4_Atom::Type AP4_ATOM_TYPE_MOOF = AP4_ATOM_TYPE('m','o','o','f');
+const AP4_Atom::Type AP4_ATOM_TYPE_MVEX = AP4_ATOM_TYPE('m','v','e','x');
+const AP4_Atom::Type AP4_ATOM_TYPE_TREX = AP4_ATOM_TYPE('t','r','e','x');
+const AP4_Atom::Type AP4_ATOM_TYPE_MINF = AP4_ATOM_TYPE('m','i','n','f');
+const AP4_Atom::Type AP4_ATOM_TYPE_META = AP4_ATOM_TYPE('m','e','t','a');
+const AP4_Atom::Type AP4_ATOM_TYPE_MDHD = AP4_ATOM_TYPE('m','d','h','d');
+const AP4_Atom::Type AP4_ATOM_TYPE_MFHD = AP4_ATOM_TYPE('m','f','h','d');
+const AP4_Atom::Type AP4_ATOM_TYPE_ILST = AP4_ATOM_TYPE('i','l','s','t');
+const AP4_Atom::Type AP4_ATOM_TYPE_HDLR = AP4_ATOM_TYPE('h','d','l','r');
+const AP4_Atom::Type AP4_ATOM_TYPE_FTYP = AP4_ATOM_TYPE('f','t','y','p');
+const AP4_Atom::Type AP4_ATOM_TYPE_IODS = AP4_ATOM_TYPE('i','o','d','s');
+const AP4_Atom::Type AP4_ATOM_TYPE_ESDS = AP4_ATOM_TYPE('e','s','d','s');
+const AP4_Atom::Type AP4_ATOM_TYPE_EDTS = AP4_ATOM_TYPE('e','d','t','s');
+const AP4_Atom::Type AP4_ATOM_TYPE_DRMS = AP4_ATOM_TYPE('d','r','m','s');
+const AP4_Atom::Type AP4_ATOM_TYPE_DRMI = AP4_ATOM_TYPE('d','r','m','i');
+const AP4_Atom::Type AP4_ATOM_TYPE_DREF = AP4_ATOM_TYPE('d','r','e','f');
+const AP4_Atom::Type AP4_ATOM_TYPE_DINF = AP4_ATOM_TYPE('d','i','n','f');
+const AP4_Atom::Type AP4_ATOM_TYPE_CTTS = AP4_ATOM_TYPE('c','t','t','s');
+const AP4_Atom::Type AP4_ATOM_TYPE_MDIA = AP4_ATOM_TYPE('m','d','i','a');
+const AP4_Atom::Type AP4_ATOM_TYPE_ELST = AP4_ATOM_TYPE('e','l','s','t');
+const AP4_Atom::Type AP4_ATOM_TYPE_VMHD = AP4_ATOM_TYPE('v','m','h','d');
+const AP4_Atom::Type AP4_ATOM_TYPE_SMHD = AP4_ATOM_TYPE('s','m','h','d');
+const AP4_Atom::Type AP4_ATOM_TYPE_NMHD = AP4_ATOM_TYPE('n','m','h','d');
+const AP4_Atom::Type AP4_ATOM_TYPE_HMHD = AP4_ATOM_TYPE('h','m','h','d');
+const AP4_Atom::Type AP4_ATOM_TYPE_FRMA = AP4_ATOM_TYPE('f','r','m','a');
+const AP4_Atom::Type AP4_ATOM_TYPE_MDAT = AP4_ATOM_TYPE('m','d','a','t');
+const AP4_Atom::Type AP4_ATOM_TYPE_FREE = AP4_ATOM_TYPE('f','r','e','e');
+const AP4_Atom::Type AP4_ATOM_TYPE_TIMS = AP4_ATOM_TYPE('t','i','m','s');
+const AP4_Atom::Type AP4_ATOM_TYPE_RTP_ = AP4_ATOM_TYPE('r','t','p',' ');
+const AP4_Atom::Type AP4_ATOM_TYPE_HNTI = AP4_ATOM_TYPE('h','n','t','i');
+const AP4_Atom::Type AP4_ATOM_TYPE_SDP_ = AP4_ATOM_TYPE('s','d','p',' ');
+const AP4_Atom::Type AP4_ATOM_TYPE_IKMS = AP4_ATOM_TYPE('i','K','M','S');
+const AP4_Atom::Type AP4_ATOM_TYPE_ISFM = AP4_ATOM_TYPE('i','S','F','M');
+const AP4_Atom::Type AP4_ATOM_TYPE_ISLT = AP4_ATOM_TYPE('i','S','L','T');
+const AP4_Atom::Type AP4_ATOM_TYPE_TREF = AP4_ATOM_TYPE('t','r','e','f');
+const AP4_Atom::Type AP4_ATOM_TYPE_HINT = AP4_ATOM_TYPE('h','i','n','t');
+const AP4_Atom::Type AP4_ATOM_TYPE_CDSC = AP4_ATOM_TYPE('c','d','s','c');
+const AP4_Atom::Type AP4_ATOM_TYPE_MPOD = AP4_ATOM_TYPE('m','p','o','d');
+const AP4_Atom::Type AP4_ATOM_TYPE_IPIR = AP4_ATOM_TYPE('i','p','i','r');
+const AP4_Atom::Type AP4_ATOM_TYPE_CHAP = AP4_ATOM_TYPE('c','h','a','p');
+const AP4_Atom::Type AP4_ATOM_TYPE_ALIS = AP4_ATOM_TYPE('a','l','i','s');
+const AP4_Atom::Type AP4_ATOM_TYPE_SYNC = AP4_ATOM_TYPE('s','y','n','c');
+const AP4_Atom::Type AP4_ATOM_TYPE_DPND = AP4_ATOM_TYPE('d','p','n','d');
+const AP4_Atom::Type AP4_ATOM_TYPE_ODRM = AP4_ATOM_TYPE('o','d','r','m');
+const AP4_Atom::Type AP4_ATOM_TYPE_ODKM = AP4_ATOM_TYPE('o','d','k','m');
+const AP4_Atom::Type AP4_ATOM_TYPE_OHDR = AP4_ATOM_TYPE('o','h','d','r');
+const AP4_Atom::Type AP4_ATOM_TYPE_ODDA = AP4_ATOM_TYPE('o','d','d','a');
+const AP4_Atom::Type AP4_ATOM_TYPE_ODHE = AP4_ATOM_TYPE('o','d','h','e');
+const AP4_Atom::Type AP4_ATOM_TYPE_ODAF = AP4_ATOM_TYPE('o','d','a','f');
+const AP4_Atom::Type AP4_ATOM_TYPE_GRPI = AP4_ATOM_TYPE('g','r','p','i');
+const AP4_Atom::Type AP4_ATOM_TYPE_IPRO = AP4_ATOM_TYPE('i','p','r','o');
+const AP4_Atom::Type AP4_ATOM_TYPE_MDRI = AP4_ATOM_TYPE('m','d','r','i');
+const AP4_Atom::Type AP4_ATOM_TYPE_AVCC = AP4_ATOM_TYPE('a','v','c','C');
+const AP4_Atom::Type AP4_ATOM_TYPE_WAVE = AP4_ATOM_TYPE('w','a','v','e');
+const AP4_Atom::Type AP4_ATOM_TYPE_WIDE = AP4_ATOM_TYPE('w','i','d','e');
+const AP4_Atom::Type AP4_ATOM_TYPE_UUID = AP4_ATOM_TYPE('u','u','i','d');
+const AP4_Atom::Type AP4_ATOM_TYPE_8ID_ = AP4_ATOM_TYPE('8','i','d',' ');
+const AP4_Atom::Type AP4_ATOM_TYPE_8BDL = AP4_ATOM_TYPE('8','b','d','l');
+const AP4_Atom::Type AP4_ATOM_TYPE_AC_3 = AP4_ATOM_TYPE('a','c','-','3');
+const AP4_Atom::Type AP4_ATOM_TYPE_EC_3 = AP4_ATOM_TYPE('e','c','-','3');
+const AP4_Atom::Type AP4_ATOM_TYPE_MFRA = AP4_ATOM_TYPE('m','f','r','a');
+const AP4_Atom::Type AP4_ATOM_TYPE_TFRA = AP4_ATOM_TYPE('t','f','r','a');
+const AP4_Atom::Type AP4_ATOM_TYPE_MFRO = AP4_ATOM_TYPE('m','f','r','o');
// ==> Start patch MPC
-const AP4_Atom::Type AP4_ATOM_TYPE_FTAB = AP4_ATOM_TYPE('f', 't', 'a', 'b');
-const AP4_Atom::Type AP4_ATOM_TYPE_CHPL = AP4_ATOM_TYPE('c', 'h', 'p', 'l');
-const AP4_Atom::Type AP4_ATOM_TYPE_SAC3 = AP4_ATOM_TYPE('s', 'a', 'c', '3');
-const AP4_Atom::Type AP4_ATOM_TYPE_DTSC = AP4_ATOM_TYPE('d', 't', 's', 'c');
-const AP4_Atom::Type AP4_ATOM_TYPE_NAM = AP4_ATOM_TYPE(169, 'n', 'a', 'm');
-
-const AP4_Atom::Type AP4_ATOM_TYPE_ART = AP4_ATOM_TYPE(169, 'A', 'R', 'T');
-const AP4_Atom::Type AP4_ATOM_TYPE_WRT = AP4_ATOM_TYPE(169, 'w', 'r', 't');
-const AP4_Atom::Type AP4_ATOM_TYPE_ALB = AP4_ATOM_TYPE(169, 'a', 'l', 'b');
-const AP4_Atom::Type AP4_ATOM_TYPE_DAY = AP4_ATOM_TYPE(169, 'd', 'a', 'y');
-const AP4_Atom::Type AP4_ATOM_TYPE_TOO = AP4_ATOM_TYPE(169, 't', 'o', 'o');
-const AP4_Atom::Type AP4_ATOM_TYPE_CMT = AP4_ATOM_TYPE(169, 'c', 'm', 't');
-const AP4_Atom::Type AP4_ATOM_TYPE_GEN = AP4_ATOM_TYPE(169, 'g', 'e', 'n');
-
-const AP4_Atom::Type AP4_ATOM_TYPE_TEXT = AP4_ATOM_TYPE('t', 'e', 'x', 't');
-const AP4_Atom::Type AP4_ATOM_TYPE_TX3G = AP4_ATOM_TYPE('t', 'x', '3', 'g');
-const AP4_Atom::Type AP4_ATOM_TYPE_CVID = AP4_ATOM_TYPE('c', 'v', 'i', 'd');
-const AP4_Atom::Type AP4_ATOM_TYPE_SVQ1 = AP4_ATOM_TYPE('S', 'V', 'Q', '1');
-const AP4_Atom::Type AP4_ATOM_TYPE_SVQ2 = AP4_ATOM_TYPE('S', 'V', 'Q', '2');
-const AP4_Atom::Type AP4_ATOM_TYPE_SVQ3 = AP4_ATOM_TYPE('S', 'V', 'Q', '3');
-const AP4_Atom::Type AP4_ATOM_TYPE_H263 = AP4_ATOM_TYPE('h', '2', '6', '3');
-const AP4_Atom::Type AP4_ATOM_TYPE_S263 = AP4_ATOM_TYPE('s', '2', '6', '3');
-
-const AP4_Atom::Type AP4_ATOM_TYPE_SAMR = AP4_ATOM_TYPE('s', 'a', 'm', 'r');
-const AP4_Atom::Type AP4_ATOM_TYPE__MP3 = AP4_ATOM_TYPE('.', 'm', 'p', '3');
-const AP4_Atom::Type AP4_ATOM_TYPE_IMA4 = AP4_ATOM_TYPE('i', 'm', 'a', '4');
-const AP4_Atom::Type AP4_ATOM_TYPE_QDMC = AP4_ATOM_TYPE('Q', 'D', 'M', 'C');
-const AP4_Atom::Type AP4_ATOM_TYPE_QDM2 = AP4_ATOM_TYPE('Q', 'D', 'M', '2');
-const AP4_Atom::Type AP4_ATOM_TYPE_TWOS = AP4_ATOM_TYPE('t', 'w', 'o', 's');
-const AP4_Atom::Type AP4_ATOM_TYPE_SOWT = AP4_ATOM_TYPE('s', 'o', 'w', 't');
-
-const AP4_Atom::Type AP4_ATOM_TYPE_CMOV = AP4_ATOM_TYPE('c', 'm', 'o', 'v');
-const AP4_Atom::Type AP4_ATOM_TYPE_DCOM = AP4_ATOM_TYPE('d', 'c', 'o', 'm');
-const AP4_Atom::Type AP4_ATOM_TYPE_CMVD = AP4_ATOM_TYPE('c', 'm', 'v', 'd');
+const AP4_Atom::Type AP4_ATOM_TYPE_FTAB = AP4_ATOM_TYPE('f','t','a','b');
+const AP4_Atom::Type AP4_ATOM_TYPE_CHPL = AP4_ATOM_TYPE('c','h','p','l');
+const AP4_Atom::Type AP4_ATOM_TYPE_SAC3 = AP4_ATOM_TYPE('s','a','c','3');
+const AP4_Atom::Type AP4_ATOM_TYPE_DTSC = AP4_ATOM_TYPE('d','t','s','c');
+const AP4_Atom::Type AP4_ATOM_TYPE_NAM = AP4_ATOM_TYPE(169,'n','a','m');
+
+const AP4_Atom::Type AP4_ATOM_TYPE_ART = AP4_ATOM_TYPE(169,'A','R','T');
+const AP4_Atom::Type AP4_ATOM_TYPE_WRT = AP4_ATOM_TYPE(169,'w','r','t');
+const AP4_Atom::Type AP4_ATOM_TYPE_ALB = AP4_ATOM_TYPE(169,'a','l','b');
+const AP4_Atom::Type AP4_ATOM_TYPE_DAY = AP4_ATOM_TYPE(169,'d','a','y');
+const AP4_Atom::Type AP4_ATOM_TYPE_TOO = AP4_ATOM_TYPE(169,'t','o','o');
+const AP4_Atom::Type AP4_ATOM_TYPE_CMT = AP4_ATOM_TYPE(169,'c','m','t');
+const AP4_Atom::Type AP4_ATOM_TYPE_GEN = AP4_ATOM_TYPE(169,'g','e','n');
+
+const AP4_Atom::Type AP4_ATOM_TYPE_TEXT = AP4_ATOM_TYPE('t','e','x','t');
+const AP4_Atom::Type AP4_ATOM_TYPE_TX3G = AP4_ATOM_TYPE('t','x','3','g');
+const AP4_Atom::Type AP4_ATOM_TYPE_CVID = AP4_ATOM_TYPE('c','v','i','d');
+const AP4_Atom::Type AP4_ATOM_TYPE_SVQ1 = AP4_ATOM_TYPE('S','V','Q','1');
+const AP4_Atom::Type AP4_ATOM_TYPE_SVQ2 = AP4_ATOM_TYPE('S','V','Q','2');
+const AP4_Atom::Type AP4_ATOM_TYPE_SVQ3 = AP4_ATOM_TYPE('S','V','Q','3');
+const AP4_Atom::Type AP4_ATOM_TYPE_H263 = AP4_ATOM_TYPE('h','2','6','3');
+const AP4_Atom::Type AP4_ATOM_TYPE_S263 = AP4_ATOM_TYPE('s','2','6','3');
+
+const AP4_Atom::Type AP4_ATOM_TYPE_SAMR = AP4_ATOM_TYPE('s','a','m','r');
+const AP4_Atom::Type AP4_ATOM_TYPE__MP3 = AP4_ATOM_TYPE('.','m','p','3');
+const AP4_Atom::Type AP4_ATOM_TYPE_IMA4 = AP4_ATOM_TYPE('i','m','a','4');
+const AP4_Atom::Type AP4_ATOM_TYPE_QDMC = AP4_ATOM_TYPE('Q','D','M','C');
+const AP4_Atom::Type AP4_ATOM_TYPE_QDM2 = AP4_ATOM_TYPE('Q','D','M','2');
+const AP4_Atom::Type AP4_ATOM_TYPE_TWOS = AP4_ATOM_TYPE('t','w','o','s');
+const AP4_Atom::Type AP4_ATOM_TYPE_SOWT = AP4_ATOM_TYPE('s','o','w','t');
+
+const AP4_Atom::Type AP4_ATOM_TYPE_CMOV = AP4_ATOM_TYPE('c','m','o','v');
+const AP4_Atom::Type AP4_ATOM_TYPE_DCOM = AP4_ATOM_TYPE('d','c','o','m');
+const AP4_Atom::Type AP4_ATOM_TYPE_CMVD = AP4_ATOM_TYPE('c','m','v','d');
// <== End patch MPC
@@ -528,16 +474,15 @@ const AP4_Atom::Type AP4_ATOM_TYPE_CMVD = AP4_ATOM_TYPE('c', 'm', 'v', 'd');
+---------------------------------------------------------------------*/
class AP4_AtomListInspector : public AP4_List<AP4_Atom>::Item::Operator
{
-public:
+ public:
AP4_AtomListInspector(AP4_AtomInspector& inspector) :
m_Inspector(inspector) {}
- AP4_Result Action(AP4_Atom* atom) const
- {
+ AP4_Result Action(AP4_Atom* atom) const {
atom->Inspect(m_Inspector);
return AP4_SUCCESS;
}
-private:
+ private:
AP4_AtomInspector& m_Inspector;
};
@@ -546,12 +491,12 @@ private:
+---------------------------------------------------------------------*/
class AP4_AtomListWriter : public AP4_List<AP4_Atom>::Item::Operator
{
-public:
+ public:
AP4_AtomListWriter(AP4_ByteStream& stream) :
m_Stream(stream) {}
AP4_Result Action(AP4_Atom* atom) const;
-private:
+ private:
AP4_ByteStream& m_Stream;
};
@@ -560,28 +505,21 @@ private:
+---------------------------------------------------------------------*/
class AP4_AtomFinder : public AP4_List<AP4_Atom>::Item::Finder
{
-public:
- AP4_AtomFinder(AP4_Atom::Type type, AP4_Ordinal index = 0) :
- m_Type(type), m_Index(index) {}
- AP4_Result Test(AP4_Atom* atom) const
- {
- if(atom->GetType() == m_Type)
- {
- if(m_Index-- == 0)
- {
+ public:
+ AP4_AtomFinder(AP4_Atom::Type type, AP4_Ordinal index = 0) :
+ m_Type(type), m_Index(index) {}
+ AP4_Result Test(AP4_Atom* atom) const {
+ if (atom->GetType() == m_Type) {
+ if (m_Index-- == 0) {
return AP4_SUCCESS;
- }
- else
- {
+ } else {
return AP4_FAILURE;
}
- }
- else
- {
+ } else {
return AP4_FAILURE;
}
}
-private:
+ private:
AP4_Atom::Type m_Type;
mutable AP4_Ordinal m_Index;
};
@@ -589,14 +527,12 @@ private:
/*----------------------------------------------------------------------
| AP4_AtomSizeAdder
+---------------------------------------------------------------------*/
-class AP4_AtomSizeAdder : public AP4_List<AP4_Atom>::Item::Operator
-{
+class AP4_AtomSizeAdder : public AP4_List<AP4_Atom>::Item::Operator {
public:
AP4_AtomSizeAdder(AP4_UI64& size) : m_Size(size) {}
private:
- AP4_Result Action(AP4_Atom* atom) const
- {
+ AP4_Result Action(AP4_Atom* atom) const {
m_Size += atom->GetSize();
return AP4_SUCCESS;
}
diff --git a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4AtomFactory.cpp b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4AtomFactory.cpp
index 97527d3d7..04158c4aa 100644
--- a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4AtomFactory.cpp
+++ b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4AtomFactory.cpp
@@ -125,18 +125,17 @@ AP4_AtomFactory::RemoveTypeHandler(TypeHandler* handler)
| AP4_AtomFactory::CreateAtomFromStream
+---------------------------------------------------------------------*/
AP4_Result
-AP4_AtomFactory::CreateAtomFromStream(AP4_ByteStream& stream,
+AP4_AtomFactory::CreateAtomFromStream(AP4_ByteStream& stream,
AP4_Atom*& atom)
{
AP4_LargeSize stream_size = 0;
AP4_Position stream_position = 0;
AP4_LargeSize bytes_available = (AP4_LargeSize)(-1);
- if(AP4_SUCCEEDED(stream.GetSize(stream_size)) &&
- stream_size != 0 &&
- AP4_SUCCEEDED(stream.Tell(stream_position)) &&
- stream_position <= stream_size)
- {
- bytes_available = stream_size - stream_position;
+ if (AP4_SUCCEEDED(stream.GetSize(stream_size)) &&
+ stream_size != 0 &&
+ AP4_SUCCEEDED(stream.Tell(stream_position)) &&
+ stream_position <= stream_size) {
+ bytes_available = stream_size-stream_position;
}
return CreateAtomFromStream(stream, bytes_available, atom);
}
@@ -145,7 +144,7 @@ AP4_AtomFactory::CreateAtomFromStream(AP4_ByteStream& stream,
| AP4_AtomFactory::CreateAtomFromStream
+---------------------------------------------------------------------*/
AP4_Result
-AP4_AtomFactory::CreateAtomFromStream(AP4_ByteStream& stream,
+AP4_AtomFactory::CreateAtomFromStream(AP4_ByteStream& stream,
AP4_LargeSize& bytes_available,
AP4_Atom*& atom)
{
@@ -155,7 +154,7 @@ AP4_AtomFactory::CreateAtomFromStream(AP4_ByteStream& stream,
atom = NULL;
// check that there are enough bytes for at least a header
- if(bytes_available < 8) return AP4_ERROR_EOS;
+ if (bytes_available < 8) return AP4_ERROR_EOS;
// remember current stream offset
AP4_Position start;
@@ -164,8 +163,7 @@ AP4_AtomFactory::CreateAtomFromStream(AP4_ByteStream& stream,
// read atom size
AP4_UI32 size_32;
result = stream.ReadUI32(size_32);
- if(AP4_FAILED(result))
- {
+ if (AP4_FAILED(result)) {
stream.Seek(start);
return result;
}
@@ -174,8 +172,7 @@ AP4_AtomFactory::CreateAtomFromStream(AP4_ByteStream& stream,
// read atom type
AP4_Atom::Type type;
result = stream.ReadUI32(type);
- if(AP4_FAILED(result))
- {
+ if (AP4_FAILED(result)) {
stream.Seek(start);
return result;
}
@@ -183,524 +180,499 @@ AP4_AtomFactory::CreateAtomFromStream(AP4_ByteStream& stream,
// handle special size values
bool atom_is_large = false;
bool force_64 = false;
- if(size == 0)
- {
+ if (size == 0) {
// atom extends to end of file
AP4_LargeSize stream_size = 0;
stream.GetSize(stream_size);
- if(stream_size >= start)
- {
+ if (stream_size >= start) {
size = stream_size - start;
}
- }
- else if(size == 1)
- {
+ } else if (size == 1) {
// 64-bit size
atom_is_large = true;
- if(bytes_available < 16)
- {
+ if (bytes_available < 16) {
stream.Seek(start);
return AP4_ERROR_INVALID_FORMAT;
}
stream.ReadUI64(size);
- if(size <= 0xFFFFFFFF)
- {
+ if (size <= 0xFFFFFFFF) {
force_64 = true;
}
}
// check the size
- if((size > 0 && size < 8) || size > bytes_available)
- {
+ if ((size > 0 && size < 8) || size > bytes_available) {
stream.Seek(start);
return AP4_ERROR_INVALID_FORMAT;
}
// create the atom
- if(GetContext() == AP4_ATOM_TYPE_STSD)
- {
+ if (GetContext() == AP4_ATOM_TYPE_STSD) {
// sample entry
- if(atom_is_large) return AP4_ERROR_INVALID_FORMAT;
- switch(type)
- {
- case AP4_ATOM_TYPE_MP4A:
+ if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
+ switch (type) {
+ case AP4_ATOM_TYPE_MP4A:
atom = new AP4_Mp4aSampleEntry(size_32, stream, *this);
break;
- case AP4_ATOM_TYPE_MP4V:
+ case AP4_ATOM_TYPE_MP4V:
atom = new AP4_Mp4vSampleEntry(size_32, stream, *this);
break;
- case AP4_ATOM_TYPE_MP4S:
+ case AP4_ATOM_TYPE_MP4S:
atom = new AP4_Mp4sSampleEntry(size_32, stream, *this);
break;
- case AP4_ATOM_TYPE_ENCA:
+ case AP4_ATOM_TYPE_ENCA:
atom = new AP4_EncaSampleEntry(size_32, stream, *this);
break;
- case AP4_ATOM_TYPE_ENCV:
+ case AP4_ATOM_TYPE_ENCV:
atom = new AP4_EncvSampleEntry(size_32, stream, *this);
break;
- case AP4_ATOM_TYPE_DRMS:
+ case AP4_ATOM_TYPE_DRMS:
atom = new AP4_DrmsSampleEntry(size_32, stream, *this);
break;
- case AP4_ATOM_TYPE_DRMI:
+ case AP4_ATOM_TYPE_DRMI:
atom = new AP4_DrmiSampleEntry(size_32, stream, *this);
break;
- case AP4_ATOM_TYPE_AVC1:
+ case AP4_ATOM_TYPE_AVC1:
atom = new AP4_Avc1SampleEntry(size_32, stream, *this);
break;
- case AP4_ATOM_TYPE_ALAC:
- // ==> Start patch MPC
+ case AP4_ATOM_TYPE_ALAC:
+ // ==> Start patch MPC
// case AP4_ATOM_TYPE_AC_3:
- // <== End patch MPC
- case AP4_ATOM_TYPE_EC_3:
+ // <== End patch MPC
+ case AP4_ATOM_TYPE_EC_3:
atom = new AP4_AudioSampleEntry(type, size_32, stream, *this);
break;
- // ==> Start patch MPC
- case AP4_ATOM_TYPE_TEXT:
- atom = new AP4_TextSampleEntry((unsigned long)size, stream, *this);
- break;
-
- case AP4_ATOM_TYPE_TX3G:
- atom = new AP4_Tx3gSampleEntry((unsigned long)size, stream, *this);
- break;
-
- case AP4_ATOM_TYPE_FTAB:
- atom = new AP4_FtabAtom((unsigned long)size, stream);
- break;
-
- case AP4_ATOM_TYPE_CHPL:
- atom = new AP4_ChplAtom((unsigned long)size, stream);
- break;
-
- case AP4_ATOM_TYPE_CVID:
- case AP4_ATOM_TYPE_SVQ1:
- case AP4_ATOM_TYPE_SVQ2:
- case AP4_ATOM_TYPE_SVQ3:
- case AP4_ATOM_TYPE_H263:
- case AP4_ATOM_TYPE_S263:
- atom = new AP4_VisualSampleEntry(type, (unsigned long)size, stream, *this);
- break;
-
- case AP4_ATOM_TYPE_SAMR:
- case AP4_ATOM_TYPE__MP3:
- case AP4_ATOM_TYPE_IMA4:
- case AP4_ATOM_TYPE_QDMC:
- case AP4_ATOM_TYPE_QDM2:
- case AP4_ATOM_TYPE_TWOS:
- case AP4_ATOM_TYPE_SOWT:
- atom = new AP4_AudioSampleEntry(type, (unsigned long)size, stream, *this);
- break;
-
- case AP4_ATOM_TYPE_AC_3: // AC3-in-MP4 from ISO Standard
- case AP4_ATOM_TYPE_SAC3: // AC3-in-MP4 from Nero Stuff >.<
- atom = new AP4_AC3SampleEntry(type, (unsigned long)size, stream, *this);
- break;
- // <== End patch MPC
-
- case AP4_ATOM_TYPE_RTP_:
+ // ==> Start patch MPC
+ case AP4_ATOM_TYPE_TEXT:
+ atom = new AP4_TextSampleEntry((unsigned long)size, stream, *this);
+ break;
+
+ case AP4_ATOM_TYPE_TX3G:
+ atom = new AP4_Tx3gSampleEntry((unsigned long)size, stream, *this);
+ break;
+
+ case AP4_ATOM_TYPE_FTAB:
+ atom = new AP4_FtabAtom((unsigned long)size, stream);
+ break;
+
+ case AP4_ATOM_TYPE_CHPL:
+ atom = new AP4_ChplAtom((unsigned long)size, stream);
+ break;
+
+ case AP4_ATOM_TYPE_CVID:
+ case AP4_ATOM_TYPE_SVQ1:
+ case AP4_ATOM_TYPE_SVQ2:
+ case AP4_ATOM_TYPE_SVQ3:
+ case AP4_ATOM_TYPE_H263:
+ case AP4_ATOM_TYPE_S263:
+ atom = new AP4_VisualSampleEntry(type, (unsigned long)size, stream, *this);
+ break;
+
+ case AP4_ATOM_TYPE_SAMR:
+ case AP4_ATOM_TYPE__MP3:
+ case AP4_ATOM_TYPE_IMA4:
+ case AP4_ATOM_TYPE_QDMC:
+ case AP4_ATOM_TYPE_QDM2:
+ case AP4_ATOM_TYPE_TWOS:
+ case AP4_ATOM_TYPE_SOWT:
+ atom = new AP4_AudioSampleEntry(type, (unsigned long)size, stream, *this);
+ break;
+
+ case AP4_ATOM_TYPE_AC_3: // AC3-in-MP4 from ISO Standard
+ case AP4_ATOM_TYPE_SAC3: // AC3-in-MP4 from Nero Stuff >.<
+ atom = new AP4_AC3SampleEntry(type, (unsigned long)size, stream, *this);
+ break;
+ // <== End patch MPC
+
+ case AP4_ATOM_TYPE_RTP_:
atom = new AP4_RtpHintSampleEntry(size_32, stream, *this);
break;
- default:
- {
- // try all the external type handlers
- AP4_List<TypeHandler>::Item* handler_item = m_TypeHandlers.FirstItem();
- while(handler_item)
+ default:
{
- TypeHandler* handler = handler_item->GetData();
- if(AP4_SUCCEEDED(handler->CreateAtom(type, size_32, stream, GetContext(), atom)))
- {
- break;
+ // try all the external type handlers
+ AP4_List<TypeHandler>::Item* handler_item = m_TypeHandlers.FirstItem();
+ while (handler_item) {
+ TypeHandler* handler = handler_item->GetData();
+ if (AP4_SUCCEEDED(handler->CreateAtom(type, size_32, stream, GetContext(), atom))) {
+ break;
+ }
+ handler_item = handler_item->GetNext();
}
- handler_item = handler_item->GetNext();
+
+ // no custom handler, create a generic entry
+ atom = new AP4_UnknownSampleEntry(type, (AP4_Size)size, stream);
}
-
- // no custom handler, create a generic entry
- atom = new AP4_UnknownSampleEntry(type, (AP4_Size)size, stream);
- }
- break;
+ break;
}
- }
- else
- {
+ } else {
// regular atom
- switch(type)
- {
- case AP4_ATOM_TYPE_MOOV:
- if(atom_is_large) return AP4_ERROR_INVALID_FORMAT;
+ switch (type) {
+ case AP4_ATOM_TYPE_MOOV:
+ if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_MoovAtom::Create(size_32, stream, *this);
break;
- case AP4_ATOM_TYPE_MVHD:
- if(atom_is_large) return AP4_ERROR_INVALID_FORMAT;
+ case AP4_ATOM_TYPE_MVHD:
+ if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_MvhdAtom::Create(size_32, stream);
break;
- case AP4_ATOM_TYPE_MEHD:
- if(atom_is_large) return AP4_ERROR_INVALID_FORMAT;
+ case AP4_ATOM_TYPE_MEHD:
+ if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_MehdAtom::Create(size_32, stream);
break;
- case AP4_ATOM_TYPE_MFHD:
- if(atom_is_large) return AP4_ERROR_INVALID_FORMAT;
+ case AP4_ATOM_TYPE_MFHD:
+ if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_MfhdAtom::Create(size_32, stream);
break;
- case AP4_ATOM_TYPE_TRAK:
- if(atom_is_large) return AP4_ERROR_INVALID_FORMAT;
+ case AP4_ATOM_TYPE_TRAK:
+ if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_TrakAtom::Create(size_32, stream, *this);
break;
- case AP4_ATOM_TYPE_TREX:
- if(atom_is_large) return AP4_ERROR_INVALID_FORMAT;
+ case AP4_ATOM_TYPE_TREX:
+ if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_TrexAtom::Create(size_32, stream);
break;
- case AP4_ATOM_TYPE_HDLR:
- if(atom_is_large) return AP4_ERROR_INVALID_FORMAT;
+ case AP4_ATOM_TYPE_HDLR:
+ if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_HdlrAtom::Create(size_32, stream);
break;
- case AP4_ATOM_TYPE_TKHD:
- if(atom_is_large) return AP4_ERROR_INVALID_FORMAT;
+ case AP4_ATOM_TYPE_TKHD:
+ if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_TkhdAtom::Create(size_32, stream);
break;
- case AP4_ATOM_TYPE_TFHD:
- if(atom_is_large) return AP4_ERROR_INVALID_FORMAT;
+ case AP4_ATOM_TYPE_TFHD:
+ if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_TfhdAtom::Create(size_32, stream);
break;
- case AP4_ATOM_TYPE_TRUN:
- if(atom_is_large) return AP4_ERROR_INVALID_FORMAT;
+ case AP4_ATOM_TYPE_TRUN:
+ if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_TrunAtom::Create(size_32, stream);
break;
- case AP4_ATOM_TYPE_TFRA:
- if(atom_is_large) return AP4_ERROR_INVALID_FORMAT;
+ case AP4_ATOM_TYPE_TFRA:
+ if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_TfraAtom::Create(size_32, stream);
break;
- case AP4_ATOM_TYPE_MFRO:
- if(atom_is_large) return AP4_ERROR_INVALID_FORMAT;
+ case AP4_ATOM_TYPE_MFRO:
+ if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_MfroAtom::Create(size_32, stream);
break;
- case AP4_ATOM_TYPE_MDHD:
- if(atom_is_large) return AP4_ERROR_INVALID_FORMAT;
+ case AP4_ATOM_TYPE_MDHD:
+ if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_MdhdAtom::Create(size_32, stream);
break;
- case AP4_ATOM_TYPE_STSD:
- if(atom_is_large) return AP4_ERROR_INVALID_FORMAT;
+ case AP4_ATOM_TYPE_STSD:
+ if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_StsdAtom::Create(size_32, stream, *this);
break;
- case AP4_ATOM_TYPE_STSC:
- if(atom_is_large) return AP4_ERROR_INVALID_FORMAT;
+ case AP4_ATOM_TYPE_STSC:
+ if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_StscAtom::Create(size_32, stream);
break;
- case AP4_ATOM_TYPE_STCO:
- if(atom_is_large) return AP4_ERROR_INVALID_FORMAT;
+ case AP4_ATOM_TYPE_STCO:
+ if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_StcoAtom::Create(size_32, stream);
break;
- case AP4_ATOM_TYPE_CO64:
- if(atom_is_large) return AP4_ERROR_INVALID_FORMAT;
+ case AP4_ATOM_TYPE_CO64:
+ if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_Co64Atom::Create(size_32, stream);
break;
- case AP4_ATOM_TYPE_STSZ:
- if(atom_is_large) return AP4_ERROR_INVALID_FORMAT;
+ case AP4_ATOM_TYPE_STSZ:
+ if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_StszAtom::Create(size_32, stream);
break;
- case AP4_ATOM_TYPE_STTS:
- if(atom_is_large) return AP4_ERROR_INVALID_FORMAT;
+ case AP4_ATOM_TYPE_STTS:
+ if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_SttsAtom::Create(size_32, stream);
break;
- case AP4_ATOM_TYPE_CTTS:
- if(atom_is_large) return AP4_ERROR_INVALID_FORMAT;
+ case AP4_ATOM_TYPE_CTTS:
+ if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_CttsAtom::Create(size_32, stream);
break;
- case AP4_ATOM_TYPE_STSS:
- if(atom_is_large) return AP4_ERROR_INVALID_FORMAT;
+ case AP4_ATOM_TYPE_STSS:
+ if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_StssAtom::Create(size_32, stream);
break;
- case AP4_ATOM_TYPE_IODS:
- if(atom_is_large) return AP4_ERROR_INVALID_FORMAT;
+ case AP4_ATOM_TYPE_IODS:
+ if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_IodsAtom::Create(size_32, stream);
break;
- case AP4_ATOM_TYPE_ESDS:
- if(atom_is_large) return AP4_ERROR_INVALID_FORMAT;
+ case AP4_ATOM_TYPE_ESDS:
+ if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_EsdsAtom::Create(size_32, stream);
break;
- case AP4_ATOM_TYPE_AVCC:
- if(atom_is_large) return AP4_ERROR_INVALID_FORMAT;
+ case AP4_ATOM_TYPE_AVCC:
+ if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_AvccAtom::Create(size_32, stream);
break;
-
-#if !defined(AP4_CONFIG_MINI_BUILD)
- case AP4_ATOM_TYPE_UUID:
- {
- AP4_UI08 uuid[16];
- result = stream.Read(uuid, 16);
- if(AP4_FAILED(result)) return result;
-
- if(AP4_CompareMemory(uuid, AP4_UUID_PIFF_TRACK_ENCRYPTION_ATOM, 16) == 0)
- {
- atom = AP4_PiffTrackEncryptionAtom::Create((AP4_Size)size, stream);
- }
- else if(AP4_CompareMemory(uuid, AP4_UUID_PIFF_SAMPLE_ENCRYPTION_ATOM, 16) == 0)
- {
- atom = AP4_PiffSampleEncryptionAtom::Create((AP4_Size)size, stream);
- }
- else
- {
- atom = new AP4_UnknownUuidAtom(size, uuid, stream);
- }
- break;
- }
-
- case AP4_ATOM_TYPE_8ID_:
+
+ #if !defined(AP4_CONFIG_MINI_BUILD)
+ case AP4_ATOM_TYPE_UUID: {
+ AP4_UI08 uuid[16];
+ result = stream.Read(uuid, 16);
+ if (AP4_FAILED(result)) return result;
+
+ if (AP4_CompareMemory(uuid, AP4_UUID_PIFF_TRACK_ENCRYPTION_ATOM, 16) == 0) {
+ atom = AP4_PiffTrackEncryptionAtom::Create((AP4_Size)size, stream);
+ } else if (AP4_CompareMemory(uuid, AP4_UUID_PIFF_SAMPLE_ENCRYPTION_ATOM, 16) == 0) {
+ atom = AP4_PiffSampleEncryptionAtom::Create((AP4_Size)size, stream);
+ } else {
+ atom = new AP4_UnknownUuidAtom(size, uuid, stream);
+ }
+ break;
+ }
+
+ case AP4_ATOM_TYPE_8ID_:
atom = new AP4_NullTerminatedStringAtom(type, size, stream);
break;
- case AP4_ATOM_TYPE_8BDL:
- if(atom_is_large) return AP4_ERROR_INVALID_FORMAT;
+ case AP4_ATOM_TYPE_8BDL:
+ if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_8bdlAtom::Create(size_32, stream);
break;
- case AP4_ATOM_TYPE_DREF:
- if(atom_is_large) return AP4_ERROR_INVALID_FORMAT;
+ case AP4_ATOM_TYPE_DREF:
+ if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_DrefAtom::Create(size_32, stream, *this);
break;
- case AP4_ATOM_TYPE_URL:
- if(atom_is_large) return AP4_ERROR_INVALID_FORMAT;
+ case AP4_ATOM_TYPE_URL:
+ if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_UrlAtom::Create(size_32, stream);
break;
- case AP4_ATOM_TYPE_ELST:
- if(atom_is_large) return AP4_ERROR_INVALID_FORMAT;
+ case AP4_ATOM_TYPE_ELST:
+ if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_ElstAtom::Create(size_32, stream);
break;
- case AP4_ATOM_TYPE_VMHD:
- if(atom_is_large) return AP4_ERROR_INVALID_FORMAT;
+ case AP4_ATOM_TYPE_VMHD:
+ if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_VmhdAtom::Create(size_32, stream);
break;
- case AP4_ATOM_TYPE_SMHD:
- if(atom_is_large) return AP4_ERROR_INVALID_FORMAT;
+ case AP4_ATOM_TYPE_SMHD:
+ if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_SmhdAtom::Create(size_32, stream);
break;
- case AP4_ATOM_TYPE_NMHD:
- if(atom_is_large) return AP4_ERROR_INVALID_FORMAT;
+ case AP4_ATOM_TYPE_NMHD:
+ if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_NmhdAtom::Create(size_32, stream);
break;
- case AP4_ATOM_TYPE_HMHD:
- if(atom_is_large) return AP4_ERROR_INVALID_FORMAT;
+ case AP4_ATOM_TYPE_HMHD:
+ if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_HmhdAtom::Create(size_32, stream);
break;
- case AP4_ATOM_TYPE_FRMA:
- if(atom_is_large) return AP4_ERROR_INVALID_FORMAT;
+ case AP4_ATOM_TYPE_FRMA:
+ if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_FrmaAtom::Create(size_32, stream);
break;
- case AP4_ATOM_TYPE_SCHM:
- if(atom_is_large) return AP4_ERROR_INVALID_FORMAT;
+ case AP4_ATOM_TYPE_SCHM:
+ if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_SchmAtom::Create(size_32, &m_ContextStack, stream);
break;
- case AP4_ATOM_TYPE_FTYP:
- if(atom_is_large) return AP4_ERROR_INVALID_FORMAT;
+ case AP4_ATOM_TYPE_FTYP:
+ if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_FtypAtom::Create(size_32, stream);
break;
-
- case AP4_ATOM_TYPE_TIMS:
- if(atom_is_large) return AP4_ERROR_INVALID_FORMAT;
+
+ case AP4_ATOM_TYPE_TIMS:
+ if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_TimsAtom::Create(size_32, stream);
break;
-
- case AP4_ATOM_TYPE_SDP_:
- if(atom_is_large) return AP4_ERROR_INVALID_FORMAT;
+
+ case AP4_ATOM_TYPE_SDP_:
+ if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_SdpAtom::Create(size_32, stream);
break;
- case AP4_ATOM_TYPE_IKMS:
- if(atom_is_large) return AP4_ERROR_INVALID_FORMAT;
+ case AP4_ATOM_TYPE_IKMS:
+ if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_IkmsAtom::Create(size_32, stream);
break;
- case AP4_ATOM_TYPE_ISFM:
- if(atom_is_large) return AP4_ERROR_INVALID_FORMAT;
+ case AP4_ATOM_TYPE_ISFM:
+ if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_IsfmAtom::Create(size_32, stream);
break;
- case AP4_ATOM_TYPE_ISLT:
- if(atom_is_large) return AP4_ERROR_INVALID_FORMAT;
+ case AP4_ATOM_TYPE_ISLT:
+ if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_IsltAtom::Create(size_32, stream);
break;
- case AP4_ATOM_TYPE_ODHE:
- if(atom_is_large) return AP4_ERROR_INVALID_FORMAT;
+ case AP4_ATOM_TYPE_ODHE:
+ if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_OdheAtom::Create(size_32, stream, *this);
break;
- case AP4_ATOM_TYPE_OHDR:
- if(atom_is_large) return AP4_ERROR_INVALID_FORMAT;
+ case AP4_ATOM_TYPE_OHDR:
+ if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_OhdrAtom::Create(size_32, stream, *this);
break;
- case AP4_ATOM_TYPE_ODDA:
+ case AP4_ATOM_TYPE_ODDA:
atom = AP4_OddaAtom::Create(size, stream);
break;
- case AP4_ATOM_TYPE_ODAF:
- if(atom_is_large) return AP4_ERROR_INVALID_FORMAT;
+ case AP4_ATOM_TYPE_ODAF:
+ if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_OdafAtom::Create(size_32, stream);
break;
- case AP4_ATOM_TYPE_GRPI:
- if(atom_is_large) return AP4_ERROR_INVALID_FORMAT;
+ case AP4_ATOM_TYPE_GRPI:
+ if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_GrpiAtom::Create(size_32, stream);
break;
- case AP4_ATOM_TYPE_IPRO:
- if(atom_is_large) return AP4_ERROR_INVALID_FORMAT;
+ case AP4_ATOM_TYPE_IPRO:
+ if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_IproAtom::Create(size_32, stream, *this);
break;
- case AP4_ATOM_TYPE_RTP_:
- if(atom_is_large) return AP4_ERROR_INVALID_FORMAT;
+ case AP4_ATOM_TYPE_RTP_:
+ if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_RtpAtom::Create(size_32, stream);
break;
- // track ref types
- case AP4_ATOM_TYPE_HINT:
- case AP4_ATOM_TYPE_CDSC:
- case AP4_ATOM_TYPE_SYNC:
- case AP4_ATOM_TYPE_MPOD:
- case AP4_ATOM_TYPE_DPND:
- case AP4_ATOM_TYPE_IPIR:
- case AP4_ATOM_TYPE_ALIS:
- case AP4_ATOM_TYPE_CHAP:
- if(GetContext() == AP4_ATOM_TYPE_TREF)
- {
- if(atom_is_large) return AP4_ERROR_INVALID_FORMAT;
+ // track ref types
+ case AP4_ATOM_TYPE_HINT:
+ case AP4_ATOM_TYPE_CDSC:
+ case AP4_ATOM_TYPE_SYNC:
+ case AP4_ATOM_TYPE_MPOD:
+ case AP4_ATOM_TYPE_DPND:
+ case AP4_ATOM_TYPE_IPIR:
+ case AP4_ATOM_TYPE_ALIS:
+ case AP4_ATOM_TYPE_CHAP:
+ if (GetContext() == AP4_ATOM_TYPE_TREF) {
+ if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_TrefTypeAtom::Create(type, size_32, stream);
}
break;
-#endif // AP4_CONFIG_MINI_BUILD
-
- // container atoms
- case AP4_ATOM_TYPE_MOOF:
- case AP4_ATOM_TYPE_MVEX:
- case AP4_ATOM_TYPE_TRAF:
- case AP4_ATOM_TYPE_TREF:
- case AP4_ATOM_TYPE_MFRA:
- case AP4_ATOM_TYPE_HNTI:
- case AP4_ATOM_TYPE_STBL:
- case AP4_ATOM_TYPE_MDIA:
- case AP4_ATOM_TYPE_DINF:
- case AP4_ATOM_TYPE_MINF:
- case AP4_ATOM_TYPE_SCHI:
- case AP4_ATOM_TYPE_SINF:
- case AP4_ATOM_TYPE_UDTA:
- case AP4_ATOM_TYPE_ILST:
- case AP4_ATOM_TYPE_EDTS:
- case AP4_ATOM_TYPE_MDRI:
- case AP4_ATOM_TYPE_WAVE:
-
- // ==> Start patch MPC
- case AP4_ATOM_TYPE_ART:
- case AP4_ATOM_TYPE_WRT:
- case AP4_ATOM_TYPE_ALB:
- case AP4_ATOM_TYPE_DAY:
- case AP4_ATOM_TYPE_TOO:
- case AP4_ATOM_TYPE_CMT:
- case AP4_ATOM_TYPE_GEN:
- case AP4_ATOM_TYPE_CMOV:
- // <== End patch MPC
-
- if(atom_is_large) return AP4_ERROR_INVALID_FORMAT;
+ #endif // AP4_CONFIG_MINI_BUILD
+
+ // container atoms
+ case AP4_ATOM_TYPE_MOOF:
+ case AP4_ATOM_TYPE_MVEX:
+ case AP4_ATOM_TYPE_TRAF:
+ case AP4_ATOM_TYPE_TREF:
+ case AP4_ATOM_TYPE_MFRA:
+ case AP4_ATOM_TYPE_HNTI:
+ case AP4_ATOM_TYPE_STBL:
+ case AP4_ATOM_TYPE_MDIA:
+ case AP4_ATOM_TYPE_DINF:
+ case AP4_ATOM_TYPE_MINF:
+ case AP4_ATOM_TYPE_SCHI:
+ case AP4_ATOM_TYPE_SINF:
+ case AP4_ATOM_TYPE_UDTA:
+ case AP4_ATOM_TYPE_ILST:
+ case AP4_ATOM_TYPE_EDTS:
+ case AP4_ATOM_TYPE_MDRI:
+ case AP4_ATOM_TYPE_WAVE:
+
+ // ==> Start patch MPC
+ case AP4_ATOM_TYPE_ART:
+ case AP4_ATOM_TYPE_WRT:
+ case AP4_ATOM_TYPE_ALB:
+ case AP4_ATOM_TYPE_DAY:
+ case AP4_ATOM_TYPE_TOO:
+ case AP4_ATOM_TYPE_CMT:
+ case AP4_ATOM_TYPE_GEN:
+ case AP4_ATOM_TYPE_CMOV:
+ // <== End patch MPC
+
+ if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_ContainerAtom::Create(type, size, false, force_64, stream, *this);
break;
- // full container atoms
- case AP4_ATOM_TYPE_META:
- case AP4_ATOM_TYPE_ODRM:
- case AP4_ATOM_TYPE_ODKM:
+ // full container atoms
+ case AP4_ATOM_TYPE_META:
+ case AP4_ATOM_TYPE_ODRM:
+ case AP4_ATOM_TYPE_ODKM:
atom = AP4_ContainerAtom::Create(type, size, true, force_64, stream, *this);
break;
- case AP4_ATOM_TYPE_FREE:
- case AP4_ATOM_TYPE_WIDE:
- case AP4_ATOM_TYPE_MDAT:
+ case AP4_ATOM_TYPE_FREE:
+ case AP4_ATOM_TYPE_WIDE:
+ case AP4_ATOM_TYPE_MDAT:
// generic atoms
break;
-
- // ==> Start patch MPC
- case AP4_ATOM_TYPE_DCOM:
- atom = AP4_DcomAtom::Create((unsigned long)size, stream);
- break;
- case AP4_ATOM_TYPE_CMVD:
- atom = AP4_CmvdAtom::Create((unsigned long)size, stream, *this);
- break;
- // <== End patch MPC
-
- default:
+
+ // ==> Start patch MPC
+ case AP4_ATOM_TYPE_DCOM:
+ atom = AP4_DcomAtom::Create((unsigned long)size, stream);
+ break;
+ case AP4_ATOM_TYPE_CMVD:
+ atom = AP4_CmvdAtom::Create((unsigned long)size, stream, *this);
+ break;
+ // <== End patch MPC
+
+ default:
// try all the external type handlers
- {
- AP4_List<TypeHandler>::Item* handler_item = m_TypeHandlers.FirstItem();
- while(handler_item)
{
- TypeHandler* handler = handler_item->GetData();
- if(AP4_SUCCEEDED(handler->CreateAtom(type, size_32, stream, GetContext(), atom)))
- {
- break;
+ AP4_List<TypeHandler>::Item* handler_item = m_TypeHandlers.FirstItem();
+ while (handler_item) {
+ TypeHandler* handler = handler_item->GetData();
+ if (AP4_SUCCEEDED(handler->CreateAtom(type, size_32, stream, GetContext(), atom))) {
+ break;
+ }
+ handler_item = handler_item->GetNext();
}
- handler_item = handler_item->GetNext();
- }
- break;
- }
+ break;
+ }
}
}
-
+
// if we failed to create an atom, use a generic version
- if(atom == NULL)
- {
+ if (atom == NULL) {
unsigned int payload_offset = 8;
- if(atom_is_large) payload_offset += 8;
- stream.Seek(start + payload_offset);
+ if (atom_is_large) payload_offset += 8;
+ stream.Seek(start+payload_offset);
atom = new AP4_UnknownAtom(type, size, stream);
}
// special case: if the atom is poorly encoded and has a 64-bit
// size header but an actual size that fits on 32-bit, adjust the
// object to reflect that.
- if(force_64)
- {
+ if (force_64) {
atom->SetSize32(1);
atom->SetSize64(size);
}
@@ -709,14 +681,13 @@ AP4_AtomFactory::CreateAtomFromStream(AP4_ByteStream& stream,
bytes_available -= size;
// skip to the end of the atom
- result = stream.Seek(start + size);
- if(AP4_FAILED(result))
- {
+ result = stream.Seek(start+size);
+ if (AP4_FAILED(result)) {
delete atom;
atom = NULL;
return result;
}
-
+
return AP4_SUCCESS;
}
@@ -724,18 +695,17 @@ AP4_AtomFactory::CreateAtomFromStream(AP4_ByteStream& stream,
| AP4_AtomFactory::CreateAtomsFromStream
+---------------------------------------------------------------------*/
AP4_Result
-AP4_AtomFactory::CreateAtomsFromStream(AP4_ByteStream& stream,
+AP4_AtomFactory::CreateAtomsFromStream(AP4_ByteStream& stream,
AP4_AtomParent& atoms)
{
AP4_LargeSize stream_size = 0;
AP4_Position stream_position = 0;
AP4_LargeSize bytes_available = (AP4_LargeSize)(-1);
- if(AP4_SUCCEEDED(stream.GetSize(stream_size)) &&
- stream_size != 0 &&
- AP4_SUCCEEDED(stream.Tell(stream_position)) &&
- stream_position <= stream_size)
- {
- bytes_available = stream_size - stream_position;
+ if (AP4_SUCCEEDED(stream.GetSize(stream_size)) &&
+ stream_size != 0 &&
+ AP4_SUCCEEDED(stream.Tell(stream_position)) &&
+ stream_position <= stream_size) {
+ bytes_available = stream_size-stream_position;
}
return CreateAtomsFromStream(stream, bytes_available, atoms);
}
@@ -744,22 +714,19 @@ AP4_AtomFactory::CreateAtomsFromStream(AP4_ByteStream& stream,
| AP4_AtomFactory::CreateAtomsFromStream
+---------------------------------------------------------------------*/
AP4_Result
-AP4_AtomFactory::CreateAtomsFromStream(AP4_ByteStream& stream,
+AP4_AtomFactory::CreateAtomsFromStream(AP4_ByteStream& stream,
AP4_LargeSize bytes_available,
AP4_AtomParent& atoms)
{
AP4_Result result;
- do
- {
+ do {
AP4_Atom* atom = NULL;
result = CreateAtomFromStream(stream, bytes_available, atom);
- if(AP4_SUCCEEDED(result) && atom != NULL)
- {
+ if (AP4_SUCCEEDED(result) && atom != NULL) {
atoms.AddChild(atom);
}
- }
- while(AP4_SUCCEEDED(result));
-
+ } while (AP4_SUCCEEDED(result));
+
return AP4_SUCCESS;
}
@@ -767,7 +734,7 @@ AP4_AtomFactory::CreateAtomsFromStream(AP4_ByteStream& stream,
| AP4_AtomFactory::PushContext
+---------------------------------------------------------------------*/
void
-AP4_AtomFactory::PushContext(AP4_Atom::Type context)
+AP4_AtomFactory::PushContext(AP4_Atom::Type context)
{
m_ContextStack.Append(context);
}
@@ -776,7 +743,7 @@ AP4_AtomFactory::PushContext(AP4_Atom::Type context)
| AP4_AtomFactory::PopContext
+---------------------------------------------------------------------*/
void
-AP4_AtomFactory::PopContext()
+AP4_AtomFactory::PopContext()
{
m_ContextStack.RemoveLast();
}
@@ -785,10 +752,10 @@ AP4_AtomFactory::PopContext()
| AP4_AtomFactory::GetContext
+---------------------------------------------------------------------*/
AP4_Atom::Type
-AP4_AtomFactory::GetContext(AP4_Ordinal depth)
+AP4_AtomFactory::GetContext(AP4_Ordinal depth)
{
AP4_Ordinal available = m_ContextStack.ItemCount();
- if(depth >= available) return 0;
+ if (depth >= available) return 0;
return m_ContextStack[available-depth-1];
}
diff --git a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4AtomFactory.h b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4AtomFactory.h
index 8f2ac116a..3c7486a7c 100644
--- a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4AtomFactory.h
+++ b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4AtomFactory.h
@@ -44,19 +44,17 @@ class AP4_ByteStream;
/*----------------------------------------------------------------------
| AP4_AtomFactory
+---------------------------------------------------------------------*/
-class AP4_AtomFactory
-{
-public:
+class AP4_AtomFactory {
+ public:
// types
- class TypeHandler
- {
- public:
- virtual ~TypeHandler() {};
- virtual AP4_Result CreateAtom(AP4_Atom::Type type,
- AP4_UI32 size,
- AP4_ByteStream& stream,
- AP4_Atom::Type context,
- AP4_Atom*& atom) = 0;
+ class TypeHandler {
+ public:
+ virtual ~TypeHandler() {};
+ virtual AP4_Result CreateAtom(AP4_Atom::Type type,
+ AP4_UI32 size,
+ AP4_ByteStream& stream,
+ AP4_Atom::Type context,
+ AP4_Atom*& atom) = 0;
};
// constructor
@@ -82,7 +80,7 @@ public:
// context
void PushContext(AP4_Atom::Type context);
void PopContext();
- AP4_Atom::Type GetContext(AP4_Ordinal depth = 0);
+ AP4_Atom::Type GetContext(AP4_Ordinal depth=0);
private:
// members
@@ -93,8 +91,7 @@ private:
/*----------------------------------------------------------------------
| AP4_DefaultAtomFactory
+---------------------------------------------------------------------*/
-class AP4_DefaultAtomFactory : public AP4_AtomFactory
-{
+class AP4_DefaultAtomFactory : public AP4_AtomFactory {
public:
// class members
static AP4_DefaultAtomFactory Instance;
diff --git a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4AtomSampleTable.cpp b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4AtomSampleTable.cpp
index cd4eb4c7f..732ca2ef2 100644
--- a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4AtomSampleTable.cpp
+++ b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4AtomSampleTable.cpp
@@ -49,8 +49,8 @@
/*----------------------------------------------------------------------
| AP4_AtomSampleTable::AP4_AtomSampleTable
+---------------------------------------------------------------------*/
-AP4_AtomSampleTable::AP4_AtomSampleTable(AP4_ContainerAtom* stbl,
- AP4_ByteStream& sample_stream) :
+AP4_AtomSampleTable::AP4_AtomSampleTable(AP4_ContainerAtom* stbl,
+ AP4_ByteStream& sample_stream) :
m_SampleStream(sample_stream)
{
m_StscAtom = AP4_DYNAMIC_CAST(AP4_StscAtom, stbl->GetChild(AP4_ATOM_TYPE_STSC));
@@ -65,44 +65,44 @@ AP4_AtomSampleTable::AP4_AtomSampleTable(AP4_ContainerAtom* stbl,
// keep a reference to the sample stream
m_SampleStream.AddReference();
- // ==> Start patch MPC
- if(m_StsdAtom && m_StszAtom && m_StscAtom && m_SttsAtom
- && m_StszAtom->m_SampleSize == 1)
- {
- // fix mov files
- for(AP4_List<AP4_Atom>::Item* item = m_StsdAtom->GetChildren().FirstItem();
- item;
- item = item->GetNext())
- {
- AP4_Atom* atom = item->GetData();
-
- if(AP4_AudioSampleEntry* ase = dynamic_cast<AP4_AudioSampleEntry*>(atom))
- {
- AP4_UI32 SamplesPerPacket = ase->GetSamplesPerPacket();
- AP4_UI32 BytesPerFrame = ase->GetBytesPerFrame();
-
- if(SamplesPerPacket > 0 && BytesPerFrame > 0)
- {
- for(int i = 0, j = m_StscAtom->m_Entries.ItemCount(); i < j; i++)
- {
- AP4_StscTableEntry& e = m_StscAtom->m_Entries[i];
- AP4_ASSERT(e.m_SamplesPerChunk % SamplesPerPacket == 0);
- e.m_SamplesPerChunk = e.m_SamplesPerChunk / SamplesPerPacket;
- e.m_FirstSample = (e.m_FirstSample - 1) / SamplesPerPacket + 1;
- }
-
- AP4_ASSERT(m_StszAtom->m_SampleCount % SamplesPerPacket == 0);
- m_StszAtom->m_SampleCount = m_StszAtom->m_SampleCount / SamplesPerPacket;
- m_StszAtom->m_SampleSize = BytesPerFrame;
-
- AP4_ASSERT(m_SttsAtom->m_Entries.ItemCount() == 1);
- m_SttsAtom->m_Entries[0].m_SampleCount = m_StszAtom->m_SampleCount;
- m_SttsAtom->m_Entries[0].m_SampleDuration = SamplesPerPacket;
- }
- }
- }
- }
- // <== End patch MPC
+ // ==> Start patch MPC
+ if(m_StsdAtom && m_StszAtom && m_StscAtom && m_SttsAtom
+ && m_StszAtom->m_SampleSize == 1)
+ {
+ // fix mov files
+ for(AP4_List<AP4_Atom>::Item* item = m_StsdAtom->GetChildren().FirstItem();
+ item;
+ item = item->GetNext())
+ {
+ AP4_Atom* atom = item->GetData();
+
+ if(AP4_AudioSampleEntry* ase = dynamic_cast<AP4_AudioSampleEntry*>(atom))
+ {
+ AP4_UI32 SamplesPerPacket = ase->GetSamplesPerPacket();
+ AP4_UI32 BytesPerFrame = ase->GetBytesPerFrame();
+
+ if(SamplesPerPacket > 0 && BytesPerFrame > 0)
+ {
+ for(int i = 0, j = m_StscAtom->m_Entries.ItemCount(); i < j; i++)
+ {
+ AP4_StscTableEntry& e = m_StscAtom->m_Entries[i];
+ AP4_ASSERT(e.m_SamplesPerChunk % SamplesPerPacket == 0);
+ e.m_SamplesPerChunk = e.m_SamplesPerChunk / SamplesPerPacket;
+ e.m_FirstSample = (e.m_FirstSample-1) / SamplesPerPacket + 1;
+ }
+
+ AP4_ASSERT(m_StszAtom->m_SampleCount % SamplesPerPacket == 0);
+ m_StszAtom->m_SampleCount = m_StszAtom->m_SampleCount / SamplesPerPacket;
+ m_StszAtom->m_SampleSize = BytesPerFrame;
+
+ AP4_ASSERT(m_SttsAtom->m_Entries.ItemCount() == 1);
+ m_SttsAtom->m_Entries[0].m_SampleCount = m_StszAtom->m_SampleCount;
+ m_SttsAtom->m_Entries[0].m_SampleDuration = SamplesPerPacket;
+ }
+ }
+ }
+ }
+ // <== End patch MPC
}
@@ -118,14 +118,13 @@ AP4_AtomSampleTable::~AP4_AtomSampleTable()
| AP4_AtomSampleTable::GetSample
+---------------------------------------------------------------------*/
AP4_Result
-AP4_AtomSampleTable::GetSample(AP4_Ordinal index,
+AP4_AtomSampleTable::GetSample(AP4_Ordinal index,
AP4_Sample& sample)
{
AP4_Result result;
// check that we have a chunk offset table
- if(m_StcoAtom == NULL && m_Co64Atom == NULL)
- {
+ if (m_StcoAtom == NULL && m_Co64Atom == NULL) {
return AP4_ERROR_INVALID_FORMAT;
}
@@ -135,69 +134,59 @@ AP4_AtomSampleTable::GetSample(AP4_Ordinal index,
// find out in which chunk this sample is located
AP4_Ordinal chunk, skip, desc;
result = m_StscAtom->GetChunkForSample(index, chunk, skip, desc);
- if(AP4_FAILED(result)) return result;
-
+ if (AP4_FAILED(result)) return result;
+
// check that the result is within bounds
- if(skip > index) return AP4_ERROR_INTERNAL;
+ if (skip > index) return AP4_ERROR_INTERNAL;
// get the atom offset for this chunk
AP4_UI64 offset;
- if(m_StcoAtom)
- {
+ if (m_StcoAtom) {
AP4_UI32 offset_32;
result = m_StcoAtom->GetChunkOffset(chunk, offset_32);
offset = offset_32;
- }
- else
- {
+ } else {
result = m_Co64Atom->GetChunkOffset(chunk, offset);
}
- if(AP4_FAILED(result)) return result;
-
+ if (AP4_FAILED(result)) return result;
+
// compute the additional offset inside the chunk
- for(unsigned int i = index - skip; i < index; i++)
- {
+ for (unsigned int i = index-skip; i < index; i++) {
AP4_Size size;
- result = m_StszAtom->GetSampleSize(i, size);
- if(AP4_FAILED(result)) return result;
+ result = m_StszAtom->GetSampleSize(i, size);
+ if (AP4_FAILED(result)) return result;
offset += size;
}
// set the description index
- sample.SetDescriptionIndex(desc - 1); // adjust for 0-based indexes
+ sample.SetDescriptionIndex(desc-1); // adjust for 0-based indexes
// set the dts and cts
AP4_UI32 cts_offset = 0;
AP4_UI64 dts = 0;
AP4_UI32 duration = 0;
result = m_SttsAtom->GetDts(index, dts, &duration);
- if(AP4_FAILED(result)) return result;
+ if (AP4_FAILED(result)) return result;
sample.SetDuration(duration);
sample.SetDts(dts);
- if(m_CttsAtom == NULL)
- {
+ if (m_CttsAtom == NULL) {
sample.SetCts(dts);
- }
- else
- {
- result = m_CttsAtom->GetCtsOffset(index, cts_offset);
- if(AP4_FAILED(result)) return result;
+ } else {
+ result = m_CttsAtom->GetCtsOffset(index, cts_offset);
+ if (AP4_FAILED(result)) return result;
sample.SetCtsDelta(cts_offset);
- }
+ }
// set the size
AP4_Size sample_size;
result = m_StszAtom->GetSampleSize(index, sample_size);
- if(AP4_FAILED(result)) return result;
+ if (AP4_FAILED(result)) return result;
sample.SetSize(sample_size);
// set the sync flag
- if(m_StssAtom == NULL)
- {
+ if (m_StssAtom == NULL) {
sample.SetSync(true);
- }
- else
- {
+ } else {
sample.SetSync(m_StssAtom->IsSampleSync(index));
}
@@ -241,26 +230,26 @@ AP4_AtomSampleTable::GetSampleDescriptionCount()
/*----------------------------------------------------------------------
| AP4_AtomSampleTable::GetSampleChunkPosition
+---------------------------------------------------------------------*/
-AP4_Result
-AP4_AtomSampleTable::GetSampleChunkPosition(AP4_Ordinal sample_index,
- AP4_Ordinal& chunk_index,
- AP4_Ordinal& position_in_chunk)
+AP4_Result
+AP4_AtomSampleTable::GetSampleChunkPosition(AP4_Ordinal sample_index,
+ AP4_Ordinal& chunk_index,
+ AP4_Ordinal& position_in_chunk)
{
// default values
chunk_index = 0;
position_in_chunk = 0;
-
+
AP4_Ordinal sample_description_index;
- return GetChunkForSample(sample_index,
- chunk_index,
- position_in_chunk,
+ return GetChunkForSample(sample_index,
+ chunk_index,
+ position_in_chunk,
sample_description_index);
}
/*----------------------------------------------------------------------
| AP4_AtomSampleTable::GetChunkForSample
+---------------------------------------------------------------------*/
-AP4_Result
+AP4_Result
AP4_AtomSampleTable::GetChunkForSample(AP4_Ordinal sample_index,
AP4_Ordinal& chunk_index,
AP4_Ordinal& position_in_chunk,
@@ -272,50 +261,42 @@ AP4_AtomSampleTable::GetChunkForSample(AP4_Ordinal sample_index,
sample_description_index = 0;
// check that we an stsc atom
- if(m_StscAtom == NULL) return AP4_ERROR_INVALID_STATE;
-
+ if (m_StscAtom == NULL) return AP4_ERROR_INVALID_STATE;
+
// get the chunk info from the stsc atom
AP4_Ordinal chunk = 0;
- AP4_Result result = m_StscAtom->GetChunkForSample(sample_index + 1, // the atom API is 1-based
- chunk,
- position_in_chunk,
- sample_description_index);
- if(AP4_FAILED(result)) return result;
- if(chunk == 0) return AP4_ERROR_INTERNAL;
+ AP4_Result result = m_StscAtom->GetChunkForSample(sample_index+1, // the atom API is 1-based
+ chunk,
+ position_in_chunk,
+ sample_description_index);
+ if (AP4_FAILED(result)) return result;
+ if (chunk == 0) return AP4_ERROR_INTERNAL;
// the atom sample and chunk indexes are 1-based, so we need to translate
- chunk_index = chunk - 1;
-
+ chunk_index = chunk-1;
+
return AP4_SUCCESS;
}
/*----------------------------------------------------------------------
| AP4_AtomSampleTable::GetChunkOffset
+---------------------------------------------------------------------*/
-AP4_Result
-AP4_AtomSampleTable::GetChunkOffset(AP4_Ordinal chunk_index,
+AP4_Result
+AP4_AtomSampleTable::GetChunkOffset(AP4_Ordinal chunk_index,
AP4_Position& offset)
{
- if(m_StcoAtom)
- {
+ if (m_StcoAtom) {
AP4_UI32 offset_32;
- AP4_Result result = m_StcoAtom->GetChunkOffset(chunk_index + 1, offset_32);
- if(AP4_SUCCEEDED(result))
- {
+ AP4_Result result = m_StcoAtom->GetChunkOffset(chunk_index+1, offset_32);
+ if (AP4_SUCCEEDED(result)) {
offset = offset_32;
- }
- else
- {
+ } else {
offset = 0;
}
return result;
- }
- else if(m_Co64Atom)
- {
- return m_Co64Atom->GetChunkOffset(chunk_index + 1, offset);
- }
- else
- {
+ } else if (m_Co64Atom) {
+ return m_Co64Atom->GetChunkOffset(chunk_index+1, offset);
+ } else {
offset = 0;
return AP4_FAILURE;
}
@@ -324,21 +305,16 @@ AP4_AtomSampleTable::GetChunkOffset(AP4_Ordinal chunk_index,
/*----------------------------------------------------------------------
| AP4_AtomSampleTable::SetChunkOffset
+---------------------------------------------------------------------*/
-AP4_Result
-AP4_AtomSampleTable::SetChunkOffset(AP4_Ordinal chunk_index,
+AP4_Result
+AP4_AtomSampleTable::SetChunkOffset(AP4_Ordinal chunk_index,
AP4_Position offset)
{
- if(m_StcoAtom)
- {
- if((offset >> 32) != 0) return AP4_ERROR_OUT_OF_RANGE;
- return m_StcoAtom->SetChunkOffset(chunk_index + 1, (AP4_UI32)offset);
- }
- else if(m_Co64Atom)
- {
- return m_Co64Atom->SetChunkOffset(chunk_index + 1, offset);
- }
- else
- {
+ if (m_StcoAtom) {
+ if ((offset >> 32) != 0) return AP4_ERROR_OUT_OF_RANGE;
+ return m_StcoAtom->SetChunkOffset(chunk_index+1, (AP4_UI32)offset);
+ } else if (m_Co64Atom) {
+ return m_Co64Atom->SetChunkOffset(chunk_index+1, offset);
+ } else {
return AP4_FAILURE;
}
}
@@ -346,53 +322,47 @@ AP4_AtomSampleTable::SetChunkOffset(AP4_Ordinal chunk_index,
/*----------------------------------------------------------------------
| AP4_AtomSampleTable::SetSampleSize
+---------------------------------------------------------------------*/
-AP4_Result
+AP4_Result
AP4_AtomSampleTable::SetSampleSize(AP4_Ordinal sample_index, AP4_Size size)
{
- return m_StszAtom ? m_StszAtom->SetSampleSize(sample_index + 1, size) : AP4_FAILURE;
+ return m_StszAtom ? m_StszAtom->SetSampleSize(sample_index+1, size) : AP4_FAILURE;
}
/*----------------------------------------------------------------------
| AP4_AtomSampleTable::GetSampleIndexForTimeStamp
+---------------------------------------------------------------------*/
-AP4_Result
-AP4_AtomSampleTable::GetSampleIndexForTimeStamp(AP4_UI64 ts,
- AP4_Ordinal& sample_index)
+AP4_Result
+AP4_AtomSampleTable::GetSampleIndexForTimeStamp(AP4_UI64 ts,
+ AP4_Ordinal& sample_index)
{
- return m_SttsAtom ? m_SttsAtom->GetSampleIndexForTimeStamp(ts, sample_index)
- : AP4_FAILURE;
+ return m_SttsAtom ? m_SttsAtom->GetSampleIndexForTimeStamp(ts, sample_index)
+ : AP4_FAILURE;
}
/*----------------------------------------------------------------------
| AP4_AtomSampleTable::GetNearestSyncSampleIndex
+---------------------------------------------------------------------*/
-AP4_Ordinal
+AP4_Ordinal
AP4_AtomSampleTable::GetNearestSyncSampleIndex(AP4_Ordinal sample_index, bool before)
{
// if we don't have an stss table, all samples match
- if(m_StssAtom == NULL) return sample_index;
-
+ if (m_StssAtom == NULL) return sample_index;
+
sample_index += 1; // the table is 1-based
AP4_Cardinal entry_count = m_StssAtom->GetEntries().ItemCount();
- if(before)
- {
- AP4_Ordinal cursor = 0;
- for(unsigned int i = 0; i < entry_count; i++)
- {
- if(m_StssAtom->GetEntries()[i] >= sample_index) return cursor;
- if(m_StssAtom->GetEntries()[i]) cursor = m_StssAtom->GetEntries()[i] - 1;
+ if (before) {
+ AP4_Ordinal cursor = 0;
+ for (unsigned int i=0; i<entry_count; i++) {
+ if (m_StssAtom->GetEntries()[i] >= sample_index) return cursor;
+ if (m_StssAtom->GetEntries()[i]) cursor = m_StssAtom->GetEntries()[i]-1;
}
// not found?
return cursor;
- }
- else
- {
- for(unsigned int i = 0; i < entry_count; i++)
- {
- if(m_StssAtom->GetEntries()[i] >= sample_index)
- {
- return m_StssAtom->GetEntries()[i] ? m_StssAtom->GetEntries()[i] - 1 : sample_index - 1;
+ } else {
+ for (unsigned int i=0; i<entry_count; i++) {
+ if (m_StssAtom->GetEntries()[i] >= sample_index) {
+ return m_StssAtom->GetEntries()[i]?m_StssAtom->GetEntries()[i]-1:sample_index-1;
}
}
diff --git a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4AtomSampleTable.h b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4AtomSampleTable.h
index e90bd9cc1..aaecbf917 100644
--- a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4AtomSampleTable.h
+++ b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4AtomSampleTable.h
@@ -54,10 +54,10 @@ class AP4_Co64Atom;
+---------------------------------------------------------------------*/
class AP4_AtomSampleTable : public AP4_SampleTable
{
-public:
+ public:
// methods
- AP4_AtomSampleTable(AP4_ContainerAtom* stbl_atom,
- AP4_ByteStream& sample_stream);
+ AP4_AtomSampleTable(AP4_ContainerAtom* stbl_atom,
+ AP4_ByteStream& sample_stream);
virtual ~AP4_AtomSampleTable();
// AP4_SampleTable methods
@@ -65,11 +65,11 @@ public:
virtual AP4_Cardinal GetSampleCount();
virtual AP4_SampleDescription* GetSampleDescription(AP4_Ordinal sd_index);
virtual AP4_Cardinal GetSampleDescriptionCount();
- virtual AP4_Result GetSampleChunkPosition(AP4_Ordinal sample_index,
- AP4_Ordinal& chunk_index,
- AP4_Ordinal& position_in_chunk);
+ virtual AP4_Result GetSampleChunkPosition(AP4_Ordinal sample_index,
+ AP4_Ordinal& chunk_index,
+ AP4_Ordinal& position_in_chunk);
virtual AP4_Result GetSampleIndexForTimeStamp(AP4_UI64 ts, AP4_Ordinal& sample_index);
- virtual AP4_Ordinal GetNearestSyncSampleIndex(AP4_Ordinal index, bool before = true);
+ virtual AP4_Ordinal GetNearestSyncSampleIndex(AP4_Ordinal index, bool before=true);
// local methods
virtual AP4_Result GetChunkForSample(AP4_Ordinal sample_index,
diff --git a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4AvcCAtom.cpp b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4AvcCAtom.cpp
index bca60cfe2..ac227203d 100644
--- a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4AvcCAtom.cpp
+++ b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4AvcCAtom.cpp
@@ -1,6 +1,6 @@
/*****************************************************************
|
-| AP4 - avcC Atoms
+| AP4 - avcC Atoms
|
| Copyright 2002-2008 Axiomatic Systems, LLC
|
@@ -45,22 +45,14 @@ AP4_DEFINE_DYNAMIC_CAST_ANCHOR(AP4_AvccAtom)
const char*
AP4_AvccAtom::GetProfileName(AP4_UI08 profile)
{
- switch(profile)
- {
- case AP4_AVC_PROFILE_BASELINE:
- return "Baseline";
- case AP4_AVC_PROFILE_MAIN:
- return "Main";
- case AP4_AVC_PROFILE_EXTENDED:
- return "Extended";
- case AP4_AVC_PROFILE_HIGH:
- return "High";
- case AP4_AVC_PROFILE_HIGH_10:
- return "High 10";
- case AP4_AVC_PROFILE_HIGH_422:
- return "High 4:2:2";
- case AP4_AVC_PROFILE_HIGH_444:
- return "High 4:4:4";
+ switch (profile) {
+ case AP4_AVC_PROFILE_BASELINE: return "Baseline";
+ case AP4_AVC_PROFILE_MAIN: return "Main";
+ case AP4_AVC_PROFILE_EXTENDED: return "Extended";
+ case AP4_AVC_PROFILE_HIGH: return "High";
+ case AP4_AVC_PROFILE_HIGH_10: return "High 10";
+ case AP4_AVC_PROFILE_HIGH_422: return "High 4:2:2";
+ case AP4_AVC_PROFILE_HIGH_444: return "High 4:4:4";
}
return NULL;
@@ -69,39 +61,36 @@ AP4_AvccAtom::GetProfileName(AP4_UI08 profile)
/*----------------------------------------------------------------------
| AP4_AvccAtom::Create
+---------------------------------------------------------------------*/
-AP4_AvccAtom*
+AP4_AvccAtom*
AP4_AvccAtom::Create(AP4_Size size, AP4_ByteStream& stream)
{
// read the raw bytes in a buffer
- unsigned int payload_size = size - AP4_ATOM_HEADER_SIZE;
+ unsigned int payload_size = size-AP4_ATOM_HEADER_SIZE;
AP4_DataBuffer payload_data(payload_size);
AP4_Result result = stream.Read(payload_data.UseData(), payload_size);
- if(AP4_FAILED(result)) return NULL;
-
+ if (AP4_FAILED(result)) return NULL;
+
// check the version
const AP4_UI08* payload = payload_data.GetData();
- if(payload[0] != 1)
- {
+ if (payload[0] != 1) {
return NULL;
}
// check the size
- if(payload_size < 6) return NULL;
- unsigned int num_seq_params = payload[5] & 31;
+ if (payload_size < 6) return NULL;
+ unsigned int num_seq_params = payload[5]&31;
unsigned int cursor = 6;
- for(unsigned int i = 0; i < num_seq_params; i++)
- {
- if(cursor + 2 > payload_size) return NULL;
- cursor += 2 + AP4_BytesToInt16BE(&payload[cursor]);
- if(cursor > payload_size) return NULL;
+ for (unsigned int i=0; i<num_seq_params; i++) {
+ if (cursor+2 > payload_size) return NULL;
+ cursor += 2+AP4_BytesToInt16BE(&payload[cursor]);
+ if (cursor > payload_size) return NULL;
}
unsigned int num_pic_params = payload[cursor++];
- if(cursor > payload_size) return NULL;
- for(unsigned int i = 0; i < num_pic_params; i++)
- {
- if(cursor + 2 > payload_size) return NULL;
- cursor += 2 + AP4_BytesToInt16BE(&payload[cursor]);
- if(cursor > payload_size) return NULL;
+ if (cursor > payload_size) return NULL;
+ for (unsigned int i=0; i<num_pic_params; i++) {
+ if (cursor+2 > payload_size) return NULL;
+ cursor += 2+AP4_BytesToInt16BE(&payload[cursor]);
+ if (cursor > payload_size) return NULL;
}
return new AP4_AvccAtom(size, payload);
}
@@ -135,14 +124,12 @@ AP4_AvccAtom::AP4_AvccAtom(const AP4_AvccAtom& other) :
{
// deep copy of the parameters
unsigned int i = 0;
- for(i = 0; i < other.m_SequenceParameters.ItemCount(); i++)
- {
+ for (i=0; i<other.m_SequenceParameters.ItemCount(); i++) {
m_SequenceParameters.Append(other.m_SequenceParameters[i]);
}
- for(i = 0; i < other.m_PictureParameters.ItemCount(); i++)
- {
+ for (i=0; i<other.m_PictureParameters.ItemCount(); i++) {
m_PictureParameters.Append(other.m_PictureParameters[i]);
- }
+ }
}
/*----------------------------------------------------------------------
@@ -152,7 +139,7 @@ AP4_AvccAtom::AP4_AvccAtom(AP4_UI32 size, const AP4_UI08* payload) :
AP4_Atom(AP4_ATOM_TYPE_AVCC, size)
{
// make a copy of our configuration bytes
- unsigned int payload_size = size - AP4_ATOM_HEADER_SIZE;
+ unsigned int payload_size = size-AP4_ATOM_HEADER_SIZE;
m_RawBytes.SetData(payload, payload_size);
// parse the payload
@@ -160,25 +147,23 @@ AP4_AvccAtom::AP4_AvccAtom(AP4_UI32 size, const AP4_UI08* payload) :
m_Profile = payload[1];
m_ProfileCompatibility = payload[2];
m_Level = payload[3];
- m_NaluLengthSize = 1 + (payload[4] & 3);
- AP4_UI08 num_seq_params = payload[5] & 31;
+ m_NaluLengthSize = 1+(payload[4]&3);
+ AP4_UI08 num_seq_params = payload[5]&31;
m_SequenceParameters.EnsureCapacity(num_seq_params);
unsigned int cursor = 6;
- for(unsigned int i = 0; i < num_seq_params; i++)
- {
+ for (unsigned int i=0; i<num_seq_params; i++) {
m_SequenceParameters.Append(AP4_DataBuffer());
AP4_UI16 param_length = AP4_BytesToInt16BE(&payload[cursor]);
- m_SequenceParameters[i].SetData(&payload[cursor] + 2, param_length);
- cursor += 2 + param_length;
+ m_SequenceParameters[i].SetData(&payload[cursor]+2, param_length);
+ cursor += 2+param_length;
}
AP4_UI08 num_pic_params = payload[cursor++];
m_PictureParameters.EnsureCapacity(num_pic_params);
- for(unsigned int i = 0; i < num_pic_params; i++)
- {
+ for (unsigned int i=0; i<num_pic_params; i++) {
m_PictureParameters.Append(AP4_DataBuffer());
AP4_UI16 param_length = AP4_BytesToInt16BE(&payload[cursor]);
- m_PictureParameters[i].SetData(&payload[cursor] + 2, param_length);
- cursor += 2 + param_length;
+ m_PictureParameters[i].SetData(&payload[cursor]+2, param_length);
+ cursor += 2+param_length;
}
}
@@ -186,11 +171,11 @@ AP4_AvccAtom::AP4_AvccAtom(AP4_UI32 size, const AP4_UI08* payload) :
/*----------------------------------------------------------------------
| AP4_AvccAtom::AP4_AvccAtom
+---------------------------------------------------------------------*/
-AP4_AvccAtom::AP4_AvccAtom(AP4_UI08 profile,
- AP4_UI08 level,
- AP4_UI08 profile_compatibility,
- AP4_UI08 length_size,
- const AP4_Array<AP4_DataBuffer>& sequence_parameters,
+AP4_AvccAtom::AP4_AvccAtom(AP4_UI08 profile,
+ AP4_UI08 level,
+ AP4_UI08 profile_compatibility,
+ AP4_UI08 length_size,
+ const AP4_Array<AP4_DataBuffer>& sequence_parameters,
const AP4_Array<AP4_DataBuffer>& picture_parameters) :
AP4_Atom(AP4_ATOM_TYPE_AVCC, AP4_ATOM_HEADER_SIZE),
m_ConfigurationVersion(1),
@@ -201,14 +186,12 @@ AP4_AvccAtom::AP4_AvccAtom(AP4_UI08 profile,
{
// deep copy of the parameters
unsigned int i = 0;
- for(i = 0; i < sequence_parameters.ItemCount(); i++)
- {
+ for (i=0; i<sequence_parameters.ItemCount(); i++) {
m_SequenceParameters.Append(sequence_parameters[i]);
}
- for(i = 0; i < picture_parameters.ItemCount(); i++)
- {
+ for (i=0; i<picture_parameters.ItemCount(); i++) {
m_PictureParameters.Append(picture_parameters[i]);
- }
+ }
// compute the raw bytes
UpdateRawBytes();
@@ -224,15 +207,13 @@ void
AP4_AvccAtom::UpdateRawBytes()
{
// compute the payload size
- unsigned int payload_size = 6;
- for(unsigned int i = 0; i < m_SequenceParameters.ItemCount(); i++)
- {
- payload_size += 2 + m_SequenceParameters[i].GetDataSize();
+ unsigned int payload_size = 6;
+ for (unsigned int i=0; i<m_SequenceParameters.ItemCount(); i++) {
+ payload_size += 2+m_SequenceParameters[i].GetDataSize();
}
++payload_size;
- for(unsigned int i = 0; i < m_PictureParameters.ItemCount(); i++)
- {
- payload_size += 2 + m_PictureParameters[i].GetDataSize();
+ for (unsigned int i=0; i<m_PictureParameters.ItemCount(); i++) {
+ payload_size += 2+m_PictureParameters[i].GetDataSize();
}
m_RawBytes.SetDataSize(payload_size);
AP4_UI08* payload = m_RawBytes.UseData();
@@ -241,11 +222,10 @@ AP4_AvccAtom::UpdateRawBytes()
payload[1] = m_Profile;
payload[2] = m_ProfileCompatibility;
payload[3] = m_Level;
- payload[4] = 0xFC | (m_NaluLengthSize - 1);
+ payload[4] = 0xFC | (m_NaluLengthSize-1);
payload[5] = 0xE0 | m_SequenceParameters.ItemCount();
unsigned int cursor = 6;
- for(unsigned int i = 0; i < m_SequenceParameters.ItemCount(); i++)
- {
+ for (unsigned int i=0; i<m_SequenceParameters.ItemCount(); i++) {
AP4_UI16 param_length = (AP4_UI16)m_SequenceParameters[i].GetDataSize();
AP4_BytesFromUInt16BE(&payload[cursor], param_length);
cursor += 2;
@@ -253,8 +233,7 @@ AP4_AvccAtom::UpdateRawBytes()
cursor += param_length;
}
payload[cursor++] = m_PictureParameters.ItemCount();
- for(unsigned int i = 0; i < m_PictureParameters.ItemCount(); i++)
- {
+ for (unsigned int i=0; i<m_PictureParameters.ItemCount(); i++) {
AP4_UI16 param_length = (AP4_UI16)m_PictureParameters[i].GetDataSize();
AP4_BytesFromUInt16BE(&payload[cursor], param_length);
cursor += 2;
@@ -280,23 +259,18 @@ AP4_AvccAtom::InspectFields(AP4_AtomInspector& inspector)
{
inspector.AddField("Configuration Version", m_ConfigurationVersion);
const char* profile_name = GetProfileName(m_Profile);
- if(profile_name)
- {
+ if (profile_name) {
inspector.AddField("Profile", profile_name);
- }
- else
- {
+ } else {
inspector.AddField("Profile", m_Profile);
}
inspector.AddField("Profile Compatibility", m_ProfileCompatibility, AP4_AtomInspector::HINT_HEX);
inspector.AddField("Level", m_Level);
inspector.AddField("NALU Length Size", m_NaluLengthSize);
- for(unsigned int i = 0; i < m_SequenceParameters.ItemCount(); i++)
- {
+ for (unsigned int i=0; i<m_SequenceParameters.ItemCount(); i++) {
inspector.AddField("Sequence Parameter", m_SequenceParameters[i].GetData(), m_SequenceParameters[i].GetDataSize());
}
- for(unsigned int i = 0; i < m_SequenceParameters.ItemCount(); i++)
- {
+ for (unsigned int i=0; i<m_SequenceParameters.ItemCount(); i++) {
inspector.AddField("Picture Parameter", m_PictureParameters[i].GetData(), m_PictureParameters[i].GetDataSize());
}
return AP4_SUCCESS;
diff --git a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4AvcCAtom.h b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4AvcCAtom.h
index c2c790759..b3b300853 100644
--- a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4AvcCAtom.h
+++ b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4AvcCAtom.h
@@ -1,6 +1,6 @@
/*****************************************************************
|
-| AP4 - avcC Atoms
+| AP4 - avcC Atoms
|
| Copyright 2002-2008 Axiomatic Systems, LLC
|
@@ -68,50 +68,26 @@ public:
const AP4_Array<AP4_DataBuffer>& sequence_parameters,
const AP4_Array<AP4_DataBuffer>& picture_parameters);
AP4_AvccAtom(const AP4_AvccAtom& other); // copy construtor
-
+
// methods
virtual AP4_Result InspectFields(AP4_AtomInspector& inspector);
virtual AP4_Result WriteFields(AP4_ByteStream& stream);
// accessors
- AP4_UI08 GetConfigurationVersion() const
- {
- return m_ConfigurationVersion;
- }
- AP4_UI08 GetProfile() const
- {
- return m_Profile;
- }
- AP4_UI08 GetLevel() const
- {
- return m_Level;
- }
- AP4_UI08 GetProfileCompatibility() const
- {
- return m_ProfileCompatibility;
- }
- AP4_UI08 GetNaluLengthSize() const
- {
- return m_NaluLengthSize;
- }
- AP4_Array<AP4_DataBuffer>& GetSequenceParameters()
- {
- return m_SequenceParameters;
- }
- AP4_Array<AP4_DataBuffer>& GetPictureParameters()
- {
- return m_PictureParameters;
- }
- const AP4_DataBuffer& GetRawBytes() const
- {
- return m_RawBytes;
- }
+ AP4_UI08 GetConfigurationVersion() const { return m_ConfigurationVersion; }
+ AP4_UI08 GetProfile() const { return m_Profile; }
+ AP4_UI08 GetLevel() const { return m_Level; }
+ AP4_UI08 GetProfileCompatibility() const { return m_ProfileCompatibility; }
+ AP4_UI08 GetNaluLengthSize() const { return m_NaluLengthSize; }
+ AP4_Array<AP4_DataBuffer>& GetSequenceParameters() { return m_SequenceParameters; }
+ AP4_Array<AP4_DataBuffer>& GetPictureParameters() { return m_PictureParameters; }
+ const AP4_DataBuffer& GetRawBytes() const { return m_RawBytes; }
private:
// methods
AP4_AvccAtom(AP4_UI32 size, const AP4_UI08* payload);
void UpdateRawBytes();
-
+
// members
AP4_UI08 m_ConfigurationVersion;
AP4_UI08 m_Profile;
diff --git a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4ByteStream.cpp b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4ByteStream.cpp
index 462eaf88a..e5c33d319 100644
--- a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4ByteStream.cpp
+++ b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4ByteStream.cpp
@@ -22,7 +22,7 @@
| You should have received a copy of the GNU General Public License
| along with Bento4|GPL; see the file COPYING. If not, write to the
| Free Software Foundation, 59 Temple Place - Suite 330, Boston, MA
-| 02111-1307, USA.
+| 02111-1307, USA.
|
****************************************************************/
@@ -46,22 +46,21 @@ AP4_Result
AP4_ByteStream::Read(void* buffer, AP4_Size bytes_to_read)
{
// shortcut
- if(bytes_to_read == 0) return AP4_SUCCESS;
-
+ if (bytes_to_read == 0) return AP4_SUCCESS;
+
// read until failure
AP4_Size bytes_read;
- while(bytes_to_read)
- {
+ while (bytes_to_read) {
AP4_Result result = ReadPartial(buffer, bytes_to_read, bytes_read);
- if(AP4_FAILED(result)) return result;
- if(bytes_read == 0) return AP4_ERROR_INTERNAL;
+ if (AP4_FAILED(result)) return result;
+ if (bytes_read == 0) return AP4_ERROR_INTERNAL;
AP4_ASSERT(bytes_read <= bytes_to_read);
bytes_to_read -= bytes_read;
- buffer = (void*)(((AP4_Byte*)buffer) + bytes_read);
+ buffer = (void*)(((AP4_Byte*)buffer)+bytes_read);
}
-
+
return AP4_SUCCESS;
-}
+}
/*----------------------------------------------------------------------
| AP4_Stream::Write
@@ -70,20 +69,19 @@ AP4_Result
AP4_ByteStream::Write(const void* buffer, AP4_Size bytes_to_write)
{
// shortcut
- if(bytes_to_write == 0) return AP4_SUCCESS;
-
+ if (bytes_to_write == 0) return AP4_SUCCESS;
+
// write until failure
AP4_Size bytes_written;
- while(bytes_to_write)
- {
+ while (bytes_to_write) {
AP4_Result result = WritePartial(buffer, bytes_to_write, bytes_written);
- if(AP4_FAILED(result)) return result;
- if(bytes_written == 0) return AP4_ERROR_INTERNAL;
+ if (AP4_FAILED(result)) return result;
+ if (bytes_written == 0) return AP4_ERROR_INTERNAL;
AP4_ASSERT(bytes_written <= bytes_to_write);
bytes_to_write -= bytes_written;
- buffer = (const void*)(((const AP4_Byte*)buffer) + bytes_written);
+ buffer = (const void*)(((const AP4_Byte*)buffer)+bytes_written);
}
-
+
return AP4_SUCCESS;
}
@@ -96,7 +94,7 @@ AP4_ByteStream::WriteString(const char* buffer)
AP4_Size string_length = static_cast<AP4_Size>(strlen(buffer));
// shortcut
- if((buffer == NULL) || (string_length == 0)) return AP4_SUCCESS;
+ if ((buffer == NULL) || (string_length == 0)) return AP4_SUCCESS;
// write the string
return Write((const void*)buffer, string_length);
@@ -197,15 +195,14 @@ AP4_ByteStream::ReadUI64(AP4_UI64& value)
// read bytes from the stream
AP4_Result result;
result = Read((void*)buffer, 8);
- if(AP4_FAILED(result))
- {
+ if (AP4_FAILED(result)) {
value = 0;
return result;
}
// convert bytes to value
value = AP4_BytesToUInt64BE(buffer);
-
+
return AP4_SUCCESS;
}
@@ -220,15 +217,14 @@ AP4_ByteStream::ReadDouble(double& value)
// read bytes from the stream
AP4_Result result;
result = Read((void*)buffer, 8);
- if(AP4_FAILED(result))
- {
+ if (AP4_FAILED(result)) {
value = 0;
return result;
}
// convert bytes to value
value = AP4_BytesToDoubleBE(buffer);
-
+
return AP4_SUCCESS;
}
@@ -243,15 +239,14 @@ AP4_ByteStream::ReadUI32(AP4_UI32& value)
// read bytes from the stream
AP4_Result result;
result = Read((void*)buffer, 4);
- if(AP4_FAILED(result))
- {
+ if (AP4_FAILED(result)) {
value = 0;
return result;
}
// convert bytes to value
value = AP4_BytesToUInt32BE(buffer);
-
+
return AP4_SUCCESS;
}
@@ -266,15 +261,14 @@ AP4_ByteStream::ReadUI24(AP4_UI32& value)
// read bytes from the stream
AP4_Result result;
result = Read((void*)buffer, 3);
- if(AP4_FAILED(result))
- {
+ if (AP4_FAILED(result)) {
value = 0;
return result;
}
// convert bytes to value
value = AP4_BytesToUInt24BE(buffer);
-
+
return AP4_SUCCESS;
}
@@ -289,15 +283,14 @@ AP4_ByteStream::ReadUI16(AP4_UI16& value)
// read bytes from the stream
AP4_Result result;
result = Read((void*)buffer, 2);
- if(AP4_FAILED(result))
- {
+ if (AP4_FAILED(result)) {
value = 0;
return result;
}
// convert bytes to value
value = AP4_BytesToUInt16BE(buffer);
-
+
return AP4_SUCCESS;
}
@@ -312,15 +305,14 @@ AP4_ByteStream::ReadUI08(AP4_UI08& value)
// read bytes from the stream
AP4_Result result;
result = Read((void*)buffer, 1);
- if(AP4_FAILED(result))
- {
+ if (AP4_FAILED(result)) {
value = 0;
return result;
}
// convert bytes to value
value = buffer[0];
-
+
return AP4_SUCCESS;
}
@@ -330,23 +322,19 @@ AP4_ByteStream::ReadUI08(AP4_UI08& value)
AP4_Result
AP4_ByteStream::ReadString(char* buffer, AP4_Size size)
{
- if(buffer == NULL || size == 0)
- {
+ if (buffer == NULL || size == 0) {
return AP4_ERROR_INVALID_PARAMETERS;
}
AP4_Size bytes_read = 0;
- while(bytes_read < size - 1)
- {
+ while (bytes_read < size-1) {
AP4_Result result;
result = Read(&buffer[bytes_read], 1);
- if(AP4_FAILED(result))
- {
+ if (AP4_FAILED(result)) {
buffer[bytes_read] = '\0';
return result;
}
- if(buffer[bytes_read] == '\0')
- {
+ if (buffer[bytes_read] == '\0') {
// end of string
return AP4_SUCCESS;
}
@@ -365,31 +353,26 @@ AP4_Result
AP4_ByteStream::CopyTo(AP4_ByteStream& stream, AP4_LargeSize size)
{
unsigned char buffer[AP4_BYTE_STREAM_COPY_BUFFER_SIZE];
- while(size)
- {
+ while (size) {
AP4_Size bytes_read;
AP4_Size bytes_to_read;
AP4_Result result;
// decide how much to read
- if(size >= sizeof(buffer))
- {
+ if (size >= sizeof(buffer)) {
bytes_to_read = sizeof(buffer);
- }
- else
- {
+ } else {
bytes_to_read = (AP4_Size)size;
}
// read up to one buffer full
result = ReadPartial(buffer, bytes_to_read, bytes_read);
- if(AP4_FAILED(result)) return result;
+ if (AP4_FAILED(result)) return result;
// copy to destination
- if(bytes_read != 0)
- {
+ if (bytes_read != 0) {
result = stream.Write(buffer, bytes_read);
- if(AP4_FAILED(result)) return result;
+ if (AP4_FAILED(result)) return result;
}
// update the size
@@ -402,8 +385,8 @@ AP4_ByteStream::CopyTo(AP4_ByteStream& stream, AP4_LargeSize size)
/*----------------------------------------------------------------------
| AP4_SubStream::AP4_SubStream
+---------------------------------------------------------------------*/
-AP4_SubStream::AP4_SubStream(AP4_ByteStream& container,
- AP4_Position offset,
+AP4_SubStream::AP4_SubStream(AP4_ByteStream& container,
+ AP4_Position offset,
AP4_LargeSize size) :
m_Container(container),
m_Offset(offset),
@@ -425,44 +408,39 @@ AP4_SubStream::~AP4_SubStream()
/*----------------------------------------------------------------------
| AP4_SubStream::ReadPartial
+---------------------------------------------------------------------*/
-AP4_Result
-AP4_SubStream::ReadPartial(void* buffer,
- AP4_Size bytes_to_read,
+AP4_Result
+AP4_SubStream::ReadPartial(void* buffer,
+ AP4_Size bytes_to_read,
AP4_Size& bytes_read)
{
// default values
bytes_read = 0;
// shortcut
- if(bytes_to_read == 0)
- {
+ if (bytes_to_read == 0) {
return AP4_SUCCESS;
}
// clamp to range
- if(m_Position + bytes_to_read > m_Size)
- {
+ if (m_Position+bytes_to_read > m_Size) {
bytes_to_read = (AP4_Size)(m_Size - m_Position);
}
// check for end of substream
- if(bytes_to_read == 0)
- {
+ if (bytes_to_read == 0) {
return AP4_ERROR_EOS;
}
// seek inside container
AP4_Result result;
- result = m_Container.Seek(m_Offset + m_Position);
- if(AP4_FAILED(result))
- {
+ result = m_Container.Seek(m_Offset+m_Position);
+ if (AP4_FAILED(result)) {
return result;
}
// read from the container
result = m_Container.ReadPartial(buffer, bytes_to_read, bytes_read);
- if(AP4_SUCCEEDED(result))
- {
+ if (AP4_SUCCEEDED(result)) {
m_Position += bytes_read;
}
return result;
@@ -471,41 +449,37 @@ AP4_SubStream::ReadPartial(void* buffer,
/*----------------------------------------------------------------------
| AP4_SubStream::WritePartial
+---------------------------------------------------------------------*/
-AP4_Result
-AP4_SubStream::WritePartial(const void* buffer,
- AP4_Size bytes_to_write,
+AP4_Result
+AP4_SubStream::WritePartial(const void* buffer,
+ AP4_Size bytes_to_write,
AP4_Size& bytes_written)
{
// default values
bytes_written = 0;
// shortcut
- if(bytes_to_write == 0)
- {
+ if (bytes_to_write == 0) {
return AP4_SUCCESS;
}
// clamp to range
- if(m_Position + bytes_to_write > m_Size)
- {
+ if (m_Position+bytes_to_write > m_Size) {
bytes_to_write = (AP4_Size)(m_Size - m_Position);
}
// check for en of substream
- if(bytes_to_write == 0)
- {
+ if (bytes_to_write == 0) {
return AP4_ERROR_EOS;
}
// seek inside container
AP4_Result result;
- result = m_Container.Seek(m_Offset + m_Position);
- if(AP4_FAILED(result)) return result;
+ result = m_Container.Seek(m_Offset+m_Position);
+ if (AP4_FAILED(result)) return result;
// write to container
result = m_Container.WritePartial(buffer, bytes_to_write, bytes_written);
- if(AP4_SUCCEEDED(result))
- {
+ if (AP4_SUCCEEDED(result)) {
m_Position += bytes_written;
}
return result;
@@ -514,11 +488,11 @@ AP4_SubStream::WritePartial(const void* buffer,
/*----------------------------------------------------------------------
| AP4_SubStream::Seek
+---------------------------------------------------------------------*/
-AP4_Result
+AP4_Result
AP4_SubStream::Seek(AP4_Position position)
{
- if(position == m_Position) return AP4_SUCCESS;
- if(position > m_Size) return AP4_FAILURE;
+ if (position == m_Position) return AP4_SUCCESS;
+ if (position > m_Size) return AP4_FAILURE;
m_Position = position;
return AP4_SUCCESS;
}
@@ -538,8 +512,7 @@ AP4_SubStream::AddReference()
void
AP4_SubStream::Release()
{
- if(--m_ReferenceCount == 0)
- {
+ if (--m_ReferenceCount == 0) {
delete this;
}
}
@@ -584,8 +557,7 @@ AP4_MemoryByteStream::AP4_MemoryByteStream(AP4_DataBuffer& data_buffer) :
+---------------------------------------------------------------------*/
AP4_MemoryByteStream::~AP4_MemoryByteStream()
{
- if(m_BufferIsLocal)
- {
+ if (m_BufferIsLocal) {
delete m_Buffer;
}
}
@@ -593,34 +565,31 @@ AP4_MemoryByteStream::~AP4_MemoryByteStream()
/*----------------------------------------------------------------------
| AP4_MemoryByteStream::ReadPartial
+---------------------------------------------------------------------*/
-AP4_Result
-AP4_MemoryByteStream::ReadPartial(void* buffer,
- AP4_Size bytes_to_read,
+AP4_Result
+AP4_MemoryByteStream::ReadPartial(void* buffer,
+ AP4_Size bytes_to_read,
AP4_Size& bytes_read)
{
// default values
bytes_read = 0;
// shortcut
- if(bytes_to_read == 0)
- {
+ if (bytes_to_read == 0) {
return AP4_SUCCESS;
}
// clamp to range
- if(m_Position + bytes_to_read > m_Buffer->GetDataSize())
- {
+ if (m_Position+bytes_to_read > m_Buffer->GetDataSize()) {
bytes_to_read = (AP4_Size)(m_Buffer->GetDataSize() - m_Position);
}
// check for end of stream
- if(bytes_to_read == 0)
- {
+ if (bytes_to_read == 0) {
return AP4_ERROR_EOS;
}
// read from the memory
- AP4_CopyMemory(buffer, m_Buffer->GetData() + m_Position, bytes_to_read);
+ AP4_CopyMemory(buffer, m_Buffer->GetData()+m_Position, bytes_to_read);
m_Position += bytes_to_read;
bytes_read = bytes_to_read;
@@ -631,50 +600,43 @@ AP4_MemoryByteStream::ReadPartial(void* buffer,
/*----------------------------------------------------------------------
| AP4_MemoryByteStream::WritePartial
+---------------------------------------------------------------------*/
-AP4_Result
-AP4_MemoryByteStream::WritePartial(const void* buffer,
- AP4_Size bytes_to_write,
+AP4_Result
+AP4_MemoryByteStream::WritePartial(const void* buffer,
+ AP4_Size bytes_to_write,
AP4_Size& bytes_written)
{
// default values
bytes_written = 0;
// shortcut
- if(bytes_to_write == 0)
- {
+ if (bytes_to_write == 0) {
return AP4_SUCCESS;
}
// check that we don't exceed the max
- if(m_Position + bytes_to_write > (AP4_Position)AP4_MEMORY_BYTE_STREAM_MAX_SIZE)
- {
+ if (m_Position+bytes_to_write > (AP4_Position)AP4_MEMORY_BYTE_STREAM_MAX_SIZE) {
return AP4_ERROR_OUT_OF_RANGE;
}
// reserve space in the buffer
- AP4_Result result = m_Buffer->Reserve((AP4_Size)(m_Position + bytes_to_write));
- if(AP4_SUCCEEDED(result))
- {
- m_Buffer->SetDataSize((AP4_Size)(m_Position + bytes_to_write));
- }
- else
- {
+ AP4_Result result = m_Buffer->Reserve((AP4_Size)(m_Position+bytes_to_write));
+ if (AP4_SUCCEEDED(result)) {
+ m_Buffer->SetDataSize((AP4_Size)(m_Position+bytes_to_write));
+ } else {
// failed to reserve, most likely caused by a buffer that has
// external storage
- if(m_Position + bytes_to_write > m_Buffer->GetDataSize())
- {
+ if (m_Position+bytes_to_write > m_Buffer->GetDataSize()) {
bytes_to_write = (AP4_Size)(m_Buffer->GetDataSize() - m_Position);
}
- }
+ }
// check for en of stream
- if(bytes_to_write == 0)
- {
+ if (bytes_to_write == 0) {
return AP4_ERROR_EOS;
}
// write to memory
- AP4_CopyMemory((void*)(m_Buffer->UseData() + m_Position), buffer, bytes_to_write);
+ AP4_CopyMemory((void*)(m_Buffer->UseData()+m_Position), buffer, bytes_to_write);
m_Position += bytes_to_write;
bytes_written = bytes_to_write;
@@ -685,10 +647,10 @@ AP4_MemoryByteStream::WritePartial(const void* buffer,
/*----------------------------------------------------------------------
| AP4_MemoryByteStream::Seek
+---------------------------------------------------------------------*/
-AP4_Result
+AP4_Result
AP4_MemoryByteStream::Seek(AP4_Position position)
{
- if(position > m_Buffer->GetDataSize()) return AP4_FAILURE;
+ if (position > m_Buffer->GetDataSize()) return AP4_FAILURE;
m_Position = position;
return AP4_SUCCESS;
}
@@ -708,8 +670,7 @@ AP4_MemoryByteStream::AddReference()
void
AP4_MemoryByteStream::Release()
{
- if(--m_ReferenceCount == 0)
- {
+ if (--m_ReferenceCount == 0) {
delete this;
}
}
@@ -717,9 +678,9 @@ AP4_MemoryByteStream::Release()
/*----------------------------------------------------------------------
| AP4_BufferedInputStream::AP4_BufferedInputStream
+---------------------------------------------------------------------*/
-AP4_BufferedInputStream::AP4_BufferedInputStream(AP4_ByteStream& source,
- AP4_Size buffer_size,
- AP4_Size seek_as_read_threshold) :
+AP4_BufferedInputStream::AP4_BufferedInputStream(AP4_ByteStream& source,
+ AP4_Size buffer_size,
+ AP4_Size seek_as_read_threshold) :
m_Buffer(buffer_size),
m_BufferPosition(0),
m_Source(source),
@@ -733,77 +694,73 @@ AP4_BufferedInputStream::AP4_BufferedInputStream(AP4_ByteStream& source,
/*----------------------------------------------------------------------
| AP4_BufferedInputStream::Refill
+---------------------------------------------------------------------*/
-AP4_Result
+AP4_Result
AP4_BufferedInputStream::Refill()
{
m_BufferPosition = 0;
AP4_Size bytes_read = 0;
- AP4_Result result = m_Source.ReadPartial(m_Buffer.UseData(),
- m_Buffer.GetBufferSize(),
- bytes_read);
- if(AP4_FAILED(result))
- {
+ AP4_Result result = m_Source.ReadPartial(m_Buffer.UseData(),
+ m_Buffer.GetBufferSize(),
+ bytes_read);
+ if (AP4_FAILED(result)) {
m_Buffer.SetDataSize(0);
return result;
}
assert(bytes_read);
m_Buffer.SetDataSize(bytes_read);
m_SourcePosition += bytes_read;
-
+
return AP4_SUCCESS;
-}
+}
/*----------------------------------------------------------------------
| AP4_BufferedInputStream::ReadPartial
+---------------------------------------------------------------------*/
-AP4_Result
-AP4_BufferedInputStream::ReadPartial(void* buffer,
- AP4_Size bytes_to_read,
+AP4_Result
+AP4_BufferedInputStream::ReadPartial(void* buffer,
+ AP4_Size bytes_to_read,
AP4_Size& bytes_read)
{
// check for shortcut
- if(bytes_to_read == 0)
- {
+ if (bytes_to_read == 0) {
bytes_read = 0;
return AP4_SUCCESS;
}
-
+
// compute how much data is available in the buffer
assert(m_BufferPosition <= m_Buffer.GetDataSize());
- AP4_Size available = m_Buffer.GetDataSize() - m_BufferPosition;
-
+ AP4_Size available = m_Buffer.GetDataSize()-m_BufferPosition;
+
// refill the buffer if it is empty
- if(available == 0)
- {
+ if (available == 0) {
AP4_Result result = Refill();
- if(AP4_FAILED(result))
- {
+ if (AP4_FAILED(result)) {
bytes_read = 0;
return result;
}
assert(m_BufferPosition == 0);
assert(m_Buffer.GetDataSize() != 0);
- available = m_Buffer.GetDataSize() - m_BufferPosition;
+ available = m_Buffer.GetDataSize()-m_BufferPosition;
}
-
+
// clamp the number of bytes to read to what's available
- if(bytes_to_read > available) bytes_to_read = available;
+ if (bytes_to_read > available) bytes_to_read = available;
bytes_read = bytes_to_read;
-
+
// copy the buffered data
- AP4_CopyMemory(buffer, m_Buffer.GetData() + m_BufferPosition, bytes_to_read);
+ AP4_CopyMemory(buffer, m_Buffer.GetData()+m_BufferPosition, bytes_to_read);
m_BufferPosition += bytes_to_read;
assert(m_BufferPosition <= m_Buffer.GetDataSize());
-
+
return AP4_SUCCESS;
}
/*----------------------------------------------------------------------
| AP4_BufferedInputStream::WritePartial
+---------------------------------------------------------------------*/
-AP4_Result
-AP4_BufferedInputStream::WritePartial(const void* /*buffer*/,
- AP4_Size /*bytes_to_write*/,
+AP4_Result
+AP4_BufferedInputStream::WritePartial(const void* /*buffer*/,
+ AP4_Size /*bytes_to_write*/,
AP4_Size& /*bytes_written*/)
{
return AP4_ERROR_NOT_SUPPORTED;
@@ -812,30 +769,26 @@ AP4_BufferedInputStream::WritePartial(const void* /*buffer*/,
/*----------------------------------------------------------------------
| AP4_BufferedInputStream::Seek
+---------------------------------------------------------------------*/
-AP4_Result
+AP4_Result
AP4_BufferedInputStream::Seek(AP4_Position position)
{
assert(m_SourcePosition >= m_Buffer.GetDataSize());
assert(m_BufferPosition <= m_Buffer.GetDataSize());
- if(position < m_SourcePosition - m_Buffer.GetDataSize() ||
- position > m_SourcePosition)
- {
+ if (position < m_SourcePosition-m_Buffer.GetDataSize() ||
+ position > m_SourcePosition) {
// out of buffer
m_BufferPosition = 0;
m_Buffer.SetDataSize(0);
-
+
// seek in the source
- if(position > m_SourcePosition && (position - m_SourcePosition <= m_SeekAsReadThreshold))
- {
+ if (position > m_SourcePosition && (position-m_SourcePosition <= m_SeekAsReadThreshold)) {
char* discard = new char[4096];
- AP4_Size to_skip = (AP4_Size)(position - m_SourcePosition);
- while(to_skip)
- {
+ AP4_Size to_skip = (AP4_Size)(position-m_SourcePosition);
+ while (to_skip) {
AP4_Size chunk = 4096;
- if(chunk > to_skip) chunk = to_skip;
+ if (chunk > to_skip) chunk = to_skip;
AP4_Result result = m_Source.Read(discard, chunk);
- if(AP4_FAILED(result))
- {
+ if (AP4_FAILED(result)) {
delete[] discard;
return result;
}
@@ -844,29 +797,27 @@ AP4_BufferedInputStream::Seek(AP4_Position position)
}
delete[] discard;
return AP4_SUCCESS;
- }
- else
- {
+ } else {
m_SourcePosition = position;
return m_Source.Seek(position);
}
}
-
+
// compute the buffer position
- m_BufferPosition = (AP4_Size)(position - (m_SourcePosition - m_Buffer.GetDataSize()));
-
+ m_BufferPosition = (AP4_Size)(position-(m_SourcePosition-m_Buffer.GetDataSize()));
+
return AP4_SUCCESS;
}
/*----------------------------------------------------------------------
| AP4_BufferedInputStream::Tell
+---------------------------------------------------------------------*/
-AP4_Result
+AP4_Result
AP4_BufferedInputStream::Tell(AP4_Position& position)
{
assert(m_SourcePosition >= m_Buffer.GetDataSize());
assert(m_BufferPosition <= m_Buffer.GetDataSize());
- position = m_SourcePosition - m_Buffer.GetDataSize() + m_BufferPosition;
+ position = m_SourcePosition-m_Buffer.GetDataSize()+m_BufferPosition;
return AP4_SUCCESS;
}
@@ -885,8 +836,7 @@ AP4_BufferedInputStream::AddReference()
void
AP4_BufferedInputStream::Release()
{
- if(--m_ReferenceCount == 0)
- {
+ if (--m_ReferenceCount == 0) {
delete this;
}
}
diff --git a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4ByteStream.h b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4ByteStream.h
index 2d69d54d7..3eaf2d803 100644
--- a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4ByteStream.h
+++ b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4ByteStream.h
@@ -42,10 +42,10 @@
+---------------------------------------------------------------------*/
class AP4_ByteStream : public AP4_Referenceable
{
-public:
+ public:
// methods
- virtual AP4_Result ReadPartial(void* buffer,
- AP4_Size bytes_to_read,
+ virtual AP4_Result ReadPartial(void* buffer,
+ AP4_Size bytes_to_read,
AP4_Size& bytes_read) = 0;
AP4_Result Read(void* buffer, AP4_Size bytes_to_read);
AP4_Result ReadDouble(double& value);
@@ -55,8 +55,8 @@ public:
AP4_Result ReadUI16(AP4_UI16& value);
AP4_Result ReadUI08(AP4_UI08& value);
AP4_Result ReadString(char* buffer, AP4_Size size);
- virtual AP4_Result WritePartial(const void* buffer,
- AP4_Size bytes_to_write,
+ virtual AP4_Result WritePartial(const void* buffer,
+ AP4_Size bytes_to_write,
AP4_Size& bytes_written) = 0;
AP4_Result Write(const void* buffer, AP4_Size bytes_to_write);
AP4_Result WriteString(const char* string_buffer);
@@ -70,10 +70,7 @@ public:
virtual AP4_Result Tell(AP4_Position& position) = 0;
virtual AP4_Result GetSize(AP4_LargeSize& size) = 0;
virtual AP4_Result CopyTo(AP4_ByteStream& stream, AP4_LargeSize size);
- virtual AP4_Result Flush()
- {
- return AP4_SUCCESS;
- }
+ virtual AP4_Result Flush() { return AP4_SUCCESS; }
};
/*----------------------------------------------------------------------
@@ -81,26 +78,24 @@ public:
+---------------------------------------------------------------------*/
class AP4_SubStream : public AP4_ByteStream
{
-public:
- AP4_SubStream(AP4_ByteStream& container,
- AP4_Position position,
+ public:
+ AP4_SubStream(AP4_ByteStream& container,
+ AP4_Position position,
AP4_LargeSize size);
// AP4_ByteStream methods
- AP4_Result ReadPartial(void* buffer,
- AP4_Size bytes_to_read,
+ AP4_Result ReadPartial(void* buffer,
+ AP4_Size bytes_to_read,
AP4_Size& bytes_read);
- AP4_Result WritePartial(const void* buffer,
- AP4_Size bytes_to_write,
+ AP4_Result WritePartial(const void* buffer,
+ AP4_Size bytes_to_write,
AP4_Size& bytes_written);
AP4_Result Seek(AP4_Position position);
- AP4_Result Tell(AP4_Position& position)
- {
+ AP4_Result Tell(AP4_Position& position) {
position = m_Position;
return AP4_SUCCESS;
}
- AP4_Result GetSize(AP4_LargeSize& size)
- {
+ AP4_Result GetSize(AP4_LargeSize& size) {
size = m_Size;
return AP4_SUCCESS;
}
@@ -109,10 +104,10 @@ public:
void AddReference();
void Release();
-protected:
+ protected:
virtual ~AP4_SubStream();
-private:
+ private:
AP4_ByteStream& m_Container;
AP4_Position m_Offset;
AP4_LargeSize m_Size;
@@ -131,20 +126,18 @@ public:
AP4_MemoryByteStream(AP4_DataBuffer& data_buffer); // data is read/written from/to supplied buffer
// AP4_ByteStream methods
- AP4_Result ReadPartial(void* buffer,
- AP4_Size bytes_to_read,
+ AP4_Result ReadPartial(void* buffer,
+ AP4_Size bytes_to_read,
AP4_Size& bytes_read);
- AP4_Result WritePartial(const void* buffer,
- AP4_Size bytes_to_write,
+ AP4_Result WritePartial(const void* buffer,
+ AP4_Size bytes_to_write,
AP4_Size& bytes_written);
AP4_Result Seek(AP4_Position position);
- AP4_Result Tell(AP4_Position& position)
- {
+ AP4_Result Tell(AP4_Position& position) {
position = m_Position;
return AP4_SUCCESS;
}
- AP4_Result GetSize(AP4_LargeSize& size)
- {
+ AP4_Result GetSize(AP4_LargeSize& size) {
size = m_Buffer->GetDataSize();
return AP4_SUCCESS;
}
@@ -154,18 +147,9 @@ public:
void Release();
// methods
- const AP4_UI08* GetData()
- {
- return m_Buffer->GetData();
- }
- AP4_UI08* UseData()
- {
- return m_Buffer->UseData();
- }
- AP4_Size GetDataSize()
- {
- return m_Buffer->GetDataSize();
- }
+ const AP4_UI08* GetData() { return m_Buffer->GetData(); }
+ AP4_UI08* UseData() { return m_Buffer->UseData(); }
+ AP4_Size GetDataSize() { return m_Buffer->GetDataSize(); }
protected:
virtual ~AP4_MemoryByteStream();
@@ -183,35 +167,29 @@ private:
class AP4_BufferedInputStream : public AP4_ByteStream
{
public:
- AP4_BufferedInputStream(AP4_ByteStream& source,
- AP4_Size buffer_size = 4096,
- AP4_Size seek_as_read_threshold = 1024 * 128);
+ AP4_BufferedInputStream(AP4_ByteStream& source,
+ AP4_Size buffer_size=4096,
+ AP4_Size seek_as_read_threshold=1024*128);
// AP4_ByteStream methods
- AP4_Result ReadPartial(void* buffer,
- AP4_Size bytes_to_read,
+ AP4_Result ReadPartial(void* buffer,
+ AP4_Size bytes_to_read,
AP4_Size& bytes_read);
- AP4_Result WritePartial(const void* buffer,
- AP4_Size bytes_to_write,
+ AP4_Result WritePartial(const void* buffer,
+ AP4_Size bytes_to_write,
AP4_Size& bytes_written);
AP4_Result Seek(AP4_Position position);
AP4_Result Tell(AP4_Position& position);
- AP4_Result GetSize(AP4_LargeSize& size)
- {
- return m_Source.GetSize(size);
- }
+ AP4_Result GetSize(AP4_LargeSize& size) { return m_Source.GetSize(size); }
// AP4_Referenceable methods
void AddReference();
void Release();
protected:
- ~AP4_BufferedInputStream()
- {
- m_Source.Release();
- }
+ ~AP4_BufferedInputStream() { m_Source.Release(); }
AP4_Result Refill();
-
+
private:
AP4_DataBuffer m_Buffer;
AP4_Size m_BufferPosition;
diff --git a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4ChplAtom.cpp b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4ChplAtom.cpp
index 87864cf2c..2c5c195a3 100644
--- a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4ChplAtom.cpp
+++ b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4ChplAtom.cpp
@@ -38,34 +38,34 @@
AP4_ChplAtom::AP4_ChplAtom(AP4_UI32 size,
AP4_ByteStream& stream)
- : AP4_Atom(AP4_ATOM_TYPE_CHPL, size)
+ : AP4_Atom(AP4_ATOM_TYPE_CHPL, size)
{
- size -= AP4_FULL_ATOM_HEADER_SIZE;
+ size -= AP4_FULL_ATOM_HEADER_SIZE;
- stream.ReadUI32(m_Reserved);
+ stream.ReadUI32(m_Reserved);
- AP4_UI08 cnt = 0;
- stream.ReadUI08(cnt);
+ AP4_UI08 cnt = 0;
+ stream.ReadUI08(cnt);
- size -= 5;
+ size -= 5;
- while(size > 0 && cnt-- > 0)
- {
- AP4_Chapter chapter;
+ while(size > 0 && cnt-- > 0)
+ {
+ AP4_Chapter chapter;
- // time
- stream.ReadUI64(chapter.Time);
+ // time
+ stream.ReadUI64(chapter.Time);
- // name
- AP4_UI08 len = 0;
- char buff[256];
- stream.ReadUI08(len);
- stream.Read(buff, len);
- buff[len] = 0;
- chapter.Name = buff;
+ // name
+ AP4_UI08 len = 0;
+ char buff[256];
+ stream.ReadUI08(len);
+ stream.Read(buff, len);
+ buff[len] = 0;
+ chapter.Name = buff;
- m_Chapters.Append(chapter);
+ m_Chapters.Append(chapter);
- size -= 8 + 1 + len;
- }
+ size -= 8+1+len;
+ }
}
diff --git a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4ChplAtom.h b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4ChplAtom.h
index fad2ef2a2..d1fa4327b 100644
--- a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4ChplAtom.h
+++ b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4ChplAtom.h
@@ -43,30 +43,20 @@
class AP4_ChplAtom : public AP4_Atom
{
public:
- AP4_ChplAtom(AP4_UI32 size,
+ AP4_ChplAtom(AP4_UI32 size,
AP4_ByteStream& stream);
- AP4_Result WriteFields(AP4_ByteStream& stream)
- {
- return AP4_FAILURE;
- }
+ AP4_Result WriteFields(AP4_ByteStream& stream) { return AP4_FAILURE; }
- struct AP4_Chapter
- {
- AP4_UI64 Time;
- AP4_String Name;
- };
+ struct AP4_Chapter {AP4_UI64 Time; AP4_String Name;};
- AP4_Array<AP4_Chapter>& GetChapters()
- {
- return m_Chapters;
- }
+ AP4_Array<AP4_Chapter>& GetChapters() { return m_Chapters; }
private:
- // members
- AP4_UI32 m_Reserved;
- AP4_Array<AP4_Chapter> m_Chapters;
+ // members
+ AP4_UI32 m_Reserved;
+ AP4_Array<AP4_Chapter> m_Chapters;
};
#endif // _AP4_CHPL_ATOM_H_
diff --git a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4CmvdAtom.cpp b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4CmvdAtom.cpp
index 539587bcc..8b4760524 100644
--- a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4CmvdAtom.cpp
+++ b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4CmvdAtom.cpp
@@ -1,6 +1,6 @@
/*****************************************************************
|
-| AP4 - cmvd Atoms
+| AP4 - cmvd Atoms
|
| Copyright 2002 Gilles Boccon-Gibod
|
@@ -34,10 +34,10 @@
#include "Ap4AtomFactory.h"
#include "Ap4ContainerAtom.h"
-AP4_CmvdAtom*
-AP4_CmvdAtom::Create(AP4_Size size, AP4_ByteStream& stream, AP4_AtomFactory& atom_factory)
-{
- return new AP4_CmvdAtom(size, stream, atom_factory);
+AP4_CmvdAtom*
+AP4_CmvdAtom::Create(AP4_Size size, AP4_ByteStream& stream, AP4_AtomFactory& atom_factory)
+{
+ return new AP4_CmvdAtom(size, stream, atom_factory);
}
/*----------------------------------------------------------------------
@@ -48,26 +48,26 @@ AP4_CmvdAtom::AP4_CmvdAtom(AP4_Size size,
AP4_AtomFactory& atom_factory) :
AP4_ContainerAtom(AP4_ATOM_TYPE_CMVD)
{
- size -= AP4_ATOM_HEADER_SIZE;
+ size -= AP4_ATOM_HEADER_SIZE;
stream.ReadUI32(m_MovieResourceSize);
- size -= 4;
+ size -= 4;
- m_Data.SetDataSize(size);
- stream.Read(m_Data.UseData(), size);
+ m_Data.SetDataSize(size);
+ stream.Read(m_Data.UseData(), size);
- /*
- // read children
- AP4_Size bytes_available = size-AP4_FULL_ATOM_HEADER_SIZE-4;
- while (entry_count--) {
- AP4_Atom* atom;
- while (AP4_SUCCEEDED(atom_factory.CreateAtomFromStream(stream,
- bytes_available,
- atom,
- this))) {
- m_Children.Add(atom);
- }
+/*
+ // read children
+ AP4_Size bytes_available = size-AP4_FULL_ATOM_HEADER_SIZE-4;
+ while (entry_count--) {
+ AP4_Atom* atom;
+ while (AP4_SUCCEEDED(atom_factory.CreateAtomFromStream(stream,
+ bytes_available,
+ atom,
+ this))) {
+ m_Children.Add(atom);
}
- */
+ }
+*/
}
diff --git a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4CmvdAtom.h b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4CmvdAtom.h
index 9d768fc88..51e2ca843 100644
--- a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4CmvdAtom.h
+++ b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4CmvdAtom.h
@@ -1,6 +1,6 @@
/*****************************************************************
|
-| AP4 - cmvd Atoms
+| AP4 - cmvd Atoms
|
| Copyright 2002 Gilles Boccon-Gibod
|
@@ -46,31 +46,22 @@
class AP4_CmvdAtom : public AP4_ContainerAtom
{
public:
- // class methods
- static AP4_CmvdAtom* Create(AP4_Size size, AP4_ByteStream& stream, AP4_AtomFactory& atom_factory);
+ // class methods
+ static AP4_CmvdAtom* Create(AP4_Size size, AP4_ByteStream& stream, AP4_AtomFactory& atom_factory);
- // methods
+ // methods
AP4_CmvdAtom(AP4_Size size,
AP4_ByteStream& stream,
AP4_AtomFactory& atom_factory);
- virtual AP4_Result WriteFields(AP4_ByteStream& stream)
- {
- return AP4_FAILURE;
- }
+ virtual AP4_Result WriteFields(AP4_ByteStream& stream) { return AP4_FAILURE; }
- AP4_UI32 GetMovieResourceSize() const
- {
- return m_MovieResourceSize;
- }
- const AP4_DataBuffer& GetDataBuffer()
- {
- return m_Data;
- }
+ AP4_UI32 GetMovieResourceSize() const { return m_MovieResourceSize; }
+ const AP4_DataBuffer& GetDataBuffer() { return m_Data; }
private:
- AP4_UI32 m_MovieResourceSize;
- AP4_DataBuffer m_Data;
+ AP4_UI32 m_MovieResourceSize;
+ AP4_DataBuffer m_Data;
};
#endif // _AP4_CMVD_ATOM_H_
diff --git a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4Co64Atom.cpp b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4Co64Atom.cpp
index df097449c..3dea98337 100644
--- a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4Co64Atom.cpp
+++ b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4Co64Atom.cpp
@@ -1,6 +1,6 @@
/*****************************************************************
|
-| AP4 - co64 Atoms
+| AP4 - co64 Atoms
|
| Copyright 2002-2008 Axiomatic Systems, LLC
|
@@ -46,8 +46,8 @@ AP4_Co64Atom::Create(AP4_Size size, AP4_ByteStream& stream)
{
AP4_UI32 version;
AP4_UI32 flags;
- if(AP4_FAILED(AP4_Atom::ReadFullHeader(stream, version, flags))) return NULL;
- if(version != 0) return NULL;
+ if (AP4_FAILED(AP4_Atom::ReadFullHeader(stream, version, flags))) return NULL;
+ if (version != 0) return NULL;
return new AP4_Co64Atom(size, version, flags, stream);
}
@@ -55,32 +55,30 @@ AP4_Co64Atom::Create(AP4_Size size, AP4_ByteStream& stream)
| AP4_Co64Atom::AP4_Co64Atom
+---------------------------------------------------------------------*/
AP4_Co64Atom::AP4_Co64Atom(AP4_UI64* entries, AP4_UI32 entry_count) :
- AP4_Atom(AP4_ATOM_TYPE_CO64,
- AP4_FULL_ATOM_HEADER_SIZE + 4 + entry_count * 8,
- 0, 0),
- m_Entries(new AP4_UI64[entry_count]),
- m_EntryCount(entry_count)
+AP4_Atom(AP4_ATOM_TYPE_CO64,
+ AP4_FULL_ATOM_HEADER_SIZE+4+entry_count*8,
+ 0, 0),
+ m_Entries(new AP4_UI64[entry_count]),
+ m_EntryCount(entry_count)
{
- AP4_CopyMemory(m_Entries, entries, m_EntryCount * 8);
+ AP4_CopyMemory(m_Entries, entries, m_EntryCount*8);
}
/*----------------------------------------------------------------------
| AP4_Co64Atom::AP4_Co64Atom
+---------------------------------------------------------------------*/
-AP4_Co64Atom::AP4_Co64Atom(AP4_UI32 size,
+AP4_Co64Atom::AP4_Co64Atom(AP4_UI32 size,
AP4_UI32 version,
AP4_UI32 flags,
AP4_ByteStream& stream) :
AP4_Atom(AP4_ATOM_TYPE_CO64, size, version, flags)
{
stream.ReadUI32(m_EntryCount);
- if(m_EntryCount > (size - AP4_FULL_ATOM_HEADER_SIZE - 4) / 8)
- {
- m_EntryCount = (size - AP4_FULL_ATOM_HEADER_SIZE - 4) / 8;
+ if (m_EntryCount > (size-AP4_FULL_ATOM_HEADER_SIZE-4)/8) {
+ m_EntryCount = (size-AP4_FULL_ATOM_HEADER_SIZE-4)/8;
}
m_Entries = new AP4_UI64[m_EntryCount];
- for(AP4_Ordinal i = 0; i < m_EntryCount; i++)
- {
+ for (AP4_Ordinal i=0; i<m_EntryCount; i++) {
stream.ReadUI64(m_Entries[i]);
}
}
@@ -100,8 +98,7 @@ AP4_Result
AP4_Co64Atom::GetChunkOffset(AP4_Ordinal chunk, AP4_UI64& chunk_offset)
{
// check the bounds
- if(chunk > m_EntryCount || chunk == 0)
- {
+ if (chunk > m_EntryCount || chunk == 0) {
return AP4_ERROR_OUT_OF_RANGE;
}
@@ -118,8 +115,7 @@ AP4_Result
AP4_Co64Atom::SetChunkOffset(AP4_Ordinal chunk, AP4_UI64 chunk_offset)
{
// check the bounds
- if(chunk > m_EntryCount || chunk == 0)
- {
+ if (chunk > m_EntryCount || chunk == 0) {
return AP4_ERROR_OUT_OF_RANGE;
}
@@ -135,8 +131,7 @@ AP4_Co64Atom::SetChunkOffset(AP4_Ordinal chunk, AP4_UI64 chunk_offset)
AP4_Result
AP4_Co64Atom::AdjustChunkOffsets(AP4_SI64 delta)
{
- for(AP4_Ordinal i = 0; i < m_EntryCount; i++)
- {
+ for (AP4_Ordinal i=0; i<m_EntryCount; i++) {
m_Entries[i] += delta;
}
@@ -153,13 +148,12 @@ AP4_Co64Atom::WriteFields(AP4_ByteStream& stream)
// entry count
result = stream.WriteUI32(m_EntryCount);
- if(AP4_FAILED(result)) return result;
+ if (AP4_FAILED(result)) return result;
// entries
- for(AP4_Ordinal i = 0; i < m_EntryCount; i++)
- {
+ for (AP4_Ordinal i=0; i<m_EntryCount; i++) {
result = stream.WriteUI64(m_Entries[i]);
- if(AP4_FAILED(result)) return result;
+ if (AP4_FAILED(result)) return result;
}
return result;
@@ -172,11 +166,9 @@ AP4_Result
AP4_Co64Atom::InspectFields(AP4_AtomInspector& inspector)
{
inspector.AddField("entry_count", m_EntryCount);
- if(inspector.GetVerbosity() >= 1)
- {
+ if (inspector.GetVerbosity() >= 1) {
char header[32];
- for(AP4_Ordinal i = 0; i < m_EntryCount; i++)
- {
+ for (AP4_Ordinal i=0; i<m_EntryCount; i++) {
AP4_FormatString(header, sizeof(header), "entry %8d", i);
inspector.AddField(header, m_Entries[i]);
}
diff --git a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4Co64Atom.h b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4Co64Atom.h
index eb79a09e5..bdfeb4736 100644
--- a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4Co64Atom.h
+++ b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4Co64Atom.h
@@ -1,6 +1,6 @@
/*****************************************************************
|
-| AP4 - co64 Atoms
+| AP4 - co64 Atoms
|
| Copyright 2002-2008 Axiomatic Systems, LLC
|
@@ -51,21 +51,15 @@ public:
~AP4_Co64Atom();
virtual AP4_Result InspectFields(AP4_AtomInspector& inspector);
virtual AP4_Result WriteFields(AP4_ByteStream& stream);
- AP4_Cardinal GetChunkCount()
- {
- return m_EntryCount;
- }
- AP4_UI64* GetChunkOffsets()
- {
- return m_Entries;
- }
+ AP4_Cardinal GetChunkCount() { return m_EntryCount; }
+ AP4_UI64* GetChunkOffsets() { return m_Entries; }
AP4_Result GetChunkOffset(AP4_Ordinal chunk, AP4_UI64& chunk_offset);
AP4_Result SetChunkOffset(AP4_Ordinal chunk, AP4_UI64 chunk_offset);
AP4_Result AdjustChunkOffsets(AP4_SI64 delta);
private:
// methods
- AP4_Co64Atom(AP4_UI32 size,
+ AP4_Co64Atom(AP4_UI32 size,
AP4_UI32 version,
AP4_UI32 flags,
AP4_ByteStream& stream);
diff --git a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4Command.cpp b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4Command.cpp
index 0e9a4b0c8..1dc6958f5 100644
--- a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4Command.cpp
+++ b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4Command.cpp
@@ -66,7 +66,7 @@ AP4_UnknownCommand::AP4_UnknownCommand(AP4_ByteStream& stream,
AP4_Command(tag, header_size, payload_size)
{
m_Data.SetDataSize(payload_size);
- stream.Read(m_Data.UseData(), payload_size);
+ stream.Read(m_Data.UseData(), payload_size);
}
/*----------------------------------------------------------------------
diff --git a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4Command.h b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4Command.h
index aff51bd2f..50cf8d736 100644
--- a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4Command.h
+++ b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4Command.h
@@ -1,6 +1,6 @@
/*****************************************************************
|
-| AP4 - Commands
+| AP4 - Commands
|
| Copyright 2002-2008 Axiomatic Systems, LLC
|
@@ -52,8 +52,8 @@ const AP4_UI08 AP4_COMMAND_TAG_OBJECT_DESCRIPTOR_EXECUTE = 0x08;
+---------------------------------------------------------------------*/
class AP4_Command : public AP4_Expandable
{
-public:
- AP4_IMPLEMENT_DYNAMIC_CAST(AP4_Command)
+ public:
+ AP4_IMPLEMENT_DYNAMIC_CAST(AP4_Command)
// constructor
AP4_Command(AP4_UI08 tag, AP4_Size header_size, AP4_Size payload_size) :
@@ -63,10 +63,7 @@ public:
virtual AP4_Result Inspect(AP4_AtomInspector& inspector);
// methods
- AP4_UI08 GetTag()
- {
- return (AP4_UI08)m_ClassId;
- }
+ AP4_UI08 GetTag() { return (AP4_UI08)m_ClassId; }
};
/*----------------------------------------------------------------------
@@ -76,11 +73,11 @@ class AP4_UnknownCommand : public AP4_Command
{
public:
// contrusctor
- AP4_UnknownCommand(AP4_ByteStream& stream,
+ AP4_UnknownCommand(AP4_ByteStream& stream,
AP4_UI08 tag,
AP4_Size header_size,
AP4_Size payload_size);
-
+
// AP4_Expandable methods
virtual AP4_Result WriteFields(AP4_ByteStream& stream);
diff --git a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4CommandFactory.cpp b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4CommandFactory.cpp
index 1b66191fc..f41312bda 100644
--- a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4CommandFactory.cpp
+++ b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4CommandFactory.cpp
@@ -38,8 +38,8 @@
| AP4_CommandFactory::CreateCommandFromStream
+---------------------------------------------------------------------*/
AP4_Result
-AP4_CommandFactory::CreateCommandFromStream(AP4_ByteStream& stream,
- AP4_Command*& command)
+AP4_CommandFactory::CreateCommandFromStream(AP4_ByteStream& stream,
+ AP4_Command*& command)
{
AP4_Result result;
@@ -53,45 +53,40 @@ AP4_CommandFactory::CreateCommandFromStream(AP4_ByteStream& stream,
// read descriptor tag
unsigned char tag;
result = stream.ReadUI08(tag);
- if(AP4_FAILED(result))
- {
+ if (AP4_FAILED(result)) {
stream.Seek(offset);
return result;
}
-
+
// read descriptor size
unsigned long payload_size = 0;
unsigned int header_size = 1;
unsigned int max = 4;
unsigned char ext = 0;
- do
- {
+ do {
header_size++;
result = stream.ReadUI08(ext);
- if(AP4_FAILED(result))
- {
+ if (AP4_FAILED(result)) {
stream.Seek(offset);
return result;
}
- payload_size = (payload_size << 7) + (ext & 0x7F);
- }
- while(--max && (ext & 0x80));
+ payload_size = (payload_size<<7) + (ext&0x7F);
+ } while (--max && (ext&0x80));
// create the command
- switch(tag)
- {
- case AP4_COMMAND_TAG_OBJECT_DESCRIPTOR_UPDATE:
- case AP4_COMMAND_TAG_IPMP_DESCRIPTOR_UPDATE:
+ switch (tag) {
+ case AP4_COMMAND_TAG_OBJECT_DESCRIPTOR_UPDATE:
+ case AP4_COMMAND_TAG_IPMP_DESCRIPTOR_UPDATE:
command = new AP4_DescriptorUpdateCommand(stream, tag, header_size, payload_size);
break;
- default:
+ default:
command = new AP4_UnknownCommand(stream, tag, header_size, payload_size);
break;
}
// skip to the end of the descriptor
- stream.Seek(offset + header_size + payload_size);
+ stream.Seek(offset+header_size+payload_size);
return AP4_SUCCESS;
}
diff --git a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4CommandFactory.h b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4CommandFactory.h
index 34bd347a2..133b35020 100644
--- a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4CommandFactory.h
+++ b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4CommandFactory.h
@@ -43,12 +43,12 @@ class AP4_ByteStream;
/*----------------------------------------------------------------------
| AP4_CommandFactory
+---------------------------------------------------------------------*/
-class AP4_CommandFactory
+class AP4_CommandFactory
{
-public:
+ public:
// class methods
static AP4_Result CreateCommandFromStream(AP4_ByteStream& stream,
- AP4_Command*& command);
+ AP4_Command*& command);
};
#endif // _AP4_COMMAND_FACTORY_H_
diff --git a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4ContainerAtom.cpp b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4ContainerAtom.cpp
index 7677a2005..deee12653 100644
--- a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4ContainerAtom.cpp
+++ b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4ContainerAtom.cpp
@@ -44,47 +44,41 @@ AP4_DEFINE_DYNAMIC_CAST_ANCHOR(AP4_ContainerAtom)
| AP4_ContainerAtom::AP4_ContainerAtom
+---------------------------------------------------------------------*/
AP4_ContainerAtom*
-AP4_ContainerAtom::Create(Type type,
+AP4_ContainerAtom::Create(Type type,
AP4_UI64 size,
bool is_full,
bool force_64,
AP4_ByteStream& stream,
AP4_AtomFactory& atom_factory)
{
- if(is_full)
- {
+ if (is_full) {
AP4_UI32 version;
AP4_UI32 flags;
- if(AP4_FAILED(AP4_Atom::ReadFullHeader(stream, version, flags))) return NULL;
-
+ if (AP4_FAILED(AP4_Atom::ReadFullHeader(stream, version, flags))) return NULL;
+
// special case for 'meta' atoms, because Apple sometimes creates them as
// regular (non-full) atoms. This is bogus, but we can try to detect it
- if(type == AP4_ATOM_TYPE_META)
- {
- AP4_UI32 phantom_size = (version << 24) | flags;
- if(phantom_size >= 8 && size >= 16)
- {
+ if (type == AP4_ATOM_TYPE_META) {
+ AP4_UI32 phantom_size = (version<<24)|flags;
+ if (phantom_size >= 8 && size >= 16) {
// version+flags looks like a size. read the next 4 bytes just
// to be sure it is a hdlr atom
AP4_UI32 peek;
- if(AP4_FAILED(stream.ReadUI32(peek))) return NULL;
- if(peek == AP4_ATOM_TYPE_HDLR)
- {
+ if (AP4_FAILED(stream.ReadUI32(peek))) return NULL;
+ if (peek == AP4_ATOM_TYPE_HDLR) {
// rewind the stream by 8 bytes
AP4_Position position;
stream.Tell(position);
- stream.Seek(position - 8);
-
+ stream.Seek(position-8);
+
// create a non-full container
return new AP4_ContainerAtom(type, size, force_64, stream, atom_factory);
}
}
}
-
+
return new AP4_ContainerAtom(type, size, force_64, version, flags, stream, atom_factory);
- }
- else
- {
+ } else {
return new AP4_ContainerAtom(type, size, force_64, stream, atom_factory);
}
}
@@ -116,10 +110,10 @@ AP4_ContainerAtom::AP4_ContainerAtom(Type type, AP4_UI64 size, bool force_64) :
/*----------------------------------------------------------------------
| AP4_ContainerAtom::AP4_ContainerAtom
+---------------------------------------------------------------------*/
-AP4_ContainerAtom::AP4_ContainerAtom(Type type,
+AP4_ContainerAtom::AP4_ContainerAtom(Type type,
AP4_UI64 size,
bool force_64,
- AP4_UI32 version,
+ AP4_UI32 version,
AP4_UI32 flags) :
AP4_Atom(type, size, force_64, version, flags)
{
@@ -129,20 +123,20 @@ AP4_ContainerAtom::AP4_ContainerAtom(Type type,
/*----------------------------------------------------------------------
| AP4_ContainerAtom::AP4_ContainerAtom
+---------------------------------------------------------------------*/
-AP4_ContainerAtom::AP4_ContainerAtom(Type type,
+AP4_ContainerAtom::AP4_ContainerAtom(Type type,
AP4_UI64 size,
bool force_64,
AP4_ByteStream& stream,
AP4_AtomFactory& atom_factory) :
AP4_Atom(type, size, force_64)
{
- ReadChildren(atom_factory, stream, size - GetHeaderSize());
+ ReadChildren(atom_factory, stream, size-GetHeaderSize());
}
/*----------------------------------------------------------------------
| AP4_ContainerAtom::AP4_ContainerAtom
+---------------------------------------------------------------------*/
-AP4_ContainerAtom::AP4_ContainerAtom(Type type,
+AP4_ContainerAtom::AP4_ContainerAtom(Type type,
AP4_UI64 size,
bool force_64,
AP4_UI32 version,
@@ -151,30 +145,26 @@ AP4_ContainerAtom::AP4_ContainerAtom(Type type,
AP4_AtomFactory& atom_factory) :
AP4_Atom(type, size, force_64, version, flags)
{
- ReadChildren(atom_factory, stream, size - GetHeaderSize());
+ ReadChildren(atom_factory, stream, size-GetHeaderSize());
}
/*----------------------------------------------------------------------
| AP4_ContainerAtom::Clone
+---------------------------------------------------------------------*/
-AP4_Atom*
+AP4_Atom*
AP4_ContainerAtom::Clone()
{
AP4_ContainerAtom* clone;
- if(m_IsFull)
- {
+ if (m_IsFull) {
clone = new AP4_ContainerAtom(m_Type, m_Version, m_Flags);
- }
- else
- {
+ } else {
clone = new AP4_ContainerAtom(m_Type);
}
AP4_List<AP4_Atom>::Item* child_item = m_Children.FirstItem();
- while(child_item)
- {
+ while (child_item) {
AP4_Atom* child_clone = child_item->GetData()->Clone();
- if(child_clone) clone->AddChild(child_clone);
+ if (child_clone) clone->AddChild(child_clone);
child_item = child_item->GetNext();
}
@@ -186,7 +176,7 @@ AP4_ContainerAtom::Clone()
+---------------------------------------------------------------------*/
void
AP4_ContainerAtom::ReadChildren(AP4_AtomFactory& atom_factory,
- AP4_ByteStream& stream,
+ AP4_ByteStream& stream,
AP4_UI64 size)
{
AP4_Atom* atom;
@@ -195,9 +185,8 @@ AP4_ContainerAtom::ReadChildren(AP4_AtomFactory& atom_factory,
// save and switch the factory's context
atom_factory.PushContext(m_Type);
- while(AP4_SUCCEEDED(
- atom_factory.CreateAtomFromStream(stream, bytes_available, atom)))
- {
+ while (AP4_SUCCEEDED(
+ atom_factory.CreateAtomFromStream(stream, bytes_available, atom))) {
atom->SetParent(this);
m_Children.Add(atom);
}
@@ -249,7 +238,7 @@ AP4_ContainerAtom::OnChildChanged(AP4_Atom*)
SetSize(size);
// update our parent
- if(m_Parent) m_Parent->OnChildChanged(this);
+ if (m_Parent) m_Parent->OnChildChanged(this);
}
/*----------------------------------------------------------------------
@@ -259,10 +248,10 @@ void
AP4_ContainerAtom::OnChildAdded(AP4_Atom* child)
{
// update our size
- SetSize(GetSize() + child->GetSize());
+ SetSize(GetSize()+child->GetSize());
// update our parent
- if(m_Parent) m_Parent->OnChildChanged(this);
+ if (m_Parent) m_Parent->OnChildChanged(this);
}
/*----------------------------------------------------------------------
@@ -272,8 +261,8 @@ void
AP4_ContainerAtom::OnChildRemoved(AP4_Atom* child)
{
// update our size
- SetSize(GetSize() - child->GetSize());
+ SetSize(GetSize()-child->GetSize());
// update our parent
- if(m_Parent) m_Parent->OnChildChanged(this);
+ if (m_Parent) m_Parent->OnChildChanged(this);
}
diff --git a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4ContainerAtom.h b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4ContainerAtom.h
index e23fabfa6..b19e18637 100644
--- a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4ContainerAtom.h
+++ b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4ContainerAtom.h
@@ -45,14 +45,14 @@ class AP4_AtomFactory;
/*----------------------------------------------------------------------
| AP4_ContainerAtom
+---------------------------------------------------------------------*/
-class AP4_ContainerAtom : public AP4_Atom, public AP4_AtomParent
+class AP4_ContainerAtom : public AP4_Atom, public AP4_AtomParent
{
public:
AP4_IMPLEMENT_DYNAMIC_CAST_D2(AP4_ContainerAtom, AP4_Atom, AP4_AtomParent)
// class methods
- static AP4_ContainerAtom* Create(Type type,
- AP4_UI64 size,
+ static AP4_ContainerAtom* Create(Type type,
+ AP4_UI64 size,
bool is_full,
bool force_64,
AP4_ByteStream& stream,
@@ -60,13 +60,10 @@ public:
// methods
explicit AP4_ContainerAtom(Type type);
- explicit AP4_ContainerAtom(Type type, AP4_UI32 version, AP4_UI32 flags);
+ explicit AP4_ContainerAtom(Type type, AP4_UI32 version, AP4_UI32 flags);
explicit AP4_ContainerAtom(Type type, AP4_UI64 size, bool force_64);
explicit AP4_ContainerAtom(Type type, AP4_UI64 size, bool force_64, AP4_UI32 version, AP4_UI32 flags);
- AP4_List<AP4_Atom>& GetChildren()
- {
- return m_Children;
- }
+ AP4_List<AP4_Atom>& GetChildren() { return m_Children; }
virtual AP4_Result InspectFields(AP4_AtomInspector& inspector);
virtual AP4_Result InspectChildren(AP4_AtomInspector& inspector);
virtual AP4_Result WriteFields(AP4_ByteStream& stream);
@@ -79,22 +76,22 @@ public:
protected:
// constructors
- AP4_ContainerAtom(Type type,
- AP4_UI64 size,
+ AP4_ContainerAtom(Type type,
+ AP4_UI64 size,
bool force_64,
AP4_UI32 version,
AP4_UI32 flags,
AP4_ByteStream& stream,
AP4_AtomFactory& atom_factory);
- AP4_ContainerAtom(Type type,
- AP4_UI64 size,
+ AP4_ContainerAtom(Type type,
+ AP4_UI64 size,
bool force_64,
AP4_ByteStream& stream,
AP4_AtomFactory& atom_factory);
// methods
void ReadChildren(AP4_AtomFactory& atom_factory,
- AP4_ByteStream& stream,
+ AP4_ByteStream& stream,
AP4_UI64 size);
};
diff --git a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4CttsAtom.cpp b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4CttsAtom.cpp
index b483be5b3..fc431825a 100644
--- a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4CttsAtom.cpp
+++ b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4CttsAtom.cpp
@@ -1,6 +1,6 @@
/*****************************************************************
|
-| AP4 - ctts Atoms
+| AP4 - ctts Atoms
|
| Copyright 2002-2008 Axiomatic Systems, LLC
|
@@ -46,8 +46,8 @@ AP4_CttsAtom::Create(AP4_UI32 size, AP4_ByteStream& stream)
{
AP4_UI32 version;
AP4_UI32 flags;
- if(AP4_FAILED(AP4_Atom::ReadFullHeader(stream, version, flags))) return NULL;
- if(version != 0) return NULL;
+ if (AP4_FAILED(AP4_Atom::ReadFullHeader(stream, version, flags))) return NULL;
+ if (version != 0) return NULL;
return new AP4_CttsAtom(size, version, flags, stream);
}
@@ -55,7 +55,7 @@ AP4_CttsAtom::Create(AP4_UI32 size, AP4_ByteStream& stream)
| AP4_CttsAtom::AP4_CttsAtom
+---------------------------------------------------------------------*/
AP4_CttsAtom::AP4_CttsAtom() :
- AP4_Atom(AP4_ATOM_TYPE_CTTS, AP4_FULL_ATOM_HEADER_SIZE + 4, 0, 0)
+ AP4_Atom(AP4_ATOM_TYPE_CTTS, AP4_FULL_ATOM_HEADER_SIZE+4, 0, 0)
{
m_LookupCache.sample = 0;
m_LookupCache.entry_index = 0;
@@ -64,7 +64,7 @@ AP4_CttsAtom::AP4_CttsAtom() :
/*----------------------------------------------------------------------
| AP4_CttsAtom::AP4_CttsAtom
+---------------------------------------------------------------------*/
-AP4_CttsAtom::AP4_CttsAtom(AP4_UI32 size,
+AP4_CttsAtom::AP4_CttsAtom(AP4_UI32 size,
AP4_UI32 version,
AP4_UI32 flags,
AP4_ByteStream& stream) :
@@ -77,16 +77,14 @@ AP4_CttsAtom::AP4_CttsAtom(AP4_UI32 size,
stream.ReadUI32(entry_count);
m_Entries.SetItemCount(entry_count);
unsigned char* buffer = new unsigned char[entry_count*8];
- AP4_Result result = stream.Read(buffer, entry_count * 8);
- if(AP4_FAILED(result))
- {
+ AP4_Result result = stream.Read(buffer, entry_count*8);
+ if (AP4_FAILED(result)) {
delete[] buffer;
return;
}
//bool use_quicktime_format = false;
//AP4_SI32 quicktime_min_offset = 0;
- for(unsigned i = 0; i < entry_count; i++)
- {
+ for (unsigned i=0; i<entry_count; i++) {
m_Entries[i].m_SampleCount = AP4_BytesToUInt32BE(&buffer[i*8 ]);
AP4_UI32 offset = AP4_BytesToUInt32BE(&buffer[i*8+4]);
//if (offset & 0x80000000) {
@@ -97,7 +95,7 @@ AP4_CttsAtom::AP4_CttsAtom(AP4_UI32 size,
m_Entries[i].m_SampleOffset = offset;
}
delete[] buffer;
-
+
// in the quicktime format, the offsets can be positive or negative, so
// we need to adjust for them here
//if (use_quicktime_format) {
@@ -126,27 +124,24 @@ AP4_CttsAtom::GetCtsOffset(AP4_Ordinal sample, AP4_UI32& cts_offset)
{
// default value
cts_offset = 0;
-
+
// sample indexes start at 1
- if(sample == 0) return AP4_ERROR_OUT_OF_RANGE;
-
+ if (sample == 0) return AP4_ERROR_OUT_OF_RANGE;
+
// check the lookup cache
AP4_Ordinal lookup_start = 0;
AP4_Ordinal sample_start = 0;
- if(sample >= m_LookupCache.sample)
- {
+ if (sample >= m_LookupCache.sample) {
// start from the cached entry
lookup_start = m_LookupCache.entry_index;
sample_start = m_LookupCache.sample;
}
- for(AP4_Ordinal i = lookup_start; i < m_Entries.ItemCount(); i++)
- {
+ for (AP4_Ordinal i = lookup_start; i < m_Entries.ItemCount(); i++) {
AP4_CttsTableEntry& entry = m_Entries[i];
// check if we have reached the sample
- if(sample <= sample_start + entry.m_SampleCount)
- {
+ if (sample <= sample_start+entry.m_SampleCount) {
// we are within the sample range for the current entry
cts_offset = entry.m_SampleOffset;
@@ -158,7 +153,7 @@ AP4_CttsAtom::GetCtsOffset(AP4_Ordinal sample, AP4_UI32& cts_offset)
}
// update the upper bound
- sample_start += entry.m_SampleCount;
+ sample_start += entry.m_SampleCount;
}
// sample is greater than the number of samples
@@ -176,18 +171,17 @@ AP4_CttsAtom::WriteFields(AP4_ByteStream& stream)
// write the entry count
AP4_Cardinal entry_count = m_Entries.ItemCount();
result = stream.WriteUI32(entry_count);
- if(AP4_FAILED(result)) return result;
+ if (AP4_FAILED(result)) return result;
// write the entries
- for(AP4_Ordinal i = 0; i < entry_count; i++)
- {
+ for (AP4_Ordinal i=0; i<entry_count; i++) {
// sample count
result = stream.WriteUI32(m_Entries[i].m_SampleCount);
- if(AP4_FAILED(result)) return result;
+ if (AP4_FAILED(result)) return result;
// time offset
result = stream.WriteUI32(m_Entries[i].m_SampleOffset);
- if(AP4_FAILED(result)) return result;
+ if (AP4_FAILED(result)) return result;
}
return AP4_SUCCESS;
@@ -201,15 +195,13 @@ AP4_CttsAtom::InspectFields(AP4_AtomInspector& inspector)
{
inspector.AddField("entry_count", m_Entries.ItemCount());
- if(inspector.GetVerbosity() >= 2)
- {
+ if (inspector.GetVerbosity() >= 2) {
char header[32];
char value[64];
- for(AP4_Ordinal i = 0; i < m_Entries.ItemCount(); i++)
- {
+ for (AP4_Ordinal i=0; i<m_Entries.ItemCount(); i++) {
AP4_FormatString(header, sizeof(header), "entry %8d", i);
- AP4_FormatString(value, sizeof(value), "count=%d, offset=%d",
- m_Entries[i].m_SampleCount,
+ AP4_FormatString(value, sizeof(value), "count=%d, offset=%d",
+ m_Entries[i].m_SampleCount,
m_Entries[i].m_SampleOffset);
inspector.AddField(header, value);
}
diff --git a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4CttsAtom.h b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4CttsAtom.h
index d853a5d99..0f86c8399 100644
--- a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4CttsAtom.h
+++ b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4CttsAtom.h
@@ -1,6 +1,6 @@
/*****************************************************************
|
-| AP4 - ctts Atoms
+| AP4 - ctts Atoms
|
| Copyright 2002-2008 Axiomatic Systems, LLC
|
@@ -44,11 +44,10 @@ class AP4_ByteStream;
/*----------------------------------------------------------------------
| AP4_CttsTableEntry
+---------------------------------------------------------------------*/
-class AP4_CttsTableEntry
-{
-public:
- AP4_CttsTableEntry() :
- m_SampleCount(0),
+class AP4_CttsTableEntry {
+ public:
+ AP4_CttsTableEntry() :
+ m_SampleCount(0),
m_SampleOffset(0) {}
AP4_CttsTableEntry(AP4_UI32 sample_count,
AP4_UI32 sample_offset) :
@@ -72,7 +71,7 @@ public:
// constructor
AP4_CttsAtom();
-
+
// methods
virtual AP4_Result InspectFields(AP4_AtomInspector& inspector);
virtual AP4_Result WriteFields(AP4_ByteStream& stream);
@@ -81,15 +80,14 @@ public:
private:
// methods
- AP4_CttsAtom(AP4_UI32 size,
+ AP4_CttsAtom(AP4_UI32 size,
AP4_UI32 version,
AP4_UI32 flags,
AP4_ByteStream& stream);
// members
AP4_Array<AP4_CttsTableEntry> m_Entries;
- struct
- {
+ struct {
AP4_Ordinal sample;
AP4_Ordinal entry_index;
} m_LookupCache;
diff --git a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4DataBuffer.cpp b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4DataBuffer.cpp
index a82f2d57c..5cd837d3c 100644
--- a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4DataBuffer.cpp
+++ b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4DataBuffer.cpp
@@ -64,8 +64,7 @@ AP4_DataBuffer::AP4_DataBuffer(const void* data, AP4_Size data_size) :
m_BufferSize(data_size),
m_DataSize(data_size)
{
- if(data && data_size)
- {
+ if (data && data_size) {
m_Buffer = new AP4_Byte[data_size];
AP4_CopyMemory(m_Buffer, data, data_size);
}
@@ -89,8 +88,7 @@ AP4_DataBuffer::AP4_DataBuffer(const AP4_DataBuffer& other) :
+---------------------------------------------------------------------*/
AP4_DataBuffer::~AP4_DataBuffer()
{
- if(m_BufferIsLocal)
- {
+ if (m_BufferIsLocal) {
delete[] m_Buffer;
}
}
@@ -101,11 +99,11 @@ AP4_DataBuffer::~AP4_DataBuffer()
AP4_Result
AP4_DataBuffer::Reserve(AP4_Size size)
{
- if(size <= m_BufferSize) return AP4_SUCCESS;
+ if (size <= m_BufferSize) return AP4_SUCCESS;
// try doubling the buffer to accomodate for the new size
- AP4_Size new_size = m_BufferSize * 2 + 1024;
- if(new_size < size) new_size = size;
+ AP4_Size new_size = m_BufferSize*2+1024;
+ if (new_size < size) new_size = size;
return SetBufferSize(new_size);
}
@@ -115,8 +113,7 @@ AP4_DataBuffer::Reserve(AP4_Size size)
AP4_Result
AP4_DataBuffer::SetBuffer(AP4_Byte* buffer, AP4_Size buffer_size)
{
- if(m_BufferIsLocal)
- {
+ if (m_BufferIsLocal) {
// destroy the local buffer
delete[] m_Buffer;
}
@@ -135,14 +132,11 @@ AP4_DataBuffer::SetBuffer(AP4_Byte* buffer, AP4_Size buffer_size)
AP4_Result
AP4_DataBuffer::SetBufferSize(AP4_Size buffer_size)
{
- if(m_BufferIsLocal)
- {
+ if (m_BufferIsLocal) {
return ReallocateBuffer(buffer_size);
- }
- else
- {
+ } else {
return AP4_FAILURE; // you cannot change the
- // buffer management mode
+ // buffer management mode
}
}
@@ -152,15 +146,11 @@ AP4_DataBuffer::SetBufferSize(AP4_Size buffer_size)
AP4_Result
AP4_DataBuffer::SetDataSize(AP4_Size size)
{
- if(size > m_BufferSize)
- {
- if(m_BufferIsLocal)
- {
+ if (size > m_BufferSize) {
+ if (m_BufferIsLocal) {
AP4_Result result = ReallocateBuffer(size);
- if(AP4_FAILED(result)) return result;
- }
- else
- {
+ if (AP4_FAILED(result)) return result;
+ } else {
return AP4_FAILURE;
}
}
@@ -174,15 +164,11 @@ AP4_DataBuffer::SetDataSize(AP4_Size size)
AP4_Result
AP4_DataBuffer::SetData(const AP4_Byte* data, AP4_Size size)
{
- if(size > m_BufferSize)
- {
- if(m_BufferIsLocal)
- {
+ if (size > m_BufferSize) {
+ if (m_BufferIsLocal) {
AP4_Result result = ReallocateBuffer(size);
- if(AP4_FAILED(result)) return result;
- }
- else
- {
+ if (AP4_FAILED(result)) return result;
+ } else {
return AP4_FAILURE;
}
}
@@ -200,16 +186,15 @@ AP4_Result
AP4_DataBuffer::ReallocateBuffer(AP4_Size size)
{
// check that the existing data fits
- if(m_DataSize > size) return AP4_FAILURE;
+ if (m_DataSize > size) return AP4_FAILURE;
// allocate a new buffer
AP4_Byte* new_buffer = new AP4_Byte[size];
// copy the contents of the previous buffer ,is any
- if(m_Buffer && m_DataSize)
- {
- AP4_CopyMemory(new_buffer, m_Buffer, m_DataSize);
- }
+ if (m_Buffer && m_DataSize) {
+ AP4_CopyMemory(new_buffer, m_Buffer, m_DataSize);
+ }
// destroy the previous buffer
delete[] m_Buffer;
diff --git a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4DataBuffer.h b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4DataBuffer.h
index 4ecdac62b..64e89f981 100644
--- a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4DataBuffer.h
+++ b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4DataBuffer.h
@@ -37,11 +37,11 @@
/*----------------------------------------------------------------------
| AP4_DataBuffer
+---------------------------------------------------------------------*/
-class AP4_DataBuffer
+class AP4_DataBuffer
{
-public:
+ public:
// constructors & destructor
- AP4_DataBuffer();
+ AP4_DataBuffer();
AP4_DataBuffer(AP4_Size size);
AP4_DataBuffer(const void* data, AP4_Size data_size);
AP4_DataBuffer(const AP4_DataBuffer& other);
@@ -50,31 +50,19 @@ public:
// data buffer handling methods
AP4_Result SetBuffer(AP4_Byte* buffer, AP4_Size buffer_size);
AP4_Result SetBufferSize(AP4_Size buffer_size);
- AP4_Size GetBufferSize() const
- {
- return m_BufferSize;
- }
+ AP4_Size GetBufferSize() const { return m_BufferSize; }
// data handling methods
- const AP4_Byte* GetData() const
- {
- return m_Buffer;
- }
- AP4_Byte* UseData()
- {
- return m_Buffer;
- };
- AP4_Size GetDataSize() const
- {
- return m_DataSize;
- }
+ const AP4_Byte* GetData() const { return m_Buffer; }
+ AP4_Byte* UseData() { return m_Buffer; };
+ AP4_Size GetDataSize() const { return m_DataSize; }
AP4_Result SetDataSize(AP4_Size size);
AP4_Result SetData(const AP4_Byte* data, AP4_Size data_size);
// memory management
AP4_Result Reserve(AP4_Size size);
-protected:
+ protected:
// members
bool m_BufferIsLocal;
AP4_Byte* m_Buffer;
@@ -88,6 +76,6 @@ private:
// forbid this
AP4_DataBuffer& operator=(const AP4_DataBuffer& other);
};
-
+
#endif // _AP4_DATA_BUFFER_H_
diff --git a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4DcomAtom.cpp b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4DcomAtom.cpp
index 688e6fc4c..9d0bcb0dc 100644
--- a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4DcomAtom.cpp
+++ b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4DcomAtom.cpp
@@ -36,18 +36,18 @@
| AP4_DcomAtom::AP4_DcomAtom
+---------------------------------------------------------------------*/
-AP4_DcomAtom*
-AP4_DcomAtom::Create(AP4_Size size, AP4_ByteStream& stream)
-{
- return new AP4_DcomAtom(size, stream);
-}
+AP4_DcomAtom*
+AP4_DcomAtom::Create(AP4_Size size, AP4_ByteStream& stream)
+{
+ return new AP4_DcomAtom(size, stream);
+}
AP4_DcomAtom::AP4_DcomAtom(AP4_Size size,
AP4_ByteStream& stream)
- : AP4_Atom(AP4_ATOM_TYPE_DCOM)
+ : AP4_Atom(AP4_ATOM_TYPE_DCOM)
{
- size -= AP4_ATOM_HEADER_SIZE;
+ size -= AP4_ATOM_HEADER_SIZE;
stream.ReadUI32(m_CompressorSubType);
}
diff --git a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4DcomAtom.h b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4DcomAtom.h
index 20b82f342..4f0e1e8a8 100644
--- a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4DcomAtom.h
+++ b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4DcomAtom.h
@@ -40,25 +40,19 @@
class AP4_DcomAtom : public AP4_Atom
{
public:
- // class methods
- static AP4_DcomAtom* Create(AP4_Size size, AP4_ByteStream& stream);
-
- // methods
- AP4_DcomAtom(AP4_Size size,
+ // class methods
+ static AP4_DcomAtom* Create(AP4_Size size, AP4_ByteStream& stream);
+
+ // methods
+ AP4_DcomAtom(AP4_Size size,
AP4_ByteStream& stream);
- AP4_Result WriteFields(AP4_ByteStream& stream)
- {
- return AP4_FAILURE;
- }
+ AP4_Result WriteFields(AP4_ByteStream& stream) { return AP4_FAILURE; }
- AP4_Atom::Type GetCompressorSubType() const
- {
- return m_CompressorSubType;
- }
+ AP4_Atom::Type GetCompressorSubType() const { return m_CompressorSubType; }
private:
- AP4_Atom::Type m_CompressorSubType;
+ AP4_Atom::Type m_CompressorSubType;
};
#endif // _AP4_DCOM_ATOM_H_
diff --git a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4Debug.cpp b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4Debug.cpp
index 98925d01c..ee09ae84d 100644
--- a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4Debug.cpp
+++ b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4Debug.cpp
@@ -58,7 +58,7 @@ void
AP4_Debug(const char* format, ...)
{
va_list args;
-
+
va_start(args, format);
char buffer[AP4_DEBUG_MAX_BUFFER];
diff --git a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4DecoderConfigDescriptor.cpp b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4DecoderConfigDescriptor.cpp
index 787abad31..45b348f2d 100644
--- a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4DecoderConfigDescriptor.cpp
+++ b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4DecoderConfigDescriptor.cpp
@@ -58,8 +58,7 @@ AP4_DecoderConfigDescriptor::AP4_DecoderConfigDescriptor(
m_MaxBitrate(max_bitrate),
m_AverageBitrate(avg_bitrate)
{
- if(dsi)
- {
+ if (dsi) {
m_SubDescriptors.Add(dsi);
m_PayloadSize += dsi->GetSize();
m_HeaderSize = MinHeaderSize(m_PayloadSize);
@@ -71,8 +70,8 @@ AP4_DecoderConfigDescriptor::AP4_DecoderConfigDescriptor(
+---------------------------------------------------------------------*/
AP4_DecoderConfigDescriptor::AP4_DecoderConfigDescriptor(
AP4_ByteStream& stream, AP4_Size header_size, AP4_Size payload_size) :
- AP4_Descriptor(AP4_DESCRIPTOR_TAG_DECODER_CONFIG,
- header_size,
+ AP4_Descriptor(AP4_DESCRIPTOR_TAG_DECODER_CONFIG,
+ header_size,
payload_size)
{
// record the start position
@@ -83,19 +82,18 @@ AP4_DecoderConfigDescriptor::AP4_DecoderConfigDescriptor(
stream.ReadUI08(m_ObjectTypeIndication);
unsigned char bits;
stream.ReadUI08(bits);
- m_StreamType = (bits >> 2) & 0x3F;
- m_UpStream = bits & 2 ? true : false;
+ m_StreamType = (bits>>2)&0x3F;
+ m_UpStream = bits&2 ? true:false;
stream.ReadUI24(m_BufferSize);
stream.ReadUI32(m_MaxBitrate);
stream.ReadUI32(m_AverageBitrate);
// read other descriptors
- AP4_SubStream* substream = new AP4_SubStream(stream, start + 13, payload_size - 13);
+ AP4_SubStream* substream = new AP4_SubStream(stream, start+13, payload_size-13);
AP4_Descriptor* descriptor = NULL;
- while(AP4_DescriptorFactory::CreateDescriptorFromStream(*substream,
- descriptor)
- == AP4_SUCCESS)
- {
+ while (AP4_DescriptorFactory::CreateDescriptorFromStream(*substream,
+ descriptor)
+ == AP4_SUCCESS) {
m_SubDescriptors.Add(descriptor);
}
substream->Release();
@@ -116,7 +114,7 @@ AP4_Result
AP4_DecoderConfigDescriptor::WriteFields(AP4_ByteStream& stream)
{
stream.WriteUI08(m_ObjectTypeIndication);
- AP4_UI08 bits = (m_StreamType << 2) | (m_UpStream ? 2 : 0) | 1;
+ AP4_UI08 bits = (m_StreamType<<2) | (m_UpStream? 2 : 0) | 1;
stream.WriteUI08(bits);
stream.WriteUI24(m_BufferSize);
stream.WriteUI32(m_MaxBitrate);
@@ -134,9 +132,9 @@ AP4_Result
AP4_DecoderConfigDescriptor::Inspect(AP4_AtomInspector& inspector)
{
char info[64];
- AP4_FormatString(info, sizeof(info), "size=%ld+%ld",
- GetHeaderSize(),
- m_PayloadSize);
+ AP4_FormatString(info, sizeof(info), "size=%ld+%ld",
+ GetHeaderSize(),
+ m_PayloadSize);
inspector.StartElement("[DecoderConfig]", info);
inspector.AddField("stream_type", m_StreamType);
inspector.AddField("object_type", m_ObjectTypeIndication);
@@ -161,17 +159,14 @@ AP4_DecoderConfigDescriptor::GetDecoderSpecificInfoDescriptor() const
{
// find the decoder specific info
AP4_Descriptor* descriptor = NULL;
- AP4_Result result =
+ AP4_Result result =
m_SubDescriptors.Find(AP4_DescriptorFinder(AP4_DESCRIPTOR_TAG_DECODER_SPECIFIC_INFO),
descriptor);
-
+
// return it
- if(AP4_SUCCEEDED(result))
- {
+ if (AP4_SUCCEEDED(result)) {
return AP4_DYNAMIC_CAST(AP4_DecoderSpecificInfoDescriptor, descriptor);
- }
- else
- {
+ } else {
return NULL;
}
}
diff --git a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4DecoderConfigDescriptor.h b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4DecoderConfigDescriptor.h
index 2b3298407..831bbf9e5 100644
--- a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4DecoderConfigDescriptor.h
+++ b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4DecoderConfigDescriptor.h
@@ -1,6 +1,6 @@
/*****************************************************************
|
-| AP4 - DecoderConfig Descriptor
+| AP4 - DecoderConfig Descriptor
|
| Copyright 2002-2008 Axiomatic Systems, LLC
|
@@ -52,7 +52,7 @@ const AP4_UI08 AP4_DESCRIPTOR_TAG_DECODER_CONFIG = 0x04;
+---------------------------------------------------------------------*/
class AP4_DecoderConfigDescriptor : public AP4_Descriptor
{
-public:
+ public:
AP4_IMPLEMENT_DYNAMIC_CAST_D(AP4_DecoderConfigDescriptor, AP4_Descriptor)
// methods
@@ -62,38 +62,25 @@ public:
AP4_UI32 max_bitrate,
AP4_UI32 avg_bitrate,
AP4_DecoderSpecificInfoDescriptor* dsi);
- AP4_DecoderConfigDescriptor(AP4_ByteStream& stream,
+ AP4_DecoderConfigDescriptor(AP4_ByteStream& stream,
AP4_Size header_size,
AP4_Size payload_size);
virtual ~AP4_DecoderConfigDescriptor();
virtual AP4_Result WriteFields(AP4_ByteStream& stream);
virtual AP4_Result Inspect(AP4_AtomInspector& inspector);
-
+
// accessors
virtual const AP4_DecoderSpecificInfoDescriptor*
- GetDecoderSpecificInfoDescriptor() const;
- virtual AP4_UI08 GetObjectTypeIndication() const
- {
- return m_ObjectTypeIndication;
- }
- virtual AP4_UI08 GetStreamType() const
- {
- return m_StreamType;
- }
- virtual AP4_UI32 GetBufferSize() const
- {
- return m_BufferSize;
+ GetDecoderSpecificInfoDescriptor() const;
+ virtual AP4_UI08 GetObjectTypeIndication() const {
+ return m_ObjectTypeIndication;
}
- virtual AP4_UI32 GetMaxBitrate() const
- {
- return m_MaxBitrate;
- }
- virtual AP4_UI32 GetAvgBitrate() const
- {
- return m_AverageBitrate;
- }
-
-private:
+ virtual AP4_UI08 GetStreamType() const { return m_StreamType; }
+ virtual AP4_UI32 GetBufferSize() const { return m_BufferSize; }
+ virtual AP4_UI32 GetMaxBitrate() const { return m_MaxBitrate; }
+ virtual AP4_UI32 GetAvgBitrate() const { return m_AverageBitrate; }
+
+ private:
// members
AP4_UI08 m_StreamType;
AP4_UI08 m_ObjectTypeIndication;
diff --git a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4DecoderSpecificInfoDescriptor.cpp b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4DecoderSpecificInfoDescriptor.cpp
index 68892c1c5..8c755964f 100644
--- a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4DecoderSpecificInfoDescriptor.cpp
+++ b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4DecoderSpecificInfoDescriptor.cpp
@@ -45,8 +45,8 @@ AP4_DEFINE_DYNAMIC_CAST_ANCHOR(AP4_DecoderSpecificInfoDescriptor)
+---------------------------------------------------------------------*/
AP4_DecoderSpecificInfoDescriptor::AP4_DecoderSpecificInfoDescriptor(
const AP4_DataBuffer& data) :
- AP4_Descriptor(AP4_DESCRIPTOR_TAG_DECODER_SPECIFIC_INFO,
- MinHeaderSize(data.GetDataSize()),
+ AP4_Descriptor(AP4_DESCRIPTOR_TAG_DECODER_SPECIFIC_INFO,
+ MinHeaderSize(data.GetDataSize()),
data.GetDataSize()),
m_Info(data)
{
@@ -57,11 +57,11 @@ AP4_DecoderSpecificInfoDescriptor::AP4_DecoderSpecificInfoDescriptor(
+---------------------------------------------------------------------*/
AP4_DecoderSpecificInfoDescriptor::AP4_DecoderSpecificInfoDescriptor(
AP4_ByteStream& stream, AP4_Size header_size, AP4_Size payload_size) :
- AP4_Descriptor(AP4_DESCRIPTOR_TAG_DECODER_SPECIFIC_INFO,
+ AP4_Descriptor(AP4_DESCRIPTOR_TAG_DECODER_SPECIFIC_INFO,
header_size, payload_size)
{
m_Info.SetDataSize(payload_size);
- stream.Read(m_Info.UseData(), payload_size);
+ stream.Read(m_Info.UseData(), payload_size);
}
/*----------------------------------------------------------------------
@@ -78,8 +78,7 @@ AP4_Result
AP4_DecoderSpecificInfoDescriptor::WriteFields(AP4_ByteStream& stream)
{
// write the info buffer
- if(m_PayloadSize && m_Info.GetDataSize())
- {
+ if (m_PayloadSize && m_Info.GetDataSize()) {
stream.Write(m_Info.GetData(), m_Info.GetDataSize());
}
@@ -93,10 +92,9 @@ AP4_Result
AP4_DecoderSpecificInfoDescriptor::Inspect(AP4_AtomInspector& inspector)
{
char* info = new char[m_Info.GetDataSize()*3+1];
- for(unsigned int i = 0; i < m_Info.GetDataSize(); i++)
- {
- AP4_FormatString(&info[i*3], 4, "%02x ", m_Info.UseData()[i]);
- }
+ for (unsigned int i=0; i<m_Info.GetDataSize(); i++) {
+ AP4_FormatString(&info[i*3], 4, "%02x ", m_Info.UseData()[i]);
+ }
info[m_Info.GetDataSize()*3] = '\0';
inspector.AddField("[DecoderSpecificInfo]", info);
delete[] info;
diff --git a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4DecoderSpecificInfoDescriptor.h b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4DecoderSpecificInfoDescriptor.h
index b20648053..8f0611c12 100644
--- a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4DecoderSpecificInfoDescriptor.h
+++ b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4DecoderSpecificInfoDescriptor.h
@@ -1,6 +1,6 @@
/*****************************************************************
|
-| AP4 - DecoderSpecificInfo Descriptor
+| AP4 - DecoderSpecificInfo Descriptor
|
| Copyright 2002-2008 Axiomatic Systems, LLC
|
@@ -57,16 +57,13 @@ public:
// methods
AP4_DecoderSpecificInfoDescriptor(const AP4_DataBuffer& data);
- AP4_DecoderSpecificInfoDescriptor(AP4_ByteStream& stream,
+ AP4_DecoderSpecificInfoDescriptor(AP4_ByteStream& stream,
AP4_Size header_size,
AP4_Size payload_size);
virtual ~AP4_DecoderSpecificInfoDescriptor();
virtual AP4_Result WriteFields(AP4_ByteStream& stream);
virtual AP4_Result Inspect(AP4_AtomInspector& inspector);
- virtual const AP4_DataBuffer& GetDecoderSpecificInfo() const
- {
- return m_Info;
- }
+ virtual const AP4_DataBuffer& GetDecoderSpecificInfo() const { return m_Info; }
private:
// members
diff --git a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4Descriptor.cpp b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4Descriptor.cpp
index 699c7f9f3..38fb28988 100644
--- a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4Descriptor.cpp
+++ b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4Descriptor.cpp
@@ -61,13 +61,13 @@ AP4_Descriptor::Inspect(AP4_AtomInspector& inspector)
| AP4_UnknownDescriptor::AP4_UnknownDescriptor
+---------------------------------------------------------------------*/
AP4_UnknownDescriptor::AP4_UnknownDescriptor(AP4_ByteStream& stream,
- AP4_UI08 tag,
- AP4_Size header_size,
- AP4_Size payload_size) :
+ AP4_UI08 tag,
+ AP4_Size header_size,
+ AP4_Size payload_size) :
AP4_Descriptor(tag, header_size, payload_size)
{
m_Data.SetDataSize(payload_size);
- stream.Read(m_Data.UseData(), payload_size);
+ stream.Read(m_Data.UseData(), payload_size);
}
/*----------------------------------------------------------------------
diff --git a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4Descriptor.h b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4Descriptor.h
index d66daa2bb..7fe0717a1 100644
--- a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4Descriptor.h
+++ b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4Descriptor.h
@@ -1,6 +1,6 @@
/*****************************************************************
|
-| AP4 - Descriptors
+| AP4 - Descriptors
|
| Copyright 2002-2008 Axiomatic Systems, LLC
|
@@ -47,9 +47,9 @@ class AP4_AtomInspector;
+---------------------------------------------------------------------*/
class AP4_Descriptor : public AP4_Expandable
{
-public:
+ public:
AP4_IMPLEMENT_DYNAMIC_CAST(AP4_Descriptor)
-
+
// constructor
AP4_Descriptor(AP4_UI08 tag, AP4_Size header_size, AP4_Size payload_size) :
AP4_Expandable(tag, CLASS_ID_SIZE_08, header_size, payload_size) {}
@@ -58,10 +58,7 @@ public:
virtual AP4_Result Inspect(AP4_AtomInspector& inspector);
// methods
- AP4_UI08 GetTag()
- {
- return (AP4_UI08)m_ClassId;
- }
+ AP4_UI08 GetTag() { return (AP4_UI08)m_ClassId; }
};
/*----------------------------------------------------------------------
@@ -71,14 +68,14 @@ class AP4_UnknownDescriptor : public AP4_Descriptor
{
public:
// contrusctor
- AP4_UnknownDescriptor(AP4_ByteStream& stream,
+ AP4_UnknownDescriptor(AP4_ByteStream& stream,
AP4_UI08 tag,
AP4_Size header_size,
AP4_Size payload_size);
-
+
// AP4_Expandable methods
virtual AP4_Result WriteFields(AP4_ByteStream& stream);
-
+
private:
// members
AP4_DataBuffer m_Data;
@@ -89,14 +86,13 @@ private:
+---------------------------------------------------------------------*/
class AP4_DescriptorFinder : public AP4_List<AP4_Descriptor>::Item::Finder
{
-public:
+ public:
AP4_DescriptorFinder(AP4_UI08 tag) : m_Tag(tag) {}
- AP4_Result Test(AP4_Descriptor* descriptor) const
- {
+ AP4_Result Test(AP4_Descriptor* descriptor) const {
return descriptor->GetTag() == m_Tag ? AP4_SUCCESS : AP4_FAILURE;
}
-
-private:
+
+ private:
AP4_UI08 m_Tag;
};
@@ -107,9 +103,8 @@ class AP4_DescriptorListWriter : public AP4_List<AP4_Descriptor>::Item::Operator
{
public:
AP4_DescriptorListWriter(AP4_ByteStream& stream) :
- m_Stream(stream) {}
- AP4_Result Action(AP4_Descriptor* descriptor) const
- {
+ m_Stream(stream) {}
+ AP4_Result Action(AP4_Descriptor* descriptor) const {
return descriptor->Write(m_Stream);
}
@@ -122,16 +117,15 @@ private:
+---------------------------------------------------------------------*/
class AP4_DescriptorListInspector : public AP4_List<AP4_Descriptor>::Item::Operator
{
-public:
+ public:
AP4_DescriptorListInspector(AP4_AtomInspector& inspector) :
m_Inspector(inspector) {}
- AP4_Result Action(AP4_Descriptor* descriptor) const
- {
+ AP4_Result Action(AP4_Descriptor* descriptor) const {
descriptor->Inspect(m_Inspector);
return AP4_SUCCESS;
}
-private:
+ private:
AP4_AtomInspector& m_Inspector;
};
diff --git a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4DescriptorFactory.cpp b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4DescriptorFactory.cpp
index a36f16f60..331a2bc23 100644
--- a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4DescriptorFactory.cpp
+++ b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4DescriptorFactory.cpp
@@ -42,8 +42,8 @@
| AP4_DescriptorFactory::CreateDescriptorFromStream
+---------------------------------------------------------------------*/
AP4_Result
-AP4_DescriptorFactory::CreateDescriptorFromStream(AP4_ByteStream& stream,
- AP4_Descriptor*& descriptor)
+AP4_DescriptorFactory::CreateDescriptorFromStream(AP4_ByteStream& stream,
+ AP4_Descriptor*& descriptor)
{
AP4_Result result;
@@ -57,83 +57,78 @@ AP4_DescriptorFactory::CreateDescriptorFromStream(AP4_ByteStream& stream,
// read descriptor tag
unsigned char tag;
result = stream.ReadUI08(tag);
- if(AP4_FAILED(result))
- {
+ if (AP4_FAILED(result)) {
stream.Seek(offset);
return result;
}
-
+
// read descriptor size
unsigned long payload_size = 0;
unsigned int header_size = 1;
unsigned int max = 4;
unsigned char ext = 0;
- do
- {
+ do {
header_size++;
result = stream.ReadUI08(ext);
- if(AP4_FAILED(result))
- {
+ if (AP4_FAILED(result)) {
stream.Seek(offset);
return result;
}
- payload_size = (payload_size << 7) + (ext & 0x7F);
- }
- while(--max && (ext & 0x80));
+ payload_size = (payload_size<<7) + (ext&0x7F);
+ } while (--max && (ext&0x80));
// create the descriptor
- switch(tag)
- {
- case AP4_DESCRIPTOR_TAG_OD:
- case AP4_DESCRIPTOR_TAG_MP4_OD:
+ switch (tag) {
+ case AP4_DESCRIPTOR_TAG_OD:
+ case AP4_DESCRIPTOR_TAG_MP4_OD:
descriptor = new AP4_ObjectDescriptor(stream, tag, header_size, payload_size);
break;
- case AP4_DESCRIPTOR_TAG_IOD:
- case AP4_DESCRIPTOR_TAG_MP4_IOD:
+ case AP4_DESCRIPTOR_TAG_IOD:
+ case AP4_DESCRIPTOR_TAG_MP4_IOD:
descriptor = new AP4_InitialObjectDescriptor(stream, tag, header_size, payload_size);
break;
- case AP4_DESCRIPTOR_TAG_ES_ID_INC:
+ case AP4_DESCRIPTOR_TAG_ES_ID_INC:
descriptor = new AP4_EsIdIncDescriptor(stream, header_size, payload_size);
break;
- case AP4_DESCRIPTOR_TAG_ES_ID_REF:
+ case AP4_DESCRIPTOR_TAG_ES_ID_REF:
descriptor = new AP4_EsIdRefDescriptor(stream, header_size, payload_size);
break;
-
- case AP4_DESCRIPTOR_TAG_ES:
+
+ case AP4_DESCRIPTOR_TAG_ES:
descriptor = new AP4_EsDescriptor(stream, header_size, payload_size);
break;
- case AP4_DESCRIPTOR_TAG_DECODER_CONFIG:
+ case AP4_DESCRIPTOR_TAG_DECODER_CONFIG:
descriptor = new AP4_DecoderConfigDescriptor(stream, header_size, payload_size);
break;
- case AP4_DESCRIPTOR_TAG_DECODER_SPECIFIC_INFO:
- descriptor = new AP4_DecoderSpecificInfoDescriptor(stream, header_size, payload_size);
- break;
-
- case AP4_DESCRIPTOR_TAG_SL_CONFIG:
- if(payload_size != 1) return AP4_ERROR_INVALID_FORMAT;
+ case AP4_DESCRIPTOR_TAG_DECODER_SPECIFIC_INFO:
+ descriptor = new AP4_DecoderSpecificInfoDescriptor(stream, header_size, payload_size);
+ break;
+
+ case AP4_DESCRIPTOR_TAG_SL_CONFIG:
+ if (payload_size != 1) return AP4_ERROR_INVALID_FORMAT;
descriptor = new AP4_SLConfigDescriptor(header_size);
break;
- case AP4_DESCRIPTOR_TAG_IPMP_DESCRIPTOR_POINTER:
+ case AP4_DESCRIPTOR_TAG_IPMP_DESCRIPTOR_POINTER:
descriptor = new AP4_IpmpDescriptorPointer(stream, header_size, payload_size);
break;
-
- case AP4_DESCRIPTOR_TAG_IPMP_DESCRIPTOR:
+
+ case AP4_DESCRIPTOR_TAG_IPMP_DESCRIPTOR:
descriptor = new AP4_IpmpDescriptor(stream, header_size, payload_size);
break;
- default:
+ default:
descriptor = new AP4_UnknownDescriptor(stream, tag, header_size, payload_size);
break;
}
// skip to the end of the descriptor
- stream.Seek(offset + header_size + payload_size);
+ stream.Seek(offset+header_size+payload_size);
return AP4_SUCCESS;
}
diff --git a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4DescriptorFactory.h b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4DescriptorFactory.h
index f76b2fbf5..9fe8bd0c8 100644
--- a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4DescriptorFactory.h
+++ b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4DescriptorFactory.h
@@ -43,12 +43,12 @@ class AP4_Descriptor;
/*----------------------------------------------------------------------
| AP4_DescriptorFactory
+---------------------------------------------------------------------*/
-class AP4_DescriptorFactory
+class AP4_DescriptorFactory
{
-public:
+ public:
// class methods
static AP4_Result CreateDescriptorFromStream(AP4_ByteStream& stream,
- AP4_Descriptor*& descriptor);
+ AP4_Descriptor*& descriptor);
};
#endif // _AP4_DESCRIPTOR_FACTORY_H_
diff --git a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4DrefAtom.cpp b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4DrefAtom.cpp
index f8fd54bc1..df83ecc1e 100644
--- a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4DrefAtom.cpp
+++ b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4DrefAtom.cpp
@@ -1,6 +1,6 @@
/*****************************************************************
|
-| AP4 - dref Atoms
+| AP4 - dref Atoms
|
| Copyright 2002-2008 Axiomatic Systems, LLC
|
@@ -37,15 +37,15 @@
/*----------------------------------------------------------------------
| AP4_DrefAtom::Create
+---------------------------------------------------------------------*/
-AP4_DrefAtom*
+AP4_DrefAtom*
AP4_DrefAtom::Create(AP4_UI32 size,
AP4_ByteStream& stream,
AP4_AtomFactory& atom_factory)
{
AP4_UI32 version;
AP4_UI32 flags;
- if(AP4_FAILED(AP4_Atom::ReadFullHeader(stream, version, flags))) return NULL;
- if(version != 0) return NULL;
+ if (AP4_FAILED(AP4_Atom::ReadFullHeader(stream, version, flags))) return NULL;
+ if (version != 0) return NULL;
return new AP4_DrefAtom(size, version, flags, stream, atom_factory);
}
@@ -56,8 +56,7 @@ AP4_DrefAtom::AP4_DrefAtom(AP4_Atom** refs, AP4_Cardinal refs_count) :
AP4_ContainerAtom(AP4_ATOM_TYPE_DREF, (AP4_UI32)0, (AP4_UI32)0)
{
m_Size32 += 4;
- for(unsigned i = 0; i < refs_count; i++)
- {
+ for (unsigned i=0; i<refs_count; i++) {
m_Children.Add(refs[i]);
m_Size32 += (AP4_UI32)refs[i]->GetSize();
}
@@ -78,14 +77,12 @@ AP4_DrefAtom::AP4_DrefAtom(AP4_UI32 size,
stream.ReadUI32(entry_count);
// read children
- AP4_LargeSize bytes_available = size - AP4_FULL_ATOM_HEADER_SIZE - 4;
- while(entry_count--)
- {
- AP4_Atom* atom;
- while(AP4_SUCCEEDED(atom_factory.CreateAtomFromStream(stream,
- bytes_available,
- atom)))
- {
+ AP4_LargeSize bytes_available = size-AP4_FULL_ATOM_HEADER_SIZE-4;
+ while (entry_count--) {
+ AP4_Atom* atom;
+ while (AP4_SUCCEEDED(atom_factory.CreateAtomFromStream(stream,
+ bytes_available,
+ atom))) {
m_Children.Add(atom);
}
}
@@ -101,7 +98,7 @@ AP4_DrefAtom::WriteFields(AP4_ByteStream& stream)
// write the number of entries
result = stream.WriteUI32(m_Children.ItemCount());
- if(AP4_FAILED(result)) return result;
+ if (AP4_FAILED(result)) return result;
// write the children
return m_Children.Apply(AP4_AtomListWriter(stream));
diff --git a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4DrefAtom.h b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4DrefAtom.h
index 8a248bc93..092e959db 100644
--- a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4DrefAtom.h
+++ b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4DrefAtom.h
@@ -1,6 +1,6 @@
/*****************************************************************
|
-| AP4 - dref Atoms
+| AP4 - dref Atoms
|
| Copyright 2002-2008 Axiomatic Systems, LLC
|
diff --git a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4ElstAtom.cpp b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4ElstAtom.cpp
index 2d8f4ff81..73a2c0920 100644
--- a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4ElstAtom.cpp
+++ b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4ElstAtom.cpp
@@ -1,6 +1,6 @@
/*****************************************************************
|
-| AP4 - elst Atoms
+| AP4 - elst Atoms
|
| Copyright 2002-2008 Axiomatic Systems, LLC
|
@@ -40,15 +40,15 @@ AP4_ElstAtom::Create(AP4_Size size, AP4_ByteStream& stream)
{
AP4_UI32 version;
AP4_UI32 flags;
- if(AP4_FAILED(AP4_Atom::ReadFullHeader(stream, version, flags))) return NULL;
- if(version > 1) return NULL;
+ if (AP4_FAILED(AP4_Atom::ReadFullHeader(stream, version, flags))) return NULL;
+ if (version > 1) return NULL;
return new AP4_ElstAtom(size, version, flags, stream);
}
/*----------------------------------------------------------------------
| AP4_ElstAtom::AP4_ElstAtom
+---------------------------------------------------------------------*/
-AP4_ElstAtom::AP4_ElstAtom(AP4_UI32 size,
+AP4_ElstAtom::AP4_ElstAtom(AP4_UI32 size,
AP4_UI32 version,
AP4_UI32 flags,
AP4_ByteStream& stream) :
@@ -57,12 +57,10 @@ AP4_ElstAtom::AP4_ElstAtom(AP4_UI32 size,
AP4_UI32 entry_count;
stream.ReadUI32(entry_count);
m_Entries.EnsureCapacity(entry_count);
- for(AP4_UI32 i = 0; i < entry_count; i++)
- {
+ for (AP4_UI32 i=0; i<entry_count; i++) {
AP4_UI16 media_rate;
AP4_UI16 zero;
- if(version == 0)
- {
+ if (version == 0) {
AP4_UI32 segment_duration;
AP4_UI32 media_time;
stream.ReadUI32(segment_duration);
@@ -70,9 +68,7 @@ AP4_ElstAtom::AP4_ElstAtom(AP4_UI32 size,
stream.ReadUI16(media_rate);
stream.ReadUI16(zero);
m_Entries.Append(AP4_ElstEntry(segment_duration, media_time, media_rate));
- }
- else
- {
+ } else {
AP4_UI64 segment_duration;
AP4_UI64 media_time;
stream.ReadUI64(segment_duration);
@@ -91,29 +87,25 @@ AP4_Result
AP4_ElstAtom::WriteFields(AP4_ByteStream& stream)
{
AP4_Result result;
-
+
result = stream.WriteUI32(m_Entries.ItemCount());
- if(AP4_FAILED(result)) return result;
- for(AP4_Ordinal i = 0; i < m_Entries.ItemCount(); i++)
- {
- if(m_Version == 0)
- {
+ if (AP4_FAILED(result)) return result;
+ for (AP4_Ordinal i=0; i<m_Entries.ItemCount(); i++) {
+ if (m_Version == 0) {
result = stream.WriteUI32((AP4_UI32)m_Entries[i].m_SegmentDuration);
- if(AP4_FAILED(result)) return result;
+ if (AP4_FAILED(result)) return result;
result = stream.WriteUI32((AP4_UI32)m_Entries[i].m_MediaTime);
- if(AP4_FAILED(result)) return result;
- }
- else
- {
+ if (AP4_FAILED(result)) return result;
+ } else {
result = stream.WriteUI64(m_Entries[i].m_SegmentDuration);
- if(AP4_FAILED(result)) return result;
+ if (AP4_FAILED(result)) return result;
result = stream.WriteUI64(m_Entries[i].m_MediaTime);
- if(AP4_FAILED(result)) return result;
+ if (AP4_FAILED(result)) return result;
}
result = stream.WriteUI16(m_Entries[i].m_MediaRate);
- if(AP4_FAILED(result)) return result;
+ if (AP4_FAILED(result)) return result;
result = stream.WriteUI16(0);
- if(AP4_FAILED(result)) return result;
+ if (AP4_FAILED(result)) return result;
}
return AP4_SUCCESS;
@@ -126,8 +118,7 @@ AP4_Result
AP4_ElstAtom::InspectFields(AP4_AtomInspector& inspector)
{
inspector.AddField("entry count", m_Entries.ItemCount());
- for(AP4_Ordinal i = 0; i < m_Entries.ItemCount(); i++)
- {
+ for (AP4_Ordinal i=0; i<m_Entries.ItemCount(); i++) {
inspector.AddField("entry/segment duration", (AP4_UI32)m_Entries[i].m_SegmentDuration);
inspector.AddField("entry/media time", (AP4_SI32)m_Entries[i].m_MediaTime);
inspector.AddField("entry/media rate", (AP4_UI16)m_Entries[i].m_MediaRate);
diff --git a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4ElstAtom.h b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4ElstAtom.h
index 7c1c76670..d613bf6bd 100644
--- a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4ElstAtom.h
+++ b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4ElstAtom.h
@@ -1,6 +1,6 @@
/*****************************************************************
|
-| AP4 - elst Atoms
+| AP4 - elst Atoms
|
| Copyright 2002-2008 Axiomatic Systems, LLC
|
@@ -44,13 +44,12 @@ class AP4_ByteStream;
/*----------------------------------------------------------------------
| AP4_ElstAtom
+---------------------------------------------------------------------*/
-class AP4_ElstEntry
-{
+class AP4_ElstEntry {
public:
AP4_ElstEntry(AP4_UI64 segment_duration = 0, AP4_SI64 media_time = 0, AP4_UI16 media_rate = 1) :
- m_SegmentDuration(segment_duration),
- m_MediaTime(media_time),
- m_MediaRate(media_rate) {}
+ m_SegmentDuration(segment_duration),
+ m_MediaTime(media_time),
+ m_MediaRate(media_rate) {}
AP4_UI64 m_SegmentDuration;
AP4_SI64 m_MediaTime;
@@ -66,12 +65,12 @@ public:
// methods
virtual AP4_Result InspectFields(AP4_AtomInspector& inspector);
virtual AP4_Result WriteFields(AP4_ByteStream& stream);
-
+
private:
// methods
- AP4_ElstAtom(AP4_UI32 size,
- AP4_UI32 version,
- AP4_UI32 flags,
+ AP4_ElstAtom(AP4_UI32 size,
+ AP4_UI32 version,
+ AP4_UI32 flags,
AP4_ByteStream& stream);
// members
diff --git a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4EsDescriptor.cpp b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4EsDescriptor.cpp
index 04bff732d..065d6f513 100644
--- a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4EsDescriptor.cpp
+++ b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4EsDescriptor.cpp
@@ -46,7 +46,7 @@ AP4_DEFINE_DYNAMIC_CAST_ANCHOR(AP4_EsIdRefDescriptor)
| AP4_EsDescriptor::AP4_EsDescriptor
+---------------------------------------------------------------------*/
AP4_EsDescriptor::AP4_EsDescriptor(AP4_UI16 es_id) :
- AP4_Descriptor(AP4_DESCRIPTOR_TAG_ES, 2, 2 + 1),
+ AP4_Descriptor(AP4_DESCRIPTOR_TAG_ES, 2, 2+1),
m_EsId(es_id),
m_OcrEsId(0),
m_Flags(0),
@@ -58,7 +58,7 @@ AP4_EsDescriptor::AP4_EsDescriptor(AP4_UI16 es_id) :
/*----------------------------------------------------------------------
| AP4_EsDescriptor::AP4_EsDescriptor
+---------------------------------------------------------------------*/
-AP4_EsDescriptor::AP4_EsDescriptor(AP4_ByteStream& stream,
+AP4_EsDescriptor::AP4_EsDescriptor(AP4_ByteStream& stream,
AP4_Size header_size,
AP4_Size payload_size) :
AP4_Descriptor(AP4_DESCRIPTOR_TAG_ES, header_size, payload_size)
@@ -70,25 +70,19 @@ AP4_EsDescriptor::AP4_EsDescriptor(AP4_ByteStream& stream,
stream.ReadUI16(m_EsId);
unsigned char bits;
stream.ReadUI08(bits);
- m_Flags = (bits >> 5) & 7;
- m_StreamPriority = bits & 0x1F;
- if(m_Flags & AP4_ES_DESCRIPTOR_FLAG_STREAM_DEPENDENCY)
- {
+ m_Flags = (bits>>5)&7;
+ m_StreamPriority = bits&0x1F;
+ if (m_Flags & AP4_ES_DESCRIPTOR_FLAG_STREAM_DEPENDENCY) {
stream.ReadUI16(m_DependsOn);
- }
- else
- {
+ } else {
m_DependsOn = 0;
}
- if(m_Flags & AP4_ES_DESCRIPTOR_FLAG_URL)
- {
+ if (m_Flags & AP4_ES_DESCRIPTOR_FLAG_URL) {
unsigned char url_length;
stream.ReadUI08(url_length);
- if(url_length)
- {
+ if (url_length) {
char* url = new char[url_length+1];
- if(url)
- {
+ if (url) {
stream.Read(url, url_length);
url[url_length] = '\0';
m_Url = url;
@@ -96,25 +90,21 @@ AP4_EsDescriptor::AP4_EsDescriptor(AP4_ByteStream& stream,
}
}
}
- if(m_Flags & AP4_ES_DESCRIPTOR_FLAG_URL)
- {
+ if (m_Flags & AP4_ES_DESCRIPTOR_FLAG_URL) {
stream.ReadUI16(m_OcrEsId);
- }
- else
- {
+ } else {
m_OcrEsId = 0;
}
// read other descriptors
AP4_Position offset;
stream.Tell(offset);
- AP4_SubStream* substream = new AP4_SubStream(stream, offset,
- payload_size - AP4_Size(offset - start));
+ AP4_SubStream* substream = new AP4_SubStream(stream, offset,
+ payload_size-AP4_Size(offset-start));
AP4_Descriptor* descriptor = NULL;
- while(AP4_DescriptorFactory::CreateDescriptorFromStream(*substream,
- descriptor)
- == AP4_SUCCESS)
- {
+ while (AP4_DescriptorFactory::CreateDescriptorFromStream(*substream,
+ descriptor)
+ == AP4_SUCCESS) {
m_SubDescriptors.Add(descriptor);
}
substream->Release();
@@ -138,32 +128,29 @@ AP4_EsDescriptor::WriteFields(AP4_ByteStream& stream)
// es id
result = stream.WriteUI16(m_EsId);
- if(AP4_FAILED(result)) return result;
+ if (AP4_FAILED(result)) return result;
// flags and other bits
- AP4_UI08 bits = m_StreamPriority | (AP4_UI08)(m_Flags << 5);
+ AP4_UI08 bits = m_StreamPriority | (AP4_UI08)(m_Flags<<5);
result = stream.WriteUI08(bits);
- if(AP4_FAILED(result)) return result;
-
+ if (AP4_FAILED(result)) return result;
+
// optional fields
- if(m_Flags & AP4_ES_DESCRIPTOR_FLAG_STREAM_DEPENDENCY)
- {
+ if (m_Flags & AP4_ES_DESCRIPTOR_FLAG_STREAM_DEPENDENCY) {
result = stream.WriteUI16(m_DependsOn);
- if(AP4_FAILED(result)) return result;
+ if (AP4_FAILED(result)) return result;
}
- if(m_Flags & AP4_ES_DESCRIPTOR_FLAG_URL)
- {
+ if (m_Flags & AP4_ES_DESCRIPTOR_FLAG_URL) {
result = stream.WriteUI08((AP4_UI08)m_Url.GetLength());
- if(AP4_FAILED(result)) return result;
+ if (AP4_FAILED(result)) return result;
result = stream.WriteString(m_Url.GetChars());
- if(AP4_FAILED(result)) return result;
+ if (AP4_FAILED(result)) return result;
result = stream.WriteUI08(0);
- if(AP4_FAILED(result)) return result;
+ if (AP4_FAILED(result)) return result;
}
- if(m_Flags & AP4_ES_DESCRIPTOR_FLAG_OCR_STREAM)
- {
+ if (m_Flags & AP4_ES_DESCRIPTOR_FLAG_OCR_STREAM) {
result = stream.WriteUI16(m_OcrEsId);
- if(AP4_FAILED(result)) return result;
+ if (AP4_FAILED(result)) return result;
}
// write the sub descriptors
@@ -179,8 +166,8 @@ AP4_Result
AP4_EsDescriptor::Inspect(AP4_AtomInspector& inspector)
{
char info[64];
- AP4_FormatString(info, sizeof(info), "size=%ld+%ld",
- GetHeaderSize(), m_PayloadSize);
+ AP4_FormatString(info, sizeof(info), "size=%ld+%ld",
+ GetHeaderSize(),m_PayloadSize);
inspector.StartElement("[ESDescriptor]", info);
inspector.AddField("es_id", m_EsId);
inspector.AddField("stream_priority", m_StreamPriority);
@@ -213,17 +200,14 @@ AP4_EsDescriptor::GetDecoderConfigDescriptor() const
{
// find the decoder config descriptor
AP4_Descriptor* descriptor = NULL;
- AP4_Result result =
+ AP4_Result result =
m_SubDescriptors.Find(AP4_DescriptorFinder(AP4_DESCRIPTOR_TAG_DECODER_CONFIG),
descriptor);
-
+
// return it
- if(AP4_SUCCEEDED(result))
- {
+ if (AP4_SUCCEEDED(result)) {
return AP4_DYNAMIC_CAST(AP4_DecoderConfigDescriptor, descriptor);
- }
- else
- {
+ } else {
return NULL;
}
}
@@ -240,9 +224,9 @@ AP4_EsIdIncDescriptor::AP4_EsIdIncDescriptor(AP4_UI32 track_id) :
/*----------------------------------------------------------------------
| AP4_EsIdIncDescriptor::AP4_EsIdIncDescriptor
+---------------------------------------------------------------------*/
-AP4_EsIdIncDescriptor::AP4_EsIdIncDescriptor(AP4_ByteStream& stream,
- AP4_Size header_size,
- AP4_Size payload_size) :
+AP4_EsIdIncDescriptor::AP4_EsIdIncDescriptor(AP4_ByteStream& stream,
+ AP4_Size header_size,
+ AP4_Size payload_size) :
AP4_Descriptor(AP4_DESCRIPTOR_TAG_ES_ID_INC, header_size, payload_size)
{
// read the track id
@@ -266,12 +250,12 @@ AP4_Result
AP4_EsIdIncDescriptor::Inspect(AP4_AtomInspector& inspector)
{
char info[64];
- AP4_FormatString(info, sizeof(info), "size=%ld+%ld",
- GetHeaderSize(), m_PayloadSize);
+ AP4_FormatString(info, sizeof(info), "size=%ld+%ld",
+ GetHeaderSize(),m_PayloadSize);
inspector.StartElement("[ES_ID_Inc]", info);
inspector.AddField("track_id", m_TrackId);
inspector.EndElement();
-
+
return AP4_SUCCESS;
}
@@ -287,9 +271,9 @@ AP4_EsIdRefDescriptor::AP4_EsIdRefDescriptor(AP4_UI16 ref_index) :
/*----------------------------------------------------------------------
| AP4_EsIdRefDescriptor::AP4_EsIdRefDescriptor
+---------------------------------------------------------------------*/
-AP4_EsIdRefDescriptor::AP4_EsIdRefDescriptor(AP4_ByteStream& stream,
- AP4_Size header_size,
- AP4_Size payload_size) :
+AP4_EsIdRefDescriptor::AP4_EsIdRefDescriptor(AP4_ByteStream& stream,
+ AP4_Size header_size,
+ AP4_Size payload_size) :
AP4_Descriptor(AP4_DESCRIPTOR_TAG_ES_ID_REF, header_size, payload_size)
{
// read the ref index
@@ -313,11 +297,11 @@ AP4_Result
AP4_EsIdRefDescriptor::Inspect(AP4_AtomInspector& inspector)
{
char info[64];
- AP4_FormatString(info, sizeof(info), "size=%ld+%ld",
- GetHeaderSize(), m_PayloadSize);
+ AP4_FormatString(info, sizeof(info), "size=%ld+%ld",
+ GetHeaderSize(),m_PayloadSize);
inspector.StartElement("[ES_ID_Ref]", info);
inspector.AddField("ref_index", m_RefIndex);
inspector.EndElement();
-
+
return AP4_SUCCESS;
}
diff --git a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4EsDescriptor.h b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4EsDescriptor.h
index 584d79a60..d971e7e05 100644
--- a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4EsDescriptor.h
+++ b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4EsDescriptor.h
@@ -1,6 +1,6 @@
/*****************************************************************
|
-| AP4 - ES Descriptor
+| AP4 - ES Descriptor
|
| Copyright 2002-2008 Axiomatic Systems, LLC
|
@@ -58,21 +58,21 @@ const int AP4_ES_DESCRIPTOR_FLAG_OCR_STREAM = 4;
+---------------------------------------------------------------------*/
class AP4_EsDescriptor : public AP4_Descriptor
{
-public:
+ public:
AP4_IMPLEMENT_DYNAMIC_CAST_D(AP4_EsDescriptor, AP4_Descriptor)
// methods
AP4_EsDescriptor(AP4_UI16 es_id);
- AP4_EsDescriptor(AP4_ByteStream& stream,
- AP4_Size header_size,
+ AP4_EsDescriptor(AP4_ByteStream& stream,
+ AP4_Size header_size,
AP4_Size payload_size);
~AP4_EsDescriptor();
virtual AP4_Result AddSubDescriptor(AP4_Descriptor* descriptor);
virtual AP4_Result WriteFields(AP4_ByteStream& stream);
virtual AP4_Result Inspect(AP4_AtomInspector& inspector);
- virtual const AP4_DecoderConfigDescriptor* GetDecoderConfigDescriptor() const;
+ virtual const AP4_DecoderConfigDescriptor* GetDecoderConfigDescriptor() const;
-private:
+ private:
// members
unsigned short m_EsId;
unsigned short m_OcrEsId;
@@ -88,24 +88,21 @@ private:
+---------------------------------------------------------------------*/
class AP4_EsIdIncDescriptor : public AP4_Descriptor
{
-public:
+ public:
AP4_IMPLEMENT_DYNAMIC_CAST_D(AP4_EsIdIncDescriptor, AP4_Descriptor)
// methods
AP4_EsIdIncDescriptor(AP4_UI32 track_id);
- AP4_EsIdIncDescriptor(AP4_ByteStream& stream,
- AP4_Size header_size,
+ AP4_EsIdIncDescriptor(AP4_ByteStream& stream,
+ AP4_Size header_size,
AP4_Size payload_size);
virtual AP4_Result WriteFields(AP4_ByteStream& stream);
virtual AP4_Result Inspect(AP4_AtomInspector& inspector);
// accessors
- AP4_UI32 GetTrackId() const
- {
- return m_TrackId;
- }
-
-private:
+ AP4_UI32 GetTrackId() const { return m_TrackId; }
+
+ private:
// members
AP4_UI32 m_TrackId;
};
@@ -115,24 +112,21 @@ private:
+---------------------------------------------------------------------*/
class AP4_EsIdRefDescriptor : public AP4_Descriptor
{
-public:
+ public:
AP4_IMPLEMENT_DYNAMIC_CAST_D(AP4_EsIdRefDescriptor, AP4_Descriptor)
// methods
AP4_EsIdRefDescriptor(AP4_UI16 ref_index);
- AP4_EsIdRefDescriptor(AP4_ByteStream& stream,
- AP4_Size header_size,
+ AP4_EsIdRefDescriptor(AP4_ByteStream& stream,
+ AP4_Size header_size,
AP4_Size payload_size);
virtual AP4_Result WriteFields(AP4_ByteStream& stream);
virtual AP4_Result Inspect(AP4_AtomInspector& inspector);
// accessors
- AP4_UI16 GetRefIndex() const
- {
- return m_RefIndex;
- }
-
-private:
+ AP4_UI16 GetRefIndex() const { return m_RefIndex; }
+
+ private:
// members
AP4_UI16 m_RefIndex;
};
diff --git a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4EsdsAtom.cpp b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4EsdsAtom.cpp
index c2937eef6..b03e73a91 100644
--- a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4EsdsAtom.cpp
+++ b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4EsdsAtom.cpp
@@ -1,6 +1,6 @@
/*****************************************************************
|
-| AP4 - esds Atoms
+| AP4 - esds Atoms
|
| Copyright 2002-2008 Axiomatic Systems, LLC
|
@@ -46,8 +46,8 @@ AP4_EsdsAtom::Create(AP4_Size size, AP4_ByteStream& stream)
{
AP4_UI32 version;
AP4_UI32 flags;
- if(AP4_FAILED(AP4_Atom::ReadFullHeader(stream, version, flags))) return NULL;
- if(version != 0) return NULL;
+ if (AP4_FAILED(AP4_Atom::ReadFullHeader(stream, version, flags))) return NULL;
+ if (version != 0) return NULL;
return new AP4_EsdsAtom(size, version, flags, stream);
}
@@ -58,13 +58,13 @@ AP4_EsdsAtom::AP4_EsdsAtom(AP4_EsDescriptor* descriptor) :
AP4_Atom(AP4_ATOM_TYPE_ESDS, AP4_FULL_ATOM_HEADER_SIZE, 0, 0),
m_EsDescriptor(descriptor)
{
- if(m_EsDescriptor) m_Size32 += m_EsDescriptor->GetSize();
+ if (m_EsDescriptor) m_Size32 += m_EsDescriptor->GetSize();
}
/*----------------------------------------------------------------------
| AP4_EsdsAtom::AP4_EsdsAtom
+---------------------------------------------------------------------*/
-AP4_EsdsAtom::AP4_EsdsAtom(AP4_UI32 size,
+AP4_EsdsAtom::AP4_EsdsAtom(AP4_UI32 size,
AP4_UI32 version,
AP4_UI32 flags,
AP4_ByteStream& stream) :
@@ -72,13 +72,10 @@ AP4_EsdsAtom::AP4_EsdsAtom(AP4_UI32 size,
{
// read descriptor
AP4_Descriptor* descriptor = NULL;
- if(AP4_DescriptorFactory::CreateDescriptorFromStream(stream, descriptor)
- == AP4_SUCCESS)
- {
+ if (AP4_DescriptorFactory::CreateDescriptorFromStream(stream, descriptor)
+ == AP4_SUCCESS) {
m_EsDescriptor = AP4_DYNAMIC_CAST(AP4_EsDescriptor, descriptor);
- }
- else
- {
+ } else {
m_EsDescriptor = NULL;
}
}
@@ -98,7 +95,7 @@ AP4_Result
AP4_EsdsAtom::WriteFields(AP4_ByteStream& stream)
{
// write the es descriptor
- if(m_EsDescriptor) return m_EsDescriptor->Write(stream);
+ if (m_EsDescriptor) return m_EsDescriptor->Write(stream);
return AP4_SUCCESS;
}
@@ -110,8 +107,7 @@ AP4_Result
AP4_EsdsAtom::InspectFields(AP4_AtomInspector& inspector)
{
// inspect descriptor
- if(m_EsDescriptor)
- {
+ if (m_EsDescriptor) {
m_EsDescriptor->Inspect(inspector);
}
diff --git a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4EsdsAtom.h b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4EsdsAtom.h
index 2eeff20a8..962f9e2c3 100644
--- a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4EsdsAtom.h
+++ b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4EsdsAtom.h
@@ -1,6 +1,6 @@
/*****************************************************************
|
-| AP4 - esds Atoms
+| AP4 - esds Atoms
|
| Copyright 2002-2008 Axiomatic Systems, LLC
|
@@ -54,17 +54,14 @@ public:
// methods
AP4_EsdsAtom(AP4_EsDescriptor* descriptor);
- ~AP4_EsdsAtom();
+ ~AP4_EsdsAtom();
virtual AP4_Result WriteFields(AP4_ByteStream& stream);
virtual AP4_Result InspectFields(AP4_AtomInspector& inspector);
- const AP4_EsDescriptor* GetEsDescriptor() const
- {
- return m_EsDescriptor;
- }
+ const AP4_EsDescriptor* GetEsDescriptor() const { return m_EsDescriptor; }
private:
// methods
- AP4_EsdsAtom(AP4_UI32 size,
+ AP4_EsdsAtom(AP4_UI32 size,
AP4_UI32 version,
AP4_UI32 flags,
AP4_ByteStream& stream);
diff --git a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4Expandable.cpp b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4Expandable.cpp
index d6a5d1373..a0fa39601 100644
--- a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4Expandable.cpp
+++ b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4Expandable.cpp
@@ -42,23 +42,23 @@ AP4_Expandable::MinHeaderSize(AP4_Size payload_size)
{
// compute how many bytes are needed to encode the payload size
// plus tag
- return 2 + (payload_size / 128);
+ return 2+(payload_size/128);
}
/*----------------------------------------------------------------------
| AP4_Expandable::AP4_Expandable
+---------------------------------------------------------------------*/
AP4_Expandable::AP4_Expandable(AP4_UI32 class_id,
- ClassIdSize class_id_size,
- AP4_Size header_size,
+ ClassIdSize class_id_size,
+ AP4_Size header_size,
AP4_Size payload_size) :
m_ClassId(class_id),
m_ClassIdSize(class_id_size),
m_HeaderSize(header_size),
m_PayloadSize(payload_size)
{
- AP4_ASSERT(header_size >= 1 + 1);
- AP4_ASSERT(header_size <= 1 + 4);
+ AP4_ASSERT(header_size >= 1+1);
+ AP4_ASSERT(header_size <= 1+4);
}
/*----------------------------------------------------------------------
@@ -70,38 +70,36 @@ AP4_Expandable::Write(AP4_ByteStream& stream)
AP4_Result result;
// write the class id
- switch(m_ClassIdSize)
- {
- case CLASS_ID_SIZE_08:
- result = stream.WriteUI08((AP4_UI08)m_ClassId);
- if(AP4_FAILED(result)) return result;
- break;
-
- default:
- return AP4_ERROR_INTERNAL;
+ switch (m_ClassIdSize) {
+ case CLASS_ID_SIZE_08:
+ result = stream.WriteUI08((AP4_UI08)m_ClassId);
+ if (AP4_FAILED(result)) return result;
+ break;
+
+ default:
+ return AP4_ERROR_INTERNAL;
}
-
+
// write the size
- AP4_ASSERT(m_HeaderSize - 1 <= 8);
+ AP4_ASSERT(m_HeaderSize-1 <= 8);
AP4_ASSERT(m_HeaderSize >= 2);
unsigned int size = m_PayloadSize;
unsigned char bytes[8];
// last bytes of the encoded size
- bytes[m_HeaderSize-2] = size & 0x7F;
+ bytes[m_HeaderSize-2] = size&0x7F;
// leading bytes of the encoded size
- for(int i = m_HeaderSize - 3; i >= 0; i--)
- {
+ for (int i=m_HeaderSize-3; i>=0; i--) {
// move to the next 7 bits
size >>= 7;
// output a byte with a top bit marker
- bytes[i] = (size & 0x7F) | 0x80;
+ bytes[i] = (size&0x7F) | 0x80;
}
- result = stream.Write(bytes, m_HeaderSize - 1);
- if(AP4_FAILED(result)) return result;
+ result = stream.Write(bytes, m_HeaderSize-1);
+ if (AP4_FAILED(result)) return result;
// write the fields
WriteFields(stream);
diff --git a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4Expandable.h b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4Expandable.h
index beba263f0..63949eeb5 100644
--- a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4Expandable.h
+++ b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4Expandable.h
@@ -1,6 +1,6 @@
/*****************************************************************
|
-| AP4 - Expandable base class
+| AP4 - Expandable base class
|
| Copyright 2002-2008 Axiomatic Systems, LLC
|
@@ -46,39 +46,29 @@ class AP4_AtomInspector;
+---------------------------------------------------------------------*/
class AP4_Expandable
{
-public:
+ public:
// types
- enum ClassIdSize
- {
+ enum ClassIdSize {
CLASS_ID_SIZE_08
};
-
+
// class methods
static AP4_Size MinHeaderSize(AP4_Size payload_size);
// methods
- AP4_Expandable(AP4_UI32 class_id,
- ClassIdSize class_id_size,
- AP4_Size header_size,
+ AP4_Expandable(AP4_UI32 class_id,
+ ClassIdSize class_id_size,
+ AP4_Size header_size,
AP4_Size payload_size);
virtual ~AP4_Expandable() {}
- AP4_UI32 GetClassId()
- {
- return m_ClassId;
- }
- AP4_Size GetSize()
- {
- return m_PayloadSize + m_HeaderSize;
- }
- AP4_Size GetHeaderSize()
- {
- return m_HeaderSize;
- }
+ AP4_UI32 GetClassId() { return m_ClassId; }
+ AP4_Size GetSize() { return m_PayloadSize+m_HeaderSize; }
+ AP4_Size GetHeaderSize() { return m_HeaderSize; }
virtual AP4_Result Write(AP4_ByteStream& stream);
virtual AP4_Result WriteFields(AP4_ByteStream& stream) = 0;
virtual AP4_Result Inspect(AP4_AtomInspector& inspector);
-protected:
+ protected:
// members
AP4_UI32 m_ClassId;
ClassIdSize m_ClassIdSize;
@@ -89,17 +79,17 @@ protected:
/*----------------------------------------------------------------------
| AP4_UnknownExpandable
+---------------------------------------------------------------------*/
-class AP4_UnknownExpandable : public AP4_Expandable
+class AP4_UnknownExpandable : public AP4_Expandable
{
public:
// methods
- AP4_UnknownExpandable(AP4_ByteStream& stream,
+ AP4_UnknownExpandable(AP4_ByteStream& stream,
AP4_UI32 class_id,
ClassIdSize class_id_size,
AP4_Size header_size,
AP4_Size payload_size);
virtual AP4_Result WriteFields(AP4_ByteStream& stream);
-
+
private:
// members
AP4_DataBuffer m_Data;
diff --git a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4File.cpp b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4File.cpp
index d8bfe3ddc..baedd893a 100644
--- a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4File.cpp
+++ b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4File.cpp
@@ -53,7 +53,7 @@ AP4_File::AP4_File(AP4_Movie* movie) :
/*----------------------------------------------------------------------
| AP4_File::AP4_File
+---------------------------------------------------------------------*/
-AP4_File::AP4_File(AP4_ByteStream& stream,
+AP4_File::AP4_File(AP4_ByteStream& stream,
AP4_AtomFactory& atom_factory,
bool moov_only) :
m_Movie(NULL),
@@ -65,30 +65,28 @@ AP4_File::AP4_File(AP4_ByteStream& stream,
AP4_Atom* atom;
AP4_Position stream_position;
bool keep_parsing = true;
- while(keep_parsing &&
- AP4_SUCCEEDED(stream.Tell(stream_position)) &&
- AP4_SUCCEEDED(atom_factory.CreateAtomFromStream(stream, atom)))
- {
+ while (keep_parsing &&
+ AP4_SUCCEEDED(stream.Tell(stream_position)) &&
+ AP4_SUCCEEDED(atom_factory.CreateAtomFromStream(stream, atom))) {
AddChild(atom);
- switch(atom->GetType())
- {
- case AP4_ATOM_TYPE_MOOV:
- m_Movie = new AP4_Movie(AP4_DYNAMIC_CAST(AP4_MoovAtom, atom), stream, false);
- if(moov_only) keep_parsing = false;
- break;
+ switch (atom->GetType()) {
+ case AP4_ATOM_TYPE_MOOV:
+ m_Movie = new AP4_Movie(AP4_DYNAMIC_CAST(AP4_MoovAtom, atom), stream, false);
+ if (moov_only) keep_parsing = false;
+ break;
- case AP4_ATOM_TYPE_FTYP:
- m_FileType = AP4_DYNAMIC_CAST(AP4_FtypAtom, atom);
- break;
+ case AP4_ATOM_TYPE_FTYP:
+ m_FileType = AP4_DYNAMIC_CAST(AP4_FtypAtom, atom);
+ break;
- case AP4_ATOM_TYPE_MDAT:
- // see if we are before the moov atom
- if(m_Movie == NULL) m_MoovIsBeforeMdat = false;
- break;
+ case AP4_ATOM_TYPE_MDAT:
+ // see if we are before the moov atom
+ if (m_Movie == NULL) m_MoovIsBeforeMdat = false;
+ break;
}
}
}
-
+
/*----------------------------------------------------------------------
| AP4_File::~AP4_File
+---------------------------------------------------------------------*/
@@ -105,7 +103,7 @@ AP4_Result
AP4_File::Inspect(AP4_AtomInspector& inspector)
{
// dump the moov atom first
- if(m_Movie) m_Movie->Inspect(inspector);
+ if (m_Movie) m_Movie->Inspect(inspector);
// dump the other atoms
m_Children.Apply(AP4_AtomListInspector(inspector));
@@ -122,17 +120,16 @@ AP4_File::SetFileType(AP4_UI32 major_brand,
AP4_UI32* compatible_brands,
AP4_Cardinal compatible_brand_count)
{
- if(m_FileType)
- {
+ if (m_FileType) {
RemoveChild(m_FileType);
delete m_FileType;
}
- m_FileType = new AP4_FtypAtom(major_brand,
+ m_FileType = new AP4_FtypAtom(major_brand,
minor_version,
compatible_brands,
compatible_brand_count);
AddChild(m_FileType, 0);
-
+
return AP4_SUCCESS;
}
@@ -142,8 +139,7 @@ AP4_File::SetFileType(AP4_UI32 major_brand,
const AP4_MetaData*
AP4_File::GetMetaData()
{
- if(m_MetaData == NULL)
- {
+ if (m_MetaData == NULL) {
m_MetaData = new AP4_MetaData(this);
}
diff --git a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4File.h b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4File.h
index 94364e968..180c31819 100644
--- a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4File.h
+++ b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4File.h
@@ -1,6 +1,6 @@
/*****************************************************************
|
-| AP4 - File
+| AP4 - File
|
| Copyright 2002-2008 Axiomatic Systems, LLC
|
@@ -48,20 +48,20 @@ class AP4_MetaData;
/*----------------------------------------------------------------------
| file type/brands
+---------------------------------------------------------------------*/
-const AP4_UI32 AP4_FILE_BRAND_QT__ = AP4_ATOM_TYPE('q', 't', ' ', ' ');
-const AP4_UI32 AP4_FILE_BRAND_ISOM = AP4_ATOM_TYPE('i', 's', 'o', 'm');
-const AP4_UI32 AP4_FILE_BRAND_MP41 = AP4_ATOM_TYPE('m', 'p', '4', '1');
-const AP4_UI32 AP4_FILE_BRAND_MP42 = AP4_ATOM_TYPE('m', 'p', '4', '2');
-const AP4_UI32 AP4_FILE_BRAND_3GP1 = AP4_ATOM_TYPE('3', 'g', 'p', '1');
-const AP4_UI32 AP4_FILE_BRAND_3GP2 = AP4_ATOM_TYPE('3', 'g', 'p', '2');
-const AP4_UI32 AP4_FILE_BRAND_3GP3 = AP4_ATOM_TYPE('3', 'g', 'p', '3');
-const AP4_UI32 AP4_FILE_BRAND_3GP4 = AP4_ATOM_TYPE('3', 'g', 'p', '4');
-const AP4_UI32 AP4_FILE_BRAND_3GP5 = AP4_ATOM_TYPE('3', 'g', 'p', '5');
-const AP4_UI32 AP4_FILE_BRAND_3G2A = AP4_ATOM_TYPE('3', 'g', '2', 'a');
-const AP4_UI32 AP4_FILE_BRAND_MMP4 = AP4_ATOM_TYPE('m', 'm', 'p', '4');
-const AP4_UI32 AP4_FILE_BRAND_M4A_ = AP4_ATOM_TYPE('M', '4', 'A', ' ');
-const AP4_UI32 AP4_FILE_BRAND_M4P_ = AP4_ATOM_TYPE('M', '4', 'P', ' ');
-const AP4_UI32 AP4_FILE_BRAND_MJP2 = AP4_ATOM_TYPE('m', 'j', 'p', '2');
+const AP4_UI32 AP4_FILE_BRAND_QT__ = AP4_ATOM_TYPE('q','t',' ',' ');
+const AP4_UI32 AP4_FILE_BRAND_ISOM = AP4_ATOM_TYPE('i','s','o','m');
+const AP4_UI32 AP4_FILE_BRAND_MP41 = AP4_ATOM_TYPE('m','p','4','1');
+const AP4_UI32 AP4_FILE_BRAND_MP42 = AP4_ATOM_TYPE('m','p','4','2');
+const AP4_UI32 AP4_FILE_BRAND_3GP1 = AP4_ATOM_TYPE('3','g','p','1');
+const AP4_UI32 AP4_FILE_BRAND_3GP2 = AP4_ATOM_TYPE('3','g','p','2');
+const AP4_UI32 AP4_FILE_BRAND_3GP3 = AP4_ATOM_TYPE('3','g','p','3');
+const AP4_UI32 AP4_FILE_BRAND_3GP4 = AP4_ATOM_TYPE('3','g','p','4');
+const AP4_UI32 AP4_FILE_BRAND_3GP5 = AP4_ATOM_TYPE('3','g','p','5');
+const AP4_UI32 AP4_FILE_BRAND_3G2A = AP4_ATOM_TYPE('3','g','2','a');
+const AP4_UI32 AP4_FILE_BRAND_MMP4 = AP4_ATOM_TYPE('m','m','p','4');
+const AP4_UI32 AP4_FILE_BRAND_M4A_ = AP4_ATOM_TYPE('M','4','A',' ');
+const AP4_UI32 AP4_FILE_BRAND_M4P_ = AP4_ATOM_TYPE('M','4','P',' ');
+const AP4_UI32 AP4_FILE_BRAND_MJP2 = AP4_ATOM_TYPE('m','j','p','2');
/*----------------------------------------------------------------------
| AP4_File
@@ -71,8 +71,7 @@ const AP4_UI32 AP4_FILE_BRAND_MJP2 = AP4_ATOM_TYPE('m', 'j', 'p', '2');
* The AP4_File object is the top level object for MP4 Files.
*/
-class AP4_File : public AP4_AtomParent
-{
+class AP4_File : public AP4_AtomParent {
public:
// constructors and destructor
/**
@@ -87,64 +86,52 @@ public:
* @param factory the atom factory that will be used to parse the stream
* @param moov_only indicates whether parsing of the atoms should stop
* when the moov atom is found or if all atoms should be parsed until the
- * end of the file.
+ * end of the file.
*/
- AP4_File(AP4_ByteStream& stream,
+ AP4_File(AP4_ByteStream& stream,
AP4_AtomFactory& atom_factory = AP4_DefaultAtomFactory::Instance,
bool moov_only = false);
/**
- * Destroys the AP4_File instance
+ * Destroys the AP4_File instance
*/
virtual ~AP4_File();
-
+
/**
* Get the top level atoms of the file
*/
- AP4_List<AP4_Atom>& GetTopLevelAtoms()
- {
- return m_Children;
- }
+ AP4_List<AP4_Atom>& GetTopLevelAtoms() { return m_Children; }
- /**
+ /**
* Get the AP4_Movie object of this file
*/
- AP4_Movie* GetMovie()
- {
- return m_Movie;
- }
-
+ AP4_Movie* GetMovie() { return m_Movie; }
+
/**
* Get the file type atom of this file
*/
- AP4_FtypAtom* GetFileType()
- {
- return m_FileType;
- }
+ AP4_FtypAtom* GetFileType() { return m_FileType; }
/**
- * Set the file type. Will internally create an AP4_Ftyp atom
- * and attach it to the file
+ * Set the file type. Will internally create an AP4_Ftyp atom
+ * and attach it to the file
*/
AP4_Result SetFileType(AP4_UI32 major_brand,
AP4_UI32 minor_version,
AP4_UI32* compatible_brands = NULL,
AP4_Cardinal compatible_brand_count = 0);
- /**
+ /**
* Ask whether the moov atom appears before the first mdat atom
*/
- bool IsMoovBeforeMdat() const
- {
- return m_MoovIsBeforeMdat;
- }
-
- /**
+ bool IsMoovBeforeMdat() const { return m_MoovIsBeforeMdat; }
+
+ /**
* Get the file's metadata description
*/
const AP4_MetaData* GetMetaData();
-
+
/**
* Inspect the content of the file with an AP4_AtomInspector
*/
diff --git a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4FileByteStream.h b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4FileByteStream.h
index 4a43e008c..f7d82706e 100644
--- a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4FileByteStream.h
+++ b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4FileByteStream.h
@@ -1,6 +1,6 @@
/*****************************************************************
|
-| AP4 - FileByteStream
+| AP4 - FileByteStream
|
| Copyright 2002-2008 Axiomatic Systems, LLC
|
@@ -43,8 +43,7 @@ class AP4_FileByteStream: public AP4_ByteStream
{
public:
// types
- typedef enum
- {
+ typedef enum {
STREAM_MODE_READ = 0,
STREAM_MODE_WRITE = 1,
STREAM_MODE_READ_WRITE = 2
@@ -61,10 +60,10 @@ public:
* it cannot
*/
static AP4_Result Create(const char* name, Mode mode, AP4_ByteStream*& stream);
-
+
// constructors
AP4_FileByteStream(AP4_ByteStream* delegate) : m_Delegate(delegate) {}
-
+
#if !defined(AP4_CONFIG_NO_EXCEPTIONS)
/**
* @deprecated
@@ -73,49 +72,28 @@ public:
#endif
// AP4_ByteStream methods
- AP4_Result ReadPartial(void* buffer,
- AP4_Size bytesToRead,
- AP4_Size& bytesRead)
- {
+ AP4_Result ReadPartial(void* buffer,
+ AP4_Size bytesToRead,
+ AP4_Size& bytesRead) {
return m_Delegate->ReadPartial(buffer, bytesToRead, bytesRead);
}
- AP4_Result WritePartial(const void* buffer,
- AP4_Size bytesToWrite,
- AP4_Size& bytesWritten)
- {
+ AP4_Result WritePartial(const void* buffer,
+ AP4_Size bytesToWrite,
+ AP4_Size& bytesWritten) {
return m_Delegate->WritePartial(buffer, bytesToWrite, bytesWritten);
}
- AP4_Result Seek(AP4_Position position)
- {
- return m_Delegate->Seek(position);
- }
- AP4_Result Tell(AP4_Position& position)
- {
- return m_Delegate->Tell(position);
- }
- AP4_Result GetSize(AP4_LargeSize& size)
- {
- return m_Delegate->GetSize(size);
- }
- AP4_Result Flush()
- {
- return m_Delegate->Flush();
- }
+ AP4_Result Seek(AP4_Position position) { return m_Delegate->Seek(position); }
+ AP4_Result Tell(AP4_Position& position) { return m_Delegate->Tell(position); }
+ AP4_Result GetSize(AP4_LargeSize& size) { return m_Delegate->GetSize(size); }
+ AP4_Result Flush() { return m_Delegate->Flush(); }
// AP4_Referenceable methods
- void AddReference()
- {
- m_Delegate->AddReference();
- }
- void Release()
- {
- m_Delegate->Release();
- }
+ void AddReference() { m_Delegate->AddReference(); }
+ void Release() { m_Delegate->Release(); }
protected:
// methods
- virtual ~AP4_FileByteStream()
- {
+ virtual ~AP4_FileByteStream() {
delete m_Delegate;
}
diff --git a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4FileCopier.cpp b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4FileCopier.cpp
index fdb90f82a..626763539 100644
--- a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4FileCopier.cpp
+++ b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4FileCopier.cpp
@@ -42,10 +42,9 @@ AP4_Result
AP4_FileCopier::Write(AP4_File& file, AP4_ByteStream& stream)
{
// write the top-level atoms
- for(AP4_List<AP4_Atom>::Item* item = file.GetTopLevelAtoms().FirstItem();
- item;
- item = item->GetNext())
- {
+ for (AP4_List<AP4_Atom>::Item* item = file.GetTopLevelAtoms().FirstItem();
+ item;
+ item = item->GetNext()) {
AP4_Atom* atom = item->GetData();
atom->Write(stream);
}
diff --git a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4FileCopier.h b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4FileCopier.h
index d6be4c3ff..320177eaf 100644
--- a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4FileCopier.h
+++ b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4FileCopier.h
@@ -43,8 +43,7 @@ class AP4_File;
/*----------------------------------------------------------------------
| AP4_FileCopier
+---------------------------------------------------------------------*/
-class AP4_FileCopier
-{
+class AP4_FileCopier {
public:
// class methods
static AP4_Result Write(AP4_File& file, AP4_ByteStream& stream);
diff --git a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4FileWriter.cpp b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4FileWriter.cpp
index 48ce0bcc1..c7e8090cc 100644
--- a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4FileWriter.cpp
+++ b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4FileWriter.cpp
@@ -50,90 +50,84 @@ AP4_FileWriter::Write(AP4_File& file, AP4_ByteStream& stream, Interleaving /* in
AP4_FtypAtom* file_type = file.GetFileType();
// write the ftyp atom (always first)
- if(file_type) file_type->Write(stream);
+ if (file_type) file_type->Write(stream);
// write the top-level atoms, except for ftyp, moov and mdat
- for(AP4_List<AP4_Atom>::Item* atom_item = file.GetChildren().FirstItem();
- atom_item;
- atom_item = atom_item->GetNext())
- {
+ for (AP4_List<AP4_Atom>::Item* atom_item = file.GetChildren().FirstItem();
+ atom_item;
+ atom_item = atom_item->GetNext()) {
AP4_Atom* atom = atom_item->GetData();
- if(atom->GetType() != AP4_ATOM_TYPE_MDAT &&
- atom->GetType() != AP4_ATOM_TYPE_FTYP &&
- atom->GetType() != AP4_ATOM_TYPE_MOOV)
- {
+ if (atom->GetType() != AP4_ATOM_TYPE_MDAT &&
+ atom->GetType() != AP4_ATOM_TYPE_FTYP &&
+ atom->GetType() != AP4_ATOM_TYPE_MOOV) {
atom->Write(stream);
}
}
-
+
// get the movie object (and stop if there isn't any)
AP4_Movie* movie = file.GetMovie();
- if(movie == NULL) return AP4_SUCCESS;
+ if (movie == NULL) return AP4_SUCCESS;
// see how much we've written so far
AP4_Position position;
stream.Tell(position);
-
+
// backup and recompute all the chunk offsets
- unsigned int t = 0;
+ unsigned int t=0;
AP4_Result result = AP4_SUCCESS;
AP4_UI64 mdat_size = AP4_ATOM_HEADER_SIZE;
- AP4_UI64 mdat_position = position + movie->GetMoovAtom()->GetSize();
+ AP4_UI64 mdat_position = position+movie->GetMoovAtom()->GetSize();
AP4_Array<AP4_Array<AP4_UI64>*> trak_chunk_offsets_backup;
AP4_Array<AP4_UI64> chunk_offsets;
- for(AP4_List<AP4_Track>::Item* track_item = movie->GetTracks().FirstItem();
- track_item;
- track_item = track_item->GetNext())
- {
+ for (AP4_List<AP4_Track>::Item* track_item = movie->GetTracks().FirstItem();
+ track_item;
+ track_item = track_item->GetNext()) {
AP4_Track* track = track_item->GetData();
AP4_TrakAtom* trak = track->GetTrakAtom();
-
+
// backup the chunk offsets
AP4_Array<AP4_UI64>* chunk_offsets_backup = new AP4_Array<AP4_UI64>();
trak_chunk_offsets_backup.Append(chunk_offsets_backup);
result = trak->GetChunkOffsets(*chunk_offsets_backup);
- if(AP4_FAILED(result)) goto end;
+ if (AP4_FAILED(result)) goto end;
// allocate space for the new chunk offsets
chunk_offsets.SetItemCount(chunk_offsets_backup->ItemCount());
-
+
// compute the new chunk offsets
AP4_Cardinal sample_count = track->GetSampleCount();
AP4_SampleTable* sample_table = track->GetSampleTable();
AP4_Sample sample;
- for(AP4_Ordinal i = 0; i < sample_count; i++)
- {
+ for (AP4_Ordinal i=0; i<sample_count; i++) {
AP4_Ordinal chunk_index = 0;
AP4_Ordinal position_in_chunk = 0;
sample_table->GetSampleChunkPosition(i, chunk_index, position_in_chunk);
sample_table->GetSample(i, sample);
- if(position_in_chunk == 0)
- {
+ if (position_in_chunk == 0) {
// this sample is the first sample in a chunk, so this is the start of a chunk
- if(chunk_index >= chunk_offsets.ItemCount()) return AP4_ERROR_INTERNAL;
- chunk_offsets[chunk_index] = mdat_position + mdat_size;
+ if (chunk_index >= chunk_offsets.ItemCount()) return AP4_ERROR_INTERNAL;
+ chunk_offsets[chunk_index] = mdat_position+mdat_size;
}
mdat_size += sample.GetSize();
- }
+ }
result = trak->SetChunkOffsets(chunk_offsets);
}
-
+
// write the moov atom
movie->GetMoovAtom()->Write(stream);
-
+
// create and write the media data (mdat)
// FIXME: this only supports 32-bit mdat size
stream.WriteUI32((AP4_UI32)mdat_size);
stream.WriteUI32(AP4_ATOM_TYPE_MDAT);
-
+
// write all tracks and restore the chunk offsets to their backed-up values
- for(AP4_List<AP4_Track>::Item* track_item = movie->GetTracks().FirstItem();
- track_item;
- track_item = track_item->GetNext(), ++t)
- {
+ for (AP4_List<AP4_Track>::Item* track_item = movie->GetTracks().FirstItem();
+ track_item;
+ track_item = track_item->GetNext(), ++t) {
AP4_Track* track = track_item->GetData();
AP4_TrakAtom* trak = track->GetTrakAtom();
-
+
// restore the backed-up chunk offsets
result = trak->SetChunkOffsets(*trak_chunk_offsets_backup[t]);
@@ -141,18 +135,16 @@ AP4_FileWriter::Write(AP4_File& file, AP4_ByteStream& stream, Interleaving /* in
AP4_Cardinal sample_count = track->GetSampleCount();
AP4_Sample sample;
AP4_DataBuffer sample_data;
- for(AP4_Ordinal i = 0; i < sample_count; i++)
- {
+ for (AP4_Ordinal i=0; i<sample_count; i++) {
track->ReadSample(i, sample, sample_data);
stream.Write(sample_data.GetData(), sample_data.GetDataSize());
}
}
end:
- for(unsigned int i = 0; i < trak_chunk_offsets_backup.ItemCount(); i++)
- {
+ for (unsigned int i=0; i<trak_chunk_offsets_backup.ItemCount(); i++) {
delete trak_chunk_offsets_backup[i];
}
-
+
return result;
}
diff --git a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4FileWriter.h b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4FileWriter.h
index d5d34dd20..4c5c75391 100644
--- a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4FileWriter.h
+++ b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4FileWriter.h
@@ -43,20 +43,18 @@ class AP4_File;
/*----------------------------------------------------------------------
| AP4_FileWriter
+---------------------------------------------------------------------*/
-class AP4_FileWriter
-{
+class AP4_FileWriter {
public:
// types
- typedef enum
- {
+ typedef enum {
INTERLEAVING_SEQUENTIAL
} Interleaving;
-
+
// class methods
- static AP4_Result Write(AP4_File& file,
- AP4_ByteStream& stream,
+ static AP4_Result Write(AP4_File& file,
+ AP4_ByteStream& stream,
Interleaving interleaving = INTERLEAVING_SEQUENTIAL);
-
+
private:
// don't instantiate this class
AP4_FileWriter() {}
diff --git a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4FragmentSampleTable.cpp b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4FragmentSampleTable.cpp
index b77e00bf7..ce862f388 100644
--- a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4FragmentSampleTable.cpp
+++ b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4FragmentSampleTable.cpp
@@ -41,50 +41,46 @@
/*----------------------------------------------------------------------
| AP4_FragmentSampleTable::AP4_FragmentSampleTable
+---------------------------------------------------------------------*/
-AP4_FragmentSampleTable::AP4_FragmentSampleTable(AP4_ContainerAtom* traf,
- AP4_TrexAtom* trex,
- AP4_ByteStream* sample_stream,
- AP4_Position moof_offset,
- AP4_Position mdat_payload_offset,
- AP4_UI64 dts_origin)
+AP4_FragmentSampleTable::AP4_FragmentSampleTable(AP4_ContainerAtom* traf,
+ AP4_TrexAtom* trex,
+ AP4_ByteStream* sample_stream,
+ AP4_Position moof_offset,
+ AP4_Position mdat_payload_offset,
+ AP4_UI64 dts_origin)
{
AP4_TfhdAtom* tfhd = AP4_DYNAMIC_CAST(AP4_TfhdAtom, traf->GetChild(AP4_ATOM_TYPE_TFHD));
- if(tfhd == NULL) return;
-
+ if (tfhd == NULL) return;
+
// count all the samples and reserve space for them
unsigned int sample_count = 0;
- for(AP4_List<AP4_Atom>::Item* item = traf->GetChildren().FirstItem();
- item;
- item = item->GetNext())
- {
+ for (AP4_List<AP4_Atom>::Item* item = traf->GetChildren().FirstItem();
+ item;
+ item = item->GetNext()) {
AP4_Atom* atom = item->GetData();
- if(atom->GetType() == AP4_ATOM_TYPE_TRUN)
- {
+ if (atom->GetType() == AP4_ATOM_TYPE_TRUN) {
AP4_TrunAtom* trun = AP4_DYNAMIC_CAST(AP4_TrunAtom, atom);
sample_count += trun->GetEntries().ItemCount();
}
- }
+ }
m_Samples.EnsureCapacity(sample_count);
-
+
// process all the trun atoms
- for(AP4_List<AP4_Atom>::Item* item = traf->GetChildren().FirstItem();
- item;
- item = item->GetNext())
- {
+ for (AP4_List<AP4_Atom>::Item* item = traf->GetChildren().FirstItem();
+ item;
+ item = item->GetNext()) {
AP4_Atom* atom = item->GetData();
- if(atom->GetType() == AP4_ATOM_TYPE_TRUN)
- {
+ if (atom->GetType() == AP4_ATOM_TYPE_TRUN) {
AP4_TrunAtom* trun = AP4_DYNAMIC_CAST(AP4_TrunAtom, atom);
- AP4_Result result = AddTrun(trun,
- tfhd,
- trex,
- sample_stream,
+ AP4_Result result = AddTrun(trun,
+ tfhd,
+ trex,
+ sample_stream,
moof_offset,
mdat_payload_offset,
dts_origin);
- if(AP4_FAILED(result)) return;
+ if (AP4_FAILED(result)) return;
}
- }
+ }
}
/*----------------------------------------------------------------------
@@ -98,8 +94,8 @@ AP4_FragmentSampleTable::~AP4_FragmentSampleTable()
| AP4_FragmentSampleTable::AddTrun
+---------------------------------------------------------------------*/
AP4_Result
-AP4_FragmentSampleTable::AddTrun(AP4_TrunAtom* trun,
- AP4_TfhdAtom* tfhd,
+AP4_FragmentSampleTable::AddTrun(AP4_TrunAtom* trun,
+ AP4_TfhdAtom* tfhd,
AP4_TrexAtom* trex,
AP4_ByteStream* sample_stream,
AP4_Position moof_offset,
@@ -108,155 +104,120 @@ AP4_FragmentSampleTable::AddTrun(AP4_TrunAtom* trun,
{
AP4_Flags tfhd_flags = tfhd->GetFlags();
AP4_Flags trun_flags = trun->GetFlags();
-
+
// update the number of samples
unsigned int start = m_Samples.ItemCount();
m_Samples.SetItemCount(start + trun->GetEntries().ItemCount());
-
+
// base data offset
AP4_Position data_offset = 0;
- if(tfhd_flags & AP4_TFHD_FLAG_BASE_DATA_OFFSET_PRESENT)
- {
+ if (tfhd_flags & AP4_TFHD_FLAG_BASE_DATA_OFFSET_PRESENT) {
data_offset = tfhd->GetBaseDataOffset();
- }
- else
- {
+ } else {
data_offset = moof_offset;
}
- if(trun_flags & AP4_TRUN_FLAG_DATA_OFFSET_PRESENT)
- {
+ if (trun_flags & AP4_TRUN_FLAG_DATA_OFFSET_PRESENT) {
data_offset += trun->GetDataOffset();
- }
+ }
// MS hack
- if(data_offset == moof_offset)
- {
+ if (data_offset == moof_offset) {
data_offset = payload_offset;
- }
- else
- {
+ } else {
payload_offset = data_offset;
}
-
+
// sample description index
AP4_UI32 sample_description_index = 0;
- if(tfhd_flags & AP4_TFHD_FLAG_SAMPLE_DESCRIPTION_INDEX_PRESENT)
- {
+ if (tfhd_flags & AP4_TFHD_FLAG_SAMPLE_DESCRIPTION_INDEX_PRESENT) {
sample_description_index = tfhd->GetSampleDescriptionIndex();
- }
- else if(trex)
- {
+ } else if (trex) {
sample_description_index = trex->GetDefaultSampleDescriptionIndex();
- }
-
+ }
+
// default sample size
AP4_UI32 default_sample_size = 0;
- if(tfhd_flags & AP4_TFHD_FLAG_DEFAULT_SAMPLE_SIZE_PRESENT)
- {
+ if (tfhd_flags & AP4_TFHD_FLAG_DEFAULT_SAMPLE_SIZE_PRESENT) {
default_sample_size = tfhd->GetDefaultSampleSize();
- }
- else if(trex)
- {
+ } else if (trex) {
default_sample_size = trex->GetDefaultSampleSize();
}
-
+
// default sample duration
AP4_UI32 default_sample_duration = 0;
- if(tfhd_flags & AP4_TFHD_FLAG_DEFAULT_SAMPLE_DURATION_PRESENT)
- {
+ if (tfhd_flags & AP4_TFHD_FLAG_DEFAULT_SAMPLE_DURATION_PRESENT) {
default_sample_duration = tfhd->GetDefaultSampleDuration();
- }
- else if(trex)
- {
+ } else if (trex) {
default_sample_duration = trex->GetDefaultSampleDuration();
}
-
+
// default sample flags
AP4_UI32 default_sample_flags = 0;
- if(tfhd_flags & AP4_TFHD_FLAG_DEFAULT_SAMPLE_FLAGS_PRESENT)
- {
+ if (tfhd_flags & AP4_TFHD_FLAG_DEFAULT_SAMPLE_FLAGS_PRESENT) {
default_sample_flags = tfhd->GetDefaultSampleFlags();
- }
- else if(trex)
- {
+ } else if (trex) {
default_sample_flags = trex->GetDefaultSampleFlags();
}
// parse all trun entries to setup the samples
AP4_UI64 dts = dts_origin;
- for(unsigned int i = 0; i < trun->GetEntries().ItemCount(); i++)
- {
+ for (unsigned int i=0; i<trun->GetEntries().ItemCount(); i++) {
const AP4_TrunAtom::Entry& entry = trun->GetEntries()[i];
AP4_Sample& sample = m_Samples[start+i];
-
+
// sample size
- if(trun_flags & AP4_TRUN_FLAG_SAMPLE_SIZE_PRESENT)
- {
+ if (trun_flags & AP4_TRUN_FLAG_SAMPLE_SIZE_PRESENT) {
sample.SetSize(entry.sample_size);
- }
- else
- {
+ } else {
sample.SetSize(default_sample_size);
}
payload_offset += sample.GetSize(); // update the payload offset
-
+
// sample duration
- if(trun_flags & AP4_TRUN_FLAG_SAMPLE_DURATION_PRESENT)
- {
+ if (trun_flags & AP4_TRUN_FLAG_SAMPLE_DURATION_PRESENT) {
sample.SetDuration(entry.sample_duration);
- }
- else
- {
+ } else {
sample.SetDuration(default_sample_duration);
}
// sample flags
AP4_UI32 sample_flags = default_sample_flags;
- if(i == 0 && (trun_flags & AP4_TRUN_FLAG_FIRST_SAMPLE_FLAGS_PRESENT))
- {
+ if (i==0 && (trun_flags & AP4_TRUN_FLAG_FIRST_SAMPLE_FLAGS_PRESENT)) {
sample_flags = trun->GetFirstSampleFlags();
- }
- else if(trun_flags & AP4_TRUN_FLAG_SAMPLE_FLAGS_PRESENT)
- {
+ } else if (trun_flags & AP4_TRUN_FLAG_SAMPLE_FLAGS_PRESENT) {
sample_flags = entry.sample_flags;
}
- if((sample_flags & AP4_FRAG_FLAG_SAMPLE_IS_DIFFERENCE) == 0)
- {
+ if ((sample_flags & AP4_FRAG_FLAG_SAMPLE_IS_DIFFERENCE) == 0) {
sample.SetSync(true);
- }
- else
- {
+ } else {
sample.SetSync(false);
}
-
+
// sample description index
sample.SetDescriptionIndex(sample_description_index);
-
+
// data stream
- if(sample_stream) sample.SetDataStream(*sample_stream);
-
+ if (sample_stream) sample.SetDataStream(*sample_stream);
+
// data offset
sample.SetOffset(data_offset);
data_offset += sample.GetSize();
-
+
// dts and cts
sample.SetDts(dts);
- if(trun_flags & AP4_TRUN_FLAG_SAMPLE_COMPOSITION_TIME_OFFSET_PRESENT)
- {
- sample.SetCts(dts + entry.sample_composition_time_offset);
- }
- else
- {
+ if (trun_flags & AP4_TRUN_FLAG_SAMPLE_COMPOSITION_TIME_OFFSET_PRESENT) {
+ sample.SetCts(dts+entry.sample_composition_time_offset);
+ } else {
sample.SetCts(dts);
}
-
+
// update the counters
dts += sample.GetDuration();
m_Duration += sample.GetDuration();
}
-
+
// update the dts
dts_origin = dts;
-
+
return AP4_SUCCESS;
}
@@ -264,10 +225,10 @@ AP4_FragmentSampleTable::AddTrun(AP4_TrunAtom* trun,
| AP4_FragmentSampleTable::GetSample
+---------------------------------------------------------------------*/
AP4_Result
-AP4_FragmentSampleTable::GetSample(AP4_Ordinal index,
+AP4_FragmentSampleTable::GetSample(AP4_Ordinal index,
AP4_Sample& sample)
{
- if(index >= m_Samples.ItemCount()) return AP4_ERROR_OUT_OF_RANGE;
+ if (index >= m_Samples.ItemCount()) return AP4_ERROR_OUT_OF_RANGE;
// copy the sample
sample = m_Samples[index];
@@ -305,23 +266,23 @@ AP4_FragmentSampleTable::GetSampleDescriptionCount()
/*----------------------------------------------------------------------
| AP4_AtomSampleTable::GetSampleChunkPosition
+---------------------------------------------------------------------*/
-AP4_Result
-AP4_FragmentSampleTable::GetSampleChunkPosition(AP4_Ordinal sample_index,
- AP4_Ordinal& chunk_index,
- AP4_Ordinal& position_in_chunk)
+AP4_Result
+AP4_FragmentSampleTable::GetSampleChunkPosition(AP4_Ordinal sample_index,
+ AP4_Ordinal& chunk_index,
+ AP4_Ordinal& position_in_chunk)
{
chunk_index = 0;
position_in_chunk = sample_index;
-
+
return AP4_SUCCESS;
}
/*----------------------------------------------------------------------
| AP4_FragmentSampleTable::GetSampleIndexForTimeStamp
+---------------------------------------------------------------------*/
-AP4_Result
-AP4_FragmentSampleTable::GetSampleIndexForTimeStamp(AP4_UI64 /*ts*/,
- AP4_Ordinal& sample_index)
+AP4_Result
+AP4_FragmentSampleTable::GetSampleIndexForTimeStamp(AP4_UI64 /*ts*/,
+ AP4_Ordinal& sample_index)
{
sample_index = 0; // FIXME
return AP4_SUCCESS;
@@ -330,7 +291,7 @@ AP4_FragmentSampleTable::GetSampleIndexForTimeStamp(AP4_UI64 /*ts*/,
/*----------------------------------------------------------------------
| AP4_FragmentSampleTable::GetNearestSyncSampleIndex
+---------------------------------------------------------------------*/
-AP4_Ordinal
+AP4_Ordinal
AP4_FragmentSampleTable::GetNearestSyncSampleIndex(AP4_Ordinal /*sample_index*/, bool /*before*/)
{
return 0; // FIXME
diff --git a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4FragmentSampleTable.h b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4FragmentSampleTable.h
index 3c16eb60a..0c626bcb5 100644
--- a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4FragmentSampleTable.h
+++ b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4FragmentSampleTable.h
@@ -50,14 +50,14 @@ class AP4_TfhdAtom;
+---------------------------------------------------------------------*/
class AP4_FragmentSampleTable : public AP4_SampleTable
{
-public:
+ public:
// methods
- AP4_FragmentSampleTable(AP4_ContainerAtom* traf,
- AP4_TrexAtom* trex,
- AP4_ByteStream* sample_stream,
- AP4_Position moof_offset,
- AP4_Position mdat_payload_offset, // hack because MS doesn't implement the spec correctly
- AP4_UI64 dts_origin = 0);
+ AP4_FragmentSampleTable(AP4_ContainerAtom* traf,
+ AP4_TrexAtom* trex,
+ AP4_ByteStream* sample_stream,
+ AP4_Position moof_offset,
+ AP4_Position mdat_payload_offset, // hack because MS doesn't implement the spec correctly
+ AP4_UI64 dts_origin=0);
virtual ~AP4_FragmentSampleTable();
// AP4_SampleTable methods
@@ -65,28 +65,25 @@ public:
virtual AP4_Cardinal GetSampleCount();
virtual AP4_SampleDescription* GetSampleDescription(AP4_Ordinal sd_index);
virtual AP4_Cardinal GetSampleDescriptionCount();
- virtual AP4_Result GetSampleChunkPosition(AP4_Ordinal sample_index,
- AP4_Ordinal& chunk_index,
- AP4_Ordinal& position_in_chunk);
+ virtual AP4_Result GetSampleChunkPosition(AP4_Ordinal sample_index,
+ AP4_Ordinal& chunk_index,
+ AP4_Ordinal& position_in_chunk);
virtual AP4_Result GetSampleIndexForTimeStamp(AP4_UI64 ts, AP4_Ordinal& sample_index);
- virtual AP4_Ordinal GetNearestSyncSampleIndex(AP4_Ordinal index, bool before = true);
+ virtual AP4_Ordinal GetNearestSyncSampleIndex(AP4_Ordinal index, bool before=true);
// methods
- AP4_UI64 GetDuration()
- {
- return m_Duration;
- }
-
+ AP4_UI64 GetDuration() { return m_Duration; }
+
private:
// members
AP4_TrunAtom* m_TrunAtom;
AP4_Array<AP4_Sample> m_Samples;
AP4_UI64 m_Duration;
-
+
// methods
- AP4_Result AddTrun(AP4_TrunAtom* trun,
- AP4_TfhdAtom* tfhd,
- AP4_TrexAtom* trex,
+ AP4_Result AddTrun(AP4_TrunAtom* trun,
+ AP4_TfhdAtom* tfhd,
+ AP4_TrexAtom* trex,
AP4_ByteStream* sample_stream,
AP4_Position moof_offset,
AP4_Position& payload_offset,
diff --git a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4FrmaAtom.cpp b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4FrmaAtom.cpp
index 8b8fbef11..cfaef69b3 100644
--- a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4FrmaAtom.cpp
+++ b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4FrmaAtom.cpp
@@ -1,6 +1,6 @@
/*****************************************************************
|
-| AP4 - frma Atoms
+| AP4 - frma Atoms
|
| Copyright 2002-2008 Axiomatic Systems, LLC
|
@@ -37,7 +37,7 @@
| AP4_FrmaAtom::AP4_FrmaAtom
+---------------------------------------------------------------------*/
AP4_FrmaAtom::AP4_FrmaAtom(AP4_UI32 original_format) :
- AP4_Atom(AP4_ATOM_TYPE_FRMA, AP4_ATOM_HEADER_SIZE + 4),
+ AP4_Atom(AP4_ATOM_TYPE_FRMA, AP4_ATOM_HEADER_SIZE+4),
m_OriginalFormat(original_format)
{
}
diff --git a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4FrmaAtom.h b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4FrmaAtom.h
index 3542ab234..c6ea77a08 100644
--- a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4FrmaAtom.h
+++ b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4FrmaAtom.h
@@ -1,6 +1,6 @@
/*****************************************************************
|
-| AP4 - frma Atoms
+| AP4 - frma Atoms
|
| Copyright 2002-2008 Axiomatic Systems, LLC
|
@@ -47,21 +47,17 @@ class AP4_FrmaAtom : public AP4_Atom
{
public:
// class methods
- static AP4_FrmaAtom* Create(AP4_Size size, AP4_ByteStream& stream)
- {
+ static AP4_FrmaAtom* Create(AP4_Size size, AP4_ByteStream& stream) {
return new AP4_FrmaAtom(size, stream);
}
- // constructors
+ // constructors
AP4_FrmaAtom(AP4_UI32 original_format);
// methods
virtual AP4_Result InspectFields(AP4_AtomInspector& inspector);
virtual AP4_Result WriteFields(AP4_ByteStream& stream);
- AP4_UI32 GetOriginalFormat()
- {
- return m_OriginalFormat;
- }
+ AP4_UI32 GetOriginalFormat() { return m_OriginalFormat; }
private:
// methods
diff --git a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4FtabAtom.cpp b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4FtabAtom.cpp
index 96cfe24b4..287238ebd 100644
--- a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4FtabAtom.cpp
+++ b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4FtabAtom.cpp
@@ -38,27 +38,27 @@
AP4_FtabAtom::AP4_FtabAtom(AP4_Size size,
AP4_ByteStream& stream)
- : AP4_Atom(AP4_ATOM_TYPE_FTAB)
+ : AP4_Atom(AP4_ATOM_TYPE_FTAB)
{
- AP4_UI16 entryCount;
+ AP4_UI16 entryCount;
stream.ReadUI16(entryCount);
- m_FontRecords.EnsureCapacity(entryCount);
+ m_FontRecords.EnsureCapacity(entryCount);
- while(entryCount--)
- {
- AP4_Tx3gFontRecord fontRecord;
+ while(entryCount--)
+ {
+ AP4_Tx3gFontRecord fontRecord;
- stream.ReadUI16(fontRecord.Id);
+ stream.ReadUI16(fontRecord.Id);
- AP4_UI08 len;
- stream.ReadUI08(len);
+ AP4_UI08 len;
+ stream.ReadUI08(len);
- char buff[256];
- stream.ReadString(buff, len + 1);
+ char buff[256];
+ stream.ReadString(buff, len+1);
- fontRecord.Name = buff;
+ fontRecord.Name = buff;
- m_FontRecords.Append(fontRecord);
- }
+ m_FontRecords.Append(fontRecord);
+ }
}
diff --git a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4FtabAtom.h b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4FtabAtom.h
index 78b2b65ae..0845347d5 100644
--- a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4FtabAtom.h
+++ b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4FtabAtom.h
@@ -42,43 +42,37 @@
class AP4_FtabAtom : public AP4_Atom
{
public:
- AP4_FtabAtom(AP4_Size size,
+ AP4_FtabAtom(AP4_Size size,
AP4_ByteStream& stream);
- AP4_Result WriteFields(AP4_ByteStream& stream)
- {
- return AP4_FAILURE;
- }
+ AP4_Result WriteFields(AP4_ByteStream& stream) { return AP4_FAILURE; }
- struct AP4_Tx3gFontRecord
- {
- AP4_UI16 Id;
- AP4_String Name;
- };
+ struct AP4_Tx3gFontRecord
+ {
+ AP4_UI16 Id;
+ AP4_String Name;
+ };
- AP4_Array<AP4_Tx3gFontRecord>& GetFontRecords()
- {
- return m_FontRecords;
- }
+ AP4_Array<AP4_Tx3gFontRecord>& GetFontRecords() { return m_FontRecords; }
- AP4_Result LookupFont(AP4_UI16 Id, AP4_String& Name)
- {
- for(unsigned long i = 0; i < m_FontRecords.ItemCount(); i++)
- {
- if(m_FontRecords[i].Id == Id)
- {
- Name = m_FontRecords[i].Name;
- return AP4_SUCCESS;
- }
- }
+ AP4_Result LookupFont(AP4_UI16 Id, AP4_String& Name)
+ {
+ for(unsigned long i = 0; i < m_FontRecords.ItemCount(); i++)
+ {
+ if(m_FontRecords[i].Id == Id)
+ {
+ Name = m_FontRecords[i].Name;
+ return AP4_SUCCESS;
+ }
+ }
- return AP4_FAILURE;
- }
+ return AP4_FAILURE;
+ }
private:
- // members
- AP4_Array<AP4_Tx3gFontRecord> m_FontRecords;
+ // members
+ AP4_Array<AP4_Tx3gFontRecord> m_FontRecords;
};
#endif // _AP4_FTAB_ATOM_H_
diff --git a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4FtypAtom.cpp b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4FtypAtom.cpp
index 511827cca..8bd20f0cc 100644
--- a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4FtypAtom.cpp
+++ b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4FtypAtom.cpp
@@ -1,6 +1,6 @@
/*****************************************************************
|
-| AP4 - ftyp Atoms
+| AP4 - ftyp Atoms
|
| Copyright 2002-2008 Axiomatic Systems, LLC
|
@@ -47,8 +47,7 @@ AP4_FtypAtom::AP4_FtypAtom(AP4_UI32 size, AP4_ByteStream& stream) :
stream.ReadUI32(m_MajorBrand);
stream.ReadUI32(m_MinorVersion);
size -= 16;
- while(size)
- {
+ while (size) {
AP4_UI32 compatible_brand;
stream.ReadUI32(compatible_brand);
m_CompatibleBrands.Append(compatible_brand);
@@ -63,7 +62,7 @@ AP4_FtypAtom::AP4_FtypAtom(AP4_UI32 major_brand,
AP4_UI32 minor_version,
AP4_UI32* compatible_brands,
AP4_Cardinal compatible_brand_count) :
- AP4_Atom(AP4_ATOM_TYPE_FTYP, AP4_ATOM_HEADER_SIZE + 8 + 4 * compatible_brand_count),
+ AP4_Atom(AP4_ATOM_TYPE_FTYP, AP4_ATOM_HEADER_SIZE+8+4*compatible_brand_count),
m_MajorBrand(major_brand),
m_MinorVersion(minor_version),
m_CompatibleBrands(compatible_brands, compatible_brand_count)
@@ -76,9 +75,8 @@ AP4_FtypAtom::AP4_FtypAtom(AP4_UI32 major_brand,
bool
AP4_FtypAtom::HasCompatibleBrand(AP4_UI32 brand)
{
- for(unsigned int i = 0; i < m_CompatibleBrands.ItemCount(); i++)
- {
- if(m_CompatibleBrands[i] == brand) return true;
+ for (unsigned int i=0; i<m_CompatibleBrands.ItemCount(); i++) {
+ if (m_CompatibleBrands[i] == brand) return true;
}
return false;
@@ -91,21 +89,20 @@ AP4_Result
AP4_FtypAtom::WriteFields(AP4_ByteStream& stream)
{
AP4_Result result;
-
+
// major brand
result = stream.WriteUI32(m_MajorBrand);
- if(AP4_FAILED(result)) return result;
+ if (AP4_FAILED(result)) return result;
// minor version
result = stream.WriteUI32(m_MinorVersion);
- if(AP4_FAILED(result)) return result;
+ if (AP4_FAILED(result)) return result;
// compatible brands
AP4_Cardinal compat_brand_count = m_CompatibleBrands.ItemCount();
- for(AP4_Ordinal i = 0; i < compat_brand_count; i++)
- {
+ for (AP4_Ordinal i=0; i<compat_brand_count; i++) {
result = stream.WriteUI32(m_CompatibleBrands[i]);
- if(AP4_FAILED(result)) return result;
+ if (AP4_FAILED(result)) return result;
}
return result;
@@ -123,8 +120,7 @@ AP4_FtypAtom::InspectFields(AP4_AtomInspector& inspector)
inspector.AddField("minor_version", m_MinorVersion, AP4_AtomInspector::HINT_HEX);
// compatible brands
- for(unsigned int i = 0; i < m_CompatibleBrands.ItemCount(); i++)
- {
+ for (unsigned int i=0; i<m_CompatibleBrands.ItemCount(); i++) {
AP4_UI32 cb = m_CompatibleBrands[i];
AP4_FormatFourChars(name, cb);
inspector.AddField("compatible_brand", name);
diff --git a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4FtypAtom.h b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4FtypAtom.h
index 8e9149476..fe6e2c0f4 100644
--- a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4FtypAtom.h
+++ b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4FtypAtom.h
@@ -1,6 +1,6 @@
/*****************************************************************
|
-| AP4 - ftyp Atoms
+| AP4 - ftyp Atoms
|
| Copyright 2002-2008 Axiomatic Systems, LLC
|
@@ -44,7 +44,7 @@ class AP4_ByteStream;
/*----------------------------------------------------------------------
| constants
+---------------------------------------------------------------------*/
-const AP4_UI32 AP4_FTYP_BRAND_ISOM = AP4_ATOM_TYPE('i', 's', 'o', 'm');
+const AP4_UI32 AP4_FTYP_BRAND_ISOM = AP4_ATOM_TYPE('i','s','o','m');
/*----------------------------------------------------------------------
| AP4_FtypAtom
@@ -55,8 +55,7 @@ public:
AP4_IMPLEMENT_DYNAMIC_CAST_D(AP4_FtypAtom, AP4_Atom)
// class methods
- static AP4_FtypAtom* Create(AP4_Size size, AP4_ByteStream& stream)
- {
+ static AP4_FtypAtom* Create(AP4_Size size, AP4_ByteStream& stream) {
return new AP4_FtypAtom(size, stream);
}
@@ -67,19 +66,12 @@ public:
AP4_Cardinal compatible_brand_count = 0);
virtual AP4_Result InspectFields(AP4_AtomInspector& inspector);
virtual AP4_Result WriteFields(AP4_ByteStream& stream);
-
+
// accessors
- AP4_UI32 GetMajorBrand()
- {
- return m_MajorBrand;
- }
- AP4_UI32 GetMinorVersion()
- {
- return m_MinorVersion;
- }
- AP4_Array<AP4_UI32>& GetCompatibleBrands()
- {
- return m_CompatibleBrands;
+ AP4_UI32 GetMajorBrand() { return m_MajorBrand; }
+ AP4_UI32 GetMinorVersion() { return m_MinorVersion; }
+ AP4_Array<AP4_UI32>& GetCompatibleBrands() {
+ return m_CompatibleBrands;
}
bool HasCompatibleBrand(AP4_UI32 brand);
diff --git a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4GrpiAtom.cpp b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4GrpiAtom.cpp
index d839d8511..f75764a14 100644
--- a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4GrpiAtom.cpp
+++ b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4GrpiAtom.cpp
@@ -1,6 +1,6 @@
/*****************************************************************
|
-| AP4 - ohdr Atoms
+| AP4 - ohdr Atoms
|
| Copyright 2002-2008 Axiomatic Systems, LLC
|
@@ -45,15 +45,15 @@ AP4_GrpiAtom::Create(AP4_Size size, AP4_ByteStream& stream)
{
AP4_UI32 version;
AP4_UI32 flags;
- if(AP4_FAILED(AP4_Atom::ReadFullHeader(stream, version, flags))) return NULL;
- if(version != 0) return NULL;
+ if (AP4_FAILED(AP4_Atom::ReadFullHeader(stream, version, flags))) return NULL;
+ if (version != 0) return NULL;
return new AP4_GrpiAtom(size, version, flags, stream);
}
/*----------------------------------------------------------------------
| AP4_GrpiAtom::AP4_GrpiAtom
+---------------------------------------------------------------------*/
-AP4_GrpiAtom::AP4_GrpiAtom(AP4_UI08 key_encryption_method,
+AP4_GrpiAtom::AP4_GrpiAtom(AP4_UI08 key_encryption_method,
const char* group_id,
const AP4_UI08* group_key,
AP4_Size group_key_length) :
@@ -62,13 +62,13 @@ AP4_GrpiAtom::AP4_GrpiAtom(AP4_UI08 key_encryption_method,
m_GroupId(group_id),
m_GroupKey(group_key, group_key_length)
{
- m_Size32 += 2 + 1 + 2 + m_GroupId.GetLength() + group_key_length;
+ m_Size32 += 2+1+2+m_GroupId.GetLength()+group_key_length;
}
/*----------------------------------------------------------------------
| AP4_GrpiAtom::AP4_GrpiAtom
+---------------------------------------------------------------------*/
-AP4_GrpiAtom::AP4_GrpiAtom(AP4_UI32 size,
+AP4_GrpiAtom::AP4_GrpiAtom(AP4_UI32 size,
AP4_UI32 version,
AP4_UI32 flags,
AP4_ByteStream& stream) :
@@ -80,7 +80,7 @@ AP4_GrpiAtom::AP4_GrpiAtom(AP4_UI32 size,
// encryption method
stream.ReadUI08(m_KeyEncryptionMethod);
-
+
// group key length
AP4_UI16 group_key_length = 0;
stream.ReadUI16(group_key_length);
@@ -107,7 +107,7 @@ AP4_GrpiAtom::WriteFields(AP4_ByteStream& stream)
AP4_CHECK(stream.WriteUI16((AP4_UI16)m_GroupKey.GetDataSize()));
AP4_CHECK(stream.Write(m_GroupId.GetChars(), m_GroupId.GetLength()));
AP4_CHECK(stream.Write(m_GroupKey.GetData(), m_GroupKey.GetDataSize()));
-
+
return AP4_SUCCESS;
}
@@ -119,15 +119,15 @@ AP4_GrpiAtom::InspectFields(AP4_AtomInspector& inspector)
{
inspector.AddField("key encryption method", m_KeyEncryptionMethod);
inspector.AddField("group id", m_GroupId.GetChars());
- inspector.AddField("group key", m_GroupKey.GetData(),
- m_GroupKey.GetDataSize());
+ inspector.AddField("group key", m_GroupKey.GetData(),
+ m_GroupKey.GetDataSize());
return AP4_SUCCESS;
}
/*----------------------------------------------------------------------
| AP4_GrpiAtom::Clone
+---------------------------------------------------------------------*/
-AP4_Atom*
+AP4_Atom*
AP4_GrpiAtom::Clone()
{
return new AP4_GrpiAtom(m_KeyEncryptionMethod,
diff --git a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4GrpiAtom.h b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4GrpiAtom.h
index 9ac2868cd..80aeae6c2 100644
--- a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4GrpiAtom.h
+++ b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4GrpiAtom.h
@@ -46,47 +46,35 @@ public:
AP4_IMPLEMENT_DYNAMIC_CAST_D(AP4_GrpiAtom, AP4_Atom)
// class methods
- static AP4_GrpiAtom* Create(AP4_Size size,
+ static AP4_GrpiAtom* Create(AP4_Size size,
AP4_ByteStream& stream);
// constructor
- AP4_GrpiAtom(AP4_UI08 key_encryption_method,
+ AP4_GrpiAtom(AP4_UI08 key_encryption_method,
const char* group_id,
const AP4_UI08* group_key,
AP4_Size group_key_length);
-
+
// methods
virtual AP4_Result InspectFields(AP4_AtomInspector& inspector);
virtual AP4_Result WriteFields(AP4_ByteStream& stream);
virtual AP4_Atom* Clone();
// accessors
- AP4_UI08 GetKeyEncryptionMethod() const
- {
- return m_KeyEncryptionMethod;
- }
- void SetKeyEncryptionMethod(AP4_UI08 encryption_method)
- {
- m_KeyEncryptionMethod = encryption_method;
- }
- const AP4_String& GetGroupId() const
- {
- return m_GroupId;
- }
- const AP4_DataBuffer& GetGroupKey() const
- {
- return m_GroupKey;
- }
-
+ AP4_UI08 GetKeyEncryptionMethod() const { return m_KeyEncryptionMethod; }
+ void SetKeyEncryptionMethod(AP4_UI08 encryption_method) { m_KeyEncryptionMethod = encryption_method; }
+ const AP4_String& GetGroupId() const { return m_GroupId; }
+ const AP4_DataBuffer& GetGroupKey() const { return m_GroupKey; }
+
private:
// methods
- AP4_GrpiAtom(AP4_UI32 size,
+ AP4_GrpiAtom(AP4_UI32 size,
AP4_UI32 version,
AP4_UI32 flags,
AP4_ByteStream& stream);
// members
- AP4_UI08 m_KeyEncryptionMethod;
+ AP4_UI08 m_KeyEncryptionMethod;
AP4_String m_GroupId;
AP4_DataBuffer m_GroupKey;
};
diff --git a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4HdlrAtom.cpp b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4HdlrAtom.cpp
index c8150ccb7..9a25e3ed3 100644
--- a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4HdlrAtom.cpp
+++ b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4HdlrAtom.cpp
@@ -1,6 +1,6 @@
/*****************************************************************
|
-| AP4 - hdlr Atoms
+| AP4 - hdlr Atoms
|
| Copyright 2002-2008 Axiomatic Systems, LLC
|
@@ -46,8 +46,8 @@ AP4_HdlrAtom::Create(AP4_Size size, AP4_ByteStream& stream)
{
AP4_UI32 version;
AP4_UI32 flags;
- if(AP4_FAILED(AP4_Atom::ReadFullHeader(stream, version, flags))) return NULL;
- if(version != 0) return NULL;
+ if (AP4_FAILED(AP4_Atom::ReadFullHeader(stream, version, flags))) return NULL;
+ if (version != 0) return NULL;
return new AP4_HdlrAtom(size, version, flags, stream);
}
@@ -59,14 +59,14 @@ AP4_HdlrAtom::AP4_HdlrAtom(AP4_Atom::Type hdlr_type, const char* hdlr_name) :
m_HandlerType(hdlr_type),
m_HandlerName(hdlr_name)
{
- m_Size32 += 20 + m_HandlerName.GetLength() + 1;
+ m_Size32 += 20+m_HandlerName.GetLength()+1;
m_Reserved[0] = m_Reserved[1] = m_Reserved[2] = 0;
}
/*----------------------------------------------------------------------
| AP4_HdlrAtom::AP4_HdlrAtom
+---------------------------------------------------------------------*/
-AP4_HdlrAtom::AP4_HdlrAtom(AP4_UI32 size,
+AP4_HdlrAtom::AP4_HdlrAtom(AP4_UI32 size,
AP4_UI32 version,
AP4_UI32 flags,
AP4_ByteStream& stream) :
@@ -78,22 +78,19 @@ AP4_HdlrAtom::AP4_HdlrAtom(AP4_UI32 size,
stream.ReadUI32(m_Reserved[0]);
stream.ReadUI32(m_Reserved[1]);
stream.ReadUI32(m_Reserved[2]);
-
+
// read the name unless it is empty
- int name_size = size - (AP4_FULL_ATOM_HEADER_SIZE + 20);
- if(name_size == 0) return;
+ int name_size = size-(AP4_FULL_ATOM_HEADER_SIZE+20);
+ if (name_size == 0) return;
char* name = new char[name_size+1];
stream.Read(name, name_size);
name[name_size] = '\0'; // force a null termination
// handle a special case: the Quicktime files have a pascal
// string here, but ISO MP4 files have a C string.
// we try to detect a pascal encoding and correct it.
- if(name[0] == name_size - 1)
- {
- m_HandlerName = name + 1;
- }
- else
- {
+ if (name[0] == name_size-1) {
+ m_HandlerName = name+1;
+ } else {
m_HandlerName = name;
}
delete[] name;
@@ -109,29 +106,27 @@ AP4_HdlrAtom::WriteFields(AP4_ByteStream& stream)
// write the data
result = stream.WriteUI32(0); // predefined
- if(AP4_FAILED(result)) return result;
+ if (AP4_FAILED(result)) return result;
result = stream.WriteUI32(m_HandlerType);
- if(AP4_FAILED(result)) return result;
+ if (AP4_FAILED(result)) return result;
result = stream.WriteUI32(m_Reserved[0]);
- if(AP4_FAILED(result)) return result;
+ if (AP4_FAILED(result)) return result;
result = stream.WriteUI32(m_Reserved[1]);
- if(AP4_FAILED(result)) return result;
+ if (AP4_FAILED(result)) return result;
result = stream.WriteUI32(m_Reserved[2]);
- if(AP4_FAILED(result)) return result;
+ if (AP4_FAILED(result)) return result;
AP4_UI08 name_size = (AP4_UI08)m_HandlerName.GetLength();
- if(AP4_FULL_ATOM_HEADER_SIZE + 20 + name_size > m_Size32)
- {
- name_size = m_Size32 - AP4_FULL_ATOM_HEADER_SIZE + 20;
+ if (AP4_FULL_ATOM_HEADER_SIZE+20+name_size > m_Size32) {
+ name_size = m_Size32-AP4_FULL_ATOM_HEADER_SIZE+20;
}
- if(name_size)
- {
+ if (name_size) {
result = stream.Write(m_HandlerName.GetChars(), name_size);
- if(AP4_FAILED(result)) return result;
+ if (AP4_FAILED(result)) return result;
}
// pad with zeros if necessary
- AP4_Size padding = m_Size32 - (AP4_FULL_ATOM_HEADER_SIZE + 20 + name_size);
- while(padding--) stream.WriteUI08(0);
+ AP4_Size padding = m_Size32-(AP4_FULL_ATOM_HEADER_SIZE+20+name_size);
+ while (padding--) stream.WriteUI08(0);
return AP4_SUCCESS;
}
diff --git a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4HdlrAtom.h b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4HdlrAtom.h
index 63080dbcb..c5b1bf135 100644
--- a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4HdlrAtom.h
+++ b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4HdlrAtom.h
@@ -1,6 +1,6 @@
/*****************************************************************
|
-| AP4 - hdlr Atoms
+| AP4 - hdlr Atoms
|
| Copyright 2002-2008 Axiomatic Systems, LLC
|
@@ -43,17 +43,17 @@ class AP4_ByteStream;
/*----------------------------------------------------------------------
| constants
+---------------------------------------------------------------------*/
-const AP4_UI32 AP4_HANDLER_TYPE_SOUN = AP4_ATOM_TYPE('s', 'o', 'u', 'n');
-const AP4_UI32 AP4_HANDLER_TYPE_VIDE = AP4_ATOM_TYPE('v', 'i', 'd', 'e');
-const AP4_UI32 AP4_HANDLER_TYPE_HINT = AP4_ATOM_TYPE('h', 'i', 'n', 't');
-const AP4_UI32 AP4_HANDLER_TYPE_MDIR = AP4_ATOM_TYPE('m', 'd', 'i', 'r');
-const AP4_UI32 AP4_HANDLER_TYPE_TEXT = AP4_ATOM_TYPE('t', 'e', 'x', 't');
-const AP4_UI32 AP4_HANDLER_TYPE_TX3G = AP4_ATOM_TYPE('t', 'x', '3', 'g');
-const AP4_UI32 AP4_HANDLER_TYPE_JPEG = AP4_ATOM_TYPE('j', 'p', 'e', 'g');
-const AP4_UI32 AP4_HANDLER_TYPE_ODSM = AP4_ATOM_TYPE('o', 'd', 's', 'm');
-const AP4_UI32 AP4_HANDLER_TYPE_SDSM = AP4_ATOM_TYPE('s', 'd', 's', 'm');
+const AP4_UI32 AP4_HANDLER_TYPE_SOUN = AP4_ATOM_TYPE('s','o','u','n');
+const AP4_UI32 AP4_HANDLER_TYPE_VIDE = AP4_ATOM_TYPE('v','i','d','e');
+const AP4_UI32 AP4_HANDLER_TYPE_HINT = AP4_ATOM_TYPE('h','i','n','t');
+const AP4_UI32 AP4_HANDLER_TYPE_MDIR = AP4_ATOM_TYPE('m','d','i','r');
+const AP4_UI32 AP4_HANDLER_TYPE_TEXT = AP4_ATOM_TYPE('t','e','x','t');
+const AP4_UI32 AP4_HANDLER_TYPE_TX3G = AP4_ATOM_TYPE('t','x','3','g');
+const AP4_UI32 AP4_HANDLER_TYPE_JPEG = AP4_ATOM_TYPE('j','p','e','g');
+const AP4_UI32 AP4_HANDLER_TYPE_ODSM = AP4_ATOM_TYPE('o','d','s','m');
+const AP4_UI32 AP4_HANDLER_TYPE_SDSM = AP4_ATOM_TYPE('s','d','s','m');
// ==> Start patch MPC
-const AP4_UI32 AP4_HANDLER_TYPE_SUBP = AP4_ATOM_TYPE('s', 'u', 'b', 'p');
+const AP4_UI32 AP4_HANDLER_TYPE_SUBP = AP4_ATOM_TYPE('s','u','b','p');
// <== End patch MPC
/*----------------------------------------------------------------------
@@ -72,18 +72,12 @@ public:
virtual AP4_Result InspectFields(AP4_AtomInspector& inspector);
virtual AP4_Result WriteFields(AP4_ByteStream& stream);
- AP4_UI32 GetHandlerType()
- {
- return m_HandlerType;
- }
- AP4_String GetHandlerName()
- {
- return m_HandlerName;
- }
+ AP4_UI32 GetHandlerType() { return m_HandlerType; }
+ AP4_String GetHandlerName() { return m_HandlerName; }
private:
// methods
- AP4_HdlrAtom(AP4_UI32 size,
+ AP4_HdlrAtom(AP4_UI32 size,
AP4_UI32 version,
AP4_UI32 flags,
AP4_ByteStream& stream);
diff --git a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4HintTrackReader.cpp b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4HintTrackReader.cpp
index 626e18d32..3e35131cb 100644
--- a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4HintTrackReader.cpp
+++ b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4HintTrackReader.cpp
@@ -45,9 +45,9 @@
/*----------------------------------------------------------------------
| AP4_HintTrackReader::AP4_HintTrackReader
+---------------------------------------------------------------------*/
-AP4_HintTrackReader::AP4_HintTrackReader(AP4_Track& hint_track,
- AP4_Movie& movie,
- AP4_UI32 ssrc) :
+AP4_HintTrackReader::AP4_HintTrackReader(AP4_Track& hint_track,
+ AP4_Movie& movie,
+ AP4_UI32 ssrc) :
m_HintTrack(hint_track),
m_MediaTrack(NULL),
m_MediaTimeScale(0),
@@ -62,8 +62,7 @@ AP4_HintTrackReader::AP4_HintTrackReader(AP4_Track& hint_track,
// get the media track
AP4_TrakAtom* hint_trak_atom = hint_track.GetTrakAtom();
AP4_Atom* atom = hint_trak_atom->FindChild("tref/hint");
- if(atom != NULL)
- {
+ if (atom != NULL) {
AP4_UI32 media_track_id = ((AP4_TrefTypeAtom*) atom)->GetTrackIds()[0];
m_MediaTrack = movie.GetTrack(media_track_id);
@@ -82,15 +81,13 @@ AP4_HintTrackReader::AP4_HintTrackReader(AP4_Track& hint_track,
// rtp time scale
atom = hint_trak_atom->FindChild("mdia/minf/stbl/rtp /tims");
- if(atom)
- {
+ if (atom) {
AP4_TimsAtom* tims = (AP4_TimsAtom*)atom;
m_RtpTimeScale = tims->GetTimeScale();
}
// generate a random ssrc if = 0
- if(m_Ssrc == 0)
- {
+ if (m_Ssrc == 0) {
m_Ssrc = rand();
}
@@ -102,23 +99,22 @@ AP4_HintTrackReader::AP4_HintTrackReader(AP4_Track& hint_track,
| AP4_HintTrackReader::Create
+---------------------------------------------------------------------*/
AP4_Result
-AP4_HintTrackReader::Create(AP4_Track& hint_track,
- AP4_Movie& movie,
+AP4_HintTrackReader::Create(AP4_Track& hint_track,
+ AP4_Movie& movie,
AP4_UI32 ssrc,
AP4_HintTrackReader*& reader)
{
// default value
reader = NULL;
-
+
// check the type
- if(hint_track.GetType() != AP4_Track::TYPE_HINT)
- {
+ if (hint_track.GetType() != AP4_Track::TYPE_HINT) {
return AP4_ERROR_INVALID_TRACK_TYPE;
}
-
+
// create a new object
reader = new AP4_HintTrackReader(hint_track, movie, ssrc);
-
+
return AP4_SUCCESS;
}
@@ -138,7 +134,7 @@ AP4_HintTrackReader::GetRtpSample(AP4_Ordinal index)
{
// get the sample
AP4_Result result = m_HintTrack.GetSample(index, m_CurrentHintSample);
- if(AP4_FAILED(result)) return result;
+ if (AP4_FAILED(result)) return result;
// renew the sample data
delete m_RtpSampleData;
@@ -162,7 +158,7 @@ AP4_HintTrackReader::GetRtpSample(AP4_Ordinal index)
AP4_UI32
AP4_HintTrackReader::GetCurrentTimeStampMs()
{
- return (AP4_UI32)AP4_ConvertTime(m_CurrentHintSample.GetCts(),
+ return (AP4_UI32)AP4_ConvertTime(m_CurrentHintSample.GetCts(),
m_HintTrack.GetMediaTimeScale(),
1000);
}
@@ -184,10 +180,10 @@ AP4_Result
AP4_HintTrackReader::GetSdpText(AP4_String& sdp_text)
{
AP4_Atom* sdp_atom = m_HintTrack.GetTrakAtom()->FindChild("udta/hnti/sdp ");
- if(sdp_atom == NULL) return AP4_FAILURE;
+ if (sdp_atom == NULL) return AP4_FAILURE;
// C cast is OK because we know the type of the atom
- sdp_text = ((AP4_SdpAtom*) sdp_atom)->GetSdpText();
+ sdp_text = ((AP4_SdpAtom*) sdp_atom)->GetSdpText();
return AP4_SUCCESS;
}
@@ -195,17 +191,17 @@ AP4_HintTrackReader::GetSdpText(AP4_String& sdp_text)
| AP4_HintTrackReader::SeekToTimeStampMs
+---------------------------------------------------------------------*/
AP4_Result
-AP4_HintTrackReader::SeekToTimeStampMs(AP4_UI32 desired_ts_ms,
+AP4_HintTrackReader::SeekToTimeStampMs(AP4_UI32 desired_ts_ms,
AP4_UI32& actual_ts_ms)
{
// get the sample index
AP4_Cardinal index;
AP4_Result result = m_HintTrack.GetSampleIndexForTimeStampMs(desired_ts_ms, index);
- if(AP4_FAILED(result)) return result;
+ if (AP4_FAILED(result)) return result;
// get the current sample based on the index and renew the sample data
result = GetRtpSample(index);
- if(AP4_FAILED(result)) return result;
+ if (AP4_FAILED(result)) return result;
// set the actual ts
actual_ts_ms = GetCurrentTimeStampMs();
@@ -216,28 +212,27 @@ AP4_HintTrackReader::SeekToTimeStampMs(AP4_UI32 desired_ts_ms,
| AP4_HintTrackReader::GetNextPacket
+---------------------------------------------------------------------*/
AP4_Result
-AP4_HintTrackReader::GetNextPacket(AP4_DataBuffer& packet_data,
+AP4_HintTrackReader::GetNextPacket(AP4_DataBuffer& packet_data,
AP4_UI32& ts_ms)
{
AP4_Result result = AP4_SUCCESS;
// get the next rtp sample if needed
AP4_List<AP4_RtpPacket>* packets = &m_RtpSampleData->GetPackets();
- while(m_PacketIndex == packets->ItemCount()) // while: handle the 0 packet case
- {
+ while (m_PacketIndex == packets->ItemCount()) { // while: handle the 0 packet case
result = GetRtpSample(++m_SampleIndex);
- if(AP4_FAILED(result)) return result;
+ if (AP4_FAILED(result)) return result;
packets = &m_RtpSampleData->GetPackets();
}
// get the packet
AP4_RtpPacket* packet;
result = packets->Get(m_PacketIndex++, packet);
- if(AP4_FAILED(result)) return result;
+ if (AP4_FAILED(result)) return result;
// build it
result = BuildRtpPacket(packet, packet_data);
- if(AP4_FAILED(result)) return result;
+ if (AP4_FAILED(result)) return result;
// set the time stamp
ts_ms = GetCurrentTimeStampMs();
@@ -249,15 +244,15 @@ AP4_HintTrackReader::GetNextPacket(AP4_DataBuffer& packet_data,
| AP4_HintTrackReader::BuildRtpPacket
+---------------------------------------------------------------------*/
AP4_Result
-AP4_HintTrackReader::BuildRtpPacket(AP4_RtpPacket* packet,
+AP4_HintTrackReader::BuildRtpPacket(AP4_RtpPacket* packet,
AP4_DataBuffer& packet_data)
{
// set the data size
AP4_Result result = packet_data.SetDataSize(packet->GetConstructedDataSize());
- if(AP4_FAILED(result)) return result;
+ if (AP4_FAILED(result)) return result;
// now write
- AP4_ByteStream* stream = new AP4_MemoryByteStream(packet_data);
+ AP4_ByteStream* stream = new AP4_MemoryByteStream(packet_data);
// header + ssrc
stream->WriteUI08(0x80 | (packet->GetPBit() << 5) | (packet->GetXBit() << 4));
@@ -266,33 +261,31 @@ AP4_HintTrackReader::BuildRtpPacket(AP4_RtpPacket* packet,
stream->WriteUI32(m_RtpTimeStampStart + (AP4_UI32)m_CurrentHintSample.GetCts() + packet->GetTimeStampOffset());
stream->WriteUI32(m_Ssrc);
- AP4_List<AP4_RtpConstructor>::Item* constructors_it
- = packet->GetConstructors().FirstItem();
- while(constructors_it != NULL)
- {
+ AP4_List<AP4_RtpConstructor>::Item* constructors_it
+ = packet->GetConstructors().FirstItem();
+ while (constructors_it != NULL) {
AP4_RtpConstructor* constructor = constructors_it->GetData();
// add data to the packet according to the constructor
- switch(constructor->GetType())
- {
- case AP4_RTP_CONSTRUCTOR_TYPE_NOOP:
- // nothing to do here
- break;
- case AP4_RTP_CONSTRUCTOR_TYPE_IMMEDIATE:
- result = WriteImmediateRtpData(
- (AP4_ImmediateRtpConstructor*) constructor, stream);
- if(AP4_FAILED(result)) return result;
- break;
- case AP4_RTP_CONSTRUCTOR_TYPE_SAMPLE:
- result = WriteSampleRtpData(
- (AP4_SampleRtpConstructor*) constructor, stream);
- if(AP4_FAILED(result)) return result;
- break;
- case AP4_RTP_CONSTRUCTOR_TYPE_SAMPLE_DESC:
- return AP4_ERROR_NOT_SUPPORTED;
- default:
- // unknown constructor type
- return AP4_FAILURE;
+ switch (constructor->GetType()) {
+ case AP4_RTP_CONSTRUCTOR_TYPE_NOOP:
+ // nothing to do here
+ break;
+ case AP4_RTP_CONSTRUCTOR_TYPE_IMMEDIATE:
+ result = WriteImmediateRtpData(
+ (AP4_ImmediateRtpConstructor*) constructor, stream);
+ if (AP4_FAILED(result)) return result;
+ break;
+ case AP4_RTP_CONSTRUCTOR_TYPE_SAMPLE:
+ result = WriteSampleRtpData(
+ (AP4_SampleRtpConstructor*) constructor, stream);
+ if (AP4_FAILED(result)) return result;
+ break;
+ case AP4_RTP_CONSTRUCTOR_TYPE_SAMPLE_DESC:
+ return AP4_ERROR_NOT_SUPPORTED;
+ default:
+ // unknown constructor type
+ return AP4_FAILURE;
}
// iterate
@@ -309,8 +302,8 @@ AP4_HintTrackReader::BuildRtpPacket(AP4_RtpPacket* packet,
| AP4_HintTrackReader::WriteImmediateRtpData
+---------------------------------------------------------------------*/
AP4_Result
-AP4_HintTrackReader::WriteImmediateRtpData(AP4_ImmediateRtpConstructor* constructor,
- AP4_ByteStream* data_stream)
+AP4_HintTrackReader::WriteImmediateRtpData(AP4_ImmediateRtpConstructor* constructor,
+ AP4_ByteStream* data_stream)
{
const AP4_DataBuffer& data_buffer = constructor->GetData();
return data_stream->Write(data_buffer.GetData(), data_buffer.GetDataSize());
@@ -320,30 +313,27 @@ AP4_HintTrackReader::WriteImmediateRtpData(AP4_ImmediateRtpConstructor* construc
| AP4_HintTrackReader::WriteSampleRtpData
+---------------------------------------------------------------------*/
AP4_Result
-AP4_HintTrackReader::WriteSampleRtpData(AP4_SampleRtpConstructor* constructor,
+AP4_HintTrackReader::WriteSampleRtpData(AP4_SampleRtpConstructor* constructor,
AP4_ByteStream* data_stream)
{
AP4_Track* referenced_track = NULL;
- if(constructor->GetTrackRefIndex() == 0xFF)
- {
+ if (constructor->GetTrackRefIndex() == 0xFF) {
// data is in the hint track
referenced_track = &m_HintTrack;
- }
- else
- {
+ } else {
// check if we have a media track
- if(m_MediaTrack == NULL) return AP4_FAILURE;
+ if (m_MediaTrack == NULL) return AP4_FAILURE;
referenced_track = m_MediaTrack;
}
// write the sample data
AP4_Sample sample;
- AP4_Result result = referenced_track->GetSample(constructor->GetSampleNum() - 1, // adjust
- sample);
+ AP4_Result result = referenced_track->GetSample(constructor->GetSampleNum()-1, // adjust
+ sample);
AP4_DataBuffer buffer(constructor->GetLength());
result = sample.ReadData(
- buffer, constructor->GetLength(), constructor->GetSampleOffset());
- if(AP4_FAILED(result)) return result;
+ buffer, constructor->GetLength(), constructor->GetSampleOffset());
+ if (AP4_FAILED(result)) return result;
// write the data
return data_stream->Write(buffer.GetData(), buffer.GetDataSize());
diff --git a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4HintTrackReader.h b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4HintTrackReader.h
index 0f4e0ef3e..71b2aebaa 100644
--- a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4HintTrackReader.h
+++ b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4HintTrackReader.h
@@ -54,34 +54,31 @@ class AP4_HintTrackReader
{
public:
// constructor and destructor
- static AP4_Result Create(AP4_Track& hint_track,
- AP4_Movie& movie,
+ static AP4_Result Create(AP4_Track& hint_track,
+ AP4_Movie& movie,
AP4_UI32 ssrc, // if 0, a random value is chosen
AP4_HintTrackReader*& reader);
~AP4_HintTrackReader();
// methods
- AP4_Result GetNextPacket(AP4_DataBuffer& packet,
+ AP4_Result GetNextPacket(AP4_DataBuffer& packet,
AP4_UI32& ts_ms);
AP4_Result SeekToTimeStampMs(AP4_UI32 desired_ts_ms,
AP4_UI32& actual_ts_ms);
AP4_UI32 GetCurrentTimeStampMs();
AP4_Result Rewind();
AP4_Result GetSdpText(AP4_String& sdp);
- AP4_Track* GetMediaTrack()
- {
- return m_MediaTrack;
- }
-
+ AP4_Track* GetMediaTrack() { return m_MediaTrack; }
+
private:
// use the factory instead of the constructor
- AP4_HintTrackReader(AP4_Track& hint_track,
- AP4_Movie& movie,
+ AP4_HintTrackReader(AP4_Track& hint_track,
+ AP4_Movie& movie,
AP4_UI32 ssrc);
-
+
// methods
AP4_Result GetRtpSample(AP4_Ordinal index);
- AP4_Result BuildRtpPacket(AP4_RtpPacket* packet,
+ AP4_Result BuildRtpPacket(AP4_RtpPacket* packet,
AP4_DataBuffer& packet_data);
AP4_Result WriteImmediateRtpData(AP4_ImmediateRtpConstructor* constructor,
AP4_ByteStream* data_stream);
diff --git a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4HmhdAtom.cpp b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4HmhdAtom.cpp
index 5fcdab9da..4864e260a 100644
--- a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4HmhdAtom.cpp
+++ b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4HmhdAtom.cpp
@@ -1,6 +1,6 @@
/*****************************************************************
|
-| AP4 - hmhd Atoms
+| AP4 - hmhd Atoms
|
| Copyright 2002-2008 Axiomatic Systems, LLC
|
@@ -41,15 +41,15 @@ AP4_HmhdAtom::Create(AP4_Size size, AP4_ByteStream& stream)
{
AP4_UI32 version;
AP4_UI32 flags;
- if(AP4_FAILED(AP4_Atom::ReadFullHeader(stream, version, flags))) return NULL;
- if(version != 0) return NULL;
+ if (AP4_FAILED(AP4_Atom::ReadFullHeader(stream, version, flags))) return NULL;
+ if (version != 0) return NULL;
return new AP4_HmhdAtom(size, version, flags, stream);
}
/*----------------------------------------------------------------------
| AP4_HmhdAtom::AP4_HmhdAtom
+---------------------------------------------------------------------*/
-AP4_HmhdAtom::AP4_HmhdAtom(AP4_UI32 size,
+AP4_HmhdAtom::AP4_HmhdAtom(AP4_UI32 size,
AP4_UI32 version,
AP4_UI32 flags,
AP4_ByteStream& stream) :
@@ -72,23 +72,23 @@ AP4_HmhdAtom::WriteFields(AP4_ByteStream& stream)
// max pdu size
result = stream.WriteUI16(m_MaxPduSize);
- if(AP4_FAILED(result)) return result;
+ if (AP4_FAILED(result)) return result;
// avg pdu size
result = stream.WriteUI16(m_AvgPduSize);
- if(AP4_FAILED(result)) return result;
+ if (AP4_FAILED(result)) return result;
// max bitrate
result = stream.WriteUI32(m_MaxBitrate);
- if(AP4_FAILED(result)) return result;
+ if (AP4_FAILED(result)) return result;
// avg bitrate
result = stream.WriteUI32(m_AvgBitrate);
- if(AP4_FAILED(result)) return result;
+ if (AP4_FAILED(result)) return result;
// reserved
result = stream.WriteUI32(m_Reserved);
- if(AP4_FAILED(result)) return result;
+ if (AP4_FAILED(result)) return result;
return AP4_SUCCESS;
}
diff --git a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4HmhdAtom.h b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4HmhdAtom.h
index 69e68efa0..c26417dc7 100644
--- a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4HmhdAtom.h
+++ b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4HmhdAtom.h
@@ -1,6 +1,6 @@
/*****************************************************************
|
-| AP4 - hmhd Atoms
+| AP4 - hmhd Atoms
|
| Copyright 2002-2008 Axiomatic Systems, LLC
|
@@ -55,7 +55,7 @@ public:
private:
// methods
- AP4_HmhdAtom(AP4_UI32 size,
+ AP4_HmhdAtom(AP4_UI32 size,
AP4_UI32 version,
AP4_UI32 flags,
AP4_ByteStream& stream);
diff --git a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4IkmsAtom.cpp b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4IkmsAtom.cpp
index 4910f51cd..8e2df2fb2 100644
--- a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4IkmsAtom.cpp
+++ b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4IkmsAtom.cpp
@@ -1,6 +1,6 @@
/*****************************************************************
|
-| AP4 - iKMS Atoms
+| AP4 - iKMS Atoms
|
| Copyright 2002-2008 Axiomatic Systems, LLC
|
@@ -45,8 +45,8 @@ AP4_IkmsAtom::Create(AP4_Size size, AP4_ByteStream& stream)
{
AP4_UI32 version;
AP4_UI32 flags;
- if(AP4_FAILED(AP4_Atom::ReadFullHeader(stream, version, flags))) return NULL;
- if(version > 1) return NULL;
+ if (AP4_FAILED(AP4_Atom::ReadFullHeader(stream, version, flags))) return NULL;
+ if (version > 1) return NULL;
return new AP4_IkmsAtom(size, version, flags, stream);
}
@@ -61,32 +61,28 @@ AP4_IkmsAtom::AP4_IkmsAtom(const char* kms_uri,
m_KmsId(kms_id),
m_KmsVersion(kms_version)
{
- m_Size32 += m_KmsUri.GetLength() + 1;
+ m_Size32 += m_KmsUri.GetLength()+1;
}
/*----------------------------------------------------------------------
| AP4_IkmsAtom::AP4_IkmsAtom
+---------------------------------------------------------------------*/
-AP4_IkmsAtom::AP4_IkmsAtom(AP4_UI32 size,
+AP4_IkmsAtom::AP4_IkmsAtom(AP4_UI32 size,
AP4_UI32 version,
AP4_UI32 flags,
AP4_ByteStream& stream) :
AP4_Atom(AP4_ATOM_TYPE_IKMS, size, version, flags)
{
- AP4_Size string_size = size - AP4_FULL_ATOM_HEADER_SIZE;
- if(m_Version == 1 && string_size >= 8)
- {
+ AP4_Size string_size = size-AP4_FULL_ATOM_HEADER_SIZE;
+ if (m_Version == 1 && string_size >= 8) {
string_size -= 8;
stream.ReadUI32(m_KmsId);
stream.ReadUI32(m_KmsVersion);
- }
- else
- {
+ } else {
m_KmsId = 0;
m_KmsVersion = 0;
}
- if(string_size)
- {
+ if (string_size) {
char* str = new char[string_size];
stream.Read(str, string_size);
str[string_size-1] = '\0'; // force null-termination
@@ -98,7 +94,7 @@ AP4_IkmsAtom::AP4_IkmsAtom(AP4_UI32 size,
/*----------------------------------------------------------------------
| AP4_IkmsAtom::Clone
+---------------------------------------------------------------------*/
-AP4_Atom*
+AP4_Atom*
AP4_IkmsAtom::Clone()
{
return new AP4_IkmsAtom(m_KmsUri.GetChars(), m_KmsId, m_KmsVersion);
@@ -111,21 +107,20 @@ AP4_Result
AP4_IkmsAtom::WriteFields(AP4_ByteStream& stream)
{
// handler version 1
- if(m_Version == 1)
- {
+ if (m_Version == 1) {
stream.WriteUI32(m_KmsId);
stream.WriteUI32(m_KmsVersion);
}
// kms uri
- AP4_Result result = stream.Write(m_KmsUri.GetChars(), m_KmsUri.GetLength() + 1);
- if(AP4_FAILED(result)) return result;
+ AP4_Result result = stream.Write(m_KmsUri.GetChars(), m_KmsUri.GetLength()+1);
+ if (AP4_FAILED(result)) return result;
// pad with zeros if necessary
- AP4_Size padding = m_Size32 - (AP4_FULL_ATOM_HEADER_SIZE + m_KmsUri.GetLength() + 1);
- if(m_Version == 1) padding -= 8;
- while(padding--) stream.WriteUI08(0);
-
+ AP4_Size padding = m_Size32-(AP4_FULL_ATOM_HEADER_SIZE+m_KmsUri.GetLength()+1);
+ if (m_Version == 1) padding-=8;
+ while (padding--) stream.WriteUI08(0);
+
return AP4_SUCCESS;
}
@@ -135,8 +130,7 @@ AP4_IkmsAtom::WriteFields(AP4_ByteStream& stream)
AP4_Result
AP4_IkmsAtom::InspectFields(AP4_AtomInspector& inspector)
{
- if(m_Version == 1)
- {
+ if (m_Version == 1) {
char id[5];
AP4_FormatFourChars(id, m_KmsId);
inspector.AddField("kms_id", id);
diff --git a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4IkmsAtom.h b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4IkmsAtom.h
index 2e2756757..7097b84bd 100644
--- a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4IkmsAtom.h
+++ b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4IkmsAtom.h
@@ -56,22 +56,13 @@ public:
virtual AP4_Result WriteFields(AP4_ByteStream& stream);
// accessors
- const AP4_String& GetKmsUri()
- {
- return m_KmsUri;
- }
- AP4_UI32 GetKmsId()
- {
- return m_KmsId;
- }
- AP4_UI32 GetKmsVersion()
- {
- return m_KmsVersion;
- }
+ const AP4_String& GetKmsUri() { return m_KmsUri; }
+ AP4_UI32 GetKmsId() { return m_KmsId; }
+ AP4_UI32 GetKmsVersion() { return m_KmsVersion; }
private:
// methods
- AP4_IkmsAtom(AP4_UI32 size,
+ AP4_IkmsAtom(AP4_UI32 size,
AP4_UI32 version,
AP4_UI32 flags,
AP4_ByteStream& stream);
diff --git a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4Interfaces.h b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4Interfaces.h
index 462bfe2d8..56502dab6 100644
--- a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4Interfaces.h
+++ b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4Interfaces.h
@@ -60,7 +60,7 @@ public:
+---------------------------------------------------------------------*/
class AP4_Referenceable
{
-public:
+ public:
// methods
virtual ~AP4_Referenceable() {}
virtual void AddReference() = 0;
diff --git a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4IodsAtom.cpp b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4IodsAtom.cpp
index 2d6822540..4baab3ce7 100644
--- a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4IodsAtom.cpp
+++ b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4IodsAtom.cpp
@@ -46,8 +46,8 @@ AP4_IodsAtom::Create(AP4_Size size, AP4_ByteStream& stream)
{
AP4_UI32 version;
AP4_UI32 flags;
- if(AP4_FAILED(AP4_Atom::ReadFullHeader(stream, version, flags))) return NULL;
- if(version != 0) return NULL;
+ if (AP4_FAILED(AP4_Atom::ReadFullHeader(stream, version, flags))) return NULL;
+ if (version != 0) return NULL;
return new AP4_IodsAtom(size, version, flags, stream);
}
@@ -58,13 +58,13 @@ AP4_IodsAtom::AP4_IodsAtom(AP4_ObjectDescriptor* descriptor) :
AP4_Atom(AP4_ATOM_TYPE_IODS, AP4_FULL_ATOM_HEADER_SIZE, 0, 0),
m_ObjectDescriptor(descriptor)
{
- if(m_ObjectDescriptor) m_Size32 += m_ObjectDescriptor->GetSize();
+ if (m_ObjectDescriptor) m_Size32 += m_ObjectDescriptor->GetSize();
}
/*----------------------------------------------------------------------
| AP4_IodsAtom::AP4_IodsAtom
+---------------------------------------------------------------------*/
-AP4_IodsAtom::AP4_IodsAtom(AP4_UI32 size,
+AP4_IodsAtom::AP4_IodsAtom(AP4_UI32 size,
AP4_UI32 version,
AP4_UI32 flags,
AP4_ByteStream& stream) :
@@ -72,13 +72,10 @@ AP4_IodsAtom::AP4_IodsAtom(AP4_UI32 size,
{
// read the descriptor
AP4_Descriptor* descriptor = NULL;
- if(AP4_DescriptorFactory::CreateDescriptorFromStream(stream, descriptor) == AP4_SUCCESS)
- {
+ if (AP4_DescriptorFactory::CreateDescriptorFromStream(stream, descriptor) == AP4_SUCCESS) {
m_ObjectDescriptor = AP4_DYNAMIC_CAST(AP4_ObjectDescriptor, descriptor);
- if(m_ObjectDescriptor == NULL) delete descriptor;
- }
- else
- {
+ if (m_ObjectDescriptor == NULL) delete descriptor;
+ } else {
m_ObjectDescriptor = NULL;
}
}
@@ -98,7 +95,7 @@ AP4_Result
AP4_IodsAtom::WriteFields(AP4_ByteStream& stream)
{
// write the es descriptor
- if(m_ObjectDescriptor) return m_ObjectDescriptor->Write(stream);
+ if (m_ObjectDescriptor) return m_ObjectDescriptor->Write(stream);
return AP4_SUCCESS;
}
@@ -110,8 +107,7 @@ AP4_Result
AP4_IodsAtom::InspectFields(AP4_AtomInspector& inspector)
{
// inspect descriptor
- if(m_ObjectDescriptor)
- {
+ if (m_ObjectDescriptor) {
m_ObjectDescriptor->Inspect(inspector);
}
diff --git a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4IodsAtom.h b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4IodsAtom.h
index fb7c1a67a..41c6c4cf0 100644
--- a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4IodsAtom.h
+++ b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4IodsAtom.h
@@ -54,17 +54,14 @@ public:
// methods
AP4_IodsAtom(AP4_ObjectDescriptor* descriptor); // ownership of 'descriptor' is transfered
- ~AP4_IodsAtom();
+ ~AP4_IodsAtom();
virtual AP4_Result WriteFields(AP4_ByteStream& stream);
virtual AP4_Result InspectFields(AP4_AtomInspector& inspector);
- const AP4_ObjectDescriptor* GetObjectDescriptor() const
- {
- return m_ObjectDescriptor;
- }
-
+ const AP4_ObjectDescriptor* GetObjectDescriptor() const { return m_ObjectDescriptor; }
+
private:
// methods
- AP4_IodsAtom(AP4_UI32 size,
+ AP4_IodsAtom(AP4_UI32 size,
AP4_UI32 version,
AP4_UI32 flags,
AP4_ByteStream& stream);
diff --git a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4Ipmp.cpp b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4Ipmp.cpp
index 2d2256d4b..c3e057ae1 100644
--- a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4Ipmp.cpp
+++ b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4Ipmp.cpp
@@ -52,14 +52,13 @@ AP4_IpmpDescriptorPointer::AP4_IpmpDescriptorPointer(AP4_UI08 descriptor_id) :
/*----------------------------------------------------------------------
| AP4_IpmpDescriptorPointer::AP4_IpmpDescriptorPointer
+---------------------------------------------------------------------*/
-AP4_IpmpDescriptorPointer::AP4_IpmpDescriptorPointer(AP4_ByteStream& stream,
- AP4_Size header_size,
- AP4_Size payload_size) :
+AP4_IpmpDescriptorPointer::AP4_IpmpDescriptorPointer(AP4_ByteStream& stream,
+ AP4_Size header_size,
+ AP4_Size payload_size) :
AP4_Descriptor(AP4_DESCRIPTOR_TAG_IPMP_DESCRIPTOR_POINTER, header_size, payload_size)
{
stream.ReadUI08(m_DescriptorId);
- if(m_DescriptorId == 0xFF && payload_size >= 5)
- {
+ if (m_DescriptorId == 0xFF && payload_size >= 5) {
stream.ReadUI16(m_DescriptorIdEx);
stream.ReadUI16(m_EsId);
}
@@ -72,8 +71,7 @@ AP4_Result
AP4_IpmpDescriptorPointer::WriteFields(AP4_ByteStream& stream)
{
stream.WriteUI08(m_DescriptorId);
- if(m_DescriptorId == 0xFF)
- {
+ if (m_DescriptorId == 0xFF) {
stream.WriteUI16(m_DescriptorIdEx);
stream.WriteUI16(m_EsId);
}
@@ -87,12 +85,11 @@ AP4_Result
AP4_IpmpDescriptorPointer::Inspect(AP4_AtomInspector& inspector)
{
char info[64];
- AP4_FormatString(info, sizeof(info), "size=%ld+%ld",
- GetHeaderSize(), m_PayloadSize);
+ AP4_FormatString(info, sizeof(info), "size=%ld+%ld",
+ GetHeaderSize(),m_PayloadSize);
inspector.StartElement("[IPMP_DescriptorPointer]", info);
inspector.AddField("IPMP_DescriptorID", m_DescriptorId);
- if(m_DescriptorId == 0xFF)
- {
+ if (m_DescriptorId == 0xFF) {
inspector.AddField("IPMP_DescriptorIDEx", m_DescriptorIdEx);
inspector.AddField("IPMP_ES_ID", m_EsId);
}
@@ -119,7 +116,7 @@ AP4_IpmpDescriptor::AP4_IpmpDescriptor(AP4_UI08 descriptor_id, AP4_UI16 ipmps_ty
/*----------------------------------------------------------------------
| AP4_IpmpDescriptor::AP4_IpmpDescriptor
+---------------------------------------------------------------------*/
-AP4_IpmpDescriptor::AP4_IpmpDescriptor(AP4_ByteStream& stream,
+AP4_IpmpDescriptor::AP4_IpmpDescriptor(AP4_ByteStream& stream,
AP4_Size header_size,
AP4_Size payload_size) :
AP4_Descriptor(AP4_DESCRIPTOR_TAG_IPMP_DESCRIPTOR, header_size, payload_size),
@@ -130,40 +127,31 @@ AP4_IpmpDescriptor::AP4_IpmpDescriptor(AP4_ByteStream& stream,
stream.ReadUI08(m_DescriptorId);
stream.ReadUI16(m_IpmpsType);
AP4_SetMemory(m_ToolId, 0, sizeof(m_ToolId));
- if(m_DescriptorId == 0xFF && m_IpmpsType == 0xFFFF)
- {
- AP4_Size fields_size = 3 + 3;
+ if (m_DescriptorId == 0xFF && m_IpmpsType == 0xFFFF) {
+ AP4_Size fields_size = 3+3;
stream.ReadUI16(m_DescriptorIdEx);
stream.Read(m_ToolId, 16);
stream.ReadUI08(m_ControlPointCode);
- if(m_ControlPointCode > 0)
- {
+ if (m_ControlPointCode > 0) {
stream.ReadUI08(m_SequenceCode);
++fields_size;
}
- if(fields_size < payload_size)
- {
- m_Data.SetDataSize(payload_size - fields_size);
- stream.Read(m_Data.UseData(), payload_size - fields_size);
+ if (fields_size < payload_size) {
+ m_Data.SetDataSize(payload_size-fields_size);
+ stream.Read(m_Data.UseData(), payload_size-fields_size);
}
- }
- else if(m_IpmpsType == 0)
- {
- if(payload_size > 3)
- {
+ } else if (m_IpmpsType == 0) {
+ if (payload_size > 3) {
char* buffer = new char[1+payload_size-3];
buffer[payload_size-3] = '\0';
- stream.Read(buffer, payload_size - 3);
- m_Url.Assign(buffer, payload_size - 3);
+ stream.Read(buffer, payload_size-3);
+ m_Url.Assign(buffer, payload_size-3);
delete[] buffer;
}
- }
- else
- {
- if(payload_size > 3)
- {
- m_Data.SetDataSize(payload_size - 3);
- stream.Read(m_Data.UseData(), payload_size - 3);
+ } else {
+ if (payload_size > 3) {
+ m_Data.SetDataSize(payload_size-3);
+ stream.Read(m_Data.UseData(), payload_size-3);
}
}
}
@@ -187,29 +175,22 @@ AP4_IpmpDescriptor::WriteFields(AP4_ByteStream& stream)
{
stream.WriteUI08(m_DescriptorId);
stream.WriteUI16(m_IpmpsType);
- if(m_DescriptorId == 0xFF && m_IpmpsType == 0xFFFF)
- {
+ if (m_DescriptorId == 0xFF && m_IpmpsType == 0xFFFF) {
stream.WriteUI16(m_DescriptorIdEx);
stream.Write(m_ToolId, 16);
stream.WriteUI08(m_ControlPointCode);
- if(m_ControlPointCode > 0)
- {
+ if (m_ControlPointCode > 0) {
stream.WriteUI08(m_SequenceCode);
}
- if(m_Data.GetDataSize())
- {
+ if (m_Data.GetDataSize()) {
stream.Write(m_Data.GetData(), m_Data.GetDataSize());
}
- }
- else if(m_IpmpsType == 0)
- {
- stream.Write(m_Url.GetChars(), m_Url.GetLength() + 1);
- }
- else
- {
+ } else if (m_IpmpsType == 0) {
+ stream.Write(m_Url.GetChars(), m_Url.GetLength()+1);
+ } else {
stream.Write(m_Data.GetData(), m_Data.GetDataSize());
}
-
+
return AP4_SUCCESS;
}
@@ -220,27 +201,21 @@ AP4_Result
AP4_IpmpDescriptor::Inspect(AP4_AtomInspector& inspector)
{
char info[64];
- AP4_FormatString(info, sizeof(info), "size=%ld+%ld",
- GetHeaderSize(), m_PayloadSize);
+ AP4_FormatString(info, sizeof(info), "size=%ld+%ld",
+ GetHeaderSize(),m_PayloadSize);
inspector.StartElement("[IPMP_Descriptor]", info);
inspector.AddField("IPMP_DescriptorID", m_DescriptorId);
inspector.AddField("IPMPS_Type", m_IpmpsType, AP4_AtomInspector::HINT_HEX);
- if(m_DescriptorId == 0xFF && m_IpmpsType == 0xFFFF)
- {
+ if (m_DescriptorId == 0xFF && m_IpmpsType == 0xFFFF) {
inspector.AddField("IPMP_DescriptorIDEx", m_DescriptorIdEx);
inspector.AddField("IPMP_ToolID", (const unsigned char*)(&m_ToolId[0]), 16, AP4_AtomInspector::HINT_HEX);
inspector.AddField("controlPointCode", m_ControlPointCode);
- if(m_ControlPointCode > 0)
- {
+ if (m_ControlPointCode > 0) {
inspector.AddField("sequenceCode", m_SequenceCode);
}
- }
- else if(m_IpmpsType == 0)
- {
+ } else if (m_IpmpsType == 0) {
inspector.AddField("URL", m_Url.GetChars());
- }
- else
- {
+ } else {
inspector.AddField("data size", m_Data.GetDataSize());
}
diff --git a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4Ipmp.h b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4Ipmp.h
index c5c121f70..52370af6d 100644
--- a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4Ipmp.h
+++ b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4Ipmp.h
@@ -1,6 +1,6 @@
/*****************************************************************
|
-| AP4 - IPMP
+| AP4 - IPMP
|
| Copyright 2002-2008 Axiomatic Systems, LLC
|
@@ -45,96 +45,63 @@ const AP4_UI08 AP4_DESCRIPTOR_TAG_IPMP_DESCRIPTOR = 0x0B;
/*----------------------------------------------------------------------
| AP4_IpmpDescriptorPointer
+---------------------------------------------------------------------*/
-class AP4_IpmpDescriptorPointer : public AP4_Descriptor
+class AP4_IpmpDescriptorPointer : public AP4_Descriptor
{
public:
AP4_IMPLEMENT_DYNAMIC_CAST_D(AP4_IpmpDescriptorPointer, AP4_Descriptor)
// methods
AP4_IpmpDescriptorPointer(AP4_UI08 descriptor_id);
- AP4_IpmpDescriptorPointer(AP4_ByteStream& stream,
- AP4_Size header_size,
+ AP4_IpmpDescriptorPointer(AP4_ByteStream& stream,
+ AP4_Size header_size,
AP4_Size payload_size);
virtual AP4_Result WriteFields(AP4_ByteStream& stream);
virtual AP4_Result Inspect(AP4_AtomInspector& inspector);
// accessors
- AP4_UI08 GetDescriptorId() const
- {
- return m_DescriptorId;
- }
- AP4_UI16 GetDescriptorIdEx() const
- {
- return m_DescriptorIdEx;
- }
- AP4_UI16 GetEsId() const
- {
- return m_EsId;
- }
+ AP4_UI08 GetDescriptorId() const { return m_DescriptorId; }
+ AP4_UI16 GetDescriptorIdEx() const { return m_DescriptorIdEx; }
+ AP4_UI16 GetEsId() const { return m_EsId; }
private:
// members
- AP4_UI08 m_DescriptorId;
- AP4_UI16 m_DescriptorIdEx;
- AP4_UI16 m_EsId;
+ AP4_UI08 m_DescriptorId;
+ AP4_UI16 m_DescriptorIdEx;
+ AP4_UI16 m_EsId;
};
/*----------------------------------------------------------------------
| AP4_IpmpDescriptor
+---------------------------------------------------------------------*/
-class AP4_IpmpDescriptor : public AP4_Descriptor
-{
+class AP4_IpmpDescriptor : public AP4_Descriptor
+{
public:
AP4_IMPLEMENT_DYNAMIC_CAST_D(AP4_IpmpDescriptor, AP4_Descriptor)
// methods
AP4_IpmpDescriptor(AP4_UI08 descriptor_id, AP4_UI16 ipmps_type);
- AP4_IpmpDescriptor(AP4_ByteStream& stream,
- AP4_Size header_size,
+ AP4_IpmpDescriptor(AP4_ByteStream& stream,
+ AP4_Size header_size,
AP4_Size payload_size);
virtual AP4_Result WriteFields(AP4_ByteStream& stream);
virtual AP4_Result Inspect(AP4_AtomInspector& inspector);
// accessors
- AP4_UI08 GetDescriptorId() const
- {
- return m_DescriptorId;
- }
- AP4_UI16 GetIpmpsType() const
- {
- return m_IpmpsType;
- }
- AP4_UI16 GetDescriptorIdEx() const
- {
- return m_DescriptorIdEx;
- }
- const AP4_UI08* GetToolId() const
- {
- return m_ToolId;
- }
- AP4_UI08 GetControlPointCode() const
- {
- return m_ControlPointCode;
- }
- AP4_UI08 GetSequenceCode() const
- {
- return m_SequenceCode;
- }
- const AP4_String& GetUrl() const
- {
- return m_Url;
- }
- const AP4_DataBuffer& GetData() const
- {
- return m_Data;
- }
+ AP4_UI08 GetDescriptorId() const { return m_DescriptorId; }
+ AP4_UI16 GetIpmpsType() const { return m_IpmpsType; }
+ AP4_UI16 GetDescriptorIdEx() const { return m_DescriptorIdEx; }
+ const AP4_UI08* GetToolId() const { return m_ToolId; }
+ AP4_UI08 GetControlPointCode() const { return m_ControlPointCode; }
+ AP4_UI08 GetSequenceCode() const { return m_SequenceCode; }
+ const AP4_String& GetUrl() const { return m_Url; }
+ const AP4_DataBuffer& GetData() const { return m_Data; }
void SetData(const unsigned char* data, AP4_Size data_size);
-
+
private:
// members
- AP4_UI08 m_DescriptorId;
+ AP4_UI08 m_DescriptorId;
AP4_UI16 m_IpmpsType;
- AP4_UI16 m_DescriptorIdEx;
+ AP4_UI16 m_DescriptorIdEx;
AP4_UI08 m_ToolId[16];
AP4_UI08 m_ControlPointCode;
AP4_UI08 m_SequenceCode;
diff --git a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4IproAtom.cpp b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4IproAtom.cpp
index 861ed9597..bf85194b1 100644
--- a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4IproAtom.cpp
+++ b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4IproAtom.cpp
@@ -1,6 +1,6 @@
/*****************************************************************
|
-| AP4 - ipro Atoms
+| AP4 - ipro Atoms
|
| Copyright 2002-2008 Axiomatic Systems, LLC
|
@@ -40,14 +40,14 @@
| AP4_IproAtom::Create
+---------------------------------------------------------------------*/
AP4_IproAtom*
-AP4_IproAtom::Create(AP4_Size size,
- AP4_ByteStream& stream,
+AP4_IproAtom::Create(AP4_Size size,
+ AP4_ByteStream& stream,
AP4_AtomFactory& atom_factory)
{
AP4_UI32 version;
AP4_UI32 flags;
- if(AP4_FAILED(AP4_Atom::ReadFullHeader(stream, version, flags))) return NULL;
- if(version != 0) return NULL;
+ if (AP4_FAILED(AP4_Atom::ReadFullHeader(stream, version, flags))) return NULL;
+ if (version != 0) return NULL;
return new AP4_IproAtom(size, version, flags, stream, atom_factory);
}
@@ -66,14 +66,12 @@ AP4_IproAtom::AP4_IproAtom(AP4_UI32 size,
stream.ReadUI16(entry_count);
// read all entries
- AP4_LargeSize bytes_available = size - AP4_FULL_ATOM_HEADER_SIZE - 2;
- for(unsigned int i = 0; i < entry_count; i++)
- {
+ AP4_LargeSize bytes_available = size-AP4_FULL_ATOM_HEADER_SIZE-2;
+ for (unsigned int i=0; i<entry_count; i++) {
AP4_Atom* atom;
- if(AP4_SUCCEEDED(atom_factory.CreateAtomFromStream(stream,
- bytes_available,
- atom)))
- {
+ if (AP4_SUCCEEDED(atom_factory.CreateAtomFromStream(stream,
+ bytes_available,
+ atom))) {
atom->SetParent(this);
m_Children.Add(atom);
}
@@ -90,7 +88,7 @@ AP4_IproAtom::WriteFields(AP4_ByteStream& stream)
// entry count
result = stream.WriteUI16(m_Children.ItemCount());
- if(AP4_FAILED(result)) return result;
+ if (AP4_FAILED(result)) return result;
// entries
return m_Children.Apply(AP4_AtomListWriter(stream));
@@ -103,7 +101,7 @@ AP4_Result
AP4_IproAtom::InspectFields(AP4_AtomInspector& inspector)
{
inspector.AddField("entry-count", m_Children.ItemCount());
-
+
// inspect children
m_Children.Apply(AP4_AtomListInspector(inspector));
diff --git a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4IproAtom.h b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4IproAtom.h
index a47724f37..a5c7d0d7f 100644
--- a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4IproAtom.h
+++ b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4IproAtom.h
@@ -1,6 +1,6 @@
/*****************************************************************
|
-| AP4 - ipro Atoms
+| AP4 - ipro Atoms
|
| Copyright 2002-2008 Axiomatic Systems, LLC
|
diff --git a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4IsfmAtom.cpp b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4IsfmAtom.cpp
index 6f573852e..8cd839eae 100644
--- a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4IsfmAtom.cpp
+++ b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4IsfmAtom.cpp
@@ -1,6 +1,6 @@
/*****************************************************************
|
-| AP4 - iSFM Atoms
+| AP4 - iSFM Atoms
|
| Copyright 2002-2008 Axiomatic Systems, LLC
|
@@ -45,8 +45,8 @@ AP4_IsfmAtom::Create(AP4_Size size, AP4_ByteStream& stream)
{
AP4_UI32 version;
AP4_UI32 flags;
- if(AP4_FAILED(AP4_Atom::ReadFullHeader(stream, version, flags))) return NULL;
- if(version != 0) return NULL;
+ if (AP4_FAILED(AP4_Atom::ReadFullHeader(stream, version, flags))) return NULL;
+ if (version != 0) return NULL;
return new AP4_IsfmAtom(size, version, flags, stream);
}
@@ -56,7 +56,7 @@ AP4_IsfmAtom::Create(AP4_Size size, AP4_ByteStream& stream)
AP4_IsfmAtom::AP4_IsfmAtom(bool selective_encryption,
AP4_UI08 key_length_indicator,
AP4_UI08 iv_length) :
- AP4_Atom(AP4_ATOM_TYPE_ISFM, AP4_FULL_ATOM_HEADER_SIZE + 3, 0, 0),
+ AP4_Atom(AP4_ATOM_TYPE_ISFM, AP4_FULL_ATOM_HEADER_SIZE+3, 0, 0),
m_SelectiveEncryption(selective_encryption),
m_KeyIndicatorLength(key_length_indicator),
m_IvLength(iv_length)
@@ -66,7 +66,7 @@ AP4_IsfmAtom::AP4_IsfmAtom(bool selective_encryption,
/*----------------------------------------------------------------------
| AP4_IsfmAtom::AP4_IsfmAtom
+---------------------------------------------------------------------*/
-AP4_IsfmAtom::AP4_IsfmAtom(AP4_UI32 size,
+AP4_IsfmAtom::AP4_IsfmAtom(AP4_UI32 size,
AP4_UI32 version,
AP4_UI32 flags,
AP4_ByteStream& stream) :
@@ -74,7 +74,7 @@ AP4_IsfmAtom::AP4_IsfmAtom(AP4_UI32 size,
{
AP4_UI08 s;
stream.ReadUI08(s);
- m_SelectiveEncryption = ((s & 0x80) != 0);
+ m_SelectiveEncryption = ((s&0x80) != 0);
stream.ReadUI08(m_KeyIndicatorLength);
stream.ReadUI08(m_IvLength);
}
@@ -82,11 +82,11 @@ AP4_IsfmAtom::AP4_IsfmAtom(AP4_UI32 size,
/*----------------------------------------------------------------------
| AP4_IsfmAtom::Clone
+---------------------------------------------------------------------*/
-AP4_Atom*
+AP4_Atom*
AP4_IsfmAtom::Clone()
{
- return new AP4_IsfmAtom(m_SelectiveEncryption,
- m_KeyIndicatorLength,
+ return new AP4_IsfmAtom(m_SelectiveEncryption,
+ m_KeyIndicatorLength,
m_IvLength);
}
@@ -100,15 +100,15 @@ AP4_IsfmAtom::WriteFields(AP4_ByteStream& stream)
// selective encryption
result = stream.WriteUI08(m_SelectiveEncryption ? 0x80 : 0);
- if(AP4_FAILED(result)) return result;
+ if (AP4_FAILED(result)) return result;
// key indicator length
result = stream.WriteUI08(m_KeyIndicatorLength);
- if(AP4_FAILED(result)) return result;
+ if (AP4_FAILED(result)) return result;
// IV length
result = stream.WriteUI08(m_IvLength);
- if(AP4_FAILED(result)) return result;
+ if (AP4_FAILED(result)) return result;
return AP4_SUCCESS;
}
diff --git a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4IsfmAtom.h b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4IsfmAtom.h
index a1070e6aa..be6ab8382 100644
--- a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4IsfmAtom.h
+++ b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4IsfmAtom.h
@@ -55,22 +55,13 @@ public:
virtual AP4_Result WriteFields(AP4_ByteStream& stream);
// accessors
- bool GetSelectiveEncryption()
- {
- return m_SelectiveEncryption;
- }
- AP4_UI08 GetKeyIndicatorLength()
- {
- return m_KeyIndicatorLength;
- }
- AP4_UI08 GetIvLength()
- {
- return m_IvLength;
- }
+ bool GetSelectiveEncryption() { return m_SelectiveEncryption; }
+ AP4_UI08 GetKeyIndicatorLength() { return m_KeyIndicatorLength; }
+ AP4_UI08 GetIvLength() { return m_IvLength; }
private:
// methods
- AP4_IsfmAtom(AP4_UI32 size,
+ AP4_IsfmAtom(AP4_UI32 size,
AP4_UI32 version,
AP4_UI32 flags,
AP4_ByteStream& stream);
diff --git a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4IsltAtom.cpp b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4IsltAtom.cpp
index e10bec51e..686e68e00 100644
--- a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4IsltAtom.cpp
+++ b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4IsltAtom.cpp
@@ -1,6 +1,6 @@
/*****************************************************************
|
-| AP4 - iSLT Atom
+| AP4 - iSLT Atom
|
| Copyright 2002-2008 Axiomatic Systems, LLC
|
@@ -41,10 +41,9 @@ AP4_DEFINE_DYNAMIC_CAST_ANCHOR(AP4_IsltAtom)
| AP4_IsltAtom::AP4_IsltAtom
+---------------------------------------------------------------------*/
AP4_IsltAtom::AP4_IsltAtom(const AP4_UI08* salt) :
- AP4_Atom(AP4_ATOM_TYPE_ISLT, AP4_ATOM_HEADER_SIZE + 8)
+ AP4_Atom(AP4_ATOM_TYPE_ISLT, AP4_ATOM_HEADER_SIZE+8)
{
- for(unsigned int i = 0; i < 8; i++)
- {
+ for (unsigned int i=0; i<8; i++) {
m_Salt[i] = salt[i];
}
}
diff --git a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4IsltAtom.h b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4IsltAtom.h
index bafe15018..949251acb 100644
--- a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4IsltAtom.h
+++ b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4IsltAtom.h
@@ -44,9 +44,8 @@ public:
AP4_IMPLEMENT_DYNAMIC_CAST_D(AP4_IsltAtom, AP4_Atom)
// class methods
- static AP4_IsltAtom* Create(AP4_Size size, AP4_ByteStream& stream)
- {
- if(size != AP4_ATOM_HEADER_SIZE + 8) return NULL;
+ static AP4_IsltAtom* Create(AP4_Size size, AP4_ByteStream& stream) {
+ if (size != AP4_ATOM_HEADER_SIZE+8) return NULL;
return new AP4_IsltAtom(size, stream);
}
@@ -56,10 +55,7 @@ public:
virtual AP4_Result WriteFields(AP4_ByteStream& stream);
// accessors
- const AP4_UI08* GetSalt()
- {
- return m_Salt;
- }
+ const AP4_UI08* GetSalt() { return m_Salt; }
private:
// methods
diff --git a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4IsmaCryp.cpp b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4IsmaCryp.cpp
index 9ceffbc55..569ca4951 100644
--- a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4IsmaCryp.cpp
+++ b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4IsmaCryp.cpp
@@ -47,15 +47,14 @@
| AP4_IsmaCipher::CreateSampleDecrypter
+---------------------------------------------------------------------*/
AP4_Result
-AP4_IsmaCipher::CreateSampleDecrypter(AP4_ProtectedSampleDescription* sample_description,
- const AP4_UI08* key,
+AP4_IsmaCipher::CreateSampleDecrypter(AP4_ProtectedSampleDescription* sample_description,
+ const AP4_UI08* key,
AP4_Size key_size,
AP4_BlockCipherFactory* block_cipher_factory,
AP4_IsmaCipher*& decrypter)
{
// check parameters
- if(key == NULL || block_cipher_factory == NULL)
- {
+ if (key == NULL || block_cipher_factory == NULL) {
return AP4_ERROR_INVALID_PARAMETERS;
}
decrypter = NULL;
@@ -63,26 +62,26 @@ AP4_IsmaCipher::CreateSampleDecrypter(AP4_ProtectedSampleDescription* sample_des
// create the cipher
AP4_BlockCipher* block_cipher = NULL;
AP4_Result result = block_cipher_factory->Create(AP4_BlockCipher::AES_128,
- AP4_BlockCipher::ENCRYPT,
- key,
- key_size,
- block_cipher);
- if(AP4_FAILED(result)) return result;
+ AP4_BlockCipher::ENCRYPT,
+ key,
+ key_size,
+ block_cipher);
+ if (AP4_FAILED(result)) return result;
// get the scheme info atom
AP4_ContainerAtom* schi = sample_description->GetSchemeInfo()->GetSchiAtom();
- if(schi == NULL) return AP4_ERROR_INVALID_FORMAT;
+ if (schi == NULL) return AP4_ERROR_INVALID_FORMAT;
// get the cipher params
AP4_IsfmAtom* isfm = AP4_DYNAMIC_CAST(AP4_IsfmAtom, schi->FindChild("iSFM"));
- if(isfm == NULL) return AP4_ERROR_INVALID_FORMAT;
-
+ if (isfm == NULL) return AP4_ERROR_INVALID_FORMAT;
+
// get the salt
AP4_IsltAtom* salt = AP4_DYNAMIC_CAST(AP4_IsltAtom, schi->FindChild("iSLT"));
// instantiate the decrypter
- decrypter = new AP4_IsmaCipher(block_cipher,
- salt ? salt->GetSalt() : NULL,
+ decrypter = new AP4_IsmaCipher(block_cipher,
+ salt?salt->GetSalt():NULL,
isfm->GetIvLength(),
isfm->GetKeyIndicatorLength(),
isfm->GetSelectiveEncryption());
@@ -92,10 +91,10 @@ AP4_IsmaCipher::CreateSampleDecrypter(AP4_ProtectedSampleDescription* sample_des
/*----------------------------------------------------------------------
| AP4_IsmaCrypCipher::AP4_IsmaCipher
+---------------------------------------------------------------------*/
-AP4_IsmaCipher::AP4_IsmaCipher(AP4_BlockCipher* block_cipher,
- const AP4_UI08* salt,
- AP4_UI08 iv_length,
- AP4_UI08 key_indicator_length,
+AP4_IsmaCipher::AP4_IsmaCipher(AP4_BlockCipher* block_cipher,
+ const AP4_UI08* salt,
+ AP4_UI08 iv_length,
+ AP4_UI08 key_indicator_length,
bool selective_encryption) :
m_IvLength(iv_length),
m_KeyIndicatorLength(key_indicator_length),
@@ -105,19 +104,16 @@ AP4_IsmaCipher::AP4_IsmaCipher(AP4_BlockCipher* block_cipher,
// left-align the salt
unsigned char salt_128[AP4_CIPHER_BLOCK_SIZE];
- unsigned int i = 0;
- if(salt)
- {
- for(; i < 8; i++)
- {
+ unsigned int i=0;
+ if (salt) {
+ for (; i<8; i++) {
salt_128[i] = salt[i];
}
}
- for(; i < AP4_CIPHER_BLOCK_SIZE; i++)
- {
+ for (; i<AP4_CIPHER_BLOCK_SIZE; i++) {
salt_128[i] = 0;
}
-
+
// create a cipher
m_Cipher = new AP4_CtrStreamCipher(block_cipher, salt_128, iv_length);
}
@@ -133,21 +129,20 @@ AP4_IsmaCipher::~AP4_IsmaCipher()
/*----------------------------------------------------------------------
| AP4_IsmaCipher::GetDecryptedSampleSize
+---------------------------------------------------------------------*/
-AP4_Size
+AP4_Size
AP4_IsmaCipher::GetDecryptedSampleSize(AP4_Sample& sample)
{
AP4_Size isma_header_size = m_KeyIndicatorLength + m_IvLength;
- if(m_SelectiveEncryption)
- {
+ if (m_SelectiveEncryption) {
++isma_header_size;
}
- return sample.GetSize() - isma_header_size;
+ return sample.GetSize()-isma_header_size;
}
/*----------------------------------------------------------------------
| AP4_IsmaCipher::DecryptSampleData
+---------------------------------------------------------------------*/
-AP4_Result
+AP4_Result
AP4_IsmaCipher::DecryptSampleData(AP4_DataBuffer& data_in,
AP4_DataBuffer& data_out,
const AP4_UI08* /*iv*/)
@@ -157,57 +152,50 @@ AP4_IsmaCipher::DecryptSampleData(AP4_DataBuffer& data_in,
AP4_Size in_size = data_in.GetDataSize();
AP4_Size header_size;
- // default to 0 output
+ // default to 0 output
data_out.SetDataSize(0);
// check the selective encryption flag
- if(in_size < 1) return AP4_ERROR_INVALID_FORMAT;
- if(m_SelectiveEncryption)
- {
- is_encrypted = ((in[0] & 0x80) != 0);
+ if (in_size < 1) return AP4_ERROR_INVALID_FORMAT;
+ if (m_SelectiveEncryption) {
+ is_encrypted = ((in[0]&0x80)!=0);
in++;
}
// check the header size
- header_size = (m_SelectiveEncryption ? 1 : 0) +
- (is_encrypted ? m_KeyIndicatorLength + m_IvLength : 0);
- if(header_size > in_size) return AP4_ERROR_INVALID_FORMAT;
+ header_size = (m_SelectiveEncryption?1:0)+
+ (is_encrypted?m_KeyIndicatorLength+m_IvLength:0);
+ if (header_size > in_size) return AP4_ERROR_INVALID_FORMAT;
// process the sample data
- AP4_Size payload_size = in_size - header_size;
+ AP4_Size payload_size = in_size-header_size;
data_out.SetDataSize(payload_size);
AP4_UI08* out = data_out.UseData();
- if(is_encrypted)
- {
+ if (is_encrypted) {
// get the IV
const AP4_UI08* iv = in;
in += m_IvLength;
// get the key indicator (we only support up to 32 bits)
unsigned int to_read = m_KeyIndicatorLength;
- while(to_read > 4)
- {
+ while (to_read > 4) {
// skip anything above 4 bytes
to_read--;
in++;
}
AP4_UI32 key_indicator = 0;
- while(to_read--)
- {
- key_indicator = (key_indicator << 8) | *in++;
+ while (to_read--) {
+ key_indicator = (key_indicator<<8) | *in++;
header_size++;
}
// we only support key indicator = 0 for now... (TODO)
- if(key_indicator != 0)
- {
+ if (key_indicator != 0) {
return AP4_ERROR_NOT_SUPPORTED;
}
m_Cipher->SetIV(iv);
m_Cipher->ProcessBuffer(in, payload_size, out);
- }
- else
- {
+ } else {
AP4_CopyMemory(out, in, payload_size);
}
@@ -217,14 +205,14 @@ AP4_IsmaCipher::DecryptSampleData(AP4_DataBuffer& data_in,
/*----------------------------------------------------------------------
| AP4_IsmaCipher::EncryptSampleData
+---------------------------------------------------------------------*/
-AP4_Result
+AP4_Result
AP4_IsmaCipher::EncryptSampleData(AP4_DataBuffer& data_in,
AP4_DataBuffer& data_out,
AP4_UI32 iv)
{
// setup the buffers
const unsigned char* in = data_in.GetData();
- data_out.SetDataSize(data_in.GetDataSize() + 4);
+ data_out.SetDataSize(data_in.GetDataSize()+4);
unsigned char* out = data_out.UseData();
// IV on 4 bytes
@@ -233,7 +221,7 @@ AP4_IsmaCipher::EncryptSampleData(AP4_DataBuffer& data_in,
// encrypt the payload
m_Cipher->SetIV(out);
AP4_Size data_size = data_in.GetDataSize();
- m_Cipher->ProcessBuffer(in, data_size, out + 4);
+ m_Cipher->ProcessBuffer(in, data_size, out+4);
return AP4_SUCCESS;
}
@@ -242,7 +230,7 @@ AP4_IsmaCipher::EncryptSampleData(AP4_DataBuffer& data_in,
| AP4_IsmaTrackDecrypter::Create
+---------------------------------------------------------------------*/
AP4_Result
-AP4_IsmaTrackDecrypter::Create(const AP4_UI08* key,
+AP4_IsmaTrackDecrypter::Create(const AP4_UI08* key,
AP4_Size key_size,
AP4_ProtectedSampleDescription* sample_description,
AP4_SampleEntry* sample_entry,
@@ -253,15 +241,15 @@ AP4_IsmaTrackDecrypter::Create(const AP4_UI08* key,
AP4_IsmaCipher* cipher = NULL;
decrypter = NULL;
AP4_Result result = AP4_IsmaCipher::CreateSampleDecrypter(sample_description,
- key,
- key_size,
- block_cipher_factory,
- cipher);
- if(AP4_FAILED(result)) return result;
+ key,
+ key_size,
+ block_cipher_factory,
+ cipher);
+ if (AP4_FAILED(result)) return result;
// instanciate the object
- decrypter = new AP4_IsmaTrackDecrypter(cipher,
- sample_entry,
+ decrypter = new AP4_IsmaTrackDecrypter(cipher,
+ sample_entry,
sample_description->GetOriginalFormat());
return AP4_SUCCESS;
}
@@ -270,8 +258,8 @@ AP4_IsmaTrackDecrypter::Create(const AP4_UI08* key,
| AP4_IsmaTrackDecrypter::AP4_IsmaTrackDecrypter
+---------------------------------------------------------------------*/
AP4_IsmaTrackDecrypter::AP4_IsmaTrackDecrypter(AP4_IsmaCipher* cipher,
- AP4_SampleEntry* sample_entry,
- AP4_UI32 original_format) :
+ AP4_SampleEntry* sample_entry,
+ AP4_UI32 original_format) :
m_Cipher(cipher),
m_SampleEntry(sample_entry),
m_OriginalFormat(original_format)
@@ -289,7 +277,7 @@ AP4_IsmaTrackDecrypter::~AP4_IsmaTrackDecrypter()
/*----------------------------------------------------------------------
| AP4_IsmaTrackDecrypter::GetProcessedSampleSize
+---------------------------------------------------------------------*/
-AP4_Size
+AP4_Size
AP4_IsmaTrackDecrypter::GetProcessedSampleSize(AP4_Sample& sample)
{
return m_Cipher->GetDecryptedSampleSize(sample);
@@ -298,7 +286,7 @@ AP4_IsmaTrackDecrypter::GetProcessedSampleSize(AP4_Sample& sample)
/*----------------------------------------------------------------------
| AP4_IsmaTrackDecrypter::ProcessTrack
+---------------------------------------------------------------------*/
-AP4_Result
+AP4_Result
AP4_IsmaTrackDecrypter::ProcessTrack()
{
m_SampleEntry->SetType(m_OriginalFormat);
@@ -309,7 +297,7 @@ AP4_IsmaTrackDecrypter::ProcessTrack()
/*----------------------------------------------------------------------
| AP4_IsmaDecrypter::ProcessSample
+---------------------------------------------------------------------*/
-AP4_Result
+AP4_Result
AP4_IsmaTrackDecrypter::ProcessSample(AP4_DataBuffer& data_in,
AP4_DataBuffer& data_out)
{
@@ -319,8 +307,7 @@ AP4_IsmaTrackDecrypter::ProcessSample(AP4_DataBuffer& data_in,
/*----------------------------------------------------------------------
| AP4_IsmaTrackEncrypter
+---------------------------------------------------------------------*/
-class AP4_IsmaTrackEncrypter : public AP4_Processor::TrackHandler
-{
+class AP4_IsmaTrackEncrypter : public AP4_Processor::TrackHandler {
public:
// constructor
AP4_IsmaTrackEncrypter(const char* kms_uri,
@@ -374,16 +361,16 @@ AP4_IsmaTrackEncrypter::~AP4_IsmaTrackEncrypter()
/*----------------------------------------------------------------------
| AP4_IsmaTrackEncrypter::GetProcessedSampleSize
+---------------------------------------------------------------------*/
-AP4_Size
+AP4_Size
AP4_IsmaTrackEncrypter::GetProcessedSampleSize(AP4_Sample& sample)
{
- return sample.GetSize() + 4; //fixed header size for now
+ return sample.GetSize()+4; //fixed header size for now
}
/*----------------------------------------------------------------------
| AP4_IsmaTrackEncrypter::ProcessTrack
+---------------------------------------------------------------------*/
-AP4_Result
+AP4_Result
AP4_IsmaTrackEncrypter::ProcessTrack()
{
// sinf container
@@ -391,16 +378,16 @@ AP4_IsmaTrackEncrypter::ProcessTrack()
// original format
AP4_FrmaAtom* frma = new AP4_FrmaAtom(m_SampleEntry->GetType());
-
+
// scheme
AP4_SchmAtom* schm = new AP4_SchmAtom(AP4_PROTECTION_SCHEME_TYPE_IAEC, 1);
-
+
// scheme info
AP4_ContainerAtom* schi = new AP4_ContainerAtom(AP4_ATOM_TYPE_SCHI);
AP4_IkmsAtom* ikms = new AP4_IkmsAtom(m_KmsUri.GetChars());
- AP4_IsfmAtom* isfm = new AP4_IsfmAtom(m_Cipher->GetSelectiveEncryption(),
- m_Cipher->GetKeyIndicatorLength(),
- m_Cipher->GetIvLength());
+ AP4_IsfmAtom* isfm = new AP4_IsfmAtom(m_Cipher->GetSelectiveEncryption(),
+ m_Cipher->GetKeyIndicatorLength(),
+ m_Cipher->GetIvLength());
AP4_IsltAtom* islt = new AP4_IsltAtom(m_Cipher->GetCipher()->GetIV());
// populate the schi container
@@ -418,21 +405,21 @@ AP4_IsmaTrackEncrypter::ProcessTrack()
// change the atom type of the sample description
m_SampleEntry->SetType(m_Format);
-
+
return AP4_SUCCESS;
}
/*----------------------------------------------------------------------
| AP4_IsmaTrackEncrypter::ProcessSample
+---------------------------------------------------------------------*/
-AP4_Result
+AP4_Result
AP4_IsmaTrackEncrypter::ProcessSample(AP4_DataBuffer& data_in,
AP4_DataBuffer& data_out)
{
AP4_Result result = m_Cipher->EncryptSampleData(data_in, data_out, m_Counter);
- if(AP4_FAILED(result)) return result;
+ if (AP4_FAILED(result)) return result;
- m_Counter += (data_in.GetDataSize() + AP4_CIPHER_BLOCK_SIZE - 1) / AP4_CIPHER_BLOCK_SIZE;
+ m_Counter += (data_in.GetDataSize()+AP4_CIPHER_BLOCK_SIZE-1)/AP4_CIPHER_BLOCK_SIZE;
return AP4_SUCCESS;
}
@@ -440,15 +427,12 @@ AP4_IsmaTrackEncrypter::ProcessSample(AP4_DataBuffer& data_in,
| AP4_IsmaEncryptingProcessor::AP4_IsmaEncryptingProcessor
+---------------------------------------------------------------------*/
AP4_IsmaEncryptingProcessor::AP4_IsmaEncryptingProcessor(const char* kms_uri,
- AP4_BlockCipherFactory* block_cipher_factory) :
+ AP4_BlockCipherFactory* block_cipher_factory) :
m_KmsUri(kms_uri)
{
- if(block_cipher_factory == NULL)
- {
+ if (block_cipher_factory == NULL) {
m_BlockCipherFactory = &AP4_DefaultBlockCipherFactory::Instance;
- }
- else
- {
+ } else {
m_BlockCipherFactory = block_cipher_factory;
}
}
@@ -456,72 +440,66 @@ AP4_IsmaEncryptingProcessor::AP4_IsmaEncryptingProcessor(const char*
/*----------------------------------------------------------------------
| AP4_IsmaEncryptingProcessor:CreateTrackHandler
+---------------------------------------------------------------------*/
-AP4_Processor::TrackHandler*
+AP4_Processor::TrackHandler*
AP4_IsmaEncryptingProcessor::CreateTrackHandler(AP4_TrakAtom* trak)
{
// find the stsd atom
AP4_StsdAtom* stsd = AP4_DYNAMIC_CAST(AP4_StsdAtom, trak->FindChild("mdia/minf/stbl/stsd"));
// avoid tracks with no stsd atom (should not happen)
- if(stsd == NULL) return NULL;
+ if (stsd == NULL) return NULL;
// only look at the first sample description
AP4_SampleEntry* entry = stsd->GetSampleEntry(0);
- if(entry == NULL) return NULL;
-
+ if (entry == NULL) return NULL;
+
// create a handler for this track if we have a key for it and we know
// how to map the type
const AP4_UI08* key;
const AP4_UI08* salt;
AP4_UI32 format = 0;
- if(AP4_SUCCEEDED(m_KeyMap.GetKeyAndIv(trak->GetId(), key, salt)))
- {
- switch(entry->GetType())
- {
- case AP4_ATOM_TYPE_MP4A:
- format = AP4_ATOM_TYPE_ENCA;
- break;
-
- case AP4_ATOM_TYPE_MP4V:
- case AP4_ATOM_TYPE_AVC1:
- format = AP4_ATOM_TYPE_ENCV;
- break;
-
- default:
- {
- // try to find if this is audio or video
- AP4_HdlrAtom* hdlr = AP4_DYNAMIC_CAST(AP4_HdlrAtom, trak->FindChild("mdia/hdlr"));
- if(hdlr)
- {
- switch(hdlr->GetHandlerType())
- {
- case AP4_HANDLER_TYPE_SOUN:
- format = AP4_ATOM_TYPE_ENCA;
- break;
-
- case AP4_HANDLER_TYPE_VIDE:
- format = AP4_ATOM_TYPE_ENCV;
- break;
+ if (AP4_SUCCEEDED(m_KeyMap.GetKeyAndIv(trak->GetId(), key, salt))) {
+ switch (entry->GetType()) {
+ case AP4_ATOM_TYPE_MP4A:
+ format = AP4_ATOM_TYPE_ENCA;
+ break;
+
+ case AP4_ATOM_TYPE_MP4V:
+ case AP4_ATOM_TYPE_AVC1:
+ format = AP4_ATOM_TYPE_ENCV;
+ break;
+
+ default: {
+ // try to find if this is audio or video
+ AP4_HdlrAtom* hdlr = AP4_DYNAMIC_CAST(AP4_HdlrAtom, trak->FindChild("mdia/hdlr"));
+ if (hdlr) {
+ switch (hdlr->GetHandlerType()) {
+ case AP4_HANDLER_TYPE_SOUN:
+ format = AP4_ATOM_TYPE_ENCA;
+ break;
+
+ case AP4_HANDLER_TYPE_VIDE:
+ format = AP4_ATOM_TYPE_ENCV;
+ break;
+ }
}
+ break;
}
- break;
- }
}
- if(format)
- {
+ if (format) {
// create the block cipher
AP4_BlockCipher* block_cipher = NULL;
- AP4_Result result = m_BlockCipherFactory->Create(AP4_BlockCipher::AES_128,
- AP4_BlockCipher::ENCRYPT,
- key,
- AP4_CIPHER_BLOCK_SIZE,
- block_cipher);
- if(AP4_FAILED(result)) return NULL;
+ AP4_Result result = m_BlockCipherFactory->Create(AP4_BlockCipher::AES_128,
+ AP4_BlockCipher::ENCRYPT,
+ key,
+ AP4_CIPHER_BLOCK_SIZE,
+ block_cipher);
+ if (AP4_FAILED(result)) return NULL;
// create the encrypter
- return new AP4_IsmaTrackEncrypter(m_KmsUri.GetChars(),
- block_cipher,
- salt,
+ return new AP4_IsmaTrackEncrypter(m_KmsUri.GetChars(),
+ block_cipher,
+ salt,
entry,
format);
}
diff --git a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4IsmaCryp.h b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4IsmaCryp.h
index 703d3268d..34cde13d8 100644
--- a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4IsmaCryp.h
+++ b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4IsmaCryp.h
@@ -49,7 +49,7 @@ class AP4_IsfmAtom;
/*----------------------------------------------------------------------
| constants
+---------------------------------------------------------------------*/
-const AP4_UI32 AP4_PROTECTION_SCHEME_TYPE_IAEC = AP4_ATOM_TYPE('i', 'A', 'E', 'C');
+const AP4_UI32 AP4_PROTECTION_SCHEME_TYPE_IAEC = AP4_ATOM_TYPE('i','A','E','C');
/*----------------------------------------------------------------------
| AP4_IsmaCipher
@@ -59,18 +59,18 @@ class AP4_IsmaCipher : public AP4_SampleDecrypter
public:
// factory
static AP4_Result CreateSampleDecrypter(AP4_ProtectedSampleDescription* sample_description,
- const AP4_UI08* key,
+ const AP4_UI08* key,
AP4_Size key_size,
AP4_BlockCipherFactory* block_cipher_factory,
AP4_IsmaCipher*& decrypter);
// constructor and destructor
- AP4_IsmaCipher(AP4_BlockCipher* block_cipher,
+ AP4_IsmaCipher(AP4_BlockCipher* block_cipher,
const AP4_UI08* salt,
AP4_UI08 iv_length,
AP4_UI08 key_indicator_length,
bool selective_encryption);
- ~AP4_IsmaCipher();
+ ~AP4_IsmaCipher();
AP4_Result EncryptSampleData(AP4_DataBuffer& data_in,
AP4_DataBuffer& data_out,
AP4_UI32 offset);
@@ -78,22 +78,10 @@ public:
AP4_DataBuffer& data_out,
const AP4_UI08* iv = NULL);
AP4_Size GetDecryptedSampleSize(AP4_Sample& sample);
- AP4_CtrStreamCipher* GetCipher()
- {
- return m_Cipher;
- }
- AP4_UI08 GetIvLength()
- {
- return m_IvLength;
- }
- AP4_UI08 GetKeyIndicatorLength()
- {
- return m_KeyIndicatorLength;
- }
- bool GetSelectiveEncryption()
- {
- return m_SelectiveEncryption;
- }
+ AP4_CtrStreamCipher* GetCipher() { return m_Cipher; }
+ AP4_UI08 GetIvLength() { return m_IvLength; }
+ AP4_UI08 GetKeyIndicatorLength() { return m_KeyIndicatorLength; }
+ bool GetSelectiveEncryption(){ return m_SelectiveEncryption;}
private:
// members
@@ -106,11 +94,10 @@ private:
/*----------------------------------------------------------------------
| AP4_IsmaTrackDecrypter
+---------------------------------------------------------------------*/
-class AP4_IsmaTrackDecrypter : public AP4_Processor::TrackHandler
-{
+class AP4_IsmaTrackDecrypter : public AP4_Processor::TrackHandler {
public:
// construction
- static AP4_Result Create(const AP4_UI08* key,
+ static AP4_Result Create(const AP4_UI08* key,
AP4_Size key_size,
AP4_ProtectedSampleDescription* sample_description,
AP4_SampleEntry* sample_entry,
@@ -148,10 +135,7 @@ public:
AP4_BlockCipherFactory* block_cipher_factory = NULL);
// accessors
- AP4_ProtectionKeyMap& GetKeyMap()
- {
- return m_KeyMap;
- }
+ AP4_ProtectionKeyMap& GetKeyMap() { return m_KeyMap; }
// methods
virtual AP4_Processor::TrackHandler* CreateTrackHandler(AP4_TrakAtom* trak);
diff --git a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4LinearReader.cpp b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4LinearReader.cpp
index d77329f0c..e8c32b558 100644
--- a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4LinearReader.cpp
+++ b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4LinearReader.cpp
@@ -48,8 +48,7 @@ AP4_LinearReader::AP4_LinearReader(AP4_Movie& movie, AP4_Size max_buffer) :
+---------------------------------------------------------------------*/
AP4_LinearReader::~AP4_LinearReader()
{
- for(unsigned int i = 0; i < m_Trackers.ItemCount(); i++)
- {
+ for (unsigned int i=0; i<m_Trackers.ItemCount(); i++) {
delete m_Trackers[i];
}
}
@@ -57,16 +56,16 @@ AP4_LinearReader::~AP4_LinearReader()
/*----------------------------------------------------------------------
| AP4_LinearReader::EnableTrack
+---------------------------------------------------------------------*/
-AP4_Result
+AP4_Result
AP4_LinearReader::EnableTrack(AP4_UI32 track_id)
{
// check if we don't already have this
- if(FindTracker(track_id)) return AP4_SUCCESS;
+ if (FindTracker(track_id)) return AP4_SUCCESS;
// find the track in the movie
AP4_Track* track = m_Movie.GetTrack(track_id);
- if(track == NULL) return AP4_ERROR_NO_SUCH_ITEM;
-
+ if (track == NULL) return AP4_ERROR_NO_SUCH_ITEM;
+
// create a new entry for the track
return m_Trackers.Append(new Tracker(track));
}
@@ -74,32 +73,30 @@ AP4_LinearReader::EnableTrack(AP4_UI32 track_id)
/*----------------------------------------------------------------------
| AP4_LinearReader::SetSampleIndex
+---------------------------------------------------------------------*/
-AP4_Result
+AP4_Result
AP4_LinearReader::SetSampleIndex(AP4_UI32 track_id, AP4_UI32 sample_index)
{
Tracker* tracker = FindTracker(track_id);
- if(tracker == NULL) return AP4_ERROR_INVALID_PARAMETERS;
+ if (tracker == NULL) return AP4_ERROR_INVALID_PARAMETERS;
assert(tracker->m_Track);
delete tracker->m_NextSample;
tracker->m_NextSample = NULL;
- if(sample_index >= tracker->m_Track->GetSampleCount())
- {
+ if (sample_index >= tracker->m_Track->GetSampleCount()) {
return AP4_ERROR_OUT_OF_RANGE;
}
tracker->m_Eos = false;
tracker->m_NextSampleIndex = sample_index;
-
+
// empty any queued samples
- for(AP4_List<SampleBuffer>::Item* item = tracker->m_Samples.FirstItem();
- item;
- item = item->GetNext())
- {
+ for (AP4_List<SampleBuffer>::Item* item = tracker->m_Samples.FirstItem();
+ item;
+ item = item->GetNext()) {
SampleBuffer* buffer = item->GetData();
m_BufferFullness -= buffer->m_Sample->GetSize();
delete buffer;
}
tracker->m_Samples.Clear();
-
+
return AP4_SUCCESS;
}
@@ -110,30 +107,25 @@ AP4_Result
AP4_LinearReader::Advance()
{
// first, check if we have space to advance
- if(m_BufferFullness >= m_MaxBufferFullness)
- {
+ if (m_BufferFullness >= m_MaxBufferFullness) {
return AP4_ERROR_NOT_ENOUGH_SPACE;
}
-
+
AP4_UI64 min_offset = (AP4_UI64)(-1);
Tracker* next_tracker = NULL;
- for(unsigned int i = 0; i < m_Trackers.ItemCount(); i++)
- {
+ for (unsigned int i=0; i<m_Trackers.ItemCount(); i++) {
Tracker* tracker = m_Trackers[i];
- if(tracker->m_Eos) continue;
-
+ if (tracker->m_Eos) continue;
+
// get the next sample unless we have it already
- if(tracker->m_NextSample == NULL)
- {
- if(tracker->m_NextSampleIndex >= tracker->m_Track->GetSampleCount())
- {
+ if (tracker->m_NextSample == NULL) {
+ if (tracker->m_NextSampleIndex >= tracker->m_Track->GetSampleCount()) {
tracker->m_Eos = true;
continue;
}
tracker->m_NextSample = new AP4_Sample();
AP4_Result result = tracker->m_Track->GetSample(tracker->m_NextSampleIndex, *tracker->m_NextSample);
- if(AP4_FAILED(result))
- {
+ if (AP4_FAILED(result)) {
tracker->m_Eos = true;
delete tracker->m_NextSample;
tracker->m_NextSample = NULL;
@@ -141,49 +133,45 @@ AP4_LinearReader::Advance()
}
}
assert(tracker->m_NextSample);
-
+
AP4_UI64 offset = tracker->m_NextSample->GetOffset();
- if(offset < min_offset)
- {
+ if (offset < min_offset) {
min_offset = offset;
next_tracker = tracker;
}
}
-
- if(next_tracker)
- {
+
+ if (next_tracker) {
// read the sample into a buffer
assert(next_tracker->m_NextSample);
SampleBuffer* buffer = new SampleBuffer(next_tracker->m_NextSample);
AP4_Result result = buffer->m_Sample->ReadData(buffer->m_Data);
- if(AP4_FAILED(result)) return result;
-
+ if (AP4_FAILED(result)) return result;
+
// add the buffer to the queue
next_tracker->m_Samples.Add(buffer);
m_BufferFullness += next_tracker->m_NextSample->GetSize();
- if(m_BufferFullness > m_BufferFullnessPeak)
- {
+ if (m_BufferFullness > m_BufferFullnessPeak) {
m_BufferFullnessPeak = m_BufferFullness;
}
next_tracker->m_NextSample = NULL;
next_tracker->m_NextSampleIndex++;
return AP4_SUCCESS;
- }
-
- return AP4_ERROR_EOS;
+ }
+
+ return AP4_ERROR_EOS;
}
/*----------------------------------------------------------------------
| AP4_LinearReader::PopSample
+---------------------------------------------------------------------*/
bool
-AP4_LinearReader::PopSample(Tracker* tracker,
- AP4_Sample& sample,
+AP4_LinearReader::PopSample(Tracker* tracker,
+ AP4_Sample& sample,
AP4_DataBuffer& sample_data)
{
SampleBuffer* head = NULL;
- if(AP4_SUCCEEDED(tracker->m_Samples.PopHead(head)))
- {
+ if (AP4_SUCCEEDED(tracker->m_Samples.PopHead(head))) {
assert(head->m_Sample);
sample = *head->m_Sample;
sample_data.SetData(head->m_Data.GetData(), head->m_Data.GetDataSize());
@@ -192,89 +180,81 @@ AP4_LinearReader::PopSample(Tracker* tracker,
delete head;
return true;
}
-
+
return false;
}
/*----------------------------------------------------------------------
| AP4_LinearReader::ReadNextSample
+---------------------------------------------------------------------*/
-AP4_Result
+AP4_Result
AP4_LinearReader::ReadNextSample(AP4_UI32 track_id,
AP4_Sample& sample,
AP4_DataBuffer& sample_data)
{
- if(m_Trackers.ItemCount() == 0)
- {
+ if (m_Trackers.ItemCount() == 0) {
return AP4_ERROR_NO_SUCH_ITEM;
}
-
+
// look for a sample from a specific track
Tracker* tracker = FindTracker(track_id);
- if(tracker == NULL) return AP4_ERROR_INVALID_PARAMETERS;
- for(;;)
- {
- if(tracker->m_Eos) return AP4_ERROR_EOS;
+ if (tracker == NULL) return AP4_ERROR_INVALID_PARAMETERS;
+ for(;;) {
+ if (tracker->m_Eos) return AP4_ERROR_EOS;
// pop a sample if we can
- if(PopSample(tracker, sample, sample_data)) return AP4_SUCCESS;
+ if (PopSample(tracker, sample, sample_data)) return AP4_SUCCESS;
AP4_Result result = Advance();
- if(AP4_FAILED(result)) return result;
+ if (AP4_FAILED(result)) return result;
}
-
+
return AP4_ERROR_EOS;
}
/*----------------------------------------------------------------------
| AP4_LinearReader::ReadNextSample
+---------------------------------------------------------------------*/
-AP4_Result
+AP4_Result
AP4_LinearReader::ReadNextSample(AP4_Sample& sample,
AP4_DataBuffer& sample_data,
AP4_UI32& track_id)
{
- if(m_Trackers.ItemCount() == 0)
- {
+ if (m_Trackers.ItemCount() == 0) {
track_id = 0;
return AP4_ERROR_NO_SUCH_ITEM;
}
-
+
// return the oldest buffered sample, if any
AP4_UI64 min_offset = (AP4_UI64)(-1);
Tracker* next_tracker = NULL;
- for(;;)
- {
- for(unsigned int i = 0; i < m_Trackers.ItemCount(); i++)
- {
+ for (;;) {
+ for (unsigned int i=0; i<m_Trackers.ItemCount(); i++) {
Tracker* tracker = m_Trackers[i];
- if(tracker->m_Eos) continue;
-
+ if (tracker->m_Eos) continue;
+
AP4_List<SampleBuffer>::Item* item = tracker->m_Samples.FirstItem();
- if(item)
- {
+ if (item) {
AP4_UI64 offset = item->GetData()->m_Sample->GetOffset();
- if(offset < min_offset)
- {
+ if (offset < min_offset) {
min_offset = offset;
next_tracker = tracker;
}
}
}
-
+
// return the sample if we have found a tracker
- if(next_tracker)
- {
+ if (next_tracker) {
PopSample(next_tracker, sample, sample_data);
track_id = next_tracker->m_Track->GetId();
return AP4_SUCCESS;
}
-
+
// nothing found, read one more sample
AP4_Result result = Advance();
- if(AP4_FAILED(result)) return result;
+ if (AP4_FAILED(result)) return result;
}
-
+
return AP4_ERROR_EOS;
}
@@ -284,11 +264,10 @@ AP4_LinearReader::ReadNextSample(AP4_Sample& sample,
AP4_LinearReader::Tracker*
AP4_LinearReader::FindTracker(AP4_UI32 track_id)
{
- for(unsigned int i = 0; i < m_Trackers.ItemCount(); i++)
- {
- if(m_Trackers[i]->m_Track->GetId() == track_id) return m_Trackers[i];
+ for (unsigned int i=0; i<m_Trackers.ItemCount(); i++) {
+ if (m_Trackers[i]->m_Track->GetId() == track_id) return m_Trackers[i];
}
-
+
// not found
return NULL;
}
diff --git a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4LinearReader.h b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4LinearReader.h
index d5dec5cb3..7ebeff4f7 100644
--- a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4LinearReader.h
+++ b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4LinearReader.h
@@ -48,81 +48,69 @@ class AP4_Track;
const unsigned int AP4_LINEAR_READER_INITIALIZED = 1;
const unsigned int AP4_LINEAR_READER_FLAG_EOS = 2;
-const unsigned int AP4_LINEAR_READER_DEFAULT_BUFFER_SIZE = 4096 * 1024;
+const unsigned int AP4_LINEAR_READER_DEFAULT_BUFFER_SIZE = 4096*1024;
/*----------------------------------------------------------------------
| AP4_LinearReader
+---------------------------------------------------------------------*/
-class AP4_LinearReader
-{
+class AP4_LinearReader {
public:
- AP4_LinearReader(AP4_Movie& movie, AP4_Size max_buffer = AP4_LINEAR_READER_DEFAULT_BUFFER_SIZE);
- ~AP4_LinearReader();
-
+ AP4_LinearReader(AP4_Movie& movie, AP4_Size max_buffer=AP4_LINEAR_READER_DEFAULT_BUFFER_SIZE);
+ ~AP4_LinearReader();
+
AP4_Result EnableTrack(AP4_UI32 track_id);
/**
* Read the next sample in storage order, from any track.
* track_id is updated to reflect the track from which the sample was read.
*/
- AP4_Result ReadNextSample(AP4_Sample& sample,
+ AP4_Result ReadNextSample(AP4_Sample& sample,
AP4_DataBuffer& sample_data,
AP4_UI32& track_id);
/**
* Read the next sample in storage order from a specific track.
*/
AP4_Result ReadNextSample(AP4_UI32 track_id,
- AP4_Sample& sample,
+ AP4_Sample& sample,
AP4_DataBuffer& sample_data);
-
+
AP4_Result SetSampleIndex(AP4_UI32 track_id, AP4_UI32 sample_index);
-
+
// accessors
- AP4_Size GetBufferFullness()
- {
- return m_BufferFullness;
- }
-
+ AP4_Size GetBufferFullness() { return m_BufferFullness; }
+
private:
- class SampleBuffer
- {
+ class SampleBuffer {
public:
SampleBuffer(AP4_Sample* sample) : m_Sample(sample) {}
- ~SampleBuffer()
- {
- delete m_Sample;
- }
+ ~SampleBuffer() { delete m_Sample; }
AP4_Sample* m_Sample;
AP4_DataBuffer m_Data;
};
- class Tracker
- {
+ class Tracker {
public:
Tracker(AP4_Track* track) :
m_Eos(false),
- m_Track(track),
+ m_Track(track),
m_NextSample(NULL),
m_NextSampleIndex(0) {}
- Tracker(const Tracker& other) :
+ Tracker(const Tracker& other) :
m_Eos(other.m_Eos),
m_Track(other.m_Track),
m_NextSample(NULL),
m_NextSampleIndex(other.m_NextSampleIndex) {} // don't copy samples
- ~Tracker()
- {
- m_Samples.DeleteReferences();
- }
+ ~Tracker() { m_Samples.DeleteReferences(); }
bool m_Eos;
AP4_Track* m_Track;
AP4_Sample* m_NextSample;
AP4_Ordinal m_NextSampleIndex;
AP4_List<SampleBuffer> m_Samples;
};
-
+
// methods
Tracker* FindTracker(AP4_UI32 track_id);
AP4_Result Advance();
bool PopSample(Tracker* tracker, AP4_Sample& sample, AP4_DataBuffer& sample_data);
-
+
// members
AP4_Movie& m_Movie;
AP4_Array<Tracker*> m_Trackers;
diff --git a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4List.h b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4List.h
index 84891b743..d6a28cc63 100644
--- a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4List.h
+++ b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4List.h
@@ -43,16 +43,16 @@ template <typename T> class AP4_List;
/*----------------------------------------------------------------------
| AP4_List
+---------------------------------------------------------------------*/
-template <typename T>
-class AP4_List
+template <typename T>
+class AP4_List
{
public:
// types
- class Item
+ class Item
{
public:
// types
- class Operator
+ class Operator
{
public:
// methods
@@ -60,7 +60,7 @@ public:
virtual AP4_Result Action(T* data) const = 0;
};
- class Finder
+ class Finder
{
public:
// methods
@@ -70,19 +70,10 @@ public:
// methods
Item(T* data) : m_Data(data), m_Next(0), m_Prev(0) {}
- ~Item() {}
- Item* GetNext()
- {
- return m_Next;
- }
- Item* GetPrev()
- {
- return m_Prev;
- }
- T* GetData()
- {
- return m_Data;
- }
+ ~Item() {}
+ Item* GetNext() { return m_Next; }
+ Item* GetPrev() { return m_Prev; }
+ T* GetData() { return m_Data; }
private:
// members
@@ -95,7 +86,7 @@ public:
};
// methods
- AP4_List<T>(): m_ItemCount(0), m_Head(0), m_Tail(0) {}
+ AP4_List<T>(): m_ItemCount(0), m_Head(0), m_Tail(0) {}
virtual ~AP4_List<T>();
AP4_Result Clear();
AP4_Result Add(T* data);
@@ -111,29 +102,20 @@ public:
AP4_Result Find(const typename Item::Finder& finder, T*& data) const;
AP4_Result ReverseFind(const typename Item::Finder& finder, T*& data) const;
AP4_Result DeleteReferences();
- AP4_Cardinal ItemCount() const
- {
- return m_ItemCount;
- }
- Item* FirstItem() const
- {
- return m_Head;
- }
- Item* LastItem() const
- {
- return m_Tail;
- }
-
+ AP4_Cardinal ItemCount() const { return m_ItemCount; }
+ Item* FirstItem() const { return m_Head; }
+ Item* LastItem() const { return m_Tail; }
+
protected:
// members
AP4_Cardinal m_ItemCount;
Item* m_Head;
Item* m_Tail;
-
+
private:
- // these cannot be used
+ // these cannot be used
AP4_List<T>(const AP4_List<T>&);
- AP4_List<T>& operator=(const AP4_List<T>&);
+ AP4_List<T>& operator=(const AP4_List<T>&);
};
/*----------------------------------------------------------------------
@@ -154,19 +136,18 @@ AP4_Result
AP4_List<T>::Clear()
{
Item* item = m_Head;
-
- while(item)
- {
+
+ while (item) {
Item* next = item->m_Next;
delete item;
item = next;
}
m_ItemCount = 0;
m_Head = m_Tail = NULL;
-
+
return AP4_SUCCESS;
}
-
+
/*----------------------------------------------------------------------
| AP4_List<T>::Add
+---------------------------------------------------------------------*/
@@ -186,15 +167,12 @@ AP4_Result
AP4_List<T>::Add(Item* item)
{
// add element at the tail
- if(m_Tail)
- {
+ if (m_Tail) {
item->m_Prev = m_Tail;
item->m_Next = NULL;
m_Tail->m_Next = item;
m_Tail = item;
- }
- else
- {
+ } else {
m_Head = item;
m_Tail = item;
item->m_Next = NULL;
@@ -203,7 +181,7 @@ AP4_List<T>::Add(Item* item)
// one more item in the list now
m_ItemCount++;
-
+
return AP4_SUCCESS;
}
@@ -216,38 +194,27 @@ AP4_List<T>::Remove(T* data)
{
Item* item = m_Head;
- while(item)
- {
- if(item->m_Data == data)
- {
+ while (item) {
+ if (item->m_Data == data) {
// delete item
- if(item->m_Prev)
- {
+ if (item->m_Prev) {
// item is not the head
- if(item->m_Next)
- {
+ if (item->m_Next) {
// item is not the tail
item->m_Next->m_Prev = item->m_Prev;
item->m_Prev->m_Next = item->m_Next;
- }
- else
- {
+ } else {
// item is the tail
m_Tail = item->m_Prev;
m_Tail->m_Next = NULL;
}
- }
- else
- {
+ } else {
// item is the head
m_Head = item->m_Next;
- if(m_Head)
- {
+ if (m_Head) {
// item is not the tail
m_Head->m_Prev = NULL;
- }
- else
- {
+ } else {
// item is also the tail
m_Tail = NULL;
}
@@ -263,7 +230,7 @@ AP4_List<T>::Remove(T* data)
}
item = item->m_Next;
}
-
+
return AP4_ERROR_NO_SUCH_ITEM;
}
@@ -276,36 +243,27 @@ AP4_List<T>::Insert(Item* where, T* data)
{
Item* item = new Item(data);
- if(where == NULL)
- {
+ if (where == NULL) {
// insert as the head
- if(m_Head)
- {
+ if (m_Head) {
// replace the current head
item->m_Prev = NULL;
item->m_Next = m_Head;
m_Head->m_Prev = item;
m_Head = item;
- }
- else
- {
+ } else {
// this item becomes the head and tail
m_Head = item;
m_Tail = item;
item->m_Next = NULL;
item->m_Prev = NULL;
}
- }
- else
- {
+ } else {
// insert after the 'where' item
- if(where == m_Tail)
- {
+ if (where == m_Tail) {
// add the item at the end
return Add(item);
- }
- else
- {
+ } else {
// update the links
item->m_Prev = where;
item->m_Next = where->m_Next;
@@ -329,14 +287,11 @@ AP4_List<T>::Get(AP4_Ordinal idx, T*& data) const
{
Item* item = m_Head;
- if(idx < m_ItemCount)
- {
- while(idx--) item = item->m_Next;
+ if (idx < m_ItemCount) {
+ while (idx--) item = item->m_Next;
data = item->m_Data;
return AP4_SUCCESS;
- }
- else
- {
+ } else {
data = NULL;
return AP4_ERROR_NO_SUCH_ITEM;
}
@@ -350,8 +305,7 @@ AP4_Result
AP4_List<T>::PopHead(T*& data)
{
// check that we have at least one item
- if(m_Head == NULL)
- {
+ if (m_Head == NULL) {
return AP4_ERROR_LIST_EMPTY;
}
@@ -359,12 +313,9 @@ AP4_List<T>::PopHead(T*& data)
data = m_Head->m_Data;
Item* head = m_Head;
m_Head = m_Head->m_Next;
- if(m_Head)
- {
+ if (m_Head) {
m_Head->m_Prev = NULL;
- }
- else
- {
+ } else {
m_Tail = NULL;
}
@@ -373,7 +324,7 @@ AP4_List<T>::PopHead(T*& data)
// one less item in the list now
m_ItemCount--;
-
+
return AP4_SUCCESS;
}
@@ -381,14 +332,13 @@ AP4_List<T>::PopHead(T*& data)
| AP4_List<T>::Apply
+---------------------------------------------------------------------*/
template <typename T>
-inline
+inline
AP4_Result
AP4_List<T>::Apply(const typename Item::Operator& op) const
{
Item* item = m_Head;
-
- while(item)
- {
+
+ while (item) {
op.Action(item->m_Data);
item = item->m_Next;
}
@@ -400,17 +350,16 @@ AP4_List<T>::Apply(const typename Item::Operator& op) const
| AP4_List<T>::ApplyUntilFailure
+---------------------------------------------------------------------*/
template <typename T>
-inline
+inline
AP4_Result
AP4_List<T>::ApplyUntilFailure(const typename Item::Operator& op) const
{
Item* item = m_Head;
-
- while(item)
- {
+
+ while (item) {
AP4_Result result;
result = op.Action(item->m_Data);
- if(result != AP4_SUCCESS) return result;
+ if (result != AP4_SUCCESS) return result;
item = item->m_Next;
}
@@ -421,17 +370,16 @@ AP4_List<T>::ApplyUntilFailure(const typename Item::Operator& op) const
| AP4_List<T>::ApplyUntilSuccess
+---------------------------------------------------------------------*/
template <typename T>
-inline
+inline
AP4_Result
AP4_List<T>::ApplyUntilSuccess(const typename Item::Operator& op) const
{
Item* item = m_Head;
-
- while(item)
- {
+
+ while (item) {
AP4_Result result;
result = op.Action(item->m_Data);
- if(result == AP4_SUCCESS) return AP4_SUCCESS;
+ if (result == AP4_SUCCESS) return AP4_SUCCESS;
item = item->m_Next;
}
@@ -442,16 +390,14 @@ AP4_List<T>::ApplyUntilSuccess(const typename Item::Operator& op) const
| AP4_List<T>::ReverseApply
+---------------------------------------------------------------------*/
template <typename T>
-inline
+inline
AP4_Result
AP4_List<T>::ReverseApply(const typename Item::Operator& op) const
{
Item* item = m_Tail;
-
- while(item)
- {
- if(op.Action(item->m_Data) != AP4_SUCCESS)
- {
+
+ while (item) {
+ if (op.Action(item->m_Data) != AP4_SUCCESS) {
return AP4_ERROR_LIST_OPERATION_ABORTED;
}
item = item->m_Prev;
@@ -464,16 +410,14 @@ AP4_List<T>::ReverseApply(const typename Item::Operator& op) const
| AP4_List<T>::Find
+---------------------------------------------------------------------*/
template <typename T>
-inline
+inline
AP4_Result
AP4_List<T>::Find(const typename Item::Finder& finder, T*& data) const
{
Item* item = m_Head;
-
- while(item)
- {
- if(finder.Test(item->m_Data) == AP4_SUCCESS)
- {
+
+ while (item) {
+ if (finder.Test(item->m_Data) == AP4_SUCCESS) {
data = item->m_Data;
return AP4_SUCCESS;
}
@@ -488,16 +432,14 @@ AP4_List<T>::Find(const typename Item::Finder& finder, T*& data) const
| AP4_List<T>::ReverseFind
+---------------------------------------------------------------------*/
template <typename T>
-inline
+inline
AP4_Result
AP4_List<T>::ReverseFind(const typename Item::Finder& finder, T*& data) const
{
Item* item = m_Tail;
-
- while(item)
- {
- if(finder.Test(item->m_Data) == AP4_SUCCESS)
- {
+
+ while (item) {
+ if (finder.Test(item->m_Data) == AP4_SUCCESS) {
data = item->m_Data;
return AP4_SUCCESS;
}
@@ -512,14 +454,13 @@ AP4_List<T>::ReverseFind(const typename Item::Finder& finder, T*& data) const
| AP4_List<T>::DeleteReferences
+---------------------------------------------------------------------*/
template <typename T>
-inline
+inline
AP4_Result
AP4_List<T>::DeleteReferences()
{
Item* item = m_Head;
-
- while(item)
- {
+
+ while (item) {
Item* next = item->m_Next;
delete item->m_Data;
delete item;
diff --git a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4Marlin.cpp b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4Marlin.cpp
index 86b197237..c4464f5df 100644
--- a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4Marlin.cpp
+++ b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4Marlin.cpp
@@ -60,12 +60,12 @@ class AP4_MarlinIpmpAtomTypeHandler : public AP4_AtomFactory::TypeHandler
public:
// constructor
AP4_MarlinIpmpAtomTypeHandler(AP4_AtomFactory* atom_factory) :
- m_AtomFactory(atom_factory) {}
- virtual AP4_Result CreateAtom(AP4_Atom::Type type,
- AP4_UI32 size,
- AP4_ByteStream& stream,
- AP4_Atom::Type context,
- AP4_Atom*& atom);
+ m_AtomFactory(atom_factory) {}
+ virtual AP4_Result CreateAtom(AP4_Atom::Type type,
+ AP4_UI32 size,
+ AP4_ByteStream& stream,
+ AP4_Atom::Type context,
+ AP4_Atom*& atom);
private:
// members
@@ -82,8 +82,7 @@ public:
static AP4_MarlinIpmpAtomFactory Instance;
// constructor
- AP4_MarlinIpmpAtomFactory()
- {
+ AP4_MarlinIpmpAtomFactory() {
AddTypeHandler(new AP4_MarlinIpmpAtomTypeHandler(this));
}
};
@@ -96,25 +95,24 @@ AP4_MarlinIpmpAtomFactory AP4_MarlinIpmpAtomFactory::Instance;
/*----------------------------------------------------------------------
| AP4_MarlinIpmpAtomTypeHandler::CreateAtom
+---------------------------------------------------------------------*/
-AP4_Result
+AP4_Result
AP4_MarlinIpmpAtomTypeHandler::CreateAtom(AP4_Atom::Type type,
- AP4_UI32 size,
- AP4_ByteStream& stream,
- AP4_Atom::Type /*context*/,
- AP4_Atom*& atom)
+ AP4_UI32 size,
+ AP4_ByteStream& stream,
+ AP4_Atom::Type /*context*/,
+ AP4_Atom*& atom)
{
- switch(type)
- {
- case AP4_ATOM_TYPE_SATR:
- atom = AP4_ContainerAtom::Create(type, size, false, false, stream, *m_AtomFactory);
- break;
-
- case AP4_ATOM_TYPE_STYP:
- atom = new AP4_NullTerminatedStringAtom(type, size, stream);
- break;
+ switch (type) {
+ case AP4_ATOM_TYPE_SATR:
+ atom = AP4_ContainerAtom::Create(type, size, false, false, stream, *m_AtomFactory);
+ break;
+
+ case AP4_ATOM_TYPE_STYP:
+ atom = new AP4_NullTerminatedStringAtom(type, size, stream);
+ break;
- default:
- atom = NULL;
+ default:
+ atom = NULL;
}
return atom ? AP4_SUCCESS : AP4_FAILURE;
@@ -123,254 +121,222 @@ AP4_MarlinIpmpAtomTypeHandler::CreateAtom(AP4_Atom::Type type,
/*----------------------------------------------------------------------
| AP4_MarlinIpmpParser:Parse
+---------------------------------------------------------------------*/
-AP4_Result
-AP4_MarlinIpmpParser::Parse(AP4_AtomParent& top_level,
+AP4_Result
+AP4_MarlinIpmpParser::Parse(AP4_AtomParent& top_level,
AP4_ByteStream& stream,
AP4_List<SinfEntry>& sinf_entries,
bool remove_od_data)
{
// check the file type
AP4_FtypAtom* ftyp = AP4_DYNAMIC_CAST(AP4_FtypAtom, top_level.GetChild(AP4_ATOM_TYPE_FTYP));
- if(ftyp == NULL ||
- (ftyp->GetMajorBrand() != AP4_MARLIN_BRAND_MGSV && !ftyp->HasCompatibleBrand(AP4_MARLIN_BRAND_MGSV)))
- {
+ if (ftyp == NULL ||
+ (ftyp->GetMajorBrand() != AP4_MARLIN_BRAND_MGSV && !ftyp->HasCompatibleBrand(AP4_MARLIN_BRAND_MGSV))) {
return AP4_ERROR_INVALID_FORMAT;
}
-
+
// check the initial object descriptor and get the OD Track ID
AP4_IodsAtom* iods = AP4_DYNAMIC_CAST(AP4_IodsAtom, top_level.FindChild("moov/iods"));
AP4_UI32 od_track_id = 0;
- if(iods == NULL) return AP4_ERROR_INVALID_FORMAT;
+ if (iods == NULL) return AP4_ERROR_INVALID_FORMAT;
const AP4_ObjectDescriptor* od = iods->GetObjectDescriptor();
- if(od == NULL) return AP4_ERROR_INVALID_FORMAT;
+ if (od == NULL) return AP4_ERROR_INVALID_FORMAT;
AP4_EsIdIncDescriptor* es_id_inc = AP4_DYNAMIC_CAST(AP4_EsIdIncDescriptor, od->FindSubDescriptor(AP4_DESCRIPTOR_TAG_ES_ID_INC));
- if(es_id_inc == NULL) return AP4_ERROR_INVALID_FORMAT;
+ if (es_id_inc == NULL) return AP4_ERROR_INVALID_FORMAT;
od_track_id = es_id_inc->GetTrackId();
-
+
// find the track pointed to by the descriptor
AP4_MoovAtom* moov = AP4_DYNAMIC_CAST(AP4_MoovAtom, top_level.GetChild(AP4_ATOM_TYPE_MOOV));
- if(moov == NULL) return AP4_ERROR_INVALID_FORMAT;
+ if (moov == NULL) return AP4_ERROR_INVALID_FORMAT;
AP4_TrakAtom* od_trak = NULL;
- for(AP4_List<AP4_TrakAtom>::Item* trak_item = moov->GetTrakAtoms().FirstItem();
- trak_item;
- trak_item = trak_item->GetNext())
- {
+ for (AP4_List<AP4_TrakAtom>::Item* trak_item = moov->GetTrakAtoms().FirstItem();
+ trak_item;
+ trak_item = trak_item->GetNext()) {
AP4_TrakAtom* trak = trak_item->GetData();
- if(trak)
- {
- if(trak->GetId() == od_track_id)
- {
+ if (trak) {
+ if (trak->GetId() == od_track_id) {
od_trak = trak;
- }
- else
- {
+ } else {
sinf_entries.Add(new SinfEntry(trak->GetId(), NULL));
}
}
}
- // check that we have found the OD track
- if(od_trak == NULL) return AP4_ERROR_INVALID_FORMAT;
+ // check that we have found the OD track
+ if (od_trak == NULL) return AP4_ERROR_INVALID_FORMAT;
// look for the 'mpod' trak references
AP4_TrefTypeAtom* track_references;
track_references = AP4_DYNAMIC_CAST(AP4_TrefTypeAtom, od_trak->FindChild("tref/mpod"));
- if(track_references == NULL) return AP4_ERROR_INVALID_FORMAT;
+ if (track_references == NULL) return AP4_ERROR_INVALID_FORMAT;
// create an AP4_Track object from the trak atom and check that it has samples
AP4_Track* od_track = new AP4_Track(*od_trak, stream, 0);
- if(od_track->GetSampleCount() < 1)
- {
+ if (od_track->GetSampleCount() < 1) {
delete od_track;
return AP4_ERROR_INVALID_FORMAT;
}
-
+
// get the first sample (in this version, we only look at a single OD command)
AP4_Sample od_sample;
AP4_Result result = od_track->GetSample(0, od_sample);
- if(AP4_FAILED(result))
- {
+ if (AP4_FAILED(result)) {
delete od_track;
return AP4_ERROR_INVALID_FORMAT;
}
-
+
// adapt the sample data into a byte stream for parsing
AP4_DataBuffer sample_data;
od_sample.ReadData(sample_data);
AP4_MemoryByteStream* sample_stream = new AP4_MemoryByteStream(sample_data);
-
- // look for one ObjectDescriptorUpdate command and
+
+ // look for one ObjectDescriptorUpdate command and
// one IPMP_DescriptorUpdate command
AP4_DescriptorUpdateCommand* od_update = NULL;
AP4_DescriptorUpdateCommand* ipmp_update = NULL;
- do
- {
+ do {
AP4_Command* command = NULL;
result = AP4_CommandFactory::CreateCommandFromStream(*sample_stream, command);
- if(AP4_SUCCEEDED(result))
- {
+ if (AP4_SUCCEEDED(result)) {
// found a command in the sample, check the type
- switch(command->GetTag())
- {
- case AP4_COMMAND_TAG_OBJECT_DESCRIPTOR_UPDATE:
- if(od_update == NULL)
- {
+ switch (command->GetTag()) {
+ case AP4_COMMAND_TAG_OBJECT_DESCRIPTOR_UPDATE:
+ if (od_update == NULL) {
od_update = AP4_DYNAMIC_CAST(AP4_DescriptorUpdateCommand, command);
}
break;
-
- case AP4_COMMAND_TAG_IPMP_DESCRIPTOR_UPDATE:
- if(ipmp_update == NULL)
- {
+
+ case AP4_COMMAND_TAG_IPMP_DESCRIPTOR_UPDATE:
+ if (ipmp_update == NULL) {
ipmp_update = AP4_DYNAMIC_CAST(AP4_DescriptorUpdateCommand, command);
}
break;
- default:
+ default:
break;
}
}
- }
- while(AP4_SUCCEEDED(result));
+ } while (AP4_SUCCEEDED(result));
sample_stream->Release();
sample_stream = NULL;
-
+
// check that we have what we need
- if(od_update == NULL || ipmp_update == NULL)
- {
+ if (od_update == NULL || ipmp_update == NULL) {
delete od_track;
return AP4_ERROR_INVALID_FORMAT;
}
-
+
// process all the object descriptors in the od update
- for(AP4_List<AP4_Descriptor>::Item* od_item = od_update->GetDescriptors().FirstItem();
- od_item;
- od_item = od_item->GetNext())
- {
+ for (AP4_List<AP4_Descriptor>::Item* od_item = od_update->GetDescriptors().FirstItem();
+ od_item;
+ od_item = od_item->GetNext()) {
od = AP4_DYNAMIC_CAST(AP4_ObjectDescriptor, od_item->GetData());
- if(od == NULL) continue;
+ if (od == NULL) continue;
// find which track this od references
AP4_EsIdRefDescriptor* es_id_ref;
es_id_ref = AP4_DYNAMIC_CAST(AP4_EsIdRefDescriptor, od->FindSubDescriptor(AP4_DESCRIPTOR_TAG_ES_ID_REF));
- if(es_id_ref == NULL ||
- es_id_ref->GetRefIndex() > track_references->GetTrackIds().ItemCount() ||
- es_id_ref->GetRefIndex() == 0)
- {
+ if (es_id_ref == NULL ||
+ es_id_ref->GetRefIndex() > track_references->GetTrackIds().ItemCount() ||
+ es_id_ref->GetRefIndex() == 0) {
continue;
}
AP4_UI32 track_id = track_references->GetTrackIds()[es_id_ref->GetRefIndex()-1];
SinfEntry* sinf_entry = NULL;
- for(AP4_List<SinfEntry>::Item* sinf_entry_item = sinf_entries.FirstItem();
- sinf_entry_item;
- sinf_entry_item = sinf_entry_item->GetNext())
- {
+ for (AP4_List<SinfEntry>::Item* sinf_entry_item = sinf_entries.FirstItem();
+ sinf_entry_item;
+ sinf_entry_item = sinf_entry_item->GetNext()) {
sinf_entry = sinf_entry_item->GetData();
- if(sinf_entry->m_TrackId == track_id)
- {
+ if (sinf_entry->m_TrackId == track_id) {
break; // match
- }
- else
- {
+ } else {
sinf_entry = NULL; // no match
}
}
- if(sinf_entry == NULL) continue; // no matching entry
- if(sinf_entry->m_Sinf != NULL) continue; // entry already populated
-
+ if (sinf_entry == NULL) continue; // no matching entry
+ if (sinf_entry->m_Sinf != NULL) continue; // entry already populated
+
// see what ipmp descriptor this od points to
AP4_IpmpDescriptorPointer* ipmpd_pointer;
ipmpd_pointer = AP4_DYNAMIC_CAST(AP4_IpmpDescriptorPointer, od->FindSubDescriptor(AP4_DESCRIPTOR_TAG_IPMP_DESCRIPTOR_POINTER));
- if(ipmpd_pointer == NULL) continue; // no pointer
+ if (ipmpd_pointer == NULL) continue; // no pointer
// find the ipmp descriptor referenced by the pointer
AP4_IpmpDescriptor* ipmpd = NULL;
- for(AP4_List<AP4_Descriptor>::Item* ipmpd_item = ipmp_update->GetDescriptors().FirstItem();
- ipmpd_item;
- ipmpd_item = ipmpd_item->GetNext())
- {
+ for (AP4_List<AP4_Descriptor>::Item* ipmpd_item = ipmp_update->GetDescriptors().FirstItem();
+ ipmpd_item;
+ ipmpd_item = ipmpd_item->GetNext()) {
// check that this descriptor is of the right type
ipmpd = AP4_DYNAMIC_CAST(AP4_IpmpDescriptor, ipmpd_item->GetData());
- if(ipmpd == NULL || ipmpd->GetIpmpsType() != AP4_MARLIN_IPMPS_TYPE_MGSV) continue;
-
+ if (ipmpd == NULL || ipmpd->GetIpmpsType() != AP4_MARLIN_IPMPS_TYPE_MGSV) continue;
+
// check the descriptor id
- if(ipmpd->GetDescriptorId() == ipmpd_pointer->GetDescriptorId())
- {
+ if (ipmpd->GetDescriptorId() == ipmpd_pointer->GetDescriptorId()) {
break; // match
- }
- else
- {
+ } else {
ipmpd = NULL; // no match
}
}
- if(ipmpd == NULL) continue; // no matching entry
-
+ if (ipmpd == NULL) continue; // no matching entry
+
// parse the ipmp data into one or more 'sinf' atoms, and keep the one with the
// right type
AP4_MemoryByteStream* data = new AP4_MemoryByteStream(ipmpd->GetData().GetData(),
- ipmpd->GetData().GetDataSize());
+ ipmpd->GetData().GetDataSize());
AP4_LargeSize bytes_available = ipmpd->GetData().GetDataSize();
- do
- {
+ do {
AP4_Atom* atom = NULL;
-
+
// setup the factory with a context so we can instantiate a 'schm'
// atom with a slightly different format than the standard 'schm'
AP4_AtomFactory* factory = &AP4_MarlinIpmpAtomFactory::Instance;
- factory->PushContext(AP4_ATOM_TYPE('m', 'r', 'l', 'n'));
-
- // parse the next atom in the stream
+ factory->PushContext(AP4_ATOM_TYPE('m','r','l','n'));
+
+ // parse the next atom in the stream
result = factory->CreateAtomFromStream(*data, bytes_available, atom);
factory->PopContext();
- if(AP4_FAILED(result) || atom == NULL) break;
-
+ if (AP4_FAILED(result) || atom == NULL) break;
+
// check that what we have parsed is indeed an 'sinf' of the right type
- if(atom->GetType() == AP4_ATOM_TYPE_SINF)
- {
+ if (atom->GetType() == AP4_ATOM_TYPE_SINF) {
AP4_ContainerAtom* sinf = AP4_DYNAMIC_CAST(AP4_ContainerAtom, atom);
AP4_SchmAtom* schm = AP4_DYNAMIC_CAST(AP4_SchmAtom, sinf->FindChild("schm"));
- if((schm->GetSchemeType() == AP4_PROTECTION_SCHEME_TYPE_MARLIN_ACBC &&
- schm->GetSchemeVersion() == 0x0100) ||
- (schm->GetSchemeType() == AP4_PROTECTION_SCHEME_TYPE_MARLIN_ACGK &&
- schm->GetSchemeVersion() == 0x0100))
- {
+ if ((schm->GetSchemeType() == AP4_PROTECTION_SCHEME_TYPE_MARLIN_ACBC &&
+ schm->GetSchemeVersion() == 0x0100) ||
+ (schm->GetSchemeType() == AP4_PROTECTION_SCHEME_TYPE_MARLIN_ACGK &&
+ schm->GetSchemeVersion() == 0x0100)) {
// store the sinf in the entry for that track
sinf_entry->m_Sinf = sinf;
break;
}
}
delete atom;
- }
- while(AP4_SUCCEEDED(result));
- data->Release();
+ } while (AP4_SUCCEEDED(result));
+ data->Release();
}
-
+
// get rid of entries that have no SINF
- for(AP4_List<SinfEntry>::Item* sinf_entry_item = sinf_entries.FirstItem();
- sinf_entry_item;
- sinf_entry_item = sinf_entry_item->GetNext())
- {
+ for (AP4_List<SinfEntry>::Item* sinf_entry_item = sinf_entries.FirstItem();
+ sinf_entry_item;
+ sinf_entry_item = sinf_entry_item->GetNext()) {
SinfEntry* sinf_entry = sinf_entry_item->GetData();
- if(sinf_entry->m_Sinf == NULL)
- {
+ if (sinf_entry->m_Sinf == NULL) {
sinf_entries.Remove(sinf_entry);
sinf_entry_item = sinf_entries.FirstItem();
continue;
}
}
-
+
// remove the iods atom and the OD track if required
- if(remove_od_data)
- {
+ if (remove_od_data) {
od_trak->Detach();
delete od_trak;
iods->Detach();
delete iods;
}
-
+
// cleanup
delete od_track;
-
+
return AP4_SUCCESS;
}
@@ -379,20 +345,15 @@ AP4_MarlinIpmpParser::Parse(AP4_AtomParent& top_level,
+---------------------------------------------------------------------*/
AP4_MarlinIpmpDecryptingProcessor::AP4_MarlinIpmpDecryptingProcessor(
const AP4_ProtectionKeyMap* key_map, /* = NULL */
- AP4_BlockCipherFactory* block_cipher_factory /* = NULL */)
-{
- if(key_map)
- {
+ AP4_BlockCipherFactory* block_cipher_factory /* = NULL */){
+ if (key_map) {
// copy the keys
m_KeyMap.SetKeys(*key_map);
}
-
- if(block_cipher_factory == NULL)
- {
+
+ if (block_cipher_factory == NULL) {
m_BlockCipherFactory = &AP4_DefaultBlockCipherFactory::Instance;
- }
- else
- {
+ } else {
m_BlockCipherFactory = block_cipher_factory;
}
}
@@ -408,10 +369,10 @@ AP4_MarlinIpmpDecryptingProcessor::~AP4_MarlinIpmpDecryptingProcessor()
/*----------------------------------------------------------------------
| AP4_MarlinIpmpDecryptingProcessor:Initialize
+---------------------------------------------------------------------*/
-AP4_Result
-AP4_MarlinIpmpDecryptingProcessor::Initialize(AP4_AtomParent& top_level,
- AP4_ByteStream& stream,
- ProgressListener* /*listener*/)
+AP4_Result
+AP4_MarlinIpmpDecryptingProcessor::Initialize(AP4_AtomParent& top_level,
+ AP4_ByteStream& stream,
+ ProgressListener* /*listener*/)
{
return AP4_MarlinIpmpParser::Parse(top_level, stream, m_SinfEntries, true);
}
@@ -419,44 +380,35 @@ AP4_MarlinIpmpDecryptingProcessor::Initialize(AP4_AtomParent& top_level,
/*----------------------------------------------------------------------
| AP4_MarlinIpmpDecryptingProcessor:CreateTrackHandler
+---------------------------------------------------------------------*/
-AP4_Processor::TrackHandler*
+AP4_Processor::TrackHandler*
AP4_MarlinIpmpDecryptingProcessor::CreateTrackHandler(AP4_TrakAtom* trak)
{
// look for this track in the list of entries
AP4_MarlinIpmpParser::SinfEntry* sinf_entry = NULL;
- for(AP4_List<AP4_MarlinIpmpParser::SinfEntry>::Item* sinf_entry_item = m_SinfEntries.FirstItem();
- sinf_entry_item;
- sinf_entry_item = sinf_entry_item->GetNext())
- {
+ for (AP4_List<AP4_MarlinIpmpParser::SinfEntry>::Item* sinf_entry_item = m_SinfEntries.FirstItem();
+ sinf_entry_item;
+ sinf_entry_item = sinf_entry_item->GetNext()) {
sinf_entry = sinf_entry_item->GetData();
- if(sinf_entry->m_TrackId == trak->GetId())
- {
+ if (sinf_entry->m_TrackId == trak->GetId()) {
break; // match
- }
- else
- {
+ } else {
sinf_entry = NULL; // no match
}
}
- if(sinf_entry == NULL) return NULL; // no matching entry
+ if (sinf_entry == NULL) return NULL; // no matching entry
AP4_ContainerAtom* sinf = sinf_entry->m_Sinf;
-
+
// check the scheme
bool use_group_key;
AP4_SchmAtom* schm = AP4_DYNAMIC_CAST(AP4_SchmAtom, sinf->GetChild(AP4_ATOM_TYPE_SCHM));
- if(schm == NULL) return NULL; // no schm
- if(schm->GetSchemeType() == AP4_PROTECTION_SCHEME_TYPE_MARLIN_ACBC &&
- schm->GetSchemeVersion() == 0x0100)
- {
+ if (schm == NULL) return NULL; // no schm
+ if (schm->GetSchemeType() == AP4_PROTECTION_SCHEME_TYPE_MARLIN_ACBC &&
+ schm->GetSchemeVersion() == 0x0100) {
use_group_key = false;
- }
- else if(schm->GetSchemeType() == AP4_PROTECTION_SCHEME_TYPE_MARLIN_ACGK &&
- schm->GetSchemeVersion() == 0x0100)
- {
+ } else if (schm->GetSchemeType() == AP4_PROTECTION_SCHEME_TYPE_MARLIN_ACGK &&
+ schm->GetSchemeVersion() == 0x0100) {
use_group_key = true;
- }
- else
- {
+ } else {
// unsupported scheme
return NULL;
}
@@ -464,32 +416,29 @@ AP4_MarlinIpmpDecryptingProcessor::CreateTrackHandler(AP4_TrakAtom* trak)
// find the key
const AP4_UI08* key = NULL;
AP4_DataBuffer unwrapped_key;
- if(use_group_key)
- {
+ if (use_group_key) {
const AP4_UI08* group_key = m_KeyMap.GetKey(0);
- if(group_key == NULL) return NULL; // no group key
+ if (group_key == NULL) return NULL; // no group key
AP4_ContainerAtom* schi = AP4_DYNAMIC_CAST(AP4_ContainerAtom, sinf->GetChild(AP4_ATOM_TYPE_SCHI));
- if(schi == NULL) return NULL; // no schi
+ if (schi == NULL) return NULL; // no schi
AP4_Atom* gkey = schi->GetChild(AP4_ATOM_TYPE_GKEY);
- if(gkey == NULL) return NULL; // no gkey
+ if (gkey == NULL) return NULL; // no gkey
AP4_MemoryByteStream* gkey_data = new AP4_MemoryByteStream();
gkey->WriteFields(*gkey_data);
AP4_AesKeyUnwrap(group_key, gkey_data->GetData(), gkey_data->GetDataSize(), unwrapped_key);
key = unwrapped_key.GetData();
- gkey_data->Release();
- }
- else
- {
+ gkey_data->Release();
+ } else {
key = m_KeyMap.GetKey(sinf_entry->m_TrackId);
}
- if(key == NULL) return NULL;
+ if (key == NULL) return NULL;
// create the decrypter
AP4_MarlinIpmpTrackDecrypter* decrypter = NULL;
AP4_Result result = AP4_MarlinIpmpTrackDecrypter::Create(*m_BlockCipherFactory,
- key, decrypter);
- if(AP4_FAILED(result)) return NULL;
-
+ key, decrypter);
+ if (AP4_FAILED(result)) return NULL;
+
return decrypter;
}
@@ -503,22 +452,22 @@ AP4_MarlinIpmpTrackDecrypter::Create(AP4_BlockCipherFactory& cipher_facto
{
// default value
decrypter = NULL;
-
+
// create a block cipher for the decrypter
AP4_BlockCipher* block_cipher = NULL;
AP4_Result result = cipher_factory.Create(AP4_BlockCipher::AES_128,
- AP4_BlockCipher::DECRYPT,
- key,
- AP4_AES_BLOCK_SIZE,
- block_cipher);
- if(AP4_FAILED(result)) return result;
-
+ AP4_BlockCipher::DECRYPT,
+ key,
+ AP4_AES_BLOCK_SIZE,
+ block_cipher);
+ if (AP4_FAILED(result)) return result;
+
// create a CBC cipher
AP4_CbcStreamCipher* cbc_cipher = new AP4_CbcStreamCipher(block_cipher, AP4_StreamCipher::DECRYPT);
-
+
// create the track decrypter
decrypter = new AP4_MarlinIpmpTrackDecrypter(cbc_cipher);
-
+
return AP4_SUCCESS;
}
@@ -533,72 +482,69 @@ AP4_MarlinIpmpTrackDecrypter::~AP4_MarlinIpmpTrackDecrypter()
/*----------------------------------------------------------------------
| AP4_MarlinIpmpTrackDecrypter:GetProcessedSampleSize
+---------------------------------------------------------------------*/
-AP4_Size
+AP4_Size
AP4_MarlinIpmpTrackDecrypter::GetProcessedSampleSize(AP4_Sample& sample)
{
// with CBC, we need to decrypt the last block to know what the padding was
- AP4_Size encrypted_size = sample.GetSize() - AP4_AES_BLOCK_SIZE;
+ AP4_Size encrypted_size = sample.GetSize()-AP4_AES_BLOCK_SIZE;
AP4_DataBuffer encrypted;
AP4_DataBuffer decrypted;
AP4_Size decrypted_size = AP4_CIPHER_BLOCK_SIZE;
- if(sample.GetSize() < 2 * AP4_CIPHER_BLOCK_SIZE)
- {
+ if (sample.GetSize() < 2*AP4_CIPHER_BLOCK_SIZE) {
return 0;
}
- AP4_Size offset = sample.GetSize() - 2 * AP4_CIPHER_BLOCK_SIZE;
- if(AP4_FAILED(sample.ReadData(encrypted, 2 * AP4_CIPHER_BLOCK_SIZE, offset)))
- {
+ AP4_Size offset = sample.GetSize()-2*AP4_CIPHER_BLOCK_SIZE;
+ if (AP4_FAILED(sample.ReadData(encrypted, 2*AP4_CIPHER_BLOCK_SIZE, offset))) {
return 0;
}
decrypted.Reserve(decrypted_size);
m_Cipher->SetIV(encrypted.GetData());
- if(AP4_FAILED(m_Cipher->ProcessBuffer(encrypted.GetData() + AP4_CIPHER_BLOCK_SIZE,
- AP4_CIPHER_BLOCK_SIZE,
- decrypted.UseData(),
- &decrypted_size,
- true)))
- {
+ if (AP4_FAILED(m_Cipher->ProcessBuffer(encrypted.GetData()+AP4_CIPHER_BLOCK_SIZE,
+ AP4_CIPHER_BLOCK_SIZE,
+ decrypted.UseData(),
+ &decrypted_size,
+ true))) {
return 0;
}
- unsigned int padding_size = AP4_CIPHER_BLOCK_SIZE - decrypted_size;
- return encrypted_size - padding_size;
+ unsigned int padding_size = AP4_CIPHER_BLOCK_SIZE-decrypted_size;
+ return encrypted_size-padding_size;
}
/*----------------------------------------------------------------------
| AP4_MarlinIpmpTrackDecrypter:ProcessSample
+---------------------------------------------------------------------*/
-AP4_Result
+AP4_Result
AP4_MarlinIpmpTrackDecrypter::ProcessSample(AP4_DataBuffer& data_in,
- AP4_DataBuffer& data_out)
+ AP4_DataBuffer& data_out)
{
AP4_Result result;
-
+
const AP4_UI08* in = data_in.GetData();
AP4_Size in_size = data_in.GetDataSize();
- // default to 0 output
+ // default to 0 output
data_out.SetDataSize(0);
// check that we have at least the minimum size
- if(in_size < 2 * AP4_AES_BLOCK_SIZE) return AP4_ERROR_INVALID_FORMAT;
+ if (in_size < 2*AP4_AES_BLOCK_SIZE) return AP4_ERROR_INVALID_FORMAT;
// process the sample data
- AP4_Size out_size = in_size - AP4_AES_BLOCK_SIZE; // worst case
+ AP4_Size out_size = in_size-AP4_AES_BLOCK_SIZE; // worst case
data_out.SetDataSize(out_size);
AP4_UI08* out = data_out.UseData();
// decrypt the data
m_Cipher->SetIV(in);
- result = m_Cipher->ProcessBuffer(in + AP4_AES_BLOCK_SIZE,
- in_size - AP4_AES_BLOCK_SIZE,
+ result = m_Cipher->ProcessBuffer(in+AP4_AES_BLOCK_SIZE,
+ in_size-AP4_AES_BLOCK_SIZE,
out,
&out_size,
true);
- if(AP4_FAILED(result)) return result;
-
+ if (AP4_FAILED(result)) return result;
+
// update the payload size
data_out.SetDataSize(out_size);
-
+
return AP4_SUCCESS;
}
@@ -611,18 +557,14 @@ AP4_MarlinIpmpEncryptingProcessor::AP4_MarlinIpmpEncryptingProcessor(
AP4_BlockCipherFactory* block_cipher_factory /* = NULL */) :
m_UseGroupKey(use_group_key)
{
- if(key_map)
- {
+ if (key_map) {
// copy the keys
m_KeyMap.SetKeys(*key_map);
}
-
- if(block_cipher_factory == NULL)
- {
+
+ if (block_cipher_factory == NULL) {
m_BlockCipherFactory = &AP4_DefaultBlockCipherFactory::Instance;
- }
- else
- {
+ } else {
m_BlockCipherFactory = block_cipher_factory;
}
}
@@ -630,7 +572,7 @@ AP4_MarlinIpmpEncryptingProcessor::AP4_MarlinIpmpEncryptingProcessor(
/*----------------------------------------------------------------------
| AP4_MarlinIpmpEncryptingProcessor::Initialize
+---------------------------------------------------------------------*/
-AP4_Result
+AP4_Result
AP4_MarlinIpmpEncryptingProcessor::Initialize(
AP4_AtomParent& top_level,
AP4_ByteStream& /*stream*/,
@@ -638,84 +580,75 @@ AP4_MarlinIpmpEncryptingProcessor::Initialize(
{
// get the moov atom
AP4_MoovAtom* moov = AP4_DYNAMIC_CAST(AP4_MoovAtom, top_level.GetChild(AP4_ATOM_TYPE_MOOV));
- if(moov == NULL) return AP4_ERROR_INVALID_FORMAT;
-
+ if (moov == NULL) return AP4_ERROR_INVALID_FORMAT;
+
// deal with the file type
AP4_FtypAtom* ftyp = AP4_DYNAMIC_CAST(AP4_FtypAtom, top_level.GetChild(AP4_ATOM_TYPE_FTYP));
- if(ftyp)
- {
+ if (ftyp) {
// remove the atom, it will be replaced with a new one
top_level.RemoveChild(ftyp);
-
+
// keep the existing brand and compatible brands
AP4_Array<AP4_UI32> compatible_brands;
- compatible_brands.EnsureCapacity(ftyp->GetCompatibleBrands().ItemCount() + 1);
- for(unsigned int i = 0; i < ftyp->GetCompatibleBrands().ItemCount(); i++)
- {
+ compatible_brands.EnsureCapacity(ftyp->GetCompatibleBrands().ItemCount()+1);
+ for (unsigned int i=0; i<ftyp->GetCompatibleBrands().ItemCount(); i++) {
compatible_brands.Append(ftyp->GetCompatibleBrands()[i]);
}
-
+
// add the MGSV compatible brand if it is not already there
- if(!ftyp->HasCompatibleBrand(AP4_MARLIN_BRAND_MGSV))
- {
+ if (!ftyp->HasCompatibleBrand(AP4_MARLIN_BRAND_MGSV)) {
compatible_brands.Append(AP4_MARLIN_BRAND_MGSV);
}
// create a replacement for the major brand
AP4_FtypAtom* new_ftyp = new AP4_FtypAtom(AP4_MARLIN_BRAND_MGSV,
- 0x13c078c, //AP4_MARLIN_BRAND_MGSV_MAJOR_VERSION,
- &compatible_brands[0],
- compatible_brands.ItemCount());
+ 0x13c078c, //AP4_MARLIN_BRAND_MGSV_MAJOR_VERSION,
+ &compatible_brands[0],
+ compatible_brands.ItemCount());
delete ftyp;
ftyp = new_ftyp;
- }
- else
- {
+ } else {
AP4_UI32 isom = AP4_FTYP_BRAND_ISOM;
ftyp = new AP4_FtypAtom(AP4_MARLIN_BRAND_MGSV, 0, &isom, 1);
}
-
+
// insert the ftyp atom as the first child
top_level.AddChild(ftyp, 0);
// create and 'mpod' track reference atom
AP4_TrefTypeAtom* mpod = new AP4_TrefTypeAtom(AP4_ATOM_TYPE_MPOD);
-
+
// look for an available track ID, starting at 1
unsigned int od_track_id = 0;
unsigned int od_track_position = 0;
- for(AP4_List<AP4_TrakAtom>::Item* trak_item = moov->GetTrakAtoms().FirstItem();
- trak_item;
- trak_item = trak_item->GetNext())
- {
+ for (AP4_List<AP4_TrakAtom>::Item* trak_item = moov->GetTrakAtoms().FirstItem();
+ trak_item;
+ trak_item = trak_item->GetNext()) {
AP4_TrakAtom* trak = trak_item->GetData();
- if(trak)
- {
+ if (trak) {
od_track_position++;
- if(trak->GetId() >= od_track_id)
- {
- od_track_id = trak->GetId() + 1;
+ if (trak->GetId() >= od_track_id) {
+ od_track_id = trak->GetId()+1;
}
-
+
// if the track is encrypted, reference it in the mpod
- if(m_KeyMap.GetKey(trak->GetId()))
- {
+ if (m_KeyMap.GetKey(trak->GetId())) {
mpod->AddTrackId(trak->GetId());
}
-
+
//m_SinfEntries.Add(new SinfEntry(trak->GetId(), NULL));
- }
+ }
}
-
+
// check that there was at least one track in the file
- if(od_track_id == 0) return AP4_ERROR_INVALID_FORMAT;
-
+ if (od_track_id == 0) return AP4_ERROR_INVALID_FORMAT;
+
// create an initial object descriptor
- AP4_InitialObjectDescriptor* iod =
+ AP4_InitialObjectDescriptor* iod =
// FIXME: get real values from the property map
new AP4_InitialObjectDescriptor(AP4_DESCRIPTOR_TAG_MP4_IOD,
1022, // object descriptor id
- false,
+ false,
0xFE, // OD profile level (0xFE = No OD profile specified)
0xFF, // scene profile level
0xFE, // audio profile level
@@ -725,183 +658,160 @@ AP4_MarlinIpmpEncryptingProcessor::Initialize(
// create an ES_ID_Inc subdescriptor and add it to the initial object descriptor
AP4_EsIdIncDescriptor* es_id_inc = new AP4_EsIdIncDescriptor(od_track_id);
iod->AddSubDescriptor(es_id_inc);
-
+
// create an iods atom to hold the initial object descriptor
AP4_IodsAtom* iods = new AP4_IodsAtom(iod);
-
+
// add the iods atom to the moov atom (try to put it just after mvhd)
int iods_position = 0;
int item_position = 0;
- for(AP4_List<AP4_Atom>::Item* moov_item = moov->GetChildren().FirstItem();
- moov_item;
- moov_item = moov_item->GetNext())
- {
- ++item_position;
- if(moov_item->GetData()->GetType() == AP4_ATOM_TYPE_MVHD)
- {
+ for (AP4_List<AP4_Atom>::Item* moov_item = moov->GetChildren().FirstItem();
+ moov_item;
+ moov_item = moov_item->GetNext()) {
+ ++item_position;
+ if (moov_item->GetData()->GetType() == AP4_ATOM_TYPE_MVHD) {
iods_position = item_position;
break;
- }
+ }
}
AP4_Result result = moov->AddChild(iods, iods_position);
- if(AP4_FAILED(result))
- {
+ if (AP4_FAILED(result)) {
delete iods;
return result;
}
-
+
// create a sample table for the OD track
AP4_SyntheticSampleTable* od_sample_table = new AP4_SyntheticSampleTable();
-
- // create the sample description for the OD track
+
+ // create the sample description for the OD track
AP4_MpegSystemSampleDescription* od_sample_description;
od_sample_description = new AP4_MpegSystemSampleDescription(AP4_STREAM_TYPE_OD,
- AP4_OTI_MPEG4_SYSTEM,
- NULL,
- 32768, // buffer size
- 1024, // max bitrate
- 512); // avg bitrate
+ AP4_OTI_MPEG4_SYSTEM,
+ NULL,
+ 32768, // buffer size
+ 1024, // max bitrate
+ 512); // avg bitrate
od_sample_table->AddSampleDescription(od_sample_description, true);
-
- // create the OD descriptor update
+
+ // create the OD descriptor update
AP4_DescriptorUpdateCommand od_update(AP4_COMMAND_TAG_OBJECT_DESCRIPTOR_UPDATE);
- for(unsigned int i = 0; i < mpod->GetTrackIds().ItemCount(); i++)
- {
- AP4_ObjectDescriptor* od = new AP4_ObjectDescriptor(AP4_DESCRIPTOR_TAG_MP4_OD, 256 + i); // descriptor id = 256+i
- od->AddSubDescriptor(new AP4_EsIdRefDescriptor(i + 1)); // index into mpod (1-based)
- od->AddSubDescriptor(new AP4_IpmpDescriptorPointer(i + 1)); // descriptor id = i+1
+ for (unsigned int i=0; i<mpod->GetTrackIds().ItemCount(); i++) {
+ AP4_ObjectDescriptor* od = new AP4_ObjectDescriptor(AP4_DESCRIPTOR_TAG_MP4_OD, 256+i); // descriptor id = 256+i
+ od->AddSubDescriptor(new AP4_EsIdRefDescriptor(i+1)); // index into mpod (1-based)
+ od->AddSubDescriptor(new AP4_IpmpDescriptorPointer(i+1)); // descriptor id = i+1
od_update.AddDescriptor(od);
}
-
- // create the IPMP descriptor update
+
+ // create the IPMP descriptor update
AP4_DescriptorUpdateCommand ipmp_update(AP4_COMMAND_TAG_IPMP_DESCRIPTOR_UPDATE);
- for(unsigned int i = 0; i < mpod->GetTrackIds().ItemCount(); i++)
- {
+ for (unsigned int i=0; i<mpod->GetTrackIds().ItemCount(); i++) {
// create the ipmp descriptor
- AP4_IpmpDescriptor* ipmp_descriptor = new AP4_IpmpDescriptor(i + 1, AP4_MARLIN_IPMPS_TYPE_MGSV);
+ AP4_IpmpDescriptor* ipmp_descriptor = new AP4_IpmpDescriptor(i+1, AP4_MARLIN_IPMPS_TYPE_MGSV);
// create the sinf container
AP4_ContainerAtom* sinf = new AP4_ContainerAtom(AP4_ATOM_TYPE_SINF);
// add the scheme type atom
- sinf->AddChild(new AP4_SchmAtom(m_UseGroupKey ?
- AP4_PROTECTION_SCHEME_TYPE_MARLIN_ACGK :
- AP4_PROTECTION_SCHEME_TYPE_MARLIN_ACBC,
+ sinf->AddChild(new AP4_SchmAtom(m_UseGroupKey?
+ AP4_PROTECTION_SCHEME_TYPE_MARLIN_ACGK:
+ AP4_PROTECTION_SCHEME_TYPE_MARLIN_ACBC,
0x0100, NULL, true));
// create the 'schi' container
AP4_ContainerAtom* schi = new AP4_ContainerAtom(AP4_ATOM_TYPE_SCHI);
- // add the content ID
+ // add the content ID
const char* content_id = m_PropertyMap.GetProperty(mpod->GetTrackIds()[i], "ContentId");
- if(content_id)
- {
+ if (content_id) {
// add the content ID (8id_)
schi->AddChild(new AP4_NullTerminatedStringAtom(AP4_ATOM_TYPE_8ID_, content_id));
}
-
+
// add the signed attributes, if any
const char* signed_attributes = m_PropertyMap.GetProperty(mpod->GetTrackIds()[i], "SignedAttributes");
- if(signed_attributes)
- {
+ if (signed_attributes) {
// decode the hex-encoded data
- unsigned int size = (unsigned int)AP4_StringLength(signed_attributes) / 2;
+ unsigned int size = (unsigned int)AP4_StringLength(signed_attributes)/2;
AP4_DataBuffer attributes_atoms;
attributes_atoms.SetDataSize(size);
- if(AP4_SUCCEEDED(AP4_ParseHex(signed_attributes, attributes_atoms.UseData(), size)))
- {
+ if (AP4_SUCCEEDED(AP4_ParseHex(signed_attributes, attributes_atoms.UseData(), size))) {
// parse all the atoms encoded in the data and add them to the 'schi' container
- AP4_MemoryByteStream* mbs = new AP4_MemoryByteStream(attributes_atoms.GetData(),
- attributes_atoms.GetDataSize());
- do
- {
+ AP4_MemoryByteStream* mbs = new AP4_MemoryByteStream(attributes_atoms.GetData(),
+ attributes_atoms.GetDataSize());
+ do {
AP4_Atom* atom = NULL;
result = AP4_DefaultAtomFactory::Instance.CreateAtomFromStream(*mbs, atom);
- if(AP4_SUCCEEDED(result) && atom)
- {
+ if (AP4_SUCCEEDED(result) && atom) {
schi->AddChild(atom);
}
- }
- while(AP4_SUCCEEDED(result));
+ } while (AP4_SUCCEEDED(result));
mbs->Release();
}
}
-
+
// find what the track type is (necessary for the next step) and the key
const AP4_UI08* key;
unsigned int key_size = 0;
AP4_Track::Type track_type = AP4_Track::TYPE_UNKNOWN;
- for(AP4_List<AP4_TrakAtom>::Item* trak_item = moov->GetTrakAtoms().FirstItem();
- trak_item;
- trak_item = trak_item->GetNext())
- {
+ for (AP4_List<AP4_TrakAtom>::Item* trak_item = moov->GetTrakAtoms().FirstItem();
+ trak_item;
+ trak_item = trak_item->GetNext()) {
AP4_TrakAtom* trak = trak_item->GetData();
- if(trak->GetId() == mpod->GetTrackIds()[i])
- {
+ if (trak->GetId() == mpod->GetTrackIds()[i]) {
// find the handler type
AP4_Atom* sub = trak->FindChild("mdia/hdlr");
- if(sub)
- {
+ if (sub) {
AP4_HdlrAtom* hdlr = AP4_DYNAMIC_CAST(AP4_HdlrAtom, sub);
- if(hdlr)
- {
+ if (hdlr) {
AP4_UI32 type = hdlr->GetHandlerType();
- if(type == AP4_HANDLER_TYPE_SOUN)
- {
+ if (type == AP4_HANDLER_TYPE_SOUN) {
track_type = AP4_Track::TYPE_AUDIO;
- }
- else if(type == AP4_HANDLER_TYPE_VIDE)
- {
+ } else if (type == AP4_HANDLER_TYPE_VIDE) {
track_type = AP4_Track::TYPE_VIDEO;
}
}
}
-
+
// find the key
const AP4_UI08* iv = NULL;
- if(AP4_SUCCEEDED(m_KeyMap.GetKeyAndIv(trak->GetId(), key, iv)))
- {
+ if (AP4_SUCCEEDED(m_KeyMap.GetKeyAndIv(trak->GetId(), key, iv))) {
key_size = 16;
}
break;
}
}
-
+
// group key
- if(m_UseGroupKey)
- {
+ if (m_UseGroupKey) {
// find the group key
const AP4_UI08* iv = NULL;
const AP4_UI08* group_key;
- if(AP4_SUCCEEDED(m_KeyMap.GetKeyAndIv(0, group_key, iv)))
- {
+ if (AP4_SUCCEEDED(m_KeyMap.GetKeyAndIv(0, group_key, iv))) {
AP4_DataBuffer wrapped_key;
result = AP4_AesKeyWrap(group_key, key, key_size, wrapped_key);
- if(AP4_FAILED(result)) return result;
- AP4_UnknownAtom* gkey = new AP4_UnknownAtom(AP4_ATOM_TYPE_GKEY,
- wrapped_key.GetData(),
- wrapped_key.GetDataSize());
+ if (AP4_FAILED(result)) return result;
+ AP4_UnknownAtom* gkey = new AP4_UnknownAtom(AP4_ATOM_TYPE_GKEY,
+ wrapped_key.GetData(),
+ wrapped_key.GetDataSize());
schi->AddChild(gkey);
}
}
-
+
// create and add the secure attributes (satr)
- if(track_type != AP4_Track::TYPE_UNKNOWN && key != NULL && key_size != 0)
- {
+ if (track_type != AP4_Track::TYPE_UNKNOWN && key != NULL && key_size != 0) {
AP4_ContainerAtom* satr = new AP4_ContainerAtom(AP4_ATOM_TYPE_SATR);
- switch(track_type)
- {
- case AP4_Track::TYPE_AUDIO:
- satr->AddChild(new AP4_NullTerminatedStringAtom(AP4_ATOM_TYPE_STYP, AP4_MARLIN_IPMP_STYP_AUDIO));
- break;
- case AP4_Track::TYPE_VIDEO:
- satr->AddChild(new AP4_NullTerminatedStringAtom(AP4_ATOM_TYPE_STYP, AP4_MARLIN_IPMP_STYP_VIDEO));
- break;
- default:
- break;
+ switch (track_type) {
+ case AP4_Track::TYPE_AUDIO:
+ satr->AddChild(new AP4_NullTerminatedStringAtom(AP4_ATOM_TYPE_STYP, AP4_MARLIN_IPMP_STYP_AUDIO));
+ break;
+ case AP4_Track::TYPE_VIDEO:
+ satr->AddChild(new AP4_NullTerminatedStringAtom(AP4_ATOM_TYPE_STYP, AP4_MARLIN_IPMP_STYP_VIDEO));
+ break;
+ default:
+ break;
}
-
+
// compute the hmac
AP4_MemoryByteStream* mbs = new AP4_MemoryByteStream();
satr->Write(*mbs);
@@ -911,74 +821,73 @@ AP4_MarlinIpmpEncryptingProcessor::Initialize(
AP4_DataBuffer hmac_value;
digester->Final(hmac_value);
AP4_Atom* hmac = new AP4_UnknownAtom(AP4_ATOM_TYPE_HMAC, hmac_value.GetData(), hmac_value.GetDataSize());
-
+
schi->AddChild(satr);
schi->AddChild(hmac);
-
+
mbs->Release();
}
-
+
sinf->AddChild(schi);
-
+
// serialize the sinf atom to a buffer and set it as the ipmp data
AP4_MemoryByteStream* sinf_data = new AP4_MemoryByteStream((AP4_Size)sinf->GetSize());
sinf->Write(*sinf_data);
ipmp_descriptor->SetData(sinf_data->GetData(), sinf_data->GetDataSize());
sinf_data->Release();
-
+
ipmp_update.AddDescriptor(ipmp_descriptor);
}
-
+
// add the sample with the descriptors and updates
AP4_MemoryByteStream* sample_data = new AP4_MemoryByteStream();
od_update.Write(*sample_data);
ipmp_update.Write(*sample_data);
od_sample_table->AddSample(*sample_data, 0, sample_data->GetDataSize(), 0, 0, 0, 0, true);
-
+
// create the OD track
AP4_TrakAtom* od_track = new AP4_TrakAtom(od_sample_table,
- AP4_HANDLER_TYPE_ODSM,
- "Bento4 Marlin OD Handler",
- od_track_id,
- 0, 0,
- 1, 1000, 1, 0, "und",
- 0, 0);
-
- // add an entry in the processor's stream table to indicate that the
+ AP4_HANDLER_TYPE_ODSM,
+ "Bento4 Marlin OD Handler",
+ od_track_id,
+ 0, 0,
+ 1, 1000, 1, 0, "und",
+ 0, 0);
+
+ // add an entry in the processor's stream table to indicate that the
// media data for the OD track is not in the file stream, but in our
// memory stream.
m_ExternalTrackData.Add(new ExternalTrackData(od_track_id, sample_data));
sample_data->Release();
-
+
// add a tref track reference atom
AP4_ContainerAtom* tref = new AP4_ContainerAtom(AP4_ATOM_TYPE_TREF);
tref->AddChild(mpod);
od_track->AddChild(tref, 1); // add after 'tkhd'
-
+
// add the track to the moov atoms (just after the last track)
moov->AddChild(od_track, od_track_position);
-
+
return AP4_SUCCESS;
}
/*----------------------------------------------------------------------
| AP4_MarlinIpmpEncryptingProcessor::CreateTrackHandler
+---------------------------------------------------------------------*/
-AP4_Processor::TrackHandler*
+AP4_Processor::TrackHandler*
AP4_MarlinIpmpEncryptingProcessor::CreateTrackHandler(AP4_TrakAtom* trak)
{
// create a handler for this track if we have a key for it
const AP4_UI08* key;
const AP4_UI08* iv;
- if(AP4_SUCCEEDED(m_KeyMap.GetKeyAndIv(trak->GetId(), key, iv)))
- {
+ if (AP4_SUCCEEDED(m_KeyMap.GetKeyAndIv(trak->GetId(), key, iv))) {
// create the track handler
AP4_MarlinIpmpTrackEncrypter* handler = NULL;
AP4_Result result = AP4_MarlinIpmpTrackEncrypter::Create(*m_BlockCipherFactory, key, iv, handler);
- if(AP4_FAILED(result)) return NULL;
+ if (AP4_FAILED(result)) return NULL;
return handler;
}
-
+
// not encrypted
return NULL;
}
@@ -994,34 +903,34 @@ AP4_MarlinIpmpTrackEncrypter::Create(AP4_BlockCipherFactory& cipher_facto
{
// default value
encrypter = NULL;
-
+
// create a block cipher
AP4_BlockCipher* block_cipher = NULL;
- AP4_Result result = cipher_factory.Create(AP4_BlockCipher::AES_128,
- AP4_BlockCipher::ENCRYPT,
- key,
- AP4_AES_BLOCK_SIZE,
- block_cipher);
- if(AP4_FAILED(result)) return result;
+ AP4_Result result = cipher_factory.Create(AP4_BlockCipher::AES_128,
+ AP4_BlockCipher::ENCRYPT,
+ key,
+ AP4_AES_BLOCK_SIZE,
+ block_cipher);
+ if (AP4_FAILED(result)) return result;
// create a CBC cipher
AP4_CbcStreamCipher* cbc_cipher = new AP4_CbcStreamCipher(block_cipher, AP4_StreamCipher::ENCRYPT);
-
+
// create the track encrypter
encrypter = new AP4_MarlinIpmpTrackEncrypter(cbc_cipher, iv);
-
+
return AP4_SUCCESS;
}
/*----------------------------------------------------------------------
| AP4_MarlinIpmpTrackEncrypter::AP4_MarlinIpmpTrackEncrypter
+---------------------------------------------------------------------*/
-AP4_MarlinIpmpTrackEncrypter::AP4_MarlinIpmpTrackEncrypter(AP4_StreamCipher* cipher,
- const AP4_UI08* iv) :
+AP4_MarlinIpmpTrackEncrypter::AP4_MarlinIpmpTrackEncrypter(AP4_StreamCipher* cipher,
+ const AP4_UI08* iv) :
m_Cipher(cipher)
{
// copy the IV
- AP4_CopyMemory(m_IV, iv, AP4_AES_BLOCK_SIZE);
+ AP4_CopyMemory(m_IV, iv, AP4_AES_BLOCK_SIZE);
}
/*----------------------------------------------------------------------
@@ -1035,47 +944,47 @@ AP4_MarlinIpmpTrackEncrypter::~AP4_MarlinIpmpTrackEncrypter()
/*----------------------------------------------------------------------
| AP4_MarlinIpmpTrackEncrypter:GetProcessedSampleSize
+---------------------------------------------------------------------*/
-AP4_Size
+AP4_Size
AP4_MarlinIpmpTrackEncrypter::GetProcessedSampleSize(AP4_Sample& sample)
{
- return AP4_CIPHER_BLOCK_SIZE * (2 + (sample.GetSize() / AP4_CIPHER_BLOCK_SIZE));
+ return AP4_CIPHER_BLOCK_SIZE*(2+(sample.GetSize()/AP4_CIPHER_BLOCK_SIZE));
}
/*----------------------------------------------------------------------
| AP4_MarlinIpmpTrackEncrypter:ProcessSample
+---------------------------------------------------------------------*/
-AP4_Result
+AP4_Result
AP4_MarlinIpmpTrackEncrypter::ProcessSample(AP4_DataBuffer& data_in,
- AP4_DataBuffer& data_out)
+ AP4_DataBuffer& data_out)
{
AP4_Result result;
-
+
const AP4_UI08* in = data_in.GetData();
AP4_Size in_size = data_in.GetDataSize();
- // default to 0 output
+ // default to 0 output
data_out.SetDataSize(0);
// process the sample data
- AP4_Size out_size = AP4_CIPHER_BLOCK_SIZE * (2 + (in_size / AP4_CIPHER_BLOCK_SIZE));
+ AP4_Size out_size = AP4_CIPHER_BLOCK_SIZE*(2+(in_size/AP4_CIPHER_BLOCK_SIZE));
data_out.SetDataSize(out_size);
AP4_UI08* out = data_out.UseData();
// write the IV
AP4_CopyMemory(out, m_IV, AP4_CIPHER_BLOCK_SIZE);
out_size -= AP4_CIPHER_BLOCK_SIZE;
-
+
// encrypt the data
m_Cipher->SetIV(m_IV);
- result = m_Cipher->ProcessBuffer(in,
- in_size,
- out + AP4_AES_BLOCK_SIZE,
+ result = m_Cipher->ProcessBuffer(in,
+ in_size,
+ out+AP4_AES_BLOCK_SIZE,
&out_size,
true);
- if(AP4_FAILED(result)) return result;
-
+ if (AP4_FAILED(result)) return result;
+
// update the payload size
- data_out.SetDataSize(out_size + AP4_AES_BLOCK_SIZE);
-
+ data_out.SetDataSize(out_size+AP4_AES_BLOCK_SIZE);
+
return AP4_SUCCESS;
}
diff --git a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4Marlin.h b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4Marlin.h
index 52601c529..7e1b428d6 100644
--- a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4Marlin.h
+++ b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4Marlin.h
@@ -47,15 +47,15 @@
/*----------------------------------------------------------------------
| constants
+---------------------------------------------------------------------*/
-const AP4_UI32 AP4_MARLIN_BRAND_MGSV = AP4_ATOM_TYPE('M', 'G', 'S', 'V');
+const AP4_UI32 AP4_MARLIN_BRAND_MGSV = AP4_ATOM_TYPE('M','G','S','V');
const AP4_UI16 AP4_MARLIN_IPMPS_TYPE_MGSV = 0xA551;
-const AP4_UI32 AP4_PROTECTION_SCHEME_TYPE_MARLIN_ACBC = AP4_ATOM_TYPE('A', 'C', 'B', 'C');
-const AP4_UI32 AP4_PROTECTION_SCHEME_TYPE_MARLIN_ACGK = AP4_ATOM_TYPE('A', 'C', 'G', 'K');
+const AP4_UI32 AP4_PROTECTION_SCHEME_TYPE_MARLIN_ACBC = AP4_ATOM_TYPE('A','C','B','C');
+const AP4_UI32 AP4_PROTECTION_SCHEME_TYPE_MARLIN_ACGK = AP4_ATOM_TYPE('A','C','G','K');
-const AP4_Atom::Type AP4_ATOM_TYPE_SATR = AP4_ATOM_TYPE('s', 'a', 't', 'r');
-const AP4_Atom::Type AP4_ATOM_TYPE_STYP = AP4_ATOM_TYPE('s', 't', 'y', 'p');
-const AP4_Atom::Type AP4_ATOM_TYPE_HMAC = AP4_ATOM_TYPE('h', 'm', 'a', 'c');
-const AP4_Atom::Type AP4_ATOM_TYPE_GKEY = AP4_ATOM_TYPE('g', 'k', 'e', 'y');
+const AP4_Atom::Type AP4_ATOM_TYPE_SATR = AP4_ATOM_TYPE('s','a','t','r');
+const AP4_Atom::Type AP4_ATOM_TYPE_STYP = AP4_ATOM_TYPE('s','t','y','p');
+const AP4_Atom::Type AP4_ATOM_TYPE_HMAC = AP4_ATOM_TYPE('h','m','a','c');
+const AP4_Atom::Type AP4_ATOM_TYPE_GKEY = AP4_ATOM_TYPE('g','k','e','y');
const char* const AP4_MARLIN_IPMP_STYP_VIDEO = "urn:marlin:organization:sne:content-type:video";
const char* const AP4_MARLIN_IPMP_STYP_AUDIO = "urn:marlin:organization:sne:content-type:audio";
@@ -67,24 +67,20 @@ class AP4_MarlinIpmpParser
{
public:
// types
- struct SinfEntry
- {
- SinfEntry(AP4_UI32 track_id, AP4_ContainerAtom* sinf) :
- m_TrackId(track_id), m_Sinf(sinf) {}
- ~SinfEntry()
- {
- delete m_Sinf;
- }
+ struct SinfEntry {
+ SinfEntry(AP4_UI32 track_id, AP4_ContainerAtom* sinf) :
+ m_TrackId(track_id), m_Sinf(sinf) {}
+ ~SinfEntry() { delete m_Sinf; }
AP4_UI32 m_TrackId;
AP4_ContainerAtom* m_Sinf;
};
-
+
// methods
- static AP4_Result Parse(AP4_AtomParent& top_level,
+ static AP4_Result Parse(AP4_AtomParent& top_level,
AP4_ByteStream& stream,
AP4_List<SinfEntry>& sinf_entries,
- bool remove_od_data = false);
-
+ bool remove_od_data=false);
+
private:
AP4_MarlinIpmpParser() {} // this class can't be instantiated
};
@@ -99,12 +95,9 @@ public:
AP4_MarlinIpmpDecryptingProcessor(const AP4_ProtectionKeyMap* key_map = NULL,
AP4_BlockCipherFactory* block_cipher_factory = NULL);
~AP4_MarlinIpmpDecryptingProcessor();
-
+
// accessors
- AP4_ProtectionKeyMap& GetKeyMap()
- {
- return m_KeyMap;
- }
+ AP4_ProtectionKeyMap& GetKeyMap() { return m_KeyMap; }
// methods
virtual AP4_Result Initialize(AP4_AtomParent& top_level,
@@ -113,7 +106,7 @@ public:
virtual AP4_Processor::TrackHandler* CreateTrackHandler(AP4_TrakAtom* trak);
private:
-
+
// members
AP4_BlockCipherFactory* m_BlockCipherFactory;
AP4_ProtectionKeyMap m_KeyMap;
@@ -130,10 +123,10 @@ public:
static AP4_Result Create(AP4_BlockCipherFactory& cipher_factory,
const AP4_UI08* key,
AP4_MarlinIpmpTrackDecrypter*& decrypter);
-
+
// destructor
~AP4_MarlinIpmpTrackDecrypter();
-
+
// AP4_Processor::TrackHandler methods
virtual AP4_Size GetProcessedSampleSize(AP4_Sample& sample);
virtual AP4_Result ProcessSample(AP4_DataBuffer& data_in,
@@ -160,14 +153,8 @@ public:
AP4_BlockCipherFactory* block_cipher_factory = NULL);
// accessors
- AP4_ProtectionKeyMap& GetKeyMap()
- {
- return m_KeyMap;
- }
- AP4_TrackPropertyMap& GetPropertyMap()
- {
- return m_PropertyMap;
- }
+ AP4_ProtectionKeyMap& GetKeyMap() { return m_KeyMap; }
+ AP4_TrackPropertyMap& GetPropertyMap() { return m_PropertyMap; }
// AP4_Processor methods
virtual AP4_Result Initialize(AP4_AtomParent& top_level,
@@ -194,10 +181,10 @@ public:
const AP4_UI08* key,
const AP4_UI08* iv,
AP4_MarlinIpmpTrackEncrypter*& encrypter);
-
+
// destructor
~AP4_MarlinIpmpTrackEncrypter();
-
+
// AP4_Processor::TrackHandler methods
virtual AP4_Size GetProcessedSampleSize(AP4_Sample& sample);
virtual AP4_Result ProcessSample(AP4_DataBuffer& data_in,
diff --git a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4MdhdAtom.cpp b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4MdhdAtom.cpp
index 5ec6b401e..78bab0b3c 100644
--- a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4MdhdAtom.cpp
+++ b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4MdhdAtom.cpp
@@ -1,6 +1,6 @@
/*****************************************************************
|
-| AP4 - mdhd Atoms
+| AP4 - mdhd Atoms
|
| Copyright 2002-2008 Axiomatic Systems, LLC
|
@@ -46,8 +46,8 @@ AP4_MdhdAtom::Create(AP4_Size size, AP4_ByteStream& stream)
{
AP4_UI32 version;
AP4_UI32 flags;
- if(AP4_FAILED(AP4_Atom::ReadFullHeader(stream, version, flags))) return NULL;
- if(version > 1) return NULL;
+ if (AP4_FAILED(AP4_Atom::ReadFullHeader(stream, version, flags))) return NULL;
+ if (version > 1) return NULL;
return new AP4_MdhdAtom(size, version, flags, stream);
}
@@ -59,7 +59,7 @@ AP4_MdhdAtom::AP4_MdhdAtom(AP4_UI32 creation_time,
AP4_UI32 time_scale,
AP4_UI64 duration,
const char* language) :
- AP4_Atom(AP4_ATOM_TYPE_MDHD, AP4_FULL_ATOM_HEADER_SIZE + 20, 0, 0),
+ AP4_Atom(AP4_ATOM_TYPE_MDHD, AP4_FULL_ATOM_HEADER_SIZE+20, 0, 0),
m_CreationTime(creation_time),
m_ModificationTime(modification_time),
m_TimeScale(time_scale),
@@ -71,14 +71,13 @@ AP4_MdhdAtom::AP4_MdhdAtom(AP4_UI32 creation_time,
/*----------------------------------------------------------------------
| AP4_MdhdAtom::AP4_MdhdAtom
+---------------------------------------------------------------------*/
-AP4_MdhdAtom::AP4_MdhdAtom(AP4_UI32 size,
+AP4_MdhdAtom::AP4_MdhdAtom(AP4_UI32 size,
AP4_UI32 version,
AP4_UI32 flags,
AP4_ByteStream& stream) :
AP4_Atom(AP4_ATOM_TYPE_MDHD, size, version, flags)
{
- if(m_Version == 0)
- {
+ if (m_Version == 0) {
AP4_UI32 creation_time;
stream.ReadUI32(creation_time);
m_CreationTime = creation_time;
@@ -89,27 +88,22 @@ AP4_MdhdAtom::AP4_MdhdAtom(AP4_UI32 size,
AP4_UI32 duration;
stream.ReadUI32(duration);
m_Duration = duration;
- }
- else
- {
+ } else {
stream.ReadUI64(m_CreationTime);
stream.ReadUI64(m_ModificationTime);
stream.ReadUI32(m_TimeScale);
stream.ReadUI64(m_Duration);
}
-
+
unsigned char lang[2];
stream.Read(lang, 2);
- char l0 = ((lang[0] >> 2) & 0x1F);
- char l1 = (((lang[0] & 0x3) << 3) | ((lang[1] >> 5) & 0x7));
- char l2 = ((lang[1] & 0x1F));
- if(l0 && l1 && l2)
- {
- char lang_str[3] = {l0 + 0x60, l1 + 0x60, l2 + 0x60};
+ char l0 = ((lang[0]>>2)&0x1F);
+ char l1 = (((lang[0]&0x3)<<3) | ((lang[1]>>5)&0x7));
+ char l2 = ((lang[1]&0x1F));
+ if (l0 && l1 && l2) {
+ char lang_str[3] = {l0+0x60, l1+0x60, l2+0x60};
m_Language.Assign(lang_str, 3);
- }
- else
- {
+ } else {
m_Language.Assign("```", 3);
}
}
@@ -122,37 +116,34 @@ AP4_MdhdAtom::WriteFields(AP4_ByteStream& stream)
{
AP4_Result result;
- if(m_Version == 0)
- {
+ if (m_Version == 0) {
result = stream.WriteUI32((AP4_UI32)m_CreationTime);
- if(AP4_FAILED(result)) return result;
+ if (AP4_FAILED(result)) return result;
result = stream.WriteUI32((AP4_UI32)m_ModificationTime);
- if(AP4_FAILED(result)) return result;
+ if (AP4_FAILED(result)) return result;
result = stream.WriteUI32(m_TimeScale);
- if(AP4_FAILED(result)) return result;
+ if (AP4_FAILED(result)) return result;
result = stream.WriteUI32((AP4_UI32)m_Duration);
- if(AP4_FAILED(result)) return result;
- }
- else
- {
+ if (AP4_FAILED(result)) return result;
+ } else {
result = stream.WriteUI64(m_CreationTime);
- if(AP4_FAILED(result)) return result;
+ if (AP4_FAILED(result)) return result;
result = stream.WriteUI64(m_ModificationTime);
- if(AP4_FAILED(result)) return result;
+ if (AP4_FAILED(result)) return result;
result = stream.WriteUI32(m_TimeScale);
- if(AP4_FAILED(result)) return result;
+ if (AP4_FAILED(result)) return result;
result = stream.WriteUI64(m_Duration);
- if(AP4_FAILED(result)) return result;
+ if (AP4_FAILED(result)) return result;
}
// write the language
- AP4_UI08 l0 = m_Language[0] - 0x60;
- AP4_UI08 l1 = m_Language[1] - 0x60;
- AP4_UI08 l2 = m_Language[2] - 0x60;
- result = stream.WriteUI08(l0 << 2 | l1 >> 3);
- if(AP4_FAILED(result)) return result;
- result = stream.WriteUI08(l1 << 5 | l2);
- if(AP4_FAILED(result)) return result;
+ AP4_UI08 l0 = m_Language[0]-0x60;
+ AP4_UI08 l1 = m_Language[1]-0x60;
+ AP4_UI08 l2 = m_Language[2]-0x60;
+ result = stream.WriteUI08(l0<<2 | l1>>3);
+ if (AP4_FAILED(result)) return result;
+ result = stream.WriteUI08(l1<<5 | l2);
+ if (AP4_FAILED(result)) return result;
// pre-defined
return stream.WriteUI16(0);
diff --git a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4MdhdAtom.h b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4MdhdAtom.h
index 4627a5fa8..f61ba9f6a 100644
--- a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4MdhdAtom.h
+++ b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4MdhdAtom.h
@@ -1,6 +1,6 @@
/*****************************************************************
|
-| AP4 - mdhd Atoms
+| AP4 - mdhd Atoms
|
| Copyright 2002-2008 Axiomatic Systems, LLC
|
@@ -62,30 +62,15 @@ public:
virtual AP4_Result WriteFields(AP4_ByteStream& stream);
AP4_UI32 GetDurationMs();
- AP4_UI64 GetDuration()
- {
- return m_Duration;
- }
- void SetDuration(AP4_UI64 duration)
- {
- m_Duration = duration;
- }
- AP4_UI32 GetTimeScale()
- {
- return m_TimeScale;
- }
- void SetTimeScale(AP4_UI32 timescale)
- {
- m_TimeScale = timescale;
- }
- const AP4_String& GetLanguage()
- {
- return m_Language;
- }
+ AP4_UI64 GetDuration() { return m_Duration; }
+ void SetDuration(AP4_UI64 duration) { m_Duration = duration; }
+ AP4_UI32 GetTimeScale() { return m_TimeScale; }
+ void SetTimeScale(AP4_UI32 timescale) { m_TimeScale = timescale; }
+ const AP4_String& GetLanguage() { return m_Language; }
private:
// methods
- AP4_MdhdAtom(AP4_UI32 size,
+ AP4_MdhdAtom(AP4_UI32 size,
AP4_UI32 version,
AP4_UI32 flags,
AP4_ByteStream& stream);
diff --git a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4MehdAtom.cpp b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4MehdAtom.cpp
index 3d25a7b52..cf4ae40ca 100644
--- a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4MehdAtom.cpp
+++ b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4MehdAtom.cpp
@@ -1,6 +1,6 @@
/*****************************************************************
|
-| AP4 - mehd Atoms
+| AP4 - mehd Atoms
|
| Copyright 2002-2008 Axiomatic Systems, LLC
|
@@ -46,8 +46,8 @@ AP4_MehdAtom::Create(AP4_Size size, AP4_ByteStream& stream)
{
AP4_UI32 version;
AP4_UI32 flags;
- if(AP4_FAILED(AP4_Atom::ReadFullHeader(stream, version, flags))) return NULL;
- if(version > 1) return NULL;
+ if (AP4_FAILED(AP4_Atom::ReadFullHeader(stream, version, flags))) return NULL;
+ if (version > 1) return NULL;
return new AP4_MehdAtom(size, version, flags, stream);
}
@@ -55,11 +55,10 @@ AP4_MehdAtom::Create(AP4_Size size, AP4_ByteStream& stream)
| AP4_MehdAtom::AP4_MehdAtom
+---------------------------------------------------------------------*/
AP4_MehdAtom::AP4_MehdAtom(AP4_UI64 duration) :
- AP4_Atom(AP4_ATOM_TYPE_MEHD, AP4_FULL_ATOM_HEADER_SIZE + 4, 0, 0),
+ AP4_Atom(AP4_ATOM_TYPE_MEHD, AP4_FULL_ATOM_HEADER_SIZE+4, 0, 0),
m_Duration(duration)
{
- if(duration > 0xFFFFFFFF)
- {
+ if (duration > 0xFFFFFFFF) {
m_Version = 1;
m_Size32 += 4;
}
@@ -68,20 +67,17 @@ AP4_MehdAtom::AP4_MehdAtom(AP4_UI64 duration) :
/*----------------------------------------------------------------------
| AP4_MehdAtom::AP4_MehdAtom
+---------------------------------------------------------------------*/
-AP4_MehdAtom::AP4_MehdAtom(AP4_UI32 size,
+AP4_MehdAtom::AP4_MehdAtom(AP4_UI32 size,
AP4_UI32 version,
AP4_UI32 flags,
AP4_ByteStream& stream) :
AP4_Atom(AP4_ATOM_TYPE_MEHD, size, version, flags)
{
- if(m_Version == 0)
- {
+ if (m_Version == 0) {
AP4_UI32 duration;
stream.ReadUI32(duration);
m_Duration = duration;
- }
- else
- {
+ } else {
stream.ReadUI64(m_Duration);
}
}
@@ -92,12 +88,9 @@ AP4_MehdAtom::AP4_MehdAtom(AP4_UI32 size,
AP4_Result
AP4_MehdAtom::WriteFields(AP4_ByteStream& stream)
{
- if(m_Version == 0)
- {
+ if (m_Version == 0) {
return stream.WriteUI32((AP4_UI32)m_Duration);
- }
- else
- {
+ } else {
return stream.WriteUI64(m_Duration);
}
}
diff --git a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4MehdAtom.h b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4MehdAtom.h
index 211da83ca..5d0052920 100644
--- a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4MehdAtom.h
+++ b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4MehdAtom.h
@@ -1,6 +1,6 @@
/*****************************************************************
|
-| AP4 - mehd Atoms
+| AP4 - mehd Atoms
|
| Copyright 2002-2008 Axiomatic Systems, LLC
|
@@ -50,21 +50,15 @@ public:
AP4_MehdAtom(AP4_UI64 duration);
virtual AP4_Result InspectFields(AP4_AtomInspector& inspector);
virtual AP4_Result WriteFields(AP4_ByteStream& stream);
- AP4_UI64 GetDuration()
- {
- return m_Duration;
- }
- void SetDuration(AP4_UI64 duration)
- {
- m_Duration = duration;
- }
+ AP4_UI64 GetDuration() { return m_Duration; }
+ void SetDuration(AP4_UI64 duration) { m_Duration = duration;}
private:
// methods
- AP4_MehdAtom(AP4_UI32 size,
+ AP4_MehdAtom(AP4_UI32 size,
AP4_UI32 version,
AP4_UI32 flags,
- AP4_ByteStream& stream);
+ AP4_ByteStream& stream);
// members
AP4_UI64 m_Duration;
diff --git a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4MfhdAtom.cpp b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4MfhdAtom.cpp
index e2fe2a4c2..62294f74a 100644
--- a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4MfhdAtom.cpp
+++ b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4MfhdAtom.cpp
@@ -1,6 +1,6 @@
/*****************************************************************
|
-| AP4 - mfhd Atoms
+| AP4 - mfhd Atoms
|
| Copyright 2002-2008 Axiomatic Systems, LLC
|
@@ -46,8 +46,8 @@ AP4_MfhdAtom::Create(AP4_Size size, AP4_ByteStream& stream)
{
AP4_UI32 version;
AP4_UI32 flags;
- if(AP4_FAILED(AP4_Atom::ReadFullHeader(stream, version, flags))) return NULL;
- if(version > 0) return NULL;
+ if (AP4_FAILED(AP4_Atom::ReadFullHeader(stream, version, flags))) return NULL;
+ if (version > 0) return NULL;
return new AP4_MfhdAtom(size, version, flags, stream);
}
@@ -55,7 +55,7 @@ AP4_MfhdAtom::Create(AP4_Size size, AP4_ByteStream& stream)
| AP4_MfhdAtom::AP4_MfhdAtom
+---------------------------------------------------------------------*/
AP4_MfhdAtom::AP4_MfhdAtom(AP4_UI32 sequence_number) :
- AP4_Atom(AP4_ATOM_TYPE_MFHD, AP4_FULL_ATOM_HEADER_SIZE + 4, 0, 0),
+ AP4_Atom(AP4_ATOM_TYPE_MFHD, AP4_FULL_ATOM_HEADER_SIZE+4, 0, 0),
m_SequenceNumber(sequence_number)
{
}
@@ -63,7 +63,7 @@ AP4_MfhdAtom::AP4_MfhdAtom(AP4_UI32 sequence_number) :
/*----------------------------------------------------------------------
| AP4_MfhdAtom::AP4_MfhdAtom
+---------------------------------------------------------------------*/
-AP4_MfhdAtom::AP4_MfhdAtom(AP4_UI32 size,
+AP4_MfhdAtom::AP4_MfhdAtom(AP4_UI32 size,
AP4_UI32 version,
AP4_UI32 flags,
AP4_ByteStream& stream) :
diff --git a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4MfhdAtom.h b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4MfhdAtom.h
index 619cac1cd..ecdaacb0d 100644
--- a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4MfhdAtom.h
+++ b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4MfhdAtom.h
@@ -1,6 +1,6 @@
/*****************************************************************
|
-| AP4 - mfhd Atoms
+| AP4 - mfhd Atoms
|
| Copyright 2002-2008 Axiomatic Systems, LLC
|
@@ -50,18 +50,12 @@ public:
virtual AP4_Result InspectFields(AP4_AtomInspector& inspector);
virtual AP4_Result WriteFields(AP4_ByteStream& stream);
- AP4_UI32 GetSequenceNumber()
- {
- return m_SequenceNumber;
- }
- void SetSequenceNumber(AP4_UI32 sequence_number)
- {
- m_SequenceNumber = sequence_number;
- }
+ AP4_UI32 GetSequenceNumber() { return m_SequenceNumber; }
+ void SetSequenceNumber(AP4_UI32 sequence_number) { m_SequenceNumber = sequence_number; }
private:
// methods
- AP4_MfhdAtom(AP4_UI32 size,
+ AP4_MfhdAtom(AP4_UI32 size,
AP4_UI32 version,
AP4_UI32 flags,
AP4_ByteStream& stream);
diff --git a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4MfroAtom.cpp b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4MfroAtom.cpp
index d9de9a6fe..7000bb529 100644
--- a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4MfroAtom.cpp
+++ b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4MfroAtom.cpp
@@ -1,6 +1,6 @@
/*****************************************************************
|
-| AP4 - tfra Atoms
+| AP4 - tfra Atoms
|
| Copyright 2002-2008 Axiomatic Systems, LLC
|
@@ -36,14 +36,14 @@
/*----------------------------------------------------------------------
| AP4_MfroAtom::Create
+---------------------------------------------------------------------*/
-AP4_MfroAtom*
+AP4_MfroAtom*
AP4_MfroAtom::Create(AP4_Size size, AP4_ByteStream& stream)
{
AP4_UI32 version = 0;
AP4_UI32 flags = 0;
AP4_Result result = ReadFullHeader(stream, version, flags);
- if(AP4_FAILED(result)) return NULL;
- if(version != 0) return NULL;
+ if (AP4_FAILED(result)) return NULL;
+ if (version != 0) return NULL;
return new AP4_MfroAtom(size, version, flags, stream);
}
@@ -51,7 +51,7 @@ AP4_MfroAtom::Create(AP4_Size size, AP4_ByteStream& stream)
| AP4_MfroAtom::AP4_MfroAtom
+---------------------------------------------------------------------*/
AP4_MfroAtom::AP4_MfroAtom(AP4_UI32 mfra_size) :
- AP4_Atom(AP4_ATOM_TYPE_MFRO, AP4_FULL_ATOM_HEADER_SIZE + 4),
+ AP4_Atom(AP4_ATOM_TYPE_MFRO, AP4_FULL_ATOM_HEADER_SIZE+4),
m_MfraSize(mfra_size)
{
}
@@ -59,9 +59,9 @@ AP4_MfroAtom::AP4_MfroAtom(AP4_UI32 mfra_size) :
/*----------------------------------------------------------------------
| AP4_MfroAtom::AP4_MfroAtom
+---------------------------------------------------------------------*/
-AP4_MfroAtom::AP4_MfroAtom(AP4_UI32 size,
- AP4_UI32 version,
- AP4_UI32 flags,
+AP4_MfroAtom::AP4_MfroAtom(AP4_UI32 size,
+ AP4_UI32 version,
+ AP4_UI32 flags,
AP4_ByteStream& stream) :
AP4_Atom(AP4_ATOM_TYPE_MFRO, size, version, flags)
{
@@ -84,6 +84,6 @@ AP4_Result
AP4_MfroAtom::InspectFields(AP4_AtomInspector& inspector)
{
inspector.AddField("mfra_size", m_MfraSize);
-
+
return AP4_SUCCESS;
}
diff --git a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4MfroAtom.h b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4MfroAtom.h
index 53992aa30..82ab1d867 100644
--- a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4MfroAtom.h
+++ b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4MfroAtom.h
@@ -1,6 +1,6 @@
/*****************************************************************
|
-| AP4 - mfro Atoms
+| AP4 - mfro Atoms
|
| Copyright 2002-2009 Axiomatic Systems, LLC
|
@@ -49,8 +49,8 @@ class AP4_MfroAtom : public AP4_Atom
public:
// class methods
static AP4_MfroAtom* Create(AP4_Size size, AP4_ByteStream& stream);
-
- // constructors
+
+ // constructors
AP4_MfroAtom(AP4_UI32 mfra_size);
// methods
@@ -58,11 +58,8 @@ public:
virtual AP4_Result WriteFields(AP4_ByteStream& stream);
// accessors
- AP4_UI32 GetMfraSize()
- {
- return m_MfraSize;
- }
-
+ AP4_UI32 GetMfraSize() { return m_MfraSize; }
+
private:
// methods
AP4_MfroAtom(AP4_UI32 size, AP4_UI32 version, AP4_UI32 flags, AP4_ByteStream& stream);
diff --git a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4MoovAtom.cpp b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4MoovAtom.cpp
index b1f771e44..a50080cf1 100644
--- a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4MoovAtom.cpp
+++ b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4MoovAtom.cpp
@@ -1,6 +1,6 @@
/*****************************************************************
|
-| AP4 - moov Atoms
+| AP4 - moov Atoms
|
| Copyright 2002-2008 Axiomatic Systems, LLC
|
@@ -53,13 +53,10 @@ public:
AP4_TrakAtomCollector(AP4_List<AP4_TrakAtom>* track_atoms) :
m_TrakAtoms(track_atoms) {}
- AP4_Result Action(AP4_Atom* atom) const
- {
- if(atom->GetType() == AP4_ATOM_TYPE_TRAK)
- {
+ AP4_Result Action(AP4_Atom* atom) const {
+ if (atom->GetType() == AP4_ATOM_TYPE_TRAK) {
AP4_TrakAtom* trak = AP4_DYNAMIC_CAST(AP4_TrakAtom, atom);
- if(trak)
- {
+ if (trak) {
m_TrakAtoms->Add(trak);
}
}
@@ -88,98 +85,97 @@ AP4_MoovAtom::AP4_MoovAtom(AP4_UI32 size,
AP4_ContainerAtom(AP4_ATOM_TYPE_MOOV, size, false, stream, atom_factory),
m_TimeScale(0)
{
- // ==> Start patch MPC
- if(AP4_ContainerAtom* cmov = dynamic_cast<AP4_ContainerAtom*>(GetChild(AP4_ATOM_TYPE_CMOV)))
- {
- AP4_DcomAtom* dcom = dynamic_cast<AP4_DcomAtom*>(cmov->GetChild(AP4_ATOM_TYPE_DCOM));
- AP4_CmvdAtom* cmvd = dynamic_cast<AP4_CmvdAtom*>(cmov->GetChild(AP4_ATOM_TYPE_CMVD));
- if(dcom && dcom->GetCompressorSubType() == AP4_ATOM_TYPE('z', 'l', 'i', 'b') && cmvd)
- {
- const AP4_DataBuffer& data = cmvd->GetDataBuffer();
-
- z_stream d_stream;
- d_stream.zalloc = (alloc_func)0;
- d_stream.zfree = (free_func)0;
- d_stream.opaque = (voidpf)0;
-
- int res;
-
- if(Z_OK == (res = inflateInit(&d_stream)))
- {
- d_stream.next_in = (Bytef*)data.GetData();
- d_stream.avail_in = data.GetDataSize();
-
- unsigned char* dst = NULL;
- int n = 0;
-
- do
- {
- dst = (unsigned char*)realloc(dst, ++n * 1000);
- d_stream.next_out = &dst[(n-1)*1000];
- d_stream.avail_out = 1000;
-
- if(Z_OK != (res = inflate(&d_stream, Z_NO_FLUSH)) && Z_STREAM_END != res)
- {
- free(dst);
- dst = NULL;
- break;
- }
- }
- while(0 == d_stream.avail_out && 0 != d_stream.avail_in && Z_STREAM_END != res);
-
- inflateEnd(&d_stream);
-
- if(dst)
- {
- AP4_ByteStream* s = new AP4_MemoryByteStream(dst, d_stream.total_out);
- ReadChildren(atom_factory, *s, d_stream.total_out);
- s->Release();
- free(dst);
- }
-
- if(AP4_MoovAtom* moov = dynamic_cast<AP4_MoovAtom*>(GetChild(AP4_ATOM_TYPE_MOOV)))
- {
- AP4_List<AP4_Atom> Children;
-
- for(AP4_List<AP4_Atom>::Item* item = moov->GetChildren().FirstItem();
- item;
- item = item->GetNext())
- {
- Children.Add(item->GetData());
- }
-
- for(AP4_List<AP4_Atom>::Item* item = Children.FirstItem();
- item;
- item = item->GetNext())
- {
- AP4_Atom* atom = item->GetData();
- atom->Detach();
- atom->SetParent(this);
- m_Children.Add(atom);
- }
-
- moov->Detach();
- delete moov;
- }
- }
- }
- }
- // <== End patch MPC
-
- // collect all trak atoms
- m_Children.Apply(AP4_TrakAtomCollector(&m_TrakAtoms));
+ // ==> Start patch MPC
+ if(AP4_ContainerAtom* cmov = dynamic_cast<AP4_ContainerAtom*>(GetChild(AP4_ATOM_TYPE_CMOV)))
+ {
+ AP4_DcomAtom* dcom = dynamic_cast<AP4_DcomAtom*>(cmov->GetChild(AP4_ATOM_TYPE_DCOM));
+ AP4_CmvdAtom* cmvd = dynamic_cast<AP4_CmvdAtom*>(cmov->GetChild(AP4_ATOM_TYPE_CMVD));
+ if(dcom && dcom->GetCompressorSubType() == AP4_ATOM_TYPE('z','l','i','b') && cmvd)
+ {
+ const AP4_DataBuffer& data = cmvd->GetDataBuffer();
+
+ z_stream d_stream;
+ d_stream.zalloc = (alloc_func)0;
+ d_stream.zfree = (free_func)0;
+ d_stream.opaque = (voidpf)0;
+
+ int res;
+
+ if(Z_OK == (res = inflateInit(&d_stream)))
+ {
+ d_stream.next_in = (Bytef*)data.GetData();
+ d_stream.avail_in = data.GetDataSize();
+
+ unsigned char* dst = NULL;
+ int n = 0;
+
+ do
+ {
+ dst = (unsigned char*)realloc(dst, ++n*1000);
+ d_stream.next_out = &dst[(n-1)*1000];
+ d_stream.avail_out = 1000;
+
+ if(Z_OK != (res = inflate(&d_stream, Z_NO_FLUSH)) && Z_STREAM_END != res)
+ {
+ free(dst);
+ dst = NULL;
+ break;
+ }
+ }
+ while(0 == d_stream.avail_out && 0 != d_stream.avail_in && Z_STREAM_END != res);
+
+ inflateEnd(&d_stream);
+
+ if(dst)
+ {
+ AP4_ByteStream* s = new AP4_MemoryByteStream(dst, d_stream.total_out);
+ ReadChildren(atom_factory, *s, d_stream.total_out);
+ s->Release();
+ free(dst);
+ }
+
+ if(AP4_MoovAtom* moov = dynamic_cast<AP4_MoovAtom*>(GetChild(AP4_ATOM_TYPE_MOOV)))
+ {
+ AP4_List<AP4_Atom> Children;
+
+ for(AP4_List<AP4_Atom>::Item* item = moov->GetChildren().FirstItem();
+ item;
+ item = item->GetNext())
+ {
+ Children.Add(item->GetData());
+ }
+
+ for(AP4_List<AP4_Atom>::Item* item = Children.FirstItem();
+ item;
+ item = item->GetNext())
+ {
+ AP4_Atom* atom = item->GetData();
+ atom->Detach();
+ atom->SetParent(this);
+ m_Children.Add(atom);
+ }
+
+ moov->Detach();
+ delete moov;
+ }
+ }
+ }
+ }
+ // <== End patch MPC
+
+ // collect all trak atoms
+ m_Children.Apply(AP4_TrakAtomCollector(&m_TrakAtoms));
}
/*----------------------------------------------------------------------
| AP4_MoovAtom::AdjustChunkOffsets
+---------------------------------------------------------------------*/
-AP4_Result
+AP4_Result
AP4_MoovAtom::AdjustChunkOffsets(AP4_SI64 offset)
{
- for(AP4_List<AP4_TrakAtom>::Item* item = m_TrakAtoms.FirstItem();
- item;
- item = item->GetNext())
- {
+ for (AP4_List<AP4_TrakAtom>::Item* item = m_TrakAtoms.FirstItem();
+ item;
+ item = item->GetNext()) {
AP4_TrakAtom* trak = item->GetData();
trak->AdjustChunkOffsets(offset);
}
@@ -194,11 +190,9 @@ void
AP4_MoovAtom::OnChildAdded(AP4_Atom* atom)
{
// keep the atom in the list of trak atoms
- if(atom->GetType() == AP4_ATOM_TYPE_TRAK)
- {
+ if (atom->GetType() == AP4_ATOM_TYPE_TRAK) {
AP4_TrakAtom* trak = AP4_DYNAMIC_CAST(AP4_TrakAtom, atom);
- if(trak)
- {
+ if (trak) {
m_TrakAtoms.Add(trak);
}
}
@@ -214,11 +208,9 @@ void
AP4_MoovAtom::OnChildRemoved(AP4_Atom* atom)
{
// remove the atom from the list of trak atoms
- if(atom->GetType() == AP4_ATOM_TYPE_TRAK)
- {
+ if (atom->GetType() == AP4_ATOM_TYPE_TRAK) {
AP4_TrakAtom* trak = AP4_DYNAMIC_CAST(AP4_TrakAtom, atom);
- if(trak)
- {
+ if (trak) {
m_TrakAtoms.Remove(trak);
}
}
diff --git a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4MoovAtom.h b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4MoovAtom.h
index 8506e0a25..f06b2a137 100644
--- a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4MoovAtom.h
+++ b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4MoovAtom.h
@@ -1,6 +1,6 @@
/*****************************************************************
|
-| AP4 - moov Atoms
+| AP4 - moov Atoms
|
| Copyright 2002-2008 Axiomatic Systems, LLC
|
@@ -52,23 +52,20 @@ public:
// class methods
static AP4_MoovAtom* Create(AP4_Size size,
AP4_ByteStream& stream,
- AP4_AtomFactory& atom_factory)
- {
+ AP4_AtomFactory& atom_factory) {
return new AP4_MoovAtom(size, stream, atom_factory);
}
// methods
AP4_MoovAtom();
- AP4_List<AP4_TrakAtom>& GetTrakAtoms()
- {
+ AP4_List<AP4_TrakAtom>& GetTrakAtoms() {
return m_TrakAtoms;
}
- AP4_UI32 GetTimeScale()
- {
+ AP4_UI32 GetTimeScale() {
return m_TimeScale;
}
AP4_Result AdjustChunkOffsets(AP4_SI64 offset);
-
+
// AP4_AtomParent methods
void OnChildAdded(AP4_Atom* atom);
void OnChildRemoved(AP4_Atom* atom);
diff --git a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4Movie.cpp b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4Movie.cpp
index bd6e24251..57c8c3c50 100644
--- a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4Movie.cpp
+++ b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4Movie.cpp
@@ -45,8 +45,7 @@ class AP4_TrackFinderById : public AP4_List<AP4_Track>::Item::Finder
{
public:
AP4_TrackFinderById(AP4_UI32 track_id) : m_TrackId(track_id) {}
- AP4_Result Test(AP4_Track* track) const
- {
+ AP4_Result Test(AP4_Track* track) const {
return track->GetId() == m_TrackId ? AP4_SUCCESS : AP4_FAILURE;
}
private:
@@ -59,16 +58,12 @@ private:
class AP4_TrackFinderByType : public AP4_List<AP4_Track>::Item::Finder
{
public:
- AP4_TrackFinderByType(AP4_Track::Type type, AP4_Ordinal index = 0) :
- m_Type(type), m_Index(index) {}
- AP4_Result Test(AP4_Track* track) const
- {
- if(track->GetType() == m_Type && m_Index-- == 0)
- {
+ AP4_TrackFinderByType(AP4_Track::Type type, AP4_Ordinal index = 0) :
+ m_Type(type), m_Index(index) {}
+ AP4_Result Test(AP4_Track* track) const {
+ if (track->GetType() == m_Type && m_Index-- == 0) {
return AP4_SUCCESS;
- }
- else
- {
+ } else {
return AP4_FAILURE;
}
}
@@ -84,9 +79,9 @@ AP4_Movie::AP4_Movie(AP4_UI32 time_scale) :
m_MoovAtomIsOwned(true)
{
m_MoovAtom = new AP4_MoovAtom();
- m_MvhdAtom = new AP4_MvhdAtom(0, 0,
- time_scale,
- 0,
+ m_MvhdAtom = new AP4_MvhdAtom(0, 0,
+ time_scale,
+ 0,
0x00010000,
0x0100);
m_MoovAtom->AddChild(m_MvhdAtom);
@@ -100,17 +95,14 @@ AP4_Movie::AP4_Movie(AP4_MoovAtom* moov, AP4_ByteStream& sample_stream, bool tra
m_MoovAtomIsOwned(transfer_moov_ownership)
{
// ignore null atoms
- if(moov == NULL) return;
+ if (moov == NULL) return;
// get the time scale
AP4_UI32 time_scale;
m_MvhdAtom = AP4_DYNAMIC_CAST(AP4_MvhdAtom, moov->GetChild(AP4_ATOM_TYPE_MVHD));
- if(m_MvhdAtom)
- {
+ if (m_MvhdAtom) {
time_scale = m_MvhdAtom->GetTimeScale();
- }
- else
- {
+ } else {
time_scale = 0;
}
@@ -118,23 +110,22 @@ AP4_Movie::AP4_Movie(AP4_MoovAtom* moov, AP4_ByteStream& sample_stream, bool tra
AP4_List<AP4_TrakAtom>* trak_atoms;
trak_atoms = &moov->GetTrakAtoms();
AP4_List<AP4_TrakAtom>::Item* item = trak_atoms->FirstItem();
- while(item)
- {
- AP4_Track* track = new AP4_Track(*item->GetData(),
+ while (item) {
+ AP4_Track* track = new AP4_Track(*item->GetData(),
sample_stream,
time_scale);
m_Tracks.Add(track);
item = item->GetNext();
}
}
-
+
/*----------------------------------------------------------------------
| AP4_Movie::~AP4_Movie
+---------------------------------------------------------------------*/
AP4_Movie::~AP4_Movie()
{
m_Tracks.DeleteReferences();
- if(m_MoovAtomIsOwned) delete m_MoovAtom;
+ if (m_MoovAtomIsOwned) delete m_MoovAtom;
}
/*----------------------------------------------------------------------
@@ -154,12 +145,9 @@ AP4_Track*
AP4_Movie::GetTrack(AP4_UI32 track_id)
{
AP4_Track* track = NULL;
- if(AP4_SUCCEEDED(m_Tracks.Find(AP4_TrackFinderById(track_id), track)))
- {
+ if (AP4_SUCCEEDED(m_Tracks.Find(AP4_TrackFinderById(track_id), track))) {
return track;
- }
- else
- {
+ } else {
return NULL;
}
}
@@ -171,12 +159,9 @@ AP4_Track*
AP4_Movie::GetTrack(AP4_Track::Type track_type, AP4_Ordinal index)
{
AP4_Track* track = NULL;
- if(AP4_SUCCEEDED(m_Tracks.Find(AP4_TrackFinderByType(track_type, index), track)))
- {
+ if (AP4_SUCCEEDED(m_Tracks.Find(AP4_TrackFinderByType(track_type, index), track))) {
return track;
- }
- else
- {
+ } else {
return NULL;
}
}
@@ -188,14 +173,12 @@ AP4_Result
AP4_Movie::AddTrack(AP4_Track* track)
{
// assign an ID to the track unless it already has one
- if(track->GetId() == 0)
- {
- track->SetId(m_Tracks.ItemCount() + 1);
+ if (track->GetId() == 0) {
+ track->SetId(m_Tracks.ItemCount()+1);
}
// if we don't have a time scale, use the one from the track
- if(m_MvhdAtom->GetTimeScale() == 0)
- {
+ if (m_MvhdAtom->GetTimeScale() == 0) {
m_MvhdAtom->SetTimeScale(track->GetMediaTimeScale());
}
@@ -203,11 +186,10 @@ AP4_Movie::AddTrack(AP4_Track* track)
track->SetMovieTimeScale(m_MvhdAtom->GetTimeScale());
// update the movie duration
- if(m_MvhdAtom->GetDuration() < track->GetDuration())
- {
+ if (m_MvhdAtom->GetDuration() < track->GetDuration()) {
m_MvhdAtom->SetDuration(track->GetDuration());
}
-
+
// attach the track as a child
track->Attach(m_MoovAtom);
m_Tracks.Add(track);
@@ -221,12 +203,9 @@ AP4_Movie::AddTrack(AP4_Track* track)
AP4_UI32
AP4_Movie::GetTimeScale()
{
- if(m_MvhdAtom)
- {
+ if (m_MvhdAtom) {
return m_MvhdAtom->GetTimeScale();
- }
- else
- {
+ } else {
return 0;
}
}
@@ -237,12 +216,9 @@ AP4_Movie::GetTimeScale()
AP4_UI64
AP4_Movie::GetDuration()
{
- if(m_MvhdAtom)
- {
+ if (m_MvhdAtom) {
return m_MvhdAtom->GetDuration();
- }
- else
- {
+ } else {
return 0;
}
}
@@ -253,12 +229,9 @@ AP4_Movie::GetDuration()
AP4_UI32
AP4_Movie::GetDurationMs()
{
- if(m_MvhdAtom)
- {
+ if (m_MvhdAtom) {
return m_MvhdAtom->GetDurationMs();
- }
- else
- {
+ } else {
return 0;
}
}
diff --git a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4Movie.h b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4Movie.h
index 8cea28a26..80d6cdb19 100644
--- a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4Movie.h
+++ b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4Movie.h
@@ -1,6 +1,6 @@
/*****************************************************************
|
-| AP4 - Movie
+| AP4 - Movie
|
| Copyright 2002-2008 Axiomatic Systems, LLC
|
@@ -48,8 +48,7 @@ class AP4_MetaData;
/*----------------------------------------------------------------------
| AP4_Movie
+---------------------------------------------------------------------*/
-class AP4_Movie
-{
+class AP4_Movie {
public:
// methods
AP4_Movie(AP4_UI32 time_scale = 0);
@@ -57,25 +56,16 @@ public:
virtual ~AP4_Movie();
AP4_Result Inspect(AP4_AtomInspector& inspector);
- AP4_MoovAtom* GetMoovAtom()
- {
- return m_MoovAtom;
- }
- AP4_MvhdAtom* GetMvhdAtom()
- {
- return m_MvhdAtom;
- }
- AP4_List<AP4_Track>& GetTracks()
- {
- return m_Tracks;
- }
+ AP4_MoovAtom* GetMoovAtom() { return m_MoovAtom;}
+ AP4_MvhdAtom* GetMvhdAtom() { return m_MvhdAtom;}
+ AP4_List<AP4_Track>& GetTracks() { return m_Tracks; }
AP4_Track* GetTrack(AP4_UI32 track_id);
AP4_Track* GetTrack(AP4_Track::Type type, AP4_Ordinal index = 0);
AP4_Result AddTrack(AP4_Track* track);
AP4_UI32 GetTimeScale();
AP4_UI64 GetDuration();
AP4_UI32 GetDurationMs();
-
+
private:
// members
AP4_MoovAtom* m_MoovAtom;
diff --git a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4MovieFragment.cpp b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4MovieFragment.cpp
index 4d982d409..d85bc008b 100644
--- a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4MovieFragment.cpp
+++ b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4MovieFragment.cpp
@@ -47,7 +47,7 @@ AP4_MovieFragment::AP4_MovieFragment(AP4_ContainerAtom* moof) :
m_MoofAtom(moof),
m_MfhdAtom(NULL)
{
- if(moof) m_MfhdAtom = AP4_DYNAMIC_CAST(AP4_MfhdAtom, moof->GetChild(AP4_ATOM_TYPE_MFHD));
+ if (moof) m_MfhdAtom = AP4_DYNAMIC_CAST(AP4_MfhdAtom, moof->GetChild(AP4_ATOM_TYPE_MFHD));
}
/*----------------------------------------------------------------------
@@ -64,7 +64,7 @@ AP4_MovieFragment::~AP4_MovieFragment()
AP4_UI32
AP4_MovieFragment::GetSequenceNumber()
{
- return m_MfhdAtom ? m_MfhdAtom->GetSequenceNumber() : 0;
+ return m_MfhdAtom?m_MfhdAtom->GetSequenceNumber():0;
}
/*----------------------------------------------------------------------
@@ -75,51 +75,44 @@ AP4_MovieFragment::GetTrackIds(AP4_Array<AP4_UI32>& ids)
{
ids.Clear();
ids.EnsureCapacity(m_MoofAtom->GetChildren().ItemCount());
-
- for(AP4_List<AP4_Atom>::Item* item = m_MoofAtom->GetChildren().FirstItem();
- item;
- item = item->GetNext())
- {
+
+ for (AP4_List<AP4_Atom>::Item* item = m_MoofAtom->GetChildren().FirstItem();
+ item;
+ item = item->GetNext()) {
AP4_Atom* atom = item->GetData();
- if(atom->GetType() == AP4_ATOM_TYPE_TRAF)
- {
+ if (atom->GetType() == AP4_ATOM_TYPE_TRAF) {
AP4_ContainerAtom* traf = AP4_DYNAMIC_CAST(AP4_ContainerAtom, atom);
- if(traf)
- {
+ if (traf) {
AP4_TfhdAtom* tfhd = AP4_DYNAMIC_CAST(AP4_TfhdAtom, traf->GetChild(AP4_ATOM_TYPE_TFHD));
- if(tfhd) ids.Append(tfhd->GetTrackId());
+ if (tfhd) ids.Append(tfhd->GetTrackId());
}
}
}
-
+
return AP4_SUCCESS;
}
/*----------------------------------------------------------------------
| AP4_MovieFragment::GetTrafAtom
+---------------------------------------------------------------------*/
-AP4_Result
+AP4_Result
AP4_MovieFragment::GetTrafAtom(AP4_UI32 track_id, AP4_ContainerAtom*& traf)
{
- for(AP4_List<AP4_Atom>::Item* item = m_MoofAtom->GetChildren().FirstItem();
- item;
- item = item->GetNext())
- {
+ for (AP4_List<AP4_Atom>::Item* item = m_MoofAtom->GetChildren().FirstItem();
+ item;
+ item = item->GetNext()) {
AP4_Atom* atom = item->GetData();
- if(atom->GetType() == AP4_ATOM_TYPE_TRAF)
- {
+ if (atom->GetType() == AP4_ATOM_TYPE_TRAF) {
traf = AP4_DYNAMIC_CAST(AP4_ContainerAtom, atom);
- if(traf)
- {
+ if (traf) {
AP4_TfhdAtom* tfhd = AP4_DYNAMIC_CAST(AP4_TfhdAtom, traf->GetChild(AP4_ATOM_TYPE_TFHD));
- if(tfhd && tfhd->GetTrackId() == track_id)
- {
+ if (tfhd && tfhd->GetTrackId() == track_id) {
return AP4_SUCCESS;
}
}
}
}
-
+
// not found
traf = NULL;
return AP4_ERROR_NO_SUCH_ITEM;
@@ -128,9 +121,9 @@ AP4_MovieFragment::GetTrafAtom(AP4_UI32 track_id, AP4_ContainerAtom*& traf)
/*----------------------------------------------------------------------
| AP4_MovieFragment::CreateSampleTable
+---------------------------------------------------------------------*/
-AP4_Result
+AP4_Result
AP4_MovieFragment::CreateSampleTable(AP4_MoovAtom* moov,
- AP4_UI32 track_id,
+ AP4_UI32 track_id,
AP4_ByteStream* sample_stream,
AP4_Position moof_offset,
AP4_Position mdat_payload_offset,
@@ -138,54 +131,49 @@ AP4_MovieFragment::CreateSampleTable(AP4_MoovAtom* moov,
{
// default value
sample_table = NULL;
-
+
// find a trex for this track, if any
AP4_ContainerAtom* mvex = NULL;
AP4_TrexAtom* trex = NULL;
- if(moov)
- {
+ if (moov) {
mvex = AP4_DYNAMIC_CAST(AP4_ContainerAtom, moov->GetChild(AP4_ATOM_TYPE_MVEX));
}
- if(mvex)
- {
- for(AP4_List<AP4_Atom>::Item* item = mvex->GetChildren().FirstItem();
- item;
- item = item->GetNext())
- {
+ if (mvex) {
+ for (AP4_List<AP4_Atom>::Item* item = mvex->GetChildren().FirstItem();
+ item;
+ item = item->GetNext()) {
AP4_Atom* atom = item->GetData();
- if(atom->GetType() == AP4_ATOM_TYPE_TREX)
- {
+ if (atom->GetType() == AP4_ATOM_TYPE_TREX) {
trex = AP4_DYNAMIC_CAST(AP4_TrexAtom, atom);
- if(trex && trex->GetTrackId() == track_id) break;
+ if (trex && trex->GetTrackId() == track_id) break;
trex = NULL;
}
}
}
AP4_ContainerAtom* traf = NULL;
- if(AP4_SUCCEEDED(GetTrafAtom(track_id, traf)))
- {
- sample_table = new AP4_FragmentSampleTable(traf,
- trex,
- sample_stream,
- moof_offset,
- mdat_payload_offset);
+ if (AP4_SUCCEEDED(GetTrafAtom(track_id, traf))) {
+ sample_table = new AP4_FragmentSampleTable(traf,
+ trex,
+ sample_stream,
+ moof_offset,
+ mdat_payload_offset);
return AP4_SUCCESS;
}
-
+
return AP4_ERROR_NO_SUCH_ITEM;
}
/*----------------------------------------------------------------------
| AP4_MovieFragment::CreateSampleTable
+---------------------------------------------------------------------*/
-AP4_Result
+AP4_Result
AP4_MovieFragment::CreateSampleTable(AP4_Movie* movie,
- AP4_UI32 track_id,
+ AP4_UI32 track_id,
AP4_ByteStream* sample_stream,
AP4_Position moof_offset,
AP4_Position mdat_payload_offset,
AP4_FragmentSampleTable*& sample_table)
{
- AP4_MoovAtom* moov = movie ? movie->GetMoovAtom() : NULL;
+ AP4_MoovAtom* moov = movie?movie->GetMoovAtom():NULL;
return CreateSampleTable(moov, track_id, sample_stream, moof_offset, mdat_payload_offset, sample_table);
}
diff --git a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4MovieFragment.h b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4MovieFragment.h
index 92b2c6de3..6ff5aae9a 100644
--- a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4MovieFragment.h
+++ b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4MovieFragment.h
@@ -53,38 +53,31 @@ const AP4_UI32 AP4_FRAG_FLAG_SAMPLE_IS_DIFFERENCE = 0x00010000;
/*----------------------------------------------------------------------
| AP4_MovieFragment
+---------------------------------------------------------------------*/
-class AP4_MovieFragment
-{
+class AP4_MovieFragment {
public:
// this constructor transfers the ownership of the moof atom to the
// newly constructed object
AP4_MovieFragment(AP4_ContainerAtom* moof);
virtual ~AP4_MovieFragment();
- AP4_ContainerAtom* GetMoofAtom()
- {
- return m_MoofAtom;
- }
- AP4_MfhdAtom* GetMfhdAtom()
- {
- return m_MfhdAtom;
- }
+ AP4_ContainerAtom* GetMoofAtom() { return m_MoofAtom;}
+ AP4_MfhdAtom* GetMfhdAtom() { return m_MfhdAtom;}
AP4_UI32 GetSequenceNumber();
AP4_Result GetTrackIds(AP4_Array<AP4_UI32>& ids);
AP4_Result GetTrafAtom(AP4_UI32 track_id, AP4_ContainerAtom*& traf);
AP4_Result CreateSampleTable(AP4_MoovAtom* moov,
- AP4_UI32 track_id,
+ AP4_UI32 track_id,
AP4_ByteStream* sample_stream,
AP4_Position moof_offset,
AP4_Position mdat_payload_offset, // hack because MS doesn't implement the spec properly
AP4_FragmentSampleTable*& sample_table);
AP4_Result CreateSampleTable(AP4_Movie* movie,
- AP4_UI32 track_id,
+ AP4_UI32 track_id,
AP4_ByteStream* sample_stream,
AP4_Position moof_offset,
AP4_Position mdat_payload_offset, // hack because MS doesn't implement the spec properly
AP4_FragmentSampleTable*& sample_table);
-
+
private:
// members
AP4_ContainerAtom* m_MoofAtom;
diff --git a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4Mpeg2Ts.cpp b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4Mpeg2Ts.cpp
index 8078a6d05..dbb5f5982 100644
--- a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4Mpeg2Ts.cpp
+++ b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4Mpeg2Ts.cpp
@@ -43,30 +43,30 @@ const unsigned int AP4_MPEG2TS_PACKET_PAYLOAD_SIZE = 184;
const unsigned int AP4_MPEG2TS_SYNC_BYTE = 0x47;
const unsigned int AP4_MPEG2TS_PCR_ADAPTATION_SIZE = 6;
-static unsigned char const StuffingBytes[AP4_MPEG2TS_PACKET_SIZE] =
+static unsigned char const StuffingBytes[AP4_MPEG2TS_PACKET_SIZE] =
{
- 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
- 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
- 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
- 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
- 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
- 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
- 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
- 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
- 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
- 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
- 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
- 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
- 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
- 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
- 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
- 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
- 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
- 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
- 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
- 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
- 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
- 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
+ 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
+ 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
+ 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
+ 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
+ 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
+ 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
+ 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
+ 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
+ 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
+ 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
+ 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
+ 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
+ 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
+ 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
+ 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
+ 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
+ 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
+ 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
+ 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
+ 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
+ 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
+ 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
0xFF, 0xFF, 0xFF, 0xFF
};
@@ -77,36 +77,21 @@ static unsigned char const StuffingBytes[AP4_MPEG2TS_PACKET_SIZE] =
static unsigned int
GetSamplingFrequencyIndex(unsigned int sampling_frequency)
{
- switch(sampling_frequency)
- {
- case 96000:
- return 0;
- case 88200:
- return 1;
- case 64000:
- return 2;
- case 48000:
- return 3;
- case 44100:
- return 4;
- case 32000:
- return 5;
- case 24000:
- return 6;
- case 22050:
- return 7;
- case 16000:
- return 8;
- case 12000:
- return 9;
- case 11025:
- return 10;
- case 8000:
- return 11;
- case 7350:
- return 12;
- default:
- return 0;
+ switch (sampling_frequency) {
+ case 96000: return 0;
+ case 88200: return 1;
+ case 64000: return 2;
+ case 48000: return 3;
+ case 44100: return 4;
+ case 32000: return 5;
+ case 24000: return 6;
+ case 22050: return 7;
+ case 16000: return 8;
+ case 12000: return 9;
+ case 11025: return 10;
+ case 8000: return 11;
+ case 7350: return 12;
+ default: return 0;
}
}
@@ -114,49 +99,48 @@ GetSamplingFrequencyIndex(unsigned int sampling_frequency)
| MakeAdtsHeader
+---------------------------------------------------------------------*/
static void
-MakeAdtsHeader(unsigned char bits[7],
+MakeAdtsHeader(unsigned char bits[7],
unsigned int frame_size,
unsigned int sampling_frequency_index,
unsigned int channel_configuration)
{
- bits[0] = 0xFF;
- bits[1] = 0xF1; // 0xF9 (MPEG2)
- bits[2] = 0x40 | (sampling_frequency_index << 2) | (channel_configuration >> 2);
- bits[3] = ((channel_configuration & 0x3) << 6) | ((frame_size + 7) >> 11);
- bits[4] = ((frame_size + 7) >> 3) & 0xFF;
- bits[5] = (((frame_size + 7) << 5) & 0xFF) | 0x1F;
- bits[6] = 0xFC;
-
- /*
- 0: syncword 12 always: '111111111111'
- 12: ID 1 0: MPEG-4, 1: MPEG-2
- 13: layer 2 always: '00'
- 15: protection_absent 1
- 16: profile 2
- 18: sampling_frequency_index 4
- 22: private_bit 1
- 23: channel_configuration 3
- 26: original/copy 1
- 27: home 1
- 28: emphasis 2 only if ID == 0
-
- ADTS Variable header: these can change from frame to frame
- 28: copyright_identification_bit 1
- 29: copyright_identification_start 1
- 30: aac_frame_length 13 length of the frame including header (in bytes)
- 43: adts_buffer_fullness 11 0x7FF indicates VBR
- 54: no_raw_data_blocks_in_frame 2
- ADTS Error check
- crc_check 16 only if protection_absent == 0
+ bits[0] = 0xFF;
+ bits[1] = 0xF1; // 0xF9 (MPEG2)
+ bits[2] = 0x40 | (sampling_frequency_index << 2) | (channel_configuration >> 2);
+ bits[3] = ((channel_configuration&0x3)<<6) | ((frame_size+7) >> 11);
+ bits[4] = ((frame_size+7) >> 3)&0xFF;
+ bits[5] = (((frame_size+7) << 5)&0xFF) | 0x1F;
+ bits[6] = 0xFC;
+
+ /*
+ 0: syncword 12 always: '111111111111'
+ 12: ID 1 0: MPEG-4, 1: MPEG-2
+ 13: layer 2 always: '00'
+ 15: protection_absent 1
+ 16: profile 2
+ 18: sampling_frequency_index 4
+ 22: private_bit 1
+ 23: channel_configuration 3
+ 26: original/copy 1
+ 27: home 1
+ 28: emphasis 2 only if ID == 0
+
+ ADTS Variable header: these can change from frame to frame
+ 28: copyright_identification_bit 1
+ 29: copyright_identification_start 1
+ 30: aac_frame_length 13 length of the frame including header (in bytes)
+ 43: adts_buffer_fullness 11 0x7FF indicates VBR
+ 54: no_raw_data_blocks_in_frame 2
+ ADTS Error check
+ crc_check 16 only if protection_absent == 0
*/
}
/*----------------------------------------------------------------------
| CRC_Table
+---------------------------------------------------------------------*/
-static AP4_UI32
-const CRC_Table[256] =
-{
+static AP4_UI32
+const CRC_Table[256] = {
0x00000000, 0x04c11db7, 0x09823b6e, 0x0d4326d9, 0x130476dc, 0x17c56b6b,
0x1a864db2, 0x1e475005, 0x2608edb8, 0x22c9f00f, 0x2f8ad6d6, 0x2b4bcb61,
0x350c9b64, 0x31cd86d3, 0x3c8ea00a, 0x384fbdbd, 0x4c11db70, 0x48d0c6c7,
@@ -209,12 +193,11 @@ static AP4_UI32
ComputeCRC(const unsigned char* data, unsigned int data_size)
{
AP4_UI32 crc = 0xFFFFFFFF;
-
- for(unsigned int i = 0; i < data_size; i++)
- {
+
+ for (unsigned int i=0; i<data_size; i++) {
crc = (crc << 8) ^ CRC_Table[((crc >> 24) ^ *data++) & 0xFF];
}
-
+
return crc;
}
@@ -222,242 +205,226 @@ ComputeCRC(const unsigned char* data, unsigned int data_size)
| AP4_Mpeg2TsWriter::Stream::WritePacketHeader
+---------------------------------------------------------------------*/
void
-AP4_Mpeg2TsWriter::Stream::WritePacketHeader(bool payload_start,
- unsigned int& payload_size,
- bool with_pcr,
- AP4_UI64 pcr,
- AP4_ByteStream& output)
+AP4_Mpeg2TsWriter::Stream::WritePacketHeader(bool payload_start,
+ unsigned int& payload_size,
+ bool with_pcr,
+ AP4_UI64 pcr,
+ AP4_ByteStream& output)
{
unsigned char header[4];
header[0] = AP4_MPEG2TS_SYNC_BYTE;
- header[1] = ((payload_start ? 1 : 0) << 6) | (m_PID >> 8);
+ header[1] = ((payload_start?1:0)<<6) | (m_PID >> 8);
header[2] = m_PID & 0xFF;
-
+
unsigned int adaptation_field_size = 0;
- if(with_pcr) adaptation_field_size += 2 + AP4_MPEG2TS_PCR_ADAPTATION_SIZE;
-
+ if (with_pcr) adaptation_field_size += 2+AP4_MPEG2TS_PCR_ADAPTATION_SIZE;
+
// clamp the payload size
- if(payload_size + adaptation_field_size > AP4_MPEG2TS_PACKET_PAYLOAD_SIZE)
- {
- payload_size = AP4_MPEG2TS_PACKET_PAYLOAD_SIZE - adaptation_field_size;
+ if (payload_size+adaptation_field_size > AP4_MPEG2TS_PACKET_PAYLOAD_SIZE) {
+ payload_size = AP4_MPEG2TS_PACKET_PAYLOAD_SIZE-adaptation_field_size;
}
-
+
// adjust the adaptation field to include stuffing if necessary
- if(adaptation_field_size + payload_size < AP4_MPEG2TS_PACKET_PAYLOAD_SIZE)
- {
- adaptation_field_size = AP4_MPEG2TS_PACKET_PAYLOAD_SIZE - payload_size;
+ if (adaptation_field_size+payload_size < AP4_MPEG2TS_PACKET_PAYLOAD_SIZE) {
+ adaptation_field_size = AP4_MPEG2TS_PACKET_PAYLOAD_SIZE-payload_size;
}
-
- if(adaptation_field_size == 0)
- {
+
+ if (adaptation_field_size == 0) {
// no adaptation field
- header[3] = (1 << 4) | ((m_ContinuityCounter++) & 0x0F);
+ header[3] = (1<<4) | ((m_ContinuityCounter++)&0x0F);
output.Write(header, 4);
- }
- else
- {
+ } else {
// adaptation field present
- header[3] = (3 << 4) | ((m_ContinuityCounter++) & 0x0F);
+ header[3] = (3<<4) | ((m_ContinuityCounter++)&0x0F);
output.Write(header, 4);
-
- if(adaptation_field_size == 1)
- {
+
+ if (adaptation_field_size == 1) {
// just one byte (stuffing)
output.WriteUI08(0);
- }
- else
- {
+ } else {
// two or more bytes (stuffing and/or PCR)
- output.WriteUI08(adaptation_field_size - 1);
- output.WriteUI08(with_pcr ? (1 << 4) : 0);
+ output.WriteUI08(adaptation_field_size-1);
+ output.WriteUI08(with_pcr?(1<<4):0);
unsigned int pcr_size = 0;
- if(with_pcr)
- {
+ if (with_pcr) {
pcr_size = AP4_MPEG2TS_PCR_ADAPTATION_SIZE;
- AP4_UI64 pcr_base = pcr / 300;
- AP4_UI32 pcr_ext = (AP4_UI32)(pcr % 300);
+ AP4_UI64 pcr_base = pcr/300;
+ AP4_UI32 pcr_ext = (AP4_UI32)(pcr%300);
AP4_BitWriter writer(pcr_size);
- writer.Write((AP4_UI32)(pcr_base >> 32), 1);
+ writer.Write((AP4_UI32)(pcr_base>>32), 1);
writer.Write((AP4_UI32)pcr_base, 32);
writer.Write(0x3F, 6);
writer.Write(pcr_ext, 9);
output.Write(writer.GetData(), pcr_size);
- }
- if(adaptation_field_size > 2)
- {
- output.Write(StuffingBytes, adaptation_field_size - pcr_size - 2);
+ }
+ if (adaptation_field_size > 2) {
+ output.Write(StuffingBytes, adaptation_field_size-pcr_size-2);
}
}
}
-}
+}
/*----------------------------------------------------------------------
| AP4_Mpeg2TsWriter::SampleStream::WritePES
+---------------------------------------------------------------------*/
AP4_Result
-AP4_Mpeg2TsWriter::SampleStream::WritePES(const unsigned char* data,
- unsigned int data_size,
- AP4_UI64 dts,
- bool with_dts,
- AP4_UI64 pts,
- bool with_pcr,
- AP4_ByteStream& output)
+AP4_Mpeg2TsWriter::SampleStream::WritePES(const unsigned char* data,
+ unsigned int data_size,
+ AP4_UI64 dts,
+ bool with_dts,
+ AP4_UI64 pts,
+ bool with_pcr,
+ AP4_ByteStream& output)
{
- unsigned int pes_header_size = 14 + (with_dts ? 5 : 0);
+ unsigned int pes_header_size = 14+(with_dts?5:0);
AP4_BitWriter pes_header(pes_header_size);
-
+
pes_header.Write(0x000001, 24); // packet_start_code_prefix
pes_header.Write(m_StreamId, 8); // stream_id
- pes_header.Write(m_StreamId == AP4_MPEG2_TS_DEFAULT_STREAM_ID_VIDEO ? 0 : (data_size + pes_header_size - 6), 16); // PES_packet_length
+ pes_header.Write(m_StreamId == AP4_MPEG2_TS_DEFAULT_STREAM_ID_VIDEO?0:(data_size+pes_header_size-6), 16); // PES_packet_length
pes_header.Write(2, 2); // '01'
pes_header.Write(0, 2); // PES_scrambling_control
pes_header.Write(0, 1); // PES_priority
pes_header.Write(1, 1); // data_alignment_indicator
pes_header.Write(0, 1); // copyright
pes_header.Write(0, 1); // original_or_copy
- pes_header.Write(with_dts ? 3 : 2, 2); // PTS_DTS_flags
+ pes_header.Write(with_dts?3:2, 2); // PTS_DTS_flags
pes_header.Write(0, 1); // ESCR_flag
pes_header.Write(0, 1); // ES_rate_flag
pes_header.Write(0, 1); // DSM_trick_mode_flag
pes_header.Write(0, 1); // additional_copy_info_flag
pes_header.Write(0, 1); // PES_CRC_flag
pes_header.Write(0, 1); // PES_extension_flag
- pes_header.Write(pes_header_size - 9, 8); // PES_header_data_length
-
- pes_header.Write(with_dts ? 3 : 2, 4); // '0010' or '0011'
- pes_header.Write((AP4_UI32)(pts >> 30), 3); // PTS[32..30]
+ pes_header.Write(pes_header_size-9, 8);// PES_header_data_length
+
+ pes_header.Write(with_dts?3:2, 4); // '0010' or '0011'
+ pes_header.Write((AP4_UI32)(pts>>30), 3); // PTS[32..30]
pes_header.Write(1, 1); // marker_bit
- pes_header.Write((AP4_UI32)(pts >> 15), 15); // PTS[29..15]
+ pes_header.Write((AP4_UI32)(pts>>15), 15); // PTS[29..15]
pes_header.Write(1, 1); // marker_bit
pes_header.Write((AP4_UI32)pts, 15); // PTS[14..0]
pes_header.Write(1, 1); // market_bit
-
- if(with_dts)
- {
+
+ if (with_dts) {
pes_header.Write(1, 4); // '0001'
- pes_header.Write((AP4_UI32)(dts >> 30), 3); // DTS[32..30]
+ pes_header.Write((AP4_UI32)(dts>>30), 3); // DTS[32..30]
pes_header.Write(1, 1); // marker_bit
- pes_header.Write((AP4_UI32)(dts >> 15), 15); // DTS[29..15]
+ pes_header.Write((AP4_UI32)(dts>>15), 15); // DTS[29..15]
pes_header.Write(1, 1); // marker_bit
pes_header.Write((AP4_UI32)dts, 15); // DTS[14..0]
pes_header.Write(1, 1); // market_bit
}
-
+
bool first_packet = true;
data_size += pes_header_size; // add size of PES header
- while(data_size)
- {
+ while (data_size) {
unsigned int payload_size = data_size;
- if(payload_size > AP4_MPEG2TS_PACKET_PAYLOAD_SIZE) payload_size = AP4_MPEG2TS_PACKET_PAYLOAD_SIZE;
-
- if(first_packet)
- {
- WritePacketHeader(first_packet, payload_size, with_pcr, (with_dts ? dts : pts) * 300, output);
+ if (payload_size > AP4_MPEG2TS_PACKET_PAYLOAD_SIZE) payload_size = AP4_MPEG2TS_PACKET_PAYLOAD_SIZE;
+
+ if (first_packet) {
+ WritePacketHeader(first_packet, payload_size, with_pcr, (with_dts?dts:pts)*300, output);
first_packet = false;
output.Write(pes_header.GetData(), pes_header_size);
- output.Write(data, payload_size - pes_header_size);
- data += payload_size - pes_header_size;
- }
- else
- {
+ output.Write(data, payload_size-pes_header_size);
+ data += payload_size-pes_header_size;
+ } else {
WritePacketHeader(first_packet, payload_size, false, 0, output);
output.Write(data, payload_size);
data += payload_size;
}
data_size -= payload_size;
}
-
+
return AP4_SUCCESS;
}
/*----------------------------------------------------------------------
| AP4_Mpeg2TsAudioSampleStream
+---------------------------------------------------------------------*/
-class AP4_Mpeg2TsAudioSampleStream : public AP4_Mpeg2TsWriter::SampleStream
+class AP4_Mpeg2TsAudioSampleStream : public AP4_Mpeg2TsWriter::SampleStream
{
public:
- static AP4_Result Create(AP4_UI16 pid,
- AP4_UI32 timescale,
+ static AP4_Result Create(AP4_UI16 pid,
+ AP4_UI32 timescale,
AP4_Mpeg2TsWriter::SampleStream*& stream);
- AP4_Result WriteSample(AP4_Sample& sample,
+ AP4_Result WriteSample(AP4_Sample& sample,
AP4_SampleDescription* sample_description,
- bool with_pcr,
+ bool with_pcr,
AP4_ByteStream& output);
-
+
private:
- AP4_Mpeg2TsAudioSampleStream(AP4_UI16 pid, AP4_UI32 timescale) :
- AP4_Mpeg2TsWriter::SampleStream(pid,
- AP4_MPEG2_TS_DEFAULT_STREAM_ID_AUDIO,
- AP4_MPEG2_STREAM_TYPE_ISO_IEC_13818_7,
- timescale) {}
+ AP4_Mpeg2TsAudioSampleStream(AP4_UI16 pid, AP4_UI32 timescale) :
+ AP4_Mpeg2TsWriter::SampleStream(pid,
+ AP4_MPEG2_TS_DEFAULT_STREAM_ID_AUDIO,
+ AP4_MPEG2_STREAM_TYPE_ISO_IEC_13818_7,
+ timescale) {}
};
/*----------------------------------------------------------------------
| AP4_Mpeg2TsAudioSampleStream::Create
+---------------------------------------------------------------------*/
-AP4_Result
-AP4_Mpeg2TsAudioSampleStream::Create(AP4_UI16 pid,
- AP4_UI32 timescale,
+AP4_Result
+AP4_Mpeg2TsAudioSampleStream::Create(AP4_UI16 pid,
+ AP4_UI32 timescale,
AP4_Mpeg2TsWriter::SampleStream*& stream)
{
stream = new AP4_Mpeg2TsAudioSampleStream(pid, timescale);
return AP4_SUCCESS;
}
-
+
/*----------------------------------------------------------------------
| AP4_Mpeg2TsAudioSampleStream::WriteSample
+---------------------------------------------------------------------*/
AP4_Result
-AP4_Mpeg2TsAudioSampleStream::WriteSample(AP4_Sample& sample,
- AP4_SampleDescription* sample_description,
- bool with_pcr,
- AP4_ByteStream& output)
+AP4_Mpeg2TsAudioSampleStream::WriteSample(AP4_Sample& sample,
+ AP4_SampleDescription* sample_description,
+ bool with_pcr,
+ AP4_ByteStream& output)
{
// check the sample description
AP4_MpegAudioSampleDescription* audio_desc = AP4_DYNAMIC_CAST(AP4_MpegAudioSampleDescription, sample_description);
- if(audio_desc == NULL) return AP4_ERROR_NOT_SUPPORTED;
- if(audio_desc->GetMpeg4AudioObjectType() != AP4_MPEG4_AUDIO_OBJECT_TYPE_AAC_LC) return AP4_ERROR_NOT_SUPPORTED;
+ if (audio_desc == NULL) return AP4_ERROR_NOT_SUPPORTED;
+ if (audio_desc->GetMpeg4AudioObjectType() != AP4_MPEG4_AUDIO_OBJECT_TYPE_AAC_LC) return AP4_ERROR_NOT_SUPPORTED;
unsigned int sampling_frequency_index = GetSamplingFrequencyIndex(audio_desc->GetSampleRate());
unsigned int channel_configuration = audio_desc->GetChannelCount();
AP4_DataBuffer data;
- if(AP4_SUCCEEDED(sample.ReadData(data)))
- {
+ if (AP4_SUCCEEDED(sample.ReadData(data))) {
unsigned char* buffer = new unsigned char[7+sample.GetSize()];
MakeAdtsHeader(buffer, sample.GetSize(), sampling_frequency_index, channel_configuration);
- AP4_CopyMemory(buffer + 7, data.GetData(), data.GetDataSize());
+ AP4_CopyMemory(buffer+7, data.GetData(), data.GetDataSize());
AP4_UI64 ts = AP4_ConvertTime(sample.GetDts(), m_TimeScale, 90000);
- WritePES(buffer, 7 + sample.GetSize(), ts, false, ts, with_pcr, output);
+ WritePES(buffer, 7+sample.GetSize(), ts, false, ts, with_pcr, output);
delete[] buffer;
}
-
+
return AP4_SUCCESS;
}
/*----------------------------------------------------------------------
| AP4_Mpeg2TsVideoSampleStream
+---------------------------------------------------------------------*/
-class AP4_Mpeg2TsVideoSampleStream : public AP4_Mpeg2TsWriter::SampleStream
+class AP4_Mpeg2TsVideoSampleStream : public AP4_Mpeg2TsWriter::SampleStream
{
public:
- static AP4_Result Create(AP4_UI16 pid,
- AP4_UI32 timescale,
+ static AP4_Result Create(AP4_UI16 pid,
+ AP4_UI32 timescale,
AP4_Mpeg2TsWriter::SampleStream*& stream);
- AP4_Result WriteSample(AP4_Sample& sample,
+ AP4_Result WriteSample(AP4_Sample& sample,
AP4_SampleDescription* sample_description,
- bool with_pcr,
+ bool with_pcr,
AP4_ByteStream& output);
-
+
private:
AP4_Mpeg2TsVideoSampleStream(AP4_UI16 pid, AP4_UI32 timescale) :
- AP4_Mpeg2TsWriter::SampleStream(pid,
- AP4_MPEG2_TS_DEFAULT_STREAM_ID_VIDEO,
+ AP4_Mpeg2TsWriter::SampleStream(pid,
+ AP4_MPEG2_TS_DEFAULT_STREAM_ID_VIDEO,
AP4_MPEG2_STREAM_TYPE_AVC,
timescale),
- m_SampleDescriptionIndex(-1),
- m_NaluLengthSize(0) {}
-
+ m_SampleDescriptionIndex(-1),
+ m_NaluLengthSize(0) {}
+
int m_SampleDescriptionIndex;
AP4_DataBuffer m_Prefix;
unsigned int m_NaluLengthSize;
@@ -467,12 +434,12 @@ private:
| AP4_Mpeg2TsVideoSampleStream::AP4_Mpeg2TsVideoSampleStream
+---------------------------------------------------------------------*/
AP4_Result
-AP4_Mpeg2TsVideoSampleStream::Create(AP4_UI16 pid,
- AP4_UI32 timescale,
+AP4_Mpeg2TsVideoSampleStream::Create(AP4_UI16 pid,
+ AP4_UI32 timescale,
AP4_Mpeg2TsWriter::SampleStream*& stream)
{
// create the stream object
- stream = new AP4_Mpeg2TsVideoSampleStream(pid, timescale);
+ stream = new AP4_Mpeg2TsVideoSampleStream(pid, timescale);
return AP4_SUCCESS;
}
@@ -480,40 +447,37 @@ AP4_Mpeg2TsVideoSampleStream::Create(AP4_UI16 pid,
| AP4_Mpeg2TsVideoSampleStream::WriteSample
+---------------------------------------------------------------------*/
AP4_Result
-AP4_Mpeg2TsVideoSampleStream::WriteSample(AP4_Sample& sample,
- AP4_SampleDescription* sample_description,
- bool with_pcr,
- AP4_ByteStream& output)
+AP4_Mpeg2TsVideoSampleStream::WriteSample(AP4_Sample& sample,
+ AP4_SampleDescription* sample_description,
+ bool with_pcr,
+ AP4_ByteStream& output)
{
// check the sample description
AP4_AvcSampleDescription* avc_desc = AP4_DYNAMIC_CAST(AP4_AvcSampleDescription, sample_description);
- if(avc_desc == NULL) return AP4_ERROR_NOT_SUPPORTED;
-
- if((int)sample.GetDescriptionIndex() != m_SampleDescriptionIndex)
- {
+ if (avc_desc == NULL) return AP4_ERROR_NOT_SUPPORTED;
+
+ if ((int)sample.GetDescriptionIndex() != m_SampleDescriptionIndex) {
m_SampleDescriptionIndex = sample.GetDescriptionIndex();
// make the SPS/PPS prefix
m_NaluLengthSize = avc_desc->GetNaluLengthSize();
m_Prefix.SetDataSize(0);
- for(unsigned int i = 0; i < avc_desc->GetSequenceParameters().ItemCount(); i++)
- {
+ for (unsigned int i=0; i<avc_desc->GetSequenceParameters().ItemCount(); i++) {
AP4_DataBuffer& buffer = avc_desc->GetSequenceParameters()[i];
unsigned int prefix_size = m_Prefix.GetDataSize();
- m_Prefix.SetDataSize(prefix_size + 4 + buffer.GetDataSize());
- unsigned char* p = m_Prefix.UseData() + prefix_size;
+ m_Prefix.SetDataSize(prefix_size+4+buffer.GetDataSize());
+ unsigned char* p = m_Prefix.UseData()+prefix_size;
*p++ = 0;
*p++ = 0;
*p++ = 0;
*p++ = 1;
AP4_CopyMemory(p, buffer.GetData(), buffer.GetDataSize());
}
- for(unsigned int i = 0; i < avc_desc->GetPictureParameters().ItemCount(); i++)
- {
+ for (unsigned int i=0; i<avc_desc->GetPictureParameters().ItemCount(); i++) {
AP4_DataBuffer& buffer = avc_desc->GetPictureParameters()[i];
unsigned int prefix_size = m_Prefix.GetDataSize();
- m_Prefix.SetDataSize(prefix_size + 4 + buffer.GetDataSize());
- unsigned char* p = m_Prefix.UseData() + prefix_size;
+ m_Prefix.SetDataSize(prefix_size+4+buffer.GetDataSize());
+ unsigned char* p = m_Prefix.UseData()+prefix_size;
*p++ = 0;
*p++ = 0;
*p++ = 0;
@@ -521,16 +485,16 @@ AP4_Mpeg2TsVideoSampleStream::WriteSample(AP4_Sample& sample,
AP4_CopyMemory(p, buffer.GetData(), buffer.GetDataSize());
}
}
-
+
// read the sample data
AP4_DataBuffer sample_data;
AP4_CHECK(sample.ReadData(sample_data));
-
+
// allocate a buffer for the PES packet
AP4_DataBuffer pes_data;
- pes_data.SetDataSize(6 + m_Prefix.GetDataSize());
+ pes_data.SetDataSize(6+m_Prefix.GetDataSize());
unsigned char* pes_buffer = pes_data.UseData();
-
+
// start of access unit
pes_buffer[0] = 0;
pes_buffer[1] = 0;
@@ -538,62 +502,54 @@ AP4_Mpeg2TsVideoSampleStream::WriteSample(AP4_Sample& sample,
pes_buffer[3] = 1;
pes_buffer[4] = 9; // NAL type = Access Unit Delimiter;
pes_buffer[5] = 0xE0; // Slice types = ANY
-
+
// copy the prefix
- AP4_CopyMemory(pes_buffer + 6, m_Prefix.GetData(), m_Prefix.GetDataSize());
-
+ AP4_CopyMemory(pes_buffer+6, m_Prefix.GetData(), m_Prefix.GetDataSize());
+
// write the NAL units
const unsigned char* data = sample_data.GetData();
unsigned int data_size = sample_data.GetDataSize();
-
- while(data_size)
- {
+
+ while (data_size) {
// sanity check
- if(data_size < m_NaluLengthSize) break;
-
+ if (data_size < m_NaluLengthSize) break;
+
// get the next NAL unit
AP4_UI32 nalu_size;
- if(m_NaluLengthSize == 1)
- {
+ if (m_NaluLengthSize == 1) {
nalu_size = *data++;
data_size--;
- }
- else if(m_NaluLengthSize == 2)
- {
+ } else if (m_NaluLengthSize == 2) {
nalu_size = AP4_BytesToInt16BE(data);
data += 2;
data_size -= 2;
- }
- else if(m_NaluLengthSize == 4)
- {
+ } else if (m_NaluLengthSize == 4) {
nalu_size = AP4_BytesToInt32BE(data);
data += 4;
data_size -= 4;
- }
- else
- {
+ } else {
break;
}
- if(nalu_size > data_size) break;
-
+ if (nalu_size > data_size) break;
+
// add a start code before the NAL unit
- unsigned int offset = pes_data.GetDataSize();
- pes_data.SetDataSize(offset + 3 + nalu_size);
- pes_buffer = pes_data.UseData() + offset;
+ unsigned int offset = pes_data.GetDataSize();
+ pes_data.SetDataSize(offset+3+nalu_size);
+ pes_buffer = pes_data.UseData()+offset;
pes_buffer[0] = 0;
pes_buffer[1] = 0;
pes_buffer[2] = 1;
- AP4_CopyMemory(pes_buffer + 3, data, nalu_size);
-
+ AP4_CopyMemory(pes_buffer+3, data, nalu_size);
+
// move to the next NAL unit
data += nalu_size;
data_size -= nalu_size;
- }
-
+ }
+
// compute the timestamp
AP4_UI64 dts = AP4_ConvertTime(sample.GetDts(), m_TimeScale, 90000);
AP4_UI64 pts = AP4_ConvertTime(sample.GetCts(), m_TimeScale, 90000);
-
+
// write the packet
return WritePES(pes_data.GetData(), pes_data.GetDataSize(), dts, true, pts, with_pcr, output);
}
@@ -629,9 +585,9 @@ AP4_Mpeg2TsWriter::WritePAT(AP4_ByteStream& output)
{
unsigned int payload_size = AP4_MPEG2TS_PACKET_PAYLOAD_SIZE;
m_PAT->WritePacketHeader(true, payload_size, false, 0, output);
-
+
AP4_BitWriter writer(1024);
-
+
writer.Write(0, 8); // pointer
writer.Write(0, 8); // table_id
writer.Write(1, 1); // section_syntax_indicator
@@ -647,12 +603,12 @@ AP4_Mpeg2TsWriter::WritePAT(AP4_ByteStream& output)
writer.Write(1, 16); // program number
writer.Write(7, 3); // reserved
writer.Write(m_PMT->GetPID(), 13); // program_map_PID
- writer.Write(ComputeCRC(writer.GetData() + 1, 17 - 1 - 4), 32);
-
+ writer.Write(ComputeCRC(writer.GetData()+1, 17-1-4), 32);
+
output.Write(writer.GetData(), 17);
-
- output.Write(StuffingBytes, AP4_MPEG2TS_PACKET_PAYLOAD_SIZE - 17);
-
+
+ output.Write(StuffingBytes, AP4_MPEG2TS_PACKET_PAYLOAD_SIZE-17);
+
return AP4_SUCCESS;
}
@@ -663,25 +619,22 @@ AP4_Result
AP4_Mpeg2TsWriter::WritePMT(AP4_ByteStream& output)
{
// check that we have at least one media stream
- if(m_Audio == NULL && m_Video == NULL)
- {
+ if (m_Audio == NULL && m_Video == NULL) {
return AP4_ERROR_INVALID_STATE;
}
-
+
unsigned int payload_size = AP4_MPEG2TS_PACKET_PAYLOAD_SIZE;
m_PMT->WritePacketHeader(true, payload_size, false, 0, output);
-
+
AP4_BitWriter writer(1024);
-
+
unsigned int section_length = 13;
unsigned int pcr_pid = 0;
- if(m_Audio)
- {
+ if (m_Audio) {
section_length += 5;
pcr_pid = m_Audio->GetPID();
- }
- if(m_Video)
- {
+ }
+ if (m_Video) {
section_length += 5;
pcr_pid = m_Video->GetPID();
}
@@ -702,46 +655,44 @@ AP4_Mpeg2TsWriter::WritePMT(AP4_ByteStream& output)
writer.Write(pcr_pid, 13); // PCD_PID
writer.Write(0xF, 4); // reserved
writer.Write(0, 12); // program_info_length
-
- if(m_Audio)
- {
- writer.Write(m_Audio->m_StreamType, 8); // stream_type
+
+ if (m_Audio) {
+ writer.Write(m_Audio->m_StreamType, 8); // stream_type
writer.Write(0x7, 3); // reserved
writer.Write(m_Audio->GetPID(), 13); // elementary_PID
writer.Write(0xF, 4); // reserved
writer.Write(0, 12); // ES_info_length
}
-
- if(m_Video)
- {
+
+ if (m_Video) {
writer.Write(m_Video->m_StreamType, 8); // stream_type
writer.Write(0x7, 3); // reserved
writer.Write(m_Video->GetPID(), 13); // elementary_PID
writer.Write(0xF, 4); // reserved
writer.Write(0, 12); // ES_info_length
}
-
- writer.Write(ComputeCRC(writer.GetData() + 1, section_length - 1), 32); // CRC
-
- output.Write(writer.GetData(), section_length + 4);
- output.Write(StuffingBytes, AP4_MPEG2TS_PACKET_PAYLOAD_SIZE - (section_length + 4));
-
+
+ writer.Write(ComputeCRC(writer.GetData()+1, section_length-1), 32); // CRC
+
+ output.Write(writer.GetData(), section_length+4);
+ output.Write(StuffingBytes, AP4_MPEG2TS_PACKET_PAYLOAD_SIZE-(section_length+4));
+
return AP4_SUCCESS;
}
/*----------------------------------------------------------------------
| AP4_Mpeg2TsWriter::SetAudioStream
+---------------------------------------------------------------------*/
-AP4_Result
+AP4_Result
AP4_Mpeg2TsWriter::SetAudioStream(AP4_UI32 timescale, SampleStream*& stream)
{
// default
stream = NULL;
-
+
AP4_Result result = AP4_Mpeg2TsAudioSampleStream::Create(AP4_MPEG2_TS_DEFAULT_PID_AUDIO,
- timescale,
- m_Audio);
- if(AP4_FAILED(result)) return result;
+ timescale,
+ m_Audio);
+ if (AP4_FAILED(result)) return result;
stream = m_Audio;
return AP4_SUCCESS;
}
@@ -749,16 +700,16 @@ AP4_Mpeg2TsWriter::SetAudioStream(AP4_UI32 timescale, SampleStream*& stream)
/*----------------------------------------------------------------------
| AP4_Mpeg2TsWriter::SetVideoStream
+---------------------------------------------------------------------*/
-AP4_Result
+AP4_Result
AP4_Mpeg2TsWriter::SetVideoStream(AP4_UI32 timescale, SampleStream*& stream)
{
// default
stream = NULL;
-
- AP4_Result result = AP4_Mpeg2TsVideoSampleStream::Create(AP4_MPEG2_TS_DEFAULT_PID_VIDEO,
- timescale,
- m_Video);
- if(AP4_FAILED(result)) return result;
+
+ AP4_Result result = AP4_Mpeg2TsVideoSampleStream::Create(AP4_MPEG2_TS_DEFAULT_PID_VIDEO,
+ timescale,
+ m_Video);
+ if (AP4_FAILED(result)) return result;
stream = m_Video;
return AP4_SUCCESS;
}
diff --git a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4Mpeg2Ts.h b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4Mpeg2Ts.h
index c0173aa78..0f898b952 100644
--- a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4Mpeg2Ts.h
+++ b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4Mpeg2Ts.h
@@ -57,7 +57,7 @@ const AP4_UI08 AP4_MPEG2_STREAM_TYPE_AVC = 0x1B;
| AP4_Mpeg2TsWriter
+---------------------------------------------------------------------*/
/**
- * This class is a simple implementation of a converter that can
+ * This class is a simple implementation of a converter that can
* convert MP4 audio and video access units into an MPEG2 transport
* stream.
* It currently only supports one audio tracks with MPEG4 AAC LC, and one
@@ -67,70 +67,59 @@ class AP4_Mpeg2TsWriter
{
public:
// classes
- class Stream
- {
+ class Stream {
public:
Stream(AP4_UI16 pid) : m_PID(pid), m_ContinuityCounter(0) {}
virtual ~Stream() {}
-
- AP4_UI16 GetPID()
- {
- return m_PID;
- }
- void WritePacketHeader(bool payload_start,
+
+ AP4_UI16 GetPID() { return m_PID; }
+ void WritePacketHeader(bool payload_start,
unsigned int& payload_size,
bool with_pcr,
AP4_UI64 pcr,
AP4_ByteStream& output);
-
+
private:
unsigned int m_PID;
unsigned int m_ContinuityCounter;
};
-
- class SampleStream : public Stream
- {
+
+ class SampleStream : public Stream {
public:
SampleStream(AP4_UI16 pid, AP4_UI16 stream_id, AP4_UI08 stream_type, AP4_UI32 timescale) :
- Stream(pid),
+ Stream(pid),
m_StreamId(stream_id),
m_StreamType(stream_type),
m_TimeScale(timescale) {}
-
- virtual AP4_Result WritePES(const unsigned char* data,
- unsigned int data_size,
- AP4_UI64 dts,
- bool with_dts,
- AP4_UI64 pts,
- bool with_pcr,
+
+ virtual AP4_Result WritePES(const unsigned char* data,
+ unsigned int data_size,
+ AP4_UI64 dts,
+ bool with_dts,
+ AP4_UI64 pts,
+ bool with_pcr,
AP4_ByteStream& output);
- virtual AP4_Result WriteSample(AP4_Sample& sample,
+ virtual AP4_Result WriteSample(AP4_Sample& sample,
AP4_SampleDescription* sample_description,
- bool with_pcr,
+ bool with_pcr,
AP4_ByteStream& output) = 0;
-
+
unsigned int m_StreamId;
AP4_UI08 m_StreamType;
AP4_UI32 m_TimeScale;
};
-
+
// constructor
AP4_Mpeg2TsWriter();
~AP4_Mpeg2TsWriter();
-
- Stream* GetPAT()
- {
- return m_PAT;
- }
- Stream* GetPMT()
- {
- return m_PMT;
- }
+
+ Stream* GetPAT() { return m_PAT; }
+ Stream* GetPMT() { return m_PMT; }
AP4_Result WritePAT(AP4_ByteStream& output);
AP4_Result WritePMT(AP4_ByteStream& output);
AP4_Result SetAudioStream(AP4_UI32 timescale, SampleStream*& stream);
AP4_Result SetVideoStream(AP4_UI32 timescale, SampleStream*& stream);
-
+
private:
Stream* m_PAT;
Stream* m_PMT;
diff --git a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4MvhdAtom.cpp b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4MvhdAtom.cpp
index 66fd9f82a..3a4e3059a 100644
--- a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4MvhdAtom.cpp
+++ b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4MvhdAtom.cpp
@@ -1,6 +1,6 @@
/*****************************************************************
|
-| AP4 - mvhd Atoms
+| AP4 - mvhd Atoms
|
| Copyright 2002-2008 Axiomatic Systems, LLC
|
@@ -46,8 +46,8 @@ AP4_MvhdAtom::Create(AP4_Size size, AP4_ByteStream& stream)
{
AP4_UI32 version;
AP4_UI32 flags;
- if(AP4_FAILED(AP4_Atom::ReadFullHeader(stream, version, flags))) return NULL;
- if(version > 1) return NULL;
+ if (AP4_FAILED(AP4_Atom::ReadFullHeader(stream, version, flags))) return NULL;
+ if (version > 1) return NULL;
return new AP4_MvhdAtom(size, version, flags, stream);
}
@@ -60,7 +60,7 @@ AP4_MvhdAtom::AP4_MvhdAtom(AP4_UI32 creation_time,
AP4_UI32 duration,
AP4_UI32 rate,
AP4_UI16 volume) :
- AP4_Atom(AP4_ATOM_TYPE_MVHD, AP4_FULL_ATOM_HEADER_SIZE + 96, 0, 0),
+ AP4_Atom(AP4_ATOM_TYPE_MVHD, AP4_FULL_ATOM_HEADER_SIZE+96, 0, 0),
m_CreationTime(creation_time),
m_ModificationTime(modification_time),
m_TimeScale(time_scale),
@@ -87,14 +87,13 @@ AP4_MvhdAtom::AP4_MvhdAtom(AP4_UI32 creation_time,
/*----------------------------------------------------------------------
| AP4_MvhdAtom::AP4_MvhdAtom
+---------------------------------------------------------------------*/
-AP4_MvhdAtom::AP4_MvhdAtom(AP4_UI32 size,
+AP4_MvhdAtom::AP4_MvhdAtom(AP4_UI32 size,
AP4_UI32 version,
AP4_UI32 flags,
AP4_ByteStream& stream) :
AP4_Atom(AP4_ATOM_TYPE_MVHD, size, version, flags)
{
- if(m_Version == 0)
- {
+ if (m_Version == 0) {
AP4_UI32 creation_time;
stream.ReadUI32(creation_time);
m_CreationTime = creation_time;
@@ -105,9 +104,7 @@ AP4_MvhdAtom::AP4_MvhdAtom(AP4_UI32 size,
AP4_UI32 duration;
stream.ReadUI32(duration);
m_Duration = duration;
- }
- else
- {
+ } else {
stream.ReadUI64(m_CreationTime);
stream.ReadUI64(m_ModificationTime);
stream.ReadUI32(m_TimeScale);
@@ -118,8 +115,7 @@ AP4_MvhdAtom::AP4_MvhdAtom(AP4_UI32 size,
stream.ReadUI16(m_Volume);
stream.Read(m_Reserved1, sizeof(m_Reserved1));
stream.Read(m_Reserved2, sizeof(m_Reserved2));
- for(int i = 0; i < 9; i++)
- {
+ for (int i=0; i<9; i++) {
stream.ReadUI32(m_Matrix[i]);
}
stream.Read(m_Predefined, sizeof(m_Predefined));
@@ -133,51 +129,47 @@ AP4_Result
AP4_MvhdAtom::WriteFields(AP4_ByteStream& stream)
{
AP4_Result result;
-
- if(m_Version == 0)
- {
+
+ if (m_Version == 0) {
result = stream.WriteUI32((AP4_UI32)m_CreationTime);
- if(AP4_FAILED(result)) return result;
+ if (AP4_FAILED(result)) return result;
result = stream.WriteUI32((AP4_UI32)m_ModificationTime);
- if(AP4_FAILED(result)) return result;
+ if (AP4_FAILED(result)) return result;
result = stream.WriteUI32(m_TimeScale);
- if(AP4_FAILED(result)) return result;
+ if (AP4_FAILED(result)) return result;
result = stream.WriteUI32((AP4_UI32)m_Duration);
- }
- else
- {
+ } else {
result = stream.WriteUI64(m_CreationTime);
- if(AP4_FAILED(result)) return result;
+ if (AP4_FAILED(result)) return result;
result = stream.WriteUI64(m_ModificationTime);
- if(AP4_FAILED(result)) return result;
+ if (AP4_FAILED(result)) return result;
result = stream.WriteUI32(m_TimeScale);
- if(AP4_FAILED(result)) return result;
+ if (AP4_FAILED(result)) return result;
result = stream.WriteUI64(m_Duration);
- if(AP4_FAILED(result)) return result;
+ if (AP4_FAILED(result)) return result;
}
// rate & volume
result = stream.WriteUI32(m_Rate);
- if(AP4_FAILED(result)) return result;
+ if (AP4_FAILED(result)) return result;
result = stream.WriteUI16(m_Volume);
- if(AP4_FAILED(result)) return result;
+ if (AP4_FAILED(result)) return result;
// reserved
result = stream.Write(m_Reserved1, sizeof(m_Reserved1));
- if(AP4_FAILED(result)) return result;
+ if (AP4_FAILED(result)) return result;
result = stream.Write(m_Reserved2, sizeof(m_Reserved2));
- if(AP4_FAILED(result)) return result;
+ if (AP4_FAILED(result)) return result;
// matrix
- for(int i = 0; i < 9; i++)
- {
+ for (int i=0; i<9; i++) {
result = stream.WriteUI32(m_Matrix[i]);
- if(AP4_FAILED(result)) return result;
+ if (AP4_FAILED(result)) return result;
}
// pre-defined
result = stream.Write(m_Predefined, sizeof(m_Predefined));
- if(AP4_FAILED(result)) return result;
+ if (AP4_FAILED(result)) return result;
// next track id
return stream.WriteUI32(m_NextTrackId);
@@ -189,12 +181,9 @@ AP4_MvhdAtom::WriteFields(AP4_ByteStream& stream)
AP4_UI32
AP4_MvhdAtom::GetDurationMs()
{
- if(m_TimeScale)
- {
+ if (m_TimeScale) {
return (AP4_UI32)AP4_ConvertTime(m_Duration, m_TimeScale, 1000);
- }
- else
- {
+ } else {
return 0;
}
}
diff --git a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4MvhdAtom.h b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4MvhdAtom.h
index 1c8bf6c83..b3d4de11d 100644
--- a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4MvhdAtom.h
+++ b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4MvhdAtom.h
@@ -1,6 +1,6 @@
/*****************************************************************
|
-| AP4 - mvhd Atoms
+| AP4 - mvhd Atoms
|
| Copyright 2002-2008 Axiomatic Systems, LLC
|
@@ -55,31 +55,21 @@ public:
AP4_UI16 volume);
virtual AP4_Result InspectFields(AP4_AtomInspector& inspector);
virtual AP4_Result WriteFields(AP4_ByteStream& stream);
- AP4_UI64 GetDuration()
- {
- return m_Duration;
- }
- void SetDuration(AP4_UI64 duration)
- {
- m_Duration = duration;
- }
+ AP4_UI64 GetDuration() { return m_Duration; }
+ void SetDuration(AP4_UI64 duration) { m_Duration = duration;}
AP4_UI32 GetDurationMs();
- AP4_UI32 GetTimeScale()
- {
- return m_TimeScale;
- }
- AP4_Result SetTimeScale(AP4_UI32 time_scale)
- {
+ AP4_UI32 GetTimeScale() { return m_TimeScale; }
+ AP4_Result SetTimeScale(AP4_UI32 time_scale) {
m_TimeScale = time_scale;
return AP4_SUCCESS;
}
private:
// methods
- AP4_MvhdAtom(AP4_UI32 size,
+ AP4_MvhdAtom(AP4_UI32 size,
AP4_UI32 version,
AP4_UI32 flags,
- AP4_ByteStream& stream);
+ AP4_ByteStream& stream);
// members
AP4_UI64 m_CreationTime;
diff --git a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4NmhdAtom.cpp b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4NmhdAtom.cpp
index aba085197..d6a660962 100644
--- a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4NmhdAtom.cpp
+++ b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4NmhdAtom.cpp
@@ -1,6 +1,6 @@
/*****************************************************************
|
-| AP4 - nmhd Atoms
+| AP4 - nmhd Atoms
|
| Copyright 2002-2008 Axiomatic Systems, LLC
|
@@ -41,8 +41,8 @@ AP4_NmhdAtom::Create(AP4_Size size, AP4_ByteStream& stream)
{
AP4_UI32 version;
AP4_UI32 flags;
- if(AP4_FAILED(AP4_Atom::ReadFullHeader(stream, version, flags))) return NULL;
- if(version != 0) return NULL;
+ if (AP4_FAILED(AP4_Atom::ReadFullHeader(stream, version, flags))) return NULL;
+ if (version != 0) return NULL;
return new AP4_NmhdAtom(size, version, flags, stream);
}
@@ -57,7 +57,7 @@ AP4_NmhdAtom::AP4_NmhdAtom() :
/*----------------------------------------------------------------------
| AP4_NmhdAtom::AP4_NmhdAtom
+---------------------------------------------------------------------*/
-AP4_NmhdAtom::AP4_NmhdAtom(AP4_UI32 size,
+AP4_NmhdAtom::AP4_NmhdAtom(AP4_UI32 size,
AP4_UI32 version,
AP4_UI32 flags,
AP4_ByteStream& /* stream */) :
diff --git a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4NmhdAtom.h b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4NmhdAtom.h
index f566db625..8c2efd336 100644
--- a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4NmhdAtom.h
+++ b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4NmhdAtom.h
@@ -1,6 +1,6 @@
/*****************************************************************
|
-| AP4 - nmhd Atoms
+| AP4 - nmhd Atoms
|
| Copyright 2002-2008 Axiomatic Systems, LLC
|
@@ -49,7 +49,7 @@ public:
private:
// methods
- AP4_NmhdAtom(AP4_UI32 size,
+ AP4_NmhdAtom(AP4_UI32 size,
AP4_UI32 version,
AP4_UI32 flags,
AP4_ByteStream& stream);
diff --git a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4ObjectDescriptor.cpp b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4ObjectDescriptor.cpp
index a3a73f023..1b74261d9 100644
--- a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4ObjectDescriptor.cpp
+++ b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4ObjectDescriptor.cpp
@@ -44,8 +44,8 @@ AP4_DEFINE_DYNAMIC_CAST_ANCHOR(AP4_DescriptorUpdateCommand)
| AP4_ObjectDescriptor::AP4_ObjectDescriptor
+---------------------------------------------------------------------*/
AP4_ObjectDescriptor::AP4_ObjectDescriptor(AP4_UI08 tag,
- AP4_Size header_size,
- AP4_Size payload_size) :
+ AP4_Size header_size,
+ AP4_Size payload_size) :
AP4_Descriptor(tag, header_size, payload_size),
m_UrlFlag(false)
{
@@ -55,7 +55,7 @@ AP4_ObjectDescriptor::AP4_ObjectDescriptor(AP4_UI08 tag,
| AP4_ObjectDescriptor::AP4_ObjectDescriptor
+---------------------------------------------------------------------*/
AP4_ObjectDescriptor::AP4_ObjectDescriptor(AP4_UI08 tag, AP4_UI16 id) :
- AP4_Descriptor(tag, 3, 2),
+ AP4_Descriptor(tag, 3, 2),
m_ObjectDescriptorId(id),
m_UrlFlag(false)
{
@@ -64,10 +64,10 @@ AP4_ObjectDescriptor::AP4_ObjectDescriptor(AP4_UI08 tag, AP4_UI16 id) :
/*----------------------------------------------------------------------
| AP4_ObjectDescriptor::AP4_ObjectDescriptor
+---------------------------------------------------------------------*/
-AP4_ObjectDescriptor::AP4_ObjectDescriptor(AP4_ByteStream& stream,
- AP4_UI08 tag,
- AP4_Size header_size,
- AP4_Size payload_size) :
+AP4_ObjectDescriptor::AP4_ObjectDescriptor(AP4_ByteStream& stream,
+ AP4_UI08 tag,
+ AP4_Size header_size,
+ AP4_Size payload_size) :
AP4_Descriptor(tag, header_size, payload_size)
{
AP4_Position start;
@@ -76,11 +76,10 @@ AP4_ObjectDescriptor::AP4_ObjectDescriptor(AP4_ByteStream& stream,
// read descriptor fields
unsigned short bits;
stream.ReadUI16(bits);
- m_ObjectDescriptorId = (bits >> 6);
- m_UrlFlag = ((bits & (1 << 5)) != 0);
-
- if(m_UrlFlag)
- {
+ m_ObjectDescriptorId = (bits>>6);
+ m_UrlFlag = ((bits&(1<<5))!=0);
+
+ if (m_UrlFlag) {
unsigned char url_length;
stream.ReadUI08(url_length);
char url[256];
@@ -92,13 +91,12 @@ AP4_ObjectDescriptor::AP4_ObjectDescriptor(AP4_ByteStream& stream,
// read other descriptors
AP4_Position offset;
stream.Tell(offset);
- AP4_SubStream* substream = new AP4_SubStream(stream, offset,
- payload_size - AP4_Size(offset - start));
+ AP4_SubStream* substream = new AP4_SubStream(stream, offset,
+ payload_size-AP4_Size(offset-start));
AP4_Descriptor* descriptor = NULL;
- while(AP4_DescriptorFactory::CreateDescriptorFromStream(*substream,
- descriptor)
- == AP4_SUCCESS)
- {
+ while (AP4_DescriptorFactory::CreateDescriptorFromStream(*substream,
+ descriptor)
+ == AP4_SUCCESS) {
m_SubDescriptors.Add(descriptor);
}
substream->Release();
@@ -115,13 +113,13 @@ AP4_ObjectDescriptor::~AP4_ObjectDescriptor()
/*----------------------------------------------------------------------
| AP4_ObjectDescriptor::FindSubDescriptor
+---------------------------------------------------------------------*/
-AP4_Descriptor*
+AP4_Descriptor*
AP4_ObjectDescriptor::FindSubDescriptor(AP4_UI08 tag) const
{
AP4_Descriptor* descriptor = NULL;
AP4_Result result = m_SubDescriptors.Find(AP4_DescriptorFinder(tag), descriptor);
- if(AP4_FAILED(result)) return NULL;
-
+ if (AP4_FAILED(result)) return NULL;
+
return descriptor;
}
@@ -134,17 +132,16 @@ AP4_ObjectDescriptor::WriteFields(AP4_ByteStream& stream)
AP4_Result result;
// id and flag
- unsigned short bits = (m_ObjectDescriptorId << 6) | (m_UrlFlag ? (1 << 5) : 0) | 0x1F;
+ unsigned short bits = (m_ObjectDescriptorId<<6)|(m_UrlFlag?(1<<5):0)|0x1F;
result = stream.WriteUI16(bits);
- if(AP4_FAILED(result)) return result;
+ if (AP4_FAILED(result)) return result;
// optional url
- if(m_UrlFlag)
- {
+ if (m_UrlFlag) {
stream.WriteUI08((AP4_UI08)m_Url.GetLength());
stream.Write(m_Url.GetChars(), m_Url.GetLength());
}
-
+
// write the sub descriptors
m_SubDescriptors.Apply(AP4_DescriptorListWriter(stream));
@@ -158,15 +155,14 @@ AP4_Result
AP4_ObjectDescriptor::Inspect(AP4_AtomInspector& inspector)
{
char info[64];
- AP4_FormatString(info, sizeof(info), "size=%ld+%ld",
- GetHeaderSize(), m_PayloadSize);
+ AP4_FormatString(info, sizeof(info), "size=%ld+%ld",
+ GetHeaderSize(),m_PayloadSize);
inspector.StartElement("[ObjectDescriptor]", info);
inspector.AddField("id", m_ObjectDescriptorId);
- if(m_UrlFlag)
- {
+ if (m_UrlFlag) {
inspector.AddField("url", m_Url.GetChars());
}
-
+
// inspect children
m_SubDescriptors.Apply(AP4_DescriptorListInspector(inspector));
@@ -187,8 +183,8 @@ AP4_ObjectDescriptor::AddSubDescriptor(AP4_Descriptor* descriptor)
// check that the header is still large enough to encode the payload
// length
unsigned int min_header_size = MinHeaderSize(m_PayloadSize);
- if(min_header_size > m_HeaderSize) m_HeaderSize = min_header_size;
-
+ if (min_header_size > m_HeaderSize) m_HeaderSize = min_header_size;
+
return AP4_SUCCESS;
}
@@ -218,10 +214,10 @@ AP4_InitialObjectDescriptor::AP4_InitialObjectDescriptor(
/*----------------------------------------------------------------------
| AP4_InitialObjectDescriptor::AP4_InitialObjectDescriptor
+---------------------------------------------------------------------*/
-AP4_InitialObjectDescriptor::AP4_InitialObjectDescriptor(AP4_ByteStream& stream,
- AP4_UI08 tag,
- AP4_Size header_size,
- AP4_Size payload_size) :
+AP4_InitialObjectDescriptor::AP4_InitialObjectDescriptor(AP4_ByteStream& stream,
+ AP4_UI08 tag,
+ AP4_Size header_size,
+ AP4_Size payload_size) :
AP4_ObjectDescriptor(tag, header_size, payload_size),
m_OdProfileLevelIndication(0),
m_SceneProfileLevelIndication(0),
@@ -235,38 +231,34 @@ AP4_InitialObjectDescriptor::AP4_InitialObjectDescriptor(AP4_ByteStream& stream,
// read descriptor fields
unsigned short bits;
stream.ReadUI16(bits);
- m_ObjectDescriptorId = (bits >> 6);
- m_UrlFlag = ((bits & (1 << 5)) != 0);
- m_IncludeInlineProfileLevelFlag = ((bits & (1 << 4)) != 0);
-
- if(m_UrlFlag)
- {
+ m_ObjectDescriptorId = (bits>>6);
+ m_UrlFlag = ((bits&(1<<5))!=0);
+ m_IncludeInlineProfileLevelFlag = ((bits&(1<<4))!=0);
+
+ if (m_UrlFlag) {
unsigned char url_length;
stream.ReadUI08(url_length);
char url[256];
stream.Read(url, url_length);
url[url_length] = '\0';
m_Url = url;
+ } else {
+ stream.ReadUI08(m_OdProfileLevelIndication);
+ stream.ReadUI08(m_SceneProfileLevelIndication);
+ stream.ReadUI08(m_AudioProfileLevelIndication);
+ stream.ReadUI08(m_VisualProfileLevelIndication);
+ stream.ReadUI08(m_GraphicsProfileLevelIndication);
}
- else
- {
- stream.ReadUI08(m_OdProfileLevelIndication);
- stream.ReadUI08(m_SceneProfileLevelIndication);
- stream.ReadUI08(m_AudioProfileLevelIndication);
- stream.ReadUI08(m_VisualProfileLevelIndication);
- stream.ReadUI08(m_GraphicsProfileLevelIndication);
- }
-
+
// read other descriptors
AP4_Position offset;
stream.Tell(offset);
- AP4_SubStream* substream = new AP4_SubStream(stream, offset,
- payload_size - AP4_Size(offset - start));
+ AP4_SubStream* substream = new AP4_SubStream(stream, offset,
+ payload_size-AP4_Size(offset-start));
AP4_Descriptor* descriptor = NULL;
- while(AP4_DescriptorFactory::CreateDescriptorFromStream(*substream,
- descriptor)
- == AP4_SUCCESS)
- {
+ while (AP4_DescriptorFactory::CreateDescriptorFromStream(*substream,
+ descriptor)
+ == AP4_SUCCESS) {
m_SubDescriptors.Add(descriptor);
}
substream->Release();
@@ -281,28 +273,25 @@ AP4_InitialObjectDescriptor::WriteFields(AP4_ByteStream& stream)
AP4_Result result;
// id and flags
- unsigned short bits = (m_ObjectDescriptorId << 6) |
- (m_UrlFlag ? (1 << 5) : 0) |
- (m_IncludeInlineProfileLevelFlag ? (1 << 4) : 0) |
+ unsigned short bits = (m_ObjectDescriptorId<<6) |
+ (m_UrlFlag?(1<<5):0) |
+ (m_IncludeInlineProfileLevelFlag?(1<<4):0)|
0xF;
result = stream.WriteUI16(bits);
- if(AP4_FAILED(result)) return result;
+ if (AP4_FAILED(result)) return result;
// optional url
- if(m_UrlFlag)
- {
+ if (m_UrlFlag) {
stream.WriteUI08((AP4_UI08)m_Url.GetLength());
stream.Write(m_Url.GetChars(), m_Url.GetLength());
+ } else {
+ stream.WriteUI08(m_OdProfileLevelIndication);
+ stream.WriteUI08(m_SceneProfileLevelIndication);
+ stream.WriteUI08(m_AudioProfileLevelIndication);
+ stream.WriteUI08(m_VisualProfileLevelIndication);
+ stream.WriteUI08(m_GraphicsProfileLevelIndication);
}
- else
- {
- stream.WriteUI08(m_OdProfileLevelIndication);
- stream.WriteUI08(m_SceneProfileLevelIndication);
- stream.WriteUI08(m_AudioProfileLevelIndication);
- stream.WriteUI08(m_VisualProfileLevelIndication);
- stream.WriteUI08(m_GraphicsProfileLevelIndication);
- }
-
+
// write the sub descriptors
m_SubDescriptors.Apply(AP4_DescriptorListWriter(stream));
@@ -316,26 +305,23 @@ AP4_Result
AP4_InitialObjectDescriptor::Inspect(AP4_AtomInspector& inspector)
{
char info[64];
- AP4_FormatString(info, sizeof(info), "size=%ld+%ld",
- GetHeaderSize(), m_PayloadSize);
+ AP4_FormatString(info, sizeof(info), "size=%ld+%ld",
+ GetHeaderSize(),m_PayloadSize);
inspector.StartElement("[InitialObjectDescriptor]", info);
inspector.AddField("id", m_ObjectDescriptorId);
- if(m_UrlFlag)
- {
+ if (m_UrlFlag) {
inspector.AddField("url", m_Url.GetChars());
- }
- else
- {
- inspector.AddField("include inline profile level flag",
- m_IncludeInlineProfileLevelFlag,
+ } else {
+ inspector.AddField("include inline profile level flag",
+ m_IncludeInlineProfileLevelFlag,
AP4_AtomInspector::HINT_BOOLEAN);
- inspector.AddField("OD profile level", m_OdProfileLevelIndication, AP4_AtomInspector::HINT_HEX);
- inspector.AddField("scene profile level", m_SceneProfileLevelIndication, AP4_AtomInspector::HINT_HEX);
- inspector.AddField("audio profile level", m_AudioProfileLevelIndication, AP4_AtomInspector::HINT_HEX);
- inspector.AddField("visual profile level", m_VisualProfileLevelIndication, AP4_AtomInspector::HINT_HEX);
- inspector.AddField("graphics profile level", m_GraphicsProfileLevelIndication, AP4_AtomInspector::HINT_HEX);
+ inspector.AddField("OD profile level", m_OdProfileLevelIndication, AP4_AtomInspector::HINT_HEX);
+ inspector.AddField("scene profile level", m_SceneProfileLevelIndication, AP4_AtomInspector::HINT_HEX);
+ inspector.AddField("audio profile level", m_AudioProfileLevelIndication, AP4_AtomInspector::HINT_HEX);
+ inspector.AddField("visual profile level", m_VisualProfileLevelIndication, AP4_AtomInspector::HINT_HEX);
+ inspector.AddField("graphics profile level", m_GraphicsProfileLevelIndication, AP4_AtomInspector::HINT_HEX);
}
-
+
// inspect children
m_SubDescriptors.Apply(AP4_DescriptorListInspector(inspector));
@@ -356,7 +342,7 @@ AP4_DescriptorUpdateCommand::AP4_DescriptorUpdateCommand(AP4_UI08 tag) :
| AP4_DescriptorUpdateCommand::AP4_DescriptorUpdateCommand
+---------------------------------------------------------------------*/
AP4_DescriptorUpdateCommand::AP4_DescriptorUpdateCommand(
- AP4_ByteStream& stream,
+ AP4_ByteStream& stream,
AP4_UI08 tag,
AP4_Size header_size,
AP4_Size payload_size) :
@@ -365,11 +351,10 @@ AP4_DescriptorUpdateCommand::AP4_DescriptorUpdateCommand(
// read the descriptors
AP4_Position offset;
stream.Tell(offset);
- AP4_SubStream* substream = new AP4_SubStream(stream, offset,
- payload_size);
+ AP4_SubStream* substream = new AP4_SubStream(stream, offset,
+ payload_size);
AP4_Descriptor* descriptor = NULL;
- while(AP4_DescriptorFactory::CreateDescriptorFromStream(*substream, descriptor) == AP4_SUCCESS)
- {
+ while (AP4_DescriptorFactory::CreateDescriptorFromStream(*substream, descriptor) == AP4_SUCCESS) {
m_Descriptors.Add(descriptor);
}
substream->Release();
@@ -402,23 +387,22 @@ AP4_Result
AP4_DescriptorUpdateCommand::Inspect(AP4_AtomInspector& inspector)
{
char info[64];
- AP4_FormatString(info, sizeof(info), "size=%ld+%ld",
- GetHeaderSize(), m_PayloadSize);
- switch(GetTag())
- {
- case AP4_COMMAND_TAG_OBJECT_DESCRIPTOR_UPDATE:
- inspector.StartElement("[ObjectDescriptorUpdate]", info);
- break;
-
- case AP4_COMMAND_TAG_IPMP_DESCRIPTOR_UPDATE:
- inspector.StartElement("[IPMP_DescriptorUpdate]", info);
- break;
-
- default:
- inspector.StartElement("[DescriptorUpdate]", info);
- break;
+ AP4_FormatString(info, sizeof(info), "size=%ld+%ld",
+ GetHeaderSize(),m_PayloadSize);
+ switch (GetTag()) {
+ case AP4_COMMAND_TAG_OBJECT_DESCRIPTOR_UPDATE:
+ inspector.StartElement("[ObjectDescriptorUpdate]", info);
+ break;
+
+ case AP4_COMMAND_TAG_IPMP_DESCRIPTOR_UPDATE:
+ inspector.StartElement("[IPMP_DescriptorUpdate]", info);
+ break;
+
+ default:
+ inspector.StartElement("[DescriptorUpdate]", info);
+ break;
}
-
+
// inspect children
m_Descriptors.Apply(AP4_DescriptorListInspector(inspector));
@@ -439,7 +423,7 @@ AP4_DescriptorUpdateCommand::AddDescriptor(AP4_Descriptor* descriptor)
// check that the header is still large enough to encode the payload
// length
unsigned int min_header_size = MinHeaderSize(m_PayloadSize);
- if(min_header_size > m_HeaderSize) m_HeaderSize = min_header_size;
+ if (min_header_size > m_HeaderSize) m_HeaderSize = min_header_size;
return AP4_SUCCESS;
}
diff --git a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4ObjectDescriptor.h b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4ObjectDescriptor.h
index f71d0b8e5..8b29c609c 100644
--- a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4ObjectDescriptor.h
+++ b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4ObjectDescriptor.h
@@ -1,6 +1,6 @@
/*****************************************************************
|
-| AP4 - Object Descriptor
+| AP4 - Object Descriptor
|
| Copyright 2002-2008 Axiomatic Systems, LLC
|
@@ -55,45 +55,36 @@ const AP4_UI08 AP4_DESCRIPTOR_TAG_MP4_IOD = 0x10;
+---------------------------------------------------------------------*/
class AP4_ObjectDescriptor : public AP4_Descriptor
{
-public:
+ public:
AP4_IMPLEMENT_DYNAMIC_CAST_D(AP4_ObjectDescriptor, AP4_Descriptor)
// methods
- AP4_ObjectDescriptor(AP4_ByteStream& stream,
+ AP4_ObjectDescriptor(AP4_ByteStream& stream,
AP4_UI08 tag,
- AP4_Size header_size,
+ AP4_Size header_size,
AP4_Size payload_size);
AP4_ObjectDescriptor(AP4_UI08 tag, AP4_UI16 id);
virtual ~AP4_ObjectDescriptor();
-
+
/**
- * Add a sub-descriptor.
+ * Add a sub-descriptor.
* Ownership of the sub-descriptor object is transfered.
- */
+ */
virtual AP4_Result AddSubDescriptor(AP4_Descriptor* descriptor);
-
+
virtual AP4_Descriptor* FindSubDescriptor(AP4_UI08 tag) const;
virtual AP4_Result WriteFields(AP4_ByteStream& stream);
virtual AP4_Result Inspect(AP4_AtomInspector& inspector);
// accessors
- AP4_UI16 GetObjectDescriptorId() const
- {
- return m_ObjectDescriptorId;
- }
- bool GetUrlFlag() const
- {
- return m_UrlFlag;
- }
- const AP4_String& GetUrl() const
- {
- return m_Url;
- }
+ AP4_UI16 GetObjectDescriptorId() const { return m_ObjectDescriptorId; }
+ bool GetUrlFlag() const { return m_UrlFlag; }
+ const AP4_String& GetUrl() const { return m_Url;}
-protected:
+ protected:
// constructor
AP4_ObjectDescriptor(AP4_UI08 tag, AP4_Size header_size, AP4_Size payload_size);
-
+
// members
AP4_UI16 m_ObjectDescriptorId;
bool m_UrlFlag;
@@ -106,11 +97,11 @@ protected:
+---------------------------------------------------------------------*/
class AP4_InitialObjectDescriptor : public AP4_ObjectDescriptor
{
-public:
+ public:
// methods
- AP4_InitialObjectDescriptor(AP4_ByteStream& stream,
+ AP4_InitialObjectDescriptor(AP4_ByteStream& stream,
AP4_UI08 tag,
- AP4_Size header_size,
+ AP4_Size header_size,
AP4_Size payload_size);
AP4_InitialObjectDescriptor(AP4_UI08 tag, // should be AP4_DESCRIPTOR_TAG_IOD or AP4_DESCRIPTOR_TAG_MP4_IOD
AP4_UI16 object_descriptor_id,
@@ -123,41 +114,23 @@ public:
virtual AP4_Result WriteFields(AP4_ByteStream& stream);
virtual AP4_Result Inspect(AP4_AtomInspector& inspector);
-
+
// accessors
- bool GetIncludeProfileLevelFlag() const
- {
- return m_IncludeInlineProfileLevelFlag;
- }
- AP4_UI08 GetOdProfileLevelIndication() const
- {
- return m_OdProfileLevelIndication;
- }
- AP4_UI08 GetSceneProfileLevelIndication() const
- {
- return m_SceneProfileLevelIndication;
- }
- AP4_UI08 GetAudioProfileLevelIndication() const
- {
- return m_AudioProfileLevelIndication;
- }
- AP4_UI08 GetVisualProfileLevelIndication() const
- {
- return m_VisualProfileLevelIndication;
- }
- AP4_UI08 GetGraphicsProfileLevelIndication() const
- {
- return m_GraphicsProfileLevelIndication;
- }
-
-private:
+ bool GetIncludeProfileLevelFlag() const { return m_IncludeInlineProfileLevelFlag; }
+ AP4_UI08 GetOdProfileLevelIndication() const { return m_OdProfileLevelIndication; }
+ AP4_UI08 GetSceneProfileLevelIndication() const { return m_SceneProfileLevelIndication; }
+ AP4_UI08 GetAudioProfileLevelIndication() const { return m_AudioProfileLevelIndication; }
+ AP4_UI08 GetVisualProfileLevelIndication() const { return m_VisualProfileLevelIndication; }
+ AP4_UI08 GetGraphicsProfileLevelIndication() const { return m_GraphicsProfileLevelIndication; }
+
+ private:
// members
bool m_IncludeInlineProfileLevelFlag;
- AP4_UI08 m_OdProfileLevelIndication;
- AP4_UI08 m_SceneProfileLevelIndication;
- AP4_UI08 m_AudioProfileLevelIndication;
- AP4_UI08 m_VisualProfileLevelIndication;
- AP4_UI08 m_GraphicsProfileLevelIndication;
+ AP4_UI08 m_OdProfileLevelIndication;
+ AP4_UI08 m_SceneProfileLevelIndication;
+ AP4_UI08 m_AudioProfileLevelIndication;
+ AP4_UI08 m_VisualProfileLevelIndication;
+ AP4_UI08 m_GraphicsProfileLevelIndication;
};
/*----------------------------------------------------------------------
@@ -169,14 +142,14 @@ private:
*/
class AP4_DescriptorUpdateCommand : public AP4_Command
{
-public:
+ public:
AP4_IMPLEMENT_DYNAMIC_CAST_D(AP4_DescriptorUpdateCommand, AP4_Command)
// methods
AP4_DescriptorUpdateCommand(AP4_UI08 tag);
- AP4_DescriptorUpdateCommand(AP4_ByteStream& stream,
+ AP4_DescriptorUpdateCommand(AP4_ByteStream& stream,
AP4_UI08 tag,
- AP4_Size header_size,
+ AP4_Size header_size,
AP4_Size payload_size);
virtual ~AP4_DescriptorUpdateCommand();
virtual AP4_Result AddDescriptor(AP4_Descriptor* descriptor);
@@ -184,12 +157,9 @@ public:
virtual AP4_Result Inspect(AP4_AtomInspector& inspector);
// accessors
- const AP4_List<AP4_Descriptor>& GetDescriptors()
- {
- return m_Descriptors;
- }
-
-protected:
+ const AP4_List<AP4_Descriptor>& GetDescriptors() { return m_Descriptors; }
+
+ protected:
// members
mutable AP4_List<AP4_Descriptor> m_Descriptors;
};
diff --git a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4OdafAtom.cpp b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4OdafAtom.cpp
index 8b4d8cea8..28805ecef 100644
--- a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4OdafAtom.cpp
+++ b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4OdafAtom.cpp
@@ -1,6 +1,6 @@
/*****************************************************************
|
-| AP4 - odaf Atoms
+| AP4 - odaf Atoms
|
| Copyright 2002-2008 Axiomatic Systems, LLC
|
@@ -45,8 +45,8 @@ AP4_OdafAtom::Create(AP4_Size size, AP4_ByteStream& stream)
{
AP4_UI32 version;
AP4_UI32 flags;
- if(AP4_FAILED(AP4_Atom::ReadFullHeader(stream, version, flags))) return NULL;
- if(version != 0) return NULL;
+ if (AP4_FAILED(AP4_Atom::ReadFullHeader(stream, version, flags))) return NULL;
+ if (version != 0) return NULL;
return new AP4_OdafAtom(size, version, flags, stream);
}
@@ -56,7 +56,7 @@ AP4_OdafAtom::Create(AP4_Size size, AP4_ByteStream& stream)
AP4_OdafAtom::AP4_OdafAtom(bool selective_encryption,
AP4_UI08 key_length_indicator,
AP4_UI08 iv_length) :
- AP4_Atom(AP4_ATOM_TYPE_ODAF, AP4_FULL_ATOM_HEADER_SIZE + 3, 0, 0),
+ AP4_Atom(AP4_ATOM_TYPE_ODAF, AP4_FULL_ATOM_HEADER_SIZE+3, 0, 0),
m_SelectiveEncryption(selective_encryption),
m_KeyIndicatorLength(key_length_indicator),
m_IvLength(iv_length)
@@ -66,7 +66,7 @@ AP4_OdafAtom::AP4_OdafAtom(bool selective_encryption,
/*----------------------------------------------------------------------
| AP4_OdafAtom::AP4_OdafAtom
+---------------------------------------------------------------------*/
-AP4_OdafAtom::AP4_OdafAtom(AP4_UI32 size,
+AP4_OdafAtom::AP4_OdafAtom(AP4_UI32 size,
AP4_UI32 version,
AP4_UI32 flags,
AP4_ByteStream& stream) :
@@ -74,7 +74,7 @@ AP4_OdafAtom::AP4_OdafAtom(AP4_UI32 size,
{
AP4_UI08 s;
stream.ReadUI08(s);
- m_SelectiveEncryption = ((s & 0x80) != 0);
+ m_SelectiveEncryption = ((s&0x80) != 0);
stream.ReadUI08(m_KeyIndicatorLength);
stream.ReadUI08(m_IvLength);
}
@@ -89,15 +89,15 @@ AP4_OdafAtom::WriteFields(AP4_ByteStream& stream)
// selective encryption
result = stream.WriteUI08(m_SelectiveEncryption ? 0x80 : 0);
- if(AP4_FAILED(result)) return result;
+ if (AP4_FAILED(result)) return result;
// key indicator length
result = stream.WriteUI08(m_KeyIndicatorLength);
- if(AP4_FAILED(result)) return result;
+ if (AP4_FAILED(result)) return result;
// IV length
result = stream.WriteUI08(m_IvLength);
- if(AP4_FAILED(result)) return result;
+ if (AP4_FAILED(result)) return result;
return AP4_SUCCESS;
}
diff --git a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4OdafAtom.h b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4OdafAtom.h
index 669ab6efe..22ba860ee 100644
--- a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4OdafAtom.h
+++ b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4OdafAtom.h
@@ -54,22 +54,13 @@ public:
virtual AP4_Result WriteFields(AP4_ByteStream& stream);
// accessors
- bool GetSelectiveEncryption()
- {
- return m_SelectiveEncryption;
- }
- AP4_UI08 GetKeyIndicatorLength()
- {
- return m_KeyIndicatorLength;
- }
- AP4_UI08 GetIvLength()
- {
- return m_IvLength;
- }
+ bool GetSelectiveEncryption() { return m_SelectiveEncryption; }
+ AP4_UI08 GetKeyIndicatorLength() { return m_KeyIndicatorLength; }
+ AP4_UI08 GetIvLength() { return m_IvLength; }
private:
// methods
- AP4_OdafAtom(AP4_UI32 size,
+ AP4_OdafAtom(AP4_UI32 size,
AP4_UI32 version,
AP4_UI32 flags,
AP4_ByteStream& stream);
diff --git a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4OddaAtom.cpp b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4OddaAtom.cpp
index 57c50c464..d7a08796a 100644
--- a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4OddaAtom.cpp
+++ b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4OddaAtom.cpp
@@ -1,6 +1,6 @@
/*****************************************************************
|
-| AP4 - odda Atoms
+| AP4 - odda Atoms
|
| Copyright 2002-2008 Axiomatic Systems, LLC
|
@@ -41,20 +41,20 @@ AP4_DEFINE_DYNAMIC_CAST_ANCHOR(AP4_OddaAtom)
| AP4_OddaAtom::Create
+---------------------------------------------------------------------*/
AP4_OddaAtom*
-AP4_OddaAtom::Create(AP4_UI64 size,
+AP4_OddaAtom::Create(AP4_UI64 size,
AP4_ByteStream& stream)
{
AP4_UI32 version;
AP4_UI32 flags;
- if(AP4_FAILED(AP4_Atom::ReadFullHeader(stream, version, flags))) return NULL;
- if(version != 0) return NULL;
+ if (AP4_FAILED(AP4_Atom::ReadFullHeader(stream, version, flags))) return NULL;
+ if (version != 0) return NULL;
return new AP4_OddaAtom(size, version, flags, stream);
}
/*----------------------------------------------------------------------
| AP4_OddaAtom::AP4_OddaAtom
+---------------------------------------------------------------------*/
-AP4_OddaAtom::AP4_OddaAtom(AP4_UI64 size,
+AP4_OddaAtom::AP4_OddaAtom(AP4_UI64 size,
AP4_UI32 version,
AP4_UI32 flags,
AP4_ByteStream& stream) :
@@ -64,14 +64,14 @@ AP4_OddaAtom::AP4_OddaAtom(AP4_UI64 size,
stream.ReadUI64(m_EncryptedDataLength);
// get the source stream position
- AP4_Position position;
+ AP4_Position position;
stream.Tell(position);
// create a substream to represent the payload
m_EncryptedPayload = new AP4_SubStream(stream, position, m_EncryptedDataLength);
-
+
// seek to the end
- stream.Seek(position + m_EncryptedDataLength);
+ stream.Seek(position+m_EncryptedDataLength);
}
/*----------------------------------------------------------------------
@@ -82,10 +82,10 @@ AP4_OddaAtom::AP4_OddaAtom(AP4_ByteStream& encrypted_payload) :
{
// encrypted data length
encrypted_payload.GetSize(m_EncryptedDataLength);
-
- // update our size
- SetSize(AP4_FULL_ATOM_HEADER_SIZE_64 + 8 + m_EncryptedDataLength, true);
-
+
+ // update our size
+ SetSize(AP4_FULL_ATOM_HEADER_SIZE_64+8+m_EncryptedDataLength, true);
+
// keep a reference to the encrypted payload
m_EncryptedPayload = &encrypted_payload;
m_EncryptedPayload->AddReference();
@@ -96,7 +96,7 @@ AP4_OddaAtom::AP4_OddaAtom(AP4_ByteStream& encrypted_payload) :
+---------------------------------------------------------------------*/
AP4_OddaAtom::~AP4_OddaAtom()
{
- if(m_EncryptedPayload) m_EncryptedPayload->Release();
+ if (m_EncryptedPayload) m_EncryptedPayload->Release();
}
@@ -107,18 +107,17 @@ AP4_Result
AP4_OddaAtom::SetEncryptedPayload(AP4_ByteStream& stream, AP4_LargeSize length)
{
// keep a reference to the stream
- if(m_EncryptedPayload)
- {
+ if (m_EncryptedPayload) {
m_EncryptedPayload->Release();
}
m_EncryptedPayload = &stream;
m_EncryptedPayload->AddReference();
-
+
// update the size
m_EncryptedDataLength = length;
SetSize(AP4_FULL_ATOM_HEADER_SIZE_64 + 8 + length, true);
- if(m_Parent) m_Parent->OnChildChanged(this);
-
+ if (m_Parent) m_Parent->OnChildChanged(this);
+
return AP4_SUCCESS;
}
@@ -131,8 +130,8 @@ AP4_OddaAtom::SetEncryptedPayload(AP4_ByteStream& stream)
// the new encrypted data length is the size of the stream
AP4_LargeSize length;
AP4_Result result = stream.GetSize(length);
- if(AP4_FAILED(result)) return result;
-
+ if (AP4_FAILED(result)) return result;
+
return SetEncryptedPayload(stream, length);
}
@@ -147,8 +146,7 @@ AP4_OddaAtom::WriteFields(AP4_ByteStream& stream)
// check that we have a source stream
// and a normal size
- if(m_EncryptedPayload == NULL || GetSize() < 8)
- {
+ if (m_EncryptedPayload == NULL || GetSize() < 8) {
return AP4_FAILURE;
}
diff --git a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4OddaAtom.h b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4OddaAtom.h
index 9acde6c14..58a402ce5 100644
--- a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4OddaAtom.h
+++ b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4OddaAtom.h
@@ -45,24 +45,21 @@ public:
AP4_IMPLEMENT_DYNAMIC_CAST_D(AP4_OddaAtom, AP4_Atom)
// class methods
- static AP4_OddaAtom* Create(AP4_UI64 size,
+ static AP4_OddaAtom* Create(AP4_UI64 size,
AP4_ByteStream& stream);
// constructor
AP4_OddaAtom(AP4_ByteStream& encrypted_payload);
-
+
// destructor
~AP4_OddaAtom();
// methods
virtual AP4_Result InspectFields(AP4_AtomInspector& inspector);
virtual AP4_Result WriteFields(AP4_ByteStream& stream);
-
+
// accessors
- AP4_UI64 GetEncryptedDataLength()
- {
- return m_EncryptedDataLength;
- }
+ AP4_UI64 GetEncryptedDataLength() { return m_EncryptedDataLength; }
/**
* Sets the encrypted payload stream (and releases any existing stream references)
@@ -73,14 +70,11 @@ public:
/**
* Returns a reference to the encrypted payload stream (does not increment the reference counter)
*/
- AP4_ByteStream& GetEncryptedPayload()
- {
- return *m_EncryptedPayload;
- }
+ AP4_ByteStream& GetEncryptedPayload() { return *m_EncryptedPayload; }
private:
// methods
- AP4_OddaAtom(AP4_UI64 size,
+ AP4_OddaAtom(AP4_UI64 size,
AP4_UI32 version,
AP4_UI32 flags,
AP4_ByteStream& stream);
diff --git a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4OdheAtom.cpp b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4OdheAtom.cpp
index 69c70ac2f..f4e2bf5c8 100644
--- a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4OdheAtom.cpp
+++ b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4OdheAtom.cpp
@@ -1,6 +1,6 @@
/*****************************************************************
|
-| AP4 - odhe Atoms
+| AP4 - odhe Atoms
|
| Copyright 2002-2008 Axiomatic Systems, LLC
|
@@ -42,21 +42,21 @@ AP4_DEFINE_DYNAMIC_CAST_ANCHOR(AP4_OdheAtom)
| AP4_OdheAtom::Create
+---------------------------------------------------------------------*/
AP4_OdheAtom*
-AP4_OdheAtom::Create(AP4_Size size,
+AP4_OdheAtom::Create(AP4_Size size,
AP4_ByteStream& stream,
AP4_AtomFactory& atom_factory)
{
AP4_UI32 version;
AP4_UI32 flags;
- if(AP4_FAILED(AP4_Atom::ReadFullHeader(stream, version, flags))) return NULL;
- if(version != 0) return NULL;
+ if (AP4_FAILED(AP4_Atom::ReadFullHeader(stream, version, flags))) return NULL;
+ if (version != 0) return NULL;
return new AP4_OdheAtom(size, version, flags, stream, atom_factory);
}
/*----------------------------------------------------------------------
| AP4_OdheAtom::AP4_OdheAtom
+---------------------------------------------------------------------*/
-AP4_OdheAtom::AP4_OdheAtom(AP4_UI32 size,
+AP4_OdheAtom::AP4_OdheAtom(AP4_UI32 size,
AP4_UI32 version,
AP4_UI32 flags,
AP4_ByteStream& stream,
@@ -71,7 +71,7 @@ AP4_OdheAtom::AP4_OdheAtom(AP4_UI32 size,
m_ContentType.Assign(content_type, content_type_length);
// read the children
- AP4_Size bytes_available = size - (AP4_FULL_ATOM_HEADER_SIZE + 1 + content_type_length);
+ AP4_Size bytes_available = size-(AP4_FULL_ATOM_HEADER_SIZE+1+content_type_length);
ReadChildren(atom_factory, stream, bytes_available);
}
@@ -83,7 +83,7 @@ AP4_OdheAtom::AP4_OdheAtom(const char* content_type,
AP4_ContainerAtom(AP4_ATOM_TYPE_ODHE, (AP4_UI32)0, (AP4_UI32)0),
m_ContentType(content_type)
{
- m_Size32 += 1 + m_ContentType.GetLength();
+ m_Size32 += 1+m_ContentType.GetLength();
AddChild(ohdr);
}
@@ -95,8 +95,7 @@ AP4_OdheAtom::WriteFields(AP4_ByteStream& stream)
{
// write the content type
AP4_CHECK(stream.WriteUI08((AP4_UI08)m_ContentType.GetLength()));
- if(m_ContentType.GetLength())
- {
+ if (m_ContentType.GetLength()) {
AP4_CHECK(stream.Write(m_ContentType.GetChars(), m_ContentType.GetLength()));
}
@@ -121,11 +120,11 @@ void
AP4_OdheAtom::OnChildChanged(AP4_Atom*)
{
// remcompute our size
- AP4_UI64 size = GetHeaderSize() + 1 + m_ContentType.GetLength();
+ AP4_UI64 size = GetHeaderSize()+1+m_ContentType.GetLength();
m_Children.Apply(AP4_AtomSizeAdder(size));
SetSize(size);
// update our parent
- if(m_Parent) m_Parent->OnChildChanged(this);
+ if (m_Parent) m_Parent->OnChildChanged(this);
}
diff --git a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4OdheAtom.h b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4OdheAtom.h
index a3e944805..44477ae13 100644
--- a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4OdheAtom.h
+++ b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4OdheAtom.h
@@ -51,8 +51,8 @@ public:
AP4_IMPLEMENT_DYNAMIC_CAST_D(AP4_OdheAtom, AP4_ContainerAtom)
// class methods
- static AP4_OdheAtom* Create(AP4_Size size,
- AP4_ByteStream& stream,
+ static AP4_OdheAtom* Create(AP4_Size size,
+ AP4_ByteStream& stream,
AP4_AtomFactory& atom_factory);
// constructor
@@ -60,23 +60,20 @@ public:
* @param: ohdr ohdr atom passed with transfer of ownership semantics
*/
AP4_OdheAtom(const char* content_type, AP4_OhdrAtom* ohdr);
-
+
// AP4_Atom methods
virtual AP4_Result InspectFields(AP4_AtomInspector& inspector);
virtual AP4_Result WriteFields(AP4_ByteStream& stream);
-
+
// AP4_AtomParent methods
virtual void OnChildChanged(AP4_Atom* child);
-
+
// methods
- const AP4_String& GetContentType()
- {
- return m_ContentType;
- }
-
+ const AP4_String& GetContentType() { return m_ContentType; }
+
private:
// methods
- AP4_OdheAtom(AP4_UI32 size,
+ AP4_OdheAtom(AP4_UI32 size,
AP4_UI32 version,
AP4_UI32 flags,
AP4_ByteStream& stream,
diff --git a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4OhdrAtom.cpp b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4OhdrAtom.cpp
index eea8b08c5..f74e0d8f5 100644
--- a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4OhdrAtom.cpp
+++ b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4OhdrAtom.cpp
@@ -1,6 +1,6 @@
/*****************************************************************
|
-| AP4 - ohdr Atoms
+| AP4 - ohdr Atoms
|
| Copyright 2002-2008 Axiomatic Systems, LLC
|
@@ -41,21 +41,21 @@ AP4_DEFINE_DYNAMIC_CAST_ANCHOR(AP4_OhdrAtom)
| AP4_OhdrAtom::Create
+---------------------------------------------------------------------*/
AP4_OhdrAtom*
-AP4_OhdrAtom::Create(AP4_Size size,
+AP4_OhdrAtom::Create(AP4_Size size,
AP4_ByteStream& stream,
AP4_AtomFactory& atom_factory)
{
AP4_UI32 version;
AP4_UI32 flags;
- if(AP4_FAILED(AP4_Atom::ReadFullHeader(stream, version, flags))) return NULL;
- if(version != 0) return NULL;
+ if (AP4_FAILED(AP4_Atom::ReadFullHeader(stream, version, flags))) return NULL;
+ if (version != 0) return NULL;
return new AP4_OhdrAtom(size, version, flags, stream, atom_factory);
}
/*----------------------------------------------------------------------
| AP4_OhdrAtom::AP4_OhdrAtom
+---------------------------------------------------------------------*/
-AP4_OhdrAtom::AP4_OhdrAtom(AP4_UI08 encryption_method,
+AP4_OhdrAtom::AP4_OhdrAtom(AP4_UI08 encryption_method,
AP4_UI08 padding_scheme,
AP4_UI64 plaintext_length,
const char* content_id,
@@ -70,13 +70,13 @@ AP4_OhdrAtom::AP4_OhdrAtom(AP4_UI08 encryption_method,
m_RightsIssuerUrl(rights_issuer_url),
m_TextualHeaders(textual_headers, textual_headers_size)
{
- m_Size32 += 1 + 1 + 8 + 2 + 2 + 2 + m_ContentId.GetLength() + m_RightsIssuerUrl.GetLength() + textual_headers_size;
+ m_Size32 += 1+1+8+2+2+2+m_ContentId.GetLength()+m_RightsIssuerUrl.GetLength()+textual_headers_size;
}
/*----------------------------------------------------------------------
| AP4_OhdrAtom::AP4_OhdrAtom
+---------------------------------------------------------------------*/
-AP4_OhdrAtom::AP4_OhdrAtom(AP4_UI32 size,
+AP4_OhdrAtom::AP4_OhdrAtom(AP4_UI32 size,
AP4_UI32 version,
AP4_UI32 flags,
AP4_ByteStream& stream,
@@ -85,7 +85,7 @@ AP4_OhdrAtom::AP4_OhdrAtom(AP4_UI32 size,
{
// encryption method
stream.ReadUI08(m_EncryptionMethod);
-
+
// padding scheme
stream.ReadUI08(m_PaddingScheme);
@@ -119,10 +119,9 @@ AP4_OhdrAtom::AP4_OhdrAtom(AP4_UI32 size,
delete[] buffer;
// read the children
- AP4_Size bytes_used = AP4_FULL_ATOM_HEADER_SIZE + 1 + 1 + 8 + 2 + 2 + 2 + content_id_length + rights_issuer_url_length + textual_headers_length;
- if(bytes_used <= size)
- {
- ReadChildren(atom_factory, stream, size - bytes_used);
+ AP4_Size bytes_used = AP4_FULL_ATOM_HEADER_SIZE+1+1+8+2+2+2+content_id_length+rights_issuer_url_length+textual_headers_length;
+ if (bytes_used <= size) {
+ ReadChildren(atom_factory, stream, size-bytes_used);
}
}
@@ -154,24 +153,21 @@ AP4_OhdrAtom::InspectFields(AP4_AtomInspector& inspector)
{
inspector.AddField("encryption_method", m_EncryptionMethod);
inspector.AddField("padding_scheme", m_PaddingScheme);
- inspector.AddField("plaintext_length", (AP4_UI32)m_PlaintextLength);
+ inspector.AddField("plaintext_length", (AP4_UI32)m_PlaintextLength);
inspector.AddField("content_id", m_ContentId.GetChars());
inspector.AddField("rights_issuer_url", m_RightsIssuerUrl.GetChars());
{
- AP4_DataBuffer output_buffer;
+ AP4_DataBuffer output_buffer;
AP4_Result result;
- result = output_buffer.Reserve(1 + m_TextualHeaders.GetDataSize());
- if(AP4_FAILED(result))
- {
- inspector.AddField("textual_headers",
- m_TextualHeaders.UseData(),
- m_TextualHeaders.GetDataSize(),
- AP4_AtomInspector::HINT_HEX);
- }
- else
- {
+ result = output_buffer.Reserve(1+m_TextualHeaders.GetDataSize());
+ if (AP4_FAILED(result)) {
+ inspector.AddField("textual_headers",
+ m_TextualHeaders.UseData(),
+ m_TextualHeaders.GetDataSize(),
+ AP4_AtomInspector::HINT_HEX);
+ } else {
AP4_Size data_len = m_TextualHeaders.GetDataSize();
AP4_Byte* textual_headers_string;
AP4_Byte* curr;
@@ -179,16 +175,14 @@ AP4_OhdrAtom::InspectFields(AP4_AtomInspector& inspector)
output_buffer.SetData((const AP4_Byte*)m_TextualHeaders.GetData(), m_TextualHeaders.GetDataSize());
curr = textual_headers_string = output_buffer.UseData();
textual_headers_string[m_TextualHeaders.GetDataSize()] = '\0';
- while(curr < textual_headers_string + data_len)
- {
- if('\0' == *curr)
- {
+ while(curr < textual_headers_string+data_len) {
+ if ('\0' == *curr) {
*curr = '\n';
}
curr++;
}
inspector.AddField("textual_headers", (const char*) textual_headers_string);
- }
+ }
}
return InspectChildren(inspector);
@@ -197,7 +191,7 @@ AP4_OhdrAtom::InspectFields(AP4_AtomInspector& inspector)
/*----------------------------------------------------------------------
| AP4_OhdrAtom::Clone
+---------------------------------------------------------------------*/
-AP4_Atom*
+AP4_Atom*
AP4_OhdrAtom::Clone()
{
AP4_OhdrAtom* clone;
@@ -210,10 +204,9 @@ AP4_OhdrAtom::Clone()
m_TextualHeaders.GetDataSize());
AP4_List<AP4_Atom>::Item* child_item = m_Children.FirstItem();
- while(child_item)
- {
+ while (child_item) {
AP4_Atom* child_clone = child_item->GetData()->Clone();
- if(child_clone) clone->AddChild(child_clone);
+ if (child_clone) clone->AddChild(child_clone);
child_item = child_item->GetNext();
}
diff --git a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4OhdrAtom.h b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4OhdrAtom.h
index a06905216..afee7f5fb 100644
--- a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4OhdrAtom.h
+++ b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4OhdrAtom.h
@@ -56,12 +56,12 @@ public:
AP4_IMPLEMENT_DYNAMIC_CAST_D(AP4_OhdrAtom, AP4_ContainerAtom)
// class methods
- static AP4_OhdrAtom* Create(AP4_Size size,
- AP4_ByteStream& stream,
+ static AP4_OhdrAtom* Create(AP4_Size size,
+ AP4_ByteStream& stream,
AP4_AtomFactory& atom_factory);
// constructor
- AP4_OhdrAtom(AP4_UI08 encryption_method,
+ AP4_OhdrAtom(AP4_UI08 encryption_method,
AP4_UI08 padding_scheme,
AP4_UI64 plaintext_length,
const char* content_id,
@@ -75,49 +75,25 @@ public:
virtual AP4_Atom* Clone();
// accessors
- AP4_UI08 GetEncryptionMethod() const
- {
- return m_EncryptionMethod;
- }
- void SetEncryptionMethod(AP4_UI08 encryption_method)
- {
- m_EncryptionMethod = encryption_method;
- }
- AP4_UI08 GetPaddingScheme() const
- {
- return m_PaddingScheme;
- }
- void SetPaddingScheme(AP4_UI08 padding_scheme)
- {
- m_PaddingScheme = padding_scheme;
- }
- AP4_UI64 GetPlaintextLength() const
- {
- return m_PlaintextLength;
- }
- const AP4_String& GetContentId() const
- {
- return m_ContentId;
- }
- const AP4_String& GetRightsIssuerUrl() const
- {
- return m_RightsIssuerUrl;
- }
- const AP4_DataBuffer& GetTextualHeaders() const
- {
- return m_TextualHeaders;
- }
+ AP4_UI08 GetEncryptionMethod() const { return m_EncryptionMethod; }
+ void SetEncryptionMethod(AP4_UI08 encryption_method) { m_EncryptionMethod = encryption_method; }
+ AP4_UI08 GetPaddingScheme() const { return m_PaddingScheme; }
+ void SetPaddingScheme(AP4_UI08 padding_scheme) { m_PaddingScheme = padding_scheme; }
+ AP4_UI64 GetPlaintextLength() const { return m_PlaintextLength; }
+ const AP4_String& GetContentId() const { return m_ContentId; }
+ const AP4_String& GetRightsIssuerUrl() const { return m_RightsIssuerUrl; }
+ const AP4_DataBuffer& GetTextualHeaders() const { return m_TextualHeaders; }
private:
// methods
- AP4_OhdrAtom(AP4_UI32 size,
+ AP4_OhdrAtom(AP4_UI32 size,
AP4_UI32 version,
AP4_UI32 flags,
AP4_ByteStream& stream,
AP4_AtomFactory& atom_factory);
// members
- AP4_UI08 m_EncryptionMethod;
+ AP4_UI08 m_EncryptionMethod;
AP4_UI08 m_PaddingScheme;
AP4_UI64 m_PlaintextLength;
AP4_String m_ContentId;
diff --git a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4OmaDcf.cpp b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4OmaDcf.cpp
index bfd3a32c8..a224ab14d 100644
--- a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4OmaDcf.cpp
+++ b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4OmaDcf.cpp
@@ -53,48 +53,45 @@
| AP4_OmaDcfAtomDecrypter::DecryptAtoms
+---------------------------------------------------------------------*/
AP4_Result
-AP4_OmaDcfAtomDecrypter::DecryptAtoms(AP4_AtomParent& atoms,
+AP4_OmaDcfAtomDecrypter::DecryptAtoms(AP4_AtomParent& atoms,
AP4_Processor::ProgressListener* /*listener*/,
AP4_BlockCipherFactory* block_cipher_factory,
AP4_ProtectionKeyMap& key_map)
{
unsigned int index = 1;
- for(AP4_List<AP4_Atom>::Item* item = atoms.GetChildren().FirstItem();
- item;
- item = item->GetNext())
- {
+ for (AP4_List<AP4_Atom>::Item* item = atoms.GetChildren().FirstItem();
+ item;
+ item = item->GetNext()) {
AP4_Atom* atom = item->GetData();
- if(atom->GetType() != AP4_ATOM_TYPE_ODRM) continue;
+ if (atom->GetType() != AP4_ATOM_TYPE_ODRM) continue;
// check that we have the key
const AP4_UI08* key = key_map.GetKey(index++);
- if(key == NULL) return AP4_ERROR_INVALID_PARAMETERS;
-
+ if (key == NULL) return AP4_ERROR_INVALID_PARAMETERS;
+
// check that we have all the atoms we need
AP4_ContainerAtom* odrm = AP4_DYNAMIC_CAST(AP4_ContainerAtom, atom);
- if(odrm == NULL) continue; // not enough info
+ if (odrm == NULL) continue; // not enough info
AP4_OdheAtom* odhe = AP4_DYNAMIC_CAST(AP4_OdheAtom, odrm->GetChild(AP4_ATOM_TYPE_ODHE));
- if(odhe == NULL) continue; // not enough info
+ if (odhe == NULL) continue; // not enough info
AP4_OddaAtom* odda = AP4_DYNAMIC_CAST(AP4_OddaAtom, odrm->GetChild(AP4_ATOM_TYPE_ODDA));
- if(odda == NULL) continue; // not enough info
+ if (odda == NULL) continue; // not enough info
AP4_OhdrAtom* ohdr = AP4_DYNAMIC_CAST(AP4_OhdrAtom, odhe->GetChild(AP4_ATOM_TYPE_OHDR));
- if(ohdr == NULL) continue; // not enough info
+ if (ohdr == NULL) continue; // not enough info
// do nothing if the atom is not encrypted
- if(ohdr->GetEncryptionMethod() == AP4_OMA_DCF_ENCRYPTION_METHOD_NULL)
- {
+ if (ohdr->GetEncryptionMethod() == AP4_OMA_DCF_ENCRYPTION_METHOD_NULL) {
continue;
}
-
+
// create the byte stream
AP4_ByteStream* cipher_stream = NULL;
- AP4_Result result = CreateDecryptingStream(*odrm,
- key,
- 16,
- block_cipher_factory,
- cipher_stream);
- if(AP4_SUCCEEDED(result))
- {
+ AP4_Result result = CreateDecryptingStream(*odrm,
+ key,
+ 16,
+ block_cipher_factory,
+ cipher_stream);
+ if (AP4_SUCCEEDED(result)) {
// replace the odda atom's payload with the decrypted stream
odda->SetEncryptedPayload(*cipher_stream, ohdr->GetPlaintextLength());
cipher_stream->Release();
@@ -111,7 +108,7 @@ AP4_OmaDcfAtomDecrypter::DecryptAtoms(AP4_AtomParent& atoms,
/*----------------------------------------------------------------------
| AP4_OmaDcfAtomDecrypter::CreateDecryptingStream
+---------------------------------------------------------------------*/
-AP4_Result
+AP4_Result
AP4_OmaDcfAtomDecrypter::CreateDecryptingStream(
AP4_ContainerAtom& odrm,
const AP4_UI08* key,
@@ -121,111 +118,105 @@ AP4_OmaDcfAtomDecrypter::CreateDecryptingStream(
{
// default return values
stream = NULL;
-
+
AP4_OdheAtom* odhe = AP4_DYNAMIC_CAST(AP4_OdheAtom, odrm.GetChild(AP4_ATOM_TYPE_ODHE));
- if(odhe == NULL) return AP4_ERROR_INVALID_FORMAT;
+ if (odhe == NULL) return AP4_ERROR_INVALID_FORMAT;
AP4_OddaAtom* odda = AP4_DYNAMIC_CAST(AP4_OddaAtom, odrm.GetChild(AP4_ATOM_TYPE_ODDA));
- if(odda == NULL) return AP4_ERROR_INVALID_FORMAT;
+ if (odda == NULL) return AP4_ERROR_INVALID_FORMAT;
AP4_OhdrAtom* ohdr = AP4_DYNAMIC_CAST(AP4_OhdrAtom, odhe->GetChild(AP4_ATOM_TYPE_OHDR));
- if(ohdr == NULL) return AP4_ERROR_INVALID_FORMAT;
-
+ if (ohdr == NULL) return AP4_ERROR_INVALID_FORMAT;
+
// shortcut for non-encrypted files
- if(ohdr->GetEncryptionMethod() == AP4_OMA_DCF_ENCRYPTION_METHOD_NULL)
- {
+ if (ohdr->GetEncryptionMethod() == AP4_OMA_DCF_ENCRYPTION_METHOD_NULL) {
stream = &odda->GetEncryptedPayload();
stream->AddReference();
return AP4_SUCCESS;
}
-
+
// if this is part of a group, use the group key to obtain the content
// key (note that the field called GroupKey in the spec is actually not
// the group key but the content key encrypted with the group key...
AP4_GrpiAtom* grpi = AP4_DYNAMIC_CAST(AP4_GrpiAtom, ohdr->GetChild(AP4_ATOM_TYPE_GRPI));
AP4_UI08* key_buffer = NULL;
- if(grpi)
- {
+ if (grpi) {
// sanity check on the encrypted key size
- if(grpi->GetGroupKey().GetDataSize() < 32)
- {
+ if (grpi->GetGroupKey().GetDataSize() < 32) {
return AP4_ERROR_INVALID_FORMAT;
}
-
+
// create a block cipher to decrypt the content key
AP4_BlockCipher* block_cipher = NULL;
AP4_Result result;
-
+
// create a stream cipher from the block cipher
- AP4_StreamCipher* stream_cipher = NULL;
- switch(ohdr->GetEncryptionMethod())
- {
- case AP4_OMA_DCF_ENCRYPTION_METHOD_AES_CBC:
- result = block_cipher_factory->Create(AP4_BlockCipher::AES_128,
- AP4_BlockCipher::DECRYPT,
- key,
- key_size,
- block_cipher);
- if(AP4_FAILED(result)) return result;
- stream_cipher = new AP4_CbcStreamCipher(block_cipher, AP4_CbcStreamCipher::DECRYPT);
- break;
-
- case AP4_OMA_DCF_ENCRYPTION_METHOD_AES_CTR:
- result = block_cipher_factory->Create(AP4_BlockCipher::AES_128,
- AP4_BlockCipher::ENCRYPT,
- key,
- key_size,
- block_cipher);
- if(AP4_FAILED(result)) return result;
- stream_cipher = new AP4_CtrStreamCipher(block_cipher, NULL, 16);
- break;
-
- default:
- return AP4_ERROR_NOT_SUPPORTED;
+ AP4_StreamCipher* stream_cipher = NULL;
+ switch (ohdr->GetEncryptionMethod()) {
+ case AP4_OMA_DCF_ENCRYPTION_METHOD_AES_CBC:
+ result = block_cipher_factory->Create(AP4_BlockCipher::AES_128,
+ AP4_BlockCipher::DECRYPT,
+ key,
+ key_size,
+ block_cipher);
+ if (AP4_FAILED(result)) return result;
+ stream_cipher = new AP4_CbcStreamCipher(block_cipher, AP4_CbcStreamCipher::DECRYPT);
+ break;
+
+ case AP4_OMA_DCF_ENCRYPTION_METHOD_AES_CTR:
+ result = block_cipher_factory->Create(AP4_BlockCipher::AES_128,
+ AP4_BlockCipher::ENCRYPT,
+ key,
+ key_size,
+ block_cipher);
+ if (AP4_FAILED(result)) return result;
+ stream_cipher = new AP4_CtrStreamCipher(block_cipher, NULL, 16);
+ break;
+
+ default:
+ return AP4_ERROR_NOT_SUPPORTED;
}
// set the IV
stream_cipher->SetIV(grpi->GetGroupKey().GetData());
-
+
// decrypt the content key
AP4_Size key_buffer_size = grpi->GetGroupKey().GetDataSize(); // worst case
key_buffer = new AP4_UI08[key_buffer_size];
- result = stream_cipher->ProcessBuffer(grpi->GetGroupKey().GetData() + 16,
- grpi->GetGroupKey().GetDataSize() - 16,
- key_buffer,
- &key_buffer_size,
+ result = stream_cipher->ProcessBuffer(grpi->GetGroupKey().GetData()+16,
+ grpi->GetGroupKey().GetDataSize()-16,
+ key_buffer,
+ &key_buffer_size,
true);
delete stream_cipher; // this will also delete the block cipher
- if(AP4_FAILED(result))
- {
+ if (AP4_FAILED(result)) {
delete[] key_buffer;
return result;
}
-
+
// point to the new key value
key = key_buffer;
key_size = key_buffer_size;
}
-
+
AP4_OmaDcfCipherMode mode;
- switch(ohdr->GetEncryptionMethod())
- {
- case AP4_OMA_DCF_ENCRYPTION_METHOD_AES_CBC:
- mode = AP4_OMA_DCF_CIPHER_MODE_CBC;
- break;
- case AP4_OMA_DCF_ENCRYPTION_METHOD_AES_CTR:
- mode = AP4_OMA_DCF_CIPHER_MODE_CTR;
- break;
- default:
- return AP4_ERROR_NOT_SUPPORTED;
+ switch (ohdr->GetEncryptionMethod()) {
+ case AP4_OMA_DCF_ENCRYPTION_METHOD_AES_CBC:
+ mode = AP4_OMA_DCF_CIPHER_MODE_CBC;
+ break;
+ case AP4_OMA_DCF_ENCRYPTION_METHOD_AES_CTR:
+ mode = AP4_OMA_DCF_CIPHER_MODE_CTR;
+ break;
+ default:
+ return AP4_ERROR_NOT_SUPPORTED;
}
-
+
AP4_Result result;
result = CreateDecryptingStream(mode,
- odda->GetEncryptedPayload(),
- ohdr->GetPlaintextLength(),
- key, key_size,
+ odda->GetEncryptedPayload(),
+ ohdr->GetPlaintextLength(),
+ key, key_size,
block_cipher_factory,
stream);
-
+
// cleanup
delete[] key_buffer;
@@ -235,7 +226,7 @@ AP4_OmaDcfAtomDecrypter::CreateDecryptingStream(
/*----------------------------------------------------------------------
| AP4_OmaDcfAtomDecrypter::CreateDecryptingStream
+---------------------------------------------------------------------*/
-AP4_Result
+AP4_Result
AP4_OmaDcfAtomDecrypter::CreateDecryptingStream(
AP4_OmaDcfCipherMode mode,
AP4_ByteStream& encrypted_stream,
@@ -243,52 +234,45 @@ AP4_OmaDcfAtomDecrypter::CreateDecryptingStream(
const AP4_UI08* key,
AP4_Size key_size,
AP4_BlockCipherFactory* block_cipher_factory,
- AP4_ByteStream*& stream)
+ AP4_ByteStream*& stream)
{
// default return value
stream = NULL;
-
+
// get the encrypted size (includes IV and padding)
AP4_LargeSize encrypted_size = 0;
AP4_Result result = encrypted_stream.GetSize(encrypted_size);
- if(AP4_FAILED(result)) return result;
+ if (AP4_FAILED(result)) return result;
// check that the encrypted size is consistent with the cipher mode
AP4_DecryptingStream::CipherMode cipher_mode;
- if(mode == AP4_OMA_DCF_CIPHER_MODE_CBC)
- {
+ if (mode == AP4_OMA_DCF_CIPHER_MODE_CBC) {
// we need at least 16 bytes of IV and 32 bytes of data+padding
// we also need a multiple of the block size
- if(encrypted_size < 48 || ((encrypted_size % 16) != 0))
- {
+ if (encrypted_size < 48 || ((encrypted_size % 16) != 0)) {
return AP4_ERROR_INVALID_FORMAT;
}
cipher_mode = AP4_DecryptingStream::CIPHER_MODE_CBC;
- }
- else if(mode == AP4_OMA_DCF_CIPHER_MODE_CTR)
- {
+ } else if (mode == AP4_OMA_DCF_CIPHER_MODE_CTR) {
// we need at least 16 bytes of IV
- if(encrypted_size < 16)
- {
+ if (encrypted_size < 16) {
return AP4_ERROR_INVALID_FORMAT;
}
cipher_mode = AP4_DecryptingStream::CIPHER_MODE_CTR;
- }
- else
- {
+ } else {
return AP4_ERROR_NOT_SUPPORTED;
}
// read the IV
AP4_UI08 iv[16];
result = encrypted_stream.Seek(0);
- if(AP4_FAILED(result)) return result;
+ if (AP4_FAILED(result)) return result;
result = encrypted_stream.Read(iv, 16);
- if(AP4_FAILED(result)) return result;
+ if (AP4_FAILED(result)) return result;
// create a sub stream with just the encrypted payload without the IV
- AP4_ByteStream* sub_stream = new AP4_SubStream(encrypted_stream, 16, encrypted_size - 16);
-
+ AP4_ByteStream* sub_stream = new AP4_SubStream(encrypted_stream, 16, encrypted_size-16);
+
// create the decrypting cipher
result = AP4_DecryptingStream::Create(cipher_mode,
*sub_stream,
@@ -302,7 +286,7 @@ AP4_OmaDcfAtomDecrypter::CreateDecryptingStream(
// we don't keep our own reference to the sub stream
sub_stream->Release();
-
+
return result;
}
@@ -310,89 +294,80 @@ AP4_OmaDcfAtomDecrypter::CreateDecryptingStream(
| AP4_OmaDcfSampleDecrypter::Create
+---------------------------------------------------------------------*/
AP4_Result
-AP4_OmaDcfSampleDecrypter::Create(AP4_ProtectedSampleDescription* sample_description,
- const AP4_UI08* key,
+AP4_OmaDcfSampleDecrypter::Create(AP4_ProtectedSampleDescription* sample_description,
+ const AP4_UI08* key,
AP4_Size key_size,
AP4_BlockCipherFactory* block_cipher_factory,
AP4_OmaDcfSampleDecrypter*& cipher)
{
// check the parameters
- if(key == NULL || block_cipher_factory == NULL)
- {
+ if (key == NULL || block_cipher_factory == NULL) {
return AP4_ERROR_INVALID_PARAMETERS;
}
-
+
// default return value
cipher = NULL;
// get the scheme info atom
AP4_ContainerAtom* schi = sample_description->GetSchemeInfo()->GetSchiAtom();
- if(schi == NULL) return AP4_ERROR_INVALID_FORMAT;
+ if (schi == NULL) return AP4_ERROR_INVALID_FORMAT;
// get and check the cipher params
- // NOTE: we only support an IV Length less than or equal to the cipher block size,
+ // NOTE: we only support an IV Length less than or equal to the cipher block size,
// and we don't know how to deal with a key indicator length != 0
AP4_OdafAtom* odaf = AP4_DYNAMIC_CAST(AP4_OdafAtom, schi->FindChild("odkm/odaf"));
- if(odaf)
- {
- if(odaf->GetIvLength() > AP4_CIPHER_BLOCK_SIZE) return AP4_ERROR_INVALID_FORMAT;
- if(odaf->GetKeyIndicatorLength() != 0) return AP4_ERROR_INVALID_FORMAT;
+ if (odaf) {
+ if (odaf->GetIvLength() > AP4_CIPHER_BLOCK_SIZE) return AP4_ERROR_INVALID_FORMAT;
+ if (odaf->GetKeyIndicatorLength() != 0) return AP4_ERROR_INVALID_FORMAT;
}
// check the scheme details and create the cipher
AP4_OhdrAtom* ohdr = AP4_DYNAMIC_CAST(AP4_OhdrAtom, schi->FindChild("odkm/ohdr"));
- if(ohdr == NULL) return AP4_ERROR_INVALID_FORMAT;
+ if (ohdr == NULL) return AP4_ERROR_INVALID_FORMAT;
AP4_UI08 encryption_method = ohdr->GetEncryptionMethod();
- if(encryption_method == AP4_OMA_DCF_ENCRYPTION_METHOD_AES_CBC)
- {
+ if (encryption_method == AP4_OMA_DCF_ENCRYPTION_METHOD_AES_CBC) {
// in CBC mode, we only support IVs of the same size as the cipher block size
- if(odaf->GetIvLength() != AP4_CIPHER_BLOCK_SIZE) return AP4_ERROR_INVALID_FORMAT;
+ if (odaf->GetIvLength() != AP4_CIPHER_BLOCK_SIZE) return AP4_ERROR_INVALID_FORMAT;
// require RFC_2630 padding
- if(ohdr->GetPaddingScheme() != AP4_OMA_DCF_PADDING_SCHEME_RFC_2630)
- {
+ if (ohdr->GetPaddingScheme() != AP4_OMA_DCF_PADDING_SCHEME_RFC_2630) {
return AP4_ERROR_NOT_SUPPORTED;
}
// create the block cipher
AP4_BlockCipher* block_cipher = NULL;
- AP4_Result result = block_cipher_factory->Create(AP4_BlockCipher::AES_128,
- AP4_BlockCipher::DECRYPT,
- key,
- key_size,
- block_cipher);
- if(AP4_FAILED(result)) return result;
+ AP4_Result result = block_cipher_factory->Create(AP4_BlockCipher::AES_128,
+ AP4_BlockCipher::DECRYPT,
+ key,
+ key_size,
+ block_cipher);
+ if (AP4_FAILED(result)) return result;
// create the cipher
- cipher = new AP4_OmaDcfCbcSampleDecrypter(block_cipher,
- odaf->GetSelectiveEncryption());
+ cipher = new AP4_OmaDcfCbcSampleDecrypter(block_cipher,
+ odaf->GetSelectiveEncryption());
return AP4_SUCCESS;
- }
- else if(encryption_method == AP4_OMA_DCF_ENCRYPTION_METHOD_AES_CTR)
- {
+ } else if (encryption_method == AP4_OMA_DCF_ENCRYPTION_METHOD_AES_CTR) {
// require NONE padding
- if(ohdr->GetPaddingScheme() != AP4_OMA_DCF_PADDING_SCHEME_NONE)
- {
+ if (ohdr->GetPaddingScheme() != AP4_OMA_DCF_PADDING_SCHEME_NONE) {
return AP4_ERROR_INVALID_FORMAT;
}
// create the block cipher
AP4_BlockCipher* block_cipher = NULL;
- AP4_Result result = block_cipher_factory->Create(AP4_BlockCipher::AES_128,
- AP4_BlockCipher::ENCRYPT,
- key,
- key_size,
- block_cipher);
- if(AP4_FAILED(result)) return result;
+ AP4_Result result = block_cipher_factory->Create(AP4_BlockCipher::AES_128,
+ AP4_BlockCipher::ENCRYPT,
+ key,
+ key_size,
+ block_cipher);
+ if (AP4_FAILED(result)) return result;
// create the cipher
- cipher = new AP4_OmaDcfCtrSampleDecrypter(block_cipher,
- odaf->GetIvLength(),
- odaf->GetSelectiveEncryption());
+ cipher = new AP4_OmaDcfCtrSampleDecrypter(block_cipher,
+ odaf->GetIvLength(),
+ odaf->GetSelectiveEncryption());
return AP4_SUCCESS;
- }
- else
- {
+ } else {
return AP4_ERROR_NOT_SUPPORTED;
}
}
@@ -420,48 +395,44 @@ AP4_OmaDcfCtrSampleDecrypter::~AP4_OmaDcfCtrSampleDecrypter()
/*----------------------------------------------------------------------
| AP4_OmaDcfCtrSampleDecrypter::DecryptSampleData
+---------------------------------------------------------------------*/
-AP4_Result
+AP4_Result
AP4_OmaDcfCtrSampleDecrypter::DecryptSampleData(AP4_DataBuffer& data_in,
- AP4_DataBuffer& data_out,
- const AP4_UI08* /*iv*/)
-{
+ AP4_DataBuffer& data_out,
+ const AP4_UI08* /*iv*/)
+{
bool is_encrypted = true;
const unsigned char* in = data_in.GetData();
AP4_Size in_size = data_in.GetDataSize();
- // default to 0 output
+ // default to 0 output
AP4_CHECK(data_out.SetDataSize(0));
// check the selective encryption flag
- if(m_SelectiveEncryption)
- {
- if(in_size < 1) return AP4_ERROR_INVALID_FORMAT;
- is_encrypted = ((in[0] & 0x80) != 0);
+ if (m_SelectiveEncryption) {
+ if (in_size < 1) return AP4_ERROR_INVALID_FORMAT;
+ is_encrypted = ((in[0]&0x80)!=0);
in++;
}
// check the size
- unsigned int header_size = (m_SelectiveEncryption ? 1 : 0) + (is_encrypted ? m_IvLength : 0);
- if(header_size > in_size) return AP4_ERROR_INVALID_FORMAT;
+ unsigned int header_size = (m_SelectiveEncryption?1:0)+(is_encrypted?m_IvLength:0);
+ if (header_size > in_size) return AP4_ERROR_INVALID_FORMAT;
// process the sample data
- AP4_Size payload_size = in_size - header_size;
+ AP4_Size payload_size = in_size-header_size;
AP4_CHECK(data_out.Reserve(payload_size));
unsigned char* out = data_out.UseData();
- if(is_encrypted)
- {
+ if (is_encrypted) {
// set the IV
m_Cipher->SetIV(in);
- AP4_CHECK(m_Cipher->ProcessBuffer(in + m_IvLength,
- payload_size,
+ AP4_CHECK(m_Cipher->ProcessBuffer(in+m_IvLength,
+ payload_size,
out));
- }
- else
- {
+ } else {
AP4_CopyMemory(out, in, payload_size);
}
AP4_CHECK(data_out.SetDataSize(payload_size));
-
+
return AP4_SUCCESS;
}
@@ -471,26 +442,23 @@ AP4_OmaDcfCtrSampleDecrypter::DecryptSampleData(AP4_DataBuffer& data_in,
AP4_Size
AP4_OmaDcfCtrSampleDecrypter::GetDecryptedSampleSize(AP4_Sample& sample)
{
- if(m_Cipher == NULL) return 0;
+ if (m_Cipher == NULL) return 0;
// decide if this sample is encrypted or not
bool is_encrypted;
- if(m_SelectiveEncryption)
- {
+ if (m_SelectiveEncryption) {
// read the first byte to see if the sample is encrypted or not
AP4_Byte h;
AP4_DataBuffer peek_buffer;
peek_buffer.SetBuffer(&h, 1);
sample.ReadData(peek_buffer, 1);
- is_encrypted = ((h & 0x80) != 0);
- }
- else
- {
+ is_encrypted = ((h&0x80)!=0);
+ } else {
is_encrypted = true;
}
- AP4_Size crypto_header_size = (m_SelectiveEncryption ? 1 : 0) + (is_encrypted ? m_IvLength : 0);
- return sample.GetSize() - crypto_header_size;
+ AP4_Size crypto_header_size = (m_SelectiveEncryption?1:0)+(is_encrypted?m_IvLength:0);
+ return sample.GetSize()-crypto_header_size;
}
/*----------------------------------------------------------------------
@@ -515,37 +483,35 @@ AP4_OmaDcfCbcSampleDecrypter::~AP4_OmaDcfCbcSampleDecrypter()
/*----------------------------------------------------------------------
| AP4_OmaDbcCbcSampleDecrypter::DecryptSampleData
+---------------------------------------------------------------------*/
-AP4_Result
+AP4_Result
AP4_OmaDcfCbcSampleDecrypter::DecryptSampleData(AP4_DataBuffer& data_in,
- AP4_DataBuffer& data_out,
- const AP4_UI08* /*iv*/)
-{
+ AP4_DataBuffer& data_out,
+ const AP4_UI08* /*iv*/)
+{
bool is_encrypted = true;
const unsigned char* in = data_in.GetData();
AP4_Size in_size = data_in.GetDataSize();
AP4_Size out_size;
- // default to 0 output
+ // default to 0 output
AP4_CHECK(data_out.SetDataSize(0));
// check the selective encryption flag
- if(m_SelectiveEncryption)
- {
- if(in_size < 1) return AP4_ERROR_INVALID_FORMAT;
- is_encrypted = ((in[0] & 0x80) != 0);
+ if (m_SelectiveEncryption) {
+ if (in_size < 1) return AP4_ERROR_INVALID_FORMAT;
+ is_encrypted = ((in[0]&0x80)!=0);
in++;
}
// check the size
- unsigned int header_size = (m_SelectiveEncryption ? 1 : 0) + (is_encrypted ? m_IvLength : 0);
- if(header_size > in_size) return AP4_ERROR_INVALID_FORMAT;
+ unsigned int header_size = (m_SelectiveEncryption?1:0)+(is_encrypted?m_IvLength:0);
+ if (header_size > in_size) return AP4_ERROR_INVALID_FORMAT;
// process the sample data
- unsigned int payload_size = in_size - header_size;
+ unsigned int payload_size = in_size-header_size;
data_out.Reserve(payload_size);
unsigned char* out = data_out.UseData();
- if(is_encrypted)
- {
+ if (is_encrypted) {
// get the IV
const AP4_UI08* iv = (const AP4_UI08*)in;
in += AP4_CIPHER_BLOCK_SIZE;
@@ -553,9 +519,7 @@ AP4_OmaDcfCbcSampleDecrypter::DecryptSampleData(AP4_DataBuffer& data_in,
m_Cipher->SetIV(iv);
out_size = payload_size;
AP4_CHECK(m_Cipher->ProcessBuffer(in, payload_size, out, &out_size, true));
- }
- else
- {
+ } else {
AP4_CopyMemory(out, in, payload_size);
out_size = payload_size;
}
@@ -571,57 +535,48 @@ AP4_OmaDcfCbcSampleDecrypter::DecryptSampleData(AP4_DataBuffer& data_in,
AP4_Size
AP4_OmaDcfCbcSampleDecrypter::GetDecryptedSampleSize(AP4_Sample& sample)
{
- if(m_Cipher == NULL) return 0;
+ if (m_Cipher == NULL) return 0;
// decide if this sample is encrypted or not
bool is_encrypted;
- if(m_SelectiveEncryption)
- {
+ if (m_SelectiveEncryption) {
// read the first byte to see if the sample is encrypted or not
AP4_Byte h;
AP4_DataBuffer peek_buffer;
peek_buffer.SetBuffer(&h, 1);
sample.ReadData(peek_buffer, 1);
- is_encrypted = ((h & 0x80) != 0);
- }
- else
- {
+ is_encrypted = ((h&0x80)!=0);
+ } else {
is_encrypted = true;
}
- if(is_encrypted)
- {
+ if (is_encrypted) {
// with CBC, we need to decrypt the last block to know what the padding was
- AP4_Size crypto_header_size = (m_SelectiveEncryption ? 1 : 0) + m_IvLength;
- AP4_Size encrypted_size = sample.GetSize() - crypto_header_size;
+ AP4_Size crypto_header_size = (m_SelectiveEncryption?1:0)+m_IvLength;
+ AP4_Size encrypted_size = sample.GetSize()-crypto_header_size;
AP4_DataBuffer encrypted;
AP4_DataBuffer decrypted;
AP4_Size decrypted_size = AP4_CIPHER_BLOCK_SIZE;
- if(sample.GetSize() < crypto_header_size + AP4_CIPHER_BLOCK_SIZE)
- {
+ if (sample.GetSize() < crypto_header_size+AP4_CIPHER_BLOCK_SIZE) {
return 0;
}
- AP4_Size offset = sample.GetSize() - 2 * AP4_CIPHER_BLOCK_SIZE;
- if(AP4_FAILED(sample.ReadData(encrypted, 2 * AP4_CIPHER_BLOCK_SIZE, offset)))
- {
+ AP4_Size offset = sample.GetSize()-2*AP4_CIPHER_BLOCK_SIZE;
+ if (AP4_FAILED(sample.ReadData(encrypted, 2*AP4_CIPHER_BLOCK_SIZE, offset))) {
return 0;
}
decrypted.Reserve(decrypted_size);
m_Cipher->SetIV(encrypted.GetData());
- if(AP4_FAILED(m_Cipher->ProcessBuffer(encrypted.GetData() + AP4_CIPHER_BLOCK_SIZE,
- AP4_CIPHER_BLOCK_SIZE,
- decrypted.UseData(),
- &decrypted_size,
- true)))
- {
+ if (AP4_FAILED(m_Cipher->ProcessBuffer(encrypted.GetData()+AP4_CIPHER_BLOCK_SIZE,
+ AP4_CIPHER_BLOCK_SIZE,
+ decrypted.UseData(),
+ &decrypted_size,
+ true))) {
return 0;
}
- unsigned int padding_size = AP4_CIPHER_BLOCK_SIZE - decrypted_size;
- return encrypted_size - padding_size;
- }
- else
- {
- return sample.GetSize() - (m_SelectiveEncryption ? 1 : 0);
+ unsigned int padding_size = AP4_CIPHER_BLOCK_SIZE-decrypted_size;
+ return encrypted_size-padding_size;
+ } else {
+ return sample.GetSize()-(m_SelectiveEncryption?1:0);
}
}
@@ -631,16 +586,13 @@ AP4_OmaDcfCbcSampleDecrypter::GetDecryptedSampleSize(AP4_Sample& sample)
AP4_OmaDcfSampleEncrypter::AP4_OmaDcfSampleEncrypter(const AP4_UI08* salt)
{
// left-align the salt
- unsigned int i = 0;
- if(salt)
- {
- for(; i < 8; i++)
- {
+ unsigned int i=0;
+ if (salt) {
+ for (; i<8; i++) {
m_Salt[i] = salt[i];
}
}
- for(; i < sizeof(m_Salt) / sizeof(m_Salt[0]); i++)
- {
+ for (; i<sizeof(m_Salt)/sizeof(m_Salt[0]); i++) {
m_Salt[i] = 0;
}
}
@@ -649,8 +601,8 @@ AP4_OmaDcfSampleEncrypter::AP4_OmaDcfSampleEncrypter(const AP4_UI08* salt)
| AP4_OmaDcfCtrSampleEncrypter::AP4_OmaDcfCtrSampleEncrypter
+---------------------------------------------------------------------*/
AP4_OmaDcfCtrSampleEncrypter::AP4_OmaDcfCtrSampleEncrypter(AP4_BlockCipher* block_cipher,
- const AP4_UI08* salt) :
- AP4_OmaDcfSampleEncrypter(salt)
+ const AP4_UI08* salt) :
+ AP4_OmaDcfSampleEncrypter(salt)
{
m_Cipher = new AP4_CtrStreamCipher(block_cipher, m_Salt, 8);
}
@@ -666,15 +618,15 @@ AP4_OmaDcfCtrSampleEncrypter::~AP4_OmaDcfCtrSampleEncrypter()
/*----------------------------------------------------------------------
| AP4_OmaDcfCtrSampleEncrypter::EncryptSampleData
+---------------------------------------------------------------------*/
-AP4_Result
+AP4_Result
AP4_OmaDcfCtrSampleEncrypter::EncryptSampleData(AP4_DataBuffer& data_in,
- AP4_DataBuffer& data_out,
- AP4_UI64 counter,
- bool /*skip_encryption*/)
+ AP4_DataBuffer& data_out,
+ AP4_UI64 counter,
+ bool /*skip_encryption*/)
{
// setup the buffers
const unsigned char* in = data_in.GetData();
- AP4_CHECK(data_out.SetDataSize(data_in.GetDataSize() + AP4_CIPHER_BLOCK_SIZE + 1));
+ AP4_CHECK(data_out.SetDataSize(data_in.GetDataSize()+AP4_CIPHER_BLOCK_SIZE+1));
unsigned char* out = data_out.UseData();
// selective encryption flag
@@ -688,8 +640,8 @@ AP4_OmaDcfCtrSampleEncrypter::EncryptSampleData(AP4_DataBuffer& data_in,
// encrypt the payload
AP4_Size data_size = data_in.GetDataSize();
- m_Cipher->SetIV(out + 8);
- m_Cipher->ProcessBuffer(in, data_size, out + AP4_CIPHER_BLOCK_SIZE);
+ m_Cipher->SetIV(out+8);
+ m_Cipher->ProcessBuffer(in, data_size, out+AP4_CIPHER_BLOCK_SIZE);
return AP4_SUCCESS;
}
@@ -697,18 +649,18 @@ AP4_OmaDcfCtrSampleEncrypter::EncryptSampleData(AP4_DataBuffer& data_in,
/*----------------------------------------------------------------------
| AP4_OmaDcfCtrSampleEncrypter::GetEncryptedSampleSize
+---------------------------------------------------------------------*/
-AP4_Size
+AP4_Size
AP4_OmaDcfCtrSampleEncrypter::GetEncryptedSampleSize(AP4_Sample& sample)
{
- return sample.GetSize() + AP4_CIPHER_BLOCK_SIZE + 1;
+ return sample.GetSize()+AP4_CIPHER_BLOCK_SIZE+1;
}
/*----------------------------------------------------------------------
| AP4_OmaDcfCbcSampleEncrypter::AP4_OmaDcfCbcSampleEncrypter
+---------------------------------------------------------------------*/
AP4_OmaDcfCbcSampleEncrypter::AP4_OmaDcfCbcSampleEncrypter(AP4_BlockCipher* block_cipher,
- const AP4_UI08* salt) :
- AP4_OmaDcfSampleEncrypter(salt)
+ const AP4_UI08* salt) :
+ AP4_OmaDcfSampleEncrypter(salt)
{
m_Cipher = new AP4_CbcStreamCipher(block_cipher, AP4_CbcStreamCipher::ENCRYPT);
}
@@ -724,17 +676,17 @@ AP4_OmaDcfCbcSampleEncrypter::~AP4_OmaDcfCbcSampleEncrypter()
/*----------------------------------------------------------------------
| AP4_OmaDcfCbcSampleEncrypter::EncryptSampleData
+---------------------------------------------------------------------*/
-AP4_Result
+AP4_Result
AP4_OmaDcfCbcSampleEncrypter::EncryptSampleData(AP4_DataBuffer& data_in,
- AP4_DataBuffer& data_out,
- AP4_UI64 counter,
- bool /*skip_encryption*/)
+ AP4_DataBuffer& data_out,
+ AP4_UI64 counter,
+ bool /*skip_encryption*/)
{
// make sure there is enough space in the output buffer
- data_out.Reserve(data_in.GetDataSize() + 2 * AP4_CIPHER_BLOCK_SIZE + 1);
+ data_out.Reserve(data_in.GetDataSize()+2*AP4_CIPHER_BLOCK_SIZE+1);
// setup the buffers
- AP4_Size out_size = data_in.GetDataSize() + AP4_CIPHER_BLOCK_SIZE;
+ AP4_Size out_size = data_in.GetDataSize()+AP4_CIPHER_BLOCK_SIZE;
unsigned char* out = data_out.UseData();
// selective encryption flag
@@ -748,12 +700,12 @@ AP4_OmaDcfCbcSampleEncrypter::EncryptSampleData(AP4_DataBuffer& data_in,
// encrypt the payload
m_Cipher->SetIV(out);
- m_Cipher->ProcessBuffer(data_in.GetData(),
+ m_Cipher->ProcessBuffer(data_in.GetData(),
data_in.GetDataSize(),
- out + AP4_CIPHER_BLOCK_SIZE,
+ out+AP4_CIPHER_BLOCK_SIZE,
&out_size,
true);
- AP4_CHECK(data_out.SetDataSize(out_size + AP4_CIPHER_BLOCK_SIZE + 1));
+ AP4_CHECK(data_out.SetDataSize(out_size+AP4_CIPHER_BLOCK_SIZE+1));
return AP4_SUCCESS;
}
@@ -765,8 +717,8 @@ AP4_Size
AP4_OmaDcfCbcSampleEncrypter::GetEncryptedSampleSize(AP4_Sample& sample)
{
AP4_Size sample_size = sample.GetSize();
- AP4_Size padding_size = AP4_CIPHER_BLOCK_SIZE - (sample_size % AP4_CIPHER_BLOCK_SIZE);
- return sample_size + padding_size + AP4_CIPHER_BLOCK_SIZE + 1;
+ AP4_Size padding_size = AP4_CIPHER_BLOCK_SIZE-(sample_size%AP4_CIPHER_BLOCK_SIZE);
+ return sample_size+padding_size+AP4_CIPHER_BLOCK_SIZE+1;
}
/*----------------------------------------------------------------------
@@ -782,29 +734,27 @@ AP4_OmaDcfTrackDecrypter::Create(
AP4_OmaDcfTrackDecrypter*& decrypter)
{
// check and set defaults
- if(key == NULL)
- {
+ if (key == NULL) {
return AP4_ERROR_INVALID_PARAMETERS;
}
- if(block_cipher_factory == NULL)
- {
+ if (block_cipher_factory == NULL) {
block_cipher_factory = &AP4_DefaultBlockCipherFactory::Instance;
}
decrypter = NULL;
// create the cipher
AP4_OmaDcfSampleDecrypter* cipher = NULL;
- AP4_Result result = AP4_OmaDcfSampleDecrypter::Create(sample_description,
- key,
- key_size,
- block_cipher_factory,
- cipher);
- if(AP4_FAILED(result)) return result;
+ AP4_Result result = AP4_OmaDcfSampleDecrypter::Create(sample_description,
+ key,
+ key_size,
+ block_cipher_factory,
+ cipher);
+ if (AP4_FAILED(result)) return result;
// instantiate the object
- decrypter = new AP4_OmaDcfTrackDecrypter(cipher,
- sample_entry,
- sample_description->GetOriginalFormat());
+ decrypter = new AP4_OmaDcfTrackDecrypter(cipher,
+ sample_entry,
+ sample_description->GetOriginalFormat());
return AP4_SUCCESS;
}
@@ -812,8 +762,8 @@ AP4_OmaDcfTrackDecrypter::Create(
| AP4_OmaDcfTrackDecrypter::AP4_OmaDcfTrackDecrypter
+---------------------------------------------------------------------*/
AP4_OmaDcfTrackDecrypter::AP4_OmaDcfTrackDecrypter(AP4_OmaDcfSampleDecrypter* cipher,
- AP4_SampleEntry* sample_entry,
- AP4_UI32 original_format) :
+ AP4_SampleEntry* sample_entry,
+ AP4_UI32 original_format) :
m_Cipher(cipher),
m_SampleEntry(sample_entry),
m_OriginalFormat(original_format)
@@ -831,17 +781,17 @@ AP4_OmaDcfTrackDecrypter::~AP4_OmaDcfTrackDecrypter()
/*----------------------------------------------------------------------
| AP4_OmaDcfTrackDecrypter::GetProcessedSampleSize
+---------------------------------------------------------------------*/
-AP4_Size
+AP4_Size
AP4_OmaDcfTrackDecrypter::GetProcessedSampleSize(AP4_Sample& sample)
{
- if(m_Cipher == NULL) return 0;
+ if (m_Cipher == NULL) return 0;
return m_Cipher->GetDecryptedSampleSize(sample);
}
/*----------------------------------------------------------------------
| AP4_OmaDcfTrackDecrypter::ProcessTrack
+---------------------------------------------------------------------*/
-AP4_Result
+AP4_Result
AP4_OmaDcfTrackDecrypter::ProcessTrack()
{
m_SampleEntry->SetType(m_OriginalFormat);
@@ -852,7 +802,7 @@ AP4_OmaDcfTrackDecrypter::ProcessTrack()
/*----------------------------------------------------------------------
| AP4_OmaDcfDecrypter::ProcessSample
+---------------------------------------------------------------------*/
-AP4_Result
+AP4_Result
AP4_OmaDcfTrackDecrypter::ProcessSample(AP4_DataBuffer& data_in,
AP4_DataBuffer& data_out)
{
@@ -862,8 +812,7 @@ AP4_OmaDcfTrackDecrypter::ProcessSample(AP4_DataBuffer& data_in,
/*----------------------------------------------------------------------
| AP4_OmaDcfTrackEncrypter
+---------------------------------------------------------------------*/
-class AP4_OmaDcfTrackEncrypter : public AP4_Processor::TrackHandler
-{
+class AP4_OmaDcfTrackEncrypter : public AP4_Processor::TrackHandler {
public:
// constructor
AP4_OmaDcfTrackEncrypter(AP4_OmaDcfCipherMode cipher_mode,
@@ -873,7 +822,7 @@ public:
AP4_UI32 format,
const char* content_id,
const char* rights_issuer_url,
- const AP4_Byte* textual_headers,
+ const AP4_Byte* textual_headers,
AP4_Size textual_headers_size);
virtual ~AP4_OmaDcfTrackEncrypter();
@@ -907,7 +856,7 @@ AP4_OmaDcfTrackEncrypter::AP4_OmaDcfTrackEncrypter(
AP4_UI32 format,
const char* content_id,
const char* rights_issuer_url,
- const AP4_Byte* textual_headers,
+ const AP4_Byte* textual_headers,
AP4_Size textual_headers_size) :
m_SampleEntry(sample_entry),
m_Format(format),
@@ -917,14 +866,11 @@ AP4_OmaDcfTrackEncrypter::AP4_OmaDcfTrackEncrypter(
m_Counter(0)
{
// instantiate the cipher (fixed params for now)
- if(cipher_mode == AP4_OMA_DCF_CIPHER_MODE_CBC)
- {
+ if (cipher_mode == AP4_OMA_DCF_CIPHER_MODE_CBC) {
m_Cipher = new AP4_OmaDcfCbcSampleEncrypter(block_cipher, salt);
m_CipherMode = AP4_OMA_DCF_ENCRYPTION_METHOD_AES_CBC;
m_CipherPadding = AP4_OMA_DCF_PADDING_SCHEME_RFC_2630;
- }
- else
- {
+ } else {
m_Cipher = new AP4_OmaDcfCtrSampleEncrypter(block_cipher, salt);
m_CipherMode = AP4_OMA_DCF_ENCRYPTION_METHOD_AES_CTR;
m_CipherPadding = AP4_OMA_DCF_PADDING_SCHEME_NONE;
@@ -942,7 +888,7 @@ AP4_OmaDcfTrackEncrypter::~AP4_OmaDcfTrackEncrypter()
/*----------------------------------------------------------------------
| AP4_OmaDcfTrackEncrypter::GetProcessedSampleSize
+---------------------------------------------------------------------*/
-AP4_Size
+AP4_Size
AP4_OmaDcfTrackEncrypter::GetProcessedSampleSize(AP4_Sample& sample)
{
return m_Cipher->GetEncryptedSampleSize(sample);
@@ -951,7 +897,7 @@ AP4_OmaDcfTrackEncrypter::GetProcessedSampleSize(AP4_Sample& sample)
/*----------------------------------------------------------------------
| AP4_OmaDcfTrackEncrypter::ProcessTrack
+---------------------------------------------------------------------*/
-AP4_Result
+AP4_Result
AP4_OmaDcfTrackEncrypter::ProcessTrack()
{
// sinf container
@@ -959,20 +905,20 @@ AP4_OmaDcfTrackEncrypter::ProcessTrack()
// original format
AP4_FrmaAtom* frma = new AP4_FrmaAtom(m_SampleEntry->GetType());
-
+
// scheme info
AP4_ContainerAtom* schi = new AP4_ContainerAtom(AP4_ATOM_TYPE_SCHI);
AP4_OdafAtom* odaf = new AP4_OdafAtom(true, 0, AP4_CIPHER_BLOCK_SIZE);
AP4_OhdrAtom* ohdr = new AP4_OhdrAtom(m_CipherMode,
- m_CipherPadding,
- 0,
- m_ContentId.GetChars(),
- m_RightsIssuerUrl.GetChars(),
- m_TextualHeaders.GetData(),
- m_TextualHeaders.GetDataSize());
+ m_CipherPadding,
+ 0,
+ m_ContentId.GetChars(),
+ m_RightsIssuerUrl.GetChars(),
+ m_TextualHeaders.GetData(),
+ m_TextualHeaders.GetDataSize());
AP4_ContainerAtom* odkm = new AP4_ContainerAtom(AP4_ATOM_TYPE_ODKM, (AP4_UI32)0, (AP4_UI32)0);
- AP4_SchmAtom* schm = new AP4_SchmAtom(AP4_PROTECTION_SCHEME_TYPE_OMA,
- AP4_PROTECTION_SCHEME_VERSION_OMA_20);
+ AP4_SchmAtom* schm = new AP4_SchmAtom(AP4_PROTECTION_SCHEME_TYPE_OMA,
+ AP4_PROTECTION_SCHEME_VERSION_OMA_20);
odkm->AddChild(odaf);
odkm->AddChild(ohdr);
@@ -989,24 +935,24 @@ AP4_OmaDcfTrackEncrypter::ProcessTrack()
// change the atom type of the sample description
m_SampleEntry->SetType(m_Format);
-
+
return AP4_SUCCESS;
}
/*----------------------------------------------------------------------
| AP4_OmaDcfTrackEncrypter::ProcessSample
+---------------------------------------------------------------------*/
-AP4_Result
+AP4_Result
AP4_OmaDcfTrackEncrypter::ProcessSample(AP4_DataBuffer& data_in,
AP4_DataBuffer& data_out)
{
- AP4_Result result = m_Cipher->EncryptSampleData(data_in,
- data_out,
- m_Counter,
- false);
- if(AP4_FAILED(result)) return result;
+ AP4_Result result = m_Cipher->EncryptSampleData(data_in,
+ data_out,
+ m_Counter,
+ false);
+ if (AP4_FAILED(result)) return result;
- m_Counter += (data_in.GetDataSize() + AP4_CIPHER_BLOCK_SIZE - 1) / AP4_CIPHER_BLOCK_SIZE;
+ m_Counter += (data_in.GetDataSize()+AP4_CIPHER_BLOCK_SIZE-1)/AP4_CIPHER_BLOCK_SIZE;
return AP4_SUCCESS;
}
@@ -1017,18 +963,14 @@ AP4_OmaDcfDecryptingProcessor::AP4_OmaDcfDecryptingProcessor(
const AP4_ProtectionKeyMap* key_map /* = NULL */,
AP4_BlockCipherFactory* block_cipher_factory /* = NULL */)
{
- if(key_map)
- {
+ if (key_map) {
// copy the keys
m_KeyMap.SetKeys(*key_map);
}
-
- if(block_cipher_factory == NULL)
- {
+
+ if (block_cipher_factory == NULL) {
m_BlockCipherFactory = &AP4_DefaultBlockCipherFactory::Instance;
- }
- else
- {
+ } else {
m_BlockCipherFactory = block_cipher_factory;
}
}
@@ -1036,26 +978,20 @@ AP4_OmaDcfDecryptingProcessor::AP4_OmaDcfDecryptingProcessor(
/*----------------------------------------------------------------------
| AP4_OmaDcfDecryptingProcessor:Initialize
+---------------------------------------------------------------------*/
-AP4_Result
-AP4_OmaDcfDecryptingProcessor::Initialize(AP4_AtomParent& top_level,
- AP4_ByteStream& /* stream */,
- ProgressListener* listener)
+AP4_Result
+AP4_OmaDcfDecryptingProcessor::Initialize(AP4_AtomParent& top_level,
+ AP4_ByteStream& /* stream */,
+ ProgressListener* listener)
{
// decide which processor to instantiate based on the file type
AP4_FtypAtom* ftyp = AP4_DYNAMIC_CAST(AP4_FtypAtom, top_level.GetChild(AP4_ATOM_TYPE_FTYP));
- if(ftyp)
- {
- if(ftyp->GetMajorBrand() == AP4_OMA_DCF_BRAND_ODCF || ftyp->HasCompatibleBrand(AP4_OMA_DCF_BRAND_ODCF))
- {
+ if (ftyp) {
+ if (ftyp->GetMajorBrand() == AP4_OMA_DCF_BRAND_ODCF || ftyp->HasCompatibleBrand(AP4_OMA_DCF_BRAND_ODCF)) {
return AP4_OmaDcfAtomDecrypter::DecryptAtoms(top_level, listener, m_BlockCipherFactory, m_KeyMap);
- }
- else
- {
+ } else {
return AP4_ERROR_INVALID_FORMAT;
}
- }
- else
- {
+ } else {
return AP4_SUCCESS;
}
}
@@ -1064,15 +1000,12 @@ AP4_OmaDcfDecryptingProcessor::Initialize(AP4_AtomParent& top_level,
| AP4_OmaDcfEncryptingProcessor:AP4_OmaDcfEncryptingProcessor
+---------------------------------------------------------------------*/
AP4_OmaDcfEncryptingProcessor::AP4_OmaDcfEncryptingProcessor(AP4_OmaDcfCipherMode cipher_mode,
- AP4_BlockCipherFactory* block_cipher_factory) :
+ AP4_BlockCipherFactory* block_cipher_factory) :
m_CipherMode(cipher_mode)
{
- if(block_cipher_factory == NULL)
- {
+ if (block_cipher_factory == NULL) {
m_BlockCipherFactory = &AP4_DefaultBlockCipherFactory::Instance;
- }
- else
- {
+ } else {
m_BlockCipherFactory = block_cipher_factory;
}
}
@@ -1080,45 +1013,40 @@ AP4_OmaDcfEncryptingProcessor::AP4_OmaDcfEncryptingProcessor(AP4_OmaDcfCipherMod
/*----------------------------------------------------------------------
| AP4_OmaDcfEncryptingProcessor::Initialize
+---------------------------------------------------------------------*/
-AP4_Result
+AP4_Result
AP4_OmaDcfEncryptingProcessor::Initialize(AP4_AtomParent& top_level,
- AP4_ByteStream& /*stream*/,
- AP4_Processor::ProgressListener* /*listener*/)
+ AP4_ByteStream& /*stream*/,
+ AP4_Processor::ProgressListener* /*listener*/)
{
AP4_FtypAtom* ftyp = AP4_DYNAMIC_CAST(AP4_FtypAtom, top_level.GetChild(AP4_ATOM_TYPE_FTYP));
- if(ftyp)
- {
+ if (ftyp) {
// remove the atom, it will be replaced with a new one
top_level.RemoveChild(ftyp);
-
+
// keep the existing brand and compatible brands
AP4_Array<AP4_UI32> compatible_brands;
- compatible_brands.EnsureCapacity(ftyp->GetCompatibleBrands().ItemCount() + 1);
- for(unsigned int i = 0; i < ftyp->GetCompatibleBrands().ItemCount(); i++)
- {
+ compatible_brands.EnsureCapacity(ftyp->GetCompatibleBrands().ItemCount()+1);
+ for (unsigned int i=0; i<ftyp->GetCompatibleBrands().ItemCount(); i++) {
compatible_brands.Append(ftyp->GetCompatibleBrands()[i]);
}
-
+
// add the OMA compatible brand if it is not already there
- if(!ftyp->HasCompatibleBrand(AP4_OMA_DCF_BRAND_OPF2))
- {
+ if (!ftyp->HasCompatibleBrand(AP4_OMA_DCF_BRAND_OPF2)) {
compatible_brands.Append(AP4_OMA_DCF_BRAND_OPF2);
}
// create a replacement
AP4_FtypAtom* new_ftyp = new AP4_FtypAtom(ftyp->GetMajorBrand(),
- ftyp->GetMinorVersion(),
- &compatible_brands[0],
- compatible_brands.ItemCount());
+ ftyp->GetMinorVersion(),
+ &compatible_brands[0],
+ compatible_brands.ItemCount());
delete ftyp;
ftyp = new_ftyp;
- }
- else
- {
+ } else {
AP4_UI32 opf2 = AP4_OMA_DCF_BRAND_OPF2;
ftyp = new AP4_FtypAtom(AP4_FTYP_BRAND_ISOM, 0, &opf2, 1);
}
-
+
// insert the ftyp atom as the first child
return top_level.AddChild(ftyp, 0);
}
@@ -1126,79 +1054,73 @@ AP4_OmaDcfEncryptingProcessor::Initialize(AP4_AtomParent& top_l
/*----------------------------------------------------------------------
| AP4_OmaDcfEncryptingProcessor:CreateTrackHandler
+---------------------------------------------------------------------*/
-AP4_Processor::TrackHandler*
+AP4_Processor::TrackHandler*
AP4_OmaDcfEncryptingProcessor::CreateTrackHandler(AP4_TrakAtom* trak)
{
// find the stsd atom
AP4_StsdAtom* stsd = AP4_DYNAMIC_CAST(AP4_StsdAtom, trak->FindChild("mdia/minf/stbl/stsd"));
// avoid tracks with no stsd atom (should not happen)
- if(stsd == NULL) return NULL;
+ if (stsd == NULL) return NULL;
// only look at the first sample description
AP4_SampleEntry* entry = stsd->GetSampleEntry(0);
- if(entry == NULL) return NULL;
-
+ if (entry == NULL) return NULL;
+
// create a handler for this track if we have a key for it and we know
// how to map the type
const AP4_UI08* key;
const AP4_UI08* iv;
AP4_UI32 format = 0;
- if(AP4_SUCCEEDED(m_KeyMap.GetKeyAndIv(trak->GetId(), key, iv)))
- {
- switch(entry->GetType())
- {
- case AP4_ATOM_TYPE_MP4A:
- format = AP4_ATOM_TYPE_ENCA;
- break;
-
- case AP4_ATOM_TYPE_MP4V:
- case AP4_ATOM_TYPE_AVC1:
- format = AP4_ATOM_TYPE_ENCV;
- break;
-
- default:
- {
- // try to find if this is audio or video
- AP4_HdlrAtom* hdlr = AP4_DYNAMIC_CAST(AP4_HdlrAtom, trak->FindChild("mdia/hdlr"));
- if(hdlr)
- {
- switch(hdlr->GetHandlerType())
- {
- case AP4_HANDLER_TYPE_SOUN:
- format = AP4_ATOM_TYPE_ENCA;
- break;
-
- case AP4_HANDLER_TYPE_VIDE:
- format = AP4_ATOM_TYPE_ENCV;
- break;
+ if (AP4_SUCCEEDED(m_KeyMap.GetKeyAndIv(trak->GetId(), key, iv))) {
+ switch (entry->GetType()) {
+ case AP4_ATOM_TYPE_MP4A:
+ format = AP4_ATOM_TYPE_ENCA;
+ break;
+
+ case AP4_ATOM_TYPE_MP4V:
+ case AP4_ATOM_TYPE_AVC1:
+ format = AP4_ATOM_TYPE_ENCV;
+ break;
+
+ default: {
+ // try to find if this is audio or video
+ AP4_HdlrAtom* hdlr = AP4_DYNAMIC_CAST(AP4_HdlrAtom, trak->FindChild("mdia/hdlr"));
+ if (hdlr) {
+ switch (hdlr->GetHandlerType()) {
+ case AP4_HANDLER_TYPE_SOUN:
+ format = AP4_ATOM_TYPE_ENCA;
+ break;
+
+ case AP4_HANDLER_TYPE_VIDE:
+ format = AP4_ATOM_TYPE_ENCV;
+ break;
+ }
}
+ break;
}
- break;
}
- }
- if(format)
- {
+ if (format) {
const char* content_id = m_PropertyMap.GetProperty(trak->GetId(), "ContentId");
const char* rights_issuer_url = m_PropertyMap.GetProperty(trak->GetId(), "RightsIssuerUrl");
AP4_DataBuffer textual_headers;
AP4_Result result = m_PropertyMap.GetTextualHeaders(trak->GetId(), textual_headers);
- if(AP4_FAILED(result)) textual_headers.SetDataSize(0);
-
+ if (AP4_FAILED(result)) textual_headers.SetDataSize(0);
+
// create the block cipher
AP4_BlockCipher* block_cipher = NULL;
- result = m_BlockCipherFactory->Create(AP4_BlockCipher::AES_128,
- AP4_BlockCipher::ENCRYPT,
- key,
- AP4_CIPHER_BLOCK_SIZE,
+ result = m_BlockCipherFactory->Create(AP4_BlockCipher::AES_128,
+ AP4_BlockCipher::ENCRYPT,
+ key,
+ AP4_CIPHER_BLOCK_SIZE,
block_cipher);
- if(AP4_FAILED(result)) return NULL;
- return new AP4_OmaDcfTrackEncrypter(m_CipherMode,
- block_cipher,
- iv,
- entry,
- format,
- content_id,
+ if (AP4_FAILED(result)) return NULL;
+ return new AP4_OmaDcfTrackEncrypter(m_CipherMode,
+ block_cipher,
+ iv,
+ entry,
+ format,
+ content_id,
rights_issuer_url,
textual_headers.GetData(),
textual_headers.GetDataSize());
diff --git a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4OmaDcf.h b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4OmaDcf.h
index 038296c5c..806f6f0db 100644
--- a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4OmaDcf.h
+++ b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4OmaDcf.h
@@ -51,13 +51,12 @@ class AP4_CtrStreamCipher;
/*----------------------------------------------------------------------
| constants
+---------------------------------------------------------------------*/
-const AP4_UI32 AP4_PROTECTION_SCHEME_TYPE_OMA = AP4_ATOM_TYPE('o', 'd', 'k', 'm');
+const AP4_UI32 AP4_PROTECTION_SCHEME_TYPE_OMA = AP4_ATOM_TYPE('o','d','k','m');
const AP4_UI32 AP4_PROTECTION_SCHEME_VERSION_OMA_20 = 0x00000200;
-const AP4_UI32 AP4_OMA_DCF_BRAND_ODCF = AP4_ATOM_TYPE('o', 'd', 'c', 'f');
-const AP4_UI32 AP4_OMA_DCF_BRAND_OPF2 = AP4_ATOM_TYPE('o', 'p', 'f', '2');
+const AP4_UI32 AP4_OMA_DCF_BRAND_ODCF = AP4_ATOM_TYPE('o','d','c','f');
+const AP4_UI32 AP4_OMA_DCF_BRAND_OPF2 = AP4_ATOM_TYPE('o','p','f','2');
-typedef enum
-{
+typedef enum {
AP4_OMA_DCF_CIPHER_MODE_CTR,
AP4_OMA_DCF_CIPHER_MODE_CBC
} AP4_OmaDcfCipherMode;
@@ -65,11 +64,10 @@ typedef enum
/*----------------------------------------------------------------------
| AP4_OmaDcfAtomDecrypter
+---------------------------------------------------------------------*/
-class AP4_OmaDcfAtomDecrypter
-{
+class AP4_OmaDcfAtomDecrypter {
public:
// class methods
- static AP4_Result DecryptAtoms(AP4_AtomParent& atoms,
+ static AP4_Result DecryptAtoms(AP4_AtomParent& atoms,
AP4_Processor::ProgressListener* listener,
AP4_BlockCipherFactory* block_cipher_factory,
AP4_ProtectionKeyMap& key_map);
@@ -77,22 +75,22 @@ public:
// Returns a byte stream that will produce the decrypted data found
// in the 'odda' child atom of an 'odrm' atom
static AP4_Result CreateDecryptingStream(AP4_ContainerAtom& odrm_atom,
- const AP4_UI08* key,
- AP4_Size key_size,
- AP4_BlockCipherFactory* block_cipher_factory,
- AP4_ByteStream*& stream);
+ const AP4_UI08* key,
+ AP4_Size key_size,
+ AP4_BlockCipherFactory* block_cipher_factory,
+ AP4_ByteStream*& stream);
// Returns a byte stream that will produce the decrypted data from
// an encrypted stream where the IV follows the encrypted bytes.
- // This method is normally not called directly: most callers will call
+ // This method is normally not called directly: most callers will call
// the stream factory that takes an 'odrm' atom as an input parameter
static AP4_Result CreateDecryptingStream(AP4_OmaDcfCipherMode mode,
- AP4_ByteStream& encrypted_stream,
- AP4_LargeSize cleartext_size,
- const AP4_UI08* key,
- AP4_Size key_size,
- AP4_BlockCipherFactory* block_cipher_factory,
- AP4_ByteStream*& stream);
+ AP4_ByteStream& encrypted_stream,
+ AP4_LargeSize cleartext_size,
+ const AP4_UI08* key,
+ AP4_Size key_size,
+ AP4_BlockCipherFactory* block_cipher_factory,
+ AP4_ByteStream*& stream);
};
/*----------------------------------------------------------------------
@@ -102,8 +100,8 @@ class AP4_OmaDcfSampleDecrypter : public AP4_SampleDecrypter
{
public:
// factory
- static AP4_Result Create(AP4_ProtectedSampleDescription* sample_description,
- const AP4_UI08* key,
+ static AP4_Result Create(AP4_ProtectedSampleDescription* sample_description,
+ const AP4_UI08* key,
AP4_Size key_size,
AP4_BlockCipherFactory* block_cipher_factory,
AP4_OmaDcfSampleDecrypter*& cipher);
@@ -168,8 +166,7 @@ private:
/*----------------------------------------------------------------------
| AP4_OmaDcfTrackDecrypter
+---------------------------------------------------------------------*/
-class AP4_OmaDcfTrackDecrypter : public AP4_Processor::TrackHandler
-{
+class AP4_OmaDcfTrackDecrypter : public AP4_Processor::TrackHandler {
public:
// constructor
static AP4_Result Create(const AP4_UI08* key,
@@ -265,12 +262,12 @@ private:
// members
AP4_CbcStreamCipher* m_Cipher;
};
-
+
/*----------------------------------------------------------------------
| AP4_OmaDcfDecryptingProcessor
+---------------------------------------------------------------------*/
/**
- * Use for DCF only, not PDCF. For PDCF, use the
+ * Use for DCF only, not PDCF. For PDCF, use the
* AP4_StandardDecryptingProcessor class
*/
class AP4_OmaDcfDecryptingProcessor : public AP4_Processor
@@ -281,10 +278,7 @@ public:
AP4_BlockCipherFactory* block_cipher_factory = NULL);
// accessors
- AP4_ProtectionKeyMap& GetKeyMap()
- {
- return m_KeyMap;
- }
+ AP4_ProtectionKeyMap& GetKeyMap() { return m_KeyMap; }
// methods
virtual AP4_Result Initialize(AP4_AtomParent& top_level,
@@ -308,14 +302,8 @@ public:
AP4_BlockCipherFactory* block_cipher_factory = NULL);
// accessors
- AP4_ProtectionKeyMap& GetKeyMap()
- {
- return m_KeyMap;
- }
- AP4_TrackPropertyMap& GetPropertyMap()
- {
- return m_PropertyMap;
- }
+ AP4_ProtectionKeyMap& GetKeyMap() { return m_KeyMap; }
+ AP4_TrackPropertyMap& GetPropertyMap() { return m_PropertyMap; }
// AP4_Processor methods
virtual AP4_Result Initialize(AP4_AtomParent& top_level,
diff --git a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4Piff.cpp b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4Piff.cpp
index a400b4073..f442658ff 100644
--- a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4Piff.cpp
+++ b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4Piff.cpp
@@ -49,12 +49,10 @@
/*----------------------------------------------------------------------
| constants
+---------------------------------------------------------------------*/
-AP4_UI08 const AP4_UUID_PIFF_TRACK_ENCRYPTION_ATOM[16] =
-{
+AP4_UI08 const AP4_UUID_PIFF_TRACK_ENCRYPTION_ATOM[16] = {
0x89, 0x74, 0xdb, 0xce, 0x7b, 0xe7, 0x4c, 0x51, 0x84, 0xf9, 0x71, 0x48, 0xf9, 0x88, 0x25, 0x54
};
-AP4_UI08 const AP4_UUID_PIFF_SAMPLE_ENCRYPTION_ATOM[16] =
-{
+AP4_UI08 const AP4_UUID_PIFF_SAMPLE_ENCRYPTION_ATOM[16] = {
0xA2, 0x39, 0x4F, 0x52, 0x5A, 0x9B, 0x4f, 0x14, 0xA2, 0x44, 0x6C, 0x42, 0x7C, 0x64, 0x8D, 0xF4
};
@@ -69,9 +67,9 @@ AP4_PiffCtrSampleEncrypter::AP4_PiffCtrSampleEncrypter(AP4_BlockCipher* block_ci
/*----------------------------------------------------------------------
| AP4_PiffCtrSampleEncrypter::EncryptSampleData
+---------------------------------------------------------------------*/
-AP4_Result
+AP4_Result
AP4_PiffCtrSampleEncrypter::EncryptSampleData(AP4_DataBuffer& /*data_in */,
- AP4_DataBuffer& /*data_out*/)
+ AP4_DataBuffer& /*data_out*/)
{
return AP4_ERROR_NOT_SUPPORTED; // FIXME: not implemented yet
}
@@ -87,9 +85,9 @@ AP4_PiffCtrSampleEncrypter::~AP4_PiffCtrSampleEncrypter()
/*----------------------------------------------------------------------
| AP4_PiffAvcCtrSampleEncrypter::EncryptSampleData
+---------------------------------------------------------------------*/
-AP4_Result
+AP4_Result
AP4_PiffAvcCtrSampleEncrypter::EncryptSampleData(AP4_DataBuffer& /*data_in */,
- AP4_DataBuffer& /*data_out*/)
+ AP4_DataBuffer& /*data_out*/)
{
return AP4_ERROR_NOT_SUPPORTED; // FIXME: not implemented yet
}
@@ -105,9 +103,9 @@ AP4_PiffCbcSampleEncrypter::AP4_PiffCbcSampleEncrypter(AP4_BlockCipher* block_ci
/*----------------------------------------------------------------------
| AP4_PiffCbcSampleEncrypter::EncryptSampleData
+---------------------------------------------------------------------*/
-AP4_Result
+AP4_Result
AP4_PiffCbcSampleEncrypter::EncryptSampleData(AP4_DataBuffer& data_in,
- AP4_DataBuffer& data_out)
+ AP4_DataBuffer& data_out)
{
// the output has the same size as the input
data_out.SetDataSize(data_in.GetDataSize());
@@ -115,28 +113,26 @@ AP4_PiffCbcSampleEncrypter::EncryptSampleData(AP4_DataBuffer& data_in,
// setup direct pointers to the buffers
const AP4_UI08* in = data_in.GetData();
AP4_UI08* out = data_out.UseData();
-
+
// setup the IV
m_Cipher->SetIV(m_Iv);
// process the sample data
- unsigned int block_count = data_in.GetDataSize() / 16;
- if(block_count)
- {
+ unsigned int block_count = data_in.GetDataSize()/16;
+ if (block_count) {
AP4_Size out_size = data_out.GetDataSize();
- AP4_Result result = m_Cipher->ProcessBuffer(in, block_count * 16, out, &out_size, false);
- if(AP4_FAILED(result)) return result;
- in += block_count * 16;
- out += block_count * 16;
-
+ AP4_Result result = m_Cipher->ProcessBuffer(in, block_count*16, out, &out_size, false);
+ if (AP4_FAILED(result)) return result;
+ in += block_count*16;
+ out += block_count*16;
+
// update the IV (last cipherblock emitted)
- AP4_CopyMemory(m_Iv, out - 16, 16);
+ AP4_CopyMemory(m_Iv, out-16, 16);
}
-
+
// any partial block at the end remains in the clear
- unsigned int partial = data_in.GetDataSize() % 16;
- if(partial)
- {
+ unsigned int partial = data_in.GetDataSize()%16;
+ if (partial) {
AP4_CopyMemory(out, in, partial);
}
return AP4_SUCCESS;
@@ -153,66 +149,62 @@ AP4_PiffCbcSampleEncrypter::~AP4_PiffCbcSampleEncrypter()
/*----------------------------------------------------------------------
| AP4_PiffAvcCbcSampleEncrypter::EncryptSampleData
+---------------------------------------------------------------------*/
-AP4_Result
+AP4_Result
AP4_PiffAvcCbcSampleEncrypter::EncryptSampleData(AP4_DataBuffer& data_in,
- AP4_DataBuffer& data_out)
-{
+ AP4_DataBuffer& data_out)
+{
// the output has the same size as the input
data_out.SetDataSize(data_in.GetDataSize());
// check some basics
- if(data_in.GetDataSize() == 0) return AP4_SUCCESS;
+ if (data_in.GetDataSize() == 0) return AP4_SUCCESS;
// setup direct pointers to the buffers
const AP4_UI08* in = data_in.GetData();
AP4_UI08* out = data_out.UseData();
-
+
// setup the IV
m_Cipher->SetIV(m_Iv);
// process the sample data, one NALU at a time
- const AP4_UI08* in_end = data_in.GetData() + data_in.GetDataSize();
- while((AP4_Size)(in_end - in) > 1 + m_NaluLengthSize)
- {
+ const AP4_UI08* in_end = data_in.GetData()+data_in.GetDataSize();
+ while ((AP4_Size)(in_end-in) > 1+m_NaluLengthSize) {
unsigned int nalu_length;
- switch(m_NaluLengthSize)
- {
- case 1:
- nalu_length = *in;
- break;
-
- case 2:
- nalu_length = AP4_BytesToUInt16BE(in);
- break;
-
- case 4:
- nalu_length = AP4_BytesToUInt32BE(in);
- break;
-
- default:
- return AP4_ERROR_INVALID_FORMAT;
+ switch (m_NaluLengthSize) {
+ case 1:
+ nalu_length = *in;
+ break;
+
+ case 2:
+ nalu_length = AP4_BytesToUInt16BE(in);
+ break;
+
+ case 4:
+ nalu_length = AP4_BytesToUInt32BE(in);
+ break;
+
+ default:
+ return AP4_ERROR_INVALID_FORMAT;
}
- unsigned int chunk_size = m_NaluLengthSize + nalu_length;
- unsigned int cleartext_size = chunk_size % 16;
- unsigned int block_count = chunk_size / 16;
- if(cleartext_size < m_NaluLengthSize + 1)
- {
+ unsigned int chunk_size = m_NaluLengthSize+nalu_length;
+ unsigned int cleartext_size = chunk_size%16;
+ unsigned int block_count = chunk_size/16;
+ if (cleartext_size < m_NaluLengthSize+1) {
AP4_ASSERT(block_count);
--block_count;
cleartext_size += 16;
}
-
+
// copy the cleartext portion
AP4_CopyMemory(out, in, cleartext_size);
-
+
// encrypt the rest
- if(block_count)
- {
- AP4_Size out_size = block_count * 16;
- m_Cipher->ProcessBuffer(in + cleartext_size, block_count * 16, out + cleartext_size, &out_size, false);
+ if (block_count) {
+ AP4_Size out_size = block_count*16;
+ m_Cipher->ProcessBuffer(in+cleartext_size, block_count*16, out+cleartext_size, &out_size, false);
}
-
+
// move the pointers
in += chunk_size;
out += chunk_size;
@@ -223,8 +215,7 @@ AP4_PiffAvcCbcSampleEncrypter::EncryptSampleData(AP4_DataBuffer& data_in,
/*----------------------------------------------------------------------
| AP4_PiffTrackEncrypter
+---------------------------------------------------------------------*/
-class AP4_PiffTrackEncrypter : public AP4_Processor::TrackHandler
-{
+class AP4_PiffTrackEncrypter : public AP4_Processor::TrackHandler {
public:
// constructor
AP4_PiffTrackEncrypter(AP4_UI32 default_algorithm_id,
@@ -268,7 +259,7 @@ AP4_PiffTrackEncrypter::AP4_PiffTrackEncrypter(
/*----------------------------------------------------------------------
| AP4_PiffTrackEncrypter::ProcessTrack
+---------------------------------------------------------------------*/
-AP4_Result
+AP4_Result
AP4_PiffTrackEncrypter::ProcessTrack()
{
// sinf container
@@ -276,17 +267,17 @@ AP4_PiffTrackEncrypter::ProcessTrack()
// original format
AP4_FrmaAtom* frma = new AP4_FrmaAtom(m_SampleEntry->GetType());
-
+
// scheme info
AP4_ContainerAtom* schi = new AP4_ContainerAtom(AP4_ATOM_TYPE_SCHI);
- AP4_SchmAtom* schm = new AP4_SchmAtom(AP4_PROTECTION_SCHEME_TYPE_PIFF,
- AP4_PROTECTION_SCHEME_VERSION_PIFF_10);
- AP4_PiffTrackEncryptionAtom* piff_enc =
- new AP4_PiffTrackEncryptionAtom(m_DefaultAlgorithmId,
- m_DefaultIvSize,
+ AP4_SchmAtom* schm = new AP4_SchmAtom(AP4_PROTECTION_SCHEME_TYPE_PIFF,
+ AP4_PROTECTION_SCHEME_VERSION_PIFF_10);
+ AP4_PiffTrackEncryptionAtom* piff_enc =
+ new AP4_PiffTrackEncryptionAtom(m_DefaultAlgorithmId,
+ m_DefaultIvSize,
m_DefaultKid);
schi->AddChild(piff_enc);
-
+
// populate the sinf container
sinf->AddChild(frma);
sinf->AddChild(schm);
@@ -297,14 +288,14 @@ AP4_PiffTrackEncrypter::ProcessTrack()
// change the atom type of the sample description
m_SampleEntry->SetType(m_Format);
-
+
return AP4_SUCCESS;
}
/*----------------------------------------------------------------------
| AP4_PiffTrackEncrypter::ProcessSample
+---------------------------------------------------------------------*/
-AP4_Result
+AP4_Result
AP4_PiffTrackEncrypter::ProcessSample(AP4_DataBuffer& data_in,
AP4_DataBuffer& data_out)
{
@@ -314,8 +305,7 @@ AP4_PiffTrackEncrypter::ProcessSample(AP4_DataBuffer& data_in,
/*----------------------------------------------------------------------
| AP4_PiffFragmentEncrypter
+---------------------------------------------------------------------*/
-class AP4_PiffFragmentEncrypter : public AP4_Processor::FragmentHandler
-{
+class AP4_PiffFragmentEncrypter : public AP4_Processor::FragmentHandler {
public:
// constructor
AP4_PiffFragmentEncrypter(AP4_ContainerAtom* traf,
@@ -339,7 +329,7 @@ private:
| AP4_PiffFragmentEncrypter::AP4_PiffFragmentEncrypter
+---------------------------------------------------------------------*/
AP4_PiffFragmentEncrypter::AP4_PiffFragmentEncrypter(AP4_ContainerAtom* traf,
- AP4_PiffEncryptingProcessor::Encrypter* encrypter) :
+ AP4_PiffEncryptingProcessor::Encrypter* encrypter) :
m_Traf(traf),
m_SampleEncryptionAtom(NULL),
m_Encrypter(encrypter),
@@ -350,39 +340,36 @@ AP4_PiffFragmentEncrypter::AP4_PiffFragmentEncrypter(AP4_ContainerAtom*
/*----------------------------------------------------------------------
| AP4_PiffFragmentEncrypter::ProcessFragment
+---------------------------------------------------------------------*/
-AP4_Result
+AP4_Result
AP4_PiffFragmentEncrypter::ProcessFragment()
{
// count the number of samples and create IVs
unsigned int sample_count = 0;
- for(AP4_List<AP4_Atom>::Item* item = m_Traf->GetChildren().FirstItem();
- item;
- item = item->GetNext())
- {
+ for (AP4_List<AP4_Atom>::Item* item = m_Traf->GetChildren().FirstItem();
+ item;
+ item = item->GetNext()) {
AP4_Atom* child = item->GetData();
- if(child->GetType() == AP4_ATOM_TYPE_TRUN)
- {
+ if (child->GetType() == AP4_ATOM_TYPE_TRUN) {
AP4_TrunAtom* trun = AP4_DYNAMIC_CAST(AP4_TrunAtom, child);
- if(trun)
- {
+ if (trun) {
sample_count += trun->GetEntries().ItemCount();
}
}
}
-
+
// create a sample encryption atom
m_SampleEncryptionAtom = new AP4_PiffSampleEncryptionAtom(sample_count);
// add the atom to the traf container
m_Traf->AddChild(m_SampleEncryptionAtom);
-
+
return AP4_SUCCESS;
}
/*----------------------------------------------------------------------
| AP4_PiffFragmentEncrypter::FinishFragment
+---------------------------------------------------------------------*/
-AP4_Result
+AP4_Result
AP4_PiffFragmentEncrypter::FinishFragment()
{
return AP4_SUCCESS;
@@ -391,13 +378,13 @@ AP4_PiffFragmentEncrypter::FinishFragment()
/*----------------------------------------------------------------------
| AP4_PiffFragmentEncrypter::ProcessSample
+---------------------------------------------------------------------*/
-AP4_Result
+AP4_Result
AP4_PiffFragmentEncrypter::ProcessSample(AP4_DataBuffer& data_in,
- AP4_DataBuffer& data_out)
+ AP4_DataBuffer& data_out)
{
// store the IV for this sample
m_SampleEncryptionAtom->SetIv(m_IvIndex++, m_Encrypter->m_SampleEncrypter->GetIv());
-
+
// encrypt the sample
AP4_Result result = m_Encrypter->m_SampleEncrypter->EncryptSampleData(data_in, data_out);
return result;
@@ -407,16 +394,13 @@ AP4_PiffFragmentEncrypter::ProcessSample(AP4_DataBuffer& data_in,
| AP4_PiffEncryptingProcessor:AP4_PiffEncryptingProcessor
+---------------------------------------------------------------------*/
AP4_PiffEncryptingProcessor::AP4_PiffEncryptingProcessor(AP4_PiffCipherMode cipher_mode,
- AP4_BlockCipherFactory* block_cipher_factory) :
+ AP4_BlockCipherFactory* block_cipher_factory) :
m_CipherMode(cipher_mode)
{
// create a block cipher factory if none is given
- if(block_cipher_factory == NULL)
- {
+ if (block_cipher_factory == NULL) {
m_BlockCipherFactory = &AP4_DefaultBlockCipherFactory::Instance;
- }
- else
- {
+ } else {
m_BlockCipherFactory = block_cipher_factory;
}
}
@@ -432,45 +416,40 @@ AP4_PiffEncryptingProcessor::~AP4_PiffEncryptingProcessor()
/*----------------------------------------------------------------------
| AP4_PiffEncryptingProcessor::Initialize
+---------------------------------------------------------------------*/
-AP4_Result
+AP4_Result
AP4_PiffEncryptingProcessor::Initialize(AP4_AtomParent& top_level,
AP4_ByteStream& /*stream*/,
AP4_Processor::ProgressListener* /*listener*/)
{
AP4_FtypAtom* ftyp = AP4_DYNAMIC_CAST(AP4_FtypAtom, top_level.GetChild(AP4_ATOM_TYPE_FTYP));
- if(ftyp)
- {
+ if (ftyp) {
// remove the atom, it will be replaced with a new one
top_level.RemoveChild(ftyp);
-
+
// keep the existing brand and compatible brands
AP4_Array<AP4_UI32> compatible_brands;
- compatible_brands.EnsureCapacity(ftyp->GetCompatibleBrands().ItemCount() + 1);
- for(unsigned int i = 0; i < ftyp->GetCompatibleBrands().ItemCount(); i++)
- {
+ compatible_brands.EnsureCapacity(ftyp->GetCompatibleBrands().ItemCount()+1);
+ for (unsigned int i=0; i<ftyp->GetCompatibleBrands().ItemCount(); i++) {
compatible_brands.Append(ftyp->GetCompatibleBrands()[i]);
}
-
+
// add the OMA compatible brand if it is not already there
- if(!ftyp->HasCompatibleBrand(AP4_PIFF_BRAND))
- {
+ if (!ftyp->HasCompatibleBrand(AP4_PIFF_BRAND)) {
compatible_brands.Append(AP4_PIFF_BRAND);
}
// create a replacement
AP4_FtypAtom* new_ftyp = new AP4_FtypAtom(ftyp->GetMajorBrand(),
- ftyp->GetMinorVersion(),
- &compatible_brands[0],
- compatible_brands.ItemCount());
+ ftyp->GetMinorVersion(),
+ &compatible_brands[0],
+ compatible_brands.ItemCount());
delete ftyp;
ftyp = new_ftyp;
- }
- else
- {
+ } else {
AP4_UI32 piff = AP4_PIFF_BRAND;
ftyp = new AP4_FtypAtom(AP4_FTYP_BRAND_ISOM, 0, &piff, 1);
}
-
+
// insert the ftyp atom as the first child
return top_level.AddChild(ftyp, 0);
}
@@ -478,116 +457,103 @@ AP4_PiffEncryptingProcessor::Initialize(AP4_AtomParent& top_lev
/*----------------------------------------------------------------------
| AP4_PiffEncryptingProcessor:CreateTrackHandler
+---------------------------------------------------------------------*/
-AP4_Processor::TrackHandler*
+AP4_Processor::TrackHandler*
AP4_PiffEncryptingProcessor::CreateTrackHandler(AP4_TrakAtom* trak)
{
// find the stsd atom
AP4_StsdAtom* stsd = AP4_DYNAMIC_CAST(AP4_StsdAtom, trak->FindChild("mdia/minf/stbl/stsd"));
// avoid tracks with no stsd atom (should not happen)
- if(stsd == NULL) return NULL;
+ if (stsd == NULL) return NULL;
// only look at the first sample description
AP4_SampleEntry* entry = stsd->GetSampleEntry(0);
- if(entry == NULL) return NULL;
-
+ if (entry == NULL) return NULL;
+
// create a handler for this track if we have a key for it and we know
// how to map the type
const AP4_UI08* key;
const AP4_UI08* iv;
- if(AP4_FAILED(m_KeyMap.GetKeyAndIv(trak->GetId(), key, iv)))
- {
+ if (AP4_FAILED(m_KeyMap.GetKeyAndIv(trak->GetId(), key, iv))) {
return NULL;
}
-
+
AP4_UI32 format = 0;
- switch(entry->GetType())
- {
- case AP4_ATOM_TYPE_MP4A:
- format = AP4_ATOM_TYPE_ENCA;
- break;
-
- case AP4_ATOM_TYPE_MP4V:
- case AP4_ATOM_TYPE_AVC1:
- format = AP4_ATOM_TYPE_ENCV;
- break;
-
- default:
- {
- // try to find if this is audio or video
- AP4_HdlrAtom* hdlr = AP4_DYNAMIC_CAST(AP4_HdlrAtom, trak->FindChild("mdia/hdlr"));
- if(hdlr)
- {
- switch(hdlr->GetHandlerType())
- {
- case AP4_HANDLER_TYPE_SOUN:
- format = AP4_ATOM_TYPE_ENCA;
- break;
+ switch (entry->GetType()) {
+ case AP4_ATOM_TYPE_MP4A:
+ format = AP4_ATOM_TYPE_ENCA;
+ break;
- case AP4_HANDLER_TYPE_VIDE:
- format = AP4_ATOM_TYPE_ENCV;
- break;
+ case AP4_ATOM_TYPE_MP4V:
+ case AP4_ATOM_TYPE_AVC1:
+ format = AP4_ATOM_TYPE_ENCV;
+ break;
+
+ default: {
+ // try to find if this is audio or video
+ AP4_HdlrAtom* hdlr = AP4_DYNAMIC_CAST(AP4_HdlrAtom, trak->FindChild("mdia/hdlr"));
+ if (hdlr) {
+ switch (hdlr->GetHandlerType()) {
+ case AP4_HANDLER_TYPE_SOUN:
+ format = AP4_ATOM_TYPE_ENCA;
+ break;
+
+ case AP4_HANDLER_TYPE_VIDE:
+ format = AP4_ATOM_TYPE_ENCV;
+ break;
+ }
}
+ break;
}
- break;
}
- }
- if(format == 0) return NULL;
-
+ if (format == 0) return NULL;
+
// get the track properties
- AP4_UI08 kid[16] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
+ AP4_UI08 kid[16] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
const char* kid_hex = m_PropertyMap.GetProperty(trak->GetId(), "KID");
- if(kid_hex && AP4_StringLength(kid_hex) == 32)
- {
+ if (kid_hex && AP4_StringLength(kid_hex) == 32) {
AP4_ParseHex(kid_hex, kid, 16);
}
-
+
// create the encrypter
AP4_Processor::TrackHandler* track_encrypter;
- track_encrypter = new AP4_PiffTrackEncrypter(m_CipherMode == AP4_PIFF_CIPHER_MODE_CBC ? AP4_PIFF_ALGORITHM_ID_CBC : AP4_PIFF_ALGORITHM_ID_CTR,
- 16,
- kid,
- entry,
- format);
-
+ track_encrypter = new AP4_PiffTrackEncrypter(m_CipherMode == AP4_PIFF_CIPHER_MODE_CBC?AP4_PIFF_ALGORITHM_ID_CBC:AP4_PIFF_ALGORITHM_ID_CTR,
+ 16,
+ kid,
+ entry,
+ format);
+
// create a block cipher
AP4_BlockCipher* block_cipher = NULL;
- AP4_Result result = m_BlockCipherFactory->Create(AP4_BlockCipher::AES_128,
- AP4_BlockCipher::ENCRYPT,
- key,
- 16,
- block_cipher);
- if(AP4_FAILED(result)) return NULL;
-
+ AP4_Result result = m_BlockCipherFactory->Create(AP4_BlockCipher::AES_128,
+ AP4_BlockCipher::ENCRYPT,
+ key,
+ 16,
+ block_cipher);
+ if (AP4_FAILED(result)) return NULL;
+
// add a new cipher state for this track
AP4_PiffSampleEncrypter* sample_encrypter = NULL;
- switch(m_CipherMode)
- {
- case AP4_PIFF_CIPHER_MODE_CBC:
- if(entry->GetType() == AP4_ATOM_TYPE_AVC1)
- {
- AP4_AvccAtom* avcc = AP4_DYNAMIC_CAST(AP4_AvccAtom, entry->GetChild(AP4_ATOM_TYPE_AVCC));
- if(avcc == NULL) return NULL;
- sample_encrypter = new AP4_PiffAvcCbcSampleEncrypter(block_cipher, avcc->GetNaluLengthSize());
- }
- else
- {
- sample_encrypter = new AP4_PiffCbcSampleEncrypter(block_cipher);
- }
- break;
-
- case AP4_PIFF_CIPHER_MODE_CTR:
- if(entry->GetType() == AP4_ATOM_TYPE_AVC1)
- {
- AP4_AvccAtom* avcc = AP4_DYNAMIC_CAST(AP4_AvccAtom, entry->GetChild(AP4_ATOM_TYPE_AVCC));
- if(avcc == NULL) return NULL;
- sample_encrypter = new AP4_PiffAvcCtrSampleEncrypter(block_cipher, avcc->GetNaluLengthSize());
- }
- else
- {
- sample_encrypter = new AP4_PiffCtrSampleEncrypter(block_cipher);
- }
- break;
+ switch (m_CipherMode) {
+ case AP4_PIFF_CIPHER_MODE_CBC:
+ if (entry->GetType() == AP4_ATOM_TYPE_AVC1) {
+ AP4_AvccAtom* avcc = AP4_DYNAMIC_CAST(AP4_AvccAtom, entry->GetChild(AP4_ATOM_TYPE_AVCC));
+ if (avcc == NULL) return NULL;
+ sample_encrypter = new AP4_PiffAvcCbcSampleEncrypter(block_cipher, avcc->GetNaluLengthSize());
+ } else {
+ sample_encrypter = new AP4_PiffCbcSampleEncrypter(block_cipher);
+ }
+ break;
+
+ case AP4_PIFF_CIPHER_MODE_CTR:
+ if (entry->GetType() == AP4_ATOM_TYPE_AVC1) {
+ AP4_AvccAtom* avcc = AP4_DYNAMIC_CAST(AP4_AvccAtom, entry->GetChild(AP4_ATOM_TYPE_AVCC));
+ if (avcc == NULL) return NULL;
+ sample_encrypter = new AP4_PiffAvcCtrSampleEncrypter(block_cipher, avcc->GetNaluLengthSize());
+ } else {
+ sample_encrypter = new AP4_PiffCtrSampleEncrypter(block_cipher);
+ }
+ break;
}
sample_encrypter->SetIv(iv);
m_Encrypters.Add(new Encrypter(trak->GetId(), sample_encrypter));
@@ -598,184 +564,160 @@ AP4_PiffEncryptingProcessor::CreateTrackHandler(AP4_TrakAtom* trak)
/*----------------------------------------------------------------------
| AP4_PiffEncryptingProcessor:CreateFragmentHandler
+---------------------------------------------------------------------*/
-AP4_Processor::FragmentHandler*
+AP4_Processor::FragmentHandler*
AP4_PiffEncryptingProcessor::CreateFragmentHandler(AP4_ContainerAtom* traf)
{
// get the traf header (tfhd) for this track fragment so we can get the track ID
AP4_TfhdAtom* tfhd = AP4_DYNAMIC_CAST(AP4_TfhdAtom, traf->GetChild(AP4_ATOM_TYPE_TFHD));
- if(tfhd == NULL) return NULL;
-
+ if (tfhd == NULL) return NULL;
+
// lookup the encrypter for this track
Encrypter* encrypter = NULL;
- for(AP4_List<Encrypter>::Item* item = m_Encrypters.FirstItem();
- item;
- item = item->GetNext())
- {
- if(item->GetData()->m_TrackId == tfhd->GetTrackId())
- {
+ for (AP4_List<Encrypter>::Item* item = m_Encrypters.FirstItem();
+ item;
+ item = item->GetNext()) {
+ if (item->GetData()->m_TrackId == tfhd->GetTrackId()) {
encrypter = item->GetData();
break;
}
}
- if(encrypter == NULL) return NULL;
+ if (encrypter == NULL) return NULL;
return new AP4_PiffFragmentEncrypter(traf, encrypter);
}
/*----------------------------------------------------------------------
| AP4_PiffSampleDecrypter::Create
+---------------------------------------------------------------------*/
-AP4_Result
-AP4_PiffSampleDecrypter::Create(AP4_ProtectedSampleDescription* sample_description,
+AP4_Result
+AP4_PiffSampleDecrypter::Create(AP4_ProtectedSampleDescription* sample_description,
AP4_ContainerAtom* traf,
- const AP4_UI08* key,
+ const AP4_UI08* key,
AP4_Size key_size,
AP4_BlockCipherFactory* block_cipher_factory,
AP4_PiffSampleDecrypter*& decrypter)
{
// check the parameters
- if(key == NULL || block_cipher_factory == NULL)
- {
+ if (key == NULL || block_cipher_factory == NULL) {
return AP4_ERROR_INVALID_PARAMETERS;
}
// default return value
decrypter = NULL;
-
- // check the sample description
- if(sample_description->GetSchemeType() != AP4_PROTECTION_SCHEME_TYPE_PIFF)
- {
+
+ // check the sample description
+ if (sample_description->GetSchemeType() != AP4_PROTECTION_SCHEME_TYPE_PIFF) {
return AP4_ERROR_INVALID_PARAMETERS;
}
-
+
// get the scheme info atom
AP4_ContainerAtom* schi = sample_description->GetSchemeInfo()->GetSchiAtom();
- if(schi == NULL) return AP4_ERROR_INVALID_FORMAT;
+ if (schi == NULL) return AP4_ERROR_INVALID_FORMAT;
// look for a track encryption atom
- AP4_PiffTrackEncryptionAtom* track_encryption_atom =
+ AP4_PiffTrackEncryptionAtom* track_encryption_atom =
AP4_DYNAMIC_CAST(AP4_PiffTrackEncryptionAtom, schi->GetChild(AP4_UUID_PIFF_TRACK_ENCRYPTION_ATOM));
-
+
// look for a sample encryption atom
AP4_PiffSampleEncryptionAtom* sample_encryption_atom = NULL;
- if(traf)
- {
+ if (traf) {
sample_encryption_atom = AP4_DYNAMIC_CAST(AP4_PiffSampleEncryptionAtom, traf->GetChild(AP4_UUID_PIFF_SAMPLE_ENCRYPTION_ATOM));
- if(sample_encryption_atom == NULL) return AP4_ERROR_INVALID_FORMAT;
+ if (sample_encryption_atom == NULL) return AP4_ERROR_INVALID_FORMAT;
}
// create the block cipher needed to decrypt the samples
AP4_UI32 algorithm_id;
unsigned int iv_size;
- if(sample_encryption_atom &&
- sample_encryption_atom->GetFlags() & AP4_PIFF_SAMPLE_ENCRYPTION_FLAG_OVERRIDE_TRACK_ENCRYPTION_DEFAULTS)
- {
+ if (sample_encryption_atom &&
+ sample_encryption_atom->GetFlags() & AP4_PIFF_SAMPLE_ENCRYPTION_FLAG_OVERRIDE_TRACK_ENCRYPTION_DEFAULTS) {
algorithm_id = sample_encryption_atom->GetAlgorithmId();
iv_size = sample_encryption_atom->GetIvSize();
- }
- else
- {
- if(track_encryption_atom == NULL) return AP4_ERROR_INVALID_FORMAT;
+ } else {
+ if (track_encryption_atom == NULL) return AP4_ERROR_INVALID_FORMAT;
algorithm_id = track_encryption_atom->GetDefaultAlgorithmId();
iv_size = track_encryption_atom->GetDefaultIvSize();
}
- switch(algorithm_id)
- {
- case AP4_PIFF_ALGORITHM_ID_NONE:
- decrypter = new AP4_PiffNullSampleDecrypter();
- break;
-
- case AP4_PIFF_ALGORITHM_ID_CTR:
- if(iv_size != 8 && iv_size != 16)
- {
- return AP4_ERROR_INVALID_FORMAT;
- }
- else
- {
- // create the block cipher
- AP4_BlockCipher* block_cipher = NULL;
- AP4_Result result = block_cipher_factory->Create(AP4_BlockCipher::AES_128,
- AP4_BlockCipher::ENCRYPT,
- key,
- key_size,
- block_cipher);
- if(AP4_FAILED(result)) return result;
-
- // create the decrypter
- if(sample_description->GetOriginalFormat() == AP4_ATOM_TYPE_AVC1)
- {
- AP4_AvcSampleDescription* avc_desc = AP4_DYNAMIC_CAST(AP4_AvcSampleDescription, sample_description->GetOriginalSampleDescription());
- if(avc_desc == NULL)
- {
- return AP4_ERROR_INVALID_FORMAT;
+ switch (algorithm_id) {
+ case AP4_PIFF_ALGORITHM_ID_NONE:
+ decrypter = new AP4_PiffNullSampleDecrypter();
+ break;
+
+ case AP4_PIFF_ALGORITHM_ID_CTR:
+ if (iv_size != 8 && iv_size != 16) {
+ return AP4_ERROR_INVALID_FORMAT;
+ } else {
+ // create the block cipher
+ AP4_BlockCipher* block_cipher = NULL;
+ AP4_Result result = block_cipher_factory->Create(AP4_BlockCipher::AES_128,
+ AP4_BlockCipher::ENCRYPT,
+ key,
+ key_size,
+ block_cipher);
+ if (AP4_FAILED(result)) return result;
+
+ // create the decrypter
+ if (sample_description->GetOriginalFormat() == AP4_ATOM_TYPE_AVC1) {
+ AP4_AvcSampleDescription* avc_desc = AP4_DYNAMIC_CAST(AP4_AvcSampleDescription, sample_description->GetOriginalSampleDescription());
+ if (avc_desc == NULL) {
+ return AP4_ERROR_INVALID_FORMAT;
+ }
+ decrypter = new AP4_PiffAvcCbcSampleDecrypter(block_cipher,
+ sample_encryption_atom,
+ avc_desc->GetNaluLengthSize());
+
+ } else {
+ decrypter = new AP4_PiffCbcSampleDecrypter(block_cipher,
+ sample_encryption_atom);
}
- decrypter = new AP4_PiffAvcCbcSampleDecrypter(block_cipher,
- sample_encryption_atom,
- avc_desc->GetNaluLengthSize());
-
}
- else
- {
- decrypter = new AP4_PiffCbcSampleDecrypter(block_cipher,
- sample_encryption_atom);
- }
- }
- break;
-
- case AP4_PIFF_ALGORITHM_ID_CBC:
- if(iv_size != 16)
- {
- return AP4_ERROR_INVALID_FORMAT;
- }
- else
- {
- // create the block cipher
- AP4_BlockCipher* block_cipher = NULL;
- AP4_Result result = block_cipher_factory->Create(AP4_BlockCipher::AES_128,
- AP4_BlockCipher::DECRYPT,
- key,
- key_size,
- block_cipher);
- if(AP4_FAILED(result)) return result;
-
- // create the decrypter
- if(sample_description->GetOriginalFormat() == AP4_ATOM_TYPE_AVC1)
- {
- AP4_AvcSampleDescription* avc_desc = AP4_DYNAMIC_CAST(AP4_AvcSampleDescription, sample_description->GetOriginalSampleDescription());
- if(avc_desc == NULL)
- {
- return AP4_ERROR_INVALID_FORMAT;
+ break;
+
+ case AP4_PIFF_ALGORITHM_ID_CBC:
+ if (iv_size != 16) {
+ return AP4_ERROR_INVALID_FORMAT;
+ } else {
+ // create the block cipher
+ AP4_BlockCipher* block_cipher = NULL;
+ AP4_Result result = block_cipher_factory->Create(AP4_BlockCipher::AES_128,
+ AP4_BlockCipher::DECRYPT,
+ key,
+ key_size,
+ block_cipher);
+ if (AP4_FAILED(result)) return result;
+
+ // create the decrypter
+ if (sample_description->GetOriginalFormat() == AP4_ATOM_TYPE_AVC1) {
+ AP4_AvcSampleDescription* avc_desc = AP4_DYNAMIC_CAST(AP4_AvcSampleDescription, sample_description->GetOriginalSampleDescription());
+ if (avc_desc == NULL) {
+ return AP4_ERROR_INVALID_FORMAT;
+ }
+ decrypter = new AP4_PiffAvcCbcSampleDecrypter(block_cipher,
+ sample_encryption_atom,
+ avc_desc->GetNaluLengthSize());
+ } else {
+ decrypter = new AP4_PiffCbcSampleDecrypter(block_cipher,
+ sample_encryption_atom);
}
- decrypter = new AP4_PiffAvcCbcSampleDecrypter(block_cipher,
- sample_encryption_atom,
- avc_desc->GetNaluLengthSize());
}
- else
- {
- decrypter = new AP4_PiffCbcSampleDecrypter(block_cipher,
- sample_encryption_atom);
- }
- }
- break;
-
- default:
- return AP4_ERROR_NOT_SUPPORTED;
+ break;
+
+ default:
+ return AP4_ERROR_NOT_SUPPORTED;
}
return AP4_SUCCESS;
}
-
+
/*----------------------------------------------------------------------
| AP4_PiffSampleDecrypter::SetSampleIndex
+---------------------------------------------------------------------*/
-AP4_Result
+AP4_Result
AP4_PiffSampleDecrypter::SetSampleIndex(AP4_Ordinal sample_index)
{
- if(sample_index < m_SampleEncryptionAtom->GetIvCount())
- {
+ if (sample_index < m_SampleEncryptionAtom->GetIvCount()) {
return AP4_ERROR_OUT_OF_RANGE;
}
m_SampleIndex = sample_index;
-
+
return AP4_SUCCESS;
}
@@ -803,10 +745,10 @@ AP4_PiffCtrSampleDecrypter::~AP4_PiffCtrSampleDecrypter()
/*----------------------------------------------------------------------
| AP4_PiffCtrSampleDecrypter::DecryptSampleData
+---------------------------------------------------------------------*/
-AP4_Result
+AP4_Result
AP4_PiffCtrSampleDecrypter::DecryptSampleData(AP4_DataBuffer& /*data_in */,
- AP4_DataBuffer& /*data_out*/,
- const AP4_UI08* /*iv */)
+ AP4_DataBuffer& /*data_out*/,
+ const AP4_UI08* /*iv */)
{
return AP4_ERROR_NOT_SUPPORTED; // FIXME: not implemented yet
}
@@ -814,10 +756,10 @@ AP4_PiffCtrSampleDecrypter::DecryptSampleData(AP4_DataBuffer& /*data_in */,
/*----------------------------------------------------------------------
| AP4_PiffAvcCtrSampleDecrypter::DecryptSampleData
+---------------------------------------------------------------------*/
-AP4_Result
+AP4_Result
AP4_PiffAvcCtrSampleDecrypter::DecryptSampleData(AP4_DataBuffer& /*data_in */,
- AP4_DataBuffer& /*data_out*/,
- const AP4_UI08* /*iv */)
+ AP4_DataBuffer& /*data_out*/,
+ const AP4_UI08* /*iv */)
{
return AP4_ERROR_NOT_SUPPORTED; // FIXME: not implemented yet
}
@@ -844,10 +786,10 @@ AP4_PiffCbcSampleDecrypter::~AP4_PiffCbcSampleDecrypter()
/*----------------------------------------------------------------------
| AP4_PiffCbcSampleDecrypter::DecryptSampleData
+---------------------------------------------------------------------*/
-AP4_Result
+AP4_Result
AP4_PiffCbcSampleDecrypter::DecryptSampleData(AP4_DataBuffer& data_in,
- AP4_DataBuffer& data_out,
- const AP4_UI08* iv)
+ AP4_DataBuffer& data_out,
+ const AP4_UI08* iv)
{
// the output has the same size as the input
data_out.SetDataSize(data_in.GetDataSize());
@@ -857,46 +799,43 @@ AP4_PiffCbcSampleDecrypter::DecryptSampleData(AP4_DataBuffer& data_in,
AP4_UI08* out = data_out.UseData();
// setup the IV
- if(iv == NULL)
- {
- if(m_SampleEncryptionAtom == NULL) return AP4_ERROR_INVALID_PARAMETERS;
+ if (iv == NULL) {
+ if (m_SampleEncryptionAtom == NULL) return AP4_ERROR_INVALID_PARAMETERS;
iv = m_SampleEncryptionAtom->GetIv(m_SampleIndex);
- if(iv == NULL) return AP4_ERROR_INVALID_FORMAT;
+ if (iv == NULL) return AP4_ERROR_INVALID_FORMAT;
}
m_Cipher->SetIV(iv);
-
+
// process the sample data
- unsigned int block_count = data_in.GetDataSize() / 16;
- if(block_count)
- {
+ unsigned int block_count = data_in.GetDataSize()/16;
+ if (block_count) {
AP4_Size out_size = data_out.GetDataSize();
- AP4_Result result = m_Cipher->ProcessBuffer(in, block_count * 16, out, &out_size, false);
- if(AP4_FAILED(result)) return result;
- AP4_ASSERT(out_size == block_count * 16);
- in += block_count * 16;
- out += block_count * 16;
+ AP4_Result result = m_Cipher->ProcessBuffer(in, block_count*16, out, &out_size, false);
+ if (AP4_FAILED(result)) return result;
+ AP4_ASSERT(out_size == block_count*16);
+ in += block_count*16;
+ out += block_count*16;
}
-
+
// any partial block at the end remains in the clear
- unsigned int partial = data_in.GetDataSize() % 16;
- if(partial)
- {
+ unsigned int partial = data_in.GetDataSize()%16;
+ if (partial) {
AP4_CopyMemory(out, in, partial);
}
-
+
// move on to the next sample
++m_SampleIndex;
-
+
return AP4_SUCCESS;
}
/*----------------------------------------------------------------------
| AP4_PiffAvcCbcSampleDecrypter::DecryptSampleData
+---------------------------------------------------------------------*/
-AP4_Result
+AP4_Result
AP4_PiffAvcCbcSampleDecrypter::DecryptSampleData(AP4_DataBuffer& data_in,
- AP4_DataBuffer& data_out,
- const AP4_UI08* iv)
+ AP4_DataBuffer& data_out,
+ const AP4_UI08* iv)
{
// the output has the same size as the input
data_out.SetDataSize(data_in.GetDataSize());
@@ -906,103 +845,98 @@ AP4_PiffAvcCbcSampleDecrypter::DecryptSampleData(AP4_DataBuffer& data_in,
AP4_UI08* out = data_out.UseData();
// setup the IV
- if(iv == NULL)
- {
- if(m_SampleEncryptionAtom == NULL) return AP4_ERROR_INVALID_PARAMETERS;
+ if (iv == NULL) {
+ if (m_SampleEncryptionAtom == NULL) return AP4_ERROR_INVALID_PARAMETERS;
iv = m_SampleEncryptionAtom->GetIv(m_SampleIndex);
- if(iv == NULL) return AP4_ERROR_INVALID_FORMAT;
+ if (iv == NULL) return AP4_ERROR_INVALID_FORMAT;
}
m_Cipher->SetIV(iv);
// process the sample data, one NALU at a time
- const AP4_UI08* in_end = data_in.GetData() + data_in.GetDataSize();
- while((AP4_Size)(in_end - in) > 1 + m_NaluLengthSize)
- {
+ const AP4_UI08* in_end = data_in.GetData()+data_in.GetDataSize();
+ while ((AP4_Size)(in_end-in) > 1+m_NaluLengthSize) {
unsigned int nalu_length;
- switch(m_NaluLengthSize)
- {
- case 1:
- nalu_length = *in;
- break;
-
- case 2:
- nalu_length = AP4_BytesToUInt16BE(in);
- break;
-
- case 4:
- nalu_length = AP4_BytesToUInt32BE(in);
- break;
-
- default:
- return AP4_ERROR_INVALID_FORMAT;
+ switch (m_NaluLengthSize) {
+ case 1:
+ nalu_length = *in;
+ break;
+
+ case 2:
+ nalu_length = AP4_BytesToUInt16BE(in);
+ break;
+
+ case 4:
+ nalu_length = AP4_BytesToUInt32BE(in);
+ break;
+
+ default:
+ return AP4_ERROR_INVALID_FORMAT;
}
- unsigned int chunk_size = m_NaluLengthSize + nalu_length;
- unsigned int cleartext_size = chunk_size % 16;
- unsigned int block_count = chunk_size / 16;
- if(cleartext_size < m_NaluLengthSize + 1)
- {
+ unsigned int chunk_size = m_NaluLengthSize+nalu_length;
+ unsigned int cleartext_size = chunk_size%16;
+ unsigned int block_count = chunk_size/16;
+ if (cleartext_size < m_NaluLengthSize+1) {
AP4_ASSERT(block_count);
--block_count;
cleartext_size += 16;
}
-
+
// copy the cleartext portion
AP4_CopyMemory(out, in, cleartext_size);
-
+
// encrypt the rest
- if(block_count)
- {
- AP4_Size out_size = block_count * 16;
- m_Cipher->ProcessBuffer(in + cleartext_size, block_count * 16, out + cleartext_size, &out_size, false);
+ if (block_count) {
+ AP4_Size out_size = block_count*16;
+ m_Cipher->ProcessBuffer(in+cleartext_size, block_count*16, out+cleartext_size, &out_size, false);
}
-
+
// move the pointers
in += chunk_size;
out += chunk_size;
}
-
+
// move on to the next sample
++m_SampleIndex;
-
+
return AP4_SUCCESS;
}
/*----------------------------------------------------------------------
| AP4_PiffTrackEncryptionAtom::Create
+---------------------------------------------------------------------*/
-AP4_PiffTrackEncryptionAtom*
+AP4_PiffTrackEncryptionAtom*
AP4_PiffTrackEncryptionAtom::Create(AP4_Size size, AP4_ByteStream& stream)
{
AP4_UI32 version = 0;
AP4_UI32 flags = 0;
AP4_Result result = ReadFullHeader(stream, version, flags);
- if(AP4_FAILED(result)) return NULL;
- if(version != 0) return NULL;
+ if (AP4_FAILED(result)) return NULL;
+ if (version != 0) return NULL;
return new AP4_PiffTrackEncryptionAtom(size, version, flags, stream);
}
/*----------------------------------------------------------------------
| AP4_PiffTrackEncryptionAtom::AP4_PiffTrackEncryptionAtom
+---------------------------------------------------------------------*/
-AP4_PiffTrackEncryptionAtom::AP4_PiffTrackEncryptionAtom(AP4_UI32 size,
- AP4_UI32 version,
- AP4_UI32 flags,
- AP4_ByteStream& stream) :
+AP4_PiffTrackEncryptionAtom::AP4_PiffTrackEncryptionAtom(AP4_UI32 size,
+ AP4_UI32 version,
+ AP4_UI32 flags,
+ AP4_ByteStream& stream) :
AP4_UuidAtom(size, AP4_UUID_PIFF_TRACK_ENCRYPTION_ATOM, version, flags)
{
stream.ReadUI24(m_DefaultAlgorithmId);
stream.ReadUI08(m_DefaultIvSize);
- stream.Read(m_DefaultKid, 16);
+ stream.Read (m_DefaultKid, 16);
}
/*----------------------------------------------------------------------
| AP4_PiffTrackEncryptionAtom::AP4_PiffTrackEncryptionAtom
+---------------------------------------------------------------------*/
AP4_PiffTrackEncryptionAtom::AP4_PiffTrackEncryptionAtom(AP4_UI32 default_algorithm_id,
- AP4_UI08 default_iv_size,
- const AP4_UI08* default_kid) :
- AP4_UuidAtom(AP4_FULL_UUID_ATOM_HEADER_SIZE + 20, AP4_UUID_PIFF_TRACK_ENCRYPTION_ATOM, 0, 0),
+ AP4_UI08 default_iv_size,
+ const AP4_UI08* default_kid) :
+ AP4_UuidAtom(AP4_FULL_UUID_ATOM_HEADER_SIZE+20, AP4_UUID_PIFF_TRACK_ENCRYPTION_ATOM, 0, 0),
m_DefaultAlgorithmId(default_algorithm_id),
m_DefaultIvSize(default_iv_size)
{
@@ -1012,31 +946,31 @@ AP4_PiffTrackEncryptionAtom::AP4_PiffTrackEncryptionAtom(AP4_UI32 default
/*----------------------------------------------------------------------
| AP4_PiffTrackEncryptionAtom::InspectFields
+---------------------------------------------------------------------*/
-AP4_Result
+AP4_Result
AP4_PiffTrackEncryptionAtom::InspectFields(AP4_AtomInspector& inspector)
{
inspector.AddField("default_AlgorithmID", m_DefaultAlgorithmId);
inspector.AddField("default_IV_size", m_DefaultIvSize);
inspector.AddField("default_KID", m_DefaultKid, 16);
-
+
return AP4_SUCCESS;
}
/*----------------------------------------------------------------------
| AP4_PiffTrackEncryptionAtom::WriteFields
+---------------------------------------------------------------------*/
-AP4_Result
+AP4_Result
AP4_PiffTrackEncryptionAtom::WriteFields(AP4_ByteStream& stream)
{
AP4_Result result;
-
- // write the fields
+
+ // write the fields
result = stream.WriteUI24(m_DefaultAlgorithmId);
- if(AP4_FAILED(result)) return result;
+ if (AP4_FAILED(result)) return result;
result = stream.WriteUI08(m_DefaultIvSize);
- if(AP4_FAILED(result)) return result;
+ if (AP4_FAILED(result)) return result;
result = stream.Write(m_DefaultKid, 16);
- if(AP4_FAILED(result)) return result;
+ if (AP4_FAILED(result)) return result;
return AP4_SUCCESS;
}
@@ -1044,50 +978,45 @@ AP4_PiffTrackEncryptionAtom::WriteFields(AP4_ByteStream& stream)
/*----------------------------------------------------------------------
| AP4_PiffSampleEncryptionAtom::Create
+---------------------------------------------------------------------*/
-AP4_PiffSampleEncryptionAtom*
+AP4_PiffSampleEncryptionAtom*
AP4_PiffSampleEncryptionAtom::Create(AP4_Size size, AP4_ByteStream& stream)
{
AP4_UI32 version = 0;
AP4_UI32 flags = 0;
AP4_Result result = ReadFullHeader(stream, version, flags);
- if(AP4_FAILED(result)) return NULL;
- if(version != 0) return NULL;
+ if (AP4_FAILED(result)) return NULL;
+ if (version != 0) return NULL;
return new AP4_PiffSampleEncryptionAtom(size, version, flags, stream);
}
/*----------------------------------------------------------------------
| AP4_PiffSampleEncryptionAtom::AP4_PiffSampleEncryptionAtom
+---------------------------------------------------------------------*/
-AP4_PiffSampleEncryptionAtom::AP4_PiffSampleEncryptionAtom(AP4_UI32 size,
- AP4_UI32 version,
- AP4_UI32 flags,
- AP4_ByteStream& stream) :
+AP4_PiffSampleEncryptionAtom::AP4_PiffSampleEncryptionAtom(AP4_UI32 size,
+ AP4_UI32 version,
+ AP4_UI32 flags,
+ AP4_ByteStream& stream) :
AP4_UuidAtom(size, AP4_UUID_PIFF_SAMPLE_ENCRYPTION_ATOM, version, flags)
{
- if(flags & AP4_PIFF_SAMPLE_ENCRYPTION_FLAG_OVERRIDE_TRACK_ENCRYPTION_DEFAULTS)
- {
+ if (flags & AP4_PIFF_SAMPLE_ENCRYPTION_FLAG_OVERRIDE_TRACK_ENCRYPTION_DEFAULTS) {
stream.ReadUI24(m_AlgorithmId);
stream.ReadUI08(m_IvSize);
- stream.Read(m_Kid, 16);
- }
- else
- {
+ stream.Read (m_Kid, 16);
+ } else {
m_AlgorithmId = 0;
m_IvSize = 0;
AP4_SetMemory(m_Kid, 0, 16);
}
-
+
stream.ReadUI32(m_IvCount);
// NOTE: the problem here is that we don't know the IV size when flags==0
// So what we do is read the whole atom and assume that there's nothing
// else after the table.
- AP4_Size payload_size = size - GetHeaderSize() - 4;
- if((flags & AP4_PIFF_SAMPLE_ENCRYPTION_FLAG_OVERRIDE_TRACK_ENCRYPTION_DEFAULTS) == 0)
- {
- if(m_IvCount)
- {
- m_IvSize = (AP4_UI08)(payload_size / m_IvCount);
+ AP4_Size payload_size = size-GetHeaderSize()-4;
+ if ((flags & AP4_PIFF_SAMPLE_ENCRYPTION_FLAG_OVERRIDE_TRACK_ENCRYPTION_DEFAULTS) == 0) {
+ if (m_IvCount) {
+ m_IvSize = (AP4_UI08)(payload_size/m_IvCount);
}
}
m_Ivs.SetDataSize(payload_size);
@@ -1098,7 +1027,7 @@ AP4_PiffSampleEncryptionAtom::AP4_PiffSampleEncryptionAtom(AP4_UI32 size,
| AP4_PiffSampleEncryptionAtom::AP4_PiffSampleEncryptionAtom
+---------------------------------------------------------------------*/
AP4_PiffSampleEncryptionAtom::AP4_PiffSampleEncryptionAtom(AP4_Cardinal sample_count) :
- AP4_UuidAtom(AP4_FULL_UUID_ATOM_HEADER_SIZE + 4 + sample_count * 16, AP4_UUID_PIFF_SAMPLE_ENCRYPTION_ATOM, 0, 0),
+ AP4_UuidAtom(AP4_FULL_UUID_ATOM_HEADER_SIZE+4+sample_count*16, AP4_UUID_PIFF_SAMPLE_ENCRYPTION_ATOM, 0, 0),
m_AlgorithmId(0),
m_IvSize(16),
m_IvCount(sample_count)
@@ -1106,7 +1035,7 @@ AP4_PiffSampleEncryptionAtom::AP4_PiffSampleEncryptionAtom(AP4_Cardinal sample_c
AP4_SetMemory(m_Kid, 0, 16);
// initialize the IVs to 0s
- m_Ivs.SetDataSize(sample_count * m_IvSize);
+ m_Ivs.SetDataSize(sample_count*m_IvSize);
AP4_SetMemory(m_Ivs.UseData(), 0, m_Ivs.GetDataSize());
}
@@ -1114,10 +1043,10 @@ AP4_PiffSampleEncryptionAtom::AP4_PiffSampleEncryptionAtom(AP4_Cardinal sample_c
| AP4_PiffSampleEncryptionAtom::AP4_PiffSampleEncryptionAtom
+---------------------------------------------------------------------*/
AP4_PiffSampleEncryptionAtom::AP4_PiffSampleEncryptionAtom(AP4_UI32 algorithm_id,
- AP4_UI08 iv_size,
- const AP4_UI08* kid,
- AP4_Cardinal sample_count) :
- AP4_UuidAtom(AP4_FULL_UUID_ATOM_HEADER_SIZE + 20 + 4, AP4_UUID_PIFF_SAMPLE_ENCRYPTION_ATOM, 0,
+ AP4_UI08 iv_size,
+ const AP4_UI08* kid,
+ AP4_Cardinal sample_count) :
+ AP4_UuidAtom(AP4_FULL_UUID_ATOM_HEADER_SIZE+20+4, AP4_UUID_PIFF_SAMPLE_ENCRYPTION_ATOM, 0,
AP4_PIFF_SAMPLE_ENCRYPTION_FLAG_OVERRIDE_TRACK_ENCRYPTION_DEFAULTS),
m_AlgorithmId(algorithm_id),
m_IvSize(iv_size),
@@ -1126,7 +1055,7 @@ AP4_PiffSampleEncryptionAtom::AP4_PiffSampleEncryptionAtom(AP4_UI32 algor
AP4_CopyMemory(m_Kid, kid, 16);
// initialize the IVs to 0s
- m_Ivs.SetDataSize(sample_count * m_IvSize);
+ m_Ivs.SetDataSize(sample_count*m_IvSize);
AP4_SetMemory(m_Ivs.UseData(), 0, m_Ivs.GetDataSize());
}
@@ -1136,86 +1065,80 @@ AP4_PiffSampleEncryptionAtom::AP4_PiffSampleEncryptionAtom(AP4_UI32 algor
const AP4_UI08*
AP4_PiffSampleEncryptionAtom::GetIv(AP4_Ordinal indx)
{
- if(m_IvSize == 0) return NULL;
- unsigned int offset = indx * m_IvSize;
- if(offset + m_IvSize > m_Ivs.GetDataSize()) return NULL;
- return m_Ivs.GetData() + offset;
+ if (m_IvSize == 0) return NULL;
+ unsigned int offset = indx*m_IvSize;
+ if (offset+m_IvSize > m_Ivs.GetDataSize()) return NULL;
+ return m_Ivs.GetData()+offset;
}
/*----------------------------------------------------------------------
| AP4_PiffSampleEncryptionAtom::SetIv
+---------------------------------------------------------------------*/
-AP4_Result
+AP4_Result
AP4_PiffSampleEncryptionAtom::SetIv(AP4_Ordinal indx, const AP4_UI08* iv)
{
- if(m_IvSize == 0) return AP4_ERROR_INVALID_STATE;
- if(indx >= m_IvCount)
- {
+ if (m_IvSize == 0) return AP4_ERROR_INVALID_STATE;
+ if (indx >= m_IvCount) {
return AP4_ERROR_OUT_OF_RANGE;
}
- AP4_CopyMemory(m_Ivs.UseData() + indx * m_IvSize, iv, m_IvSize);
-
+ AP4_CopyMemory(m_Ivs.UseData()+indx*m_IvSize, iv, m_IvSize);
+
return AP4_SUCCESS;
}
/*----------------------------------------------------------------------
| AP4_PiffSampleEncryptionAtom::InspectFields
+---------------------------------------------------------------------*/
-AP4_Result
+AP4_Result
AP4_PiffSampleEncryptionAtom::InspectFields(AP4_AtomInspector& inspector)
{
- if(m_Flags & AP4_PIFF_SAMPLE_ENCRYPTION_FLAG_OVERRIDE_TRACK_ENCRYPTION_DEFAULTS)
- {
+ if (m_Flags & AP4_PIFF_SAMPLE_ENCRYPTION_FLAG_OVERRIDE_TRACK_ENCRYPTION_DEFAULTS) {
inspector.AddField("AlgorithmID", m_AlgorithmId);
inspector.AddField("IV_size", m_IvSize);
inspector.AddField("KID", m_Kid, 16);
}
-
- if(m_IvSize > 0 && m_IvSize <= 16 && inspector.GetVerbosity() >= 1)
- {
- unsigned int sample_count = m_Ivs.GetDataSize() / m_IvSize;
- for(unsigned int i = 0; i < sample_count; i++)
- {
+
+ if (m_IvSize > 0 && m_IvSize <= 16 && inspector.GetVerbosity() >= 1) {
+ unsigned int sample_count = m_Ivs.GetDataSize()/m_IvSize;
+ for (unsigned int i=0; i<sample_count; i++) {
char header[32];
char hex[33];
hex[32] = '\0';
- AP4_FormatString(header, sizeof(header), "IV %4d", i);
- AP4_FormatHex(m_Ivs.GetData() + i * m_IvSize, m_IvSize, hex);
+ AP4_FormatString(header, sizeof(header), "IV %4d", i);
+ AP4_FormatHex(m_Ivs.GetData()+i*m_IvSize, m_IvSize, hex);
inspector.AddField(header, hex);
}
}
-
+
return AP4_SUCCESS;
}
/*----------------------------------------------------------------------
| AP4_PiffSampleEncryptionAtom::WriteFields
+---------------------------------------------------------------------*/
-AP4_Result
+AP4_Result
AP4_PiffSampleEncryptionAtom::WriteFields(AP4_ByteStream& stream)
{
AP4_Result result;
-
+
// optional fields
- if(m_Flags & AP4_PIFF_SAMPLE_ENCRYPTION_FLAG_OVERRIDE_TRACK_ENCRYPTION_DEFAULTS)
- {
+ if (m_Flags & AP4_PIFF_SAMPLE_ENCRYPTION_FLAG_OVERRIDE_TRACK_ENCRYPTION_DEFAULTS) {
result = stream.WriteUI24(m_AlgorithmId);
- if(AP4_FAILED(result)) return result;
+ if (AP4_FAILED(result)) return result;
result = stream.WriteUI08(m_IvSize);
- if(AP4_FAILED(result)) return result;
+ if (AP4_FAILED(result)) return result;
result = stream.Write(m_Kid, 16);
- if(AP4_FAILED(result)) return result;
+ if (AP4_FAILED(result)) return result;
}
-
+
// IVs
result = stream.WriteUI32(m_IvCount);
- if(AP4_FAILED(result)) return result;
- if(m_Ivs.GetDataSize())
- {
+ if (AP4_FAILED(result)) return result;
+ if (m_Ivs.GetDataSize()) {
stream.Write(m_Ivs.GetData(), m_Ivs.GetDataSize());
- if(AP4_FAILED(result)) return result;
+ if (AP4_FAILED(result)) return result;
}
-
+
return AP4_SUCCESS;
}
diff --git a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4Piff.h b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4Piff.h
index 3724befbc..73ad5659c 100644
--- a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4Piff.h
+++ b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4Piff.h
@@ -52,24 +52,23 @@ class AP4_PiffSampleEncryptionAtom;
/*----------------------------------------------------------------------
| constants
+---------------------------------------------------------------------*/
-const AP4_UI32 AP4_PROTECTION_SCHEME_TYPE_PIFF = AP4_ATOM_TYPE('p', 'i', 'f', 'f');
+const AP4_UI32 AP4_PROTECTION_SCHEME_TYPE_PIFF = AP4_ATOM_TYPE('p','i','f','f');
const AP4_UI32 AP4_PROTECTION_SCHEME_VERSION_PIFF_10 = 0x00010000;
-const AP4_UI32 AP4_PIFF_BRAND = AP4_ATOM_TYPE('p', 'i', 'f', 'f');
-const AP4_UI32 AP4_PIFF_ALGORITHM_ID_NONE = 0;
-const AP4_UI32 AP4_PIFF_ALGORITHM_ID_CTR = 1;
-const AP4_UI32 AP4_PIFF_ALGORITHM_ID_CBC = 2;
+const AP4_UI32 AP4_PIFF_BRAND = AP4_ATOM_TYPE('p','i','f','f');
+const AP4_UI32 AP4_PIFF_ALGORITHM_ID_NONE = 0;
+const AP4_UI32 AP4_PIFF_ALGORITHM_ID_CTR = 1;
+const AP4_UI32 AP4_PIFF_ALGORITHM_ID_CBC = 2;
extern AP4_UI08 const AP4_UUID_PIFF_TRACK_ENCRYPTION_ATOM[16];
extern AP4_UI08 const AP4_UUID_PIFF_SAMPLE_ENCRYPTION_ATOM[16];
const unsigned int AP4_PIFF_SAMPLE_ENCRYPTION_FLAG_OVERRIDE_TRACK_ENCRYPTION_DEFAULTS = 1;
-typedef enum
-{
+typedef enum {
AP4_PIFF_CIPHER_MODE_CTR,
AP4_PIFF_CIPHER_MODE_CBC
} AP4_PiffCipherMode;
-
+
/*----------------------------------------------------------------------
| AP4_PiffSampleEncrypter
+---------------------------------------------------------------------*/
@@ -77,25 +76,16 @@ class AP4_PiffSampleEncrypter
{
public:
// constructor and destructor
- AP4_PiffSampleEncrypter()
- {
- AP4_SetMemory(m_Iv, 0, 16);
- };
+ AP4_PiffSampleEncrypter() { AP4_SetMemory(m_Iv, 0, 16); };
virtual ~AP4_PiffSampleEncrypter() {}
// methods
virtual AP4_Result EncryptSampleData(AP4_DataBuffer& data_in,
- AP4_DataBuffer& data_out) = 0;
-
- void SetIv(const AP4_UI08* iv)
- {
- AP4_CopyMemory(m_Iv, iv, 16);
- }
- const AP4_UI08* GetIv()
- {
- return m_Iv;
- }
+ AP4_DataBuffer& data_out) = 0;
+ void SetIv(const AP4_UI08* iv) { AP4_CopyMemory(m_Iv, iv, 16); }
+ const AP4_UI08* GetIv() { return m_Iv; }
+
protected:
AP4_UI08 m_Iv[16];
};
@@ -113,7 +103,7 @@ public:
// methods
virtual AP4_Result EncryptSampleData(AP4_DataBuffer& data_in,
AP4_DataBuffer& data_out);
-
+
protected:
// members
AP4_CtrStreamCipher* m_Cipher;
@@ -134,7 +124,7 @@ public:
// methods
virtual AP4_Result EncryptSampleData(AP4_DataBuffer& data_in,
AP4_DataBuffer& data_out);
-
+
private:
// members
AP4_Size m_NaluLengthSize;
@@ -187,15 +177,11 @@ class AP4_PiffEncryptingProcessor : public AP4_Processor
{
public:
// types
- struct Encrypter
- {
+ struct Encrypter {
Encrypter(AP4_UI32 track_id, AP4_PiffSampleEncrypter* sample_encrypter) :
m_TrackId(track_id),
m_SampleEncrypter(sample_encrypter) {}
- Encrypter()
- {
- delete m_SampleEncrypter;
- }
+ Encrypter() { delete m_SampleEncrypter; }
AP4_UI32 m_TrackId;
AP4_PiffSampleEncrypter* m_SampleEncrypter;
};
@@ -206,14 +192,8 @@ public:
~AP4_PiffEncryptingProcessor();
// accessors
- AP4_ProtectionKeyMap& GetKeyMap()
- {
- return m_KeyMap;
- }
- AP4_TrackPropertyMap& GetPropertyMap()
- {
- return m_PropertyMap;
- }
+ AP4_ProtectionKeyMap& GetKeyMap() { return m_KeyMap; }
+ AP4_TrackPropertyMap& GetPropertyMap() { return m_PropertyMap; }
// AP4_Processor methods
virtual AP4_Result Initialize(AP4_AtomParent& top_level,
@@ -221,8 +201,8 @@ public:
AP4_Processor::ProgressListener* listener = NULL);
virtual AP4_Processor::TrackHandler* CreateTrackHandler(AP4_TrakAtom* trak);
virtual AP4_Processor::FragmentHandler* CreateFragmentHandler(AP4_ContainerAtom* traf);
-
-protected:
+
+protected:
// members
AP4_PiffCipherMode m_CipherMode;
AP4_BlockCipherFactory* m_BlockCipherFactory;
@@ -238,9 +218,9 @@ class AP4_PiffSampleDecrypter : public AP4_SampleDecrypter
{
public:
// factory
- static AP4_Result Create(AP4_ProtectedSampleDescription* sample_description,
+ static AP4_Result Create(AP4_ProtectedSampleDescription* sample_description,
AP4_ContainerAtom* traf,
- const AP4_UI08* key,
+ const AP4_UI08* key,
AP4_Size key_size,
AP4_BlockCipherFactory* block_cipher_factory,
AP4_PiffSampleDecrypter*& decrypter);
@@ -264,12 +244,11 @@ class AP4_PiffNullSampleDecrypter : public AP4_PiffSampleDecrypter
public:
// constructor
AP4_PiffNullSampleDecrypter() : AP4_PiffSampleDecrypter(NULL) {}
-
+
// methods
virtual AP4_Result DecryptSampleData(AP4_DataBuffer& data_in,
AP4_DataBuffer& data_out,
- const AP4_UI08* /*iv = NULL*/)
- {
+ const AP4_UI08* /*iv = NULL*/) {
data_out.SetData(data_in.GetData(), data_in.GetDataSize());
return AP4_SUCCESS;
}
@@ -373,8 +352,8 @@ class AP4_PiffTrackEncryptionAtom : public AP4_UuidAtom
{
public:
// class methods
- static AP4_PiffTrackEncryptionAtom* Create(AP4_Size size,
- AP4_ByteStream& stream);
+ static AP4_PiffTrackEncryptionAtom* Create(AP4_Size size,
+ AP4_ByteStream& stream);
// constructors
AP4_PiffTrackEncryptionAtom(AP4_UI32 default_algorithm_id,
@@ -386,22 +365,13 @@ public:
virtual AP4_Result WriteFields(AP4_ByteStream& stream);
// accessors
- AP4_UI32 GetDefaultAlgorithmId()
- {
- return m_DefaultAlgorithmId;
- }
- AP4_UI08 GetDefaultIvSize()
- {
- return m_DefaultIvSize;
- }
- const AP4_UI08* GetDefaultKid()
- {
- return m_DefaultKid;
- }
+ AP4_UI32 GetDefaultAlgorithmId() { return m_DefaultAlgorithmId; }
+ AP4_UI08 GetDefaultIvSize() { return m_DefaultIvSize; }
+ const AP4_UI08* GetDefaultKid() { return m_DefaultKid; }
private:
// methods
- AP4_PiffTrackEncryptionAtom(AP4_UI32 size,
+ AP4_PiffTrackEncryptionAtom(AP4_UI32 size,
AP4_UI32 version,
AP4_UI32 flags,
AP4_ByteStream& stream);
@@ -419,8 +389,8 @@ class AP4_PiffSampleEncryptionAtom : public AP4_UuidAtom
{
public:
// class methods
- static AP4_PiffSampleEncryptionAtom* Create(AP4_Size size,
- AP4_ByteStream& stream);
+ static AP4_PiffSampleEncryptionAtom* Create(AP4_Size size,
+ AP4_ByteStream& stream);
// constructors
AP4_PiffSampleEncryptionAtom(AP4_Cardinal sample_count);
@@ -434,29 +404,17 @@ public:
virtual AP4_Result WriteFields(AP4_ByteStream& stream);
// accessors
- AP4_UI32 GetAlgorithmId()
- {
- return m_AlgorithmId;
- }
- AP4_UI08 GetIvSize()
- {
- return m_IvSize;
- }
+ AP4_UI32 GetAlgorithmId() { return m_AlgorithmId; }
+ AP4_UI08 GetIvSize() { return m_IvSize; }
AP4_Result SetIvSize(AP4_UI08 iv_size);
- const AP4_UI08* GetKid()
- {
- return m_Kid;
- }
- AP4_Cardinal GetIvCount()
- {
- return m_IvCount;
- }
+ const AP4_UI08* GetKid() { return m_Kid; }
+ AP4_Cardinal GetIvCount() { return m_IvCount; }
const AP4_UI08* GetIv(AP4_Ordinal indx);
AP4_Result SetIv(AP4_Ordinal indx, const AP4_UI08* iv);
private:
// methods
- AP4_PiffSampleEncryptionAtom(AP4_UI32 size,
+ AP4_PiffSampleEncryptionAtom(AP4_UI32 size,
AP4_UI32 version,
AP4_UI32 flags,
AP4_ByteStream& stream);
diff --git a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4Processor.cpp b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4Processor.cpp
index 433209466..129989b1e 100644
--- a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4Processor.cpp
+++ b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4Processor.cpp
@@ -46,12 +46,11 @@
/*----------------------------------------------------------------------
| types
+---------------------------------------------------------------------*/
-struct AP4_SampleLocator
-{
- AP4_SampleLocator() :
- m_TrakIndex(0),
- m_SampleTable(NULL),
- m_SampleIndex(0),
+struct AP4_SampleLocator {
+ AP4_SampleLocator() :
+ m_TrakIndex(0),
+ m_SampleTable(NULL),
+ m_SampleIndex(0),
m_ChunkIndex(0) {}
AP4_Ordinal m_TrakIndex;
AP4_AtomSampleTable* m_SampleTable;
@@ -60,16 +59,14 @@ struct AP4_SampleLocator
AP4_Sample m_Sample;
};
-struct AP4_SampleCursor
-{
+struct AP4_SampleCursor {
AP4_SampleCursor() : m_EndReached(false) {}
AP4_SampleLocator m_Locator;
bool m_EndReached;
};
-struct AP4_MoofLocator
-{
- AP4_MoofLocator(AP4_ContainerAtom* moof, AP4_UI64 offset) :
+struct AP4_MoofLocator {
+ AP4_MoofLocator(AP4_ContainerAtom* moof, AP4_UI64 offset) :
m_Moof(moof),
m_Offset(offset) {}
AP4_ContainerAtom* m_Moof;
@@ -80,147 +77,132 @@ struct AP4_MoofLocator
| AP4_Processor::ProcessFragments
+---------------------------------------------------------------------*/
AP4_Result
-AP4_Processor::ProcessFragments(AP4_MoovAtom* moov,
- AP4_List<AP4_MoofLocator>& moofs,
+AP4_Processor::ProcessFragments(AP4_MoovAtom* moov,
+ AP4_List<AP4_MoofLocator>& moofs,
AP4_ContainerAtom* mfra,
- AP4_ByteStream& input,
+ AP4_ByteStream& input,
AP4_ByteStream& output)
{
- // FIXME: this only works for non-changing moofs
-
- for(AP4_List<AP4_MoofLocator>::Item* item = moofs.FirstItem();
- item;
- item = item->GetNext())
- {
+ // FIXME: this only works for non-changing moofs
+
+ for (AP4_List<AP4_MoofLocator>::Item* item = moofs.FirstItem();
+ item;
+ item = item->GetNext()) {
AP4_MoofLocator* locator = item->GetData();
AP4_ContainerAtom* moof = locator->m_Moof;
AP4_UI64 moof_offset = locator->m_Offset;
- AP4_UI64 mdat_payload_offset = moof_offset + moof->GetSize() + 8;
+ AP4_UI64 mdat_payload_offset = moof_offset+moof->GetSize()+8;
AP4_MovieFragment* fragment = new AP4_MovieFragment(moof);
AP4_Sample sample;
AP4_DataBuffer sample_data_in;
AP4_DataBuffer sample_data_out;
AP4_Result result;
-
+
// process all the traf atoms
AP4_Array<AP4_Processor::FragmentHandler*> handlers;
- for(; AP4_Atom* atom = moof->GetChild(AP4_ATOM_TYPE_TRAF, handlers.ItemCount());)
- {
+ for (;AP4_Atom* atom = moof->GetChild(AP4_ATOM_TYPE_TRAF, handlers.ItemCount());) {
AP4_ContainerAtom* traf = AP4_DYNAMIC_CAST(AP4_ContainerAtom, atom);
AP4_Processor::FragmentHandler* handler = CreateFragmentHandler(traf);
- if(handler) result = handler->ProcessFragment();
+ if (handler) result = handler->ProcessFragment();
handlers.Append(handler);
}
-
+
// write the moof
AP4_UI64 moof_out_start = 0;
output.Tell(moof_out_start);
bool moof_has_changed = false;
moof->Write(output);
-
+
// process all track runs
- for(unsigned int i = 0; i < handlers.ItemCount(); i++)
- {
+ for (unsigned int i=0; i<handlers.ItemCount(); i++) {
AP4_FragmentSampleTable* sample_table = NULL;
AP4_Processor::FragmentHandler* handler = handlers[i];
// get the track ID
AP4_ContainerAtom* traf = AP4_DYNAMIC_CAST(AP4_ContainerAtom, moof->GetChild(AP4_ATOM_TYPE_TRAF, i));
AP4_TfhdAtom* tfhd = AP4_DYNAMIC_CAST(AP4_TfhdAtom, traf->GetChild(AP4_ATOM_TYPE_TFHD, i));
-
+
// create a sample table object so we can read the sample data
result = fragment->CreateSampleTable(moov, tfhd->GetTrackId(), &input, moof_offset, mdat_payload_offset, sample_table);
- if(AP4_FAILED(result)) return result;
+ if (AP4_FAILED(result)) return result;
// compute the mdat size
AP4_UI64 mdat_size = 0;
- for(unsigned int j = 0; j < sample_table->GetSampleCount(); j++)
- {
+ for (unsigned int j=0; j<sample_table->GetSampleCount(); j++) {
result = sample_table->GetSample(j, sample);
- if(AP4_FAILED(result)) return result;
+ if (AP4_FAILED(result)) return result;
mdat_size += sample.GetSize();
}
-
+
// write an mdat header
- if(mdat_size > 0xFFFFFFFF - 8)
- {
+ if (mdat_size > 0xFFFFFFFF-8) {
// we don't support large mdat fragments
return AP4_ERROR_OUT_OF_RANGE;
}
- if(mdat_size)
- {
- output.WriteUI32((AP4_UI32)(8 + mdat_size));
+ if (mdat_size) {
+ output.WriteUI32((AP4_UI32)(8+mdat_size));
output.WriteUI32(AP4_ATOM_TYPE_MDAT);
}
-
+
#if defined(AP4_DEBUG)
AP4_Position before;
output.Tell(before);
#endif
-
+
// write the mdat
- for(unsigned int j = 0; j < sample_table->GetSampleCount(); j++)
- {
+ for (unsigned int j=0; j<sample_table->GetSampleCount(); j++) {
result = sample_table->GetSample(j, sample);
- if(AP4_FAILED(result)) return result;
+ if (AP4_FAILED(result)) return result;
sample.ReadData(sample_data_in);
-
+
// process the sample data
- if(handler)
- {
+ if (handler) {
result = handler->ProcessSample(sample_data_in, sample_data_out);
- if(AP4_FAILED(result)) return result;
+ if (AP4_FAILED(result)) return result;
// write the sample data
result = output.Write(sample_data_out.GetData(), sample_data_out.GetDataSize());
- if(AP4_FAILED(result)) return result;
+ if (AP4_FAILED(result)) return result;
// give the handler a chance to update the atoms
result = handler->FinishFragment();
- if(AP4_SUCCEEDED(result)) moof_has_changed = true;
- }
- else
- {
+ if (AP4_SUCCEEDED(result)) moof_has_changed = true;
+ } else {
// write the sample data (unmodified)
result = output.Write(sample_data_in.GetData(), sample_data_in.GetDataSize());
- if(AP4_FAILED(result)) return result;
+ if (AP4_FAILED(result)) return result;
}
}
-
+
#if defined(AP4_DEBUG)
AP4_Position after;
output.Tell(after);
- AP4_ASSERT(after - before == mdat_size);
+ AP4_ASSERT(after-before == mdat_size);
#endif
delete sample_table;
}
-
+
// update the moof if needed
AP4_UI64 mdat_out_end = 0;
output.Tell(mdat_out_end);
- if(moof_has_changed)
- {
+ if (moof_has_changed) {
output.Seek(moof_out_start);
moof->Write(output);
output.Seek(mdat_out_end);
}
-
+
// update the mfra if we have one
- if(mfra)
- {
- for(AP4_List<AP4_Atom>::Item* mfra_item = mfra->GetChildren().FirstItem();
- mfra_item;
- mfra_item = mfra_item->GetNext())
- {
- if(mfra_item->GetData()->GetType() != AP4_ATOM_TYPE_TFRA) continue;
+ if (mfra) {
+ for (AP4_List<AP4_Atom>::Item* mfra_item = mfra->GetChildren().FirstItem();
+ mfra_item;
+ mfra_item = mfra_item->GetNext()) {
+ if (mfra_item->GetData()->GetType() != AP4_ATOM_TYPE_TFRA) continue;
AP4_TfraAtom* tfra = AP4_DYNAMIC_CAST(AP4_TfraAtom, mfra_item->GetData());
- if(tfra == NULL) continue;
+ if (tfra == NULL) continue;
AP4_Array<AP4_TfraAtom::Entry>& entries = tfra->GetEntries();
AP4_Cardinal entry_count = entries.ItemCount();
- for(unsigned int i = 0; i < entry_count; i++)
- {
- if(entries[i].m_MoofOffset == locator->m_Offset)
- {
+ for (unsigned int i=0; i<entry_count; i++) {
+ if (entries[i].m_MoofOffset == locator->m_Offset) {
entries[i].m_MoofOffset = moof_out_start;
}
}
@@ -229,7 +211,7 @@ AP4_Processor::ProcessFragments(AP4_MoovAtom* moov,
delete fragment;
}
-
+
return AP4_SUCCESS;
}
@@ -237,7 +219,7 @@ AP4_Processor::ProcessFragments(AP4_MoovAtom* moov,
| AP4_Processor::Process
+---------------------------------------------------------------------*/
AP4_Result
-AP4_Processor::Process(AP4_ByteStream& input,
+AP4_Processor::Process(AP4_ByteStream& input,
AP4_ByteStream& output,
ProgressListener* listener,
AP4_AtomFactory& atom_factory)
@@ -251,29 +233,20 @@ AP4_Processor::Process(AP4_ByteStream& input,
AP4_ContainerAtom* mfra = NULL;
AP4_List<AP4_MoofLocator> moofs;
AP4_UI64 stream_offset = 0;
- for(AP4_Atom* atom = NULL;
+ for (AP4_Atom* atom = NULL;
AP4_SUCCEEDED(atom_factory.CreateAtomFromStream(input, atom));
- input.Tell(stream_offset))
- {
- if(atom->GetType() == AP4_ATOM_TYPE_MDAT)
- {
+ input.Tell(stream_offset)) {
+ if (atom->GetType() == AP4_ATOM_TYPE_MDAT) {
continue;
- }
- else if(atom->GetType() == AP4_ATOM_TYPE_MOOV)
- {
+ } else if (atom->GetType() == AP4_ATOM_TYPE_MOOV) {
moov = (AP4_MoovAtom*)atom;
- }
- else if(atom->GetType() == AP4_ATOM_TYPE_MOOF)
- {
+ } else if (atom->GetType() == AP4_ATOM_TYPE_MOOF) {
AP4_ContainerAtom* moof = AP4_DYNAMIC_CAST(AP4_ContainerAtom, atom);
- if(moof)
- {
+ if (moof) {
moofs.Add(new AP4_MoofLocator(moof, stream_offset));
}
continue;
- }
- else if(atom->GetType() == AP4_ATOM_TYPE_MFRA)
- {
+ } else if (atom->GetType() == AP4_ATOM_TYPE_MFRA) {
mfra = AP4_DYNAMIC_CAST(AP4_ContainerAtom, atom);
continue;
}
@@ -282,7 +255,7 @@ AP4_Processor::Process(AP4_ByteStream& input,
// initialize the processor
AP4_Result result = Initialize(top_level, input);
- if(AP4_FAILED(result)) return result;
+ if (AP4_FAILED(result)) return result;
// process the tracks if we have a moov atom
AP4_Array<AP4_SampleLocator> locators;
@@ -291,75 +264,64 @@ AP4_Processor::Process(AP4_ByteStream& input,
AP4_LargeSize mdat_payload_size = 0;
TrackHandler** handlers = NULL;
AP4_SampleCursor* cursors = NULL;
- if(moov)
- {
+ if (moov) {
// build an array of track sample locators
trak_atoms = &moov->GetTrakAtoms();
track_count = trak_atoms->ItemCount();
cursors = new AP4_SampleCursor[track_count];
handlers = new TrackHandler*[track_count];
- for(AP4_Ordinal i = 0; i < track_count; i++)
- {
+ for (AP4_Ordinal i=0; i<track_count; i++) {
handlers[i] = NULL;
}
-
+
unsigned int index = 0;
- for(AP4_List<AP4_TrakAtom>::Item* item = trak_atoms->FirstItem(); item; item = item->GetNext())
- {
+ for (AP4_List<AP4_TrakAtom>::Item* item = trak_atoms->FirstItem(); item; item=item->GetNext()) {
AP4_TrakAtom* trak = item->GetData();
// find the stsd atom
AP4_ContainerAtom* stbl = AP4_DYNAMIC_CAST(AP4_ContainerAtom, trak->FindChild("mdia/minf/stbl"));
- if(stbl == NULL) continue;
-
+ if (stbl == NULL) continue;
+
// see if there's an external data source for this track
AP4_ByteStream* trak_data_stream = &input;
- for(AP4_List<ExternalTrackData>::Item* ditem = m_ExternalTrackData.FirstItem(); ditem; ditem = ditem->GetNext())
- {
+ for (AP4_List<ExternalTrackData>::Item* ditem = m_ExternalTrackData.FirstItem(); ditem; ditem=ditem->GetNext()) {
ExternalTrackData* tdata = ditem->GetData();
- if(tdata->m_TrackId == trak->GetId())
- {
+ if (tdata->m_TrackId == trak->GetId()) {
trak_data_stream = tdata->m_MediaData;
break;
}
}
- // create the track handler
+ // create the track handler
handlers[index] = CreateTrackHandler(trak);
cursors[index].m_Locator.m_TrakIndex = index;
cursors[index].m_Locator.m_SampleTable = new AP4_AtomSampleTable(stbl, *trak_data_stream);
cursors[index].m_Locator.m_SampleIndex = 0;
cursors[index].m_Locator.m_ChunkIndex = 0;
- if(cursors[index].m_Locator.m_SampleTable->GetSampleCount())
- {
+ if (cursors[index].m_Locator.m_SampleTable->GetSampleCount()) {
cursors[index].m_Locator.m_SampleTable->GetSample(0, cursors[index].m_Locator.m_Sample);
- }
- else
- {
+ } else {
cursors[index].m_EndReached = true;
}
- index++;
+ index++;
}
// figure out the layout of the chunks
- for(;;)
- {
+ for (;;) {
// see which is the next sample to write
AP4_UI64 min_offset = (AP4_UI64)(-1);
int cursor = -1;
- for(unsigned int i = 0; i < track_count; i++)
- {
- if(!cursors[i].m_EndReached &&
- cursors[i].m_Locator.m_Sample.GetOffset() <= min_offset)
- {
+ for (unsigned int i=0; i<track_count; i++) {
+ if (!cursors[i].m_EndReached &&
+ cursors[i].m_Locator.m_Sample.GetOffset() <= min_offset) {
min_offset = cursors[i].m_Locator.m_Sample.GetOffset();
cursor = i;
}
}
// stop if all cursors are exhausted
- if(cursor == -1) break;
+ if (cursor == -1) break;
// append this locator to the layout list
AP4_SampleLocator& locator = cursors[cursor].m_Locator;
@@ -367,19 +329,16 @@ AP4_Processor::Process(AP4_ByteStream& input,
// move the cursor to the next sample
locator.m_SampleIndex++;
- if(locator.m_SampleIndex == locator.m_SampleTable->GetSampleCount())
- {
+ if (locator.m_SampleIndex == locator.m_SampleTable->GetSampleCount()) {
// mark this track as completed
cursors[cursor].m_EndReached = true;
- }
- else
- {
+ } else {
// get the next sample info
locator.m_SampleTable->GetSample(locator.m_SampleIndex, locator.m_Sample);
AP4_Ordinal skip, sdesc;
locator.m_SampleTable->GetChunkForSample(locator.m_SampleIndex,
- locator.m_ChunkIndex,
- skip, sdesc);
+ locator.m_ChunkIndex,
+ skip, sdesc);
}
}
@@ -388,28 +347,23 @@ AP4_Processor::Process(AP4_ByteStream& input,
int current_chunk = -1;
AP4_Position current_chunk_offset = 0;
AP4_Size current_chunk_size = 0;
- for(AP4_Ordinal i = 0; i < locators.ItemCount(); i++)
- {
+ for (AP4_Ordinal i=0; i<locators.ItemCount(); i++) {
AP4_SampleLocator& locator = locators[i];
- if((int)locator.m_TrakIndex != current_track ||
- (int)locator.m_ChunkIndex != current_chunk)
- {
+ if ((int)locator.m_TrakIndex != current_track ||
+ (int)locator.m_ChunkIndex != current_chunk) {
// start a new chunk for this track
current_chunk_offset += current_chunk_size;
current_chunk_size = 0;
current_track = locator.m_TrakIndex;
current_chunk = locator.m_ChunkIndex;
locator.m_SampleTable->SetChunkOffset(locator.m_ChunkIndex, current_chunk_offset);
- }
+ }
AP4_Size sample_size;
TrackHandler* handler = handlers[locator.m_TrakIndex];
- if(handler)
- {
+ if (handler) {
sample_size = handler->GetProcessedSampleSize(locator.m_Sample);
locator.m_SampleTable->SetSampleSize(locator.m_SampleIndex, sample_size);
- }
- else
- {
+ } else {
sample_size = locator.m_Sample.GetSize();
}
current_chunk_size += sample_size;
@@ -417,10 +371,9 @@ AP4_Processor::Process(AP4_ByteStream& input,
}
// process the tracks (ex: sample descriptions processing)
- for(AP4_Ordinal i = 0; i < track_count; i++)
- {
+ for (AP4_Ordinal i=0; i<track_count; i++) {
TrackHandler* handler = handlers[i];
- if(handler) handler->ProcessTrack();
+ if (handler) handler->ProcessTrack();
}
}
@@ -433,78 +386,65 @@ AP4_Processor::Process(AP4_ByteStream& input,
// see if we need a 64-bit or 32-bit mdat
AP4_Size mdat_header_size = AP4_ATOM_HEADER_SIZE;
- if(mdat_payload_size + mdat_header_size > 0xFFFFFFFF)
- {
+ if (mdat_payload_size+mdat_header_size > 0xFFFFFFFF) {
// we need a 64-bit size
mdat_header_size += 8;
}
-
+
// adjust the chunk offsets
- for(AP4_Ordinal i = 0; i < track_count; i++)
- {
+ for (AP4_Ordinal i=0; i<track_count; i++) {
AP4_TrakAtom* trak;
trak_atoms->Get(i, trak);
- trak->AdjustChunkOffsets(atoms_size + mdat_header_size);
+ trak->AdjustChunkOffsets(atoms_size+mdat_header_size);
}
// write all atoms
top_level.GetChildren().Apply(AP4_AtomListWriter(output));
// write mdat header
- if(mdat_payload_size)
- {
- if(mdat_header_size == AP4_ATOM_HEADER_SIZE)
- {
+ if (mdat_payload_size) {
+ if (mdat_header_size == AP4_ATOM_HEADER_SIZE) {
// 32-bit size
- output.WriteUI32((AP4_UI32)(mdat_header_size + mdat_payload_size));
+ output.WriteUI32((AP4_UI32)(mdat_header_size+mdat_payload_size));
output.WriteUI32(AP4_ATOM_TYPE_MDAT);
- }
- else
- {
+ } else {
// 64-bit size
output.WriteUI32(1);
output.WriteUI32(AP4_ATOM_TYPE_MDAT);
- output.WriteUI64(mdat_header_size + mdat_payload_size);
+ output.WriteUI64(mdat_header_size+mdat_payload_size);
}
}
-
+
#if defined(AP4_DEBUG)
AP4_Position before;
output.Tell(before);
#endif
// write the samples
- if(moov)
- {
+ if (moov) {
AP4_Sample sample;
AP4_DataBuffer data_in;
AP4_DataBuffer data_out;
- for(unsigned int i = 0; i < locators.ItemCount(); i++)
- {
+ for (unsigned int i=0; i<locators.ItemCount(); i++) {
AP4_SampleLocator& locator = locators[i];
locator.m_Sample.ReadData(data_in);
TrackHandler* handler = handlers[locator.m_TrakIndex];
- if(handler)
- {
+ if (handler) {
result = handler->ProcessSample(data_in, data_out);
- if(AP4_FAILED(result)) return result;
+ if (AP4_FAILED(result)) return result;
output.Write(data_out.GetData(), data_out.GetDataSize());
- }
- else
- {
- output.Write(data_in.GetData(), data_in.GetDataSize());
+ } else {
+ output.Write(data_in.GetData(), data_in.GetDataSize());
}
// notify the progress listener
- if(listener)
- {
- listener->OnProgress(i + 1, locators.ItemCount());
+ if (listener) {
+ listener->OnProgress(i+1, locators.ItemCount());
}
}
// cleanup
- for(AP4_Ordinal i = 0; i < track_count; i++)
- {
+ for (AP4_Ordinal i=0; i<track_count; i++) {
delete cursors[i].m_Locator.m_SampleTable;
delete handlers[i];
}
@@ -515,30 +455,29 @@ AP4_Processor::Process(AP4_ByteStream& input,
#if defined(AP4_DEBUG)
AP4_Position after;
output.Tell(after);
- AP4_ASSERT(after - before == mdat_payload_size);
+ AP4_ASSERT(after-before == mdat_payload_size);
#endif
// process the fragments, if any
result = ProcessFragments(moov, moofs, mfra, input, output);
- if(AP4_FAILED(result)) return result;
-
+ if (AP4_FAILED(result)) return result;
+
// write the mfra atom at the end if we have one
- if(mfra)
- {
+ if (mfra) {
mfra->Write(output);
}
-
+
// cleanup
moofs.DeleteReferences();
delete mfra;
-
+
return AP4_SUCCESS;
}
/*----------------------------------------------------------------------
| AP4_Processor:Initialize
+---------------------------------------------------------------------*/
-AP4_Result
+AP4_Result
AP4_Processor::Initialize(AP4_AtomParent& /* top_level */,
AP4_ByteStream& /* stream */,
ProgressListener* /* listener */)
@@ -550,9 +489,9 @@ AP4_Processor::Initialize(AP4_AtomParent& /* top_level */,
/*----------------------------------------------------------------------
| AP4_Processor:Finalize
+---------------------------------------------------------------------*/
-AP4_Result
+AP4_Result
AP4_Processor::Finalize(AP4_AtomParent& /* top_level */,
- ProgressListener* /* listener */)
+ ProgressListener* /* listener */ )
{
// default implementation: do nothing
return AP4_SUCCESS;
diff --git a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4Processor.h b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4Processor.h
index 0cac374ae..2e7b4186d 100644
--- a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4Processor.h
+++ b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4Processor.h
@@ -50,40 +50,37 @@ struct AP4_MoofLocator;
/*----------------------------------------------------------------------
| AP4_Processor
+---------------------------------------------------------------------*/
-class AP4_Processor
-{
+class AP4_Processor {
public:
/**
* Abstract class that defines the interface implemented by progress
* listeners. A progress listener is called during the AP4_Processor::Process()
* method to notify of progres information.
*/
- class ProgressListener
- {
+ class ProgressListener {
public:
virtual ~ProgressListener() {}
/**
* This method is called during the call to AP4_Processor::Process() to
- * notify of the progress of the operation. If this method returns an
+ * notify of the progress of the operation. If this method returns an
* error result, processing is aborted.
* @param step Ordinal of the current progress step.
* @param total Total number of steps.
- * @return A result code. If this method returns AP4_SUCCESS, the
+ * @return A result code. If this method returns AP4_SUCCESS, the
* processing continues. If an error code is returned, the processing
* is aborted.
*/
- virtual AP4_Result OnProgress(unsigned int step,
+ virtual AP4_Result OnProgress(unsigned int step,
unsigned int total) = 0;
};
/**
* Abstract class that defines the interface implemented by concrete
- * track handlers. A track handler is responsible for processing a
+ * track handlers. A track handler is responsible for processing a
* track and its media samples.
*/
- class TrackHandler
- {
+ class TrackHandler {
public:
/**
* Default destructor.
@@ -94,20 +91,14 @@ public:
* A track handler may override this method if it needs to modify
* the track atoms before processing the track samples.
*/
- virtual AP4_Result ProcessTrack()
- {
- return AP4_SUCCESS;
- }
+ virtual AP4_Result ProcessTrack() { return AP4_SUCCESS; }
/**
* Returns the size of a sample after processing.
* @param sample Sample of which the processed size is requested.
* @return Size of the sample data after processing.
*/
- virtual AP4_Size GetProcessedSampleSize(AP4_Sample& sample)
- {
- return sample.GetSize();
- }
+ virtual AP4_Size GetProcessedSampleSize(AP4_Sample& sample) { return sample.GetSize(); }
/**
* Process the data of one sample.
@@ -121,11 +112,10 @@ public:
/**
* Abstract class that defines the interface implemented by concrete
- * fragment handlers. A fragment handler is responsible for processing a
+ * fragment handlers. A fragment handler is responsible for processing a
* fragment and its media samples.
*/
- class FragmentHandler
- {
+ class FragmentHandler {
public:
/**
* Default destructor.
@@ -136,30 +126,21 @@ public:
* A fragment handler may override this method if it needs to modify
* the fragment atoms before processing the fragment samples.
*/
- virtual AP4_Result ProcessFragment()
- {
- return AP4_SUCCESS;
- }
+ virtual AP4_Result ProcessFragment() { return AP4_SUCCESS; }
/**
* A fragment handler may override this method if it needs to modify
* the fragment atoms after processing the fragment samples.
* NOTE: this method MUST NOT change the size of any of the atoms.
*/
- virtual AP4_Result FinishFragment()
- {
- return AP4_ERROR_NOT_SUPPORTED;
- }
+ virtual AP4_Result FinishFragment() { return AP4_ERROR_NOT_SUPPORTED; }
/**
* Returns the size of a sample after processing.
* @param sample Sample of which the processed size is requested.
* @return Size of the sample data after processing.
*/
- virtual AP4_Size GetProcessedSampleSize(AP4_Sample& sample)
- {
- return sample.GetSize();
- }
+ virtual AP4_Size GetProcessedSampleSize(AP4_Sample& sample) { return sample.GetSize(); }
/**
* Process the data of one sample.
@@ -174,10 +155,7 @@ public:
/**
* Default destructor
*/
- virtual ~AP4_Processor()
- {
- m_ExternalTrackData.DeleteReferences();
- }
+ virtual ~AP4_Processor() { m_ExternalTrackData.DeleteReferences(); }
/**
* Process the input stream into an output stream.
@@ -185,13 +163,13 @@ public:
* @param output Output stream to which the processed input
* will be written.
* @param listener Pointer to a listener, or NULL. The listener
- * will be called one or more times before this method returns,
+ * will be called one or more times before this method returns,
* with progress information.
*/
- AP4_Result Process(AP4_ByteStream& input,
+ AP4_Result Process(AP4_ByteStream& input,
AP4_ByteStream& output,
ProgressListener* listener = NULL,
- AP4_AtomFactory& atom_factory =
+ AP4_AtomFactory& atom_factory =
AP4_DefaultAtomFactory::Instance);
/**
@@ -199,7 +177,7 @@ public:
* It is called just after the input stream has been parsed into
* an atom tree, before the processing of the tracks.
* @param top_level Container atom containing all the atoms parsed
- * from the input stream. Note that this atom does not actually
+ * from the input stream. Note that this atom does not actually
* exist in the file; it is a synthetised container created for the
* purpose of holding together all the input's top-level atoms.
*/
@@ -218,52 +196,41 @@ public:
* This method can be overridden by concrete subclasses.
* It is called once for each track in the input file.
* @param track Pointer to the track for which a handler should be
- * created.
- * @return A pointer to a track handler, or NULL if no handler
+ * created.
+ * @return A pointer to a track handler, or NULL if no handler
* needs to be created for that track.
*/
- virtual TrackHandler* CreateTrackHandler(AP4_TrakAtom* /*trak*/)
- {
- return NULL;
- }
+ virtual TrackHandler* CreateTrackHandler(AP4_TrakAtom* /*trak*/) { return NULL; }
/**
* This method can be overridden by concrete subclasses.
* It is called once for each fragment in the input file.
* @param track Pointer to the fragment for which a handler should be
- * created.
- * @return A pointer to a fragment handler, or NULL if no handler
+ * created.
+ * @return A pointer to a fragment handler, or NULL if no handler
* needs to be created for that fragment.
*/
- virtual FragmentHandler* CreateFragmentHandler(AP4_ContainerAtom* /*traf*/)
- {
- return NULL;
- }
-
+ virtual FragmentHandler* CreateFragmentHandler(AP4_ContainerAtom* /*traf*/) { return NULL; }
+
protected:
- class ExternalTrackData
- {
+ class ExternalTrackData {
public:
ExternalTrackData(unsigned int track_id, AP4_ByteStream* media_data) :
- m_TrackId(track_id), m_MediaData(media_data)
- {
+ m_TrackId(track_id), m_MediaData(media_data) {
media_data->AddReference();
}
- ~ExternalTrackData()
- {
- m_MediaData->Release();
- }
+ ~ExternalTrackData() { m_MediaData->Release(); }
unsigned int m_TrackId;
AP4_ByteStream* m_MediaData;
};
- AP4_Result ProcessFragments(AP4_MoovAtom* moov,
- AP4_List<AP4_MoofLocator>& moofs,
+ AP4_Result ProcessFragments(AP4_MoovAtom* moov,
+ AP4_List<AP4_MoofLocator>& moofs,
AP4_ContainerAtom* mfra,
- AP4_ByteStream& input,
+ AP4_ByteStream& input,
AP4_ByteStream& output);
-
-
+
+
AP4_List<ExternalTrackData> m_ExternalTrackData;
};
diff --git a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4Protection.cpp b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4Protection.cpp
index d7b6a7f14..cf918b3f9 100644
--- a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4Protection.cpp
+++ b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4Protection.cpp
@@ -57,9 +57,9 @@ AP4_DEFINE_DYNAMIC_CAST_ANCHOR(AP4_ProtectedSampleDescription)
| AP4_EncaSampleEntry::AP4_EncaSampleEntry
+---------------------------------------------------------------------*/
AP4_EncaSampleEntry::AP4_EncaSampleEntry(AP4_UI32 type,
- AP4_Size size,
- AP4_ByteStream& stream,
- AP4_AtomFactory& atom_factory) :
+ AP4_Size size,
+ AP4_ByteStream& stream,
+ AP4_AtomFactory& atom_factory) :
AP4_AudioSampleEntry(type, size, stream, atom_factory)
{
}
@@ -68,8 +68,8 @@ AP4_EncaSampleEntry::AP4_EncaSampleEntry(AP4_UI32 type,
| AP4_EncaSampleEntry::AP4_EncaSampleEntry
+---------------------------------------------------------------------*/
AP4_EncaSampleEntry::AP4_EncaSampleEntry(AP4_Size size,
- AP4_ByteStream& stream,
- AP4_AtomFactory& atom_factory) :
+ AP4_ByteStream& stream,
+ AP4_AtomFactory& atom_factory) :
AP4_AudioSampleEntry(AP4_ATOM_TYPE_ENCA, size, stream, atom_factory)
{
}
@@ -89,34 +89,30 @@ AP4_EncaSampleEntry::ToSampleDescription()
// get the scheme info
AP4_SchmAtom* schm = (AP4_SchmAtom*)FindChild("sinf/schm");
- AP4_UI32 original_format = frma ? frma->GetOriginalFormat() : AP4_ATOM_TYPE_MP4A;
- if(schm)
- {
+ AP4_UI32 original_format = frma?frma->GetOriginalFormat():AP4_ATOM_TYPE_MP4A;
+ if (schm) {
// create the original sample description
return new AP4_ProtectedSampleDescription(
- m_Type,
- ToTargetSampleDescription(original_format),
- original_format,
- schm->GetSchemeType(),
- schm->GetSchemeVersion(),
- schm->GetSchemeUri().GetChars(),
- schi);
- }
- else if(schi)
- {
+ m_Type,
+ ToTargetSampleDescription(original_format),
+ original_format,
+ schm->GetSchemeType(),
+ schm->GetSchemeVersion(),
+ schm->GetSchemeUri().GetChars(),
+ schi);
+ } else if (schi) {
// try to see if we can guess the protection scheme from the 'schi' contents
AP4_Atom* odkm = schi->GetChild(AP4_ATOM_TYPE_ODKM);
- if(odkm)
- {
+ if (odkm) {
// create the original sample description
return new AP4_ProtectedSampleDescription(
- m_Type,
- ToTargetSampleDescription(original_format),
- original_format,
- AP4_PROTECTION_SCHEME_TYPE_OMA,
- AP4_PROTECTION_SCHEME_VERSION_OMA_20,
- NULL,
- schi);
+ m_Type,
+ ToTargetSampleDescription(original_format),
+ original_format,
+ AP4_PROTECTION_SCHEME_TYPE_OMA,
+ AP4_PROTECTION_SCHEME_VERSION_OMA_20,
+ NULL,
+ schi);
}
}
@@ -130,33 +126,29 @@ AP4_EncaSampleEntry::ToSampleDescription()
AP4_SampleDescription*
AP4_EncaSampleEntry::ToTargetSampleDescription(AP4_UI32 format)
{
- switch(format)
- {
- case AP4_ATOM_TYPE_MP4A:
- {
- AP4_EsdsAtom* esds = AP4_DYNAMIC_CAST(AP4_EsdsAtom, GetChild(AP4_ATOM_TYPE_ESDS));
- if(esds == NULL)
- {
- // check if this is a quicktime style sample description
- if(m_QtVersion > 0)
- {
- esds = AP4_DYNAMIC_CAST(AP4_EsdsAtom, FindChild("wave/esds"));
+ switch (format) {
+ case AP4_ATOM_TYPE_MP4A: {
+ AP4_EsdsAtom* esds = AP4_DYNAMIC_CAST(AP4_EsdsAtom, GetChild(AP4_ATOM_TYPE_ESDS));
+ if (esds == NULL) {
+ // check if this is a quicktime style sample description
+ if (m_QtVersion > 0) {
+ esds = AP4_DYNAMIC_CAST(AP4_EsdsAtom, FindChild("wave/esds"));
+ }
}
+ return new AP4_MpegAudioSampleDescription(
+ GetSampleRate(),
+ GetSampleSize(),
+ GetChannelCount(),
+ esds);
}
- return new AP4_MpegAudioSampleDescription(
- GetSampleRate(),
- GetSampleSize(),
- GetChannelCount(),
- esds);
- }
-
- default:
- return new AP4_GenericAudioSampleDescription(
- format,
- GetSampleRate(),
- GetSampleSize(),
- GetChannelCount(),
- this);
+
+ default:
+ return new AP4_GenericAudioSampleDescription(
+ format,
+ GetSampleRate(),
+ GetSampleSize(),
+ GetChannelCount(),
+ this);
}
}
@@ -164,9 +156,9 @@ AP4_EncaSampleEntry::ToTargetSampleDescription(AP4_UI32 format)
| AP4_EncvSampleEntry::AP4_EncvSampleEntry
+---------------------------------------------------------------------*/
AP4_EncvSampleEntry::AP4_EncvSampleEntry(AP4_UI32 type,
- AP4_Size size,
- AP4_ByteStream& stream,
- AP4_AtomFactory& atom_factory) :
+ AP4_Size size,
+ AP4_ByteStream& stream,
+ AP4_AtomFactory& atom_factory) :
AP4_VisualSampleEntry(type, size, stream, atom_factory)
{
}
@@ -175,8 +167,8 @@ AP4_EncvSampleEntry::AP4_EncvSampleEntry(AP4_UI32 type,
| AP4_EncvSampleEntry::AP4_EncvSampleEntry
+---------------------------------------------------------------------*/
AP4_EncvSampleEntry::AP4_EncvSampleEntry(AP4_Size size,
- AP4_ByteStream& stream,
- AP4_AtomFactory& atom_factory) :
+ AP4_ByteStream& stream,
+ AP4_AtomFactory& atom_factory) :
AP4_VisualSampleEntry(AP4_ATOM_TYPE_ENCV, size, stream, atom_factory)
{
}
@@ -196,34 +188,30 @@ AP4_EncvSampleEntry::ToSampleDescription()
// get the scheme info
AP4_SchmAtom* schm = (AP4_SchmAtom*)FindChild("sinf/schm");
- AP4_UI32 original_format = frma ? frma->GetOriginalFormat() : AP4_ATOM_TYPE_MP4V;
- if(schm)
- {
+ AP4_UI32 original_format = frma?frma->GetOriginalFormat():AP4_ATOM_TYPE_MP4V;
+ if (schm) {
// create the sample description
return new AP4_ProtectedSampleDescription(
- m_Type,
- ToTargetSampleDescription(original_format),
- original_format,
- schm->GetSchemeType(),
- schm->GetSchemeVersion(),
- schm->GetSchemeUri().GetChars(),
- schi);
- }
- else if(schi)
- {
+ m_Type,
+ ToTargetSampleDescription(original_format),
+ original_format,
+ schm->GetSchemeType(),
+ schm->GetSchemeVersion(),
+ schm->GetSchemeUri().GetChars(),
+ schi);
+ } else if (schi) {
// try to see if we can guess the protection scheme from the 'schi' contents
AP4_Atom* odkm = schi->GetChild(AP4_ATOM_TYPE_ODKM);
- if(odkm)
- {
+ if (odkm) {
// create the original sample description
return new AP4_ProtectedSampleDescription(
- m_Type,
- ToTargetSampleDescription(original_format),
- original_format,
- AP4_PROTECTION_SCHEME_TYPE_OMA,
- AP4_PROTECTION_SCHEME_VERSION_OMA_20,
- NULL,
- schi);
+ m_Type,
+ ToTargetSampleDescription(original_format),
+ original_format,
+ AP4_PROTECTION_SCHEME_TYPE_OMA,
+ AP4_PROTECTION_SCHEME_VERSION_OMA_20,
+ NULL,
+ schi);
}
}
@@ -238,32 +226,31 @@ AP4_EncvSampleEntry::ToSampleDescription()
AP4_SampleDescription*
AP4_EncvSampleEntry::ToTargetSampleDescription(AP4_UI32 format)
{
- switch(format)
- {
- case AP4_ATOM_TYPE_AVC1:
- return new AP4_AvcSampleDescription(
- m_Width,
- m_Height,
- m_Depth,
- m_CompressorName.GetChars(),
- this);
-
- case AP4_ATOM_TYPE_MP4V:
- return new AP4_MpegVideoSampleDescription(
- m_Width,
- m_Height,
- m_Depth,
- m_CompressorName.GetChars(),
- AP4_DYNAMIC_CAST(AP4_EsdsAtom, GetChild(AP4_ATOM_TYPE_ESDS)));
-
- default:
- return new AP4_GenericVideoSampleDescription(
- format,
- m_Width,
- m_Height,
- m_Depth,
- m_CompressorName.GetChars(),
- this);
+ switch (format) {
+ case AP4_ATOM_TYPE_AVC1:
+ return new AP4_AvcSampleDescription(
+ m_Width,
+ m_Height,
+ m_Depth,
+ m_CompressorName.GetChars(),
+ this);
+
+ case AP4_ATOM_TYPE_MP4V:
+ return new AP4_MpegVideoSampleDescription(
+ m_Width,
+ m_Height,
+ m_Depth,
+ m_CompressorName.GetChars(),
+ AP4_DYNAMIC_CAST(AP4_EsdsAtom, GetChild(AP4_ATOM_TYPE_ESDS)));
+
+ default:
+ return new AP4_GenericVideoSampleDescription(
+ format,
+ m_Width,
+ m_Height,
+ m_Depth,
+ m_CompressorName.GetChars(),
+ this);
}
}
@@ -271,8 +258,8 @@ AP4_EncvSampleEntry::ToTargetSampleDescription(AP4_UI32 format)
| AP4_DrmsSampleEntry::AP4_DrmsSampleEntry
+---------------------------------------------------------------------*/
AP4_DrmsSampleEntry::AP4_DrmsSampleEntry(AP4_Size size,
- AP4_ByteStream& stream,
- AP4_AtomFactory& atom_factory) :
+ AP4_ByteStream& stream,
+ AP4_AtomFactory& atom_factory) :
AP4_EncaSampleEntry(AP4_ATOM_TYPE_DRMS, size, stream, atom_factory)
{
}
@@ -281,8 +268,8 @@ AP4_DrmsSampleEntry::AP4_DrmsSampleEntry(AP4_Size size,
| AP4_DrmiSampleEntry::AP4_DrmiSampleEntry
+---------------------------------------------------------------------*/
AP4_DrmiSampleEntry::AP4_DrmiSampleEntry(AP4_Size size,
- AP4_ByteStream& stream,
- AP4_AtomFactory& atom_factory) :
+ AP4_ByteStream& stream,
+ AP4_AtomFactory& atom_factory) :
AP4_EncvSampleEntry(AP4_ATOM_TYPE_DRMI, size, stream, atom_factory)
{
}
@@ -300,12 +287,9 @@ AP4_ProtectionSchemeInfo::~AP4_ProtectionSchemeInfo()
+---------------------------------------------------------------------*/
AP4_ProtectionSchemeInfo::AP4_ProtectionSchemeInfo(AP4_ContainerAtom* schi)
{
- if(schi)
- {
+ if (schi) {
m_SchiAtom = (AP4_ContainerAtom*)schi->Clone();
- }
- else
- {
+ } else {
m_SchiAtom = NULL;
}
}
@@ -328,16 +312,13 @@ AP4_ProtectionKeyMap::~AP4_ProtectionKeyMap()
/*----------------------------------------------------------------------
| AP4_ProtectionKeyMap::SetKey
+---------------------------------------------------------------------*/
-AP4_Result
+AP4_Result
AP4_ProtectionKeyMap::SetKey(AP4_UI32 track_id, const AP4_UI08* key, const AP4_UI08* iv)
{
KeyEntry* entry = GetEntry(track_id);
- if(entry == NULL)
- {
+ if (entry == NULL) {
m_KeyEntries.Add(new KeyEntry(track_id, key, iv));
- }
- else
- {
+ } else {
entry->SetKey(key, iv);
}
@@ -347,12 +328,11 @@ AP4_ProtectionKeyMap::SetKey(AP4_UI32 track_id, const AP4_UI08* key, const AP4_U
/*----------------------------------------------------------------------
| AP4_ProtectionKeyMap::SetKey
+---------------------------------------------------------------------*/
-AP4_Result
+AP4_Result
AP4_ProtectionKeyMap::SetKeys(const AP4_ProtectionKeyMap& key_map)
{
AP4_List<KeyEntry>::Item* item = key_map.m_KeyEntries.FirstItem();
- while(item)
- {
+ while (item) {
KeyEntry* entry = item->GetData();
m_KeyEntries.Add(new KeyEntry(entry->m_TrackId,
entry->m_Key,
@@ -365,20 +345,17 @@ AP4_ProtectionKeyMap::SetKeys(const AP4_ProtectionKeyMap& key_map)
/*----------------------------------------------------------------------
| AP4_ProtectionKeyMap::GetKeyIv
+---------------------------------------------------------------------*/
-AP4_Result
-AP4_ProtectionKeyMap::GetKeyAndIv(AP4_UI32 track_id,
- const AP4_UI08*& key,
+AP4_Result
+AP4_ProtectionKeyMap::GetKeyAndIv(AP4_UI32 track_id,
+ const AP4_UI08*& key,
const AP4_UI08*& iv)
{
KeyEntry* entry = GetEntry(track_id);
- if(entry)
- {
+ if (entry) {
key = entry->m_Key;
iv = entry->m_IV;
return AP4_SUCCESS;
- }
- else
- {
+ } else {
return AP4_ERROR_NO_SUCH_ITEM;
}
}
@@ -386,16 +363,13 @@ AP4_ProtectionKeyMap::GetKeyAndIv(AP4_UI32 track_id,
/*----------------------------------------------------------------------
| AP4_ProtectionKeyMap::GetKey
+---------------------------------------------------------------------*/
-const AP4_UI08*
+const AP4_UI08*
AP4_ProtectionKeyMap::GetKey(AP4_UI32 track_id) const
{
KeyEntry* entry = GetEntry(track_id);
- if(entry)
- {
+ if (entry) {
return entry->m_Key;
- }
- else
- {
+ } else {
return NULL;
}
}
@@ -407,10 +381,9 @@ AP4_ProtectionKeyMap::KeyEntry*
AP4_ProtectionKeyMap::GetEntry(AP4_UI32 track_id) const
{
AP4_List<KeyEntry>::Item* item = m_KeyEntries.FirstItem();
- while(item)
- {
+ while (item) {
KeyEntry* entry = (KeyEntry*)item->GetData();
- if(entry->m_TrackId == track_id) return entry;
+ if (entry->m_TrackId == track_id) return entry;
item = item->GetNext();
}
@@ -420,9 +393,9 @@ AP4_ProtectionKeyMap::GetEntry(AP4_UI32 track_id) const
/*----------------------------------------------------------------------
| AP4_ProtectionKeyMap::KeyEntry::KeyEntry
+---------------------------------------------------------------------*/
-AP4_ProtectionKeyMap::KeyEntry::KeyEntry(AP4_UI32 track_id,
- const AP4_UI08* key,
- const AP4_UI08* iv /* = NULL */) :
+AP4_ProtectionKeyMap::KeyEntry::KeyEntry(AP4_UI32 track_id,
+ const AP4_UI08* key,
+ const AP4_UI08* iv /* = NULL */) :
m_TrackId(track_id)
{
SetKey(key, iv);
@@ -435,12 +408,9 @@ void
AP4_ProtectionKeyMap::KeyEntry::SetKey(const AP4_UI08* key, const AP4_UI08* iv)
{
AP4_CopyMemory(m_Key, key, sizeof(m_Key));
- if(iv)
- {
+ if (iv) {
AP4_CopyMemory(m_IV, iv, sizeof(m_IV));
- }
- else
- {
+ } else {
AP4_SetMemory(m_IV, 0, sizeof(m_IV));
}
}
@@ -457,8 +427,8 @@ AP4_TrackPropertyMap::~AP4_TrackPropertyMap()
| AP4_TrackPropertyMap::SetProperty
+---------------------------------------------------------------------*/
AP4_Result
-AP4_TrackPropertyMap::SetProperty(AP4_UI32 track_id,
- const char* name,
+AP4_TrackPropertyMap::SetProperty(AP4_UI32 track_id,
+ const char* name,
const char* value)
{
return m_Entries.Add(new Entry(track_id, name, value));
@@ -467,12 +437,11 @@ AP4_TrackPropertyMap::SetProperty(AP4_UI32 track_id,
/*----------------------------------------------------------------------
| AP4_TrackPropertyMap::SetProperties
+---------------------------------------------------------------------*/
-AP4_Result
+AP4_Result
AP4_TrackPropertyMap::SetProperties(const AP4_TrackPropertyMap& properties)
{
AP4_List<Entry>::Item* item = properties.m_Entries.FirstItem();
- while(item)
- {
+ while (item) {
Entry* entry = item->GetData();
m_Entries.Add(new Entry(entry->m_TrackId,
entry->m_Name.GetChars(),
@@ -489,12 +458,10 @@ const char*
AP4_TrackPropertyMap::GetProperty(AP4_UI32 track_id, const char* name)
{
AP4_List<Entry>::Item* item = m_Entries.FirstItem();
- while(item)
- {
+ while (item) {
Entry* entry = item->GetData();
- if(entry->m_TrackId == track_id &&
- AP4_CompareStrings(entry->m_Name.GetChars(), name) == 0)
- {
+ if (entry->m_TrackId == track_id &&
+ AP4_CompareStrings(entry->m_Name.GetChars(), name) == 0) {
return entry->m_Value.GetChars();
}
item = item->GetNext();
@@ -507,76 +474,69 @@ AP4_TrackPropertyMap::GetProperty(AP4_UI32 track_id, const char* name)
/*----------------------------------------------------------------------
| AP4_TrackPropertyMap::GetTextualHeaders
+---------------------------------------------------------------------*/
-AP4_Result
+AP4_Result
AP4_TrackPropertyMap::GetTextualHeaders(AP4_UI32 track_id, AP4_DataBuffer& textual_headers)
{
AP4_Size buffer_size = 0;
AP4_Result result = AP4_SUCCESS;
AP4_Byte* data_buffer;
-
+
// get the size needed for the textual headers
AP4_List<Entry>::Item* item = m_Entries.FirstItem();
- while(item)
- {
+ while (item) {
Entry* entry = item->GetData();
- if(entry->m_TrackId == track_id)
- {
+ if (entry->m_TrackId == track_id) {
const char* name = entry->m_Name.GetChars();
- if(AP4_CompareStrings(name, "ContentId") != 0 &&
- AP4_CompareStrings(name, "RightsIssuerUrl") != 0 &&
- AP4_CompareStrings(name, "KID") != 0)
- {
- buffer_size += (entry->m_Name.GetLength() +
+ if (AP4_CompareStrings(name, "ContentId") != 0 &&
+ AP4_CompareStrings(name, "RightsIssuerUrl") != 0 &&
+ AP4_CompareStrings(name, "KID") != 0) {
+ buffer_size += (entry->m_Name.GetLength() +
entry->m_Value.GetLength() +
- 2); // colon + nul
-
- }
+ 2); // colon + nul
+
+ }
}
- item = item->GetNext();
+ item = item->GetNext();
}
-
+
result = textual_headers.SetDataSize(buffer_size);
AP4_CHECK(result);
-
+
data_buffer = textual_headers.UseData();
-
+
// set the textual headers
item = m_Entries.FirstItem();
- while(item)
- {
+ while (item) {
Entry* entry = item->GetData();
- if(entry->m_TrackId == track_id)
- {
+ if (entry->m_TrackId == track_id) {
const char* name = entry->m_Name.GetChars();
const char* value = NULL;
AP4_Size name_len = 0;
AP4_Size value_len = 0;
-
- if(AP4_CompareStrings(name, "ContentId") != 0 &&
- AP4_CompareStrings(name, "RightsIssuerUrl") != 0 &&
- AP4_CompareStrings(name, "KID") != 0)
- {
+
+ if (AP4_CompareStrings(name, "ContentId") != 0 &&
+ AP4_CompareStrings(name, "RightsIssuerUrl") != 0 &&
+ AP4_CompareStrings(name, "KID") != 0) {
name_len = entry->m_Name.GetLength();
value = entry->m_Value.GetChars();
- value_len = entry->m_Value.GetLength();
-
+ value_len = entry->m_Value.GetLength();
+
// format is name:value\0
- if(name && value)
- {
+ if (name && value) {
AP4_CopyMemory(data_buffer, name, name_len);
data_buffer[name_len] = ':';
- data_buffer += (1 + name_len);
+ data_buffer += (1+name_len);
AP4_CopyMemory(data_buffer, value, value_len);
data_buffer[value_len] = '\0';
- data_buffer += (1 + value_len);
- }
- }
- }
- item = item->GetNext();
+ data_buffer += (1+value_len);
+ }
+ }
+ }
+ item = item->GetNext();
}
-
+
// success path
- return AP4_SUCCESS;
+ return AP4_SUCCESS;
}
/*----------------------------------------------------------------------
@@ -608,7 +568,7 @@ AP4_ProtectedSampleDescription::AP4_ProtectedSampleDescription(
AP4_ProtectedSampleDescription::~AP4_ProtectedSampleDescription()
{
delete m_SchemeInfo;
- if(m_OriginalSampleDescriptionIsOwned) delete m_OriginalSampleDescription;
+ if (m_OriginalSampleDescriptionIsOwned) delete m_OriginalSampleDescription;
}
/*----------------------------------------------------------------------
@@ -618,33 +578,32 @@ AP4_Atom*
AP4_ProtectedSampleDescription::ToAtom() const
{
// construct the atom for the original sample description
- if(m_OriginalSampleDescription == NULL) return NULL;
+ if (m_OriginalSampleDescription == NULL) return NULL;
AP4_Atom* atom = m_OriginalSampleDescription->ToAtom();
-
+
// switch the atom type
atom->SetType(m_Format);
// check that the constructed atom is a container
AP4_ContainerAtom* container = AP4_DYNAMIC_CAST(AP4_ContainerAtom, atom);
- if(container == NULL) return atom; // not a container ?? return now.
-
+ if (container == NULL) return atom; // not a container ?? return now.
+
// create the sinf atom
AP4_ContainerAtom* sinf = new AP4_ContainerAtom(AP4_ATOM_TYPE_SINF);
-
+
// create and add a frma atom
AP4_FrmaAtom* frma = new AP4_FrmaAtom(m_OriginalFormat);
sinf->AddChild(frma);
-
+
// create and add a schm atom
AP4_SchmAtom* schm = new AP4_SchmAtom(m_SchemeType, m_SchemeVersion, m_SchemeUri.GetChars());
sinf->AddChild(schm);
// add the schi atom
- if(m_SchemeInfo && m_SchemeInfo->GetSchiAtom())
- {
+ if (m_SchemeInfo && m_SchemeInfo->GetSchiAtom()) {
sinf->AddChild(m_SchemeInfo->GetSchiAtom()->Clone());
}
-
+
// add the sinf to the returned atom
container->AddChild(sinf);
@@ -654,61 +613,56 @@ AP4_ProtectedSampleDescription::ToAtom() const
/*----------------------------------------------------------------------
| AP4_SampleDecrypter:Create
+---------------------------------------------------------------------*/
-AP4_SampleDecrypter*
+AP4_SampleDecrypter*
AP4_SampleDecrypter::Create(AP4_ProtectedSampleDescription* sample_description,
const AP4_UI08* key,
AP4_Size key_size,
AP4_BlockCipherFactory* block_cipher_factory)
{
- if(sample_description == NULL || key == NULL) return NULL;
+ if (sample_description == NULL || key == NULL) return NULL;
// select the block cipher factory
- if(block_cipher_factory == NULL)
- {
+ if (block_cipher_factory == NULL) {
block_cipher_factory = &AP4_DefaultBlockCipherFactory::Instance;
}
- switch(sample_description->GetSchemeType())
- {
- case AP4_PROTECTION_SCHEME_TYPE_OMA:
- {
- AP4_OmaDcfSampleDecrypter* decrypter = NULL;
- AP4_Result result = AP4_OmaDcfSampleDecrypter::Create(sample_description,
- key,
- key_size,
- block_cipher_factory,
- decrypter);
- if(AP4_FAILED(result)) return NULL;
- return decrypter;
- }
-
- case AP4_PROTECTION_SCHEME_TYPE_IAEC:
- {
- AP4_IsmaCipher* decrypter = NULL;
- AP4_Result result = AP4_IsmaCipher::CreateSampleDecrypter(sample_description,
- key,
- key_size,
- block_cipher_factory,
- decrypter);
- if(AP4_FAILED(result)) return NULL;
- return decrypter;
- }
+ switch(sample_description->GetSchemeType()) {
+ case AP4_PROTECTION_SCHEME_TYPE_OMA: {
+ AP4_OmaDcfSampleDecrypter* decrypter = NULL;
+ AP4_Result result = AP4_OmaDcfSampleDecrypter::Create(sample_description,
+ key,
+ key_size,
+ block_cipher_factory,
+ decrypter);
+ if (AP4_FAILED(result)) return NULL;
+ return decrypter;
+ }
- case AP4_PROTECTION_SCHEME_TYPE_PIFF:
- {
- AP4_PiffSampleDecrypter* decrypter = NULL;
- AP4_Result result = AP4_PiffSampleDecrypter::Create(sample_description,
- NULL,
- key,
- key_size,
- block_cipher_factory,
- decrypter);
- if(AP4_FAILED(result)) return NULL;
- return decrypter;
- }
+ case AP4_PROTECTION_SCHEME_TYPE_IAEC: {
+ AP4_IsmaCipher* decrypter = NULL;
+ AP4_Result result = AP4_IsmaCipher::CreateSampleDecrypter(sample_description,
+ key,
+ key_size,
+ block_cipher_factory,
+ decrypter);
+ if (AP4_FAILED(result)) return NULL;
+ return decrypter;
+ }
- default:
- return NULL;
+ case AP4_PROTECTION_SCHEME_TYPE_PIFF: {
+ AP4_PiffSampleDecrypter* decrypter = NULL;
+ AP4_Result result = AP4_PiffSampleDecrypter::Create(sample_description,
+ NULL,
+ key,
+ key_size,
+ block_cipher_factory,
+ decrypter);
+ if (AP4_FAILED(result)) return NULL;
+ return decrypter;
+ }
+
+ default:
+ return NULL;
}
return NULL;
@@ -717,38 +671,35 @@ AP4_SampleDecrypter::Create(AP4_ProtectedSampleDescription* sample_description,
/*----------------------------------------------------------------------
| AP4_SampleDecrypter:Create
+---------------------------------------------------------------------*/
-AP4_SampleDecrypter*
+AP4_SampleDecrypter*
AP4_SampleDecrypter::Create(AP4_ProtectedSampleDescription* sample_description,
AP4_ContainerAtom* traf,
const AP4_UI08* key,
AP4_Size key_size,
AP4_BlockCipherFactory* block_cipher_factory)
{
- if(sample_description == NULL || traf == NULL || key == NULL) return NULL;
+ if (sample_description == NULL || traf == NULL || key == NULL) return NULL;
// select the block cipher factory
- if(block_cipher_factory == NULL)
- {
+ if (block_cipher_factory == NULL) {
block_cipher_factory = &AP4_DefaultBlockCipherFactory::Instance;
}
- switch(sample_description->GetSchemeType())
- {
- case AP4_PROTECTION_SCHEME_TYPE_PIFF:
- {
- AP4_PiffSampleDecrypter* decrypter = NULL;
- AP4_Result result = AP4_PiffSampleDecrypter::Create(sample_description,
- traf,
- key,
- key_size,
- block_cipher_factory,
- decrypter);
- if(AP4_FAILED(result)) return NULL;
- return decrypter;
- }
+ switch(sample_description->GetSchemeType()) {
+ case AP4_PROTECTION_SCHEME_TYPE_PIFF: {
+ AP4_PiffSampleDecrypter* decrypter = NULL;
+ AP4_Result result = AP4_PiffSampleDecrypter::Create(sample_description,
+ traf,
+ key,
+ key_size,
+ block_cipher_factory,
+ decrypter);
+ if (AP4_FAILED(result)) return NULL;
+ return decrypter;
+ }
- default:
- return NULL;
+ default:
+ return NULL;
}
return NULL;
@@ -761,18 +712,14 @@ AP4_StandardDecryptingProcessor::AP4_StandardDecryptingProcessor(
const AP4_ProtectionKeyMap* key_map /* = NULL */,
AP4_BlockCipherFactory* block_cipher_factory /* = NULL */)
{
- if(key_map)
- {
+ if (key_map) {
// copy the keys
m_KeyMap.SetKeys(*key_map);
}
-
- if(block_cipher_factory == NULL)
- {
+
+ if (block_cipher_factory == NULL) {
m_BlockCipherFactory = &AP4_DefaultBlockCipherFactory::Instance;
- }
- else
- {
+ } else {
m_BlockCipherFactory = block_cipher_factory;
}
}
@@ -780,28 +727,25 @@ AP4_StandardDecryptingProcessor::AP4_StandardDecryptingProcessor(
/*----------------------------------------------------------------------
| AP4_StandardDecryptingProcessor:Initialize
+---------------------------------------------------------------------*/
-AP4_Result
+AP4_Result
AP4_StandardDecryptingProcessor::Initialize(AP4_AtomParent& top_level,
- AP4_ByteStream& /*stream*/,
- ProgressListener* /*listener*/)
+ AP4_ByteStream& /*stream*/,
+ ProgressListener* /*listener*/)
{
AP4_FtypAtom* ftyp = AP4_DYNAMIC_CAST(AP4_FtypAtom, top_level.GetChild(AP4_ATOM_TYPE_FTYP));
- if(ftyp)
- {
+ if (ftyp) {
// remove the atom, it will be replaced with a new one
top_level.RemoveChild(ftyp);
-
+
// keep the existing brand and compatible brands except for the ones we want to remove
AP4_Array<AP4_UI32> compatible_brands;
compatible_brands.EnsureCapacity(ftyp->GetCompatibleBrands().ItemCount());
- for(unsigned int i = 0; i < ftyp->GetCompatibleBrands().ItemCount(); i++)
- {
- if(ftyp->GetCompatibleBrands()[i] != AP4_OMA_DCF_BRAND_OPF2)
- {
+ for (unsigned int i=0; i<ftyp->GetCompatibleBrands().ItemCount(); i++) {
+ if (ftyp->GetCompatibleBrands()[i] != AP4_OMA_DCF_BRAND_OPF2) {
compatible_brands.Append(ftyp->GetCompatibleBrands()[i]);
}
}
-
+
// create a replacement for the major brand
top_level.AddChild(new AP4_FtypAtom(ftyp->GetMajorBrand(),
ftyp->GetMinorVersion(),
@@ -809,63 +753,57 @@ AP4_StandardDecryptingProcessor::Initialize(AP4_AtomParent& top_level,
compatible_brands.ItemCount()), 0);
delete ftyp;
}
-
+
return AP4_SUCCESS;
}
/*----------------------------------------------------------------------
| AP4_StandardDecryptingProcessor:CreateTrackHandler
+---------------------------------------------------------------------*/
-AP4_Processor::TrackHandler*
+AP4_Processor::TrackHandler*
AP4_StandardDecryptingProcessor::CreateTrackHandler(AP4_TrakAtom* trak)
{
// find the stsd atom
AP4_StsdAtom* stsd = AP4_DYNAMIC_CAST(AP4_StsdAtom, trak->FindChild("mdia/minf/stbl/stsd"));
// avoid tracks with no stsd atom (should not happen)
- if(stsd == NULL) return NULL;
+ if (stsd == NULL) return NULL;
// we only look at the first sample description
AP4_SampleDescription* desc = stsd->GetSampleDescription(0);
AP4_SampleEntry* entry = stsd->GetSampleEntry(0);
- if(desc == NULL || entry == NULL) return NULL;
- if(desc->GetType() == AP4_SampleDescription::TYPE_PROTECTED)
- {
+ if (desc == NULL || entry == NULL) return NULL;
+ if (desc->GetType() == AP4_SampleDescription::TYPE_PROTECTED) {
// create a handler for this track
- AP4_ProtectedSampleDescription* protected_desc =
+ AP4_ProtectedSampleDescription* protected_desc =
static_cast<AP4_ProtectedSampleDescription*>(desc);
- if(protected_desc->GetSchemeType() == AP4_PROTECTION_SCHEME_TYPE_OMA)
- {
+ if (protected_desc->GetSchemeType() == AP4_PROTECTION_SCHEME_TYPE_OMA) {
const AP4_UI08* key = m_KeyMap.GetKey(trak->GetId());
- if(key)
- {
+ if (key) {
AP4_OmaDcfTrackDecrypter* handler = NULL;
- AP4_Result result = AP4_OmaDcfTrackDecrypter::Create(key,
- AP4_CIPHER_BLOCK_SIZE,
- protected_desc,
- entry,
- m_BlockCipherFactory,
- handler);
- if(AP4_FAILED(result)) return NULL;
+ AP4_Result result = AP4_OmaDcfTrackDecrypter::Create(key,
+ AP4_CIPHER_BLOCK_SIZE,
+ protected_desc,
+ entry,
+ m_BlockCipherFactory,
+ handler);
+ if (AP4_FAILED(result)) return NULL;
return handler;
}
- }
- else if(protected_desc->GetSchemeType() == AP4_PROTECTION_SCHEME_TYPE_IAEC)
- {
+ } else if (protected_desc->GetSchemeType() == AP4_PROTECTION_SCHEME_TYPE_IAEC) {
const AP4_UI08* key = m_KeyMap.GetKey(trak->GetId());
- if(key)
- {
+ if (key) {
AP4_IsmaTrackDecrypter* handler = NULL;
- AP4_Result result = AP4_IsmaTrackDecrypter::Create(key,
- AP4_CIPHER_BLOCK_SIZE,
- protected_desc,
- entry,
- m_BlockCipherFactory,
- handler);
- if(AP4_FAILED(result)) return NULL;
+ AP4_Result result = AP4_IsmaTrackDecrypter::Create(key,
+ AP4_CIPHER_BLOCK_SIZE,
+ protected_desc,
+ entry,
+ m_BlockCipherFactory,
+ handler);
+ if (AP4_FAILED(result)) return NULL;
return handler;
}
- }
+ }
}
return NULL;
@@ -889,39 +827,36 @@ AP4_DecryptingStream::Create(CipherMode mode,
stream = NULL;
// default cipher settings
- if(block_cipher_factory == NULL)
- {
+ if (block_cipher_factory == NULL) {
block_cipher_factory = &AP4_DefaultBlockCipherFactory::Instance;
}
-
+
// get the encrypted size (includes padding)
AP4_LargeSize encrypted_size = 0;
AP4_Result result = encrypted_stream.GetSize(encrypted_size);
- if(AP4_FAILED(result)) return result;
-
+ if (AP4_FAILED(result)) return result;
+
// check IV
- if(iv == NULL || iv_size != 16) return AP4_ERROR_INVALID_PARAMETERS;
-
+ if (iv == NULL || iv_size != 16) return AP4_ERROR_INVALID_PARAMETERS;
+
// check that the encrypted size is consistent with the cipher mode
- if(mode == CIPHER_MODE_CBC)
- {
+ if (mode == CIPHER_MODE_CBC) {
// we need at least 32 bytes of data+padding
// we also need a multiple of the block size
- if(encrypted_size < 32 || ((encrypted_size % 16) != 0))
- {
+ if (encrypted_size < 32 || ((encrypted_size % 16) != 0)) {
return AP4_ERROR_INVALID_FORMAT;
}
}
-
+
// create the stream cipher
AP4_BlockCipher* block_cipher;
result = block_cipher_factory->Create(AP4_BlockCipher::AES_128,
- (mode == CIPHER_MODE_CTR ?
+ (mode == CIPHER_MODE_CTR ?
AP4_BlockCipher::ENCRYPT :
AP4_BlockCipher::DECRYPT),
key, key_size, block_cipher);
- if(AP4_FAILED(result)) return result;
-
+ if (AP4_FAILED(result)) return result;
+
// keep a reference to the source stream
encrypted_stream.AddReference();
@@ -937,24 +872,23 @@ AP4_DecryptingStream::Create(CipherMode mode,
dec_stream->m_BufferFullness = 0;
dec_stream->m_BufferOffset = 0;
dec_stream->m_ReferenceCount = 1;
-
+
// create the cipher according to the mode
- switch(mode)
- {
- case CIPHER_MODE_CBC:
- dec_stream->m_StreamCipher = new AP4_CbcStreamCipher(block_cipher,
- AP4_StreamCipher::DECRYPT);
- break;
- case CIPHER_MODE_CTR:
- dec_stream->m_StreamCipher = new AP4_CtrStreamCipher(block_cipher,
- NULL,
- AP4_CIPHER_BLOCK_SIZE);
- break;
- default:
- // should never occur
- AP4_ASSERT(0);
+ switch (mode) {
+ case CIPHER_MODE_CBC:
+ dec_stream->m_StreamCipher = new AP4_CbcStreamCipher(block_cipher,
+ AP4_StreamCipher::DECRYPT);
+ break;
+ case CIPHER_MODE_CTR:
+ dec_stream->m_StreamCipher = new AP4_CtrStreamCipher(block_cipher,
+ NULL,
+ AP4_CIPHER_BLOCK_SIZE);
+ break;
+ default:
+ // should never occur
+ AP4_ASSERT(0);
}
-
+
// set the IV
dec_stream->m_StreamCipher->SetIV(iv);
@@ -973,7 +907,7 @@ AP4_DecryptingStream::~AP4_DecryptingStream()
/*----------------------------------------------------------------------
| AP4_DecryptingStream::AddReference
+---------------------------------------------------------------------*/
-void
+void
AP4_DecryptingStream::AddReference()
{
++m_ReferenceCount;
@@ -982,40 +916,37 @@ AP4_DecryptingStream::AddReference()
/*----------------------------------------------------------------------
| AP4_DecryptingStream::Release
+---------------------------------------------------------------------*/
-void
+void
AP4_DecryptingStream::Release()
{
- if(--m_ReferenceCount == 0) delete this;
+ if (--m_ReferenceCount == 0) delete this;
}
/*----------------------------------------------------------------------
| AP4_DecryptingStream::ReadPartial
+---------------------------------------------------------------------*/
-AP4_Result
-AP4_DecryptingStream::ReadPartial(void* buffer,
- AP4_Size bytes_to_read,
+AP4_Result
+AP4_DecryptingStream::ReadPartial(void* buffer,
+ AP4_Size bytes_to_read,
AP4_Size& bytes_read)
{
bytes_read = 0;
// never read more than what's available
- AP4_LargeSize available = m_CleartextSize - m_CleartextPosition;
- if(available < bytes_to_read)
- {
- if(available == 0)
- {
+ AP4_LargeSize available = m_CleartextSize-m_CleartextPosition;
+ if (available < bytes_to_read) {
+ if (available == 0) {
return AP4_ERROR_EOS;
}
bytes_to_read = (AP4_Size)available;
}
-
- if(m_BufferFullness)
- {
+
+ if (m_BufferFullness) {
// we have some leftovers
AP4_Size chunk = bytes_to_read;
- if(chunk > m_BufferFullness) chunk = m_BufferFullness;
+ if (chunk > m_BufferFullness) chunk = m_BufferFullness;
AP4_CopyMemory(buffer, &m_Buffer[m_BufferOffset], chunk);
- buffer = (char*)buffer + chunk;
+ buffer = (char*)buffer+chunk;
m_CleartextPosition += chunk;
available -= chunk;
bytes_to_read -= chunk;
@@ -1027,45 +958,36 @@ AP4_DecryptingStream::ReadPartial(void* buffer,
// seek to the right place in the input
m_EncryptedStream->Seek(m_EncryptedPosition);
- while(bytes_to_read)
- {
+ while (bytes_to_read) {
// read from the source
AP4_UI08 encrypted[16];
AP4_Size encrypted_read = 0;
AP4_Result result = m_EncryptedStream->ReadPartial(encrypted, 16, encrypted_read);
- if(result == AP4_ERROR_EOS)
- {
- if(bytes_read == 0)
- {
+ if (result == AP4_ERROR_EOS) {
+ if (bytes_read == 0) {
return AP4_ERROR_EOS;
- }
- else
- {
+ } else {
return AP4_SUCCESS;
}
- }
- else if(result != AP4_SUCCESS)
- {
+ } else if (result != AP4_SUCCESS) {
return result;
- }
- else
- {
+ } else {
m_EncryptedPosition += encrypted_read;
}
bool is_last_buffer = (m_EncryptedPosition >= m_EncryptedSize);
AP4_Size buffer_size = 16;
- result = m_StreamCipher->ProcessBuffer(encrypted,
- encrypted_read,
- m_Buffer,
+ result = m_StreamCipher->ProcessBuffer(encrypted,
+ encrypted_read,
+ m_Buffer,
&buffer_size,
is_last_buffer);
m_BufferOffset = 0;
m_BufferFullness = buffer_size;
AP4_Size chunk = bytes_to_read;
- if(chunk > m_BufferFullness) chunk = m_BufferFullness;
+ if (chunk > m_BufferFullness) chunk = m_BufferFullness;
AP4_CopyMemory(buffer, &m_Buffer[m_BufferOffset], chunk);
- buffer = (char*)buffer + chunk;
+ buffer = (char*)buffer+chunk;
m_CleartextPosition += chunk;
available -= chunk;
bytes_to_read -= chunk;
@@ -1080,9 +1002,9 @@ AP4_DecryptingStream::ReadPartial(void* buffer,
/*----------------------------------------------------------------------
| AP4_DecryptingStream::WritePartial
+---------------------------------------------------------------------*/
-AP4_Result
-AP4_DecryptingStream::WritePartial(const void* /* buffer */,
- AP4_Size /* bytes_to_write */,
+AP4_Result
+AP4_DecryptingStream::WritePartial(const void* /* buffer */,
+ AP4_Size /* bytes_to_write */,
AP4_Size& /* bytes_written */)
{
return AP4_ERROR_NOT_SUPPORTED;
@@ -1091,47 +1013,45 @@ AP4_DecryptingStream::WritePartial(const void* /* buffer */,
/*----------------------------------------------------------------------
| AP4_DecryptingStream::Seek
+---------------------------------------------------------------------*/
-AP4_Result
+AP4_Result
AP4_DecryptingStream::Seek(AP4_Position position)
{
AP4_Cardinal preroll = 0;
-
+
// check bounds
- if(position > m_CleartextSize)
- {
+ if (position > m_CleartextSize) {
return AP4_ERROR_INVALID_PARAMETERS;
}
-
+
// try to put the stream cipher at the right offset
AP4_CHECK(m_StreamCipher->SetStreamOffset(position, &preroll));
// seek in the source stream
- AP4_CHECK(m_EncryptedStream->Seek(position - preroll));
-
+ AP4_CHECK(m_EncryptedStream->Seek(position-preroll));
+
// if we need to, process the preroll bytes
- if(preroll > 0)
- {
+ if (preroll > 0) {
AP4_Size out_size = 0;
AP4_UI08 buffer[2*AP4_CIPHER_BLOCK_SIZE]; // bigger than preroll
AP4_CHECK(m_EncryptedStream->Read(buffer, preroll));
AP4_CHECK(m_StreamCipher->ProcessBuffer(buffer, preroll, buffer, &out_size));
- AP4_ASSERT(out_size == 0); // we're just feeding prerolled bytes,
- // there can be no output
+ AP4_ASSERT(out_size == 0); // we're just feeding prerolled bytes,
+ // there can be no output
}
-
+
// update the counters
m_CleartextPosition = position;
m_EncryptedPosition = position;
m_BufferFullness = 0;
m_BufferOffset = 0;
-
+
return AP4_SUCCESS;
}
/*----------------------------------------------------------------------
| AP4_DecryptingStream::Tell
+---------------------------------------------------------------------*/
-AP4_Result
+AP4_Result
AP4_DecryptingStream::Tell(AP4_Position& position)
{
position = m_CleartextPosition;
@@ -1141,7 +1061,7 @@ AP4_DecryptingStream::Tell(AP4_Position& position)
/*----------------------------------------------------------------------
| AP4_DecryptingStream::GetSize
+---------------------------------------------------------------------*/
-AP4_Result
+AP4_Result
AP4_DecryptingStream::GetSize(AP4_LargeSize& size)
{
size = m_CleartextSize;
@@ -1168,25 +1088,24 @@ AP4_EncryptingStream::Create(CipherMode mode,
// get the cleartext size
AP4_LargeSize cleartext_size = 0;
AP4_Result result = cleartext_stream.GetSize(cleartext_size);
- if(AP4_FAILED(result)) return result;
-
+ if (AP4_FAILED(result)) return result;
+
// check IV
- if(iv == NULL || iv_size != 16) return AP4_ERROR_INVALID_PARAMETERS;
-
+ if (iv == NULL || iv_size != 16) return AP4_ERROR_INVALID_PARAMETERS;
+
// compute the encrypted size
AP4_LargeSize encrypted_size = cleartext_size;
- if(mode == CIPHER_MODE_CBC)
- {
- encrypted_size += (16 - (cleartext_size % 16)); // with padding
+ if (mode == CIPHER_MODE_CBC) {
+ encrypted_size += (16-(cleartext_size%16)); // with padding
}
-
+
// create the stream cipher
AP4_BlockCipher* block_cipher;
result = block_cipher_factory->Create(AP4_BlockCipher::AES_128,
AP4_BlockCipher::ENCRYPT,
key, key_size, block_cipher);
- if(AP4_FAILED(result)) return result;
-
+ if (AP4_FAILED(result)) return result;
+
// keep a reference to the source stream
cleartext_stream.AddReference();
@@ -1204,30 +1123,28 @@ AP4_EncryptingStream::Create(CipherMode mode,
enc_stream->m_ReferenceCount = 1;
// deal with the prepended IV if required
- if(prepend_iv)
- {
+ if (prepend_iv) {
enc_stream->m_EncryptedSize += 16;
enc_stream->m_BufferFullness = 16;
AP4_CopyMemory(enc_stream->m_Buffer, iv, 16);
}
-
+
// create the cipher according to the mode
- switch(mode)
- {
- case CIPHER_MODE_CBC:
- enc_stream->m_StreamCipher = new AP4_CbcStreamCipher(block_cipher,
- AP4_StreamCipher::ENCRYPT);
- break;
- case CIPHER_MODE_CTR:
- enc_stream->m_StreamCipher = new AP4_CtrStreamCipher(block_cipher,
- NULL,
- AP4_CIPHER_BLOCK_SIZE);
- break;
- default:
- // should never occur
- AP4_ASSERT(0);
+ switch (mode) {
+ case CIPHER_MODE_CBC:
+ enc_stream->m_StreamCipher = new AP4_CbcStreamCipher(block_cipher,
+ AP4_StreamCipher::ENCRYPT);
+ break;
+ case CIPHER_MODE_CTR:
+ enc_stream->m_StreamCipher = new AP4_CtrStreamCipher(block_cipher,
+ NULL,
+ AP4_CIPHER_BLOCK_SIZE);
+ break;
+ default:
+ // should never occur
+ AP4_ASSERT(0);
}
-
+
// set the IV
enc_stream->m_StreamCipher->SetIV(iv);
@@ -1246,7 +1163,7 @@ AP4_EncryptingStream::~AP4_EncryptingStream()
/*----------------------------------------------------------------------
| AP4_EncryptingStream::AddReference
+---------------------------------------------------------------------*/
-void
+void
AP4_EncryptingStream::AddReference()
{
++m_ReferenceCount;
@@ -1255,37 +1172,35 @@ AP4_EncryptingStream::AddReference()
/*----------------------------------------------------------------------
| AP4_EncryptingStream::Release
+---------------------------------------------------------------------*/
-void
+void
AP4_EncryptingStream::Release()
{
- if(--m_ReferenceCount == 0) delete this;
+ if (--m_ReferenceCount == 0) delete this;
}
/*----------------------------------------------------------------------
| AP4_EncryptingStream::ReadPartial
+---------------------------------------------------------------------*/
-AP4_Result
-AP4_EncryptingStream::ReadPartial(void* buffer,
- AP4_Size bytes_to_read,
+AP4_Result
+AP4_EncryptingStream::ReadPartial(void* buffer,
+ AP4_Size bytes_to_read,
AP4_Size& bytes_read)
{
bytes_read = 0;
// never read more than what's available
- AP4_LargeSize available = m_EncryptedSize - m_EncryptedPosition;
- if(available < bytes_to_read)
- {
- if(available == 0) return AP4_ERROR_EOS;
+ AP4_LargeSize available = m_EncryptedSize-m_EncryptedPosition;
+ if (available < bytes_to_read) {
+ if (available == 0) return AP4_ERROR_EOS;
bytes_to_read = (AP4_Size)available;
}
-
- if(m_BufferFullness)
- {
+
+ if (m_BufferFullness) {
// we have some leftovers
AP4_Size chunk = bytes_to_read;
- if(chunk > m_BufferFullness) chunk = m_BufferFullness;
+ if (chunk > m_BufferFullness) chunk = m_BufferFullness;
AP4_CopyMemory(buffer, &m_Buffer[m_BufferOffset], chunk);
- buffer = (char*)buffer + chunk;
+ buffer = (char*)buffer+chunk;
m_EncryptedPosition += chunk;
available -= chunk;
bytes_to_read -= chunk;
@@ -1297,47 +1212,37 @@ AP4_EncryptingStream::ReadPartial(void* buffer,
// seek to the right place in the input
m_CleartextStream->Seek(m_CleartextPosition);
- while(bytes_to_read)
- {
+ while (bytes_to_read) {
// read from the source
AP4_UI08 cleartext[16];
AP4_Size cleartext_read = 0;
AP4_Result result = m_CleartextStream->ReadPartial(cleartext, 16, cleartext_read);
- if(result == AP4_ERROR_EOS)
- {
- if(bytes_read == 0)
- {
+ if (result == AP4_ERROR_EOS) {
+ if (bytes_read == 0) {
return AP4_ERROR_EOS;
- }
- else
- {
+ } else {
return AP4_SUCCESS;
}
- }
- else if(result != AP4_SUCCESS)
- {
+ } else if (result != AP4_SUCCESS) {
return result;
- }
- else
- {
+ } else {
m_CleartextPosition += cleartext_read;
}
bool is_last_buffer = (m_CleartextPosition >= m_CleartextSize);
AP4_Size buffer_size = 32; // enough for one block plus one block padding
- result = m_StreamCipher->ProcessBuffer(cleartext,
- cleartext_read,
- m_Buffer,
+ result = m_StreamCipher->ProcessBuffer(cleartext,
+ cleartext_read,
+ m_Buffer,
&buffer_size,
is_last_buffer);
m_BufferOffset = 0;
m_BufferFullness = buffer_size;
AP4_Size chunk = bytes_to_read;
- if(chunk > m_BufferFullness) chunk = m_BufferFullness;
- if(chunk)
- {
+ if (chunk > m_BufferFullness) chunk = m_BufferFullness;
+ if (chunk) {
AP4_CopyMemory(buffer, &m_Buffer[m_BufferOffset], chunk);
- buffer = (char*)buffer + chunk;
+ buffer = (char*)buffer+chunk;
m_EncryptedPosition += chunk;
available -= chunk;
bytes_to_read -= chunk;
@@ -1353,9 +1258,9 @@ AP4_EncryptingStream::ReadPartial(void* buffer,
/*----------------------------------------------------------------------
| AP4_EncryptingStream::WritePartial
+---------------------------------------------------------------------*/
-AP4_Result
-AP4_EncryptingStream::WritePartial(const void* /* buffer */,
- AP4_Size /* bytes_to_write */,
+AP4_Result
+AP4_EncryptingStream::WritePartial(const void* /* buffer */,
+ AP4_Size /* bytes_to_write */,
AP4_Size& /* bytes_written */)
{
return AP4_ERROR_NOT_SUPPORTED;
@@ -1364,15 +1269,12 @@ AP4_EncryptingStream::WritePartial(const void* /* buffer */,
/*----------------------------------------------------------------------
| AP4_EncryptingStream::Seek
+---------------------------------------------------------------------*/
-AP4_Result
+AP4_Result
AP4_EncryptingStream::Seek(AP4_Position position)
{
- if(position == m_EncryptedPosition)
- {
+ if (position == m_EncryptedPosition) {
return AP4_SUCCESS;
- }
- else
- {
+ } else {
return AP4_ERROR_NOT_SUPPORTED;
}
}
@@ -1380,7 +1282,7 @@ AP4_EncryptingStream::Seek(AP4_Position position)
/*----------------------------------------------------------------------
| AP4_EncryptingStream::Tell
+---------------------------------------------------------------------*/
-AP4_Result
+AP4_Result
AP4_EncryptingStream::Tell(AP4_Position& position)
{
position = m_EncryptedPosition;
@@ -1390,7 +1292,7 @@ AP4_EncryptingStream::Tell(AP4_Position& position)
/*----------------------------------------------------------------------
| AP4_EncryptingStream::GetSize
+---------------------------------------------------------------------*/
-AP4_Result
+AP4_Result
AP4_EncryptingStream::GetSize(AP4_LargeSize& size)
{
size = m_EncryptedSize;
@@ -1415,21 +1317,19 @@ AP4_DefaultBlockCipherFactory::Create(AP4_BlockCipher::CipherType type,
// setup default return vaule
cipher = NULL;
- switch(type)
- {
- case AP4_BlockCipher::AES_128:
- // check cipher parameters
- if(key == NULL || key_size != AP4_AES_BLOCK_SIZE)
- {
- return AP4_ERROR_INVALID_PARAMETERS;
- }
+ switch (type) {
+ case AP4_BlockCipher::AES_128:
+ // check cipher parameters
+ if (key == NULL || key_size != AP4_AES_BLOCK_SIZE) {
+ return AP4_ERROR_INVALID_PARAMETERS;
+ }
- // create the cipher
- cipher = new AP4_AesBlockCipher(key, direction);
- return AP4_SUCCESS;
+ // create the cipher
+ cipher = new AP4_AesBlockCipher(key, direction);
+ return AP4_SUCCESS;
- default:
- // not supported
- return AP4_ERROR_NOT_SUPPORTED;
+ default:
+ // not supported
+ return AP4_ERROR_NOT_SUPPORTED;
}
}
diff --git a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4Protection.h b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4Protection.h
index a7ff9f678..1979193ad 100644
--- a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4Protection.h
+++ b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4Protection.h
@@ -50,7 +50,7 @@ class AP4_StreamCipher;
// this is fixed for now
const unsigned int AP4_PROTECTION_KEY_LENGTH = 16;
-const AP4_UI32 AP4_PROTECTION_SCHEME_TYPE_ITUNES = AP4_ATOM_TYPE('i', 't', 'u', 'n');
+const AP4_UI32 AP4_PROTECTION_SCHEME_TYPE_ITUNES = AP4_ATOM_TYPE('i','t','u','n');
/*----------------------------------------------------------------------
| AP4_EncaSampleEntry
@@ -71,7 +71,7 @@ public:
AP4_SampleDescription* ToSampleDescription();
// this method is used as a factory by the ISMACryp classes
- // NOTE: this should be named ToSampleDescription, but C++ has a
+ // NOTE: this should be named ToSampleDescription, but C++ has a
// problem with that because the base class does not have this
// overloaded method, but has another other one by that name
virtual AP4_SampleDescription* ToTargetSampleDescription(AP4_UI32 format);
@@ -96,7 +96,7 @@ public:
AP4_SampleDescription* ToSampleDescription();
// this method is used as a factory by the ISMACryp classes
- // NOTE: this should be named ToSampleDescription, but C++ has a
+ // NOTE: this should be named ToSampleDescription, but C++ has a
// problem with that because the base class does not have this
// overloaded method, but has another other one by that name
virtual AP4_SampleDescription* ToTargetSampleDescription(AP4_UI32 format);
@@ -144,8 +144,7 @@ public:
private:
// types
- class KeyEntry
- {
+ class KeyEntry {
public:
KeyEntry(AP4_UI32 track_id, const AP4_UI08* key, const AP4_UI08* iv = NULL);
void SetKey(const AP4_UI08* key, const AP4_UI08* iv);
@@ -172,18 +171,17 @@ public:
AP4_Result SetProperties(const AP4_TrackPropertyMap& properties);
const char* GetProperty(AP4_UI32 track_id, const char* name);
AP4_Result GetTextualHeaders(AP4_UI32 track_id, AP4_DataBuffer& buffer);
-
+
// destructor
virtual ~AP4_TrackPropertyMap();
private:
// types
- class Entry
- {
+ class Entry {
public:
Entry(AP4_UI32 track_id, const char* name, const char* value) :
- m_TrackId(track_id), m_Name(name), m_Value(value) {}
+ m_TrackId(track_id), m_Name(name), m_Value(value) {}
AP4_UI32 m_TrackId;
AP4_String m_Name;
AP4_String m_Value;
@@ -204,10 +202,7 @@ public:
virtual ~AP4_ProtectionSchemeInfo();
// accessors
- AP4_ContainerAtom* GetSchiAtom()
- {
- return m_SchiAtom;
- }
+ AP4_ContainerAtom* GetSchiAtom() { return m_SchiAtom; }
protected:
AP4_ContainerAtom* m_SchiAtom;
@@ -229,33 +224,19 @@ public:
AP4_UI32 scheme_version,
const char* scheme_uri,
AP4_ContainerAtom* schi_atom, // will be cloned
- bool transfer_ownership_of_original = true);
+ bool transfer_ownership_of_original=true);
~AP4_ProtectedSampleDescription();
-
+
// accessors
- AP4_SampleDescription* GetOriginalSampleDescription()
- {
+ AP4_SampleDescription* GetOriginalSampleDescription() {
return m_OriginalSampleDescription;
}
- AP4_UI32 GetOriginalFormat() const
- {
- return m_OriginalFormat;
- }
- AP4_UI32 GetSchemeType() const
- {
- return m_SchemeType;
- }
- AP4_UI32 GetSchemeVersion() const
- {
- return m_SchemeVersion;
- }
- const AP4_String& GetSchemeUri() const
- {
- return m_SchemeUri;
- }
- AP4_ProtectionSchemeInfo* GetSchemeInfo() const
- {
- return m_SchemeInfo;
+ AP4_UI32 GetOriginalFormat() const { return m_OriginalFormat; }
+ AP4_UI32 GetSchemeType() const { return m_SchemeType; }
+ AP4_UI32 GetSchemeVersion() const { return m_SchemeVersion; }
+ const AP4_String& GetSchemeUri() const { return m_SchemeUri; }
+ AP4_ProtectionSchemeInfo* GetSchemeInfo() const {
+ return m_SchemeInfo;
}
// implementation of abstract base class methods
@@ -279,20 +260,18 @@ class AP4_BlockCipher
{
public:
// types
- typedef enum
- {
+ typedef enum {
ENCRYPT,
DECRYPT
} CipherDirection;
- typedef enum
- {
+ typedef enum {
AES_128
} CipherType;
// constructor and destructor
virtual ~AP4_BlockCipher() {}
-
+
// methods
virtual AP4_Result ProcessBlock(const AP4_UI08* block_in, AP4_UI08* block_out) = 0;
};
@@ -356,14 +335,8 @@ public:
virtual ~AP4_SampleDecrypter() {}
// methods
- virtual AP4_Size GetDecryptedSampleSize(AP4_Sample& sample)
- {
- return sample.GetSize();
- }
- virtual AP4_Result SetSampleIndex(AP4_Ordinal /*index*/)
- {
- return AP4_SUCCESS;
- }
+ virtual AP4_Size GetDecryptedSampleSize(AP4_Sample& sample) { return sample.GetSize(); }
+ virtual AP4_Result SetSampleIndex(AP4_Ordinal /*index*/) { return AP4_SUCCESS; }
virtual AP4_Result DecryptSampleData(AP4_DataBuffer& data_in,
AP4_DataBuffer& data_out,
const AP4_UI08* iv = NULL) = 0;
@@ -380,11 +353,8 @@ public:
AP4_BlockCipherFactory* block_cipher_factory = NULL);
// accessors
- AP4_ProtectionKeyMap& GetKeyMap()
- {
- return m_KeyMap;
- }
-
+ AP4_ProtectionKeyMap& GetKeyMap() { return m_KeyMap; }
+
// methods
virtual AP4_Result Initialize(AP4_AtomParent& top_level,
AP4_ByteStream& stream,
@@ -400,11 +370,9 @@ private:
/*----------------------------------------------------------------------
| AP4_DecryptingStream
+---------------------------------------------------------------------*/
-class AP4_DecryptingStream : public AP4_ByteStream
-{
+class AP4_DecryptingStream : public AP4_ByteStream {
public:
- typedef enum
- {
+ typedef enum {
CIPHER_MODE_CTR,
CIPHER_MODE_CBC
} CipherMode;
@@ -420,11 +388,11 @@ public:
AP4_ByteStream*& stream);
// AP4_ByteStream methods
- virtual AP4_Result ReadPartial(void* buffer,
- AP4_Size bytes_to_read,
+ virtual AP4_Result ReadPartial(void* buffer,
+ AP4_Size bytes_to_read,
AP4_Size& bytes_read);
- virtual AP4_Result WritePartial(const void* buffer,
- AP4_Size bytes_to_write,
+ virtual AP4_Result WritePartial(const void* buffer,
+ AP4_Size bytes_to_write,
AP4_Size& bytes_written);
virtual AP4_Result Seek(AP4_Position position);
virtual AP4_Result Tell(AP4_Position& position);
@@ -456,11 +424,9 @@ private:
/*----------------------------------------------------------------------
| AP4_EncryptingStream
+---------------------------------------------------------------------*/
-class AP4_EncryptingStream : public AP4_ByteStream
-{
+class AP4_EncryptingStream : public AP4_ByteStream {
public:
- typedef enum
- {
+ typedef enum {
CIPHER_MODE_CTR,
CIPHER_MODE_CBC
} CipherMode;
@@ -476,11 +442,11 @@ public:
AP4_ByteStream*& stream);
// AP4_ByteStream methods
- virtual AP4_Result ReadPartial(void* buffer,
- AP4_Size bytes_to_read,
+ virtual AP4_Result ReadPartial(void* buffer,
+ AP4_Size bytes_to_read,
AP4_Size& bytes_read);
- virtual AP4_Result WritePartial(const void* buffer,
- AP4_Size bytes_to_write,
+ virtual AP4_Result WritePartial(const void* buffer,
+ AP4_Size bytes_to_write,
AP4_Size& bytes_written);
virtual AP4_Result Seek(AP4_Position position);
virtual AP4_Result Tell(AP4_Position& position);
diff --git a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4Results.cpp b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4Results.cpp
index 6dbd42fd8..1bb2c5cd8 100644
--- a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4Results.cpp
+++ b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4Results.cpp
@@ -39,55 +39,30 @@
const char*
AP4_ResultText(int result)
{
- switch(result)
- {
- case AP4_SUCCESS:
- return "AP4_SUCCESS";
- case AP4_FAILURE:
- return "AP4_FAILURE";
- case AP4_ERROR_OUT_OF_MEMORY:
- return "AP4_ERROR_OUT_OF_MEMORY";
- case AP4_ERROR_INVALID_PARAMETERS:
- return "AP4_ERROR_INVALID_PARAMETERS";
- case AP4_ERROR_NO_SUCH_FILE:
- return "AP4_ERROR_NO_SUCH_FILE";
- case AP4_ERROR_PERMISSION_DENIED:
- return "AP4_ERROR_PERMISSION_DENIED";
- case AP4_ERROR_CANNOT_OPEN_FILE:
- return "AP4_ERROR_CANNOT_OPEN_FILE";
- case AP4_ERROR_EOS:
- return "AP4_ERROR_EOS";
- case AP4_ERROR_WRITE_FAILED:
- return "AP4_ERROR_WRITE_FAILED";
- case AP4_ERROR_READ_FAILED:
- return "AP4_ERROR_READ_FAILED";
- case AP4_ERROR_INVALID_FORMAT:
- return "AP4_ERROR_INVALID_FORMAT";
- case AP4_ERROR_NO_SUCH_ITEM:
- return "AP4_ERROR_NO_SUCH_ITEM";
- case AP4_ERROR_OUT_OF_RANGE:
- return "AP4_ERROR_OUT_OF_RANGE";
- case AP4_ERROR_INTERNAL:
- return "AP4_ERROR_INTERNAL";
- case AP4_ERROR_INVALID_STATE:
- return "AP4_ERROR_INVALID_STATE";
- case AP4_ERROR_LIST_EMPTY:
- return "AP4_ERROR_LIST_EMPTY";
- case AP4_ERROR_LIST_OPERATION_ABORTED:
- return "AP4_ERROR_LIST_OPERATION_ABORTED";
- case AP4_ERROR_INVALID_RTP_CONSTRUCTOR_TYPE:
- return "AP4_ERROR_INVALID_RTP_CONSTRUCTOR_TYPE";
- case AP4_ERROR_NOT_SUPPORTED:
- return "AP4_ERROR_NOT_SUPPORTED";
- case AP4_ERROR_INVALID_TRACK_TYPE:
- return "AP4_ERROR_INVALID_TRACK_TYPE";
- case AP4_ERROR_INVALID_RTP_PACKET_EXTRA_DATA:
- return "AP4_ERROR_INVALID_RTP_PACKET_EXTRA_DATA";
- case AP4_ERROR_BUFFER_TOO_SMALL:
- return "AP4_ERROR_BUFFER_TOO_SMALL";
- case AP4_ERROR_NOT_ENOUGH_DATA:
- return "AP4_ERROR_NOT_ENOUGH_DATA";
- default:
- return "UNKNOWN";
+ switch (result) {
+ case AP4_SUCCESS: return "AP4_SUCCESS";
+ case AP4_FAILURE: return "AP4_FAILURE";
+ case AP4_ERROR_OUT_OF_MEMORY: return "AP4_ERROR_OUT_OF_MEMORY";
+ case AP4_ERROR_INVALID_PARAMETERS: return "AP4_ERROR_INVALID_PARAMETERS";
+ case AP4_ERROR_NO_SUCH_FILE: return "AP4_ERROR_NO_SUCH_FILE";
+ case AP4_ERROR_PERMISSION_DENIED: return "AP4_ERROR_PERMISSION_DENIED";
+ case AP4_ERROR_CANNOT_OPEN_FILE: return "AP4_ERROR_CANNOT_OPEN_FILE";
+ case AP4_ERROR_EOS: return "AP4_ERROR_EOS";
+ case AP4_ERROR_WRITE_FAILED: return "AP4_ERROR_WRITE_FAILED";
+ case AP4_ERROR_READ_FAILED: return "AP4_ERROR_READ_FAILED";
+ case AP4_ERROR_INVALID_FORMAT: return "AP4_ERROR_INVALID_FORMAT";
+ case AP4_ERROR_NO_SUCH_ITEM: return "AP4_ERROR_NO_SUCH_ITEM";
+ case AP4_ERROR_OUT_OF_RANGE: return "AP4_ERROR_OUT_OF_RANGE";
+ case AP4_ERROR_INTERNAL: return "AP4_ERROR_INTERNAL";
+ case AP4_ERROR_INVALID_STATE: return "AP4_ERROR_INVALID_STATE";
+ case AP4_ERROR_LIST_EMPTY: return "AP4_ERROR_LIST_EMPTY";
+ case AP4_ERROR_LIST_OPERATION_ABORTED: return "AP4_ERROR_LIST_OPERATION_ABORTED";
+ case AP4_ERROR_INVALID_RTP_CONSTRUCTOR_TYPE: return "AP4_ERROR_INVALID_RTP_CONSTRUCTOR_TYPE";
+ case AP4_ERROR_NOT_SUPPORTED: return "AP4_ERROR_NOT_SUPPORTED";
+ case AP4_ERROR_INVALID_TRACK_TYPE: return "AP4_ERROR_INVALID_TRACK_TYPE";
+ case AP4_ERROR_INVALID_RTP_PACKET_EXTRA_DATA: return "AP4_ERROR_INVALID_RTP_PACKET_EXTRA_DATA";
+ case AP4_ERROR_BUFFER_TOO_SMALL: return "AP4_ERROR_BUFFER_TOO_SMALL";
+ case AP4_ERROR_NOT_ENOUGH_DATA: return "AP4_ERROR_NOT_ENOUGH_DATA";
+ default: return "UNKNOWN";
}
}
diff --git a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4RtpAtom.cpp b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4RtpAtom.cpp
index 5308cf363..ad46363cd 100644
--- a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4RtpAtom.cpp
+++ b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4RtpAtom.cpp
@@ -1,6 +1,6 @@
/*****************************************************************
|
-| AP4 - sdp Atoms
+| AP4 - sdp Atoms
|
| Copyright 2002-2008 Axiomatic Systems, LLC
|
@@ -44,9 +44,8 @@ AP4_RtpAtom::AP4_RtpAtom(AP4_UI32 size, AP4_ByteStream& stream) :
stream.ReadUI32(m_DescriptionFormat);
// sdptext
- int str_size = size - (AP4_ATOM_HEADER_SIZE + 4);
- if(str_size)
- {
+ int str_size = size-(AP4_ATOM_HEADER_SIZE+4);
+ if (str_size) {
char* str = new char[str_size+1];
stream.Read(str, str_size);
str[str_size] = '\0'; // force null-termination
@@ -65,16 +64,16 @@ AP4_RtpAtom::WriteFields(AP4_ByteStream& stream)
// description format
result = stream.WriteUI32(m_DescriptionFormat);
- if(AP4_FAILED(result)) return result;
+ if (AP4_FAILED(result)) return result;
// sdp text
result = stream.Write(m_SdpText.GetChars(), m_SdpText.GetLength());
- if(AP4_FAILED(result)) return result;
+ if (AP4_FAILED(result)) return result;
// pad with zeros if necessary
- AP4_Size padding = m_Size32 - (AP4_ATOM_HEADER_SIZE + 4 + m_SdpText.GetLength());
- while(padding--) stream.WriteUI08(0);
-
+ AP4_Size padding = m_Size32-(AP4_ATOM_HEADER_SIZE+4+m_SdpText.GetLength());
+ while (padding--) stream.WriteUI08(0);
+
return AP4_SUCCESS;
}
diff --git a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4RtpAtom.h b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4RtpAtom.h
index 1f30eebdc..596d96cfc 100644
--- a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4RtpAtom.h
+++ b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4RtpAtom.h
@@ -1,6 +1,6 @@
/*****************************************************************
|
-| AP4 - rtp Atoms
+| AP4 - rtp Atoms
|
| Copyright 2002-2008 Axiomatic Systems, LLC
|
@@ -49,16 +49,12 @@ class AP4_RtpAtom : public AP4_Atom
{
public:
// class methods
- static AP4_RtpAtom* Create(AP4_Size size, AP4_ByteStream& stream)
- {
+ static AP4_RtpAtom* Create(AP4_Size size, AP4_ByteStream& stream) {
return new AP4_RtpAtom(size, stream);
}
// methods
- const AP4_String& GetSdpText()
- {
- return m_SdpText;
- }
+ const AP4_String& GetSdpText() { return m_SdpText; }
virtual AP4_Result InspectFields(AP4_AtomInspector& inspector);
virtual AP4_Result WriteFields(AP4_ByteStream& stream);
diff --git a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4RtpHint.cpp b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4RtpHint.cpp
index 71b1f915a..3f9f19c0e 100644
--- a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4RtpHint.cpp
+++ b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4RtpHint.cpp
@@ -38,8 +38,7 @@
AP4_RtpSampleData::~AP4_RtpSampleData()
{
AP4_List<AP4_RtpPacket>::Item* it = m_Packets.FirstItem();
- while(it != NULL)
- {
+ while (it != NULL) {
it->GetData()->Release();
it = it->GetNext();
}
@@ -56,22 +55,20 @@ AP4_RtpSampleData::AP4_RtpSampleData(AP4_ByteStream& stream, AP4_UI32 size)
AP4_UI16 packet_count;
stream.ReadUI16(packet_count);
-
+
AP4_UI16 reserved;
stream.ReadUI16(reserved); // later, check that reserved is 0
// packets
- for(AP4_UI16 i = 0; i < packet_count; i++)
- {
+ for (AP4_UI16 i=0; i<packet_count; i++) {
AP4_RtpPacket* packet = new AP4_RtpPacket(stream);
m_Packets.Add(packet);
}
// extra data
stream.Tell(extra_data_start);
- AP4_Size extra_data_size = size - (AP4_UI32)(extra_data_start - start);
- if(extra_data_size != 0)
- {
+ AP4_Size extra_data_size = size - (AP4_UI32)(extra_data_start-start);
+ if (extra_data_size != 0) {
m_ExtraData.SetDataSize(extra_data_size);
stream.Read(m_ExtraData.UseData(), extra_data_size);
}
@@ -88,8 +85,7 @@ AP4_RtpSampleData::GetSize()
// packets
AP4_List<AP4_RtpPacket>::Item* it = m_Packets.FirstItem();
- while(it != NULL)
- {
+ while (it != NULL) {
result = it->GetData()->GetSize();
it = it->GetNext();
}
@@ -114,23 +110,22 @@ AP4_RtpSampleData::ToByteStream()
// write in it
AP4_Result result = stream->WriteUI16(static_cast<AP4_UI16>(m_Packets.ItemCount()));
- if(AP4_FAILED(result)) goto bail;
+ if (AP4_FAILED(result)) goto bail;
result = stream->WriteUI16(0); // reserved
- if(AP4_FAILED(result)) goto bail;
+ if (AP4_FAILED(result)) goto bail;
{
AP4_List<AP4_RtpPacket>::Item* it = m_Packets.FirstItem();
- while(it != NULL)
- {
+ while (it != NULL) {
result = it->GetData()->Write(*stream);
- if(AP4_FAILED(result)) goto bail;
+ if (AP4_FAILED(result)) goto bail;
it = it->GetNext();
}
}
result = stream->Write(m_ExtraData.GetData(), m_ExtraData.GetDataSize());
- if(AP4_FAILED(result)) goto bail;
+ if (AP4_FAILED(result)) goto bail;
// return
return stream;
@@ -154,14 +149,14 @@ AP4_RtpSampleData::AddPacket(AP4_RtpPacket* packet)
/*----------------------------------------------------------------------
| AP4_RtpPacket::AP4_RtpPacket
+---------------------------------------------------------------------*/
-AP4_RtpPacket::AP4_RtpPacket(int relative_time,
- bool p_bit,
- bool x_bit,
- bool m_bit,
- AP4_UI08 payload_type,
- AP4_UI16 sequence_seed,
+AP4_RtpPacket::AP4_RtpPacket(int relative_time,
+ bool p_bit,
+ bool x_bit,
+ bool m_bit,
+ AP4_UI08 payload_type,
+ AP4_UI16 sequence_seed,
int time_stamp_offset /* = 0 */,
- bool bframe_flag /* = false */,
+ bool bframe_flag /* = false */,
bool repeat_flag /* = false */) :
m_ReferenceCount(1),
m_RelativeTime(relative_time),
@@ -216,36 +211,31 @@ AP4_RtpPacket::AP4_RtpPacket(AP4_ByteStream& stream) :
stream.ReadUI16(constructor_count);
// parse the packet extra data
- if(extra_flag)
- {
+ if (extra_flag) {
// read the length
AP4_UI32 extra_length;
stream.ReadUI32(extra_length);
- // check it
- if(extra_length < 4) return;
+ // check it
+ if (extra_length < 4) return;
// now read the entries
extra_length -= 4;
- while(extra_length > 0)
- {
+ while (extra_length > 0) {
AP4_UI32 entry_length;
AP4_UI32 entry_tag;
stream.ReadUI32(entry_length);
stream.ReadUI32(entry_tag);
// check the entry
- if(entry_length < 8) return;
+ if (entry_length < 8) return;
// parse the single entry that's currently defined in the spec
- if(entry_tag == AP4_ATOM_TYPE('r', 't', 'p', 'o') && entry_length == 12)
- {
+ if (entry_tag == AP4_ATOM_TYPE('r','t','p','o') && entry_length == 12) {
AP4_UI32 time_stamp_offset;
stream.ReadUI32(time_stamp_offset);
m_TimeStampOffset = time_stamp_offset;
- }
- else
- {
+ } else {
// ignore it
AP4_Position cur_pos;
stream.Tell(cur_pos);
@@ -257,8 +247,7 @@ AP4_RtpPacket::AP4_RtpPacket(AP4_ByteStream& stream) :
}
// constructors
- for(AP4_UI16 i = 0; i < constructor_count; i++)
- {
+ for (AP4_UI16 i=0; i<constructor_count; i++) {
AP4_RtpConstructor* constructor = NULL;
AP4_RtpConstructorFactory::CreateConstructorFromStream(stream, constructor);
m_Constructors.Add(constructor);
@@ -271,8 +260,7 @@ AP4_RtpPacket::AP4_RtpPacket(AP4_ByteStream& stream) :
AP4_RtpPacket::~AP4_RtpPacket()
{
AP4_List<AP4_RtpConstructor>::Item* it = m_Constructors.FirstItem();
- while(it != NULL)
- {
+ while (it != NULL) {
it->GetData()->Release();
it = it->GetNext();
}
@@ -293,8 +281,7 @@ AP4_RtpPacket::AddReference()
void
AP4_RtpPacket::Release()
{
- if(--m_ReferenceCount == 0)
- {
+ if (--m_ReferenceCount == 0) {
delete this;
}
}
@@ -305,7 +292,7 @@ AP4_RtpPacket::Release()
AP4_Size
AP4_RtpPacket::GetSize()
{
- AP4_Size result = 12 + (m_TimeStampOffset != 0) ? 16 : 0;
+ AP4_Size result = 12 + (m_TimeStampOffset != 0)?16:0;
result += m_Constructors.ItemCount() * AP4_RTP_CONSTRUCTOR_SIZE;
return result;
}
@@ -314,60 +301,58 @@ AP4_RtpPacket::GetSize()
| AP4_RtpPacket::Write
+---------------------------------------------------------------------*/
AP4_Result
-AP4_RtpPacket::Write(AP4_ByteStream& stream)
+AP4_RtpPacket::Write(AP4_ByteStream& stream)
{
// check the payload type
- if(m_PayloadType > 128) return AP4_FAILURE;
+ if (m_PayloadType > 128) return AP4_FAILURE;
// now write
AP4_Result result = stream.WriteUI32(m_RelativeTime);
- if(AP4_FAILED(result)) return result;
+ if (AP4_FAILED(result)) return result;
result = stream.WriteUI08(0x80 | m_PBit << 5 | m_XBit << 4);
- if(AP4_FAILED(result)) return result;
+ if (AP4_FAILED(result)) return result;
result = stream.WriteUI08(m_MBit << 7 | m_PayloadType);
- if(AP4_FAILED(result)) return result;
+ if (AP4_FAILED(result)) return result;
result = stream.WriteUI16(m_SequenceSeed);
- if(AP4_FAILED(result)) return result;
+ if (AP4_FAILED(result)) return result;
result = stream.WriteUI08(0);
- if(AP4_FAILED(result)) return result;
+ if (AP4_FAILED(result)) return result;
// deal with extra flag
bool extra_flag = m_TimeStampOffset != 0;
- result = stream.WriteUI08(0x00 | extra_flag << 2
- | m_BFrameFlag << 1
- | m_RepeatFlag << 0);
- if(AP4_FAILED(result)) return result;
+ result = stream.WriteUI08(0x00 | extra_flag << 2
+ | m_BFrameFlag << 1
+ | m_RepeatFlag << 0);
+ if (AP4_FAILED(result)) return result;
// constructor count
result = stream.WriteUI16(static_cast<AP4_UI16>(m_Constructors.ItemCount()));
// write extra data
- if(extra_flag)
- {
+ if (extra_flag) {
// extra_length
result = stream.WriteUI32(16); // 4 (extra_length) + 12 (rtpo atom)
- if(AP4_FAILED(result)) return result;
+ if (AP4_FAILED(result)) return result;
// rtpo atom
result = stream.WriteUI32(12); // size
- if(AP4_FAILED(result)) return result;
- result = stream.WriteUI32(AP4_ATOM_TYPE('r', 't', 'p', 'o'));
- if(AP4_FAILED(result)) return result;
+ if (AP4_FAILED(result)) return result;
+ result = stream.WriteUI32(AP4_ATOM_TYPE('r','t','p','o'));
+ if (AP4_FAILED(result)) return result;
result = stream.WriteUI32(m_TimeStampOffset);
- if(AP4_FAILED(result)) return result;
+ if (AP4_FAILED(result)) return result;
}
// constructors
AP4_List<AP4_RtpConstructor>::Item* it = m_Constructors.FirstItem();
- while(it != NULL)
- {
+ while (it != NULL) {
result = it->GetData()->Write(stream);
- if(AP4_FAILED(result)) return result;
+ if (AP4_FAILED(result)) return result;
it = it->GetNext();
}
return result;
@@ -377,7 +362,7 @@ AP4_RtpPacket::Write(AP4_ByteStream& stream)
| AP4_RtpPacket::AddConstructor
+---------------------------------------------------------------------*/
AP4_Result
-AP4_RtpPacket::AddConstructor(AP4_RtpConstructor* constructor)
+AP4_RtpPacket::AddConstructor(AP4_RtpConstructor* constructor)
{
constructor->AddReference();
return m_Constructors.Add(constructor);
@@ -393,10 +378,9 @@ AP4_RtpPacket::GetConstructedDataSize()
AP4_Size size = 12;
// constructed data from constructors
- AP4_List<AP4_RtpConstructor>::Item* constructors_it
- = m_Constructors.FirstItem();
- while(constructors_it != NULL)
- {
+ AP4_List<AP4_RtpConstructor>::Item* constructors_it
+ = m_Constructors.FirstItem();
+ while (constructors_it != NULL) {
size += constructors_it->GetData()->GetConstructedDataSize();
constructors_it = constructors_it->GetNext();
}
@@ -420,8 +404,7 @@ AP4_RtpConstructor::AddReference()
void
AP4_RtpConstructor::Release()
{
- if(--m_ReferenceCount == 0)
- {
+ if (--m_ReferenceCount == 0) {
delete this;
}
}
@@ -432,7 +415,7 @@ AP4_Result
AP4_RtpConstructor::Write(AP4_ByteStream& stream)
{
AP4_Result result = stream.WriteUI08(m_Type);
- if(AP4_FAILED(result)) return result;
+ if (AP4_FAILED(result)) return result;
return DoWrite(stream);
}
@@ -445,7 +428,7 @@ AP4_NoopRtpConstructor::AP4_NoopRtpConstructor(AP4_ByteStream& stream) :
{
AP4_Position cur_offset;
stream.Tell(cur_offset);
- stream.Seek(cur_offset + 15);
+ stream.Seek(cur_offset+15);
}
/*----------------------------------------------------------------------
@@ -483,7 +466,7 @@ AP4_ImmediateRtpConstructor::AP4_ImmediateRtpConstructor(AP4_ByteStream& stream)
stream.Read(m_Data.UseData(), data_size);
// reposition the stream
- stream.Seek(cur_offset + 15);
+ stream.Seek(cur_offset+15);
}
@@ -494,26 +477,26 @@ AP4_Result
AP4_ImmediateRtpConstructor::DoWrite(AP4_ByteStream& stream)
{
// first check that the data is not too large
- if(m_Data.GetDataSize() > 14) return AP4_FAILURE;
+ if (m_Data.GetDataSize() > 14) return AP4_FAILURE;
// now write
AP4_Result result = stream.WriteUI08(static_cast<AP4_UI08>(m_Data.GetDataSize()));
- if(AP4_FAILED(result)) return result;
+ if (AP4_FAILED(result)) return result;
result = stream.Write(m_Data.GetData(), m_Data.GetDataSize());
- if(AP4_FAILED(result)) return result;
+ if (AP4_FAILED(result)) return result;
// pad
AP4_Byte pad[14];
- return stream.Write(pad, sizeof(pad) - m_Data.GetDataSize());
+ return stream.Write(pad, sizeof(pad)-m_Data.GetDataSize());
}
/*----------------------------------------------------------------------
| AP4_SampleRtpConstructor::AP4_SampleRtpConstructor
+---------------------------------------------------------------------*/
-AP4_SampleRtpConstructor::AP4_SampleRtpConstructor(AP4_UI08 track_ref_index,
- AP4_UI16 length,
- AP4_UI32 sample_num,
- AP4_UI32 sample_offset) :
+AP4_SampleRtpConstructor::AP4_SampleRtpConstructor(AP4_UI08 track_ref_index,
+ AP4_UI16 length,
+ AP4_UI32 sample_num,
+ AP4_UI32 sample_offset) :
AP4_RtpConstructor(AP4_RTP_CONSTRUCTOR_TYPE_SAMPLE),
m_TrackRefIndex(track_ref_index),
m_Length(length),
@@ -538,7 +521,7 @@ AP4_SampleRtpConstructor::AP4_SampleRtpConstructor(AP4_ByteStream& stream) :
stream.ReadUI32(m_SampleOffset);
// reposition the stream
- stream.Seek(cur_offset + 15);
+ stream.Seek(cur_offset+15);
}
/*----------------------------------------------------------------------
| AP4_SampleRtpConstructor::DoWrite
@@ -547,19 +530,19 @@ AP4_Result
AP4_SampleRtpConstructor::DoWrite(AP4_ByteStream& stream)
{
AP4_Result result = stream.WriteUI08(m_TrackRefIndex);
- if(AP4_FAILED(result)) return result;
+ if (AP4_FAILED(result)) return result;
result = stream.WriteUI16(m_Length);
- if(AP4_FAILED(result)) return result;
+ if (AP4_FAILED(result)) return result;
result = stream.WriteUI32(m_SampleNum);
- if(AP4_FAILED(result)) return result;
+ if (AP4_FAILED(result)) return result;
result = stream.WriteUI32(m_SampleOffset);
- if(AP4_FAILED(result)) return result;
+ if (AP4_FAILED(result)) return result;
result = stream.WriteUI16(1); // bytes per block
- if(AP4_FAILED(result)) return result;
+ if (AP4_FAILED(result)) return result;
return stream.WriteUI16(1); // samples per block
}
@@ -567,10 +550,10 @@ AP4_SampleRtpConstructor::DoWrite(AP4_ByteStream& stream)
/*----------------------------------------------------------------------
| AP4_SampleDescRtpConstructor::AP4_SampleDescRtpConstructor
+---------------------------------------------------------------------*/
-AP4_SampleDescRtpConstructor::AP4_SampleDescRtpConstructor(AP4_UI08 track_ref_index,
- AP4_UI16 length,
- AP4_UI32 sample_desc_index,
- AP4_UI32 sample_desc_offset) :
+AP4_SampleDescRtpConstructor::AP4_SampleDescRtpConstructor(AP4_UI08 track_ref_index,
+ AP4_UI16 length,
+ AP4_UI32 sample_desc_index,
+ AP4_UI32 sample_desc_offset) :
AP4_RtpConstructor(AP4_RTP_CONSTRUCTOR_TYPE_SAMPLE_DESC),
m_TrackRefIndex(track_ref_index),
m_Length(length),
@@ -595,7 +578,7 @@ AP4_SampleDescRtpConstructor::AP4_SampleDescRtpConstructor(AP4_ByteStream& strea
stream.ReadUI32(m_SampleDescOffset);
// reposition the stream
- stream.Seek(cur_offset + 15);
+ stream.Seek(cur_offset+15);
}
/*----------------------------------------------------------------------
@@ -605,16 +588,16 @@ AP4_Result
AP4_SampleDescRtpConstructor::DoWrite(AP4_ByteStream& stream)
{
AP4_Result result = stream.WriteUI08(m_TrackRefIndex);
- if(AP4_FAILED(result)) return result;
+ if (AP4_FAILED(result)) return result;
result = stream.WriteUI16(m_Length);
- if(AP4_FAILED(result)) return result;
+ if (AP4_FAILED(result)) return result;
result = stream.WriteUI32(m_SampleDescIndex);
- if(AP4_FAILED(result)) return result;
+ if (AP4_FAILED(result)) return result;
result = stream.WriteUI32(m_SampleDescOffset);
- if(AP4_FAILED(result)) return result;
+ if (AP4_FAILED(result)) return result;
return stream.WriteUI32(0); // reserved
}
@@ -623,31 +606,30 @@ AP4_SampleDescRtpConstructor::DoWrite(AP4_ByteStream& stream)
| AP4_RtpConstructorFactory::CreateConstructorFromStream
+---------------------------------------------------------------------*/
AP4_Result
-AP4_RtpConstructorFactory::CreateConstructorFromStream(AP4_ByteStream& stream,
- AP4_RtpConstructor*& constructor)
+AP4_RtpConstructorFactory::CreateConstructorFromStream(AP4_ByteStream& stream,
+ AP4_RtpConstructor*& constructor)
{
// read the first byte (type)
AP4_RtpConstructor::Type type;
AP4_Result result = stream.ReadUI08(type);
- if(AP4_FAILED(result)) return result;
+ if (AP4_FAILED(result)) return result;
// now create the right constructor
- switch(type)
- {
- case AP4_RTP_CONSTRUCTOR_TYPE_NOOP:
- constructor = new AP4_NoopRtpConstructor(stream);
- break;
- case AP4_RTP_CONSTRUCTOR_TYPE_IMMEDIATE:
- constructor = new AP4_ImmediateRtpConstructor(stream);
- break;
- case AP4_RTP_CONSTRUCTOR_TYPE_SAMPLE:
- constructor = new AP4_SampleRtpConstructor(stream);
- break;
- case AP4_RTP_CONSTRUCTOR_TYPE_SAMPLE_DESC:
- constructor = new AP4_SampleDescRtpConstructor(stream);
- break;
- default:
- return AP4_ERROR_INVALID_RTP_CONSTRUCTOR_TYPE;
+ switch(type) {
+ case AP4_RTP_CONSTRUCTOR_TYPE_NOOP:
+ constructor = new AP4_NoopRtpConstructor(stream);
+ break;
+ case AP4_RTP_CONSTRUCTOR_TYPE_IMMEDIATE:
+ constructor = new AP4_ImmediateRtpConstructor(stream);
+ break;
+ case AP4_RTP_CONSTRUCTOR_TYPE_SAMPLE:
+ constructor = new AP4_SampleRtpConstructor(stream);
+ break;
+ case AP4_RTP_CONSTRUCTOR_TYPE_SAMPLE_DESC:
+ constructor = new AP4_SampleDescRtpConstructor(stream);
+ break;
+ default:
+ return AP4_ERROR_INVALID_RTP_CONSTRUCTOR_TYPE;
}
return AP4_SUCCESS;
diff --git a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4RtpHint.h b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4RtpHint.h
index 7972c119f..f747c8212 100644
--- a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4RtpHint.h
+++ b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4RtpHint.h
@@ -59,14 +59,12 @@ public:
virtual AP4_Result AddPacket(AP4_RtpPacket* packet);
virtual AP4_Size GetSize();
virtual AP4_ByteStream* ToByteStream();
-
+
// accessors
- AP4_List<AP4_RtpPacket>& GetPackets()
- {
+ AP4_List<AP4_RtpPacket>& GetPackets() {
return m_Packets;
}
- const AP4_DataBuffer& GetExtraData() const
- {
+ const AP4_DataBuffer& GetExtraData() const {
return m_ExtraData;
}
@@ -104,52 +102,24 @@ public:
// Referenceable methods
void AddReference();
void Release();
-
+
// Accessors
- int GetRelativeTime() const
- {
- return m_RelativeTime;
- }
- bool GetPBit() const
- {
- return m_PBit;
- }
- bool GetXBit() const
- {
- return m_XBit;
- }
- bool GetMBit() const
- {
- return m_MBit;
- }
- AP4_UI08 GetPayloadType() const
- {
- return m_PayloadType;
- }
- AP4_UI16 GetSequenceSeed() const
- {
- return m_SequenceSeed;
- }
- int GetTimeStampOffset() const
- {
- return m_TimeStampOffset;
- }
- bool GetBFrameFlag() const
- {
- return m_BFrameFlag;
- }
- bool GetRepeatFlag() const
- {
- return m_RepeatFlag;
- }
- AP4_List<AP4_RtpConstructor>& GetConstructors()
- {
+ int GetRelativeTime() const { return m_RelativeTime; }
+ bool GetPBit() const { return m_PBit; }
+ bool GetXBit() const { return m_XBit; }
+ bool GetMBit() const { return m_MBit; }
+ AP4_UI08 GetPayloadType() const { return m_PayloadType; }
+ AP4_UI16 GetSequenceSeed() const { return m_SequenceSeed; }
+ int GetTimeStampOffset() const { return m_TimeStampOffset; }
+ bool GetBFrameFlag() const { return m_BFrameFlag; }
+ bool GetRepeatFlag() const { return m_RepeatFlag; }
+ AP4_List<AP4_RtpConstructor>& GetConstructors() {
return m_Constructors;
}
private:
// members
- AP4_Cardinal m_ReferenceCount;
+ AP4_Cardinal m_ReferenceCount;
int m_RelativeTime;
bool m_PBit;
bool m_XBit;
@@ -175,10 +145,7 @@ public:
AP4_RtpConstructor(Type type) : m_ReferenceCount(1), m_Type(type) {}
// methods
- Type GetType() const
- {
- return m_Type;
- }
+ Type GetType() const { return m_Type; }
AP4_Result Write(AP4_ByteStream& stream);
virtual AP4_Size GetConstructedDataSize() = 0;
@@ -220,10 +187,7 @@ public:
AP4_NoopRtpConstructor() : AP4_RtpConstructor(AP4_RTP_CONSTRUCTOR_TYPE_NOOP) {}
// methods
- virtual AP4_Size GetConstructedDataSize()
- {
- return 0;
- }
+ virtual AP4_Size GetConstructedDataSize() { return 0; }
protected:
// methods
@@ -239,18 +203,12 @@ public:
// constructor
AP4_ImmediateRtpConstructor(AP4_ByteStream& stream);
AP4_ImmediateRtpConstructor(const AP4_DataBuffer& data);
-
+
// accessors
- const AP4_DataBuffer& GetData() const
- {
- return m_Data;
- }
+ const AP4_DataBuffer& GetData() const { return m_Data; }
// methods
- virtual AP4_Size GetConstructedDataSize()
- {
- return m_Data.GetDataSize();
- }
+ virtual AP4_Size GetConstructedDataSize() { return m_Data.GetDataSize(); }
protected:
// methods
@@ -272,30 +230,15 @@ public:
AP4_UI16 length,
AP4_UI32 sample_num,
AP4_UI32 sample_offset);
-
+
// accessors
- AP4_UI08 GetTrackRefIndex() const
- {
- return m_TrackRefIndex;
- }
- AP4_UI16 GetLength() const
- {
- return m_Length;
- }
- AP4_UI32 GetSampleNum() const
- {
- return m_SampleNum;
- }
- AP4_UI32 GetSampleOffset() const
- {
- return m_SampleOffset;
- }
+ AP4_UI08 GetTrackRefIndex() const { return m_TrackRefIndex; }
+ AP4_UI16 GetLength() const { return m_Length; }
+ AP4_UI32 GetSampleNum() const { return m_SampleNum; }
+ AP4_UI32 GetSampleOffset() const { return m_SampleOffset; }
// methods
- virtual AP4_Size GetConstructedDataSize()
- {
- return m_Length;
- }
+ virtual AP4_Size GetConstructedDataSize() { return m_Length; }
protected:
// methods
@@ -322,29 +265,14 @@ public:
AP4_UI32 sample_desc_offset);
// accessors
- AP4_UI08 GetTrackRefIndex() const
- {
- return m_TrackRefIndex;
- }
- AP4_UI16 GetLength() const
- {
- return m_Length;
- }
- AP4_UI32 GetSampleDescIndex() const
- {
- return m_SampleDescIndex;
- }
- AP4_UI32 GetSampleDescOffset() const
- {
- return m_SampleDescOffset;
- }
+ AP4_UI08 GetTrackRefIndex() const { return m_TrackRefIndex; }
+ AP4_UI16 GetLength() const { return m_Length; }
+ AP4_UI32 GetSampleDescIndex() const { return m_SampleDescIndex; }
+ AP4_UI32 GetSampleDescOffset() const { return m_SampleDescOffset; }
// methods
- virtual AP4_Size GetConstructedDataSize()
- {
- return m_Length;
- }
-
+ virtual AP4_Size GetConstructedDataSize() { return m_Length; }
+
protected:
// methods
virtual AP4_Result DoWrite(AP4_ByteStream& stream);
@@ -359,11 +287,11 @@ protected:
/*----------------------------------------------------------------------
| AP4_RtpConstructorFactory
+---------------------------------------------------------------------*/
-class AP4_RtpConstructorFactory
+class AP4_RtpConstructorFactory
{
public:
static AP4_Result CreateConstructorFromStream(AP4_ByteStream& stream,
- AP4_RtpConstructor*& constructor);
+ AP4_RtpConstructor*& constructor);
};
#endif // _AP4_RTP_HINT_H_
diff --git a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4SLConfigDescriptor.cpp b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4SLConfigDescriptor.cpp
index 38a01ce36..7b791c3e4 100644
--- a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4SLConfigDescriptor.cpp
+++ b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4SLConfigDescriptor.cpp
@@ -1,6 +1,6 @@
/*****************************************************************
|
-| AP4 - SLConfig Descriptor
+| AP4 - SLConfig Descriptor
|
| Copyright 2002-2008 Axiomatic Systems, LLC
|
diff --git a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4SLConfigDescriptor.h b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4SLConfigDescriptor.h
index 66820e6a3..73a26ec9b 100644
--- a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4SLConfigDescriptor.h
+++ b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4SLConfigDescriptor.h
@@ -1,6 +1,6 @@
/*****************************************************************
|
-| AP4 - SLConfig Descriptor
+| AP4 - SLConfig Descriptor
|
| Copyright 2002-2008 Axiomatic Systems, LLC
|
@@ -43,7 +43,7 @@ const AP4_UI08 AP4_DESCRIPTOR_TAG_SL_CONFIG = 0x06;
/*----------------------------------------------------------------------
| AP4_SLConfigDescriptor
+---------------------------------------------------------------------*/
-class AP4_SLConfigDescriptor : public AP4_Descriptor
+class AP4_SLConfigDescriptor : public AP4_Descriptor
{
public:
// methods
diff --git a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4Sample.cpp b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4Sample.cpp
index d0a15aa55..060084044 100644
--- a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4Sample.cpp
+++ b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4Sample.cpp
@@ -135,21 +135,21 @@ AP4_Result
AP4_Sample::ReadData(AP4_DataBuffer& data, AP4_Size size, AP4_Size offset)
{
// check that we have a stream
- if(m_DataStream == NULL) return AP4_FAILURE;
+ if (m_DataStream == NULL) return AP4_FAILURE;
// shortcut
- if(size == 0) return AP4_SUCCESS;
+ if (size == 0) return AP4_SUCCESS;
// check the size
- if(m_Size < size + offset) return AP4_FAILURE;
+ if (m_Size < size+offset) return AP4_FAILURE;
// set the buffer size
AP4_Result result = data.SetDataSize(size);
- if(AP4_FAILED(result)) return result;
+ if (AP4_FAILED(result)) return result;
// get the data from the stream
- result = m_DataStream->Seek(m_Offset + offset);
- if(AP4_FAILED(result)) return result;
+ result = m_DataStream->Seek(m_Offset+offset);
+ if (AP4_FAILED(result)) return result;
return m_DataStream->Read(data.UseData(), size);
}
diff --git a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4Sample.h b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4Sample.h
index 0af63fbac..ba5a0235f 100644
--- a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4Sample.h
+++ b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4Sample.h
@@ -43,7 +43,7 @@ class AP4_DataBuffer;
/*----------------------------------------------------------------------
| AP4_Sample DO NOT DERIVE FROM THIS CLASS
+---------------------------------------------------------------------*/
-class AP4_Sample
+class AP4_Sample
{
public:
/**
@@ -55,19 +55,19 @@ public:
* Copy constructor
*/
AP4_Sample(const AP4_Sample& other);
-
+
/**
* Construct an AP4_Sample referencing a data stream
*
- * @param data_stream The byte stream that contains the sample data.
- * The sample object added to the track will keep a reference to that byte
+ * @param data_stream The byte stream that contains the sample data.
+ * The sample object added to the track will keep a reference to that byte
* stream
* @param offset Position of the first byte of sample data within the stream
* @param size Size in bytes of the sample data
- * @param description_index Index of the sample description that applies to
+ * @param description_index Index of the sample description that applies to
* this sample
* @param dts Decoding timestamp of the sample
- * @param cts_delta Difference between the CTS (composition/display timestamp) and the
+ * @param cts_delta Difference between the CTS (composition/display timestamp) and the
* DTS (decoding timestamp), in the timescale of the media.
* @param sync_flag Boolean flag indicating whether this is a sync sample
* or not
@@ -80,7 +80,7 @@ public:
AP4_UI64 dts,
AP4_UI32 cts_delta,
bool sync_flag);
-
+
~AP4_Sample(); // not virtual on purpose: do not derive from it
// operators
@@ -88,119 +88,71 @@ public:
// methods
AP4_Result ReadData(AP4_DataBuffer& data);
- AP4_Result ReadData(AP4_DataBuffer& data,
- AP4_Size size,
+ AP4_Result ReadData(AP4_DataBuffer& data,
+ AP4_Size size,
AP4_Size offset = 0);
// sample properties accessors
AP4_ByteStream* GetDataStream();
void SetDataStream(AP4_ByteStream& stream);
- AP4_Position GetOffset() const
- {
- return m_Offset;
- }
- void SetOffset(AP4_Position offset)
- {
- m_Offset = offset;
- }
- AP4_Size GetSize()
- {
- return m_Size;
- }
- void SetSize(AP4_Size size)
- {
- m_Size = size;
- }
- AP4_Ordinal GetDescriptionIndex() const
- {
- return m_DescriptionIndex;
- }
- void SetDescriptionIndex(AP4_Ordinal index)
- {
- m_DescriptionIndex = index;
- }
-
+ AP4_Position GetOffset() const { return m_Offset; }
+ void SetOffset(AP4_Position offset) { m_Offset = offset; }
+ AP4_Size GetSize() { return m_Size; }
+ void SetSize(AP4_Size size) { m_Size = size; }
+ AP4_Ordinal GetDescriptionIndex() const { return m_DescriptionIndex; }
+ void SetDescriptionIndex(AP4_Ordinal index) { m_DescriptionIndex = index; }
+
/**
* Get the DTS (Decoding Time Stamp) of the sample in the timescale of the media
*/
- AP4_UI64 GetDts() const
- {
- return m_Dts;
- }
+ AP4_UI64 GetDts() const { return m_Dts; }
/**
* Set the DTS (Decoding Time Stamp) of the sample in the timescale of the media
*/
- void SetDts(AP4_UI64 dts)
- {
- m_Dts = dts;
- }
+ void SetDts(AP4_UI64 dts) { m_Dts = dts; }
/**
* Get the CTS (Composition Time Stamp) of the sample in the timescale of the media
*/
- AP4_UI64 GetCts() const
- {
- return m_Dts + m_CtsDelta;
- }
+ AP4_UI64 GetCts() const { return m_Dts+m_CtsDelta; }
/**
* Set the CTS (Composition Time Stamp) of the sample in the timescale of the media
*/
- void SetCts(AP4_UI64 cts)
- {
- m_CtsDelta = (cts > m_Dts) ? (AP4_UI32)(cts - m_Dts) : 0;
- }
+ void SetCts(AP4_UI64 cts) { m_CtsDelta = (cts > m_Dts) ? (AP4_UI32)(cts-m_Dts) : 0; }
/**
* Get the CTS Delta (difference between the CTS (Composition Time Stamp) and DTS (Decoding Time Stamp)
* of the sample in the timescale of the media.
*/
- AP4_UI32 GetCtsDelta() const
- {
- return m_CtsDelta;
- }
+ AP4_UI32 GetCtsDelta() const { return m_CtsDelta; }
/**
* Set the CTS Delta (difference between the CTS (Composition Time Stamp) and DTS (Decoding Time Stamp)
* of the sample in the timescale of the media.
*/
- void SetCtsDelta(AP4_UI32 delta)
- {
- m_CtsDelta = (AP4_SI32)delta;
- }
+ void SetCtsDelta(AP4_UI32 delta) { m_CtsDelta = (AP4_SI32)delta; }
/**
* Get the duration of the sample in the timescale of the media
*/
- AP4_UI32 GetDuration() const
- {
- return m_Duration;
- }
+ AP4_UI32 GetDuration() const { return m_Duration; }
/**
* Set the duration of the sample in the timescale of the media
*/
- void SetDuration(AP4_UI32 duration)
- {
- m_Duration = duration;
- }
+ void SetDuration(AP4_UI32 duration) { m_Duration = duration; }
/**
* Return whether the sample is a sync (random-access point) sample or not.
*/
- bool IsSync() const
- {
- return m_IsSync;
- }
+ bool IsSync() const { return m_IsSync; }
/**
* Set whether the sample is a sync (random-access point) sample or not.
*/
- void SetSync(bool is_sync)
- {
- m_IsSync = is_sync;
- }
+ void SetSync(bool is_sync) { m_IsSync = is_sync; }
protected:
AP4_ByteStream* m_DataStream;
diff --git a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4SampleDescription.cpp b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4SampleDescription.cpp
index f7a0b1698..e301d0cf4 100644
--- a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4SampleDescription.cpp
+++ b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4SampleDescription.cpp
@@ -56,70 +56,38 @@ AP4_DEFINE_DYNAMIC_CAST_ANCHOR(AP4_AvcSampleDescription)
const char*
AP4_GetFormatName(AP4_UI32 format)
{
- switch(format)
- {
- case AP4_SAMPLE_FORMAT_MP4A:
- return "MPEG-4 Audio";
- case AP4_SAMPLE_FORMAT_MP4V:
- return "MPEG-4 Video";
- case AP4_SAMPLE_FORMAT_MP4S:
- return "MPEG-4 Systems";
- case AP4_SAMPLE_FORMAT_ALAC:
- return "Apple Lossless Audio";
- case AP4_SAMPLE_FORMAT_AVC1:
- return "H.264";
- case AP4_SAMPLE_FORMAT_OVC1:
- return "VC-1";
- case AP4_SAMPLE_FORMAT_OWMA:
- return "WMA";
- case AP4_SAMPLE_FORMAT_AC_3:
- return "Dolby Digital (AC-3)";
- case AP4_SAMPLE_FORMAT_EC_3:
- return "Dolby Digital Plus (Enhanced AC-3)";
- case AP4_SAMPLE_FORMAT_AVCP:
- return "Advanced Video Coding Parameters";
- case AP4_SAMPLE_FORMAT_DRAC:
- return "Dirac";
- case AP4_SAMPLE_FORMAT_DRA1:
- return "DRA Audio";
- case AP4_SAMPLE_FORMAT_G726:
- return "G726";
- case AP4_SAMPLE_FORMAT_MJP2:
- return "Motion JPEG 2000";
- case AP4_SAMPLE_FORMAT_OKSD:
- return "OMA Keys";
- case AP4_SAMPLE_FORMAT_RAW_:
- return "Uncompressed Audio";
- case AP4_SAMPLE_FORMAT_RTP_:
- return "RTP Hints";
- case AP4_SAMPLE_FORMAT_S263:
- return "H.263";
- case AP4_SAMPLE_FORMAT_SAMR:
- return "Narrowband AMR";
- case AP4_SAMPLE_FORMAT_SAWB:
- return "Wideband AMR";
- case AP4_SAMPLE_FORMAT_SAWP:
- return "Extended AMR";
- case AP4_SAMPLE_FORMAT_SEVC:
- return "EVRC Voice";
- case AP4_SAMPLE_FORMAT_SQCP:
- return "13K Voice";
- case AP4_SAMPLE_FORMAT_SRTP:
- return "SRTP Hints";
- case AP4_SAMPLE_FORMAT_SSMV:
- return "SMV Voice";
- case AP4_SAMPLE_FORMAT_TEXT:
- return "Textual Metadata";
- case AP4_SAMPLE_FORMAT_TWOS:
- return "Uncompressed 16-bit Audio";
- case AP4_SAMPLE_FORMAT_TX3G:
- return "Timed Text";
- case AP4_SAMPLE_FORMAT_VC_1:
- return "SMPTE VC-1";
- case AP4_SAMPLE_FORMAT_XML_:
- return "XML Metadata";
- default:
- return NULL;
+ switch (format) {
+ case AP4_SAMPLE_FORMAT_MP4A: return "MPEG-4 Audio";
+ case AP4_SAMPLE_FORMAT_MP4V: return "MPEG-4 Video";
+ case AP4_SAMPLE_FORMAT_MP4S: return "MPEG-4 Systems";
+ case AP4_SAMPLE_FORMAT_ALAC: return "Apple Lossless Audio";
+ case AP4_SAMPLE_FORMAT_AVC1: return "H.264";
+ case AP4_SAMPLE_FORMAT_OVC1: return "VC-1";
+ case AP4_SAMPLE_FORMAT_OWMA: return "WMA";
+ case AP4_SAMPLE_FORMAT_AC_3: return "Dolby Digital (AC-3)";
+ case AP4_SAMPLE_FORMAT_EC_3: return "Dolby Digital Plus (Enhanced AC-3)";
+ case AP4_SAMPLE_FORMAT_AVCP: return "Advanced Video Coding Parameters";
+ case AP4_SAMPLE_FORMAT_DRAC: return "Dirac";
+ case AP4_SAMPLE_FORMAT_DRA1: return "DRA Audio";
+ case AP4_SAMPLE_FORMAT_G726: return "G726";
+ case AP4_SAMPLE_FORMAT_MJP2: return "Motion JPEG 2000";
+ case AP4_SAMPLE_FORMAT_OKSD: return "OMA Keys";
+ case AP4_SAMPLE_FORMAT_RAW_: return "Uncompressed Audio";
+ case AP4_SAMPLE_FORMAT_RTP_: return "RTP Hints";
+ case AP4_SAMPLE_FORMAT_S263: return "H.263";
+ case AP4_SAMPLE_FORMAT_SAMR: return "Narrowband AMR";
+ case AP4_SAMPLE_FORMAT_SAWB: return "Wideband AMR";
+ case AP4_SAMPLE_FORMAT_SAWP: return "Extended AMR";
+ case AP4_SAMPLE_FORMAT_SEVC: return "EVRC Voice";
+ case AP4_SAMPLE_FORMAT_SQCP: return "13K Voice";
+ case AP4_SAMPLE_FORMAT_SRTP: return "SRTP Hints";
+ case AP4_SAMPLE_FORMAT_SSMV: return "SMV Voice";
+ case AP4_SAMPLE_FORMAT_TEXT: return "Textual Metadata";
+ case AP4_SAMPLE_FORMAT_TWOS: return "Uncompressed 16-bit Audio";
+ case AP4_SAMPLE_FORMAT_TX3G: return "Timed Text";
+ case AP4_SAMPLE_FORMAT_VC_1: return "SMPTE VC-1";
+ case AP4_SAMPLE_FORMAT_XML_: return "XML Metadata";
+ default: return NULL;
}
}
@@ -127,21 +95,18 @@ AP4_GetFormatName(AP4_UI32 format)
| AP4_SampleDescription::AP4_SampleDescription
+---------------------------------------------------------------------*/
AP4_SampleDescription::AP4_SampleDescription(Type type,
- AP4_UI32 format,
- AP4_AtomParent* details) :
+ AP4_UI32 format,
+ AP4_AtomParent* details) :
m_Type(type), m_Format(format)
{
- if(details)
- {
- for(AP4_List<AP4_Atom>::Item* item = details->GetChildren().FirstItem();
- item;
- item = item->GetNext())
- {
+ if (details) {
+ for (AP4_List<AP4_Atom>::Item* item = details->GetChildren().FirstItem();
+ item;
+ item = item->GetNext()) {
AP4_Atom* atom = item->GetData();
- if(atom)
- {
+ if (atom) {
AP4_Atom* clone = atom->Clone();
- if(clone) m_Details.AddChild(clone);
+ if (clone) m_Details.AddChild(clone);
}
}
}
@@ -153,27 +118,24 @@ AP4_SampleDescription::AP4_SampleDescription(Type type,
AP4_SampleDescription*
AP4_SampleDescription::Clone(AP4_Result* result)
{
- if(result) *result = AP4_SUCCESS;
+ if (result) *result = AP4_SUCCESS;
AP4_Atom* atom = ToAtom();
- if(atom == NULL)
- {
- if(result) *result = AP4_FAILURE;
+ if (atom == NULL) {
+ if (result) *result = AP4_FAILURE;
return NULL;
}
AP4_SampleEntry* sample_entry = AP4_DYNAMIC_CAST(AP4_SampleEntry, atom);
- if(sample_entry == NULL)
- {
- if(result) *result = AP4_ERROR_INTERNAL;
+ if (sample_entry == NULL) {
+ if (result) *result = AP4_ERROR_INTERNAL;
delete atom;
return NULL;
}
-
+
AP4_SampleDescription* clone = sample_entry->ToSampleDescription();
- if(clone == NULL)
- {
- if(result) *result = AP4_ERROR_INTERNAL;
+ if (clone == NULL) {
+ if (result) *result = AP4_ERROR_INTERNAL;
}
-
+
delete atom;
return clone;
}
@@ -191,8 +153,8 @@ AP4_SampleDescription::ToAtom() const
| AP4_UnknownSampleDescription::AP4_UnknownSampleDescription
+---------------------------------------------------------------------*/
AP4_UnknownSampleDescription::AP4_UnknownSampleDescription(AP4_Atom* atom) :
- AP4_SampleDescription(AP4_SampleDescription::TYPE_UNKNOWN,
- atom->GetType(),
+ AP4_SampleDescription(AP4_SampleDescription::TYPE_UNKNOWN,
+ atom->GetType(),
NULL),
m_Atom(atom->Clone())
{
@@ -213,53 +175,48 @@ AP4_SampleDescription*
AP4_UnknownSampleDescription::Clone(AP4_Result* result)
{
AP4_Atom* atom_clone = NULL;
- if(m_Atom)
- {
+ if (m_Atom) {
atom_clone = m_Atom->Clone();
- if(atom_clone == NULL)
- {
- if(result) *result = AP4_FAILURE;
+ if (atom_clone == NULL) {
+ if (result) *result = AP4_FAILURE;
return NULL;
}
}
- if(result) *result = AP4_SUCCESS;
+ if (result) *result = AP4_SUCCESS;
return new AP4_UnknownSampleDescription(atom_clone);
}
/*----------------------------------------------------------------------
| AP4_UnknownSampleDescription::ToAtom
+---------------------------------------------------------------------*/
-AP4_Atom*
+AP4_Atom*
AP4_UnknownSampleDescription::ToAtom() const
{
- if(m_Atom)
- {
+ if (m_Atom) {
return m_Atom->Clone();
- }
- else
- {
+ } else {
return NULL;
}
}
-
+
/*----------------------------------------------------------------------
| AP4_AvcSampleDescription::AP4_AvcSampleDescription
+---------------------------------------------------------------------*/
AP4_AvcSampleDescription::AP4_AvcSampleDescription(AP4_UI16 width,
- AP4_UI16 height,
- AP4_UI16 depth,
- const char* compressor_name,
- AP4_UI08 profile,
- AP4_UI08 level,
- AP4_UI08 profile_compatibility,
- AP4_UI08 length_size,
- const AP4_Array<AP4_DataBuffer>& sequence_parameters,
- const AP4_Array<AP4_DataBuffer>& picture_parameters) :
+ AP4_UI16 height,
+ AP4_UI16 depth,
+ const char* compressor_name,
+ AP4_UI08 profile,
+ AP4_UI08 level,
+ AP4_UI08 profile_compatibility,
+ AP4_UI08 length_size,
+ const AP4_Array<AP4_DataBuffer>& sequence_parameters,
+ const AP4_Array<AP4_DataBuffer>& picture_parameters) :
AP4_SampleDescription(TYPE_AVC, AP4_SAMPLE_FORMAT_AVC1, NULL),
AP4_VideoSampleDescription(width, height, depth, compressor_name)
{
- m_AvccAtom = new AP4_AvccAtom(profile,
- level,
+ m_AvccAtom = new AP4_AvccAtom(profile,
+ level,
profile_compatibility,
length_size,
sequence_parameters,
@@ -271,19 +228,16 @@ AP4_AvcSampleDescription::AP4_AvcSampleDescription(AP4_UI16 width,
| AP4_AvcSampleDescription::AP4_AvcSampleDescription
+---------------------------------------------------------------------*/
AP4_AvcSampleDescription::AP4_AvcSampleDescription(AP4_UI16 width,
- AP4_UI16 height,
- AP4_UI16 depth,
- const char* compressor_name,
- const AP4_AvccAtom* avcc) :
+ AP4_UI16 height,
+ AP4_UI16 depth,
+ const char* compressor_name,
+ const AP4_AvccAtom* avcc) :
AP4_SampleDescription(TYPE_AVC, AP4_SAMPLE_FORMAT_AVC1, NULL),
AP4_VideoSampleDescription(width, height, depth, compressor_name)
{
- if(avcc)
- {
+ if (avcc) {
m_AvccAtom = new AP4_AvccAtom(*avcc);
- }
- else
- {
+ } else {
// should never happen
m_AvccAtom = new AP4_AvccAtom();
}
@@ -294,21 +248,18 @@ AP4_AvcSampleDescription::AP4_AvcSampleDescription(AP4_UI16 width,
| AP4_AvcSampleDescription::AP4_AvcSampleDescription
+---------------------------------------------------------------------*/
AP4_AvcSampleDescription::AP4_AvcSampleDescription(AP4_UI16 width,
- AP4_UI16 height,
- AP4_UI16 depth,
- const char* compressor_name,
- AP4_AtomParent* details) :
+ AP4_UI16 height,
+ AP4_UI16 depth,
+ const char* compressor_name,
+ AP4_AtomParent* details) :
AP4_SampleDescription(TYPE_AVC, AP4_SAMPLE_FORMAT_AVC1, details),
AP4_VideoSampleDescription(width, height, depth, compressor_name),
m_AvccAtom(NULL)
{
AP4_AvccAtom* avcc = AP4_DYNAMIC_CAST(AP4_AvccAtom, details->GetChild(AP4_ATOM_TYPE_AVCC));
- if(avcc)
- {
+ if (avcc) {
m_AvccAtom = new AP4_AvccAtom(*avcc);
- }
- else
- {
+ } else {
// shoud never happen
m_AvccAtom = new AP4_AvccAtom();
}
@@ -321,10 +272,10 @@ AP4_AvcSampleDescription::AP4_AvcSampleDescription(AP4_UI16 width,
AP4_Atom*
AP4_AvcSampleDescription::ToAtom() const
{
- return new AP4_Avc1SampleEntry(m_Width,
- m_Height,
- m_Depth,
- m_CompressorName.GetChars(),
+ return new AP4_Avc1SampleEntry(m_Width,
+ m_Height,
+ m_Depth,
+ m_CompressorName.GetChars(),
*m_AvccAtom);
}
@@ -332,7 +283,7 @@ AP4_AvcSampleDescription::ToAtom() const
| AP4_MpegSampleDescription::AP4_MpegSampleDescription
+---------------------------------------------------------------------*/
AP4_MpegSampleDescription::AP4_MpegSampleDescription(AP4_UI32 format,
- AP4_EsdsAtom* esds) :
+ AP4_EsdsAtom* esds) :
AP4_SampleDescription(TYPE_MPEG, format, NULL),
m_StreamType(0),
m_ObjectTypeId(0),
@@ -340,17 +291,15 @@ AP4_MpegSampleDescription::AP4_MpegSampleDescription(AP4_UI32 format,
m_MaxBitrate(0),
m_AvgBitrate(0)
{
- if(esds)
- {
+ if (esds) {
// get the es descriptor
const AP4_EsDescriptor* es_desc = esds->GetEsDescriptor();
- if(es_desc == NULL) return;
+ if (es_desc == NULL) return;
// get the decoder config descriptor
const AP4_DecoderConfigDescriptor* dc_desc =
es_desc->GetDecoderConfigDescriptor();
- if(dc_desc)
- {
+ if (dc_desc) {
m_StreamType = dc_desc->GetStreamType();
m_ObjectTypeId = dc_desc->GetObjectTypeIndication();
m_BufferSize = dc_desc->GetBufferSize();
@@ -358,8 +307,7 @@ AP4_MpegSampleDescription::AP4_MpegSampleDescription(AP4_UI32 format,
m_AvgBitrate = dc_desc->GetAvgBitrate();
const AP4_DecoderSpecificInfoDescriptor* dsi_desc =
dc_desc->GetDecoderSpecificInfoDescriptor();
- if(dsi_desc != NULL)
- {
+ if (dsi_desc != NULL) {
m_DecoderInfo.SetData(dsi_desc->GetDecoderSpecificInfo().GetData(),
dsi_desc->GetDecoderSpecificInfo().GetDataSize());
}
@@ -385,8 +333,7 @@ AP4_MpegSampleDescription::AP4_MpegSampleDescription(
m_MaxBitrate(max_bitrate),
m_AvgBitrate(avg_bitrate)
{
- if(decoder_info != NULL)
- {
+ if (decoder_info != NULL) {
m_DecoderInfo.SetData(decoder_info->GetData(), decoder_info->GetDataSize());
}
}
@@ -394,31 +341,28 @@ AP4_MpegSampleDescription::AP4_MpegSampleDescription(
/*----------------------------------------------------------------------
| AP4_MpegSampleDescription::CreateEsDescriptor
+---------------------------------------------------------------------*/
-AP4_EsDescriptor*
+AP4_EsDescriptor*
AP4_MpegSampleDescription::CreateEsDescriptor() const
{
AP4_EsDescriptor* desc = new AP4_EsDescriptor(0);
AP4_DecoderSpecificInfoDescriptor* dsi_desc;
- if(m_DecoderInfo.GetDataSize() != 0)
- {
+ if (m_DecoderInfo.GetDataSize() != 0) {
dsi_desc = new AP4_DecoderSpecificInfoDescriptor(m_DecoderInfo);
- }
- else
- {
+ } else {
dsi_desc = NULL;
}
- AP4_DecoderConfigDescriptor* decoder_config =
+ AP4_DecoderConfigDescriptor* decoder_config =
new AP4_DecoderConfigDescriptor(m_StreamType,
- m_ObjectTypeId,
- m_BufferSize,
- m_MaxBitrate,
- m_AvgBitrate,
- dsi_desc);
+ m_ObjectTypeId,
+ m_BufferSize,
+ m_MaxBitrate,
+ m_AvgBitrate,
+ dsi_desc);
desc->AddSubDescriptor(decoder_config);
-
+
// add a fixed SL Config
desc->AddSubDescriptor(new AP4_SLConfigDescriptor());
-
+
return desc;
}
@@ -486,8 +430,8 @@ AP4_MpegAudioSampleDescription::AP4_MpegAudioSampleDescription(
AP4_UI32 avg_bitrate) :
AP4_MpegSampleDescription(AP4_ATOM_TYPE_MP4A,
AP4_STREAM_TYPE_AUDIO,
- oti,
- decoder_info, buffer_size,
+ oti,
+ decoder_info, buffer_size,
max_bitrate, avg_bitrate),
AP4_AudioSampleDescription(sample_rate, sample_size, channel_count)
{
@@ -499,7 +443,7 @@ AP4_MpegAudioSampleDescription::AP4_MpegAudioSampleDescription(
AP4_Atom*
AP4_MpegAudioSampleDescription::ToAtom() const
{
- return new AP4_Mp4aSampleEntry(m_SampleRate << 16,
+ return new AP4_Mp4aSampleEntry(m_SampleRate<<16,
m_SampleSize,
m_ChannelCount,
CreateEsDescriptor());
@@ -511,20 +455,16 @@ AP4_MpegAudioSampleDescription::ToAtom() const
AP4_MpegAudioSampleDescription::Mpeg4AudioObjectType
AP4_MpegAudioSampleDescription::GetMpeg4AudioObjectType() const
{
- if(m_ObjectTypeId == AP4_OTI_MPEG4_AUDIO &&
- m_DecoderInfo.GetDataSize() >= 1)
- {
- AP4_UI08 type = m_DecoderInfo.GetData()[0] >> 3;
- if(type == 31)
- {
- if(m_DecoderInfo.GetDataSize() < 2) return 0;
- type = 32 + (((m_DecoderInfo.GetData()[0] & 0x07) << 3) |
- ((m_DecoderInfo.GetData()[1] & 0xE0) >> 5));
+ if (m_ObjectTypeId == AP4_OTI_MPEG4_AUDIO &&
+ m_DecoderInfo.GetDataSize() >= 1) {
+ AP4_UI08 type = m_DecoderInfo.GetData()[0]>>3;
+ if (type == 31) {
+ if (m_DecoderInfo.GetDataSize() < 2) return 0;
+ type = 32+(((m_DecoderInfo.GetData()[0]&0x07)<<3) |
+ ((m_DecoderInfo.GetData()[1]&0xE0)>>5));
}
return type;
- }
- else
- {
+ } else {
return 0;
}
}
@@ -538,7 +478,7 @@ AP4_MpegVideoSampleDescription::AP4_MpegVideoSampleDescription(
AP4_UI16 depth,
const char* compressor_name,
AP4_EsdsAtom* esds) :
-
+
AP4_MpegSampleDescription(AP4_ATOM_TYPE_MP4V, esds),
AP4_VideoSampleDescription(width, height, depth, compressor_name)
{
@@ -557,7 +497,7 @@ AP4_MpegVideoSampleDescription::AP4_MpegVideoSampleDescription(
AP4_UI32 buffer_size,
AP4_UI32 max_bitrate,
AP4_UI32 avg_bitrate) :
- AP4_MpegSampleDescription(AP4_ATOM_TYPE_MP4V,
+ AP4_MpegSampleDescription(AP4_ATOM_TYPE_MP4V,
AP4_STREAM_TYPE_VISUAL,
oti,
decoder_info,
@@ -584,164 +524,95 @@ AP4_MpegVideoSampleDescription::ToAtom() const
/*----------------------------------------------------------------------
| AP4_MpegSampleDescription::GetStreamTypeString
+---------------------------------------------------------------------*/
-const char*
+const char*
AP4_MpegSampleDescription::GetStreamTypeString(StreamType type)
{
- switch(type)
- {
- case AP4_STREAM_TYPE_FORBIDDEN:
- return "INVALID";
- case AP4_STREAM_TYPE_OD:
- return "Object Descriptor";
- case AP4_STREAM_TYPE_CR:
- return "CR";
- case AP4_STREAM_TYPE_BIFS:
- return "BIFS";
- case AP4_STREAM_TYPE_VISUAL:
- return "Visual";
- case AP4_STREAM_TYPE_AUDIO:
- return "Audio";
- case AP4_STREAM_TYPE_MPEG7:
- return "MPEG-7";
- case AP4_STREAM_TYPE_IPMP:
- return "IPMP";
- case AP4_STREAM_TYPE_OCI:
- return "OCI";
- case AP4_STREAM_TYPE_MPEGJ:
- return "MPEG-J";
- default:
- return "UNKNOWN";
+ switch (type) {
+ case AP4_STREAM_TYPE_FORBIDDEN: return "INVALID";
+ case AP4_STREAM_TYPE_OD: return "Object Descriptor";
+ case AP4_STREAM_TYPE_CR: return "CR";
+ case AP4_STREAM_TYPE_BIFS: return "BIFS";
+ case AP4_STREAM_TYPE_VISUAL: return "Visual";
+ case AP4_STREAM_TYPE_AUDIO: return "Audio";
+ case AP4_STREAM_TYPE_MPEG7: return "MPEG-7";
+ case AP4_STREAM_TYPE_IPMP: return "IPMP";
+ case AP4_STREAM_TYPE_OCI: return "OCI";
+ case AP4_STREAM_TYPE_MPEGJ: return "MPEG-J";
+ default: return "UNKNOWN";
}
}
/*----------------------------------------------------------------------
| AP4_MpegSampleDescription::GetObjectTypeString
+---------------------------------------------------------------------*/
-const char*
+const char*
AP4_MpegSampleDescription::GetObjectTypeString(OTI oti)
{
- switch(oti)
- {
- case AP4_OTI_MPEG4_SYSTEM:
- return "MPEG-4 System";
- case AP4_OTI_MPEG4_SYSTEM_COR:
- return "MPEG-4 System COR";
- case AP4_OTI_MPEG4_VISUAL:
- return "MPEG-4 Video";
- case AP4_OTI_MPEG4_AUDIO:
- return "MPEG-4 Audio";
- case AP4_OTI_MPEG2_VISUAL_SIMPLE:
- return "MPEG-2 Video Simple Profile";
- case AP4_OTI_MPEG2_VISUAL_MAIN:
- return "MPEG-2 Video Main Profile";
- case AP4_OTI_MPEG2_VISUAL_SNR:
- return "MPEG-2 Video SNR";
- case AP4_OTI_MPEG2_VISUAL_SPATIAL:
- return "MPEG-2 Video Spatial";
- case AP4_OTI_MPEG2_VISUAL_HIGH:
- return "MPEG-2 Video High";
- case AP4_OTI_MPEG2_VISUAL_422:
- return "MPEG-2 Video 4:2:2";
- case AP4_OTI_MPEG2_AAC_AUDIO_MAIN:
- return "MPEG-2 Audio AAC Main Profile";
- case AP4_OTI_MPEG2_AAC_AUDIO_LC:
- return "MPEG-2 Audio AAC Low Complexity";
- case AP4_OTI_MPEG2_AAC_AUDIO_SSRP:
- return "MPEG-2 Audio AAC SSRP";
- case AP4_OTI_MPEG2_PART3_AUDIO:
- return "MPEG-2 Audio Part-3";
- case AP4_OTI_MPEG1_VISUAL:
- return "MPEG-1 Video";
- case AP4_OTI_MPEG1_AUDIO:
- return "MPEG-1 Audio";
- case AP4_OTI_JPEG:
- return "JPEG";
- default:
- return "UNKNOWN";
+ switch (oti) {
+ case AP4_OTI_MPEG4_SYSTEM: return "MPEG-4 System";
+ case AP4_OTI_MPEG4_SYSTEM_COR: return "MPEG-4 System COR";
+ case AP4_OTI_MPEG4_VISUAL: return "MPEG-4 Video";
+ case AP4_OTI_MPEG4_AUDIO: return "MPEG-4 Audio";
+ case AP4_OTI_MPEG2_VISUAL_SIMPLE: return "MPEG-2 Video Simple Profile";
+ case AP4_OTI_MPEG2_VISUAL_MAIN: return "MPEG-2 Video Main Profile";
+ case AP4_OTI_MPEG2_VISUAL_SNR: return "MPEG-2 Video SNR";
+ case AP4_OTI_MPEG2_VISUAL_SPATIAL: return "MPEG-2 Video Spatial";
+ case AP4_OTI_MPEG2_VISUAL_HIGH: return "MPEG-2 Video High";
+ case AP4_OTI_MPEG2_VISUAL_422: return "MPEG-2 Video 4:2:2";
+ case AP4_OTI_MPEG2_AAC_AUDIO_MAIN: return "MPEG-2 Audio AAC Main Profile";
+ case AP4_OTI_MPEG2_AAC_AUDIO_LC: return "MPEG-2 Audio AAC Low Complexity";
+ case AP4_OTI_MPEG2_AAC_AUDIO_SSRP: return "MPEG-2 Audio AAC SSRP";
+ case AP4_OTI_MPEG2_PART3_AUDIO: return "MPEG-2 Audio Part-3";
+ case AP4_OTI_MPEG1_VISUAL: return "MPEG-1 Video";
+ case AP4_OTI_MPEG1_AUDIO: return "MPEG-1 Audio";
+ case AP4_OTI_JPEG: return "JPEG";
+ default: return "UNKNOWN";
}
}
/*----------------------------------------------------------------------
| AP4_MpegAudioSampleDescription::GetMpeg4AudioObjectTypeString
+---------------------------------------------------------------------*/
-const char*
+const char*
AP4_MpegAudioSampleDescription::GetMpeg4AudioObjectTypeString(Mpeg4AudioObjectType type)
{
- switch(type)
- {
- case AP4_MPEG4_AUDIO_OBJECT_TYPE_AAC_MAIN:
- return "AAC Main Profile";
- case AP4_MPEG4_AUDIO_OBJECT_TYPE_AAC_LC:
- return "AAC Low Complexity";
- case AP4_MPEG4_AUDIO_OBJECT_TYPE_AAC_SSR:
- return "AAC Scalable Sample Rate";
- case AP4_MPEG4_AUDIO_OBJECT_TYPE_AAC_LTP:
- return "AAC Long Term Predictor";
- case AP4_MPEG4_AUDIO_OBJECT_TYPE_SBR:
- return "Spectral Band Replication";
- case AP4_MPEG4_AUDIO_OBJECT_TYPE_AAC_SCALABLE:
- return "AAC Scalable";
- case AP4_MPEG4_AUDIO_OBJECT_TYPE_TWINVQ:
- return "Twin VQ";
- case AP4_MPEG4_AUDIO_OBJECT_TYPE_CELP:
- return "CELP";
- case AP4_MPEG4_AUDIO_OBJECT_TYPE_HVXC:
- return "HVXC";
- case AP4_MPEG4_AUDIO_OBJECT_TYPE_TTSI:
- return "TTSI";
- case AP4_MPEG4_AUDIO_OBJECT_TYPE_MAIN_SYNTHETIC:
- return "Main Synthetic";
- case AP4_MPEG4_AUDIO_OBJECT_TYPE_WAVETABLE_SYNTHESIS:
- return "Wavetable Synthesis";
- case AP4_MPEG4_AUDIO_OBJECT_TYPE_GENERAL_MIDI:
- return "General MIDI";
- case AP4_MPEG4_AUDIO_OBJECT_TYPE_ALGORITHMIC_SYNTHESIS:
- return "Algorithmic Synthesis";
- case AP4_MPEG4_AUDIO_OBJECT_TYPE_ER_AAC_LC:
- return "Error Resilient AAC Low Complexity";
- case AP4_MPEG4_AUDIO_OBJECT_TYPE_ER_AAC_LTP:
- return "Error Resilient AAC Long Term Prediction";
- case AP4_MPEG4_AUDIO_OBJECT_TYPE_ER_AAC_SCALABLE:
- return "Error Resilient AAC Scalable";
- case AP4_MPEG4_AUDIO_OBJECT_TYPE_ER_TWINVQ:
- return "Error Resilient Twin VQ";
- case AP4_MPEG4_AUDIO_OBJECT_TYPE_ER_BSAC:
- return "Error Resilient Bit Sliced Arithmetic Coding";
- case AP4_MPEG4_AUDIO_OBJECT_TYPE_ER_AAC_LD:
- return "Error Resilient AAC Low Delay";
- case AP4_MPEG4_AUDIO_OBJECT_TYPE_ER_CELP:
- return "Error Resilient CELP";
- case AP4_MPEG4_AUDIO_OBJECT_TYPE_ER_HVXC:
- return "Error Resilient HVXC";
- case AP4_MPEG4_AUDIO_OBJECT_TYPE_ER_HILN:
- return "Error Resilient HILN";
- case AP4_MPEG4_AUDIO_OBJECT_TYPE_ER_PARAMETRIC:
- return "Error Resilient Parametric";
- case AP4_MPEG4_AUDIO_OBJECT_TYPE_SSC:
- return "SSC";
- case AP4_MPEG4_AUDIO_OBJECT_TYPE_MPEG_SURROUND:
- return "MPEG Surround";
- case AP4_MPEG4_AUDIO_OBJECT_TYPE_LAYER_1:
- return "MPEG Layer 1";
- case AP4_MPEG4_AUDIO_OBJECT_TYPE_LAYER_2:
- return "MPEG Layer 2";
- case AP4_MPEG4_AUDIO_OBJECT_TYPE_LAYER_3:
- return "MPEG Layer 3";
- case AP4_MPEG4_AUDIO_OBJECT_TYPE_DST:
- return "Direct Stream Transfer";
- case AP4_MPEG4_AUDIO_OBJECT_TYPE_ALS:
- return "ALS Lossless Coding";
- case AP4_MPEG4_AUDIO_OBJECT_TYPE_SLS:
- return "SLS Scalable Lossless Coding";
- case AP4_MPEG4_AUDIO_OBJECT_TYPE_SLS_NON_CORE:
- return "SLS Scalable Lossless Coding (Non Core)";
- case AP4_MPEG4_AUDIO_OBJECT_TYPE_ER_AAC_ELD:
- return "Error Resilient AAC ELD";
- case AP4_MPEG4_AUDIO_OBJECT_TYPE_SMR_SIMPLE:
- return "SMR Simple";
- case AP4_MPEG4_AUDIO_OBJECT_TYPE_SMR_MAIN:
- return "SMR Main";
- default:
- return "UNKNOWN";
+ switch (type) {
+ case AP4_MPEG4_AUDIO_OBJECT_TYPE_AAC_MAIN: return "AAC Main Profile";
+ case AP4_MPEG4_AUDIO_OBJECT_TYPE_AAC_LC: return "AAC Low Complexity";
+ case AP4_MPEG4_AUDIO_OBJECT_TYPE_AAC_SSR: return "AAC Scalable Sample Rate";
+ case AP4_MPEG4_AUDIO_OBJECT_TYPE_AAC_LTP: return "AAC Long Term Predictor";
+ case AP4_MPEG4_AUDIO_OBJECT_TYPE_SBR: return "Spectral Band Replication";
+ case AP4_MPEG4_AUDIO_OBJECT_TYPE_AAC_SCALABLE: return "AAC Scalable";
+ case AP4_MPEG4_AUDIO_OBJECT_TYPE_TWINVQ: return "Twin VQ";
+ case AP4_MPEG4_AUDIO_OBJECT_TYPE_CELP: return "CELP";
+ case AP4_MPEG4_AUDIO_OBJECT_TYPE_HVXC: return "HVXC";
+ case AP4_MPEG4_AUDIO_OBJECT_TYPE_TTSI: return "TTSI";
+ case AP4_MPEG4_AUDIO_OBJECT_TYPE_MAIN_SYNTHETIC: return "Main Synthetic";
+ case AP4_MPEG4_AUDIO_OBJECT_TYPE_WAVETABLE_SYNTHESIS: return "Wavetable Synthesis";
+ case AP4_MPEG4_AUDIO_OBJECT_TYPE_GENERAL_MIDI: return "General MIDI";
+ case AP4_MPEG4_AUDIO_OBJECT_TYPE_ALGORITHMIC_SYNTHESIS: return "Algorithmic Synthesis";
+ case AP4_MPEG4_AUDIO_OBJECT_TYPE_ER_AAC_LC: return "Error Resilient AAC Low Complexity";
+ case AP4_MPEG4_AUDIO_OBJECT_TYPE_ER_AAC_LTP: return "Error Resilient AAC Long Term Prediction";
+ case AP4_MPEG4_AUDIO_OBJECT_TYPE_ER_AAC_SCALABLE: return "Error Resilient AAC Scalable";
+ case AP4_MPEG4_AUDIO_OBJECT_TYPE_ER_TWINVQ: return "Error Resilient Twin VQ";
+ case AP4_MPEG4_AUDIO_OBJECT_TYPE_ER_BSAC: return "Error Resilient Bit Sliced Arithmetic Coding";
+ case AP4_MPEG4_AUDIO_OBJECT_TYPE_ER_AAC_LD: return "Error Resilient AAC Low Delay";
+ case AP4_MPEG4_AUDIO_OBJECT_TYPE_ER_CELP: return "Error Resilient CELP";
+ case AP4_MPEG4_AUDIO_OBJECT_TYPE_ER_HVXC: return "Error Resilient HVXC";
+ case AP4_MPEG4_AUDIO_OBJECT_TYPE_ER_HILN: return "Error Resilient HILN";
+ case AP4_MPEG4_AUDIO_OBJECT_TYPE_ER_PARAMETRIC: return "Error Resilient Parametric";
+ case AP4_MPEG4_AUDIO_OBJECT_TYPE_SSC: return "SSC";
+ case AP4_MPEG4_AUDIO_OBJECT_TYPE_MPEG_SURROUND: return "MPEG Surround";
+ case AP4_MPEG4_AUDIO_OBJECT_TYPE_LAYER_1: return "MPEG Layer 1";
+ case AP4_MPEG4_AUDIO_OBJECT_TYPE_LAYER_2: return "MPEG Layer 2";
+ case AP4_MPEG4_AUDIO_OBJECT_TYPE_LAYER_3: return "MPEG Layer 3";
+ case AP4_MPEG4_AUDIO_OBJECT_TYPE_DST: return "Direct Stream Transfer";
+ case AP4_MPEG4_AUDIO_OBJECT_TYPE_ALS: return "ALS Lossless Coding";
+ case AP4_MPEG4_AUDIO_OBJECT_TYPE_SLS: return "SLS Scalable Lossless Coding";
+ case AP4_MPEG4_AUDIO_OBJECT_TYPE_SLS_NON_CORE: return "SLS Scalable Lossless Coding (Non Core)";
+ case AP4_MPEG4_AUDIO_OBJECT_TYPE_ER_AAC_ELD: return "Error Resilient AAC ELD";
+ case AP4_MPEG4_AUDIO_OBJECT_TYPE_SMR_SIMPLE: return "SMR Simple";
+ case AP4_MPEG4_AUDIO_OBJECT_TYPE_SMR_MAIN: return "SMR Main";
+ default: return "UNKNOWN";
}
}
diff --git a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4SampleDescription.h b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4SampleDescription.h
index d38be6658..9e60cad7d 100644
--- a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4SampleDescription.h
+++ b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4SampleDescription.h
@@ -88,12 +88,11 @@ AP4_GetFormatName(AP4_UI32 format);
+---------------------------------------------------------------------*/
class AP4_SampleDescription
{
-public:
+ public:
AP4_IMPLEMENT_DYNAMIC_CAST(AP4_SampleDescription)
// type constants of the sample description
- enum Type
- {
+ enum Type {
TYPE_UNKNOWN = 0x00,
TYPE_MPEG = 0x01,
TYPE_PROTECTED = 0x02,
@@ -101,30 +100,21 @@ public:
};
// constructors & destructor
- AP4_SampleDescription(Type type,
- AP4_UI32 format,
+ AP4_SampleDescription(Type type,
+ AP4_UI32 format,
AP4_AtomParent* details);
virtual ~AP4_SampleDescription() {}
virtual AP4_SampleDescription* Clone(AP4_Result* result = NULL);
-
+
// accessors
- Type GetType() const
- {
- return m_Type;
- }
- AP4_UI32 GetFormat() const
- {
- return m_Format;
- }
- AP4_AtomParent& GetDetails()
- {
- return m_Details;
- }
-
+ Type GetType() const { return m_Type; }
+ AP4_UI32 GetFormat() const { return m_Format; }
+ AP4_AtomParent& GetDetails() { return m_Details; }
+
// factories
virtual AP4_Atom* ToAtom() const;
-protected:
+ protected:
Type m_Type;
AP4_UI32 m_Format;
AP4_AtomParent m_Details;
@@ -143,14 +133,11 @@ public:
~AP4_UnknownSampleDescription();
virtual AP4_SampleDescription* Clone(AP4_Result* result);
- virtual AP4_Atom* ToAtom() const;
-
+ virtual AP4_Atom* ToAtom() const;
+
// accessor
- const AP4_Atom* GetAtom()
- {
- return m_Atom;
- }
-
+ const AP4_Atom* GetAtom() { return m_Atom; }
+
private:
AP4_Atom* m_Atom;
};
@@ -167,23 +154,14 @@ public:
AP4_AudioSampleDescription(unsigned int sample_rate,
unsigned int sample_size,
unsigned int channel_count) :
- m_SampleRate(sample_rate),
- m_SampleSize(sample_size),
- m_ChannelCount(channel_count) {}
+ m_SampleRate(sample_rate),
+ m_SampleSize(sample_size),
+ m_ChannelCount(channel_count) {}
// accessors
- AP4_UI32 GetSampleRate()
- {
- return m_SampleRate;
- }
- AP4_UI16 GetSampleSize()
- {
- return m_SampleSize;
- }
- AP4_UI16 GetChannelCount()
- {
- return m_ChannelCount;
- }
+ AP4_UI32 GetSampleRate() { return m_SampleRate; }
+ AP4_UI16 GetSampleSize() { return m_SampleSize; }
+ AP4_UI16 GetChannelCount() { return m_ChannelCount; }
protected:
// members
@@ -205,28 +183,16 @@ public:
AP4_UI16 height,
AP4_UI16 depth,
const char* compressor_name) :
- m_Width(width),
- m_Height(height),
- m_Depth(depth),
- m_CompressorName(compressor_name) {}
+ m_Width(width),
+ m_Height(height),
+ m_Depth(depth),
+ m_CompressorName(compressor_name) {}
// accessors
- AP4_UI16 GetWidth()
- {
- return m_Width;
- }
- AP4_UI16 GetHeight()
- {
- return m_Height;
- }
- AP4_UI16 GetDepth()
- {
- return m_Depth;
- }
- const char* GetCompressorName()
- {
- return m_CompressorName.GetChars();
- }
+ AP4_UI16 GetWidth() { return m_Width; }
+ AP4_UI16 GetHeight() { return m_Height; }
+ AP4_UI16 GetDepth() { return m_Depth; }
+ const char* GetCompressorName() { return m_CompressorName.GetChars(); }
protected:
// members
@@ -240,7 +206,7 @@ protected:
| AP4_GenericAudioSampleDescription
+---------------------------------------------------------------------*/
class AP4_GenericAudioSampleDescription : public AP4_SampleDescription,
- public AP4_AudioSampleDescription
+ public AP4_AudioSampleDescription
{
public:
AP4_IMPLEMENT_DYNAMIC_CAST_D2(AP4_GenericAudioSampleDescription, AP4_SampleDescription, AP4_AudioSampleDescription)
@@ -259,7 +225,7 @@ public:
| AP4_GenericVideoSampleDescription
+---------------------------------------------------------------------*/
class AP4_GenericVideoSampleDescription : public AP4_SampleDescription,
- public AP4_VideoSampleDescription
+ public AP4_VideoSampleDescription
{
public:
AP4_IMPLEMENT_DYNAMIC_CAST_D2(AP4_GenericVideoSampleDescription, AP4_SampleDescription, AP4_VideoSampleDescription)
@@ -271,15 +237,15 @@ public:
AP4_UI16 depth,
const char* compressor_name,
AP4_AtomParent* details) :
- AP4_SampleDescription(TYPE_UNKNOWN, format, details),
- AP4_VideoSampleDescription(width, height, depth, compressor_name) {}
+ AP4_SampleDescription(TYPE_UNKNOWN, format, details),
+ AP4_VideoSampleDescription(width, height, depth, compressor_name) {}
};
/*----------------------------------------------------------------------
| AP4_AvcSampleDescription
+---------------------------------------------------------------------*/
class AP4_AvcSampleDescription : public AP4_SampleDescription,
- public AP4_VideoSampleDescription
+ public AP4_VideoSampleDescription
{
public:
AP4_IMPLEMENT_DYNAMIC_CAST_D2(AP4_AvcSampleDescription, AP4_SampleDescription, AP4_VideoSampleDescription)
@@ -290,7 +256,7 @@ public:
AP4_UI16 depth,
const char* compressor_name,
const AP4_AvccAtom* avcc);
-
+
AP4_AvcSampleDescription(AP4_UI16 width,
AP4_UI16 height,
AP4_UI16 depth,
@@ -307,47 +273,22 @@ public:
AP4_UI08 nalu_length_size,
const AP4_Array<AP4_DataBuffer>& sequence_parameters,
const AP4_Array<AP4_DataBuffer>& picture_parameters);
-
+
// accessors
- AP4_UI08 GetConfigurationVersion() const
- {
- return m_AvccAtom->GetConfigurationVersion();
- }
- AP4_UI08 GetProfile() const
- {
- return m_AvccAtom->GetProfile();
- }
- AP4_UI08 GetLevel() const
- {
- return m_AvccAtom->GetLevel();
- }
- AP4_UI08 GetProfileCompatibility() const
- {
- return m_AvccAtom->GetProfileCompatibility();
- }
- AP4_UI08 GetNaluLengthSize() const
- {
- return m_AvccAtom->GetNaluLengthSize();
- }
- AP4_Array<AP4_DataBuffer>& GetSequenceParameters()
- {
- return m_AvccAtom->GetSequenceParameters();
- }
- AP4_Array<AP4_DataBuffer>& GetPictureParameters()
- {
- return m_AvccAtom->GetPictureParameters();
- }
- const AP4_DataBuffer& GetRawBytes() const
- {
- return m_AvccAtom->GetRawBytes();
- }
-
+ AP4_UI08 GetConfigurationVersion() const { return m_AvccAtom->GetConfigurationVersion(); }
+ AP4_UI08 GetProfile() const { return m_AvccAtom->GetProfile(); }
+ AP4_UI08 GetLevel() const { return m_AvccAtom->GetLevel(); }
+ AP4_UI08 GetProfileCompatibility() const { return m_AvccAtom->GetProfileCompatibility(); }
+ AP4_UI08 GetNaluLengthSize() const { return m_AvccAtom->GetNaluLengthSize(); }
+ AP4_Array<AP4_DataBuffer>& GetSequenceParameters() {return m_AvccAtom->GetSequenceParameters(); }
+ AP4_Array<AP4_DataBuffer>& GetPictureParameters() { return m_AvccAtom->GetPictureParameters(); }
+ const AP4_DataBuffer& GetRawBytes() const { return m_AvccAtom->GetRawBytes(); }
+
// inherited from AP4_SampleDescription
virtual AP4_Atom* ToAtom() const;
-
+
// static methods
- static const char* GetProfileName(AP4_UI08 profile)
- {
+ static const char* GetProfileName(AP4_UI08 profile) {
return AP4_AvccAtom::GetProfileName(profile);
}
@@ -360,13 +301,13 @@ private:
+---------------------------------------------------------------------*/
class AP4_MpegSampleDescription : public AP4_SampleDescription
{
-public:
+ public:
AP4_IMPLEMENT_DYNAMIC_CAST_D(AP4_MpegSampleDescription, AP4_SampleDescription)
// types
typedef AP4_UI08 StreamType;
typedef AP4_UI08 OTI;
-
+
// class methods
static const char* GetStreamTypeString(StreamType type);
static const char* GetObjectTypeString(OTI oti);
@@ -381,37 +322,19 @@ public:
AP4_UI32 buffer_size,
AP4_UI32 max_bitrate,
AP4_UI32 avg_bitrate);
-
+
// accessors
- AP4_Byte GetStreamType() const
- {
- return m_StreamType;
- }
- AP4_Byte GetObjectTypeId() const
- {
- return m_ObjectTypeId;
- }
- AP4_UI32 GetBufferSize() const
- {
- return m_BufferSize;
- }
- AP4_UI32 GetMaxBitrate() const
- {
- return m_MaxBitrate;
- }
- AP4_UI32 GetAvgBitrate() const
- {
- return m_AvgBitrate;
- }
- const AP4_DataBuffer& GetDecoderInfo() const
- {
- return m_DecoderInfo;
- }
+ AP4_Byte GetStreamType() const { return m_StreamType; }
+ AP4_Byte GetObjectTypeId() const { return m_ObjectTypeId; }
+ AP4_UI32 GetBufferSize() const { return m_BufferSize; }
+ AP4_UI32 GetMaxBitrate() const { return m_MaxBitrate; }
+ AP4_UI32 GetAvgBitrate() const { return m_AvgBitrate; }
+ const AP4_DataBuffer& GetDecoderInfo() const { return m_DecoderInfo; }
// methods
AP4_EsDescriptor* CreateEsDescriptor() const;
-protected:
+ protected:
// members
AP4_UI32 m_Format;
StreamType m_StreamType;
@@ -447,23 +370,23 @@ public:
| AP4_MpegAudioSampleDescription
+---------------------------------------------------------------------*/
class AP4_MpegAudioSampleDescription : public AP4_MpegSampleDescription,
- public AP4_AudioSampleDescription
+ public AP4_AudioSampleDescription
{
public:
AP4_IMPLEMENT_DYNAMIC_CAST_D2(AP4_MpegAudioSampleDescription, AP4_MpegSampleDescription, AP4_AudioSampleDescription)
// types
typedef AP4_UI08 Mpeg4AudioObjectType;
-
+
// class methods
static const char* GetMpeg4AudioObjectTypeString(Mpeg4AudioObjectType type);
-
+
// constructor
AP4_MpegAudioSampleDescription(unsigned int sample_rate,
unsigned int sample_size,
unsigned int channel_count,
AP4_EsdsAtom* esds);
-
+
AP4_MpegAudioSampleDescription(OTI oti,
unsigned int sample_rate,
unsigned int sample_size,
@@ -477,8 +400,8 @@ public:
AP4_Atom* ToAtom() const;
/**
- * For sample descriptions of MPEG-4 audio tracks (i.e GetObjectTypeId()
- * returns AP4_OTI_MPEG4_AUDIO), this method returns the MPEG4 Audio Object
+ * For sample descriptions of MPEG-4 audio tracks (i.e GetObjectTypeId()
+ * returns AP4_OTI_MPEG4_AUDIO), this method returns the MPEG4 Audio Object
* Type. For other sample descriptions, this method returns 0.
*/
Mpeg4AudioObjectType GetMpeg4AudioObjectType() const;
@@ -488,7 +411,7 @@ public:
| AP4_MpegVideoSampleDescription
+---------------------------------------------------------------------*/
class AP4_MpegVideoSampleDescription : public AP4_MpegSampleDescription,
- public AP4_VideoSampleDescription
+ public AP4_VideoSampleDescription
{
public:
AP4_IMPLEMENT_DYNAMIC_CAST_D2(AP4_MpegVideoSampleDescription, AP4_MpegSampleDescription, AP4_VideoSampleDescription)
@@ -499,7 +422,7 @@ public:
AP4_UI16 depth,
const char* compressor_name,
AP4_EsdsAtom* esds);
-
+
AP4_MpegVideoSampleDescription(OTI oti,
AP4_UI16 width,
AP4_UI16 height,
@@ -519,7 +442,7 @@ public:
+---------------------------------------------------------------------*/
const AP4_MpegSampleDescription::StreamType AP4_STREAM_TYPE_FORBIDDEN = 0x00;
const AP4_MpegSampleDescription::StreamType AP4_STREAM_TYPE_OD = 0x01;
-const AP4_MpegSampleDescription::StreamType AP4_STREAM_TYPE_CR = 0x02;
+const AP4_MpegSampleDescription::StreamType AP4_STREAM_TYPE_CR = 0x02;
const AP4_MpegSampleDescription::StreamType AP4_STREAM_TYPE_BIFS = 0x03;
const AP4_MpegSampleDescription::StreamType AP4_STREAM_TYPE_VISUAL = 0x04;
const AP4_MpegSampleDescription::StreamType AP4_STREAM_TYPE_AUDIO = 0x05;
@@ -587,8 +510,8 @@ const AP4_UI08 AP4_MPEG4_AUDIO_OBJECT_TYPE_SMR_SIMPLE = 40; /**< SMR
const AP4_UI08 AP4_MPEG4_AUDIO_OBJECT_TYPE_SMR_MAIN = 41; /**< SMR Main */
// ==> Start patch MPC
-const AP4_MpegSampleDescription::OTI AP4_NERO_VOBSUB = 0xE0;
-// <== End patch MPC
+const AP4_MpegSampleDescription::OTI AP4_NERO_VOBSUB = 0xE0;
+// <== End patch MPC
#endif // _AP4_SAMPLE_DESCRIPTION_H_
diff --git a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4SampleEntry.cpp b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4SampleEntry.cpp
index ee975ab08..086401b01 100644
--- a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4SampleEntry.cpp
+++ b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4SampleEntry.cpp
@@ -93,11 +93,10 @@ AP4_SampleEntry::Read(AP4_ByteStream& stream, AP4_AtomFactory& atom_factory)
// read children atoms (ex: esds and maybe others)
// NOTE: not all sample entries have children atoms
- AP4_Size payload_size = (AP4_Size)(GetSize() - GetHeaderSize());
+ AP4_Size payload_size = (AP4_Size)(GetSize()-GetHeaderSize());
AP4_Size fields_size = GetFieldsSize();
- if(payload_size > fields_size)
- {
- ReadChildren(atom_factory, stream, payload_size - fields_size);
+ if (payload_size > fields_size) {
+ ReadChildren(atom_factory, stream, payload_size-fields_size);
}
}
@@ -129,15 +128,15 @@ AP4_Result
AP4_SampleEntry::WriteFields(AP4_ByteStream& stream)
{
AP4_Result result;
-
+
// reserved1
result = stream.Write(m_Reserved1, sizeof(m_Reserved1));
- if(AP4_FAILED(result)) return result;
+ if (AP4_FAILED(result)) return result;
// data reference index
result = stream.WriteUI16(m_DataReferenceIndex);
- if(AP4_FAILED(result)) return result;
-
+ if (AP4_FAILED(result)) return result;
+
return result;
}
@@ -151,11 +150,11 @@ AP4_SampleEntry::Write(AP4_ByteStream& stream)
// write the header
result = WriteHeader(stream);
- if(AP4_FAILED(result)) return result;
+ if (AP4_FAILED(result)) return result;
// write the fields
result = WriteFields(stream);
- if(AP4_FAILED(result)) return result;
+ if (AP4_FAILED(result)) return result;
// write the children atoms
return m_Children.Apply(AP4_AtomListWriter(stream));
@@ -200,12 +199,12 @@ void
AP4_SampleEntry::OnChildChanged(AP4_Atom*)
{
// recompute our size
- AP4_UI64 size = GetHeaderSize() + GetFieldsSize();
+ AP4_UI64 size = GetHeaderSize()+GetFieldsSize();
m_Children.Apply(AP4_AtomSizeAdder(size));
m_Size32 = (AP4_UI32)size;
// update our parent
- if(m_Parent) m_Parent->OnChildChanged(this);
+ if (m_Parent) m_Parent->OnChildChanged(this);
}
/*----------------------------------------------------------------------
@@ -220,14 +219,13 @@ AP4_SampleEntry::ToSampleDescription()
/*----------------------------------------------------------------------
| AP4_UnknownSampleEntry::AP4_UnknownSampleEntry
+---------------------------------------------------------------------*/
-AP4_UnknownSampleEntry::AP4_UnknownSampleEntry(AP4_Atom::Type type,
- AP4_Size size,
- AP4_ByteStream& stream) :
+AP4_UnknownSampleEntry::AP4_UnknownSampleEntry(AP4_Atom::Type type,
+ AP4_Size size,
+ AP4_ByteStream& stream) :
AP4_SampleEntry(type, size)
{
- if(size > AP4_ATOM_HEADER_SIZE + AP4_SampleEntry::GetFieldsSize())
- {
- m_Payload.SetDataSize(size - (AP4_ATOM_HEADER_SIZE + AP4_SampleEntry::GetFieldsSize()));
+ if (size > AP4_ATOM_HEADER_SIZE+AP4_SampleEntry::GetFieldsSize()) {
+ m_Payload.SetDataSize(size-(AP4_ATOM_HEADER_SIZE+AP4_SampleEntry::GetFieldsSize()));
ReadFields(stream);
}
}
@@ -235,7 +233,7 @@ AP4_UnknownSampleEntry::AP4_UnknownSampleEntry(AP4_Atom::Type type,
/*----------------------------------------------------------------------
| AP4_UnknownSampleEntry::ToSampleDescription
+---------------------------------------------------------------------*/
-AP4_SampleDescription*
+AP4_SampleDescription*
AP4_UnknownSampleEntry::ToSampleDescription()
{
return new AP4_UnknownSampleDescription(this);
@@ -244,10 +242,10 @@ AP4_UnknownSampleEntry::ToSampleDescription()
/*----------------------------------------------------------------------
| AP4_UnknownSampleEntry::GetFieldsSize
+---------------------------------------------------------------------*/
-AP4_Size
+AP4_Size
AP4_UnknownSampleEntry::GetFieldsSize()
{
- return AP4_SampleEntry::GetFieldsSize() + m_Payload.GetDataSize();
+ return AP4_SampleEntry::GetFieldsSize()+m_Payload.GetDataSize();
}
/*----------------------------------------------------------------------
@@ -258,8 +256,8 @@ AP4_UnknownSampleEntry::ReadFields(AP4_ByteStream& stream)
{
// sample entry
AP4_Result result = AP4_SampleEntry::ReadFields(stream);
- if(AP4_FAILED(result)) return result;
-
+ if (AP4_FAILED(result)) return result;
+
// read the payload
return stream.Read(m_Payload.UseData(), m_Payload.GetDataSize());
}
@@ -271,11 +269,11 @@ AP4_Result
AP4_UnknownSampleEntry::WriteFields(AP4_ByteStream& stream)
{
AP4_Result result;
-
+
// write the fields of the base class
result = AP4_SampleEntry::WriteFields(stream);
- if(AP4_FAILED(result)) return result;
-
+ if (AP4_FAILED(result)) return result;
+
// write the payload
return stream.Write(m_Payload.GetData(), m_Payload.GetDataSize());
}
@@ -288,7 +286,7 @@ AP4_MpegSystemSampleEntry::AP4_MpegSystemSampleEntry(
AP4_EsDescriptor* descriptor) :
AP4_SampleEntry(type)
{
- if(descriptor) AddChild(new AP4_EsdsAtom(descriptor));
+ if (descriptor) AddChild(new AP4_EsdsAtom(descriptor));
}
/*----------------------------------------------------------------------
@@ -310,7 +308,7 @@ AP4_SampleDescription*
AP4_MpegSystemSampleEntry::ToSampleDescription()
{
return new AP4_MpegSystemSampleDescription(
- AP4_DYNAMIC_CAST(AP4_EsdsAtom, GetChild(AP4_ATOM_TYPE_ESDS)));
+ AP4_DYNAMIC_CAST(AP4_EsdsAtom, GetChild(AP4_ATOM_TYPE_ESDS)));
}
/*----------------------------------------------------------------------
@@ -325,8 +323,8 @@ AP4_Mp4sSampleEntry::AP4_Mp4sSampleEntry(AP4_EsDescriptor* descriptor) :
| AP4_Mp4sSampleEntry::AP4_Mp4sSampleEntry
+---------------------------------------------------------------------*/
AP4_Mp4sSampleEntry::AP4_Mp4sSampleEntry(AP4_Size size,
- AP4_ByteStream& stream,
- AP4_AtomFactory& atom_factory) :
+ AP4_ByteStream& stream,
+ AP4_AtomFactory& atom_factory) :
AP4_MpegSystemSampleEntry(AP4_ATOM_TYPE_MP4S, size, stream, atom_factory)
{
}
@@ -339,16 +337,16 @@ AP4_Mp4sSampleEntry::ToSampleDescription()
{
// create a sample description
return new AP4_MpegSystemSampleDescription(
- AP4_DYNAMIC_CAST(AP4_EsdsAtom, GetChild(AP4_ATOM_TYPE_ESDS)));
+ AP4_DYNAMIC_CAST(AP4_EsdsAtom, GetChild(AP4_ATOM_TYPE_ESDS)));
}
/*----------------------------------------------------------------------
| AP4_AudioSampleEntry::AP4_AudioSampleEntry
+---------------------------------------------------------------------*/
AP4_AudioSampleEntry::AP4_AudioSampleEntry(AP4_Atom::Type format,
- AP4_UI32 sample_rate,
- AP4_UI16 sample_size,
- AP4_UI16 channel_count) :
+ AP4_UI32 sample_rate,
+ AP4_UI16 sample_size,
+ AP4_UI16 channel_count) :
AP4_SampleEntry(format),
m_QtVersion(0),
m_QtRevision(0),
@@ -369,7 +367,7 @@ AP4_AudioSampleEntry::AP4_AudioSampleEntry(AP4_Atom::Type format,
m_QtV2BitsPerChannel(0),
m_QtV2FormatSpecificFlags(0),
m_QtV2BytesPerAudioPacket(0),
- m_QtV2LPCMFramesPerAudioPacket(0)
+ m_QtV2LPCMFramesPerAudioPacket(0)
{
m_Size32 += 20;
}
@@ -378,30 +376,27 @@ AP4_AudioSampleEntry::AP4_AudioSampleEntry(AP4_Atom::Type format,
| AP4_AudioSampleEntry::AP4_AudioSampleEntry
+---------------------------------------------------------------------*/
AP4_AudioSampleEntry::AP4_AudioSampleEntry(AP4_Atom::Type format,
- AP4_Size size,
- AP4_ByteStream& stream,
- AP4_AtomFactory& atom_factory) :
+ AP4_Size size,
+ AP4_ByteStream& stream,
+ AP4_AtomFactory& atom_factory) :
AP4_SampleEntry(format, size)
{
Read(stream, atom_factory);
}
-
+
/*----------------------------------------------------------------------
| AP4_AudioSampleEntry::GetFieldsSize
+---------------------------------------------------------------------*/
AP4_Size
AP4_AudioSampleEntry::GetFieldsSize()
{
- AP4_Size size = AP4_SampleEntry::GetFieldsSize() + 20;
- if(m_QtVersion == 1)
- {
+ AP4_Size size = AP4_SampleEntry::GetFieldsSize()+20;
+ if (m_QtVersion == 1) {
size += 16;
+ } else if (m_QtVersion == 2) {
+ size += 36+m_QtV2Extension.GetDataSize();
}
- else if(m_QtVersion == 2)
- {
- size += 36 + m_QtV2Extension.GetDataSize();
- }
-
+
return size;
}
@@ -411,13 +406,10 @@ AP4_AudioSampleEntry::GetFieldsSize()
AP4_UI32
AP4_AudioSampleEntry::GetSampleRate()
{
- if(m_QtVersion == 2)
- {
+ if (m_QtVersion == 2) {
return (AP4_UI32)(m_QtV2SampleRate64);
- }
- else
- {
- return m_SampleRate >> 16;
+ } else {
+ return m_SampleRate>>16;
}
}
@@ -427,12 +419,9 @@ AP4_AudioSampleEntry::GetSampleRate()
AP4_UI16
AP4_AudioSampleEntry::GetChannelCount()
{
- if(m_QtVersion == 2)
- {
+ if (m_QtVersion == 2) {
return m_QtV2ChannelCount;
- }
- else
- {
+ } else {
return m_ChannelCount;
}
}
@@ -445,7 +434,7 @@ AP4_AudioSampleEntry::ReadFields(AP4_ByteStream& stream)
{
// sample entry
AP4_Result result = AP4_SampleEntry::ReadFields(stream);
- if(result < 0) return result;
+ if (result < 0) return result;
// read the fields of this class
stream.ReadUI16(m_QtVersion);
@@ -458,15 +447,12 @@ AP4_AudioSampleEntry::ReadFields(AP4_ByteStream& stream)
stream.ReadUI32(m_SampleRate);
// if this is a QT V1 entry, read the extension
- if(m_QtVersion == 1)
- {
+ if (m_QtVersion == 1) {
stream.ReadUI32(m_QtV1SamplesPerPacket);
stream.ReadUI32(m_QtV1BytesPerPacket);
stream.ReadUI32(m_QtV1BytesPerFrame);
stream.ReadUI32(m_QtV1BytesPerSample);
- }
- else if(m_QtVersion == 2)
- {
+ } else if (m_QtVersion == 2) {
stream.ReadUI32(m_QtV2StructSize);
stream.ReadDouble(m_QtV2SampleRate64);
stream.ReadUI32(m_QtV2ChannelCount);
@@ -475,19 +461,16 @@ AP4_AudioSampleEntry::ReadFields(AP4_ByteStream& stream)
stream.ReadUI32(m_QtV2FormatSpecificFlags);
stream.ReadUI32(m_QtV2BytesPerAudioPacket);
stream.ReadUI32(m_QtV2LPCMFramesPerAudioPacket);
- if(m_QtV2StructSize > 72)
- {
- unsigned int ext_size = m_QtV2StructSize - 72;
+ if (m_QtV2StructSize > 72) {
+ unsigned int ext_size = m_QtV2StructSize-72;
m_QtV2Extension.SetDataSize(ext_size);
stream.Read(m_QtV2Extension.UseData(), ext_size);
}
m_QtV1SamplesPerPacket =
- m_QtV1BytesPerPacket =
- m_QtV1BytesPerFrame =
- m_QtV1BytesPerSample = 0;
- }
- else
- {
+ m_QtV1BytesPerPacket =
+ m_QtV1BytesPerFrame =
+ m_QtV1BytesPerSample = 0;
+ } else {
m_QtV1SamplesPerPacket = 0;
m_QtV1BytesPerPacket = 0;
m_QtV1BytesPerFrame = 0;
@@ -501,7 +484,7 @@ AP4_AudioSampleEntry::ReadFields(AP4_ByteStream& stream)
m_QtV2BytesPerAudioPacket = 0;
m_QtV2LPCMFramesPerAudioPacket = 0;
}
-
+
return AP4_SUCCESS;
}
@@ -512,55 +495,52 @@ AP4_Result
AP4_AudioSampleEntry::WriteFields(AP4_ByteStream& stream)
{
AP4_Result result;
-
+
// write the fields of the base class
result = AP4_SampleEntry::WriteFields(stream);
// QT version
result = stream.WriteUI16(m_QtVersion);
- if(AP4_FAILED(result)) return result;
+ if (AP4_FAILED(result)) return result;
// QT revision
result = stream.WriteUI16(m_QtRevision);
- if(AP4_FAILED(result)) return result;
+ if (AP4_FAILED(result)) return result;
// QT vendor
result = stream.WriteUI32(m_QtVendor);
- if(AP4_FAILED(result)) return result;
+ if (AP4_FAILED(result)) return result;
// channel count
result = stream.WriteUI16(m_ChannelCount);
- if(AP4_FAILED(result)) return result;
-
- // sample size
+ if (AP4_FAILED(result)) return result;
+
+ // sample size
result = stream.WriteUI16(m_SampleSize);
- if(AP4_FAILED(result)) return result;
+ if (AP4_FAILED(result)) return result;
// QT compression ID
result = stream.WriteUI16(m_QtCompressionId);
- if(AP4_FAILED(result)) return result;
+ if (AP4_FAILED(result)) return result;
// QT packet size
result = stream.WriteUI16(m_QtPacketSize);
- if(AP4_FAILED(result)) return result;
+ if (AP4_FAILED(result)) return result;
// sample rate
result = stream.WriteUI32(m_SampleRate);
- if(AP4_FAILED(result)) return result;
+ if (AP4_FAILED(result)) return result;
- if(m_QtVersion == 1)
- {
+ if (m_QtVersion == 1) {
result = stream.WriteUI32(m_QtV1SamplesPerPacket);
- if(AP4_FAILED(result)) return result;
+ if (AP4_FAILED(result)) return result;
result = stream.WriteUI32(m_QtV1BytesPerPacket);
- if(AP4_FAILED(result)) return result;
+ if (AP4_FAILED(result)) return result;
result = stream.WriteUI32(m_QtV1BytesPerFrame);
- if(AP4_FAILED(result)) return result;
+ if (AP4_FAILED(result)) return result;
result = stream.WriteUI32(m_QtV1BytesPerSample);
- if(AP4_FAILED(result)) return result;
- }
- else if(m_QtVersion == 2)
- {
+ if (AP4_FAILED(result)) return result;
+ } else if (m_QtVersion == 2) {
stream.WriteUI32(m_QtV2StructSize);
stream.WriteDouble(m_QtV2SampleRate64);
stream.WriteUI32(m_QtV2ChannelCount);
@@ -569,13 +549,12 @@ AP4_AudioSampleEntry::WriteFields(AP4_ByteStream& stream)
stream.WriteUI32(m_QtV2FormatSpecificFlags);
stream.WriteUI32(m_QtV2BytesPerAudioPacket);
stream.WriteUI32(m_QtV2LPCMFramesPerAudioPacket);
- if(m_QtV2Extension.GetDataSize())
- {
+ if (m_QtV2Extension.GetDataSize()) {
stream.Write(m_QtV2Extension.GetData(),
m_QtV2Extension.GetDataSize());
}
}
-
+
return result;
}
@@ -592,11 +571,10 @@ AP4_AudioSampleEntry::InspectFields(AP4_AtomInspector& inspector)
inspector.AddField("channel_count", GetChannelCount());
inspector.AddField("sample_size", GetSampleSize());
inspector.AddField("sample_rate", GetSampleRate());
- if(m_QtVersion)
- {
+ if (m_QtVersion) {
inspector.AddField("qt_version", m_QtVersion);
}
-
+
return AP4_SUCCESS;
}
@@ -608,11 +586,11 @@ AP4_AudioSampleEntry::ToSampleDescription()
{
// create a sample description
return new AP4_GenericAudioSampleDescription(
- m_Type,
- GetSampleRate(),
- GetSampleSize(),
- GetChannelCount(),
- this);
+ m_Type,
+ GetSampleRate(),
+ GetSampleSize(),
+ GetChannelCount(),
+ this);
}
/*----------------------------------------------------------------------
@@ -620,13 +598,13 @@ AP4_AudioSampleEntry::ToSampleDescription()
+---------------------------------------------------------------------*/
AP4_MpegAudioSampleEntry::AP4_MpegAudioSampleEntry(
AP4_UI32 type,
- AP4_UI32 sample_rate,
+ AP4_UI32 sample_rate,
AP4_UI16 sample_size,
AP4_UI16 channel_count,
AP4_EsDescriptor* descriptor) :
AP4_AudioSampleEntry(type, sample_rate, sample_size, channel_count)
{
- if(descriptor) AddChild(new AP4_EsdsAtom(descriptor));
+ if (descriptor) AddChild(new AP4_EsdsAtom(descriptor));
}
/*----------------------------------------------------------------------
@@ -649,32 +627,30 @@ AP4_MpegAudioSampleEntry::ToSampleDescription()
{
// find the esds atom
AP4_EsdsAtom* esds = AP4_DYNAMIC_CAST(AP4_EsdsAtom, GetChild(AP4_ATOM_TYPE_ESDS));
- if(esds == NULL)
- {
+ if (esds == NULL) {
// check if this is a quicktime style sample description
- if(m_QtVersion > 0)
- {
+ if (m_QtVersion > 0) {
esds = AP4_DYNAMIC_CAST(AP4_EsdsAtom, FindChild("wave/esds"));
}
}
-
+
// create a sample description
return new AP4_MpegAudioSampleDescription(GetSampleRate(),
- GetSampleSize(),
- GetChannelCount(),
- esds);
+ GetSampleSize(),
+ GetChannelCount(),
+ esds);
}
/*----------------------------------------------------------------------
| AP4_Mp4aSampleEntry::AP4_Mp4aSampleEntry
+---------------------------------------------------------------------*/
-AP4_Mp4aSampleEntry::AP4_Mp4aSampleEntry(AP4_UI32 sample_rate,
- AP4_UI16 sample_size,
- AP4_UI16 channel_count,
- AP4_EsDescriptor* descriptor) :
- AP4_MpegAudioSampleEntry(AP4_ATOM_TYPE_MP4A,
- sample_rate,
- sample_size,
+AP4_Mp4aSampleEntry::AP4_Mp4aSampleEntry(AP4_UI32 sample_rate,
+ AP4_UI16 sample_size,
+ AP4_UI16 channel_count,
+ AP4_EsDescriptor* descriptor) :
+ AP4_MpegAudioSampleEntry(AP4_ATOM_TYPE_MP4A,
+ sample_rate,
+ sample_size,
channel_count,
descriptor)
{
@@ -684,8 +660,8 @@ AP4_Mp4aSampleEntry::AP4_Mp4aSampleEntry(AP4_UI32 sample_rate,
| AP4_Mp4aSampleEntry::AP4_Mp4aSampleEntry
+---------------------------------------------------------------------*/
AP4_Mp4aSampleEntry::AP4_Mp4aSampleEntry(AP4_Size size,
- AP4_ByteStream& stream,
- AP4_AtomFactory& atom_factory) :
+ AP4_ByteStream& stream,
+ AP4_AtomFactory& atom_factory) :
AP4_MpegAudioSampleEntry(AP4_ATOM_TYPE_MP4A, size, stream, atom_factory)
{
}
@@ -694,7 +670,7 @@ AP4_Mp4aSampleEntry::AP4_Mp4aSampleEntry(AP4_Size size,
| AP4_VisualSampleEntry::AP4_VisualSampleEntry
+---------------------------------------------------------------------*/
AP4_VisualSampleEntry::AP4_VisualSampleEntry(
- AP4_Atom::Type format,
+ AP4_Atom::Type format,
AP4_UI16 width,
AP4_UI16 height,
AP4_UI16 depth,
@@ -720,9 +696,9 @@ AP4_VisualSampleEntry::AP4_VisualSampleEntry(
| AP4_VisualSampleEntry::AP4_VisualSampleEntry
+---------------------------------------------------------------------*/
AP4_VisualSampleEntry::AP4_VisualSampleEntry(AP4_Atom::Type format,
- AP4_Size size,
- AP4_ByteStream& stream,
- AP4_AtomFactory& atom_factory) :
+ AP4_Size size,
+ AP4_ByteStream& stream,
+ AP4_AtomFactory& atom_factory) :
AP4_SampleEntry(format, size)
{
Read(stream, atom_factory);
@@ -734,7 +710,7 @@ AP4_VisualSampleEntry::AP4_VisualSampleEntry(AP4_Atom::Type format,
AP4_Size
AP4_VisualSampleEntry::GetFieldsSize()
{
- return AP4_SampleEntry::GetFieldsSize() + 70;
+ return AP4_SampleEntry::GetFieldsSize()+70;
}
/*----------------------------------------------------------------------
@@ -745,7 +721,7 @@ AP4_VisualSampleEntry::ReadFields(AP4_ByteStream& stream)
{
// sample entry
AP4_Result result = AP4_SampleEntry::ReadFields(stream);
- if(result < 0) return result;
+ if (result < 0) return result;
// read fields from this class
stream.ReadUI16(m_Predefined1);
@@ -761,8 +737,7 @@ AP4_VisualSampleEntry::ReadFields(AP4_ByteStream& stream)
char compressor_name[33];
stream.Read(compressor_name, 32);
int name_length = compressor_name[0];
- if(name_length < 32)
- {
+ if (name_length < 32) {
compressor_name[name_length+1] = 0; // force null termination
m_CompressorName = &compressor_name[1];
}
@@ -780,71 +755,69 @@ AP4_Result
AP4_VisualSampleEntry::WriteFields(AP4_ByteStream& stream)
{
AP4_Result result;
-
+
// write the fields of the base class
result = AP4_SampleEntry::WriteFields(stream);
- if(AP4_FAILED(result)) return result;
+ if (AP4_FAILED(result)) return result;
// predefined1
result = stream.WriteUI16(m_Predefined1);
- if(AP4_FAILED(result)) return result;
-
+ if (AP4_FAILED(result)) return result;
+
// reserved2
result = stream.WriteUI16(m_Reserved2);
- if(AP4_FAILED(result)) return result;
-
+ if (AP4_FAILED(result)) return result;
+
// predefined2
result = stream.Write(m_Predefined2, sizeof(m_Predefined2));
- if(AP4_FAILED(result)) return result;
-
+ if (AP4_FAILED(result)) return result;
+
// width
result = stream.WriteUI16(m_Width);
- if(AP4_FAILED(result)) return result;
-
+ if (AP4_FAILED(result)) return result;
+
// height
result = stream.WriteUI16(m_Height);
- if(AP4_FAILED(result)) return result;
-
+ if (AP4_FAILED(result)) return result;
+
// horizontal resolution
result = stream.WriteUI32(m_HorizResolution);
- if(AP4_FAILED(result)) return result;
-
+ if (AP4_FAILED(result)) return result;
+
// vertical resolution
result = stream.WriteUI32(m_VertResolution);
- if(AP4_FAILED(result)) return result;
-
+ if (AP4_FAILED(result)) return result;
+
// reserved3
result = stream.WriteUI32(m_Reserved3);
- if(AP4_FAILED(result)) return result;
-
+ if (AP4_FAILED(result)) return result;
+
// frame count
result = stream.WriteUI16(m_FrameCount);
- if(AP4_FAILED(result)) return result;
-
+ if (AP4_FAILED(result)) return result;
+
// compressor name
unsigned char compressor_name[32];
unsigned int name_length = m_CompressorName.GetLength();
- if(name_length > 31) name_length = 31;
+ if (name_length > 31) name_length = 31;
compressor_name[0] = name_length;
- for(unsigned int i = 0; i < name_length; i++)
- {
+ for (unsigned int i=0; i<name_length; i++) {
compressor_name[i+1] = m_CompressorName[i];
}
- for(unsigned int i = name_length + 1; i < 32; i++)
- {
+ for (unsigned int i=name_length+1; i<32; i++) {
compressor_name[i] = 0;
}
result = stream.Write(compressor_name, 32);
- if(AP4_FAILED(result)) return result;
-
+ if (AP4_FAILED(result)) return result;
+
// depth
result = stream.WriteUI16(m_Depth);
- if(AP4_FAILED(result)) return result;
-
+ if (AP4_FAILED(result)) return result;
+
// predefined3
result = stream.WriteUI16(m_Predefined3);
- if(AP4_FAILED(result)) return result;
-
+ if (AP4_FAILED(result)) return result;
+
return result;
}
@@ -873,12 +846,12 @@ AP4_VisualSampleEntry::ToSampleDescription()
{
// create a sample description
return new AP4_GenericVideoSampleDescription(
- m_Type,
- m_Width,
- m_Height,
- m_Depth,
- m_CompressorName.GetChars(),
- this);
+ m_Type,
+ m_Width,
+ m_Height,
+ m_Depth,
+ m_CompressorName.GetChars(),
+ this);
}
/*----------------------------------------------------------------------
@@ -891,13 +864,13 @@ AP4_MpegVideoSampleEntry::AP4_MpegVideoSampleEntry(
AP4_UI16 depth,
const char* compressor_name,
AP4_EsDescriptor* descriptor) :
- AP4_VisualSampleEntry(type,
- width,
- height,
- depth,
+ AP4_VisualSampleEntry(type,
+ width,
+ height,
+ depth,
compressor_name)
{
- if(descriptor) AddChild(new AP4_EsdsAtom(descriptor));
+ if (descriptor) AddChild(new AP4_EsdsAtom(descriptor));
}
/*----------------------------------------------------------------------
@@ -920,25 +893,25 @@ AP4_MpegVideoSampleEntry::ToSampleDescription()
{
// create a sample description
return new AP4_MpegVideoSampleDescription(
- m_Width,
- m_Height,
- m_Depth,
- m_CompressorName.GetChars(),
- AP4_DYNAMIC_CAST(AP4_EsdsAtom, GetChild(AP4_ATOM_TYPE_ESDS)));
+ m_Width,
+ m_Height,
+ m_Depth,
+ m_CompressorName.GetChars(),
+ AP4_DYNAMIC_CAST(AP4_EsdsAtom, GetChild(AP4_ATOM_TYPE_ESDS)));
}
/*----------------------------------------------------------------------
| AP4_Mp4vSampleEntry::AP4_Mp4vSampleEntry
+---------------------------------------------------------------------*/
AP4_Mp4vSampleEntry::AP4_Mp4vSampleEntry(AP4_UI16 width,
- AP4_UI16 height,
- AP4_UI16 depth,
- const char* compressor_name,
- AP4_EsDescriptor* descriptor) :
- AP4_MpegVideoSampleEntry(AP4_ATOM_TYPE_MP4V,
- width,
- height,
- depth,
+ AP4_UI16 height,
+ AP4_UI16 depth,
+ const char* compressor_name,
+ AP4_EsDescriptor* descriptor) :
+ AP4_MpegVideoSampleEntry(AP4_ATOM_TYPE_MP4V,
+ width,
+ height,
+ depth,
compressor_name,
descriptor)
{
@@ -948,8 +921,8 @@ AP4_Mp4vSampleEntry::AP4_Mp4vSampleEntry(AP4_UI16 width,
| AP4_Mp4vSampleEntry::AP4_Mp4aSampleEntry
+---------------------------------------------------------------------*/
AP4_Mp4vSampleEntry::AP4_Mp4vSampleEntry(AP4_Size size,
- AP4_ByteStream& stream,
- AP4_AtomFactory& atom_factory) :
+ AP4_ByteStream& stream,
+ AP4_AtomFactory& atom_factory) :
AP4_MpegVideoSampleEntry(AP4_ATOM_TYPE_MP4V, size, stream, atom_factory)
{
}
@@ -958,25 +931,25 @@ AP4_Mp4vSampleEntry::AP4_Mp4vSampleEntry(AP4_Size size,
| AP4_Avc1SampleEntry::AP4_Avc1SampleEntry
+---------------------------------------------------------------------*/
AP4_Avc1SampleEntry::AP4_Avc1SampleEntry(AP4_UI16 width,
- AP4_UI16 height,
- AP4_UI16 depth,
- const char* compressor_name,
- const AP4_AvccAtom& avcc) :
- AP4_VisualSampleEntry(AP4_ATOM_TYPE_AVC1,
- width,
- height,
- depth,
+ AP4_UI16 height,
+ AP4_UI16 depth,
+ const char* compressor_name,
+ const AP4_AvccAtom& avcc) :
+ AP4_VisualSampleEntry(AP4_ATOM_TYPE_AVC1,
+ width,
+ height,
+ depth,
compressor_name)
{
- AddChild(new AP4_AvccAtom(avcc));
+ AddChild(new AP4_AvccAtom(avcc));
}
/*----------------------------------------------------------------------
| AP4_Avc1SampleEntry::AP4_Avc1SampleEntry
+---------------------------------------------------------------------*/
AP4_Avc1SampleEntry::AP4_Avc1SampleEntry(AP4_Size size,
- AP4_ByteStream& stream,
- AP4_AtomFactory& atom_factory) :
+ AP4_ByteStream& stream,
+ AP4_AtomFactory& atom_factory) :
AP4_VisualSampleEntry(AP4_ATOM_TYPE_AVC1, size, stream, atom_factory)
{
}
@@ -988,20 +961,20 @@ AP4_SampleDescription*
AP4_Avc1SampleEntry::ToSampleDescription()
{
return new AP4_AvcSampleDescription(
- m_Width,
- m_Height,
- m_Depth,
- m_CompressorName.GetChars(),
- AP4_DYNAMIC_CAST(AP4_AvccAtom, GetChild(AP4_ATOM_TYPE_AVCC)));
+ m_Width,
+ m_Height,
+ m_Depth,
+ m_CompressorName.GetChars(),
+ AP4_DYNAMIC_CAST(AP4_AvccAtom, GetChild(AP4_ATOM_TYPE_AVCC)));
}
/*----------------------------------------------------------------------
| AP4_RtpHintSampleEntry::AP4_RtpHintSampleEntry
+---------------------------------------------------------------------*/
AP4_RtpHintSampleEntry::AP4_RtpHintSampleEntry(AP4_UI16 hint_track_version,
- AP4_UI16 highest_compatible_version,
- AP4_UI32 max_packet_size,
- AP4_UI32 timescale):
+ AP4_UI16 highest_compatible_version,
+ AP4_UI32 max_packet_size,
+ AP4_UI32 timescale):
AP4_SampleEntry(AP4_ATOM_TYPE_RTP_),
m_HintTrackVersion(hint_track_version),
m_HighestCompatibleVersion(highest_compatible_version),
@@ -1015,8 +988,8 @@ AP4_RtpHintSampleEntry::AP4_RtpHintSampleEntry(AP4_UI16 hint_track_version,
| AP4_RtpHintSampleEntry::AP4_RtpHintSampleEntry
+---------------------------------------------------------------------*/
AP4_RtpHintSampleEntry::AP4_RtpHintSampleEntry(AP4_Size size,
- AP4_ByteStream& stream,
- AP4_AtomFactory& atom_factory):
+ AP4_ByteStream& stream,
+ AP4_AtomFactory& atom_factory):
AP4_SampleEntry(AP4_ATOM_TYPE_RTP_, size)
{
Read(stream, atom_factory);
@@ -1028,7 +1001,7 @@ AP4_RtpHintSampleEntry::AP4_RtpHintSampleEntry(AP4_Size size,
AP4_Size
AP4_RtpHintSampleEntry::GetFieldsSize()
{
- return AP4_SampleEntry::GetFieldsSize() + 8;
+ return AP4_SampleEntry::GetFieldsSize()+8;
}
/*----------------------------------------------------------------------
@@ -1039,15 +1012,15 @@ AP4_RtpHintSampleEntry::ReadFields(AP4_ByteStream& stream)
{
// sample entry
AP4_Result result = AP4_SampleEntry::ReadFields(stream);
- if(result < 0) return result;
+ if (result < 0) return result;
// data
result = stream.ReadUI16(m_HintTrackVersion);
- if(AP4_FAILED(result)) return result;
+ if (AP4_FAILED(result)) return result;
result = stream.ReadUI16(m_HighestCompatibleVersion);
- if(AP4_FAILED(result)) return result;
+ if (AP4_FAILED(result)) return result;
result = stream.ReadUI32(m_MaxPacketSize);
- if(AP4_FAILED(result)) return result;
+ if (AP4_FAILED(result)) return result;
return AP4_SUCCESS;
}
@@ -1060,15 +1033,15 @@ AP4_RtpHintSampleEntry::WriteFields(AP4_ByteStream& stream)
{
// sample entry
AP4_Result result = AP4_SampleEntry::WriteFields(stream);
- if(AP4_FAILED(result)) return result;
-
+ if (AP4_FAILED(result)) return result;
+
// data
result = stream.WriteUI16(m_HintTrackVersion);
- if(AP4_FAILED(result)) return result;
+ if (AP4_FAILED(result)) return result;
result = stream.WriteUI16(m_HighestCompatibleVersion);
- if(AP4_FAILED(result)) return result;
+ if (AP4_FAILED(result)) return result;
result = stream.WriteUI32(m_MaxPacketSize);
- if(AP4_FAILED(result)) return result;
+ if (AP4_FAILED(result)) return result;
return result;
}
@@ -1081,12 +1054,12 @@ AP4_RtpHintSampleEntry::InspectFields(AP4_AtomInspector& inspector)
{
// sample entry
AP4_SampleEntry::InspectFields(inspector);
-
+
// fields
inspector.AddField("hint_track_version", m_HintTrackVersion);
inspector.AddField("highest_compatible_version", m_HighestCompatibleVersion);
inspector.AddField("max_packet_size", m_MaxPacketSize);
-
+
return AP4_SUCCESS;
}
@@ -1095,8 +1068,8 @@ AP4_RtpHintSampleEntry::InspectFields(AP4_AtomInspector& inspector)
| AP4_TextSampleEntry::AP4_TextSampleEntry
+---------------------------------------------------------------------*/
AP4_TextSampleEntry::AP4_TextSampleEntry(AP4_Size size,
- AP4_ByteStream& stream,
- AP4_AtomFactory& atom_factory):
+ AP4_ByteStream& stream,
+ AP4_AtomFactory& atom_factory):
AP4_SampleEntry(AP4_ATOM_TYPE_TEXT, size)
{
// read fields
@@ -1106,7 +1079,7 @@ AP4_TextSampleEntry::AP4_TextSampleEntry(AP4_Size size,
/*----------------------------------------------------------------------
| AP4_TextSampleEntry::~AP4_TextSampleEntry
+---------------------------------------------------------------------*/
-AP4_TextSampleEntry::~AP4_TextSampleEntry()
+AP4_TextSampleEntry::~AP4_TextSampleEntry()
{
}
@@ -1118,37 +1091,37 @@ AP4_TextSampleEntry::ReadFields(AP4_ByteStream& stream)
{
// sample entry
AP4_Result result = AP4_SampleEntry::ReadFields(stream);
- if(result < 0) return result;
+ if (result < 0) return result;
// data
result = stream.ReadUI32(m_Description.DisplayFlags);
- if(AP4_FAILED(result)) return result;
+ if (AP4_FAILED(result)) return result;
result = stream.ReadUI32(m_Description.TextJustification);
- if(AP4_FAILED(result)) return result;
+ if (AP4_FAILED(result)) return result;
result = stream.Read(&m_Description.BackgroundColor, 4);
- if(AP4_FAILED(result)) return result;
+ if (AP4_FAILED(result)) return result;
result = stream.ReadUI16(m_Description.TextBox.Top);
- if(AP4_FAILED(result)) return result;
+ if (AP4_FAILED(result)) return result;
result = stream.ReadUI16(m_Description.TextBox.Left);
- if(AP4_FAILED(result)) return result;
+ if (AP4_FAILED(result)) return result;
result = stream.ReadUI16(m_Description.TextBox.Bottom);
- if(AP4_FAILED(result)) return result;
+ if (AP4_FAILED(result)) return result;
result = stream.ReadUI16(m_Description.TextBox.Right);
- if(AP4_FAILED(result)) return result;
+ if (AP4_FAILED(result)) return result;
result = stream.ReadUI16(m_Description.Style.StartChar);
- if(AP4_FAILED(result)) return result;
+ if (AP4_FAILED(result)) return result;
result = stream.ReadUI16(m_Description.Style.EndChar);
- if(AP4_FAILED(result)) return result;
+ if (AP4_FAILED(result)) return result;
result = stream.ReadUI16(m_Description.Style.Ascent);
- if(AP4_FAILED(result)) return result;
+ if (AP4_FAILED(result)) return result;
result = stream.ReadUI16(m_Description.Style.Font.Id);
- if(AP4_FAILED(result)) return result;
+ if (AP4_FAILED(result)) return result;
result = stream.ReadUI08(m_Description.Style.Font.Face);
- if(AP4_FAILED(result)) return result;
+ if (AP4_FAILED(result)) return result;
result = stream.ReadUI08(m_Description.Style.Font.Size);
- if(AP4_FAILED(result)) return result;
+ if (AP4_FAILED(result)) return result;
result = stream.Read(&m_Description.Style.Font.Color, 4);
- if(AP4_FAILED(result)) return result;
+ if (AP4_FAILED(result)) return result;
// TODO: stream.ReadString(); -> m_Description.DefaultFontName
@@ -1163,8 +1136,8 @@ AP4_TextSampleEntry::WriteFields(AP4_ByteStream& stream)
{
// sample entry
AP4_Result result = AP4_SampleEntry::WriteFields(stream);
- if(AP4_FAILED(result)) return result;
-
+ if (AP4_FAILED(result)) return result;
+
// TODO: data
return result;
@@ -1178,9 +1151,9 @@ AP4_TextSampleEntry::InspectFields(AP4_AtomInspector& inspector)
{
// sample entry
AP4_SampleEntry::InspectFields(inspector);
-
+
// TODO: fields
-
+
return AP4_SUCCESS;
}
@@ -1188,8 +1161,8 @@ AP4_TextSampleEntry::InspectFields(AP4_AtomInspector& inspector)
| AP4_Tx3gSampleEntry::AP4_Tx3gSampleEntry
+---------------------------------------------------------------------*/
AP4_Tx3gSampleEntry::AP4_Tx3gSampleEntry(AP4_Size size,
- AP4_ByteStream& stream,
- AP4_AtomFactory& atom_factory):
+ AP4_ByteStream& stream,
+ AP4_AtomFactory& atom_factory):
AP4_SampleEntry(AP4_ATOM_TYPE_TX3G, size)
{
// read fields
@@ -1197,13 +1170,13 @@ AP4_Tx3gSampleEntry::AP4_Tx3gSampleEntry(AP4_Size size,
ReadFields(stream);
// read children atoms (fdat? blnk?)
- ReadChildren(atom_factory, stream, size - AP4_ATOM_HEADER_SIZE - fields_size);
+ ReadChildren(atom_factory, stream, size-AP4_ATOM_HEADER_SIZE-fields_size);
}
/*----------------------------------------------------------------------
| AP4_Tx3gSampleEntry::~AP4_Tx3gSampleEntry
+---------------------------------------------------------------------*/
-AP4_Tx3gSampleEntry::~AP4_Tx3gSampleEntry()
+AP4_Tx3gSampleEntry::~AP4_Tx3gSampleEntry()
{
}
@@ -1213,7 +1186,7 @@ AP4_Tx3gSampleEntry::~AP4_Tx3gSampleEntry()
AP4_Size
AP4_Tx3gSampleEntry::GetFieldsSize()
{
- return AP4_SampleEntry::GetFieldsSize() + 4 + 1 + 1 + 4 + 2 + 2 + 2 + 2 + 2 + 2 + 2 + 1 + 1 + 4;
+ return AP4_SampleEntry::GetFieldsSize()+4+1+1+4+2+2+2+2+2+2+2+1+1+4;
}
/*----------------------------------------------------------------------
@@ -1224,37 +1197,37 @@ AP4_Tx3gSampleEntry::ReadFields(AP4_ByteStream& stream)
{
// sample entry
AP4_Result result = AP4_SampleEntry::ReadFields(stream);
- if(result < 0) return result;
+ if (result < 0) return result;
// data
result = stream.ReadUI32(m_Description.DisplayFlags);
- if(AP4_FAILED(result)) return result;
+ if (AP4_FAILED(result)) return result;
result = stream.ReadUI08(m_Description.HorizontalJustification);
- if(AP4_FAILED(result)) return result;
+ if (AP4_FAILED(result)) return result;
result = stream.ReadUI08(m_Description.VerticalJustification);
- if(AP4_FAILED(result)) return result;
+ if (AP4_FAILED(result)) return result;
result = stream.Read(&m_Description.BackgroundColor, 4);
- if(AP4_FAILED(result)) return result;
+ if (AP4_FAILED(result)) return result;
result = stream.ReadUI16(m_Description.TextBox.Top);
- if(AP4_FAILED(result)) return result;
+ if (AP4_FAILED(result)) return result;
result = stream.ReadUI16(m_Description.TextBox.Left);
- if(AP4_FAILED(result)) return result;
+ if (AP4_FAILED(result)) return result;
result = stream.ReadUI16(m_Description.TextBox.Bottom);
- if(AP4_FAILED(result)) return result;
+ if (AP4_FAILED(result)) return result;
result = stream.ReadUI16(m_Description.TextBox.Right);
- if(AP4_FAILED(result)) return result;
+ if (AP4_FAILED(result)) return result;
result = stream.ReadUI16(m_Description.Style.StartChar);
- if(AP4_FAILED(result)) return result;
+ if (AP4_FAILED(result)) return result;
result = stream.ReadUI16(m_Description.Style.EndChar);
- if(AP4_FAILED(result)) return result;
+ if (AP4_FAILED(result)) return result;
result = stream.ReadUI16(m_Description.Style.Font.Id);
- if(AP4_FAILED(result)) return result;
+ if (AP4_FAILED(result)) return result;
result = stream.ReadUI08(m_Description.Style.Font.Face);
- if(AP4_FAILED(result)) return result;
+ if (AP4_FAILED(result)) return result;
result = stream.ReadUI08(m_Description.Style.Font.Size);
- if(AP4_FAILED(result)) return result;
+ if (AP4_FAILED(result)) return result;
result = stream.Read(&m_Description.Style.Font.Color, 4);
- if(AP4_FAILED(result)) return result;
+ if (AP4_FAILED(result)) return result;
return AP4_SUCCESS;
}
@@ -1267,8 +1240,8 @@ AP4_Tx3gSampleEntry::WriteFields(AP4_ByteStream& stream)
{
// sample entry
AP4_Result result = AP4_SampleEntry::WriteFields(stream);
- if(AP4_FAILED(result)) return result;
-
+ if (AP4_FAILED(result)) return result;
+
// TODO: data
return result;
@@ -1282,9 +1255,9 @@ AP4_Tx3gSampleEntry::InspectFields(AP4_AtomInspector& inspector)
{
// sample entry
AP4_SampleEntry::InspectFields(inspector);
-
+
// TODO: fields
-
+
return AP4_SUCCESS;
}
@@ -1292,24 +1265,24 @@ AP4_Tx3gSampleEntry::InspectFields(AP4_AtomInspector& inspector)
| AP4_Tx3gSampleEntry::GetFontNameById
+---------------------------------------------------------------------*/
-AP4_Result
+AP4_Result
AP4_Tx3gSampleEntry::GetFontNameById(AP4_Ordinal Id, AP4_String& Name)
{
- if(AP4_FtabAtom* ftab = dynamic_cast<AP4_FtabAtom*>(GetChild(AP4_ATOM_TYPE_FTAB)))
- {
- AP4_Array<AP4_FtabAtom::AP4_Tx3gFontRecord> FontRecords = ftab->GetFontRecords();
-
- for(int i = 0, j = FontRecords.ItemCount(); i < j; i++)
- {
- if(Id == FontRecords[i].Id)
- {
- Name = FontRecords[i].Name;
- return AP4_SUCCESS;
- }
- }
- }
+ if(AP4_FtabAtom* ftab = dynamic_cast<AP4_FtabAtom*>(GetChild(AP4_ATOM_TYPE_FTAB)))
+ {
+ AP4_Array<AP4_FtabAtom::AP4_Tx3gFontRecord> FontRecords = ftab->GetFontRecords();
- return AP4_FAILURE;
+ for(int i = 0, j = FontRecords.ItemCount(); i < j; i++)
+ {
+ if(Id == FontRecords[i].Id)
+ {
+ Name = FontRecords[i].Name;
+ return AP4_SUCCESS;
+ }
+ }
+ }
+
+ return AP4_FAILURE;
}
@@ -1319,18 +1292,18 @@ AP4_Tx3gSampleEntry::GetFontNameById(AP4_Ordinal Id, AP4_String& Name)
| AP4_AC3SampleEntry::AP4_AC3SampleEntry
+---------------------------------------------------------------------*/
AP4_AC3SampleEntry::AP4_AC3SampleEntry(AP4_Atom::Type format,
- AP4_UI32 sample_rate,
- AP4_UI16 sample_size,
- AP4_UI16 channel_count) :
+ AP4_UI32 sample_rate,
+ AP4_UI16 sample_size,
+ AP4_UI16 channel_count) :
AP4_AudioSampleEntry(format, sample_rate, sample_size, channel_count)
{
}
AP4_AC3SampleEntry::AP4_AC3SampleEntry(AP4_Atom::Type format,
- AP4_Size size,
- AP4_ByteStream& stream,
- AP4_AtomFactory& atom_factory) :
- AP4_AudioSampleEntry(format, size, stream, atom_factory)
+ AP4_Size size,
+ AP4_ByteStream& stream,
+ AP4_AtomFactory& atom_factory) :
+ AP4_AudioSampleEntry(format, size, stream, atom_factory)
{
}
@@ -1342,70 +1315,68 @@ AP4_Result
AP4_AC3SampleEntry::ReadFields(AP4_ByteStream& stream)
{
- AP4_AudioSampleEntry::ReadFields(stream);
-
- // SampleSize field from AudioSampleEntry shall be ignored
- m_SampleSize = 0;
-
- // AC3SpecificBox
-
- // BoxHeader.Size, BoxHeader.Type
- char junk[8];
- stream.Read(junk, 8);
-
- AP4_UI32 data;
- stream.ReadUI24(data);
-
- // fscod
- switch((data >> 22) & 0x3)
- {
- case 0:
- m_SampleRate = 48000;
- break;
- case 1:
- m_SampleRate = 44100;
- break;
- case 2:
- m_SampleRate = 32000;
- break;
- }
-
- m_SampleRate <<= 16;
-
- // acmod
- switch((data >> 11) & 0x7)
- {
- case 1:
- m_ChannelCount = 1;
- break;
- case 0:
- case 2:
- m_ChannelCount = 2;
- break;
- case 3:
- case 4:
- m_ChannelCount = 3;
- break;
- case 5:
- case 6:
- m_ChannelCount = 4;
- break;
- case 7:
- m_ChannelCount = 5;
- break;
- }
-
- // lfeon
- if(((data >> 10) & 0x1) == 1)
- m_ChannelCount++;
-
- return AP4_SUCCESS;
+ AP4_AudioSampleEntry::ReadFields(stream);
+
+ // SampleSize field from AudioSampleEntry shall be ignored
+ m_SampleSize = 0;
+
+ // AC3SpecificBox
+
+ // BoxHeader.Size, BoxHeader.Type
+ char junk[8];
+ stream.Read(junk, 8);
+
+ AP4_UI32 data;
+ stream.ReadUI24(data);
+
+ // fscod
+ switch ((data>>22) & 0x3) {
+ case 0:
+ m_SampleRate = 48000;
+ break;
+ case 1:
+ m_SampleRate = 44100;
+ break;
+ case 2:
+ m_SampleRate = 32000;
+ break;
+ }
+
+ m_SampleRate <<= 16;
+
+ // acmod
+ switch ((data>>11) & 0x7) {
+ case 1:
+ m_ChannelCount = 1;
+ break;
+ case 0:
+ case 2:
+ m_ChannelCount = 2;
+ break;
+ case 3:
+ case 4:
+ m_ChannelCount = 3;
+ break;
+ case 5:
+ case 6:
+ m_ChannelCount = 4;
+ break;
+ case 7:
+ m_ChannelCount = 5;
+ break;
+ }
+
+ // lfeon
+ if (((data>>10) & 0x1) == 1)
+ m_ChannelCount++;
+
+ return AP4_SUCCESS;
}
AP4_Size
AP4_AC3SampleEntry::GetFieldsSize()
{
- return AP4_AudioSampleEntry::GetFieldsSize() + 11;
+ return AP4_AudioSampleEntry::GetFieldsSize() + 11;
}
// <== End patch MPC \ No newline at end of file
diff --git a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4SampleEntry.h b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4SampleEntry.h
index 90d40cb22..f11a3506c 100644
--- a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4SampleEntry.h
+++ b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4SampleEntry.h
@@ -50,21 +50,18 @@ class AP4_AvccAtom;
+---------------------------------------------------------------------*/
class AP4_SampleEntry : public AP4_ContainerAtom
{
-public:
+ public:
AP4_IMPLEMENT_DYNAMIC_CAST_D(AP4_SampleEntry, AP4_ContainerAtom)
// methods
AP4_SampleEntry(AP4_Atom::Type format, AP4_UI16 data_ref_index = 1);
- AP4_SampleEntry(AP4_Atom::Type format,
+ AP4_SampleEntry(AP4_Atom::Type format,
AP4_Size size,
AP4_ByteStream& stream,
AP4_AtomFactory& atom_factory);
virtual ~AP4_SampleEntry() {}
-
- AP4_UI16 GetDataReferenceIndex()
- {
- return m_DataReferenceIndex;
- }
+
+ AP4_UI16 GetDataReferenceIndex() { return m_DataReferenceIndex; }
virtual AP4_Result Write(AP4_ByteStream& stream);
virtual AP4_Result Inspect(AP4_AtomInspector& inspector);
virtual AP4_SampleDescription* ToSampleDescription();
@@ -72,7 +69,7 @@ public:
// AP4_AtomParent methods
virtual void OnChildChanged(AP4_Atom* child);
-protected:
+ protected:
// constructor
AP4_SampleEntry(AP4_Atom::Type format, AP4_Size size);
@@ -93,20 +90,17 @@ protected:
+---------------------------------------------------------------------*/
class AP4_UnknownSampleEntry : public AP4_SampleEntry
{
-public:
+ public:
// this constructor takes ownership of the atom passed to it
AP4_UnknownSampleEntry(AP4_Atom::Type type, AP4_Size size, AP4_ByteStream& stream);
-
+
// AP4_SampleEntry methods
virtual AP4_SampleDescription* ToSampleDescription();
// accessors
- const AP4_DataBuffer& GetPayload()
- {
- return m_Payload;
- }
-
-protected:
+ const AP4_DataBuffer& GetPayload() { return m_Payload; }
+
+ protected:
// methods
virtual AP4_Size GetFieldsSize();
virtual AP4_Result ReadFields(AP4_ByteStream& stream);
@@ -134,21 +128,12 @@ public:
// accessors
AP4_UI32 GetSampleRate();
- AP4_UI16 GetSampleSize()
- {
- return m_SampleSize;
- }
+ AP4_UI16 GetSampleSize() { return m_SampleSize; }
AP4_UI16 GetChannelCount();
- // ==> Start patch MPC
- AP4_UI32 GetBytesPerFrame()
- {
- return m_QtV1BytesPerFrame;
- };
- AP4_UI32 GetSamplesPerPacket()
- {
- return m_QtV1SamplesPerPacket;
- }
- // <== End patch MPC
+ // ==> Start patch MPC
+ AP4_UI32 GetBytesPerFrame() { return m_QtV1BytesPerFrame; };
+ AP4_UI32 GetSamplesPerPacket(){ return m_QtV1SamplesPerPacket; }
+ // <== End patch MPC
// methods
AP4_SampleDescription* ToSampleDescription();
@@ -164,17 +149,17 @@ protected:
AP4_UI16 m_QtVersion; // 0, 1 or 2
AP4_UI16 m_QtRevision; // 0
AP4_UI32 m_QtVendor; // 0
- AP4_UI16 m_ChannelCount;
- AP4_UI16 m_SampleSize;
+ AP4_UI16 m_ChannelCount;
+ AP4_UI16 m_SampleSize;
AP4_UI16 m_QtCompressionId; // 0 or -2
AP4_UI16 m_QtPacketSize; // always 0
- AP4_UI32 m_SampleRate; // 16.16 fixed point
-
+ AP4_UI32 m_SampleRate; // 16.16 fixed point
+
AP4_UI32 m_QtV1SamplesPerPacket;
AP4_UI32 m_QtV1BytesPerPacket;
AP4_UI32 m_QtV1BytesPerFrame;
AP4_UI32 m_QtV1BytesPerSample;
-
+
AP4_UI32 m_QtV2StructSize;
double m_QtV2SampleRate64;
AP4_UI32 m_QtV2ChannelCount;
@@ -193,7 +178,7 @@ class AP4_VisualSampleEntry : public AP4_SampleEntry
{
public:
// methods
- AP4_VisualSampleEntry(AP4_Atom::Type format,
+ AP4_VisualSampleEntry(AP4_Atom::Type format,
AP4_UI16 width,
AP4_UI16 height,
AP4_UI16 depth,
@@ -204,30 +189,12 @@ public:
AP4_AtomFactory& atom_factory);
// accessors
- AP4_UI16 GetWidth()
- {
- return m_Width;
- }
- AP4_UI16 GetHeight()
- {
- return m_Height;
- }
- AP4_UI16 GetHorizResolution()
- {
- return m_HorizResolution;
- }
- AP4_UI16 GetVertResolution()
- {
- return m_VertResolution;
- }
- AP4_UI16 GetDepth()
- {
- return m_Depth;
- }
- const char* GetCompressorName()
- {
- return m_CompressorName.GetChars();
- }
+ AP4_UI16 GetWidth() { return m_Width; }
+ AP4_UI16 GetHeight() { return m_Height; }
+ AP4_UI16 GetHorizResolution(){ return m_HorizResolution; }
+ AP4_UI16 GetVertResolution() { return m_VertResolution; }
+ AP4_UI16 GetDepth() { return m_Depth; }
+ const char* GetCompressorName() { return m_CompressorName.GetChars(); }
// methods
AP4_SampleDescription* ToSampleDescription();
@@ -249,7 +216,7 @@ protected:
AP4_UI32 m_VertResolution; // = 0x00480000 (72 dpi)
AP4_UI32 m_Reserved3; // = 0
AP4_UI16 m_FrameCount; // = 1
- AP4_String m_CompressorName;
+ AP4_String m_CompressorName;
AP4_UI16 m_Depth; // = 0x0018
AP4_UI16 m_Predefined3; // = 0xFFFF
};
@@ -280,7 +247,7 @@ class AP4_MpegAudioSampleEntry : public AP4_AudioSampleEntry
public:
// constructors
AP4_MpegAudioSampleEntry(AP4_UI32 type,
- AP4_UI32 sample_rate,
+ AP4_UI32 sample_rate,
AP4_UI16 sample_size,
AP4_UI16 channel_count,
AP4_EsDescriptor* descriptor);
@@ -320,7 +287,7 @@ public:
+---------------------------------------------------------------------*/
class AP4_Mp4sSampleEntry : public AP4_MpegSystemSampleEntry
{
-public:
+ public:
// constructors
AP4_Mp4sSampleEntry(AP4_Size size,
AP4_ByteStream& stream,
@@ -336,12 +303,12 @@ public:
+---------------------------------------------------------------------*/
class AP4_Mp4aSampleEntry : public AP4_MpegAudioSampleEntry
{
-public:
+ public:
// constructors
AP4_Mp4aSampleEntry(AP4_Size size,
AP4_ByteStream& stream,
AP4_AtomFactory& atom_factory);
- AP4_Mp4aSampleEntry(AP4_UI32 sample_rate,
+ AP4_Mp4aSampleEntry(AP4_UI32 sample_rate,
AP4_UI16 sample_size,
AP4_UI16 channel_count,
AP4_EsDescriptor* descriptor);
@@ -352,7 +319,7 @@ public:
+---------------------------------------------------------------------*/
class AP4_Mp4vSampleEntry : public AP4_MpegVideoSampleEntry
{
-public:
+ public:
// constructors
AP4_Mp4vSampleEntry(AP4_Size size,
AP4_ByteStream& stream,
@@ -361,7 +328,7 @@ public:
AP4_UI16 height,
AP4_UI16 depth,
const char* compressor_name,
- AP4_EsDescriptor* descriptor);
+ AP4_EsDescriptor* descriptor);
};
/*----------------------------------------------------------------------
@@ -379,7 +346,7 @@ public:
AP4_UI16 depth,
const char* compressor_name,
const AP4_AvccAtom& avcc);
-
+
// inherited from AP4_SampleEntry
virtual AP4_SampleDescription* ToSampleDescription();
};
@@ -398,7 +365,7 @@ public:
AP4_RtpHintSampleEntry(AP4_Size size,
AP4_ByteStream& stream,
AP4_AtomFactory& atom_factory);
-
+
protected:
// methods
virtual AP4_Size GetFieldsSize();
@@ -421,36 +388,21 @@ class AP4_TextSampleEntry : public AP4_SampleEntry
public:
// methods
AP4_TextSampleEntry(AP4_Size size,
- AP4_ByteStream& stream,
- AP4_AtomFactory& atom_factory);
+ AP4_ByteStream& stream,
+ AP4_AtomFactory& atom_factory);
virtual ~AP4_TextSampleEntry();
-
- struct AP4_TextDescription
- {
- AP4_UI32 DisplayFlags;
- AP4_UI32 TextJustification;
- AP4_UI32 BackgroundColor;
- struct
- {
- AP4_UI16 Top, Left, Bottom, Right;
- } TextBox;
- struct
- {
- AP4_UI16 StartChar, EndChar, Ascent;
- struct
- {
- AP4_UI16 Id;
- AP4_UI08 Face, Size;
- AP4_UI32 Color;
- } Font;
- } Style;
- AP4_String DefaultFontName;
- };
-
- const AP4_TextDescription& GetDescription() const
- {
- return m_Description;
- };
+
+ struct AP4_TextDescription
+ {
+ AP4_UI32 DisplayFlags;
+ AP4_UI32 TextJustification;
+ AP4_UI32 BackgroundColor;
+ struct {AP4_UI16 Top, Left, Bottom, Right;} TextBox;
+ struct {AP4_UI16 StartChar, EndChar, Ascent; struct {AP4_UI16 Id; AP4_UI08 Face, Size; AP4_UI32 Color;} Font;} Style;
+ AP4_String DefaultFontName;
+ };
+
+ const AP4_TextDescription& GetDescription() const { return m_Description; };
protected:
// methods
@@ -459,7 +411,7 @@ protected:
virtual AP4_Result InspectFields(AP4_AtomInspector& inspector);
// members
- AP4_TextDescription m_Description;
+ AP4_TextDescription m_Description;
};
/*----------------------------------------------------------------------
@@ -470,38 +422,23 @@ class AP4_Tx3gSampleEntry : public AP4_SampleEntry
public:
// methods
AP4_Tx3gSampleEntry(AP4_Size size,
- AP4_ByteStream& stream,
- AP4_AtomFactory& atom_factory);
+ AP4_ByteStream& stream,
+ AP4_AtomFactory& atom_factory);
virtual ~AP4_Tx3gSampleEntry();
+
+ struct AP4_Tx3gDescription
+ {
+ AP4_UI32 DisplayFlags;
+ AP4_UI08 HorizontalJustification;
+ AP4_UI08 VerticalJustification;
+ AP4_UI32 BackgroundColor;
+ struct {AP4_UI16 Top, Left, Bottom, Right;} TextBox;
+ struct {AP4_UI16 StartChar, EndChar; struct {AP4_UI16 Id; AP4_UI08 Face, Size; AP4_UI32 Color;} Font;} Style;
+ };
- struct AP4_Tx3gDescription
- {
- AP4_UI32 DisplayFlags;
- AP4_UI08 HorizontalJustification;
- AP4_UI08 VerticalJustification;
- AP4_UI32 BackgroundColor;
- struct
- {
- AP4_UI16 Top, Left, Bottom, Right;
- } TextBox;
- struct
- {
- AP4_UI16 StartChar, EndChar;
- struct
- {
- AP4_UI16 Id;
- AP4_UI08 Face, Size;
- AP4_UI32 Color;
- } Font;
- } Style;
- };
-
- const AP4_Tx3gDescription& GetDescription() const
- {
- return m_Description;
- };
-
- AP4_Result GetFontNameById(AP4_Ordinal Id, AP4_String& Name);
+ const AP4_Tx3gDescription& GetDescription() const { return m_Description; };
+
+ AP4_Result GetFontNameById(AP4_Ordinal Id, AP4_String& Name);
protected:
// methods
@@ -511,7 +448,7 @@ protected:
virtual AP4_Result InspectFields(AP4_AtomInspector& inspector);
// members
- AP4_Tx3gDescription m_Description;
+ AP4_Tx3gDescription m_Description;
};
@@ -521,20 +458,20 @@ protected:
+---------------------------------------------------------------------*/
class AP4_AC3SampleEntry : public AP4_AudioSampleEntry
{
-public:
+ public:
// constructors
AP4_AC3SampleEntry(AP4_Atom::Type format,
- AP4_UI32 sample_rate,
+ AP4_UI32 sample_rate,
AP4_UI16 sample_size,
AP4_UI16 channel_count);
AP4_AC3SampleEntry(AP4_Atom::Type format,
- AP4_Size size,
+ AP4_Size size,
AP4_ByteStream& stream,
AP4_AtomFactory& atom_factory);
protected:
- virtual AP4_Size GetFieldsSize();
+ virtual AP4_Size GetFieldsSize();
virtual AP4_Result ReadFields(AP4_ByteStream& stream);
};
// <== End patch MPC
diff --git a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4SampleSource.cpp b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4SampleSource.cpp
index d0dfb7e29..a641c6a2d 100644
--- a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4SampleSource.cpp
+++ b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4SampleSource.cpp
@@ -42,7 +42,7 @@ AP4_TrackSampleSource::AP4_TrackSampleSource(AP4_Track* track) :
m_SampleIndex(0)
{
}
-
+
/*----------------------------------------------------------------------
| AP4_TrackSampleSource
+---------------------------------------------------------------------*/
@@ -55,7 +55,7 @@ AP4_TrackSampleSource::GetTimeScale()
/*----------------------------------------------------------------------
| AP4_TrackSampleSource::GetDurationMs
+---------------------------------------------------------------------*/
-AP4_UI32
+AP4_UI32
AP4_TrackSampleSource::GetDurationMs()
{
return m_Track->GetDurationMs();
@@ -64,7 +64,7 @@ AP4_TrackSampleSource::GetDurationMs()
/*----------------------------------------------------------------------
| AP4_TrackSampleSource::GetTrackId
+---------------------------------------------------------------------*/
-AP4_UI32
+AP4_UI32
AP4_TrackSampleSource::GetTrackId()
{
return m_Track->GetId();
@@ -73,18 +73,18 @@ AP4_TrackSampleSource::GetTrackId()
/*----------------------------------------------------------------------
| AP4_TrackSampleSource::ReadNextSample
+---------------------------------------------------------------------*/
-AP4_Result
+AP4_Result
AP4_TrackSampleSource::ReadNextSample(AP4_Sample& sample, AP4_DataBuffer& buffer)
{
AP4_Result result = m_Track->ReadSample(m_SampleIndex, sample, buffer);
- if(AP4_SUCCEEDED(result)) ++m_SampleIndex;
+ if (AP4_SUCCEEDED(result)) ++m_SampleIndex;
return result;
}
/*----------------------------------------------------------------------
| AP4_TrackSampleSource::GetNearestSyncSampleIndex
+---------------------------------------------------------------------*/
-AP4_Ordinal
+AP4_Ordinal
AP4_TrackSampleSource::GetNearestSyncSampleIndex(AP4_Ordinal indx, bool before)
{
return m_Track->GetNearestSyncSampleIndex(indx, before);
@@ -93,7 +93,7 @@ AP4_TrackSampleSource::GetNearestSyncSampleIndex(AP4_Ordinal indx, bool before)
/*----------------------------------------------------------------------
| AP4_TrackSampleSource::GetSampleIndexForTimeStampMs
+---------------------------------------------------------------------*/
-AP4_Result
+AP4_Result
AP4_TrackSampleSource::GetSampleIndexForTimeStampMs(AP4_UI32 timestamp, AP4_Ordinal& indx)
{
return m_Track->GetSampleIndexForTimeStampMs(timestamp, indx);
@@ -102,21 +102,21 @@ AP4_TrackSampleSource::GetSampleIndexForTimeStampMs(AP4_UI32 timestamp, AP4_Ordi
/*----------------------------------------------------------------------
| AP4_TrackSampleSource::SetSampleIndex
+---------------------------------------------------------------------*/
-AP4_Result
+AP4_Result
AP4_TrackSampleSource::SetSampleIndex(AP4_Ordinal indx)
{
- if(indx >= m_Track->GetSampleCount()) return AP4_ERROR_OUT_OF_RANGE;
+ if (indx >= m_Track->GetSampleCount()) return AP4_ERROR_OUT_OF_RANGE;
m_SampleIndex = indx;
-
+
return AP4_SUCCESS;
}
/*----------------------------------------------------------------------
| AP4_TrackSampleSource::GetSampleDescription
+---------------------------------------------------------------------*/
-AP4_SampleDescription*
+AP4_SampleDescription*
AP4_TrackSampleSource::GetSampleDescription(AP4_Ordinal indx)
{
return m_Track->GetSampleDescription(indx);
}
-
+
diff --git a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4SampleSource.h b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4SampleSource.h
index 9cdc0178b..3f2cd94d2 100644
--- a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4SampleSource.h
+++ b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4SampleSource.h
@@ -49,12 +49,12 @@ class AP4_SampleSource
{
public:
virtual ~AP4_SampleSource() {}
-
+
/**
* Return the timscale of the sample's media
*/
virtual AP4_UI32 GetTimeScale() = 0;
-
+
/**
* Return the duration in milliseconds
*/
@@ -65,27 +65,27 @@ public:
* no track ID associated with it.
*/
virtual AP4_UI32 GetTrackId() = 0;
-
+
/**
* Read the next sample from the source
*/
virtual AP4_Result ReadNextSample(AP4_Sample& sample, AP4_DataBuffer& buffer) = 0;
-
+
/**
* Return the index of the nearest sync sample from a given sample index.
*/
- virtual AP4_Ordinal GetNearestSyncSampleIndex(AP4_Ordinal indx, bool before = true) = 0;
-
+ virtual AP4_Ordinal GetNearestSyncSampleIndex(AP4_Ordinal indx, bool before=true) = 0;
+
/**
* Return the sample index given a timestamp in milliseconds
*/
virtual AP4_Result GetSampleIndexForTimeStampMs(AP4_UI32 timestamp, AP4_Ordinal& indx) = 0;
-
+
/**
* Seek to a specific sample index.
*/
virtual AP4_Result SetSampleIndex(AP4_Ordinal indx) = 0;
-
+
/**
* Return a sample description by index.
* Returns NULL if there is no sample description with the requested index.
@@ -99,17 +99,17 @@ public:
class AP4_TrackSampleSource : public AP4_SampleSource
{
public:
- AP4_TrackSampleSource(AP4_Track* track);
-
+ AP4_TrackSampleSource(AP4_Track* track);
+
virtual AP4_UI32 GetTimeScale();
virtual AP4_UI32 GetDurationMs();
virtual AP4_UI32 GetTrackId();
virtual AP4_Result ReadNextSample(AP4_Sample& sample, AP4_DataBuffer& buffer);
- virtual AP4_Ordinal GetNearestSyncSampleIndex(AP4_Ordinal indx, bool before = true);
+ virtual AP4_Ordinal GetNearestSyncSampleIndex(AP4_Ordinal indx, bool before=true);
virtual AP4_Result GetSampleIndexForTimeStampMs(AP4_UI32 timestamp, AP4_Ordinal& indx);
virtual AP4_Result SetSampleIndex(AP4_Ordinal indx);
virtual AP4_SampleDescription* GetSampleDescription(AP4_Ordinal indx);
-
+
private:
AP4_Track* m_Track;
AP4_Ordinal m_SampleIndex;
diff --git a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4SampleTable.cpp b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4SampleTable.cpp
index 743ca6f84..3f892d2a9 100644
--- a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4SampleTable.cpp
+++ b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4SampleTable.cpp
@@ -44,7 +44,7 @@
/*----------------------------------------------------------------------
| AP4_SampleTable::GenerateStblAtom
+---------------------------------------------------------------------*/
-AP4_Result
+AP4_Result
AP4_SampleTable::GenerateStblAtom(AP4_ContainerAtom*& stbl)
{
// create the stbl container
@@ -64,10 +64,10 @@ AP4_SampleTable::GenerateStblAtom(AP4_ContainerAtom*& stbl)
// create the stss atom
AP4_StssAtom* stss = new AP4_StssAtom();
-
+
// declare the ctts atom (may be created later)
AP4_CttsAtom* ctts = NULL;
-
+
// start chunk table
AP4_Ordinal current_chunk_index = 0;
AP4_Size current_chunk_size = 0;
@@ -83,69 +83,61 @@ AP4_SampleTable::GenerateStblAtom(AP4_ContainerAtom*& stbl)
// process all the samples
bool all_samples_are_sync = false;
AP4_Cardinal sample_count = GetSampleCount();
- for(AP4_Ordinal i = 0; i < sample_count; i++)
- {
+ for (AP4_Ordinal i=0; i<sample_count; i++) {
AP4_Sample sample;
GetSample(i, sample);
-
+
// update DTS table
AP4_UI32 new_duration = sample.GetDuration();
- if(new_duration != current_duration && current_duration_run != 0)
- {
+ if (new_duration != current_duration && current_duration_run != 0) {
// emit a new stts entry
stts->AddEntry(current_duration_run, current_duration);
-
+
// reset the run count
current_duration_run = 0;
- }
+ }
++current_duration_run;
current_duration = new_duration;
-
+
// update CTS table
AP4_UI32 new_cts_delta = sample.GetCtsDelta();
- if(new_cts_delta != current_cts_delta && current_cts_delta_run != 0)
- {
+ if (new_cts_delta != current_cts_delta && current_cts_delta_run != 0) {
// create a ctts atom if we don't have one
- if(ctts == NULL) ctts = new AP4_CttsAtom();
-
+ if (ctts == NULL) ctts = new AP4_CttsAtom();
+
//emit a new ctts entry
ctts->AddEntry(current_cts_delta_run, current_cts_delta);
-
+
// reset the run count
current_cts_delta_run = 0;
}
++current_cts_delta_run;
current_cts_delta = new_cts_delta;
-
+
// add an entry into the stsz atom
stsz->AddEntry(sample.GetSize());
-
+
// update the sync sample table
- if(sample.IsSync())
- {
- stss->AddEntry(i + 1);
- if(i == 0) all_samples_are_sync = true;
- }
- else
- {
+ if (sample.IsSync()) {
+ stss->AddEntry(i+1);
+ if (i==0) all_samples_are_sync = true;
+ } else {
all_samples_are_sync = false;
}
-
+
// see in which chunk this sample is
AP4_Ordinal chunk_index = 0;
AP4_Ordinal position_in_chunk = 0;
AP4_Result result = GetSampleChunkPosition(i, chunk_index, position_in_chunk);
- if(AP4_SUCCEEDED(result))
- {
- if(chunk_index != current_chunk_index && current_samples_in_chunk != 0)
- {
+ if (AP4_SUCCEEDED(result)) {
+ if (chunk_index != current_chunk_index && current_samples_in_chunk != 0) {
// new chunk
chunk_offsets.Append(current_chunk_offset);
current_chunk_offset += current_chunk_size;
- stsc->AddEntry(1,
+ stsc->AddEntry(1,
current_samples_in_chunk,
- current_sample_description_index + 1);
+ current_sample_description_index+1);
current_samples_in_chunk = 0;
current_chunk_size = 0;
@@ -155,32 +147,30 @@ AP4_SampleTable::GenerateStblAtom(AP4_ContainerAtom*& stbl)
// store the sample description index
current_sample_description_index = sample.GetDescriptionIndex();
-
+
// adjust the current chunk info
current_chunk_size += sample.GetSize();
- ++current_samples_in_chunk;
+ ++current_samples_in_chunk;
}
// finish the stts table
stts->AddEntry(current_duration_run, current_duration);
// finish the ctts table if we have one
- if(ctts)
- {
+ if (ctts) {
AP4_ASSERT(current_cts_delta_run != 0);
-
+
// add a ctts entry
ctts->AddEntry(current_cts_delta_run, current_cts_delta);
- }
-
+ }
+
// process any unfinished chunk
- if(current_samples_in_chunk != 0)
- {
+ if (current_samples_in_chunk != 0) {
// new chunk
chunk_offsets.Append(current_chunk_offset);
- stsc->AddEntry(1,
+ stsc->AddEntry(1,
current_samples_in_chunk,
- current_sample_description_index + 1);
+ current_sample_description_index+1);
}
// attach the children of stbl
@@ -188,24 +178,19 @@ AP4_SampleTable::GenerateStblAtom(AP4_ContainerAtom*& stbl)
stbl->AddChild(stsz);
stbl->AddChild(stsc);
stbl->AddChild(stts);
- if(ctts) stbl->AddChild(ctts);
- if(!all_samples_are_sync && stss->GetEntries().ItemCount() != 0)
- {
+ if (ctts) stbl->AddChild(ctts);
+ if (!all_samples_are_sync && stss->GetEntries().ItemCount() != 0) {
stbl->AddChild(stss);
- }
- else
- {
+ } else {
delete stss;
}
-
+
// see if we need a co64 or an stco atom
AP4_Size chunk_count = chunk_offsets.ItemCount();
- if(current_chunk_offset <= 0xFFFFFFFF)
- {
+ if (current_chunk_offset <= 0xFFFFFFFF) {
// make an array of 32-bit entries
AP4_UI32* chunk_offsets_32 = new AP4_UI32[chunk_count];
- for(unsigned int i = 0; i < chunk_count; i++)
- {
+ for (unsigned int i=0; i<chunk_count; i++) {
chunk_offsets_32[i] = (AP4_UI32)chunk_offsets[i];
}
// create the stco atom
@@ -213,9 +198,7 @@ AP4_SampleTable::GenerateStblAtom(AP4_ContainerAtom*& stbl)
stbl->AddChild(stco);
delete[] chunk_offsets_32;
- }
- else
- {
+ } else {
// create the co64 atom
AP4_Co64Atom* co64 = new AP4_Co64Atom(&chunk_offsets[0], chunk_count);
stbl->AddChild(co64);
diff --git a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4SampleTable.h b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4SampleTable.h
index 67c3b843a..45a6c7bb0 100644
--- a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4SampleTable.h
+++ b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4SampleTable.h
@@ -44,8 +44,7 @@ class AP4_SampleDescription;
/*----------------------------------------------------------------------
| AP4_SampleTable
+---------------------------------------------------------------------*/
-class AP4_SampleTable
-{
+class AP4_SampleTable {
public:
// constructors and destructor
virtual ~AP4_SampleTable() {};
@@ -54,14 +53,14 @@ public:
virtual AP4_Result GenerateStblAtom(AP4_ContainerAtom*& stbl);
virtual AP4_Result GetSample(AP4_Ordinal sample_index, AP4_Sample& sample) = 0;
virtual AP4_Cardinal GetSampleCount() = 0;
- virtual AP4_Result GetSampleChunkPosition(AP4_Ordinal sample_index,
- AP4_Ordinal& chunk_index,
- AP4_Ordinal& position_in_chunk) = 0;
+ virtual AP4_Result GetSampleChunkPosition(AP4_Ordinal sample_index,
+ AP4_Ordinal& chunk_index,
+ AP4_Ordinal& position_in_chunk) = 0;
virtual AP4_Cardinal GetSampleDescriptionCount() = 0;
virtual AP4_SampleDescription* GetSampleDescription(AP4_Ordinal index) = 0;
virtual AP4_Result GetSampleIndexForTimeStamp(AP4_UI64 ts,
- AP4_Ordinal& index) = 0;
- virtual AP4_Ordinal GetNearestSyncSampleIndex(AP4_Ordinal index, bool before = true) = 0;
+ AP4_Ordinal& index) = 0;
+ virtual AP4_Ordinal GetNearestSyncSampleIndex(AP4_Ordinal index, bool before=true) = 0;
};
#endif // _AP4_SAMPLE_TABLE_H_
diff --git a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4SchmAtom.cpp b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4SchmAtom.cpp
index 5916a14a9..767e59368 100644
--- a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4SchmAtom.cpp
+++ b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4SchmAtom.cpp
@@ -1,6 +1,6 @@
/*****************************************************************
|
-| AP4 - schm Atoms
+| AP4 - schm Atoms
|
| Copyright 2002-2008 Axiomatic Systems, LLC
|
@@ -42,29 +42,27 @@ AP4_DEFINE_DYNAMIC_CAST_ANCHOR(AP4_SchmAtom)
| AP4_SchmAtom::Create
+---------------------------------------------------------------------*/
AP4_SchmAtom*
-AP4_SchmAtom::Create(AP4_Size size,
+AP4_SchmAtom::Create(AP4_Size size,
AP4_Array<AP4_Atom::Type>* context,
AP4_ByteStream& stream)
{
AP4_UI32 version;
AP4_UI32 flags;
- if(AP4_FAILED(AP4_Atom::ReadFullHeader(stream, version, flags))) return NULL;
- if(version != 0) return NULL;
- if(size < AP4_FULL_ATOM_HEADER_SIZE + 6) return NULL;
-
+ if (AP4_FAILED(AP4_Atom::ReadFullHeader(stream, version, flags))) return NULL;
+ if (version != 0) return NULL;
+ if (size < AP4_FULL_ATOM_HEADER_SIZE+6) return NULL;
+
// check the context to see if this is a short form atom or not
bool short_form = false;
- if(size < AP4_FULL_ATOM_HEADER_SIZE + 8) short_form = true;
- if(context)
- {
+ if (size < AP4_FULL_ATOM_HEADER_SIZE+8) short_form = true;
+ if (context) {
AP4_Size context_depth = context->ItemCount();
- if(context_depth >= 2 &&
- (*context)[context_depth-2] == AP4_ATOM_TYPE('m', 'r', 'l', 'n'))
- {
+ if (context_depth >= 2 &&
+ (*context)[context_depth-2] == AP4_ATOM_TYPE('m','r','l','n')) {
short_form = true;
}
}
-
+
return new AP4_SchmAtom(size, version, flags, short_form, stream);
}
@@ -75,23 +73,22 @@ AP4_SchmAtom::AP4_SchmAtom(AP4_UI32 scheme_type,
AP4_UI32 scheme_version,
const char* scheme_uri,
bool short_form) :
- AP4_Atom(AP4_ATOM_TYPE_SCHM, AP4_FULL_ATOM_HEADER_SIZE + 4 + (short_form ? 2 : 4), 0, 0),
+ AP4_Atom(AP4_ATOM_TYPE_SCHM, AP4_FULL_ATOM_HEADER_SIZE+4+(short_form?2:4), 0, 0),
m_AtomHasShortForm(short_form),
m_SchemeType(scheme_type),
m_SchemeVersion(scheme_version)
{
- if(scheme_uri)
- {
+ if (scheme_uri) {
m_SchemeUri = scheme_uri;
m_Flags = 1;
- m_Size32 += m_SchemeUri.GetLength() + 1;
+ m_Size32 += m_SchemeUri.GetLength()+1;
}
}
/*----------------------------------------------------------------------
| AP4_SchmAtom::AP4_SchmAtom
+---------------------------------------------------------------------*/
-AP4_SchmAtom::AP4_SchmAtom(AP4_UI32 size,
+AP4_SchmAtom::AP4_SchmAtom(AP4_UI32 size,
AP4_UI32 version,
AP4_UI32 flags,
bool short_form,
@@ -100,21 +97,16 @@ AP4_SchmAtom::AP4_SchmAtom(AP4_UI32 size,
m_AtomHasShortForm(short_form)
{
stream.ReadUI32(m_SchemeType);
- if(short_form)
- {
+ if (short_form) {
AP4_UI16 short_version;
stream.ReadUI16(short_version);
m_SchemeVersion = short_version;
- }
- else
- {
+ } else {
stream.ReadUI32(m_SchemeVersion);
}
- if(m_Flags & 1)
- {
- int str_size = size - (AP4_FULL_ATOM_HEADER_SIZE + 8);
- if(str_size > 0)
- {
+ if (m_Flags & 1) {
+ int str_size = size-(AP4_FULL_ATOM_HEADER_SIZE+8);
+ if (str_size > 0) {
char* str = new char[str_size];
stream.Read(str, str_size);
str[str_size-1] = '\0'; // force null-termination
@@ -134,30 +126,26 @@ AP4_SchmAtom::WriteFields(AP4_ByteStream& stream)
// scheme type
result = stream.WriteUI32(m_SchemeType);
- if(AP4_FAILED(result)) return result;
+ if (AP4_FAILED(result)) return result;
// scheme version
- if(m_AtomHasShortForm)
- {
+ if (m_AtomHasShortForm) {
result = stream.WriteUI16((AP4_UI16)m_SchemeVersion);
- if(AP4_FAILED(result)) return result;
- }
- else
- {
+ if (AP4_FAILED(result)) return result;
+ } else {
result = stream.WriteUI32(m_SchemeVersion);
- if(AP4_FAILED(result)) return result;
+ if (AP4_FAILED(result)) return result;
}
-
+
// uri if needed
- if(m_Flags & 1)
- {
- result = stream.Write(m_SchemeUri.GetChars(), m_SchemeUri.GetLength() + 1);
- if(AP4_FAILED(result)) return result;
+ if (m_Flags & 1) {
+ result = stream.Write(m_SchemeUri.GetChars(), m_SchemeUri.GetLength()+1);
+ if (AP4_FAILED(result)) return result;
// pad with zeros if necessary
- AP4_Size fields_size = 4 + (m_AtomHasShortForm ? 2 : 4);
- AP4_Size padding = m_Size32 - (AP4_FULL_ATOM_HEADER_SIZE + fields_size + m_SchemeUri.GetLength() + 1);
- while(padding--) stream.WriteUI08(0);
+ AP4_Size fields_size = 4+(m_AtomHasShortForm?2:4);
+ AP4_Size padding = m_Size32-(AP4_FULL_ATOM_HEADER_SIZE+fields_size+m_SchemeUri.GetLength()+1);
+ while (padding--) stream.WriteUI08(0);
}
return result;
@@ -172,17 +160,13 @@ AP4_SchmAtom::InspectFields(AP4_AtomInspector& inspector)
char st[5];
AP4_FormatFourChars(st, m_SchemeType);
inspector.AddField("scheme_type", st);
- if(m_AtomHasShortForm)
- {
+ if (m_AtomHasShortForm) {
inspector.AddField("scheme_version (short)", m_SchemeVersion);
- }
- else
- {
+ } else {
inspector.AddField("scheme_version", m_SchemeVersion);
}
- if(m_Flags & 1)
- {
- inspector.AddField("scheme_uri", m_SchemeUri.GetChars());
+ if (m_Flags & 1) {
+ inspector.AddField("scheme_uri", m_SchemeUri.GetChars());
}
return AP4_SUCCESS;
diff --git a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4SchmAtom.h b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4SchmAtom.h
index fa60f9d62..3b2a065db 100644
--- a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4SchmAtom.h
+++ b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4SchmAtom.h
@@ -1,6 +1,6 @@
/*****************************************************************
|
-| AP4 - schm Atoms
+| AP4 - schm Atoms
|
| Copyright 2002-2008 Axiomatic Systems, LLC
|
@@ -51,7 +51,7 @@ public:
AP4_IMPLEMENT_DYNAMIC_CAST_D(AP4_SchmAtom, AP4_Atom)
// class methods
- static AP4_SchmAtom* Create(AP4_Size size,
+ static AP4_SchmAtom* Create(AP4_Size size,
AP4_Array<AP4_Atom::Type>* context,
AP4_ByteStream& stream);
@@ -66,22 +66,13 @@ public:
virtual AP4_Result WriteFields(AP4_ByteStream& stream);
// accessors
- AP4_UI32 GetSchemeType()
- {
- return m_SchemeType;
- }
- AP4_UI32 GetSchemeVersion()
- {
- return m_SchemeVersion;
- }
- AP4_String& GetSchemeUri()
- {
- return m_SchemeUri;
- }
+ AP4_UI32 GetSchemeType() { return m_SchemeType; }
+ AP4_UI32 GetSchemeVersion() { return m_SchemeVersion; }
+ AP4_String& GetSchemeUri() { return m_SchemeUri; }
private:
// methods
- AP4_SchmAtom(AP4_UI32 size,
+ AP4_SchmAtom(AP4_UI32 size,
AP4_UI32 version,
AP4_UI32 flags,
bool short_form,
@@ -89,7 +80,7 @@ private:
// members
bool m_AtomHasShortForm; // for versions of this where the version
- // field is only 16 bits
+ // field is only 16 bits
AP4_UI32 m_SchemeType;
AP4_UI32 m_SchemeVersion;
AP4_String m_SchemeUri;
diff --git a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4SdpAtom.cpp b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4SdpAtom.cpp
index 88abc8f93..56237781e 100644
--- a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4SdpAtom.cpp
+++ b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4SdpAtom.cpp
@@ -1,6 +1,6 @@
/*****************************************************************
|
-| AP4 - sdp Atoms
+| AP4 - sdp Atoms
|
| Copyright 2002-2008 Axiomatic Systems, LLC
|
@@ -41,7 +41,7 @@ AP4_SdpAtom::AP4_SdpAtom(const char* sdp_text) :
AP4_Atom(AP4_ATOM_TYPE_SDP_, AP4_ATOM_HEADER_SIZE),
m_SdpText(sdp_text)
{
- m_Size32 += m_SdpText.GetLength() + 1;
+ m_Size32 += m_SdpText.GetLength()+1;
}
/*----------------------------------------------------------------------
@@ -51,9 +51,8 @@ AP4_SdpAtom::AP4_SdpAtom(AP4_UI32 size, AP4_ByteStream& stream) :
AP4_Atom(AP4_ATOM_TYPE_SDP_, size)
{
// sdptext
- AP4_Size str_size = size - AP4_ATOM_HEADER_SIZE;
- if(str_size > 0)
- {
+ AP4_Size str_size = size-AP4_ATOM_HEADER_SIZE;
+ if (str_size > 0) {
char* str = new char[str_size+1];
stream.Read(str, str_size);
str[str_size] = '\0'; // force null-termination
@@ -70,12 +69,12 @@ AP4_SdpAtom::WriteFields(AP4_ByteStream& stream)
{
// sdptext
AP4_Result result = stream.Write(m_SdpText.GetChars(), m_SdpText.GetLength());
- if(AP4_FAILED(result)) return result;
+ if (AP4_FAILED(result)) return result;
// pad with zeros if necessary
- AP4_Size padding = m_Size32 - (AP4_ATOM_HEADER_SIZE + m_SdpText.GetLength());
- while(padding--) stream.WriteUI08(0);
-
+ AP4_Size padding = m_Size32-(AP4_ATOM_HEADER_SIZE+m_SdpText.GetLength());
+ while (padding--) stream.WriteUI08(0);
+
return AP4_SUCCESS;
}
diff --git a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4SdpAtom.h b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4SdpAtom.h
index 0c8ea9a1f..421a73b12 100644
--- a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4SdpAtom.h
+++ b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4SdpAtom.h
@@ -1,6 +1,6 @@
/*****************************************************************
|
-| AP4 - sdp Atoms
+| AP4 - sdp Atoms
|
| Copyright 2002-2008 Axiomatic Systems, LLC
|
@@ -48,8 +48,7 @@ class AP4_SdpAtom : public AP4_Atom
{
public:
// class methods
- static AP4_SdpAtom* Create(AP4_Size size, AP4_ByteStream& stream)
- {
+ static AP4_SdpAtom* Create(AP4_Size size, AP4_ByteStream& stream) {
return new AP4_SdpAtom(size, stream);
}
@@ -57,7 +56,7 @@ public:
AP4_SdpAtom(const char* sdp_text);
virtual AP4_Result InspectFields(AP4_AtomInspector& inspector);
virtual AP4_Result WriteFields(AP4_ByteStream& stream);
-
+
// accessors
const AP4_String& GetSdpText() const;
diff --git a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4SmhdAtom.cpp b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4SmhdAtom.cpp
index ee7adb9d1..88052ced1 100644
--- a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4SmhdAtom.cpp
+++ b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4SmhdAtom.cpp
@@ -1,6 +1,6 @@
/*****************************************************************
|
-| AP4 - smhd Atoms
+| AP4 - smhd Atoms
|
| Copyright 2002-2008 Axiomatic Systems, LLC
|
@@ -41,8 +41,8 @@ AP4_SmhdAtom::Create(AP4_Size size, AP4_ByteStream& stream)
{
AP4_UI32 version;
AP4_UI32 flags;
- if(AP4_FAILED(AP4_Atom::ReadFullHeader(stream, version, flags))) return NULL;
- if(version != 0) return NULL;
+ if (AP4_FAILED(AP4_Atom::ReadFullHeader(stream, version, flags))) return NULL;
+ if (version != 0) return NULL;
return new AP4_SmhdAtom(size, version, flags, stream);
}
@@ -50,7 +50,7 @@ AP4_SmhdAtom::Create(AP4_Size size, AP4_ByteStream& stream)
| AP4_SmhdAtom::AP4_SmhdAtom
+---------------------------------------------------------------------*/
AP4_SmhdAtom::AP4_SmhdAtom(AP4_UI16 balance) :
- AP4_Atom(AP4_ATOM_TYPE_SMHD, AP4_FULL_ATOM_HEADER_SIZE + 4, 0, 0),
+ AP4_Atom(AP4_ATOM_TYPE_SMHD, AP4_FULL_ATOM_HEADER_SIZE+4, 0, 0),
m_Balance(balance)
{
m_Reserved = 0;
@@ -59,7 +59,7 @@ AP4_SmhdAtom::AP4_SmhdAtom(AP4_UI16 balance) :
/*----------------------------------------------------------------------
| AP4_SmhdAtom::AP4_SmhdAtom
+---------------------------------------------------------------------*/
-AP4_SmhdAtom::AP4_SmhdAtom(AP4_UI32 size,
+AP4_SmhdAtom::AP4_SmhdAtom(AP4_UI32 size,
AP4_UI32 version,
AP4_UI32 flags,
AP4_ByteStream& stream) :
@@ -79,11 +79,11 @@ AP4_SmhdAtom::WriteFields(AP4_ByteStream& stream)
// balance
result = stream.WriteUI16(m_Balance);
- if(AP4_FAILED(result)) return result;
+ if (AP4_FAILED(result)) return result;
// reserved
result = stream.WriteUI16(m_Reserved);
- if(AP4_FAILED(result)) return result;
+ if (AP4_FAILED(result)) return result;
return AP4_SUCCESS;
}
diff --git a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4SmhdAtom.h b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4SmhdAtom.h
index 1cf71d987..8d6269b5b 100644
--- a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4SmhdAtom.h
+++ b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4SmhdAtom.h
@@ -1,6 +1,6 @@
/*****************************************************************
|
-| AP4 - smhd Atoms
+| AP4 - smhd Atoms
|
| Copyright 2002-2008 Axiomatic Systems, LLC
|
@@ -51,7 +51,7 @@ public:
private:
// methods
- AP4_SmhdAtom(AP4_UI32 size,
+ AP4_SmhdAtom(AP4_UI32 size,
AP4_UI32 version,
AP4_UI32 flags,
AP4_ByteStream& stream);
diff --git a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4StcoAtom.cpp b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4StcoAtom.cpp
index 397da3850..4ed8fe1f3 100644
--- a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4StcoAtom.cpp
+++ b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4StcoAtom.cpp
@@ -1,6 +1,6 @@
/*****************************************************************
|
-| AP4 - stco Atoms
+| AP4 - stco Atoms
|
| Copyright 2002-2008 Axiomatic Systems, LLC
|
@@ -46,8 +46,8 @@ AP4_StcoAtom::Create(AP4_Size size, AP4_ByteStream& stream)
{
AP4_UI32 version;
AP4_UI32 flags;
- if(AP4_FAILED(AP4_Atom::ReadFullHeader(stream, version, flags))) return NULL;
- if(version != 0) return NULL;
+ if (AP4_FAILED(AP4_Atom::ReadFullHeader(stream, version, flags))) return NULL;
+ if (version != 0) return NULL;
return new AP4_StcoAtom(size, version, flags, stream);
}
@@ -55,39 +55,36 @@ AP4_StcoAtom::Create(AP4_Size size, AP4_ByteStream& stream)
| AP4_StcoAtom::AP4_StcoAtom
+---------------------------------------------------------------------*/
AP4_StcoAtom::AP4_StcoAtom(AP4_UI32* entries, AP4_UI32 entry_count) :
- AP4_Atom(AP4_ATOM_TYPE_STCO,
- AP4_FULL_ATOM_HEADER_SIZE + 4 + entry_count * 4,
- 0, 0),
- m_Entries(new AP4_UI32[entry_count]),
- m_EntryCount(entry_count)
+AP4_Atom(AP4_ATOM_TYPE_STCO,
+ AP4_FULL_ATOM_HEADER_SIZE+4+entry_count*4,
+ 0, 0),
+ m_Entries(new AP4_UI32[entry_count]),
+ m_EntryCount(entry_count)
{
- AP4_CopyMemory(m_Entries, entries, m_EntryCount * 4);
+ AP4_CopyMemory(m_Entries, entries, m_EntryCount*4);
}
/*----------------------------------------------------------------------
| AP4_StcoAtom::AP4_StcoAtom
+---------------------------------------------------------------------*/
-AP4_StcoAtom::AP4_StcoAtom(AP4_UI32 size,
+AP4_StcoAtom::AP4_StcoAtom(AP4_UI32 size,
AP4_UI32 version,
AP4_UI32 flags,
AP4_ByteStream& stream) :
AP4_Atom(AP4_ATOM_TYPE_STCO, size, version, flags)
{
stream.ReadUI32(m_EntryCount);
- if(m_EntryCount > (size - AP4_FULL_ATOM_HEADER_SIZE - 4) / 4)
- {
- m_EntryCount = (size - AP4_FULL_ATOM_HEADER_SIZE - 4) / 4;
+ if (m_EntryCount > (size-AP4_FULL_ATOM_HEADER_SIZE-4)/4) {
+ m_EntryCount = (size-AP4_FULL_ATOM_HEADER_SIZE-4)/4;
}
m_Entries = new AP4_UI32[m_EntryCount];
unsigned char* buffer = new unsigned char[m_EntryCount*4];
- AP4_Result result = stream.Read(buffer, m_EntryCount * 4);
- if(AP4_FAILED(result))
- {
+ AP4_Result result = stream.Read(buffer, m_EntryCount*4);
+ if (AP4_FAILED(result)) {
delete[] buffer;
return;
}
- for(AP4_Ordinal i = 0; i < m_EntryCount; i++)
- {
+ for (AP4_Ordinal i=0; i<m_EntryCount; i++) {
m_Entries[i] = AP4_BytesToUInt32BE(&buffer[i*4]);
}
delete[] buffer;
@@ -108,8 +105,7 @@ AP4_Result
AP4_StcoAtom::GetChunkOffset(AP4_Ordinal chunk, AP4_UI32& chunk_offset)
{
// check the bounds
- if(chunk > m_EntryCount || chunk == 0)
- {
+ if (chunk > m_EntryCount || chunk == 0) {
return AP4_ERROR_OUT_OF_RANGE;
}
@@ -126,8 +122,7 @@ AP4_Result
AP4_StcoAtom::SetChunkOffset(AP4_Ordinal chunk, AP4_UI32 chunk_offset)
{
// check the bounds
- if(chunk > m_EntryCount || chunk == 0)
- {
+ if (chunk > m_EntryCount || chunk == 0) {
return AP4_ERROR_OUT_OF_RANGE;
}
@@ -143,8 +138,7 @@ AP4_StcoAtom::SetChunkOffset(AP4_Ordinal chunk, AP4_UI32 chunk_offset)
AP4_Result
AP4_StcoAtom::AdjustChunkOffsets(int delta)
{
- for(AP4_Ordinal i = 0; i < m_EntryCount; i++)
- {
+ for (AP4_Ordinal i=0; i<m_EntryCount; i++) {
m_Entries[i] += delta;
}
@@ -161,13 +155,12 @@ AP4_StcoAtom::WriteFields(AP4_ByteStream& stream)
// entry count
result = stream.WriteUI32(m_EntryCount);
- if(AP4_FAILED(result)) return result;
+ if (AP4_FAILED(result)) return result;
// entries
- for(AP4_Ordinal i = 0; i < m_EntryCount; i++)
- {
+ for (AP4_Ordinal i=0; i<m_EntryCount; i++) {
result = stream.WriteUI32(m_Entries[i]);
- if(AP4_FAILED(result)) return result;
+ if (AP4_FAILED(result)) return result;
}
return result;
@@ -180,15 +173,13 @@ AP4_Result
AP4_StcoAtom::InspectFields(AP4_AtomInspector& inspector)
{
inspector.AddField("entry_count", m_EntryCount);
- if(inspector.GetVerbosity() >= 1)
- {
+ if (inspector.GetVerbosity() >= 1) {
char header[32];
- for(AP4_Ordinal i = 0; i < m_EntryCount; i++)
- {
+ for (AP4_Ordinal i=0; i<m_EntryCount; i++) {
AP4_FormatString(header, sizeof(header), "entry %8d", i);
inspector.AddField(header, m_Entries[i]);
}
}
-
+
return AP4_SUCCESS;
}
diff --git a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4StcoAtom.h b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4StcoAtom.h
index 2a4777250..7fdaea4cc 100644
--- a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4StcoAtom.h
+++ b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4StcoAtom.h
@@ -1,6 +1,6 @@
/*****************************************************************
|
-| AP4 - stco Atoms
+| AP4 - stco Atoms
|
| Copyright 2002-2008 Axiomatic Systems, LLC
|
@@ -51,21 +51,15 @@ public:
~AP4_StcoAtom();
virtual AP4_Result InspectFields(AP4_AtomInspector& inspector);
virtual AP4_Result WriteFields(AP4_ByteStream& stream);
- AP4_Cardinal GetChunkCount()
- {
- return m_EntryCount;
- }
- AP4_UI32* GetChunkOffsets()
- {
- return m_Entries;
- }
+ AP4_Cardinal GetChunkCount() { return m_EntryCount; }
+ AP4_UI32* GetChunkOffsets() { return m_Entries; }
AP4_Result GetChunkOffset(AP4_Ordinal chunk, AP4_UI32& chunk_offset);
AP4_Result SetChunkOffset(AP4_Ordinal chunk, AP4_UI32 chunk_offset);
AP4_Result AdjustChunkOffsets(int delta);
-
+
private:
// methods
- AP4_StcoAtom(AP4_UI32 size,
+ AP4_StcoAtom(AP4_UI32 size,
AP4_UI32 version,
AP4_UI32 flags,
AP4_ByteStream& stream);
diff --git a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4String.cpp b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4String.cpp
index f3a3f77d2..f93422416 100644
--- a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4String.cpp
+++ b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4String.cpp
@@ -46,24 +46,22 @@ AP4_String::AP4_String() : m_Chars(&EmptyString), m_Length(0) {}
/*----------------------------------------------------------------------
| AP4_String::AP4_String
+---------------------------------------------------------------------*/
-AP4_String::AP4_String(const char* s)
-{
- if(s == NULL)
- {
+AP4_String::AP4_String(const char* s) {
+ if (s == NULL) {
m_Chars = &EmptyString;
m_Length = 0;
return;
}
m_Length = (AP4_Size)AP4_StringLength(s);
m_Chars = new char[m_Length+1];
- AP4_CopyMemory(m_Chars, s, m_Length + 1);
+ AP4_CopyMemory(m_Chars, s, m_Length+1);
}
/*----------------------------------------------------------------------
| AP4_String::AP4_String
+---------------------------------------------------------------------*/
AP4_String::AP4_String(const char* s, AP4_Size size) :
- m_Chars(new char[size+1]),
+ m_Chars(new char[size+1]),
m_Length(size)
{
m_Chars[size] = 0;
@@ -73,29 +71,27 @@ AP4_String::AP4_String(const char* s, AP4_Size size) :
/*----------------------------------------------------------------------
| AP4_String::AP4_String
+---------------------------------------------------------------------*/
-AP4_String::AP4_String(const AP4_String& s)
-{
+AP4_String::AP4_String(const AP4_String& s) {
m_Length = s.m_Length;
m_Chars = new char[m_Length+1];
- AP4_CopyMemory(m_Chars, s.m_Chars, m_Length + 1);
+ AP4_CopyMemory(m_Chars, s.m_Chars, m_Length+1);
}
/*----------------------------------------------------------------------
| AP4_String::AP4_String
+---------------------------------------------------------------------*/
-AP4_String::AP4_String(AP4_Size size)
-{
+AP4_String::AP4_String(AP4_Size size) {
m_Length = size;
m_Chars = new char[m_Length+1];
- for(unsigned int i = 0; i < size + 1; i++) m_Chars[i] = 0;
+ for (unsigned int i=0; i<size+1; i++) m_Chars[i] = 0;
}
/*----------------------------------------------------------------------
| AP4_String::~AP4_String
+---------------------------------------------------------------------*/
-AP4_String::~AP4_String()
+AP4_String::~AP4_String()
{
- if(m_Chars != &EmptyString) delete[] m_Chars;
+ if (m_Chars != &EmptyString) delete[] m_Chars;
}
/*----------------------------------------------------------------------
@@ -104,11 +100,11 @@ AP4_String::~AP4_String()
const AP4_String&
AP4_String::operator=(const AP4_String& s)
{
- if(&s == this) return s;
- if(m_Chars != &EmptyString) delete[] m_Chars;
+ if (&s == this) return s;
+ if (m_Chars != &EmptyString) delete[] m_Chars;
m_Length = s.m_Length;
m_Chars = new char[m_Length+1];
- AP4_CopyMemory(m_Chars, s.m_Chars, m_Length + 1);
+ AP4_CopyMemory(m_Chars, s.m_Chars, m_Length+1);
return *this;
}
@@ -119,14 +115,11 @@ AP4_String::operator=(const AP4_String& s)
const AP4_String&
AP4_String::operator=(const char* s)
{
- if(s == NULL)
- {
- if(m_Chars != &EmptyString) delete[] m_Chars;
+ if (s == NULL) {
+ if (m_Chars != &EmptyString) delete[] m_Chars;
m_Chars = &EmptyString;
m_Length = 0;
- }
- else
- {
+ } else {
Assign(s, (AP4_Size)AP4_StringLength(s));
}
@@ -139,10 +132,9 @@ AP4_String::operator=(const char* s)
bool
AP4_String::operator==(const AP4_String& s) const
{
- if(m_Length != s.m_Length) return false;
- for(unsigned int i = 0; i < m_Length; i++)
- {
- if(m_Chars[i] != s.m_Chars[i]) return false;
+ if (m_Length != s.m_Length) return false;
+ for (unsigned int i=0; i<m_Length; i++) {
+ if (m_Chars[i] != s.m_Chars[i]) return false;
}
return true;
}
@@ -155,10 +147,9 @@ bool
AP4_String::operator==(const char* s) const
{
AP4_Size s_length = (AP4_Size)AP4_StringLength(s);
- if(m_Length != s_length) return false;
- for(unsigned int i = 0; i < s_length; i++)
- {
- if(m_Chars[i] != s[i]) return false;
+ if (m_Length != s_length) return false;
+ for (unsigned int i=0; i<s_length; i++) {
+ if (m_Chars[i] != s[i]) return false;
}
return true;
}
@@ -169,7 +160,7 @@ AP4_String::operator==(const char* s) const
void
AP4_String::Assign(const char* s, AP4_Size size)
{
- if(m_Chars != &EmptyString) delete[] m_Chars;
+ if (m_Chars != &EmptyString) delete[] m_Chars;
m_Length = size;
m_Chars = new char[m_Length+1];
AP4_CopyMemory(m_Chars, s, m_Length);
@@ -183,9 +174,8 @@ int
AP4_String::Find(char c, unsigned int start) const
{
const char* chars = GetChars();
- for(unsigned int i = start; i < m_Length; i++)
- {
- if(chars[i] == c) return i;
+ for (unsigned int i=start; i<m_Length; i++) {
+ if (chars[i] == c) return i;
}
return -1;
}
diff --git a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4String.h b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4String.h
index 0461075bd..f1d81ef06 100644
--- a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4String.h
+++ b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4String.h
@@ -54,37 +54,21 @@ public:
// operators
const AP4_String& operator=(const AP4_String& s);
const AP4_String& operator=(const char* s);
- char operator[](unsigned int index) const
- {
+ char operator[](unsigned int index) const {
return m_Chars[index];
}
bool operator==(const AP4_String& s) const;
- bool operator!=(const AP4_String& s) const
- {
- return !(*this == s);
- }
+ bool operator!=(const AP4_String& s) const { return !(*this == s); }
bool operator==(const char* s) const;
- bool operator!=(const char* s) const
- {
- return !(*this == s);
- }
+ bool operator!=(const char* s) const { return !(*this == s); }
// methods
- AP4_Size GetLength() const
- {
- return m_Length;
- }
- const char* GetChars() const
- {
- return m_Chars;
- }
- char* UseChars()
- {
- return m_Chars;
- }
+ AP4_Size GetLength() const { return m_Length; }
+ const char* GetChars() const { return m_Chars; }
+ char* UseChars() { return m_Chars; }
void Assign(const char* chars, AP4_Size size);
int Find(char c, unsigned int start = 0) const;
-
+
private:
// class members
static char EmptyString;
diff --git a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4StscAtom.cpp b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4StscAtom.cpp
index ad4e10c52..7e108f285 100644
--- a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4StscAtom.cpp
+++ b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4StscAtom.cpp
@@ -1,6 +1,6 @@
-/*****************************************************************
+ /*****************************************************************
|
-| AP4 - stsc Atoms
+| AP4 - stsc Atoms
|
| Copyright 2002-2008 Axiomatic Systems, LLC
|
@@ -24,7 +24,7 @@
| Free Software Foundation, 59 Temple Place - Suite 330, Boston, MA
| 02111-1307, USA.
|
-****************************************************************/
+ ****************************************************************/
/*----------------------------------------------------------------------
| includes
@@ -46,8 +46,8 @@ AP4_StscAtom::Create(AP4_Size size, AP4_ByteStream& stream)
{
AP4_UI32 version;
AP4_UI32 flags;
- if(AP4_FAILED(AP4_Atom::ReadFullHeader(stream, version, flags))) return NULL;
- if(version != 0) return NULL;
+ if (AP4_FAILED(AP4_Atom::ReadFullHeader(stream, version, flags))) return NULL;
+ if (version != 0) return NULL;
return new AP4_StscAtom(size, version, flags, stream);
}
@@ -55,7 +55,7 @@ AP4_StscAtom::Create(AP4_Size size, AP4_ByteStream& stream)
| AP4_StscAtom::AP4_StscAtom
+---------------------------------------------------------------------*/
AP4_StscAtom::AP4_StscAtom() :
- AP4_Atom(AP4_ATOM_TYPE_STSC, AP4_FULL_ATOM_HEADER_SIZE + 4, 0, 0),
+ AP4_Atom(AP4_ATOM_TYPE_STSC, AP4_FULL_ATOM_HEADER_SIZE+4, 0, 0),
m_CachedChunkGroup(0)
{
}
@@ -63,7 +63,7 @@ AP4_StscAtom::AP4_StscAtom() :
/*----------------------------------------------------------------------
| AP4_StscAtom::AP4_StscAtom
+---------------------------------------------------------------------*/
-AP4_StscAtom::AP4_StscAtom(AP4_UI32 size,
+AP4_StscAtom::AP4_StscAtom(AP4_UI32 size,
AP4_UI32 version,
AP4_UI32 flags,
AP4_ByteStream& stream) :
@@ -75,21 +75,18 @@ AP4_StscAtom::AP4_StscAtom(AP4_UI32 size,
stream.ReadUI32(entry_count);
m_Entries.SetItemCount(entry_count);
unsigned char* buffer = new unsigned char[entry_count*12];
- AP4_Result result = stream.Read(buffer, entry_count * 12);
- if(AP4_FAILED(result))
- {
+ AP4_Result result = stream.Read(buffer, entry_count*12);
+ if (AP4_FAILED(result)) {
delete[] buffer;
return;
}
- for(unsigned int i = 0; i < entry_count; i++)
- {
+ for (unsigned int i=0; i<entry_count; i++) {
AP4_UI32 first_chunk = AP4_BytesToUInt32BE(&buffer[i*12 ]);
AP4_UI32 samples_per_chunk = AP4_BytesToUInt32BE(&buffer[i*12+4]);
AP4_UI32 sample_description_index = AP4_BytesToUInt32BE(&buffer[i*12+8]);
- if(i)
- {
- AP4_Ordinal prev = i - 1;
- m_Entries[prev].m_ChunkCount = first_chunk - m_Entries[prev].m_FirstChunk;
+ if (i) {
+ AP4_Ordinal prev = i-1;
+ m_Entries[prev].m_ChunkCount = first_chunk-m_Entries[prev].m_FirstChunk;
first_sample += m_Entries[prev].m_ChunkCount * m_Entries[prev].m_SamplesPerChunk;
}
m_Entries[i].m_ChunkCount = 0; // not known yet
@@ -114,14 +111,13 @@ AP4_StscAtom::WriteFields(AP4_ByteStream& stream)
result = stream.WriteUI32(entry_count);
// entries
- for(AP4_Ordinal i = 0; i < entry_count; i++)
- {
+ for (AP4_Ordinal i=0; i<entry_count; i++) {
stream.WriteUI32(m_Entries[i].m_FirstChunk);
- if(AP4_FAILED(result)) return result;
+ if (AP4_FAILED(result)) return result;
stream.WriteUI32(m_Entries[i].m_SamplesPerChunk);
- if(AP4_FAILED(result)) return result;
+ if (AP4_FAILED(result)) return result;
stream.WriteUI32(m_Entries[i].m_SampleDescriptionIndex);
- if(AP4_FAILED(result)) return result;
+ if (AP4_FAILED(result)) return result;
}
return result;
@@ -130,7 +126,7 @@ AP4_StscAtom::WriteFields(AP4_ByteStream& stream)
/*----------------------------------------------------------------------
| AP4_StscAtom::AddEntry
+---------------------------------------------------------------------*/
-AP4_Result
+AP4_Result
AP4_StscAtom::AddEntry(AP4_Cardinal chunk_count,
AP4_Cardinal samples_per_chunk,
AP4_Ordinal sample_description_index)
@@ -138,18 +134,15 @@ AP4_StscAtom::AddEntry(AP4_Cardinal chunk_count,
AP4_Ordinal first_chunk;
AP4_Ordinal first_sample;
AP4_Cardinal entry_count = m_Entries.ItemCount();
- if(entry_count == 0)
- {
+ if (entry_count == 0) {
// first entry
first_chunk = 1;
first_sample = 1;
- }
- else
- {
- first_chunk = m_Entries[entry_count-1].m_FirstChunk +
+ } else {
+ first_chunk = m_Entries[entry_count-1].m_FirstChunk+
m_Entries[entry_count-1].m_ChunkCount;
- first_sample = m_Entries[entry_count-1].m_FirstSample +
- m_Entries[entry_count-1].m_ChunkCount *
+ first_sample = m_Entries[entry_count-1].m_FirstSample+
+ m_Entries[entry_count-1].m_ChunkCount*
m_Entries[entry_count-1].m_SamplesPerChunk;
}
m_Entries.Append(AP4_StscTableEntry(first_chunk, first_sample, chunk_count, samples_per_chunk, sample_description_index));
@@ -175,35 +168,26 @@ AP4_StscAtom::GetChunkForSample(AP4_Ordinal sample,
// decide whether to start the search from the cached index
// or from the start
AP4_Ordinal group;
- if(m_CachedChunkGroup < m_Entries.ItemCount() &&
- m_Entries[m_CachedChunkGroup].m_FirstSample <= sample)
- {
+ if (m_CachedChunkGroup < m_Entries.ItemCount() &&
+ m_Entries[m_CachedChunkGroup].m_FirstSample <= sample) {
group = m_CachedChunkGroup;
- }
- else
- {
+ } else {
group = 0;
}
// find which group of chunk contains this one
- while(group < m_Entries.ItemCount())
- {
- AP4_Cardinal sample_count =
- m_Entries[group].m_ChunkCount * m_Entries[group].m_SamplesPerChunk;
- if(sample_count == 0)
- {
+ while (group < m_Entries.ItemCount()) {
+ AP4_Cardinal sample_count =
+ m_Entries[group].m_ChunkCount*m_Entries[group].m_SamplesPerChunk;
+ if (sample_count == 0) {
// unlimited samples in this group (last group)
- if(m_Entries[group].m_FirstSample > sample)
- {
+ if (m_Entries[group].m_FirstSample > sample) {
// something is wrong
return AP4_ERROR_INVALID_FORMAT;
}
- }
- else
- {
+ } else {
// normal group
- if(m_Entries[group].m_FirstSample + sample_count <= sample)
- {
+ if (m_Entries[group].m_FirstSample + sample_count <= sample) {
// the sample is not in this group
group++;
continue;
@@ -211,18 +195,17 @@ AP4_StscAtom::GetChunkForSample(AP4_Ordinal sample,
}
// the sample is in this group
- if(m_Entries[group].m_SamplesPerChunk == 0)
- {
+ if (m_Entries[group].m_SamplesPerChunk == 0) {
// something is wrong
return AP4_ERROR_INVALID_FORMAT;
}
- unsigned int chunk_offset =
- ((sample - m_Entries[group].m_FirstSample) /
- m_Entries[group].m_SamplesPerChunk);
+ unsigned int chunk_offset =
+ ((sample-m_Entries[group].m_FirstSample) /
+ m_Entries[group].m_SamplesPerChunk);
chunk = m_Entries[group].m_FirstChunk + chunk_offset;
skip = sample -
- (m_Entries[group].m_FirstSample +
- m_Entries[group].m_SamplesPerChunk * chunk_offset);
+ (m_Entries[group].m_FirstSample +
+ m_Entries[group].m_SamplesPerChunk*chunk_offset);
sample_description_index = m_Entries[group].m_SampleDescriptionIndex;
// cache the result (to accelerate finding the right group
@@ -248,24 +231,22 @@ AP4_StscAtom::InspectFields(AP4_AtomInspector& inspector)
inspector.AddField("entry_count", m_Entries.ItemCount());
// dump table entries
- if(inspector.GetVerbosity() >= 1)
- {
+ if (inspector.GetVerbosity() >= 1) {
char header[32];
char value[256];
- for(unsigned int i = 0; i < m_Entries.ItemCount(); i++)
- {
- AP4_FormatString(header, sizeof(header), "entry %8d", i);
- AP4_FormatString(value, sizeof(value),
- "first_chunk=%d, first_sample*=%d, chunk_count*=%d, samples_per_chunk=%d, sample_desc_index=%d",
- m_Entries[i].m_FirstChunk,
- m_Entries[i].m_FirstSample,
- m_Entries[i].m_ChunkCount,
- m_Entries[i].m_SamplesPerChunk,
- m_Entries[i].m_SampleDescriptionIndex);
+ for (unsigned int i=0; i<m_Entries.ItemCount(); i++) {
+ AP4_FormatString(header, sizeof(header), "entry %8d", i);
+ AP4_FormatString(value, sizeof(value),
+ "first_chunk=%d, first_sample*=%d, chunk_count*=%d, samples_per_chunk=%d, sample_desc_index=%d",
+ m_Entries[i].m_FirstChunk,
+ m_Entries[i].m_FirstSample,
+ m_Entries[i].m_ChunkCount,
+ m_Entries[i].m_SamplesPerChunk,
+ m_Entries[i].m_SampleDescriptionIndex);
inspector.AddField(header, value);
}
}
-
+
return AP4_SUCCESS;
}
diff --git a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4StscAtom.h b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4StscAtom.h
index c0acf224a..23def43b7 100644
--- a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4StscAtom.h
+++ b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4StscAtom.h
@@ -1,6 +1,6 @@
/*****************************************************************
|
-| AP4 - stsc Atoms
+| AP4 - stsc Atoms
|
| Copyright 2002-2008 Axiomatic Systems, LLC
|
@@ -39,14 +39,13 @@
/*----------------------------------------------------------------------
| AP4_StscTableEntry
+---------------------------------------------------------------------*/
-class AP4_StscTableEntry
-{
-public:
- AP4_StscTableEntry() :
- m_FirstChunk(0),
+class AP4_StscTableEntry {
+ public:
+ AP4_StscTableEntry() :
+ m_FirstChunk(0),
m_FirstSample(0),
m_ChunkCount(0),
- m_SamplesPerChunk(0),
+ m_SamplesPerChunk(0),
m_SampleDescriptionIndex(0) {}
AP4_StscTableEntry(AP4_Ordinal first_chunk,
AP4_Ordinal first_sample,
@@ -81,7 +80,7 @@ class AP4_StscAtom : public AP4_Atom
{
public:
AP4_IMPLEMENT_DYNAMIC_CAST_D(AP4_StscAtom, AP4_Atom)
-
+
// class methods
static AP4_StscAtom* Create(AP4_Size size, AP4_ByteStream& stream);
@@ -97,14 +96,14 @@ public:
AP4_Ordinal sample_description_index);
virtual AP4_Result WriteFields(AP4_ByteStream& stream);
- // ==> Start patch MPC
- // FIXME
- friend class AP4_AtomSampleTable;
- // <== End patch MPC
+ // ==> Start patch MPC
+ // FIXME
+ friend class AP4_AtomSampleTable;
+ // <== End patch MPC
private:
// methods
- AP4_StscAtom(AP4_UI32 size,
+ AP4_StscAtom(AP4_UI32 size,
AP4_UI32 version,
AP4_UI32 flags,
AP4_ByteStream& stream);
diff --git a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4StsdAtom.cpp b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4StsdAtom.cpp
index 766b1ca7a..3ce86da1b 100644
--- a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4StsdAtom.cpp
+++ b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4StsdAtom.cpp
@@ -1,6 +1,6 @@
/*****************************************************************
|
-| AP4 - stsd Atoms
+| AP4 - stsd Atoms
|
| Copyright 2002-2008 Axiomatic Systems, LLC
|
@@ -45,14 +45,14 @@ AP4_DEFINE_DYNAMIC_CAST_ANCHOR(AP4_StsdAtom)
| AP4_StsdAtom::Create
+---------------------------------------------------------------------*/
AP4_StsdAtom*
-AP4_StsdAtom::Create(AP4_Size size,
- AP4_ByteStream& stream,
+AP4_StsdAtom::Create(AP4_Size size,
+ AP4_ByteStream& stream,
AP4_AtomFactory& atom_factory)
{
AP4_UI32 version;
AP4_UI32 flags;
- if(AP4_FAILED(AP4_Atom::ReadFullHeader(stream, version, flags))) return NULL;
- if(version != 0) return NULL;
+ if (AP4_FAILED(AP4_Atom::ReadFullHeader(stream, version, flags))) return NULL;
+ if (version != 0) return NULL;
return new AP4_StsdAtom(size, version, flags, stream, atom_factory);
}
@@ -65,8 +65,7 @@ AP4_StsdAtom::AP4_StsdAtom(AP4_SampleTable* sample_table) :
m_Size32 += 4;
AP4_Cardinal sample_description_count = sample_table->GetSampleDescriptionCount();
m_SampleDescriptions.EnsureCapacity(sample_description_count);
- for(AP4_Ordinal i = 0; i < sample_description_count; i++)
- {
+ for (AP4_Ordinal i=0; i<sample_description_count; i++) {
// clear the cache entry
m_SampleDescriptions.Append(NULL);
@@ -98,14 +97,12 @@ AP4_StsdAtom::AP4_StsdAtom(AP4_UI32 size,
atom_factory.PushContext(m_Type);
// read all entries
- AP4_LargeSize bytes_available = size - AP4_FULL_ATOM_HEADER_SIZE - 4;
- for(unsigned int i = 0; i < entry_count; i++)
- {
+ AP4_LargeSize bytes_available = size-AP4_FULL_ATOM_HEADER_SIZE-4;
+ for (unsigned int i=0; i<entry_count; i++) {
AP4_Atom* atom;
- if(AP4_SUCCEEDED(atom_factory.CreateAtomFromStream(stream,
- bytes_available,
- atom)))
- {
+ if (AP4_SUCCEEDED(atom_factory.CreateAtomFromStream(stream,
+ bytes_available,
+ atom))) {
atom->SetParent(this);
m_Children.Add(atom);
}
@@ -116,8 +113,7 @@ AP4_StsdAtom::AP4_StsdAtom(AP4_UI32 size,
// initialize the sample description cache
m_SampleDescriptions.EnsureCapacity(m_Children.ItemCount());
- for(AP4_Ordinal i = 0; i < m_Children.ItemCount(); i++)
- {
+ for (AP4_Ordinal i=0; i<m_Children.ItemCount(); i++) {
m_SampleDescriptions.Append(NULL);
}
}
@@ -127,8 +123,7 @@ AP4_StsdAtom::AP4_StsdAtom(AP4_UI32 size,
+---------------------------------------------------------------------*/
AP4_StsdAtom::~AP4_StsdAtom()
{
- for(AP4_Ordinal i = 0; i < m_SampleDescriptions.ItemCount(); i++)
- {
+ for (AP4_Ordinal i=0; i<m_SampleDescriptions.ItemCount(); i++) {
delete m_SampleDescriptions[i];
}
}
@@ -143,7 +138,7 @@ AP4_StsdAtom::WriteFields(AP4_ByteStream& stream)
// entry count
result = stream.WriteUI32(m_Children.ItemCount());
- if(AP4_FAILED(result)) return result;
+ if (AP4_FAILED(result)) return result;
// entries
return m_Children.Apply(AP4_AtomListWriter(stream));
@@ -156,12 +151,12 @@ void
AP4_StsdAtom::OnChildChanged(AP4_Atom*)
{
// remcompute our size
- AP4_UI64 size = GetHeaderSize() + 4;
+ AP4_UI64 size = GetHeaderSize()+4;
m_Children.Apply(AP4_AtomSizeAdder(size));
m_Size32 = (AP4_UI32)size;
// update our parent
- if(m_Parent) m_Parent->OnChildChanged(this);
+ if (m_Parent) m_Parent->OnChildChanged(this);
}
/*----------------------------------------------------------------------
@@ -171,21 +166,18 @@ AP4_SampleDescription*
AP4_StsdAtom::GetSampleDescription(AP4_Ordinal index)
{
// check index
- if(index >= m_Children.ItemCount()) return NULL;
+ if (index >= m_Children.ItemCount()) return NULL;
// return the description if we already have it in the internal table
- if(m_SampleDescriptions[index]) return m_SampleDescriptions[index];
+ if (m_SampleDescriptions[index]) return m_SampleDescriptions[index];
// create and cache a sample description for this entry
AP4_Atom* entry;
m_Children.Get(index, entry);
AP4_SampleEntry* sample_entry = AP4_DYNAMIC_CAST(AP4_SampleEntry, entry);
- if(sample_entry == NULL)
- {
+ if (sample_entry == NULL) {
m_SampleDescriptions[index] = new AP4_UnknownSampleDescription(entry);
- }
- else
- {
+ } else {
m_SampleDescriptions[index] = sample_entry->ToSampleDescription();
}
return m_SampleDescriptions[index];
@@ -198,7 +190,7 @@ AP4_SampleEntry*
AP4_StsdAtom::GetSampleEntry(AP4_Ordinal index)
{
// check index
- if(index >= m_Children.ItemCount()) return NULL;
+ if (index >= m_Children.ItemCount()) return NULL;
// return the sample entry
AP4_Atom* entry;
@@ -222,7 +214,7 @@ AP4_Result
AP4_StsdAtom::InspectFields(AP4_AtomInspector& inspector)
{
inspector.AddField("entry-count", m_Children.ItemCount());
-
+
// inspect children
m_Children.Apply(AP4_AtomListInspector(inspector));
diff --git a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4StsdAtom.h b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4StsdAtom.h
index b47948d25..8a5013a72 100644
--- a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4StsdAtom.h
+++ b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4StsdAtom.h
@@ -1,6 +1,6 @@
/*****************************************************************
|
-| AP4 - stsd Atoms
+| AP4 - stsd Atoms
|
| Copyright 2002-2008 Axiomatic Systems, LLC
|
diff --git a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4StssAtom.cpp b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4StssAtom.cpp
index 76a348249..23d06f82d 100644
--- a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4StssAtom.cpp
+++ b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4StssAtom.cpp
@@ -1,6 +1,6 @@
/*****************************************************************
|
-| AP4 - stss Atoms
+| AP4 - stss Atoms
|
| Copyright 2002-2008 Axiomatic Systems, LLC
|
@@ -46,8 +46,8 @@ AP4_StssAtom::Create(AP4_Size size, AP4_ByteStream& stream)
{
AP4_UI32 version;
AP4_UI32 flags;
- if(AP4_FAILED(AP4_Atom::ReadFullHeader(stream, version, flags))) return NULL;
- if(version != 0) return NULL;
+ if (AP4_FAILED(AP4_Atom::ReadFullHeader(stream, version, flags))) return NULL;
+ if (version != 0) return NULL;
return new AP4_StssAtom(size, version, flags, stream);
}
@@ -55,14 +55,14 @@ AP4_StssAtom::Create(AP4_Size size, AP4_ByteStream& stream)
| AP4_StssAtom::AP4_StssAtom
+---------------------------------------------------------------------*/
AP4_StssAtom::AP4_StssAtom() :
- AP4_Atom(AP4_ATOM_TYPE_STSS, AP4_FULL_ATOM_HEADER_SIZE + 4, 0, 0)
+ AP4_Atom(AP4_ATOM_TYPE_STSS, AP4_FULL_ATOM_HEADER_SIZE+4, 0, 0)
{
}
/*----------------------------------------------------------------------
| AP4_StssAtom::AP4_StssAtom
+---------------------------------------------------------------------*/
-AP4_StssAtom::AP4_StssAtom(AP4_UI32 size,
+AP4_StssAtom::AP4_StssAtom(AP4_UI32 size,
AP4_UI32 version,
AP4_UI32 flags,
AP4_ByteStream& stream) :
@@ -71,11 +71,9 @@ AP4_StssAtom::AP4_StssAtom(AP4_UI32 size,
{
AP4_UI32 entry_count;
stream.ReadUI32(entry_count);
- while(entry_count--)
- {
+ while (entry_count--) {
AP4_UI32 entry_sample_index;
- if(stream.ReadUI32(entry_sample_index) == AP4_SUCCESS)
- {
+ if (stream.ReadUI32(entry_sample_index) == AP4_SUCCESS) {
m_Entries.Append(entry_sample_index);
}
}
@@ -92,13 +90,12 @@ AP4_StssAtom::WriteFields(AP4_ByteStream& stream)
// entry count
AP4_Cardinal entry_count = m_Entries.ItemCount();
result = stream.WriteUI32(entry_count);
- if(AP4_FAILED(result)) return result;
+ if (AP4_FAILED(result)) return result;
// entries
- for(AP4_Ordinal i = 0; i < entry_count; i++)
- {
+ for (AP4_Ordinal i=0; i<entry_count; i++) {
result = stream.WriteUI32(m_Entries[i]);
- if(AP4_FAILED(result)) return result;
+ if (AP4_FAILED(result)) return result;
}
return result;
@@ -112,7 +109,7 @@ AP4_StssAtom::AddEntry(AP4_UI32 sample)
{
m_Entries.Append(sample);
m_Size32 += 4;
-
+
return AP4_SUCCESS;
}
@@ -125,24 +122,21 @@ AP4_StssAtom::IsSampleSync(AP4_Ordinal sample)
unsigned int entry_index = 0;
// check bounds
- if(sample == 0 || m_Entries.ItemCount() == 0) return false;
+ if (sample == 0 || m_Entries.ItemCount() == 0) return false;
// see if we can start from the cached index
- if(m_Entries[m_LookupCache] <= sample)
- {
+ if (m_Entries[m_LookupCache] <= sample) {
entry_index = m_LookupCache;
}
// do a linear search
- while(entry_index < m_Entries.ItemCount() &&
- m_Entries[entry_index] <= sample)
- {
- if(m_Entries[entry_index] == sample)
- {
+ while (entry_index < m_Entries.ItemCount() &&
+ m_Entries[entry_index] <= sample) {
+ if (m_Entries[entry_index] == sample) {
m_LookupCache = entry_index;
return true;
}
- entry_index++;
+ entry_index++;
}
return false;
@@ -158,4 +152,4 @@ AP4_StssAtom::InspectFields(AP4_AtomInspector& inspector)
return AP4_SUCCESS;
}
-
+
diff --git a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4StssAtom.h b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4StssAtom.h
index ccc4bf795..0384cb6a3 100644
--- a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4StssAtom.h
+++ b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4StssAtom.h
@@ -1,6 +1,6 @@
/*****************************************************************
|
-| AP4 - stss Atoms
+| AP4 - stss Atoms
|
| Copyright 2002-2008 Axiomatic Systems, LLC
|
@@ -48,13 +48,10 @@ public:
// constructor
AP4_StssAtom();
-
+
// methods
// methods
- const AP4_Array<AP4_UI32>& GetEntries()
- {
- return m_Entries;
- }
+ const AP4_Array<AP4_UI32>& GetEntries() { return m_Entries; }
AP4_Result AddEntry(AP4_UI32 sample);
virtual AP4_Result InspectFields(AP4_AtomInspector& inspector);
virtual bool IsSampleSync(AP4_Ordinal sample);
@@ -62,11 +59,11 @@ public:
private:
// methods
- AP4_StssAtom(AP4_UI32 size,
+ AP4_StssAtom(AP4_UI32 size,
AP4_UI32 version,
AP4_UI32 flags,
AP4_ByteStream& stream);
-
+
// members
AP4_Array<AP4_UI32> m_Entries;
AP4_Ordinal m_LookupCache;
diff --git a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4StszAtom.cpp b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4StszAtom.cpp
index 19f116346..97dfc9f91 100644
--- a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4StszAtom.cpp
+++ b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4StszAtom.cpp
@@ -1,6 +1,6 @@
/*****************************************************************
|
-| AP4 - stsz Atoms
+| AP4 - stsz Atoms
|
| Copyright 2002-2008 Axiomatic Systems, LLC
|
@@ -46,8 +46,8 @@ AP4_StszAtom::Create(AP4_Size size, AP4_ByteStream& stream)
{
AP4_UI32 version;
AP4_UI32 flags;
- if(AP4_FAILED(AP4_Atom::ReadFullHeader(stream, version, flags))) return NULL;
- if(version != 0) return NULL;
+ if (AP4_FAILED(AP4_Atom::ReadFullHeader(stream, version, flags))) return NULL;
+ if (version != 0) return NULL;
return new AP4_StszAtom(size, version, flags, stream);
}
@@ -55,7 +55,7 @@ AP4_StszAtom::Create(AP4_Size size, AP4_ByteStream& stream)
| AP4_StszAtom::AP4_StszAtom
+---------------------------------------------------------------------*/
AP4_StszAtom::AP4_StszAtom() :
- AP4_Atom(AP4_ATOM_TYPE_STSZ, AP4_FULL_ATOM_HEADER_SIZE + 8, 0, 0),
+ AP4_Atom(AP4_ATOM_TYPE_STSZ, AP4_FULL_ATOM_HEADER_SIZE+8, 0, 0),
m_SampleSize(0),
m_SampleCount(0)
{
@@ -64,7 +64,7 @@ AP4_StszAtom::AP4_StszAtom() :
/*----------------------------------------------------------------------
| AP4_StszAtom::AP4_StszAtom
+---------------------------------------------------------------------*/
-AP4_StszAtom::AP4_StszAtom(AP4_UI32 size,
+AP4_StszAtom::AP4_StszAtom(AP4_UI32 size,
AP4_UI32 version,
AP4_UI32 flags,
AP4_ByteStream& stream) :
@@ -72,19 +72,16 @@ AP4_StszAtom::AP4_StszAtom(AP4_UI32 size,
{
stream.ReadUI32(m_SampleSize);
stream.ReadUI32(m_SampleCount);
- if(m_SampleSize == 0) // means that the samples have different sizes
- {
+ if (m_SampleSize == 0) { // means that the samples have different sizes
unsigned long sample_count = m_SampleCount;
m_Entries.SetItemCount(sample_count);
unsigned char* buffer = new unsigned char[sample_count*4];
- AP4_Result result = stream.Read(buffer, sample_count * 4);
- if(AP4_FAILED(result))
- {
+ AP4_Result result = stream.Read(buffer, sample_count*4);
+ if (AP4_FAILED(result)) {
delete[] buffer;
return;
}
- for(unsigned int i = 0; i < sample_count; i++)
- {
+ for (unsigned int i=0; i<sample_count; i++) {
m_Entries[i] = AP4_BytesToUInt32BE(&buffer[i*4]);
}
delete[] buffer;
@@ -101,19 +98,17 @@ AP4_StszAtom::WriteFields(AP4_ByteStream& stream)
// sample size
result = stream.WriteUI32(m_SampleSize);
- if(AP4_FAILED(result)) return result;
+ if (AP4_FAILED(result)) return result;
// sample count
result = stream.WriteUI32(m_SampleCount);
- if(AP4_FAILED(result)) return result;
+ if (AP4_FAILED(result)) return result;
// entries if needed (the samples have different sizes)
- if(m_SampleSize == 0)
- {
- for(AP4_UI32 i = 0; i < m_SampleCount; i++)
- {
+ if (m_SampleSize == 0) {
+ for (AP4_UI32 i=0; i<m_SampleCount; i++) {
result = stream.WriteUI32(m_Entries[i]);
- if(AP4_FAILED(result)) return result;
+ if (AP4_FAILED(result)) return result;
}
}
@@ -136,20 +131,14 @@ AP4_Result
AP4_StszAtom::GetSampleSize(AP4_Ordinal sample, AP4_Size& sample_size)
{
// check the sample index
- if(sample > m_SampleCount || sample == 0)
- {
+ if (sample > m_SampleCount || sample == 0) {
sample_size = 0;
return AP4_ERROR_OUT_OF_RANGE;
- }
- else
- {
+ } else {
// find the size
- if(m_SampleSize != 0) // constant size
- {
+ if (m_SampleSize != 0) { // constant size
sample_size = m_SampleSize;
- }
- else
- {
+ } else {
sample_size = m_Entries[sample - 1];
}
return AP4_SUCCESS;
@@ -163,33 +152,23 @@ AP4_Result
AP4_StszAtom::SetSampleSize(AP4_Ordinal sample, AP4_Size sample_size)
{
// check the sample index
- if(sample > m_SampleCount || sample == 0)
- {
+ if (sample > m_SampleCount || sample == 0) {
return AP4_ERROR_OUT_OF_RANGE;
- }
- else
- {
- if(m_Entries.ItemCount() == 0)
- {
+ } else {
+ if (m_Entries.ItemCount() == 0) {
// all samples must have the same size
- if(sample_size != m_SampleSize)
- {
+ if (sample_size != m_SampleSize) {
// not the same
- if(sample == 1)
- {
+ if (sample == 1) {
// if this is the first sample, update the global size
m_SampleSize = sample_size;
return AP4_SUCCESS;
- }
- else
- {
+ } else {
// can't have different sizes
return AP4_ERROR_INVALID_PARAMETERS;
}
}
- }
- else
- {
+ } else {
// each sample has a different size
m_Entries[sample - 1] = sample_size;
}
@@ -201,7 +180,7 @@ AP4_StszAtom::SetSampleSize(AP4_Ordinal sample, AP4_Size sample_size)
/*----------------------------------------------------------------------
| AP4_StszAtom::AddEntry
+---------------------------------------------------------------------*/
-AP4_Result
+AP4_Result
AP4_StszAtom::AddEntry(AP4_UI32 size)
{
m_Entries.Append(size);
@@ -220,11 +199,9 @@ AP4_StszAtom::InspectFields(AP4_AtomInspector& inspector)
inspector.AddField("sample_size", m_SampleSize);
inspector.AddField("sample_count", m_Entries.ItemCount());
- if(inspector.GetVerbosity() >= 2)
- {
+ if (inspector.GetVerbosity() >= 2) {
char header[32];
- for(AP4_Ordinal i = 0; i < m_Entries.ItemCount(); i++)
- {
+ for (AP4_Ordinal i=0; i<m_Entries.ItemCount(); i++) {
AP4_FormatString(header, sizeof(header), "entry %8d", i);
inspector.AddField(header, m_Entries[i]);
}
diff --git a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4StszAtom.h b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4StszAtom.h
index 70d480c46..70bfa9309 100644
--- a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4StszAtom.h
+++ b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4StszAtom.h
@@ -1,6 +1,6 @@
/*****************************************************************
|
-| AP4 - stsz Atoms
+| AP4 - stsz Atoms
|
| Copyright 2002-2008 Axiomatic Systems, LLC
|
@@ -51,7 +51,7 @@ public:
virtual AP4_Result InspectFields(AP4_AtomInspector& inspector);
virtual AP4_Result WriteFields(AP4_ByteStream& stream);
virtual AP4_UI32 GetSampleCount();
- virtual AP4_Result GetSampleSize(AP4_Ordinal sample,
+ virtual AP4_Result GetSampleSize(AP4_Ordinal sample,
AP4_Size& sample_size);
/**
* Set the sample size.
@@ -63,18 +63,18 @@ public:
* the global size, and calling with sample>1 will check that
* the value of sample_size is the same as the global size m_SampleSize.
*/
- virtual AP4_Result SetSampleSize(AP4_Ordinal sample,
+ virtual AP4_Result SetSampleSize(AP4_Ordinal sample,
AP4_Size sample_size);
virtual AP4_Result AddEntry(AP4_UI32 size);
- // ==> Start patch MPC
- // FIXME
- friend class AP4_AtomSampleTable;
- // <== End patch MPC
+ // ==> Start patch MPC
+ // FIXME
+ friend class AP4_AtomSampleTable;
+ // <== End patch MPC
private:
// methods
- AP4_StszAtom(AP4_UI32 size,
+ AP4_StszAtom(AP4_UI32 size,
AP4_UI32 version,
AP4_UI32 flags,
AP4_ByteStream& stream);
diff --git a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4SttsAtom.cpp b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4SttsAtom.cpp
index 4db29e8e6..15a8d8418 100644
--- a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4SttsAtom.cpp
+++ b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4SttsAtom.cpp
@@ -1,6 +1,6 @@
/*****************************************************************
|
-| AP4 - stts Atoms
+| AP4 - stts Atoms
|
| Copyright 2002-2008 Axiomatic Systems, LLC
|
@@ -46,8 +46,8 @@ AP4_SttsAtom::Create(AP4_Size size, AP4_ByteStream& stream)
{
AP4_UI32 version;
AP4_UI32 flags;
- if(AP4_FAILED(AP4_Atom::ReadFullHeader(stream, version, flags))) return NULL;
- if(version != 0) return NULL;
+ if (AP4_FAILED(AP4_Atom::ReadFullHeader(stream, version, flags))) return NULL;
+ if (version != 0) return NULL;
return new AP4_SttsAtom(size, version, flags, stream);
}
@@ -55,7 +55,7 @@ AP4_SttsAtom::Create(AP4_Size size, AP4_ByteStream& stream)
| AP4_SttsAtom::AP4_SttsAtom
+---------------------------------------------------------------------*/
AP4_SttsAtom::AP4_SttsAtom() :
- AP4_Atom(AP4_ATOM_TYPE_STTS, AP4_FULL_ATOM_HEADER_SIZE + 4, 0, 0)
+ AP4_Atom(AP4_ATOM_TYPE_STTS, AP4_FULL_ATOM_HEADER_SIZE+4, 0, 0)
{
m_LookupCache.entry_index = 0;
m_LookupCache.sample = 0;
@@ -65,7 +65,7 @@ AP4_SttsAtom::AP4_SttsAtom() :
/*----------------------------------------------------------------------
| AP4_SttsAtom::AP4_SttsAtom
+---------------------------------------------------------------------*/
-AP4_SttsAtom::AP4_SttsAtom(AP4_UI32 size,
+AP4_SttsAtom::AP4_SttsAtom(AP4_UI32 size,
AP4_UI32 version,
AP4_UI32 flags,
AP4_ByteStream& stream) :
@@ -77,13 +77,11 @@ AP4_SttsAtom::AP4_SttsAtom(AP4_UI32 size,
AP4_UI32 entry_count;
stream.ReadUI32(entry_count);
- while(entry_count--)
- {
+ while (entry_count--) {
AP4_UI32 sample_count;
AP4_UI32 sample_duration;
- if(stream.ReadUI32(sample_count) == AP4_SUCCESS &&
- stream.ReadUI32(sample_duration) == AP4_SUCCESS)
- {
+ if (stream.ReadUI32(sample_count) == AP4_SUCCESS &&
+ stream.ReadUI32(sample_duration) == AP4_SUCCESS) {
m_Entries.Append(AP4_SttsTableEntry(sample_count,
sample_duration));
}
@@ -98,17 +96,16 @@ AP4_SttsAtom::GetDts(AP4_Ordinal sample, AP4_UI64& dts, AP4_UI32* duration)
{
// default value
dts = 0;
- if(duration) *duration = 0;
-
+ if (duration) *duration = 0;
+
// sample indexes start at 1
- if(sample == 0) return AP4_ERROR_OUT_OF_RANGE;
+ if (sample == 0) return AP4_ERROR_OUT_OF_RANGE;
// check the lookup cache
AP4_Ordinal lookup_start = 0;
AP4_Ordinal sample_start = 0;
AP4_UI64 dts_start = 0;
- if(sample >= m_LookupCache.sample)
- {
+ if (sample >= m_LookupCache.sample) {
// start from the cached entry
lookup_start = m_LookupCache.entry_index;
sample_start = m_LookupCache.sample;
@@ -116,28 +113,26 @@ AP4_SttsAtom::GetDts(AP4_Ordinal sample, AP4_UI64& dts, AP4_UI32* duration)
}
// look from the last known point
- for(AP4_Ordinal i = lookup_start; i < m_Entries.ItemCount(); i++)
- {
+ for (AP4_Ordinal i = lookup_start; i < m_Entries.ItemCount(); i++) {
AP4_SttsTableEntry& entry = m_Entries[i];
// check if we have reached the sample
- if(sample <= sample_start + entry.m_SampleCount)
- {
+ if (sample <= sample_start+entry.m_SampleCount) {
// we are within the sample range for the current entry
- dts = dts_start + (AP4_UI64)(sample - 1 - sample_start) * (AP4_UI64)entry.m_SampleDuration;
- if(duration) *duration = entry.m_SampleDuration;
-
+ dts = dts_start + (AP4_UI64)(sample-1 - sample_start) * (AP4_UI64)entry.m_SampleDuration;
+ if (duration) *duration = entry.m_SampleDuration;
+
// update the lookup cache
m_LookupCache.entry_index = i;
m_LookupCache.sample = sample_start;
m_LookupCache.dts = dts_start;
-
+
return AP4_SUCCESS;
}
-
+
// update the sample and dts bases
sample_start += entry.m_SampleCount;
- dts_start += entry.m_SampleCount * entry.m_SampleDuration;
+ dts_start += entry.m_SampleCount*entry.m_SampleDuration;
}
// sample is greater than the number of samples
@@ -167,18 +162,17 @@ AP4_SttsAtom::WriteFields(AP4_ByteStream& stream)
// write the entry count
AP4_Cardinal entry_count = m_Entries.ItemCount();
result = stream.WriteUI32(entry_count);
- if(AP4_FAILED(result)) return result;
+ if (AP4_FAILED(result)) return result;
// write the entries
- for(AP4_Ordinal i = 0; i < entry_count; i++)
- {
+ for (AP4_Ordinal i=0; i<entry_count; i++) {
// sample count
result = stream.WriteUI32(m_Entries[i].m_SampleCount);
- if(AP4_FAILED(result)) return result;
+ if (AP4_FAILED(result)) return result;
// time offset
result = stream.WriteUI32(m_Entries[i].m_SampleDuration);
- if(AP4_FAILED(result)) return result;
+ if (AP4_FAILED(result)) return result;
}
return AP4_SUCCESS;
@@ -188,24 +182,22 @@ AP4_SttsAtom::WriteFields(AP4_ByteStream& stream)
| AP4_SttsAtom::GetSampleIndexForTimeStamp
+---------------------------------------------------------------------*/
AP4_Result
-AP4_SttsAtom::GetSampleIndexForTimeStamp(AP4_UI64 ts,
- AP4_Ordinal& sample_index)
+AP4_SttsAtom::GetSampleIndexForTimeStamp(AP4_UI64 ts,
+ AP4_Ordinal& sample_index)
{
// init
AP4_Cardinal entry_count = m_Entries.ItemCount();
AP4_UI64 accumulated = 0;
sample_index = 0;
-
- for(AP4_Ordinal i = 0; i < entry_count; i++)
- {
- AP4_UI64 next_accumulated =
+
+ for (AP4_Ordinal i=0; i<entry_count; i++) {
+ AP4_UI64 next_accumulated =
accumulated +
- (AP4_UI64)m_Entries[i].m_SampleCount *
+ (AP4_UI64)m_Entries[i].m_SampleCount *
(AP4_UI64)m_Entries[i].m_SampleDuration;
-
+
// check if the ts is in the range of this entry
- if(ts < next_accumulated)
- {
+ if (ts < next_accumulated) {
sample_index += (AP4_UI32)((ts - accumulated) / m_Entries[i].m_SampleDuration);
return AP4_SUCCESS;
}
@@ -227,17 +219,15 @@ AP4_SttsAtom::InspectFields(AP4_AtomInspector& inspector)
{
inspector.AddField("entry_count", m_Entries.ItemCount());
- if(inspector.GetVerbosity() >= 1)
- {
+ if (inspector.GetVerbosity() >= 1) {
char header[32];
char value[256];
- for(AP4_Ordinal i = 0; i < m_Entries.ItemCount(); i++)
- {
+ for (AP4_Ordinal i=0; i<m_Entries.ItemCount(); i++) {
AP4_FormatString(header, sizeof(header), "entry %8d", i);
- AP4_FormatString(value, sizeof(value),
- "sample_count=%d, sample_duration=%d",
- m_Entries[i].m_SampleCount,
- m_Entries[i].m_SampleDuration);
+ AP4_FormatString(value, sizeof(value),
+ "sample_count=%d, sample_duration=%d",
+ m_Entries[i].m_SampleCount,
+ m_Entries[i].m_SampleDuration);
inspector.AddField(header, value);
}
}
diff --git a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4SttsAtom.h b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4SttsAtom.h
index 4f9784c85..def7acc37 100644
--- a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4SttsAtom.h
+++ b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4SttsAtom.h
@@ -1,6 +1,6 @@
/*****************************************************************
|
-| AP4 - stts Atoms
+| AP4 - stts Atoms
|
| Copyright 2002-2008 Axiomatic Systems, LLC
|
@@ -38,11 +38,10 @@
/*----------------------------------------------------------------------
| AP4_SttsTableEntry
+---------------------------------------------------------------------*/
-class AP4_SttsTableEntry
-{
-public:
- AP4_SttsTableEntry() :
- m_SampleCount(0),
+class AP4_SttsTableEntry {
+ public:
+ AP4_SttsTableEntry() :
+ m_SampleCount(0),
m_SampleDuration(0) {}
AP4_SttsTableEntry(AP4_UI32 sample_count,
AP4_UI32 sample_duration) :
@@ -69,26 +68,25 @@ public:
virtual AP4_Result InspectFields(AP4_AtomInspector& inspector);
virtual AP4_Result GetDts(AP4_Ordinal sample, AP4_UI64& dts, AP4_UI32* duration = NULL);
virtual AP4_Result AddEntry(AP4_UI32 sample_count, AP4_UI32 sample_duration);
- virtual AP4_Result GetSampleIndexForTimeStamp(AP4_UI64 ts,
- AP4_Ordinal& sample_index);
+ virtual AP4_Result GetSampleIndexForTimeStamp(AP4_UI64 ts,
+ AP4_Ordinal& sample_index);
virtual AP4_Result WriteFields(AP4_ByteStream& stream);
- // ==> Start patch MPC
- // FIXME
- friend class AP4_AtomSampleTable;
- // <== End patch MPC
+ // ==> Start patch MPC
+ // FIXME
+ friend class AP4_AtomSampleTable;
+ // <== End patch MPC
private:
// methods
- AP4_SttsAtom(AP4_UI32 size,
+ AP4_SttsAtom(AP4_UI32 size,
AP4_UI32 version,
AP4_UI32 flags,
AP4_ByteStream& stream);
// members
AP4_Array<AP4_SttsTableEntry> m_Entries;
- struct
- {
+ struct {
AP4_Ordinal entry_index;
AP4_Ordinal sample;
AP4_UI64 dts;
diff --git a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4SyntheticSampleTable.cpp b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4SyntheticSampleTable.cpp
index 492c045c2..b2926e4ac 100644
--- a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4SyntheticSampleTable.cpp
+++ b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4SyntheticSampleTable.cpp
@@ -38,7 +38,7 @@
| AP4_SyntheticSampleTable::AP4_SyntheticSampleTable()
+---------------------------------------------------------------------*/
AP4_SyntheticSampleTable::AP4_SyntheticSampleTable(AP4_Cardinal chunk_size) :
- m_ChunkSize(chunk_size ? chunk_size : AP4_SYNTHETIC_SAMPLE_TABLE_DEFAULT_CHUNK_SIZE)
+ m_ChunkSize(chunk_size?chunk_size:AP4_SYNTHETIC_SAMPLE_TABLE_DEFAULT_CHUNK_SIZE)
{
m_LookupCache.m_Sample = 0;
m_LookupCache.m_Chunk = 0;
@@ -58,7 +58,7 @@ AP4_SyntheticSampleTable::~AP4_SyntheticSampleTable()
AP4_Result
AP4_SyntheticSampleTable::GetSample(AP4_Ordinal sample_index, AP4_Sample& sample)
{
- if(sample_index >= m_Samples.ItemCount()) return AP4_ERROR_OUT_OF_RANGE;
+ if (sample_index >= m_Samples.ItemCount()) return AP4_ERROR_OUT_OF_RANGE;
sample = m_Samples[sample_index];
return AP4_SUCCESS;
@@ -67,7 +67,7 @@ AP4_SyntheticSampleTable::GetSample(AP4_Ordinal sample_index, AP4_Sample& sample
/*----------------------------------------------------------------------
| AP4_SyntheticSampleTable::GetSampleCount
+---------------------------------------------------------------------*/
-AP4_Cardinal
+AP4_Cardinal
AP4_SyntheticSampleTable::GetSampleCount()
{
return m_Samples.ItemCount();
@@ -76,48 +76,45 @@ AP4_SyntheticSampleTable::GetSampleCount()
/*----------------------------------------------------------------------
| AP4_SyntheticSampleTable::GetSampleChunkPosition
+---------------------------------------------------------------------*/
-AP4_Result
+AP4_Result
AP4_SyntheticSampleTable::GetSampleChunkPosition(
- AP4_Ordinal sample_index,
+ AP4_Ordinal sample_index,
AP4_Ordinal& chunk_index,
AP4_Ordinal& position_in_chunk)
{
// default values
chunk_index = 0;
position_in_chunk = 0;
-
+
// check parameters
- if(sample_index >= m_Samples.ItemCount()) return AP4_ERROR_OUT_OF_RANGE;
-
- // look for the chunk
+ if (sample_index >= m_Samples.ItemCount()) return AP4_ERROR_OUT_OF_RANGE;
+
+ // look for the chunk
AP4_Ordinal sample_cursor = 0;
AP4_Ordinal chunk_cursor = 0;
- if(sample_index >= m_LookupCache.m_Sample)
- {
+ if (sample_index >= m_LookupCache.m_Sample) {
sample_cursor = m_LookupCache.m_Sample;
chunk_cursor = m_LookupCache.m_Chunk;
}
- for(;
- chunk_cursor < m_SamplesInChunk.ItemCount();
- sample_cursor += m_SamplesInChunk[chunk_cursor++])
- {
- if(sample_cursor + m_SamplesInChunk[chunk_cursor] > sample_index)
- {
+ for (;
+ chunk_cursor < m_SamplesInChunk.ItemCount();
+ sample_cursor += m_SamplesInChunk[chunk_cursor++]) {
+ if (sample_cursor+m_SamplesInChunk[chunk_cursor] > sample_index) {
chunk_index = chunk_cursor;
- position_in_chunk = sample_index - sample_cursor;
+ position_in_chunk = sample_index-sample_cursor;
m_LookupCache.m_Sample = sample_cursor;
m_LookupCache.m_Chunk = chunk_cursor;
return AP4_SUCCESS;
}
}
-
+
return AP4_ERROR_OUT_OF_RANGE;
}
/*----------------------------------------------------------------------
| AP4_SyntheticSampleTable::GetSampleDescriptionCount
+---------------------------------------------------------------------*/
-AP4_Cardinal
+AP4_Cardinal
AP4_SyntheticSampleTable::GetSampleDescriptionCount()
{
return m_SampleDescriptions.ItemCount();
@@ -126,16 +123,13 @@ AP4_SyntheticSampleTable::GetSampleDescriptionCount()
/*----------------------------------------------------------------------
| AP4_SyntheticSampleTable::GetSampleDescription
+---------------------------------------------------------------------*/
-AP4_SampleDescription*
+AP4_SampleDescription*
AP4_SyntheticSampleTable::GetSampleDescription(AP4_Ordinal index)
{
SampleDescriptionHolder* holder;
- if(AP4_SUCCEEDED(m_SampleDescriptions.Get(index, holder)))
- {
+ if (AP4_SUCCEEDED(m_SampleDescriptions.Get(index, holder))) {
return holder->m_SampleDescription;
- }
- else
- {
+ } else {
return NULL;
}
}
@@ -143,9 +137,9 @@ AP4_SyntheticSampleTable::GetSampleDescription(AP4_Ordinal index)
/*----------------------------------------------------------------------
| AP4_SyntheticSampleTable::AddSampleDescription
+---------------------------------------------------------------------*/
-AP4_Result
+AP4_Result
AP4_SyntheticSampleTable::AddSampleDescription(AP4_SampleDescription* description,
- bool transfer_ownership)
+ bool transfer_ownership)
{
return m_SampleDescriptions.Add(new SampleDescriptionHolder(description, transfer_ownership));
}
@@ -153,7 +147,7 @@ AP4_SyntheticSampleTable::AddSampleDescription(AP4_SampleDescription* descriptio
/*----------------------------------------------------------------------
| AP4_SyntheticSampleTable::AddSample
+---------------------------------------------------------------------*/
-AP4_Result
+AP4_Result
AP4_SyntheticSampleTable::AddSample(AP4_ByteStream& data_stream,
AP4_Position offset,
AP4_Size size,
@@ -164,50 +158,38 @@ AP4_SyntheticSampleTable::AddSample(AP4_ByteStream& data_stream,
bool sync)
{
// decide if we need to start a new chunk or increment the last one
- if(m_SamplesInChunk.ItemCount() == 0 ||
- m_SamplesInChunk[m_SamplesInChunk.ItemCount()-1] >= m_ChunkSize ||
- m_Samples.ItemCount() == 0 ||
- m_Samples[m_Samples.ItemCount()-1].GetDescriptionIndex() != description_index)
- {
+ if (m_SamplesInChunk.ItemCount() == 0 ||
+ m_SamplesInChunk[m_SamplesInChunk.ItemCount()-1] >= m_ChunkSize ||
+ m_Samples.ItemCount() == 0 ||
+ m_Samples[m_Samples.ItemCount()-1].GetDescriptionIndex() != description_index) {
m_SamplesInChunk.Append(1);
- }
- else
- {
+ } else {
++m_SamplesInChunk[m_SamplesInChunk.ItemCount()-1];
}
-
+
// compute the timestamps
- if(m_Samples.ItemCount() > 0)
- {
+ if (m_Samples.ItemCount() > 0) {
AP4_Sample* prev_sample = &m_Samples[m_Samples.ItemCount()-1];
- if(dts == 0)
- {
- if(prev_sample->GetDuration() == 0)
- {
+ if (dts == 0) {
+ if (prev_sample->GetDuration() == 0) {
// can't compute the DTS for this sample
return AP4_ERROR_INVALID_PARAMETERS;
}
- dts = prev_sample->GetDts() + prev_sample->GetDuration();
- }
- else
- {
- if(prev_sample->GetDuration() == 0)
- {
+ dts = prev_sample->GetDts()+prev_sample->GetDuration();
+ } else {
+ if (prev_sample->GetDuration() == 0) {
// update the previous sample
- if(dts <= prev_sample->GetDts()) return AP4_ERROR_INVALID_PARAMETERS;
- prev_sample->SetDuration((AP4_UI32)(dts - prev_sample->GetDts()));
- }
- else
- {
- if(dts != prev_sample->GetDts() + prev_sample->GetDuration())
- {
+ if (dts <= prev_sample->GetDts()) return AP4_ERROR_INVALID_PARAMETERS;
+ prev_sample->SetDuration((AP4_UI32)(dts-prev_sample->GetDts()));
+ } else {
+ if (dts != prev_sample->GetDts()+prev_sample->GetDuration()) {
// mismatch
return AP4_ERROR_INVALID_PARAMETERS;
}
}
}
}
-
+
// add the sample to the table
AP4_Sample sample(data_stream, offset, size, duration, description_index, dts, cts_delta, sync);
return m_Samples.Append(sample);
@@ -216,9 +198,9 @@ AP4_SyntheticSampleTable::AddSample(AP4_ByteStream& data_stream,
/*----------------------------------------------------------------------
| AP4_SyntheticSampleTable::GetSampleIndexForTimeStamp
+---------------------------------------------------------------------*/
-AP4_Result
-AP4_SyntheticSampleTable::GetSampleIndexForTimeStamp(AP4_UI64 /* ts */,
- AP4_Ordinal& /* index */)
+AP4_Result
+AP4_SyntheticSampleTable::GetSampleIndexForTimeStamp(AP4_UI64 /* ts */,
+ AP4_Ordinal& /* index */)
{
return AP4_ERROR_NOT_SUPPORTED;
}
@@ -226,24 +208,19 @@ AP4_SyntheticSampleTable::GetSampleIndexForTimeStamp(AP4_UI64 /* ts */,
/*----------------------------------------------------------------------
| AP4_SyntheticSampleTable::GetNearestSyncSampleIndex
+---------------------------------------------------------------------*/
-AP4_Ordinal
+AP4_Ordinal
AP4_SyntheticSampleTable::GetNearestSyncSampleIndex(AP4_Ordinal sample_index, bool before)
{
- if(before)
- {
- for(int i = sample_index; i >= 0; i--)
- {
- if(m_Samples[i].IsSync()) return i;
+ if (before) {
+ for (int i=sample_index; i>=0; i--) {
+ if (m_Samples[i].IsSync()) return i;
}
// not found?
return 0;
- }
- else
- {
+ } else {
AP4_Cardinal entry_count = m_Samples.ItemCount();
- for(unsigned int i = sample_index; i < entry_count; i++)
- {
- if(m_Samples[i].IsSync()) return i;
+ for (unsigned int i=sample_index; i<entry_count; i++) {
+ if (m_Samples[i].IsSync()) return i;
}
// not found?
return m_Samples.ItemCount();
diff --git a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4SyntheticSampleTable.h b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4SyntheticSampleTable.h
index 9f9ba4d6b..e54d9074d 100644
--- a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4SyntheticSampleTable.h
+++ b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4SyntheticSampleTable.h
@@ -53,18 +53,18 @@ const AP4_Cardinal AP4_SYNTHETIC_SAMPLE_TABLE_DEFAULT_CHUNK_SIZE = 10;
+---------------------------------------------------------------------*/
class AP4_SyntheticSampleTable : public AP4_SampleTable
{
-public:
+ public:
// methods
- AP4_SyntheticSampleTable(AP4_Cardinal chunk_size
- = AP4_SYNTHETIC_SAMPLE_TABLE_DEFAULT_CHUNK_SIZE);
+ AP4_SyntheticSampleTable(AP4_Cardinal chunk_size
+ = AP4_SYNTHETIC_SAMPLE_TABLE_DEFAULT_CHUNK_SIZE);
virtual ~AP4_SyntheticSampleTable();
// AP4_SampleTable methods
virtual AP4_Result GetSample(AP4_Ordinal index, AP4_Sample& sample);
virtual AP4_Cardinal GetSampleCount();
- virtual AP4_Result GetSampleChunkPosition(AP4_Ordinal sample_index,
- AP4_Ordinal& chunk_index,
- AP4_Ordinal& position_in_chunk);
+ virtual AP4_Result GetSampleChunkPosition(AP4_Ordinal sample_index,
+ AP4_Ordinal& chunk_index,
+ AP4_Ordinal& position_in_chunk);
virtual AP4_Cardinal GetSampleDescriptionCount();
virtual AP4_SampleDescription* GetSampleDescription(AP4_Ordinal index);
virtual AP4_Result GetSampleIndexForTimeStamp(AP4_UI64 ts, AP4_Ordinal& index);
@@ -72,19 +72,19 @@ public:
// methods
/**
- * Add a sample description to the sample table.
+ * Add a sample description to the sample table.
* Each added sample description will have the next available index, starting at 0
*
* @param description Pointer to the sample description to add
* @param transfer_ownership Boolean flag indicating whether the ownership of the
* sample description object is transfered to the sample table object (true by default).
- * If true, the sample table object will own the sample description object, and will
- * delete it when it is itself deleted. If false, the ownership remains with the caller,
+ * If true, the sample table object will own the sample description object, and will
+ * delete it when it is itself deleted. If false, the ownership remains with the caller,
* and only a referencing pointer is kept, thus the caller must ensure that the object
* is not deleted before the sample table is deleted.
*/
virtual AP4_Result AddSampleDescription(AP4_SampleDescription* description,
- bool transfer_ownership = true);
+ bool transfer_ownership=true);
/**
* Add a sample to the sample table, where the sample duration is given
@@ -97,16 +97,16 @@ public:
* value can be 0 if the duration is not known. In that case, the next sample
* added to the table MUST have a non-zero value for the DTS (decoding timestamp),
* which will allow the actual duration of this sample to be computed.
- * @param description_index Index of the sample description that applies to
+ * @param description_index Index of the sample description that applies to
* this sample (typically 0).
* @param dts DTS (decoding timestamp) of the sample. If this value is 0, and there
- * already are samples in the table, the DTS of the sample will be automatically
+ * already are samples in the table, the DTS of the sample will be automatically
* computed based on the DTS and duration of the preceding sample. If this value is
- * not equal to the DTS+duration of the preceding sample, the duration of the
+ * not equal to the DTS+duration of the preceding sample, the duration of the
* preceding sample is automatically adjusted, unless it has a non-zero value, in which
* case AP4_ERROR_INVALID_PARAMETERS is returned.
* The DTS of the first sample in the table MUST always be 0.
- * @param cts_delta Difference between the CTS (composition/display timestamp) and DTS
+ * @param cts_delta Difference between the CTS (composition/display timestamp) and DTS
* (decoding timestamp) of the sample (in the timescale of the media)
* @param sync Boolean flag indicating whether this is a sync sample or not.
*/
@@ -121,26 +121,21 @@ public:
private:
// classes
- class SampleDescriptionHolder
- {
+ class SampleDescriptionHolder {
public:
SampleDescriptionHolder(AP4_SampleDescription* description, bool is_owned) :
m_SampleDescription(description), m_IsOwned(is_owned) {}
- ~SampleDescriptionHolder()
- {
- if(m_IsOwned) delete m_SampleDescription;
- }
+ ~SampleDescriptionHolder() { if (m_IsOwned) delete m_SampleDescription; }
AP4_SampleDescription* m_SampleDescription;
bool m_IsOwned;
};
-
+
// members
AP4_Array<AP4_Sample> m_Samples;
AP4_List<SampleDescriptionHolder> m_SampleDescriptions;
AP4_Cardinal m_ChunkSize;
AP4_Array<AP4_UI32> m_SamplesInChunk;
- struct
- {
+ struct {
AP4_Ordinal m_Sample;
AP4_Ordinal m_Chunk;
} m_LookupCache;
diff --git a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4TfhdAtom.cpp b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4TfhdAtom.cpp
index 7daa6af08..678e6ccb3 100644
--- a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4TfhdAtom.cpp
+++ b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4TfhdAtom.cpp
@@ -1,6 +1,6 @@
/*****************************************************************
|
-| AP4 - tfhd Atoms
+| AP4 - tfhd Atoms
|
| Copyright 2002-2008 Axiomatic Systems, LLC
|
@@ -45,31 +45,31 @@ AP4_TfhdAtom::Create(AP4_Size size, AP4_ByteStream& stream)
{
AP4_UI32 version;
AP4_UI32 flags;
- if(AP4_FAILED(AP4_Atom::ReadFullHeader(stream, version, flags))) return NULL;
- if(version > 0) return NULL;
- if(size != ComputeSize(flags)) return NULL;
+ if (AP4_FAILED(AP4_Atom::ReadFullHeader(stream, version, flags))) return NULL;
+ if (version > 0) return NULL;
+ if (size != ComputeSize(flags)) return NULL;
return new AP4_TfhdAtom(size, version, flags, stream);
}
/*----------------------------------------------------------------------
| AP4_TfhdAtom::ComputeSize
+---------------------------------------------------------------------*/
-AP4_UI32
+AP4_UI32
AP4_TfhdAtom::ComputeSize(AP4_UI32 flags)
{
- AP4_UI32 size = AP4_FULL_ATOM_HEADER_SIZE + 4;
- if(flags & AP4_TFHD_FLAG_BASE_DATA_OFFSET_PRESENT) size += 8;
- if(flags & AP4_TFHD_FLAG_SAMPLE_DESCRIPTION_INDEX_PRESENT) size += 4;
- if(flags & AP4_TFHD_FLAG_DEFAULT_SAMPLE_DURATION_PRESENT) size += 4;
- if(flags & AP4_TFHD_FLAG_DEFAULT_SAMPLE_SIZE_PRESENT) size += 4;
- if(flags & AP4_TFHD_FLAG_DEFAULT_SAMPLE_FLAGS_PRESENT) size += 4;
+ AP4_UI32 size = AP4_FULL_ATOM_HEADER_SIZE+4;
+ if (flags & AP4_TFHD_FLAG_BASE_DATA_OFFSET_PRESENT) size += 8;
+ if (flags & AP4_TFHD_FLAG_SAMPLE_DESCRIPTION_INDEX_PRESENT) size += 4;
+ if (flags & AP4_TFHD_FLAG_DEFAULT_SAMPLE_DURATION_PRESENT) size += 4;
+ if (flags & AP4_TFHD_FLAG_DEFAULT_SAMPLE_SIZE_PRESENT) size += 4;
+ if (flags & AP4_TFHD_FLAG_DEFAULT_SAMPLE_FLAGS_PRESENT) size += 4;
return size;
}
/*----------------------------------------------------------------------
| AP4_TfhdAtom::AP4_TfhdAtom
+---------------------------------------------------------------------*/
-AP4_TfhdAtom::AP4_TfhdAtom(AP4_UI32 flags,
+AP4_TfhdAtom::AP4_TfhdAtom(AP4_UI32 flags,
AP4_UI32 track_id,
AP4_UI64 base_data_offset,
AP4_UI32 sample_description_index,
@@ -89,31 +89,26 @@ AP4_TfhdAtom::AP4_TfhdAtom(AP4_UI32 flags,
/*----------------------------------------------------------------------
| AP4_TfhdAtom::AP4_TfhdAtom
+---------------------------------------------------------------------*/
-AP4_TfhdAtom::AP4_TfhdAtom(AP4_UI32 size,
+AP4_TfhdAtom::AP4_TfhdAtom(AP4_UI32 size,
AP4_UI32 version,
AP4_UI32 flags,
AP4_ByteStream& stream) :
AP4_Atom(AP4_ATOM_TYPE_TFHD, size, version, flags)
{
stream.ReadUI32(m_TrackId);
- if(flags & AP4_TFHD_FLAG_BASE_DATA_OFFSET_PRESENT)
- {
+ if (flags & AP4_TFHD_FLAG_BASE_DATA_OFFSET_PRESENT) {
stream.ReadUI64(m_BaseDataOffset);
}
- if(flags & AP4_TFHD_FLAG_SAMPLE_DESCRIPTION_INDEX_PRESENT)
- {
+ if (flags & AP4_TFHD_FLAG_SAMPLE_DESCRIPTION_INDEX_PRESENT) {
stream.ReadUI32(m_SampleDescriptionIndex);
}
- if(flags & AP4_TFHD_FLAG_DEFAULT_SAMPLE_DURATION_PRESENT)
- {
+ if (flags & AP4_TFHD_FLAG_DEFAULT_SAMPLE_DURATION_PRESENT) {
stream.ReadUI32(m_DefaultSampleDuration);
}
- if(flags & AP4_TFHD_FLAG_DEFAULT_SAMPLE_SIZE_PRESENT)
- {
+ if (flags & AP4_TFHD_FLAG_DEFAULT_SAMPLE_SIZE_PRESENT) {
stream.ReadUI32(m_DefaultSampleSize);
}
- if(flags & AP4_TFHD_FLAG_DEFAULT_SAMPLE_FLAGS_PRESENT)
- {
+ if (flags & AP4_TFHD_FLAG_DEFAULT_SAMPLE_FLAGS_PRESENT) {
stream.ReadUI32(m_DefaultSampleFlags);
}
}
@@ -125,35 +120,30 @@ AP4_Result
AP4_TfhdAtom::WriteFields(AP4_ByteStream& stream)
{
AP4_Result result;
-
+
result = stream.WriteUI32(m_TrackId);
- if(AP4_FAILED(result)) return result;
- if(m_Flags & AP4_TFHD_FLAG_BASE_DATA_OFFSET_PRESENT)
- {
+ if (AP4_FAILED(result)) return result;
+ if (m_Flags & AP4_TFHD_FLAG_BASE_DATA_OFFSET_PRESENT) {
result = stream.WriteUI64(m_BaseDataOffset);
- if(AP4_FAILED(result)) return result;
+ if (AP4_FAILED(result)) return result;
}
- if(m_Flags & AP4_TFHD_FLAG_SAMPLE_DESCRIPTION_INDEX_PRESENT)
- {
+ if (m_Flags & AP4_TFHD_FLAG_SAMPLE_DESCRIPTION_INDEX_PRESENT) {
result = stream.WriteUI32(m_SampleDescriptionIndex);
- if(AP4_FAILED(result)) return result;
+ if (AP4_FAILED(result)) return result;
}
- if(m_Flags & AP4_TFHD_FLAG_DEFAULT_SAMPLE_DURATION_PRESENT)
- {
+ if (m_Flags & AP4_TFHD_FLAG_DEFAULT_SAMPLE_DURATION_PRESENT) {
stream.WriteUI32(m_DefaultSampleDuration);
- if(AP4_FAILED(result)) return result;
+ if (AP4_FAILED(result)) return result;
}
- if(m_Flags & AP4_TFHD_FLAG_DEFAULT_SAMPLE_SIZE_PRESENT)
- {
+ if (m_Flags & AP4_TFHD_FLAG_DEFAULT_SAMPLE_SIZE_PRESENT) {
stream.WriteUI32(m_DefaultSampleSize);
- if(AP4_FAILED(result)) return result;
+ if (AP4_FAILED(result)) return result;
}
- if(m_Flags & AP4_TFHD_FLAG_DEFAULT_SAMPLE_FLAGS_PRESENT)
- {
+ if (m_Flags & AP4_TFHD_FLAG_DEFAULT_SAMPLE_FLAGS_PRESENT) {
stream.WriteUI32(m_DefaultSampleFlags);
- if(AP4_FAILED(result)) return result;
+ if (AP4_FAILED(result)) return result;
}
-
+
return AP4_SUCCESS;
}
@@ -164,25 +154,20 @@ AP4_Result
AP4_TfhdAtom::InspectFields(AP4_AtomInspector& inspector)
{
inspector.AddField("track ID", m_TrackId);
- if(m_Flags & AP4_TFHD_FLAG_BASE_DATA_OFFSET_PRESENT)
- {
+ if (m_Flags & AP4_TFHD_FLAG_BASE_DATA_OFFSET_PRESENT) {
inspector.AddField("base data offset", m_BaseDataOffset);
}
- if(m_Flags & AP4_TFHD_FLAG_SAMPLE_DESCRIPTION_INDEX_PRESENT)
- {
+ if (m_Flags & AP4_TFHD_FLAG_SAMPLE_DESCRIPTION_INDEX_PRESENT) {
inspector.AddField("sample description index", m_SampleDescriptionIndex);
}
- if(m_Flags & AP4_TFHD_FLAG_DEFAULT_SAMPLE_DURATION_PRESENT)
- {
+ if (m_Flags & AP4_TFHD_FLAG_DEFAULT_SAMPLE_DURATION_PRESENT) {
inspector.AddField("default sample duration", m_DefaultSampleDuration);
}
- if(m_Flags & AP4_TFHD_FLAG_DEFAULT_SAMPLE_SIZE_PRESENT)
- {
+ if (m_Flags & AP4_TFHD_FLAG_DEFAULT_SAMPLE_SIZE_PRESENT) {
inspector.AddField("default sample size", m_DefaultSampleSize);
}
- if(m_Flags & AP4_TFHD_FLAG_DEFAULT_SAMPLE_FLAGS_PRESENT)
- {
- inspector.AddField("default sample flags", m_DefaultSampleFlags, AP4_AtomInspector::HINT_HEX);
+ if (m_Flags & AP4_TFHD_FLAG_DEFAULT_SAMPLE_FLAGS_PRESENT) {
+ inspector.AddField("default sample flags", m_DefaultSampleFlags, AP4_AtomInspector::HINT_HEX );
}
return AP4_SUCCESS;
diff --git a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4TfhdAtom.h b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4TfhdAtom.h
index 6fba18062..db0d3f777 100644
--- a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4TfhdAtom.h
+++ b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4TfhdAtom.h
@@ -1,6 +1,6 @@
/*****************************************************************
|
-| AP4 - tfhd Atoms
+| AP4 - tfhd Atoms
|
| Copyright 2002-2008 Axiomatic Systems, LLC
|
@@ -57,7 +57,7 @@ public:
static AP4_UI32 ComputeSize(AP4_UI32 flags);
// methods
- AP4_TfhdAtom(AP4_UI32 flags,
+ AP4_TfhdAtom(AP4_UI32 flags,
AP4_UI32 track_id,
AP4_UI64 base_data_offset,
AP4_UI32 sample_description_index,
@@ -67,58 +67,22 @@ public:
virtual AP4_Result InspectFields(AP4_AtomInspector& inspector);
virtual AP4_Result WriteFields(AP4_ByteStream& stream);
- AP4_UI32 GetTrackId()
- {
- return m_TrackId;
- }
- void SetTrackId(AP4_UI32 track_id)
- {
- m_TrackId = track_id;
- }
- AP4_UI64 GetBaseDataOffset()
- {
- return m_BaseDataOffset;
- }
- void SetBaseDataOffset(AP4_UI64 offset)
- {
- m_BaseDataOffset = offset;
- }
- AP4_UI32 GetSampleDescriptionIndex()
- {
- return m_SampleDescriptionIndex;
- }
- void SetSampleDescriptionIndex(AP4_UI32 indx)
- {
- m_SampleDescriptionIndex = indx;
- }
- AP4_UI32 GetDefaultSampleDuration()
- {
- return m_DefaultSampleDuration;
- }
- void SetDefaultSampleDuration(AP4_UI32 duration)
- {
- m_DefaultSampleDuration = duration;
- }
- AP4_UI32 GetDefaultSampleSize()
- {
- return m_DefaultSampleSize;
- }
- void SetDefaultSampleSize(AP4_UI32 size)
- {
- m_DefaultSampleSize = size;
- }
- AP4_UI32 GetDefaultSampleFlags()
- {
- return m_DefaultSampleFlags;
- }
- void SetDefaultSampleFlags(AP4_UI32 flags)
- {
- m_DefaultSampleFlags = flags;
- }
+ AP4_UI32 GetTrackId() { return m_TrackId; }
+ void SetTrackId(AP4_UI32 track_id) { m_TrackId = track_id; }
+ AP4_UI64 GetBaseDataOffset() { return m_BaseDataOffset; }
+ void SetBaseDataOffset(AP4_UI64 offset) { m_BaseDataOffset = offset; }
+ AP4_UI32 GetSampleDescriptionIndex() { return m_SampleDescriptionIndex; }
+ void SetSampleDescriptionIndex(AP4_UI32 indx) { m_SampleDescriptionIndex = indx; }
+ AP4_UI32 GetDefaultSampleDuration() { return m_DefaultSampleDuration; }
+ void SetDefaultSampleDuration(AP4_UI32 duration) { m_DefaultSampleDuration = duration; }
+ AP4_UI32 GetDefaultSampleSize() { return m_DefaultSampleSize; }
+ void SetDefaultSampleSize(AP4_UI32 size) { m_DefaultSampleSize = size; }
+ AP4_UI32 GetDefaultSampleFlags() { return m_DefaultSampleFlags; }
+ void SetDefaultSampleFlags(AP4_UI32 flags) { m_DefaultSampleFlags = flags; }
private:
// methods
- AP4_TfhdAtom(AP4_UI32 size,
+ AP4_TfhdAtom(AP4_UI32 size,
AP4_UI32 version,
AP4_UI32 flags,
AP4_ByteStream& stream);
diff --git a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4TfraAtom.cpp b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4TfraAtom.cpp
index 2aa930892..1c5437128 100644
--- a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4TfraAtom.cpp
+++ b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4TfraAtom.cpp
@@ -1,6 +1,6 @@
/*****************************************************************
|
-| AP4 - tfra Atoms
+| AP4 - tfra Atoms
|
| Copyright 2002-2008 Axiomatic Systems, LLC
|
@@ -36,14 +36,14 @@
/*----------------------------------------------------------------------
| AP4_TfraAtom::Create
+---------------------------------------------------------------------*/
-AP4_TfraAtom*
+AP4_TfraAtom*
AP4_TfraAtom::Create(AP4_Size size, AP4_ByteStream& stream)
{
AP4_UI32 version = 0;
AP4_UI32 flags = 0;
AP4_Result result = ReadFullHeader(stream, version, flags);
- if(AP4_FAILED(result)) return NULL;
- if(version > 1) return NULL;
+ if (AP4_FAILED(result)) return NULL;
+ if (version > 1) return NULL;
return new AP4_TfraAtom(size, version, flags, stream);
}
@@ -51,37 +51,33 @@ AP4_TfraAtom::Create(AP4_Size size, AP4_ByteStream& stream)
| AP4_TfraAtom::AP4_TfraAtom
+---------------------------------------------------------------------*/
AP4_TfraAtom::AP4_TfraAtom() :
- AP4_Atom(AP4_ATOM_TYPE_TFRA, AP4_FULL_ATOM_HEADER_SIZE + 4 + 4 + 4)
+ AP4_Atom(AP4_ATOM_TYPE_TFRA, AP4_FULL_ATOM_HEADER_SIZE+4+4+4)
{
}
/*----------------------------------------------------------------------
| AP4_TfraAtom::AP4_TfraAtom
+---------------------------------------------------------------------*/
-AP4_TfraAtom::AP4_TfraAtom(AP4_UI32 size,
- AP4_UI32 version,
- AP4_UI32 flags,
+AP4_TfraAtom::AP4_TfraAtom(AP4_UI32 size,
+ AP4_UI32 version,
+ AP4_UI32 flags,
AP4_ByteStream& stream) :
AP4_Atom(AP4_ATOM_TYPE_TFRA, size, version, flags)
{
stream.ReadUI32(m_TrackId);
AP4_UI32 fields = 0;
stream.ReadUI32(fields);
- m_LengthSizeOfTrafNumber = (fields >> 4) & 3;
- m_LengthSizeOfTrunNumber = (fields >> 2) & 3;
- m_LengthSizeOfSampleNumber = (fields) & 3;
+ m_LengthSizeOfTrafNumber = (fields>>4)&3;
+ m_LengthSizeOfTrunNumber = (fields>>2)&3;
+ m_LengthSizeOfSampleNumber = (fields )&3;
AP4_UI32 entry_count = 0;
stream.ReadUI32(entry_count);
m_Entries.SetItemCount(entry_count);
- for(unsigned int i = 0; i < entry_count; i++)
- {
- if(version == 1)
- {
+ for (unsigned int i=0; i<entry_count; i++) {
+ if (version == 1) {
stream.ReadUI64(m_Entries[i].m_Time);
stream.ReadUI64(m_Entries[i].m_MoofOffset);
- }
- else
- {
+ } else {
AP4_UI32 time = 0;
AP4_UI32 moof_offset = 0;
stream.ReadUI32(time);
@@ -89,101 +85,86 @@ AP4_TfraAtom::AP4_TfraAtom(AP4_UI32 size,
m_Entries[i].m_Time = time;
m_Entries[i].m_MoofOffset = moof_offset;
}
- switch(m_LengthSizeOfTrafNumber)
- {
- case 0:
- {
- AP4_UI08 traf_number;
- stream.ReadUI08(traf_number);
- m_Entries[i].m_TrafNumber = traf_number;
- break;
- }
- case 1:
- {
- AP4_UI16 traf_number;
- stream.ReadUI16(traf_number);
- m_Entries[i].m_TrafNumber = traf_number;
- break;
- }
- case 2:
- {
- AP4_UI32 traf_number;
- stream.ReadUI24(traf_number);
- m_Entries[i].m_TrafNumber = traf_number;
- break;
- }
- case 3:
- {
- AP4_UI32 traf_number;
- stream.ReadUI32(traf_number);
- m_Entries[i].m_TrafNumber = traf_number;
- break;
- }
- }
-
- switch(m_LengthSizeOfTrunNumber)
- {
- case 0:
- {
- AP4_UI08 trun_number;
- stream.ReadUI08(trun_number);
- m_Entries[i].m_TrunNumber = trun_number;
- break;
- }
- case 1:
- {
- AP4_UI16 trun_number;
- stream.ReadUI16(trun_number);
- m_Entries[i].m_TrunNumber = trun_number;
- break;
- }
- case 2:
- {
- AP4_UI32 trun_number;
- stream.ReadUI24(trun_number);
- m_Entries[i].m_TrunNumber = trun_number;
- break;
- }
- case 3:
- {
- AP4_UI32 trun_number;
- stream.ReadUI32(trun_number);
- m_Entries[i].m_TrunNumber = trun_number;
- break;
- }
- }
-
- switch(m_LengthSizeOfSampleNumber)
- {
- case 0:
- {
- AP4_UI08 sample_number;
- stream.ReadUI08(sample_number);
- m_Entries[i].m_SampleNumber = sample_number;
- break;
- }
- case 1:
- {
- AP4_UI16 sample_number;
- stream.ReadUI16(sample_number);
- m_Entries[i].m_SampleNumber = sample_number;
- break;
- }
- case 2:
- {
- AP4_UI32 sample_number;
- stream.ReadUI24(sample_number);
- m_Entries[i].m_SampleNumber = sample_number;
- break;
- }
- case 3:
- {
- AP4_UI32 sample_number;
- stream.ReadUI32(sample_number);
- m_Entries[i].m_SampleNumber = sample_number;
- break;
+ switch (m_LengthSizeOfTrafNumber) {
+ case 0: {
+ AP4_UI08 traf_number;
+ stream.ReadUI08(traf_number);
+ m_Entries[i].m_TrafNumber = traf_number;
+ break;
+ }
+ case 1: {
+ AP4_UI16 traf_number;
+ stream.ReadUI16(traf_number);
+ m_Entries[i].m_TrafNumber = traf_number;
+ break;
+ }
+ case 2: {
+ AP4_UI32 traf_number;
+ stream.ReadUI24(traf_number);
+ m_Entries[i].m_TrafNumber = traf_number;
+ break;
+ }
+ case 3: {
+ AP4_UI32 traf_number;
+ stream.ReadUI32(traf_number);
+ m_Entries[i].m_TrafNumber = traf_number;
+ break;
+ }
}
+
+ switch (m_LengthSizeOfTrunNumber) {
+ case 0: {
+ AP4_UI08 trun_number;
+ stream.ReadUI08(trun_number);
+ m_Entries[i].m_TrunNumber = trun_number;
+ break;
+ }
+ case 1: {
+ AP4_UI16 trun_number;
+ stream.ReadUI16(trun_number);
+ m_Entries[i].m_TrunNumber = trun_number;
+ break;
+ }
+ case 2: {
+ AP4_UI32 trun_number;
+ stream.ReadUI24(trun_number);
+ m_Entries[i].m_TrunNumber = trun_number;
+ break;
+ }
+ case 3: {
+ AP4_UI32 trun_number;
+ stream.ReadUI32(trun_number);
+ m_Entries[i].m_TrunNumber = trun_number;
+ break;
+ }
}
+
+ switch (m_LengthSizeOfSampleNumber) {
+ case 0: {
+ AP4_UI08 sample_number;
+ stream.ReadUI08(sample_number);
+ m_Entries[i].m_SampleNumber = sample_number;
+ break;
+ }
+ case 1: {
+ AP4_UI16 sample_number;
+ stream.ReadUI16(sample_number);
+ m_Entries[i].m_SampleNumber = sample_number;
+ break;
+ }
+ case 2: {
+ AP4_UI32 sample_number;
+ stream.ReadUI24(sample_number);
+ m_Entries[i].m_SampleNumber = sample_number;
+ break;
+ }
+ case 3: {
+ AP4_UI32 sample_number;
+ stream.ReadUI32(sample_number);
+ m_Entries[i].m_SampleNumber = sample_number;
+ break;
+ }
+ }
}
}
@@ -196,100 +177,93 @@ AP4_TfraAtom::WriteFields(AP4_ByteStream& stream)
AP4_Result result;
result = stream.WriteUI32(m_TrackId);
- if(AP4_FAILED(result)) return result;
- AP4_UI32 fields = (m_LengthSizeOfTrafNumber << 4) |
- (m_LengthSizeOfTrunNumber << 2) |
- (m_LengthSizeOfSampleNumber);
+ if (AP4_FAILED(result)) return result;
+ AP4_UI32 fields = (m_LengthSizeOfTrafNumber<<4)|
+ (m_LengthSizeOfTrunNumber<<2)|
+ (m_LengthSizeOfSampleNumber );
result = stream.WriteUI32(fields);
- if(AP4_FAILED(result)) return result;
+ if (AP4_FAILED(result)) return result;
result = stream.WriteUI32(m_Entries.ItemCount());
- for(unsigned int i = 0; i < m_Entries.ItemCount(); i++)
- {
- if(m_Version == 1)
- {
+ for (unsigned int i=0; i<m_Entries.ItemCount(); i++) {
+ if (m_Version == 1) {
result = stream.WriteUI64(m_Entries[i].m_Time);
- if(AP4_FAILED(result)) return result;
+ if (AP4_FAILED(result)) return result;
result = stream.WriteUI64(m_Entries[i].m_MoofOffset);
- if(AP4_FAILED(result)) return result;
- }
- else
- {
+ if (AP4_FAILED(result)) return result;
+ } else {
result = stream.WriteUI32((AP4_UI32)m_Entries[i].m_Time);
- if(AP4_FAILED(result)) return result;
+ if (AP4_FAILED(result)) return result;
result = stream.WriteUI32((AP4_UI32)m_Entries[i].m_MoofOffset);
- if(AP4_FAILED(result)) return result;
+ if (AP4_FAILED(result)) return result;
}
- switch(m_LengthSizeOfTrafNumber)
- {
- case 0:
- result = stream.WriteUI08((AP4_UI08)m_Entries[i].m_TrafNumber);
- if(AP4_FAILED(result)) return result;
- break;
+ switch (m_LengthSizeOfTrafNumber) {
+ case 0:
+ result = stream.WriteUI08((AP4_UI08)m_Entries[i].m_TrafNumber);
+ if (AP4_FAILED(result)) return result;
+ break;
- case 1:
- result = stream.WriteUI16((AP4_UI16)m_Entries[i].m_TrafNumber);
- if(AP4_FAILED(result)) return result;
- break;
+ case 1:
+ result = stream.WriteUI16((AP4_UI16)m_Entries[i].m_TrafNumber);
+ if (AP4_FAILED(result)) return result;
+ break;
- case 2:
- result = stream.WriteUI24(m_Entries[i].m_TrafNumber);
- if(AP4_FAILED(result)) return result;
- break;
+ case 2:
+ result = stream.WriteUI24(m_Entries[i].m_TrafNumber);
+ if (AP4_FAILED(result)) return result;
+ break;
- case 3:
- result = stream.WriteUI32(m_Entries[i].m_TrafNumber);
- if(AP4_FAILED(result)) return result;
- break;
+ case 3:
+ result = stream.WriteUI32(m_Entries[i].m_TrafNumber);
+ if (AP4_FAILED(result)) return result;
+ break;
}
+
+ switch (m_LengthSizeOfTrunNumber) {
+ case 0:
+ result = stream.WriteUI08((AP4_UI08)m_Entries[i].m_TrunNumber);
+ if (AP4_FAILED(result)) return result;
+ break;
- switch(m_LengthSizeOfTrunNumber)
- {
- case 0:
- result = stream.WriteUI08((AP4_UI08)m_Entries[i].m_TrunNumber);
- if(AP4_FAILED(result)) return result;
- break;
-
- case 1:
- result = stream.WriteUI16((AP4_UI16)m_Entries[i].m_TrunNumber);
- if(AP4_FAILED(result)) return result;
- break;
+ case 1:
+ result = stream.WriteUI16((AP4_UI16)m_Entries[i].m_TrunNumber);
+ if (AP4_FAILED(result)) return result;
+ break;
- case 2:
- result = stream.WriteUI24(m_Entries[i].m_TrunNumber);
- if(AP4_FAILED(result)) return result;
- break;
+ case 2:
+ result = stream.WriteUI24(m_Entries[i].m_TrunNumber);
+ if (AP4_FAILED(result)) return result;
+ break;
- case 3:
- result = stream.WriteUI32(m_Entries[i].m_TrunNumber);
- if(AP4_FAILED(result)) return result;
- break;
+ case 3:
+ result = stream.WriteUI32(m_Entries[i].m_TrunNumber);
+ if (AP4_FAILED(result)) return result;
+ break;
}
- switch(m_LengthSizeOfSampleNumber)
- {
- case 0:
- result = stream.WriteUI08((AP4_UI08)m_Entries[i].m_SampleNumber);
- if(AP4_FAILED(result)) return result;
- break;
+ switch (m_LengthSizeOfSampleNumber) {
+ case 0:
+ result = stream.WriteUI08((AP4_UI08)m_Entries[i].m_SampleNumber);
+ if (AP4_FAILED(result)) return result;
+ break;
- case 1:
- result = stream.WriteUI16((AP4_UI16)m_Entries[i].m_SampleNumber);
- if(AP4_FAILED(result)) return result;
- break;
+ case 1:
+ result = stream.WriteUI16((AP4_UI16)m_Entries[i].m_SampleNumber);
+ if (AP4_FAILED(result)) return result;
+ break;
- case 2:
- result = stream.WriteUI24(m_Entries[i].m_SampleNumber);
- if(AP4_FAILED(result)) return result;
- break;
+ case 2:
+ result = stream.WriteUI24(m_Entries[i].m_SampleNumber);
+ if (AP4_FAILED(result)) return result;
+ break;
- case 3:
- result = stream.WriteUI32(m_Entries[i].m_SampleNumber);
- if(AP4_FAILED(result)) return result;
- break;
+ case 3:
+ result = stream.WriteUI32(m_Entries[i].m_SampleNumber);
+ if (AP4_FAILED(result)) return result;
+ break;
}
}
-
+
return AP4_SUCCESS;
}
@@ -304,14 +278,12 @@ AP4_TfraAtom::InspectFields(AP4_AtomInspector& inspector)
inspector.AddField("length_size_of_trun_num", m_LengthSizeOfTrunNumber);
inspector.AddField("length_size_of_sample_num", m_LengthSizeOfSampleNumber);
inspector.AddField("entry count", m_Entries.ItemCount());
- if(inspector.GetVerbosity() >= 1)
- {
- for(unsigned int i = 0; i < m_Entries.ItemCount(); i++)
- {
+ if (inspector.GetVerbosity() >= 1) {
+ for (unsigned int i=0; i<m_Entries.ItemCount(); i++) {
char name[16];
char value[256];
AP4_FormatString(name, sizeof(name), "[%04d]", i);
- AP4_FormatString(value, sizeof(value),
+ AP4_FormatString(value, sizeof(value),
"time=%lld, moof_offset=%lld, traf_number=%d, trun_number=%d, sample_number=%d",
m_Entries[i].m_Time,
m_Entries[i].m_MoofOffset,
@@ -321,6 +293,6 @@ AP4_TfraAtom::InspectFields(AP4_AtomInspector& inspector)
inspector.AddField(name, value);
}
}
-
+
return AP4_SUCCESS;
}
diff --git a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4TfraAtom.h b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4TfraAtom.h
index 22a3c0df7..fc5f78495 100644
--- a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4TfraAtom.h
+++ b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4TfraAtom.h
@@ -1,6 +1,6 @@
/*****************************************************************
|
-| AP4 - tfra Atoms
+| AP4 - tfra Atoms
|
| Copyright 2002-2008 Axiomatic Systems, LLC
|
@@ -48,8 +48,7 @@ class AP4_TfraAtom : public AP4_Atom
{
public:
// types
- struct Entry
- {
+ struct Entry {
Entry() : m_Time(0), m_MoofOffset(0), m_TrafNumber(0), m_TrunNumber(0), m_SampleNumber(0) {}
AP4_UI64 m_Time;
AP4_UI64 m_MoofOffset;
@@ -57,11 +56,11 @@ public:
AP4_UI32 m_TrunNumber;
AP4_UI32 m_SampleNumber;
};
-
+
// class methods
static AP4_TfraAtom* Create(AP4_Size size, AP4_ByteStream& stream);
-
- // constructors
+
+ // constructors
AP4_TfraAtom();
// methods
@@ -69,10 +68,7 @@ public:
virtual AP4_Result WriteFields(AP4_ByteStream& stream);
// accessors
- AP4_Array<Entry>& GetEntries()
- {
- return m_Entries;
- }
+ AP4_Array<Entry>& GetEntries() { return m_Entries; }
private:
// methods
diff --git a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4TimsAtom.cpp b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4TimsAtom.cpp
index fb05c36d7..f6f446e7d 100644
--- a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4TimsAtom.cpp
+++ b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4TimsAtom.cpp
@@ -1,6 +1,6 @@
/*****************************************************************
|
-| AP4 - tims Atoms
+| AP4 - tims Atoms
|
| Copyright 2002-2008 Axiomatic Systems, LLC
|
@@ -38,7 +38,7 @@
| AP4_TimsAtom::AP4_TimsAtom
+---------------------------------------------------------------------*/
AP4_TimsAtom::AP4_TimsAtom(AP4_UI32 timescale) :
- AP4_Atom(AP4_ATOM_TYPE_TIMS, AP4_ATOM_HEADER_SIZE + 4),
+ AP4_Atom(AP4_ATOM_TYPE_TIMS, AP4_ATOM_HEADER_SIZE+4),
m_TimeScale(timescale)
{
}
diff --git a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4TimsAtom.h b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4TimsAtom.h
index 6f47d45df..3a78bdc2a 100644
--- a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4TimsAtom.h
+++ b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4TimsAtom.h
@@ -1,6 +1,6 @@
/*****************************************************************
|
-| AP4 - tims Atoms
+| AP4 - tims Atoms
|
| Copyright 2002-2008 Axiomatic Systems, LLC
|
@@ -41,8 +41,7 @@ class AP4_TimsAtom : public AP4_Atom
{
public:
// class methods
- static AP4_TimsAtom* Create(AP4_Size size, AP4_ByteStream& stream)
- {
+ static AP4_TimsAtom* Create(AP4_Size size, AP4_ByteStream& stream) {
return new AP4_TimsAtom(size, stream);
}
@@ -52,10 +51,7 @@ public:
virtual AP4_Result WriteFields(AP4_ByteStream& stream);
// accessors
- virtual AP4_UI32 GetTimeScale()
- {
- return m_TimeScale;
- }
+ virtual AP4_UI32 GetTimeScale() { return m_TimeScale; }
private:
// methods
diff --git a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4TkhdAtom.cpp b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4TkhdAtom.cpp
index f106b58f4..6060ac049 100644
--- a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4TkhdAtom.cpp
+++ b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4TkhdAtom.cpp
@@ -1,6 +1,6 @@
/*****************************************************************
|
-| AP4 - tkhd Atoms
+| AP4 - tkhd Atoms
|
| Copyright 2002-2008 Axiomatic Systems, LLC
|
@@ -46,8 +46,8 @@ AP4_TkhdAtom::Create(AP4_Size size, AP4_ByteStream& stream)
{
AP4_UI32 version;
AP4_UI32 flags;
- if(AP4_FAILED(AP4_Atom::ReadFullHeader(stream, version, flags))) return NULL;
- if(version > 1) return NULL;
+ if (AP4_FAILED(AP4_Atom::ReadFullHeader(stream, version, flags))) return NULL;
+ if (version > 1) return NULL;
return new AP4_TkhdAtom(size, version, flags, stream);
}
@@ -61,7 +61,7 @@ AP4_TkhdAtom::AP4_TkhdAtom(AP4_UI32 creation_time,
AP4_UI16 volume,
AP4_UI32 width,
AP4_UI32 height) :
- AP4_Atom(AP4_ATOM_TYPE_TKHD, AP4_FULL_ATOM_HEADER_SIZE + 80, 0, 0),
+ AP4_Atom(AP4_ATOM_TYPE_TKHD, AP4_FULL_ATOM_HEADER_SIZE+80, 0, 0),
m_CreationTime(creation_time),
m_ModificationTime(modification_time),
m_TrackId(track_id),
@@ -93,14 +93,13 @@ AP4_TkhdAtom::AP4_TkhdAtom(AP4_UI32 creation_time,
/*----------------------------------------------------------------------
| AP4_TkhdAtom::AP4_TkhdAtom
+---------------------------------------------------------------------*/
-AP4_TkhdAtom::AP4_TkhdAtom(AP4_UI32 size,
+AP4_TkhdAtom::AP4_TkhdAtom(AP4_UI32 size,
AP4_UI32 version,
AP4_UI32 flags,
AP4_ByteStream& stream) :
AP4_Atom(AP4_ATOM_TYPE_TKHD, size, version, flags)
{
- if(m_Version == 0)
- {
+ if (m_Version == 0) {
// we only deal with version 0 for now
AP4_UI32 creation_time;
stream.ReadUI32(creation_time);
@@ -113,9 +112,7 @@ AP4_TkhdAtom::AP4_TkhdAtom(AP4_UI32 size,
AP4_UI32 duration;
stream.ReadUI32(duration);
m_Duration = duration;
- }
- else
- {
+ } else {
stream.ReadUI64(m_CreationTime);
stream.ReadUI64(m_ModificationTime);
stream.ReadUI32(m_TrackId);
@@ -128,8 +125,7 @@ AP4_TkhdAtom::AP4_TkhdAtom(AP4_UI32 size,
stream.ReadUI16(m_AlternateGroup);
stream.ReadUI16(m_Volume);
stream.ReadUI16(m_Reserved3);
- for(int i = 0; i < 9; i++)
- {
+ for (int i=0; i<9; i++) {
stream.ReadUI32(m_Matrix[i]);
}
stream.ReadUI32(m_Width);
@@ -145,60 +141,56 @@ AP4_TkhdAtom::WriteFields(AP4_ByteStream& stream)
AP4_Result result;
// creation/modification time, track id, reserved1 & duration
- if(m_Version == 0)
- {
+ if (m_Version == 0) {
result = stream.WriteUI32((AP4_UI32)m_CreationTime);
- if(AP4_FAILED(result)) return result;
+ if (AP4_FAILED(result)) return result;
result = stream.WriteUI32((AP4_UI32)m_ModificationTime);
- if(AP4_FAILED(result)) return result;
+ if (AP4_FAILED(result)) return result;
result = stream.WriteUI32(m_TrackId);
- if(AP4_FAILED(result)) return result;
+ if (AP4_FAILED(result)) return result;
result = stream.WriteUI32(m_Reserved1);
- if(AP4_FAILED(result)) return result;
+ if (AP4_FAILED(result)) return result;
result = stream.WriteUI32((AP4_UI32)m_Duration);
- if(AP4_FAILED(result)) return result;
- }
- else
- {
+ if (AP4_FAILED(result)) return result;
+ } else {
result = stream.WriteUI64(m_CreationTime);
- if(AP4_FAILED(result)) return result;
+ if (AP4_FAILED(result)) return result;
result = stream.WriteUI64(m_ModificationTime);
- if(AP4_FAILED(result)) return result;
+ if (AP4_FAILED(result)) return result;
result = stream.WriteUI32(m_TrackId);
- if(AP4_FAILED(result)) return result;
+ if (AP4_FAILED(result)) return result;
result = stream.WriteUI32(m_Reserved1);
- if(AP4_FAILED(result)) return result;
+ if (AP4_FAILED(result)) return result;
result = stream.WriteUI64(m_Duration);
- if(AP4_FAILED(result)) return result;
+ if (AP4_FAILED(result)) return result;
}
// reserved2
result = stream.Write(m_Reserved2, sizeof(m_Reserved2));
- if(AP4_FAILED(result)) return result;
+ if (AP4_FAILED(result)) return result;
// layer, alternate group & volume
result = stream.WriteUI16(m_Layer);
- if(AP4_FAILED(result)) return result;
+ if (AP4_FAILED(result)) return result;
result = stream.WriteUI16(m_AlternateGroup);
- if(AP4_FAILED(result)) return result;
+ if (AP4_FAILED(result)) return result;
result = stream.WriteUI16(m_Volume);
- if(AP4_FAILED(result)) return result;
+ if (AP4_FAILED(result)) return result;
// reserved3
result = stream.WriteUI16(m_Reserved3);
// matrix
- for(int i = 0; i < 9; i++)
- {
+ for (int i=0; i<9; i++) {
result = stream.WriteUI32(m_Matrix[i]);
- if(AP4_FAILED(result)) return result;
+ if (AP4_FAILED(result)) return result;
}
// width & height
result = stream.WriteUI32(m_Width);
- if(AP4_FAILED(result)) return result;
+ if (AP4_FAILED(result)) return result;
result = stream.WriteUI32(m_Height);
- if(AP4_FAILED(result)) return result;
+ if (AP4_FAILED(result)) return result;
return result;
}
@@ -212,8 +204,8 @@ AP4_TkhdAtom::InspectFields(AP4_AtomInspector& inspector)
inspector.AddField("enabled", ((m_Flags & AP4_TKHD_FLAG_TRACK_ENABLED) ? 1 : 0), AP4_AtomInspector::HINT_BOOLEAN);
inspector.AddField("id", m_TrackId);
inspector.AddField("duration", m_Duration);
- inspector.AddFieldF("width", (float)m_Width / 65536.0f);
- inspector.AddFieldF("height", (float)m_Height / 65536.0f);
-
+ inspector.AddFieldF("width", (float)m_Width/65536.0f);
+ inspector.AddFieldF("height", (float)m_Height/65536.0f);
+
return AP4_SUCCESS;
}
diff --git a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4TkhdAtom.h b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4TkhdAtom.h
index a703638d7..d0d0f7b68 100644
--- a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4TkhdAtom.h
+++ b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4TkhdAtom.h
@@ -1,6 +1,6 @@
/*****************************************************************
|
-| AP4 - tkhd Atoms
+| AP4 - tkhd Atoms
|
| Copyright 2002-2008 Axiomatic Systems, LLC
|
@@ -61,53 +61,28 @@ public:
AP4_UI64 duration,
AP4_UI16 volume,
AP4_UI32 width,
- AP4_UI32 height);
+ AP4_UI32 height);
virtual AP4_Result InspectFields(AP4_AtomInspector& inspector);
virtual AP4_Result WriteFields(AP4_ByteStream& stream);
- AP4_UI64 GetDuration()
- {
- return m_Duration;
- }
- void SetDuration(AP4_UI64 duration)
- {
- m_Duration = duration;
- }
- AP4_UI32 GetTrackId()
- {
- return m_TrackId;
- }
- void SetTrackId(AP4_UI32 track_id)
- {
- m_TrackId = track_id;
- }
+ AP4_UI64 GetDuration() { return m_Duration; }
+ void SetDuration(AP4_UI64 duration) { m_Duration = duration; }
+ AP4_UI32 GetTrackId() { return m_TrackId; }
+ void SetTrackId(AP4_UI32 track_id) { m_TrackId = track_id; }
- void GetTranslation(float& x, float& y)
- {
+ void GetTranslation(float& x, float& y) {
x = (float)(*(int*)&m_Matrix[6]) / 65536;
y = (float)(*(int*)&m_Matrix[7]) / 65536;
}
- AP4_UI32 GetWidth()
- {
- return m_Width;
- }
- void SetWidth(AP4_UI32 width)
- {
- m_Width = width;
- }
- AP4_UI32 GetHeight()
- {
- return m_Height;
- }
- void SetHeight(AP4_UI32 height)
- {
- m_Height = height;
- }
+ AP4_UI32 GetWidth() { return m_Width; }
+ void SetWidth(AP4_UI32 width) { m_Width = width; }
+ AP4_UI32 GetHeight() { return m_Height; }
+ void SetHeight(AP4_UI32 height) { m_Height = height; }
-private:
+ private:
// methods
- AP4_TkhdAtom(AP4_UI32 size,
+ AP4_TkhdAtom(AP4_UI32 size,
AP4_UI32 version,
AP4_UI32 flags,
AP4_ByteStream& stream);
diff --git a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4Track.cpp b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4Track.cpp
index 810750582..9dc915571 100644
--- a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4Track.cpp
+++ b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4Track.cpp
@@ -49,7 +49,7 @@
+---------------------------------------------------------------------*/
AP4_Track::AP4_Track(Type type,
AP4_SampleTable* sample_table,
- AP4_UI32 track_id,
+ AP4_UI32 track_id,
AP4_UI32 movie_time_scale,
AP4_UI64 track_duration,
AP4_UI32 media_time_scale,
@@ -61,66 +61,65 @@ AP4_Track::AP4_Track(Type type,
m_Type(type),
m_SampleTable(sample_table),
m_SampleTableIsOwned(true),
- m_MovieTimeScale(movie_time_scale ?
- movie_time_scale :
+ m_MovieTimeScale(movie_time_scale ?
+ movie_time_scale :
AP4_TRACK_DEFAULT_MOVIE_TIMESCALE)
{
// compute the default volume value
unsigned int volume = 0;
- if(type == TYPE_AUDIO) volume = 0x100;
+ if (type == TYPE_AUDIO) volume = 0x100;
// compute the handler type and name
AP4_Atom::Type hdlr_type;
const char* hdlr_name;
- switch(type)
- {
- case TYPE_AUDIO:
- hdlr_type = AP4_HANDLER_TYPE_SOUN;
- hdlr_name = "Bento4 Sound Handler";
- break;
-
- case TYPE_VIDEO:
- hdlr_type = AP4_HANDLER_TYPE_VIDE;
- hdlr_name = "Bento4 Video Handler";
- break;
-
- case TYPE_HINT:
- hdlr_type = AP4_HANDLER_TYPE_HINT;
- hdlr_name = "Bento4 Hint Handler";
- break;
-
- case TYPE_TEXT:
- hdlr_type = AP4_HANDLER_TYPE_TEXT;
- hdlr_name = "Bento4 Text Handler";
- break;
-
- default:
- hdlr_type = 0;
- hdlr_name = NULL;
- break;
+ switch (type) {
+ case TYPE_AUDIO:
+ hdlr_type = AP4_HANDLER_TYPE_SOUN;
+ hdlr_name = "Bento4 Sound Handler";
+ break;
+
+ case TYPE_VIDEO:
+ hdlr_type = AP4_HANDLER_TYPE_VIDE;
+ hdlr_name = "Bento4 Video Handler";
+ break;
+
+ case TYPE_HINT:
+ hdlr_type = AP4_HANDLER_TYPE_HINT;
+ hdlr_name = "Bento4 Hint Handler";
+ break;
+
+ case TYPE_TEXT:
+ hdlr_type = AP4_HANDLER_TYPE_TEXT;
+ hdlr_name = "Bento4 Text Handler";
+ break;
+
+ default:
+ hdlr_type = 0;
+ hdlr_name = NULL;
+ break;
}
// create a trak atom
m_TrakAtom = new AP4_TrakAtom(sample_table,
- hdlr_type,
+ hdlr_type,
hdlr_name,
- track_id,
- 0,
- 0,
+ track_id,
+ 0,
+ 0,
track_duration,
media_time_scale,
media_duration,
- volume,
+ volume,
language,
- width,
+ width,
height);
}
/*----------------------------------------------------------------------
| AP4_Track::AP4_Track
+---------------------------------------------------------------------*/
-AP4_Track::AP4_Track(AP4_TrakAtom& atom,
- AP4_ByteStream& sample_stream,
+AP4_Track::AP4_Track(AP4_TrakAtom& atom,
+ AP4_ByteStream& sample_stream,
AP4_UI32 movie_time_scale) :
m_TrakAtom(&atom),
m_TrakAtomIsOwned(false),
@@ -131,51 +130,35 @@ AP4_Track::AP4_Track(AP4_TrakAtom& atom,
{
// find the handler type
AP4_Atom* sub = atom.FindChild("mdia/hdlr");
- if(sub)
- {
+ if (sub) {
AP4_HdlrAtom* hdlr = AP4_DYNAMIC_CAST(AP4_HdlrAtom, sub);
- if(hdlr)
- {
+ if (hdlr) {
AP4_UI32 type = hdlr->GetHandlerType();
- if(type == AP4_HANDLER_TYPE_SOUN)
- {
+ if (type == AP4_HANDLER_TYPE_SOUN) {
m_Type = TYPE_AUDIO;
- }
- else if(type == AP4_HANDLER_TYPE_VIDE)
- {
+ } else if (type == AP4_HANDLER_TYPE_VIDE) {
m_Type = TYPE_VIDEO;
- }
- else if(type == AP4_HANDLER_TYPE_HINT)
- {
+ } else if (type == AP4_HANDLER_TYPE_HINT) {
m_Type = TYPE_HINT;
- }
- else if(type == AP4_HANDLER_TYPE_ODSM ||
- type == AP4_HANDLER_TYPE_SDSM)
- {
+ } else if (type == AP4_HANDLER_TYPE_ODSM ||
+ type == AP4_HANDLER_TYPE_SDSM) {
m_Type = TYPE_SYSTEM;
- }
- else if(type == AP4_HANDLER_TYPE_TEXT ||
- type == AP4_HANDLER_TYPE_TX3G)
- {
+ } else if (type == AP4_HANDLER_TYPE_TEXT ||
+ type == AP4_HANDLER_TYPE_TX3G) {
m_Type = TYPE_TEXT;
- }
- else if(type == AP4_HANDLER_TYPE_JPEG)
- {
+ } else if (type == AP4_HANDLER_TYPE_JPEG) {
m_Type = TYPE_JPEG;
- // ==> Start patch MPC
- }
- else if(type == AP4_HANDLER_TYPE_SUBP)
- {
- m_Type = TYPE_SUBP;
- // <== End patch MPC
- }
+ // ==> Start patch MPC
+ } else if (type == AP4_HANDLER_TYPE_SUBP) {
+ m_Type = TYPE_SUBP;
+ // <== End patch MPC
+ }
}
}
// create a facade for the stbl atom
AP4_ContainerAtom* stbl = AP4_DYNAMIC_CAST(AP4_ContainerAtom, atom.FindChild("mdia/minf/stbl"));
- if(stbl)
- {
+ if (stbl) {
m_SampleTable = new AP4_AtomSampleTable(stbl, sample_stream);
}
}
@@ -185,33 +168,31 @@ AP4_Track::AP4_Track(AP4_TrakAtom& atom,
+---------------------------------------------------------------------*/
AP4_Track::~AP4_Track()
{
- if(m_TrakAtomIsOwned) delete m_TrakAtom;
- if(m_SampleTableIsOwned) delete m_SampleTable;
+ if (m_TrakAtomIsOwned) delete m_TrakAtom;
+ if (m_SampleTableIsOwned) delete m_SampleTable;
}
/*----------------------------------------------------------------------
| AP4_Track::Clone
+---------------------------------------------------------------------*/
-AP4_Track*
+AP4_Track*
AP4_Track::Clone(AP4_Result* result)
{
AP4_SyntheticSampleTable* sample_table = new AP4_SyntheticSampleTable();
-
+
// default return value
- if(result) *result = AP4_SUCCESS;
-
+ if (result) *result = AP4_SUCCESS;
+
// add clones of the sample descriptions to the new sample table
- for(unsigned int i = 0; ; i++)
- {
+ for (unsigned int i=0; ;i++) {
AP4_SampleDescription* sample_description = GetSampleDescription(i);
- if(sample_description == NULL) break;
+ if (sample_description == NULL) break;
sample_table->AddSampleDescription(sample_description->Clone());
}
AP4_Sample sample;
AP4_Ordinal index = 0;
- while(AP4_SUCCEEDED(GetSample(index, sample)))
- {
+ while (AP4_SUCCEEDED(GetSample(index, sample))) {
AP4_ByteStream* data_stream;
data_stream = sample.GetDataStream();
sample_table->AddSample(*data_stream,
@@ -224,8 +205,8 @@ AP4_Track::Clone(AP4_Result* result)
sample.IsSync());
AP4_RELEASE(data_stream); // release our ref, the table has kept its own ref.
index++;
- }
-
+ }
+
// create the cloned track
AP4_Track* clone = new AP4_Track(GetType(),
sample_table,
@@ -237,7 +218,7 @@ AP4_Track::Clone(AP4_Result* result)
GetTrackLanguage().GetChars(),
GetWidth(),
GetHeight());
-
+
return clone;
}
@@ -247,7 +228,7 @@ AP4_Track::Clone(AP4_Result* result)
AP4_Result
AP4_Track::Attach(AP4_MoovAtom* moov)
{
- if(!m_TrakAtomIsOwned) return AP4_ERROR_INTERNAL;
+ if (!m_TrakAtomIsOwned) return AP4_ERROR_INTERNAL;
moov->AddChild(m_TrakAtom);
m_TrakAtomIsOwned = false;
@@ -260,11 +241,9 @@ AP4_Track::Attach(AP4_MoovAtom* moov)
AP4_UI32
AP4_Track::GetFlags()
{
- if(m_TrakAtom)
- {
+ if (m_TrakAtom) {
AP4_TkhdAtom* tkhd = AP4_DYNAMIC_CAST(AP4_TkhdAtom, m_TrakAtom->FindChild("tkhd"));
- if(tkhd)
- {
+ if (tkhd) {
return tkhd->GetFlags();
}
}
@@ -277,11 +256,9 @@ AP4_Track::GetFlags()
AP4_Result
AP4_Track::SetFlags(AP4_UI32 flags)
{
- if(m_TrakAtom)
- {
+ if (m_TrakAtom) {
AP4_TkhdAtom* tkhd = AP4_DYNAMIC_CAST(AP4_TkhdAtom, m_TrakAtom->FindChild("tkhd"));
- if(tkhd)
- {
+ if (tkhd) {
tkhd->SetFlags(flags);
return AP4_SUCCESS;
}
@@ -295,11 +272,9 @@ AP4_Track::SetFlags(AP4_UI32 flags)
AP4_UI32
AP4_Track::GetHandlerType()
{
- if(m_TrakAtom)
- {
+ if (m_TrakAtom) {
AP4_HdlrAtom* hdlr = AP4_DYNAMIC_CAST(AP4_HdlrAtom, m_TrakAtom->FindChild("mdia/hdlr"));
- if(hdlr)
- {
+ if (hdlr) {
return hdlr->GetHandlerType();
}
}
@@ -376,7 +351,7 @@ AP4_Track::GetSampleCount()
/*----------------------------------------------------------------------
| AP4_Track::GetSample
+---------------------------------------------------------------------*/
-AP4_Result
+AP4_Result
AP4_Track::GetSample(AP4_Ordinal index, AP4_Sample& sample)
{
// delegate to the sample table
@@ -396,8 +371,8 @@ AP4_Track::GetSampleDescription(AP4_Ordinal index)
/*----------------------------------------------------------------------
| AP4_Track::ReadSample
+---------------------------------------------------------------------*/
-AP4_Result
-AP4_Track::ReadSample(AP4_Ordinal index,
+AP4_Result
+AP4_Track::ReadSample(AP4_Ordinal index,
AP4_Sample& sample,
AP4_DataBuffer& data)
{
@@ -405,7 +380,7 @@ AP4_Track::ReadSample(AP4_Ordinal index,
// get the sample
result = GetSample(index, sample);
- if(AP4_FAILED(result)) return result;
+ if (AP4_FAILED(result)) return result;
// read the data
return sample.ReadData(data);
@@ -414,7 +389,7 @@ AP4_Track::ReadSample(AP4_Ordinal index,
/*----------------------------------------------------------------------
| AP4_Track::GetSampleIndexForTimeStampMs
+---------------------------------------------------------------------*/
-AP4_Result
+AP4_Result
AP4_Track::GetSampleIndexForTimeStampMs(AP4_UI32 ts_ms, AP4_Ordinal& index)
{
// convert the ts in the timescale of the track's media
@@ -426,10 +401,10 @@ AP4_Track::GetSampleIndexForTimeStampMs(AP4_UI32 ts_ms, AP4_Ordinal& index)
/*----------------------------------------------------------------------
| AP4_Track::GetNearestSyncSampleIndex
+---------------------------------------------------------------------*/
-AP4_Ordinal
+AP4_Ordinal
AP4_Track::GetNearestSyncSampleIndex(AP4_Ordinal index, bool before /* = true */)
{
- if(m_SampleTable == NULL) return index;
+ if (m_SampleTable == NULL) return index;
return m_SampleTable->GetNearestSyncSampleIndex(index, before);
}
@@ -440,13 +415,13 @@ AP4_Result
AP4_Track::SetMovieTimeScale(AP4_UI32 time_scale)
{
// check that we can convert
- if(m_MovieTimeScale == 0) return AP4_FAILURE;
+ if (m_MovieTimeScale == 0) return AP4_FAILURE;
// convert from one time scale to the other
- m_TrakAtom->SetDuration(AP4_ConvertTime(m_TrakAtom->GetDuration(),
+ m_TrakAtom->SetDuration(AP4_ConvertTime(m_TrakAtom->GetDuration(),
m_MovieTimeScale,
time_scale));
-
+
// keep the new movie timescale
m_MovieTimeScale = time_scale;
@@ -459,7 +434,7 @@ AP4_Track::SetMovieTimeScale(AP4_UI32 time_scale)
AP4_UI32
AP4_Track::GetMediaTimeScale()
{
- return m_TrakAtom ? m_TrakAtom->GetMediaTimeScale() : 0;
+ return m_TrakAtom?m_TrakAtom->GetMediaTimeScale():0;
}
/*----------------------------------------------------------------------
@@ -468,7 +443,7 @@ AP4_Track::GetMediaTimeScale()
AP4_UI64
AP4_Track::GetMediaDuration()
{
- return m_TrakAtom ? m_TrakAtom->GetMediaDuration() : 0;
+ return m_TrakAtom?m_TrakAtom->GetMediaDuration():0;
}
/*----------------------------------------------------------------------
@@ -477,8 +452,7 @@ AP4_Track::GetMediaDuration()
const AP4_String
AP4_Track::GetTrackName()
{
- if(AP4_HdlrAtom* hdlr = AP4_DYNAMIC_CAST(AP4_HdlrAtom, m_TrakAtom->FindChild("mdia/hdlr")))
- {
+ if (AP4_HdlrAtom* hdlr = AP4_DYNAMIC_CAST(AP4_HdlrAtom, m_TrakAtom->FindChild("mdia/hdlr"))) {
return hdlr->GetHandlerName();
}
return NULL;
@@ -490,8 +464,7 @@ AP4_Track::GetTrackName()
const AP4_String
AP4_Track::GetTrackLanguage()
{
- if(AP4_MdhdAtom* mdhd = AP4_DYNAMIC_CAST(AP4_MdhdAtom, m_TrakAtom->FindChild("mdia/mdhd")))
- {
+ if (AP4_MdhdAtom* mdhd = AP4_DYNAMIC_CAST(AP4_MdhdAtom, m_TrakAtom->FindChild("mdia/mdhd"))) {
return mdhd->GetLanguage();
}
return NULL;
diff --git a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4Track.h b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4Track.h
index 33836d607..12b48560c 100644
--- a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4Track.h
+++ b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4Track.h
@@ -63,12 +63,10 @@ const AP4_UI32 AP4_TRACK_FLAG_IN_PREVIEW = 0x0004;
/*----------------------------------------------------------------------
| AP4_Track
+---------------------------------------------------------------------*/
-class AP4_Track
-{
-public:
+class AP4_Track {
+ public:
// types
- typedef enum
- {
+ typedef enum {
TYPE_UNKNOWN = 0,
TYPE_AUDIO = 1,
TYPE_VIDEO = 2,
@@ -77,15 +75,15 @@ public:
TYPE_TEXT = 5,
TYPE_JPEG = 6,
TYPE_RTP = 7,
- // ==> Start patch MPC
- TYPE_SUBP = 8
- // <== End patch MPC
+ // ==> Start patch MPC
+ TYPE_SUBP = 8
+ // <== End patch MPC
} Type;
// methods
AP4_Track(Type type,
AP4_SampleTable* sample_table, // ownership is transfered to the AP4_Track object
- AP4_UI32 track_id,
+ AP4_UI32 track_id,
AP4_UI32 movie_time_scale, // 0 = use default
AP4_UI64 track_duration, // in the movie timescale
AP4_UI32 media_time_scale,
@@ -93,24 +91,21 @@ public:
const char* language,
AP4_UI32 width, // in 16.16 fixed point
AP4_UI32 height); // in 16.16 fixed point
- AP4_Track(AP4_TrakAtom& atom,
+ AP4_Track(AP4_TrakAtom& atom,
AP4_ByteStream& sample_stream,
AP4_UI32 movie_time_scale);
virtual ~AP4_Track();
-
- /**
- * Clone a track. This is useful if you want to create a track from
- * a non-synthetic track (parsed from a file for example) and
+
+ /**
+ * Clone a track. This is useful if you want to create a track from
+ * a non-synthetic track (parsed from a file for example) and
* write it out
*/
AP4_Track* Clone(AP4_Result* result = NULL);
-
+
AP4_UI32 GetFlags();
AP4_Result SetFlags(AP4_UI32 flags);
- AP4_Track::Type GetType()
- {
- return m_Type;
- }
+ AP4_Track::Type GetType() { return m_Type; }
AP4_UI32 GetHandlerType();
AP4_UI64 GetDuration(); // in the timescale of the movie
AP4_UI32 GetDurationMs(); // in milliseconds
@@ -118,35 +113,26 @@ public:
AP4_UI32 GetHeight(); // in 16.16 fixed point
AP4_Cardinal GetSampleCount();
AP4_Result GetSample(AP4_Ordinal index, AP4_Sample& sample);
- AP4_Result ReadSample(AP4_Ordinal index,
+ AP4_Result ReadSample(AP4_Ordinal index,
AP4_Sample& sample,
AP4_DataBuffer& data);
- AP4_Result GetSampleIndexForTimeStampMs(AP4_UI32 ts_ms,
- AP4_Ordinal& index);
- AP4_Ordinal GetNearestSyncSampleIndex(AP4_Ordinal index, bool before = true);
+ AP4_Result GetSampleIndexForTimeStampMs(AP4_UI32 ts_ms,
+ AP4_Ordinal& index);
+ AP4_Ordinal GetNearestSyncSampleIndex(AP4_Ordinal index, bool before=true);
AP4_SampleDescription* GetSampleDescription(AP4_Ordinal index);
- AP4_SampleTable* GetSampleTable()
- {
- return m_SampleTable;
- }
+ AP4_SampleTable* GetSampleTable() { return m_SampleTable; }
AP4_UI32 GetId();
AP4_Result SetId(AP4_UI32 track_id);
- AP4_TrakAtom* GetTrakAtom()
- {
- return m_TrakAtom;
- }
+ AP4_TrakAtom* GetTrakAtom() { return m_TrakAtom; }
AP4_Result SetMovieTimeScale(AP4_UI32 time_scale);
- AP4_UI32 GetMovieTimeScale()
- {
- return m_MovieTimeScale;
- }
+ AP4_UI32 GetMovieTimeScale() { return m_MovieTimeScale; }
AP4_UI32 GetMediaTimeScale();
AP4_UI64 GetMediaDuration(); // in the timescale of the media
const AP4_String GetTrackName();
const AP4_String GetTrackLanguage();
AP4_Result Attach(AP4_MoovAtom* moov);
-protected:
+ protected:
// members
AP4_TrakAtom* m_TrakAtom;
bool m_TrakAtomIsOwned;
diff --git a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4TrakAtom.cpp b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4TrakAtom.cpp
index b35a76284..57202f92e 100644
--- a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4TrakAtom.cpp
+++ b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4TrakAtom.cpp
@@ -1,6 +1,6 @@
/*****************************************************************
|
-| AP4 - trak Atoms
+| AP4 - trak Atoms
|
| Copyright 2002-2008 Axiomatic Systems, LLC
|
@@ -55,7 +55,7 @@ AP4_DEFINE_DYNAMIC_CAST_ANCHOR(AP4_TrakAtom)
+---------------------------------------------------------------------*/
AP4_TrakAtom::AP4_TrakAtom(AP4_SampleTable* sample_table,
AP4_Atom::Type hdlr_type,
- const char* hdlr_name,
+ const char* hdlr_name,
AP4_UI32 track_id,
AP4_UI32 creation_time,
AP4_UI32 modification_time,
@@ -71,12 +71,12 @@ AP4_TrakAtom::AP4_TrakAtom(AP4_SampleTable* sample_table,
AP4_Result result;
// create a tkhd atom
- m_TkhdAtom = new AP4_TkhdAtom(creation_time,
- modification_time,
+ m_TkhdAtom = new AP4_TkhdAtom(creation_time,
+ modification_time,
track_id,
- track_duration,
- volume,
- width,
+ track_duration,
+ volume,
+ width,
height);
// create an edts
@@ -87,24 +87,23 @@ AP4_TrakAtom::AP4_TrakAtom(AP4_SampleTable* sample_table,
// create a hdlr atom for the mdia atom
AP4_HdlrAtom* hdlr = new AP4_HdlrAtom(hdlr_type, hdlr_name);
- // create a minf atom
+ // create a minf atom
AP4_ContainerAtom* minf = new AP4_ContainerAtom(AP4_ATOM_TYPE_MINF);
// create a media header atom for minf (vmhd, smhd, hmhd or nmhd)
AP4_Atom* minf_header;
- switch(hdlr_type)
- {
- case AP4_HANDLER_TYPE_VIDE:
- minf_header = new AP4_VmhdAtom(0, 0, 0, 0);
- break;
-
- case AP4_HANDLER_TYPE_SOUN:
- minf_header = new AP4_SmhdAtom(0);
- break;
-
- default:
- minf_header = new AP4_NmhdAtom();
- break;
+ switch (hdlr_type) {
+ case AP4_HANDLER_TYPE_VIDE:
+ minf_header = new AP4_VmhdAtom(0, 0, 0, 0);
+ break;
+
+ case AP4_HANDLER_TYPE_SOUN:
+ minf_header = new AP4_SmhdAtom(0);
+ break;
+
+ default:
+ minf_header = new AP4_NmhdAtom();
+ break;
}
// create a dinf atom for minf
@@ -119,15 +118,15 @@ AP4_TrakAtom::AP4_TrakAtom(AP4_SampleTable* sample_table,
// create a stbl atom for minf
AP4_ContainerAtom* stbl;
result = sample_table->GenerateStblAtom(stbl);
- if(AP4_FAILED(result)) stbl = NULL;
-
+ if (AP4_FAILED(result)) stbl = NULL;
+
// populate the dinf atom
dinf->AddChild(dref);
// populate the minf atom
minf->AddChild(minf_header);
minf->AddChild(dinf);
- if(stbl) minf->AddChild(stbl);
+ if (stbl) minf->AddChild(stbl);
// create a mdhd atom for the mdia atom
m_MdhdAtom = new AP4_MdhdAtom(creation_time,
@@ -164,7 +163,7 @@ AP4_TrakAtom::AP4_TrakAtom(AP4_UI32 size,
AP4_UI32
AP4_TrakAtom::GetId()
{
- return m_TkhdAtom ? m_TkhdAtom->GetTrackId() : 0;
+ return m_TkhdAtom?m_TkhdAtom->GetTrackId():0;
}
/*----------------------------------------------------------------------
@@ -173,13 +172,10 @@ AP4_TrakAtom::GetId()
AP4_Result
AP4_TrakAtom::SetId(AP4_UI32 id)
{
- if(m_TkhdAtom)
- {
- m_TkhdAtom->SetTrackId(id);
+ if (m_TkhdAtom) {
+ m_TkhdAtom->SetTrackId(id);
return AP4_SUCCESS;
- }
- else
- {
+ } else {
return AP4_ERROR_INVALID_STATE;
}
}
@@ -190,7 +186,7 @@ AP4_TrakAtom::SetId(AP4_UI32 id)
AP4_UI32
AP4_TrakAtom::GetMediaTimeScale()
{
- return m_MdhdAtom ? m_MdhdAtom->GetTimeScale() : 0;
+ return m_MdhdAtom?m_MdhdAtom->GetTimeScale():0;
}
/*----------------------------------------------------------------------
@@ -199,13 +195,10 @@ AP4_TrakAtom::GetMediaTimeScale()
AP4_Result
AP4_TrakAtom::SetMediaTimeScale(AP4_UI32 timescale)
{
- if(m_MdhdAtom)
- {
- m_MdhdAtom->SetTimeScale(timescale);
+ if (m_MdhdAtom) {
+ m_MdhdAtom->SetTimeScale(timescale);
return AP4_SUCCESS;
- }
- else
- {
+ } else {
return AP4_ERROR_INVALID_STATE;
}
}
@@ -216,7 +209,7 @@ AP4_TrakAtom::SetMediaTimeScale(AP4_UI32 timescale)
AP4_UI64
AP4_TrakAtom::GetDuration()
{
- return m_TkhdAtom ? m_TkhdAtom->GetDuration() : 0;
+ return m_TkhdAtom?m_TkhdAtom->GetDuration():0;
}
/*----------------------------------------------------------------------
@@ -225,13 +218,10 @@ AP4_TrakAtom::GetDuration()
AP4_Result
AP4_TrakAtom::SetDuration(AP4_UI64 duration)
{
- if(m_TkhdAtom)
- {
+ if (m_TkhdAtom) {
m_TkhdAtom->SetDuration(duration);
return AP4_SUCCESS;
- }
- else
- {
+ } else {
return AP4_ERROR_INVALID_STATE;
}
}
@@ -242,7 +232,7 @@ AP4_TrakAtom::SetDuration(AP4_UI64 duration)
AP4_UI64
AP4_TrakAtom::GetMediaDuration()
{
- return m_MdhdAtom ? m_MdhdAtom->GetDuration() : 0;
+ return m_MdhdAtom?m_MdhdAtom->GetDuration():0;
}
/*----------------------------------------------------------------------
@@ -251,13 +241,10 @@ AP4_TrakAtom::GetMediaDuration()
AP4_Result
AP4_TrakAtom::SetMediaDuration(AP4_UI32 duration)
{
- if(m_MdhdAtom)
- {
+ if (m_MdhdAtom) {
m_MdhdAtom->SetDuration(duration);
return AP4_SUCCESS;
- }
- else
- {
+ } else {
return AP4_ERROR_INVALID_STATE;
}
}
@@ -268,7 +255,7 @@ AP4_TrakAtom::SetMediaDuration(AP4_UI32 duration)
AP4_UI32
AP4_TrakAtom::GetWidth()
{
- return m_TkhdAtom ? m_TkhdAtom->GetWidth() : 0;
+ return m_TkhdAtom?m_TkhdAtom->GetWidth():0;
}
/*----------------------------------------------------------------------
@@ -277,13 +264,10 @@ AP4_TrakAtom::GetWidth()
AP4_Result
AP4_TrakAtom::SetWidth(AP4_UI32 width)
{
- if(m_TkhdAtom)
- {
+ if (m_TkhdAtom) {
m_TkhdAtom->SetWidth(width);
return AP4_SUCCESS;
- }
- else
- {
+ } else {
return AP4_ERROR_INVALID_STATE;
}
}
@@ -294,7 +278,7 @@ AP4_TrakAtom::SetWidth(AP4_UI32 width)
AP4_UI32
AP4_TrakAtom::GetHeight()
{
- return m_TkhdAtom ? m_TkhdAtom->GetHeight() : 0;
+ return m_TkhdAtom?m_TkhdAtom->GetHeight():0;
}
/*----------------------------------------------------------------------
@@ -303,13 +287,10 @@ AP4_TrakAtom::GetHeight()
AP4_Result
AP4_TrakAtom::SetHeight(AP4_UI32 height)
{
- if(m_TkhdAtom)
- {
+ if (m_TkhdAtom) {
m_TkhdAtom->SetHeight(height);
return AP4_SUCCESS;
- }
- else
- {
+ } else {
return AP4_ERROR_INVALID_STATE;
}
}
@@ -317,22 +298,17 @@ AP4_TrakAtom::SetHeight(AP4_UI32 height)
/*----------------------------------------------------------------------
| AP4_TrakAtom::AdjustChunkOffsets
+---------------------------------------------------------------------*/
-AP4_Result
+AP4_Result
AP4_TrakAtom::AdjustChunkOffsets(AP4_SI64 delta)
{
AP4_Atom* atom;
- if((atom = FindChild("mdia/minf/stbl/stco")))
- {
+ if ((atom = FindChild("mdia/minf/stbl/stco"))) {
AP4_StcoAtom* stco = AP4_DYNAMIC_CAST(AP4_StcoAtom, atom);
return stco->AdjustChunkOffsets((int)delta);
- }
- else if((atom = FindChild("mdia/minf/stbl/co64")))
- {
+ } else if ((atom = FindChild("mdia/minf/stbl/co64"))) {
AP4_Co64Atom* co64 = AP4_DYNAMIC_CAST(AP4_Co64Atom, atom);
return co64->AdjustChunkOffsets(delta);
- }
- else
- {
+ } else {
return AP4_ERROR_INVALID_STATE;
}
}
@@ -344,34 +320,27 @@ AP4_Result
AP4_TrakAtom::GetChunkOffsets(AP4_Array<AP4_UI64>& chunk_offsets)
{
AP4_Atom* atom;
- if((atom = FindChild("mdia/minf/stbl/stco")))
- {
+ if ((atom = FindChild("mdia/minf/stbl/stco"))) {
AP4_StcoAtom* stco = AP4_DYNAMIC_CAST(AP4_StcoAtom, atom);
- if(stco == NULL) return AP4_ERROR_INTERNAL;
+ if (stco == NULL) return AP4_ERROR_INTERNAL;
AP4_Cardinal stco_chunk_count = stco->GetChunkCount();
const AP4_UI32* stco_chunk_offsets = stco->GetChunkOffsets();
chunk_offsets.SetItemCount(stco_chunk_count);
- for(unsigned int i = 0; i < stco_chunk_count; i++)
- {
+ for (unsigned int i=0; i<stco_chunk_count; i++) {
chunk_offsets[i] = stco_chunk_offsets[i];
}
return AP4_SUCCESS;
- }
- else if((atom = FindChild("mdia/minf/stbl/co64")))
- {
+ } else if ((atom = FindChild("mdia/minf/stbl/co64"))) {
AP4_Co64Atom* co64 = AP4_DYNAMIC_CAST(AP4_Co64Atom, atom);
- if(co64 == NULL) return AP4_ERROR_INTERNAL;
+ if (co64 == NULL) return AP4_ERROR_INTERNAL;
AP4_Cardinal co64_chunk_count = co64->GetChunkCount();
const AP4_UI64* co64_chunk_offsets = co64->GetChunkOffsets();
chunk_offsets.SetItemCount(co64_chunk_count);
- for(unsigned int i = 0; i < co64_chunk_count; i++)
- {
+ for (unsigned int i=0; i<co64_chunk_count; i++) {
chunk_offsets[i] = co64_chunk_offsets[i];
}
return AP4_SUCCESS;
- }
- else
- {
+ } else {
return AP4_ERROR_INVALID_STATE;
}
}
@@ -383,40 +352,31 @@ AP4_Result
AP4_TrakAtom::SetChunkOffsets(const AP4_Array<AP4_UI64>& chunk_offsets)
{
AP4_Atom* atom;
- if((atom = FindChild("mdia/minf/stbl/stco")))
- {
+ if ((atom = FindChild("mdia/minf/stbl/stco"))) {
AP4_StcoAtom* stco = AP4_DYNAMIC_CAST(AP4_StcoAtom, atom);
- if(stco == NULL) return AP4_ERROR_INTERNAL;
+ if (stco == NULL) return AP4_ERROR_INTERNAL;
AP4_Cardinal stco_chunk_count = stco->GetChunkCount();
AP4_UI32* stco_chunk_offsets = stco->GetChunkOffsets();
- if(stco_chunk_count > chunk_offsets.ItemCount())
- {
+ if (stco_chunk_count > chunk_offsets.ItemCount()) {
return AP4_ERROR_OUT_OF_RANGE;
}
- for(unsigned int i = 0; i < stco_chunk_count; i++)
- {
+ for (unsigned int i=0; i<stco_chunk_count; i++) {
stco_chunk_offsets[i] = (AP4_UI32)chunk_offsets[i];
}
return AP4_SUCCESS;
- }
- else if((atom = FindChild("mdia/minf/stbl/co64")))
- {
+ } else if ((atom = FindChild("mdia/minf/stbl/co64"))) {
AP4_Co64Atom* co64 = AP4_DYNAMIC_CAST(AP4_Co64Atom, atom);
- if(co64 == NULL) return AP4_ERROR_INTERNAL;
+ if (co64 == NULL) return AP4_ERROR_INTERNAL;
AP4_Cardinal co64_chunk_count = co64->GetChunkCount();
AP4_UI64* co64_chunk_offsets = co64->GetChunkOffsets();
- if(co64_chunk_count > chunk_offsets.ItemCount())
- {
+ if (co64_chunk_count > chunk_offsets.ItemCount()) {
return AP4_ERROR_OUT_OF_RANGE;
}
- for(unsigned int i = 0; i < co64_chunk_count; i++)
- {
+ for (unsigned int i=0; i<co64_chunk_count; i++) {
co64_chunk_offsets[i] = chunk_offsets[i];
}
return AP4_SUCCESS;
- }
- else
- {
+ } else {
return AP4_ERROR_INVALID_STATE;
}
}
diff --git a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4TrakAtom.h b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4TrakAtom.h
index 8aa57336f..8006375ee 100644
--- a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4TrakAtom.h
+++ b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4TrakAtom.h
@@ -1,6 +1,6 @@
/*****************************************************************
|
-| AP4 - trak Atoms
+| AP4 - trak Atoms
|
| Copyright 2002-2008 Axiomatic Systems, LLC
|
@@ -48,14 +48,13 @@ class AP4_SampleTable;
+---------------------------------------------------------------------*/
class AP4_TrakAtom : public AP4_ContainerAtom
{
-public:
+ public:
AP4_IMPLEMENT_DYNAMIC_CAST_D(AP4_TrakAtom, AP4_ContainerAtom)
// class methods
- static AP4_TrakAtom* Create(AP4_Size size,
- AP4_ByteStream& stream,
- AP4_AtomFactory& atom_factory)
- {
+ static AP4_TrakAtom* Create(AP4_Size size,
+ AP4_ByteStream& stream,
+ AP4_AtomFactory& atom_factory) {
return new AP4_TrakAtom(size, stream, atom_factory);
}
@@ -63,7 +62,7 @@ public:
AP4_TrakAtom(AP4_SampleTable* sample_table,
AP4_Atom::Type hdlr_type,
const char* hdlr_name,
- AP4_UI32 track_id,
+ AP4_UI32 track_id,
AP4_UI32 creation_time,
AP4_UI32 modification_time,
AP4_UI64 track_duration,
@@ -73,10 +72,7 @@ public:
const char* language,
AP4_UI32 width,
AP4_UI32 heigh);
- AP4_TkhdAtom* GetTkhdAtom()
- {
- return m_TkhdAtom;
- }
+ AP4_TkhdAtom* GetTkhdAtom() { return m_TkhdAtom; }
AP4_Result AdjustChunkOffsets(AP4_SI64 delta);
AP4_Result GetChunkOffsets(AP4_Array<AP4_UI64>& chunk_offsets);
AP4_Result SetChunkOffsets(const AP4_Array<AP4_UI64>& chunk_offsets);
@@ -92,8 +88,8 @@ public:
AP4_Result SetWidth(AP4_UI32 width);
AP4_UI32 GetHeight();
AP4_Result SetHeight(AP4_UI32 height);
-
-private:
+
+ private:
// methods
AP4_TrakAtom(AP4_UI32 size,
AP4_ByteStream& stream,
diff --git a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4TrefTypeAtom.cpp b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4TrefTypeAtom.cpp
index aa97f3d45..bac78fd4c 100644
--- a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4TrefTypeAtom.cpp
+++ b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4TrefTypeAtom.cpp
@@ -1,6 +1,6 @@
/*****************************************************************
|
-| AP4 - tref type Atoms
+| AP4 - tref type Atoms
|
| Copyright 2002-2008 Axiomatic Systems, LLC
|
@@ -47,16 +47,15 @@ AP4_TrefTypeAtom::AP4_TrefTypeAtom(AP4_Atom::Type type) :
/*----------------------------------------------------------------------
| AP4_TrefTypeAtom::AP4_TrefTypeAtom
+---------------------------------------------------------------------*/
-AP4_TrefTypeAtom::AP4_TrefTypeAtom(AP4_Atom::Type type,
- AP4_UI32 size,
+AP4_TrefTypeAtom::AP4_TrefTypeAtom(AP4_Atom::Type type,
+ AP4_UI32 size,
AP4_ByteStream& stream) :
AP4_Atom(type, size)
{
AP4_Size data_size = size - 8; // size and atom type
-
+
// read the track ids
- while(data_size >= 4)
- {
+ while (data_size >= 4) {
AP4_UI32 track_id;
stream.ReadUI32(track_id);
m_TrackIds.Append(track_id);
@@ -71,8 +70,7 @@ AP4_Result
AP4_TrefTypeAtom::AddTrackId(AP4_UI32 track_id)
{
AP4_Result result = m_TrackIds.Append(track_id);
- if(AP4_SUCCEEDED(result))
- {
+ if (AP4_SUCCEEDED(result)) {
m_Size32 += 4;
}
return result;
@@ -87,10 +85,9 @@ AP4_TrefTypeAtom::WriteFields(AP4_ByteStream& stream)
AP4_Result result = AP4_SUCCESS;
AP4_Size track_id_count = m_TrackIds.ItemCount();
- for(AP4_Ordinal i = 0; i < track_id_count; i++)
- {
+ for (AP4_Ordinal i=0; i<track_id_count; i++) {
result = stream.WriteUI32(m_TrackIds[i]);
- if(AP4_FAILED(result)) return result;
+ if (AP4_FAILED(result)) return result;
}
return AP4_SUCCESS;
@@ -103,9 +100,8 @@ AP4_Result
AP4_TrefTypeAtom::InspectFields(AP4_AtomInspector& inspector)
{
inspector.AddField("track_id_count", m_TrackIds.ItemCount());
- for(AP4_Ordinal i = 0; i < m_TrackIds.ItemCount(); i++)
- {
- inspector.AddField("track id ", m_TrackIds[i]);
+ for (AP4_Ordinal i=0; i<m_TrackIds.ItemCount(); i++) {
+ inspector.AddField("track id ", m_TrackIds[i]);
}
return AP4_SUCCESS;
}
diff --git a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4TrefTypeAtom.h b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4TrefTypeAtom.h
index 129e03250..438f03f53 100644
--- a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4TrefTypeAtom.h
+++ b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4TrefTypeAtom.h
@@ -1,6 +1,6 @@
/*****************************************************************
|
-| AP4 - tref type Atoms
+| AP4 - tref type Atoms
|
| Copyright 2002-2008 Axiomatic Systems, LLC
|
@@ -44,27 +44,23 @@ public:
AP4_IMPLEMENT_DYNAMIC_CAST_D(AP4_TrefTypeAtom, AP4_Atom)
// class methods
- static AP4_TrefTypeAtom* Create(AP4_Atom::Type type,
- AP4_UI32 size,
- AP4_ByteStream& stream)
- {
+ static AP4_TrefTypeAtom* Create(AP4_Atom::Type type,
+ AP4_UI32 size,
+ AP4_ByteStream& stream) {
return new AP4_TrefTypeAtom(type, size, stream);
}
// contructor
AP4_TrefTypeAtom(AP4_Atom::Type type);
-
+
// methods
virtual AP4_Result InspectFields(AP4_AtomInspector& inspector);
virtual AP4_Result WriteFields(AP4_ByteStream& stream);
AP4_Result AddTrackId(AP4_UI32 track_id);
// accessors
- const AP4_Array<AP4_UI32>& GetTrackIds()
- {
- return m_TrackIds;
- }
-
+ const AP4_Array<AP4_UI32>& GetTrackIds() { return m_TrackIds; }
+
private:
// methods
AP4_TrefTypeAtom(AP4_Atom::Type type, AP4_UI32 size, AP4_ByteStream& stream);
diff --git a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4TrexAtom.cpp b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4TrexAtom.cpp
index 7e0a8effc..6745e764a 100644
--- a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4TrexAtom.cpp
+++ b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4TrexAtom.cpp
@@ -1,6 +1,6 @@
/*****************************************************************
|
-| AP4 - trex Atoms
+| AP4 - trex Atoms
|
| Copyright 2002-2008 Axiomatic Systems, LLC
|
@@ -46,8 +46,8 @@ AP4_TrexAtom::Create(AP4_Size size, AP4_ByteStream& stream)
{
AP4_UI32 version;
AP4_UI32 flags;
- if(AP4_FAILED(AP4_Atom::ReadFullHeader(stream, version, flags))) return NULL;
- if(version != 0) return NULL;
+ if (AP4_FAILED(AP4_Atom::ReadFullHeader(stream, version, flags))) return NULL;
+ if (version != 0) return NULL;
return new AP4_TrexAtom(size, version, flags, stream);
}
@@ -59,7 +59,7 @@ AP4_TrexAtom::AP4_TrexAtom(AP4_UI32 track_id,
AP4_UI32 default_sample_duration,
AP4_UI32 default_sample_size,
AP4_UI32 default_sample_flags) :
- AP4_Atom(AP4_ATOM_TYPE_TREX, AP4_FULL_ATOM_HEADER_SIZE + 20, 0, 0),
+ AP4_Atom(AP4_ATOM_TYPE_TREX, AP4_FULL_ATOM_HEADER_SIZE+20, 0, 0),
m_TrackId(track_id),
m_DefaultSampleDescriptionIndex(default_sample_description_index),
m_DefaultSampleDuration(default_sample_duration),
@@ -71,7 +71,7 @@ AP4_TrexAtom::AP4_TrexAtom(AP4_UI32 track_id,
/*----------------------------------------------------------------------
| AP4_TrexAtom::AP4_TrexAtom
+---------------------------------------------------------------------*/
-AP4_TrexAtom::AP4_TrexAtom(AP4_UI32 size,
+AP4_TrexAtom::AP4_TrexAtom(AP4_UI32 size,
AP4_UI32 version,
AP4_UI32 flags,
AP4_ByteStream& stream) :
diff --git a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4TrexAtom.h b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4TrexAtom.h
index a8b19126f..42cf1fa2d 100644
--- a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4TrexAtom.h
+++ b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4TrexAtom.h
@@ -1,6 +1,6 @@
/*****************************************************************
|
-| AP4 - trex Atoms
+| AP4 - trex Atoms
|
| Copyright 2002-2008 Axiomatic Systems, LLC
|
@@ -61,40 +61,25 @@ public:
virtual AP4_Result WriteFields(AP4_ByteStream& stream);
// accessors
- AP4_UI32 GetTrackId()
- {
- return m_TrackId;
- }
- AP4_UI32 GetDefaultSampleDescriptionIndex()
- {
- return m_DefaultSampleDescriptionIndex;
- }
- AP4_UI32 GetDefaultSampleDuration()
- {
- return m_DefaultSampleDuration;
- }
- AP4_UI32 GetDefaultSampleSize()
- {
- return m_DefaultSampleSize;
- }
- AP4_UI32 GetDefaultSampleFlags()
- {
- return m_DefaultSampleFlags;
- }
+ AP4_UI32 GetTrackId() { return m_TrackId; }
+ AP4_UI32 GetDefaultSampleDescriptionIndex() { return m_DefaultSampleDescriptionIndex; }
+ AP4_UI32 GetDefaultSampleDuration() { return m_DefaultSampleDuration; }
+ AP4_UI32 GetDefaultSampleSize() { return m_DefaultSampleSize; }
+ AP4_UI32 GetDefaultSampleFlags() { return m_DefaultSampleFlags; }
private:
// methods
- AP4_TrexAtom(AP4_UI32 size,
+ AP4_TrexAtom(AP4_UI32 size,
AP4_UI32 version,
AP4_UI32 flags,
- AP4_ByteStream& stream);
+ AP4_ByteStream& stream);
// members
- AP4_UI32 m_TrackId;
- AP4_UI32 m_DefaultSampleDescriptionIndex;
- AP4_UI32 m_DefaultSampleDuration;
- AP4_UI32 m_DefaultSampleSize;
- AP4_UI32 m_DefaultSampleFlags;
+ AP4_UI32 m_TrackId;
+ AP4_UI32 m_DefaultSampleDescriptionIndex;
+ AP4_UI32 m_DefaultSampleDuration;
+ AP4_UI32 m_DefaultSampleSize;
+ AP4_UI32 m_DefaultSampleFlags;
};
#endif // _AP4_TREX_ATOM_H_
diff --git a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4TrunAtom.cpp b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4TrunAtom.cpp
index 56ee52726..e7d4ffc71 100644
--- a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4TrunAtom.cpp
+++ b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4TrunAtom.cpp
@@ -1,6 +1,6 @@
/*****************************************************************
|
-| AP4 - trun Atoms
+| AP4 - trun Atoms
|
| Copyright 2002-2008 Axiomatic Systems, LLC
|
@@ -45,22 +45,21 @@ AP4_TrunAtom::Create(AP4_Size size, AP4_ByteStream& stream)
{
AP4_UI32 version;
AP4_UI32 flags;
- if(AP4_FAILED(AP4_Atom::ReadFullHeader(stream, version, flags))) return NULL;
- if(version > 0) return NULL;
+ if (AP4_FAILED(AP4_Atom::ReadFullHeader(stream, version, flags))) return NULL;
+ if (version > 0) return NULL;
return new AP4_TrunAtom(size, version, flags, stream);
}
/*----------------------------------------------------------------------
| AP4_TrunAtom::ComputeRecordFieldsCount
+---------------------------------------------------------------------*/
-unsigned int
+unsigned int
AP4_TrunAtom::ComputeRecordFieldsCount(AP4_UI32 flags)
{
// count the number of bits set to 1 in the second byte of the flags
unsigned int count = 0;
- for(unsigned int i = 0; i < 8; i++)
- {
- if(flags & (1 << (i + 8))) ++count;
+ for (unsigned int i=0; i<8; i++) {
+ if (flags & (1<<(i+8))) ++count;
}
return count;
}
@@ -68,14 +67,13 @@ AP4_TrunAtom::ComputeRecordFieldsCount(AP4_UI32 flags)
/*----------------------------------------------------------------------
| AP4_TrunAtom::ComputeOptionalFieldsCount
+---------------------------------------------------------------------*/
-unsigned int
+unsigned int
AP4_TrunAtom::ComputeOptionalFieldsCount(AP4_UI32 flags)
{
// count the number of bits set to 1 in the LSB of the flags
unsigned int count = 0;
- for(unsigned int i = 0; i < 8; i++)
- {
- if(flags & (1 << i)) ++count;
+ for (unsigned int i=0; i<8; i++) {
+ if (flags & (1<<i)) ++count;
}
return count;
}
@@ -83,20 +81,20 @@ AP4_TrunAtom::ComputeOptionalFieldsCount(AP4_UI32 flags)
/*----------------------------------------------------------------------
| AP4_TrunAtom::AP4_TrunAtom
+---------------------------------------------------------------------*/
-AP4_TrunAtom::AP4_TrunAtom(AP4_UI32 flags,
+AP4_TrunAtom::AP4_TrunAtom(AP4_UI32 flags,
AP4_SI32 data_offset,
AP4_UI32 first_sample_flags) :
- AP4_Atom(AP4_ATOM_TYPE_TRUN, AP4_FULL_ATOM_HEADER_SIZE + 4, 0, flags),
+ AP4_Atom(AP4_ATOM_TYPE_TRUN, AP4_FULL_ATOM_HEADER_SIZE+4, 0, flags),
m_DataOffset(data_offset),
m_FirstSampleFlags(first_sample_flags)
{
- m_Size32 += 4 * ComputeOptionalFieldsCount(flags);
+ m_Size32 += 4*ComputeOptionalFieldsCount(flags);
}
/*----------------------------------------------------------------------
| AP4_TrunAtom::AP4_TrunAtom
+---------------------------------------------------------------------*/
-AP4_TrunAtom::AP4_TrunAtom(AP4_UI32 size,
+AP4_TrunAtom::AP4_TrunAtom(AP4_UI32 size,
AP4_UI32 version,
AP4_UI32 flags,
AP4_ByteStream& stream) :
@@ -107,54 +105,45 @@ AP4_TrunAtom::AP4_TrunAtom(AP4_UI32 size,
// read optional fields
int optional_fields_count = (int)ComputeOptionalFieldsCount(flags);
- if(flags & AP4_TRUN_FLAG_DATA_OFFSET_PRESENT)
- {
+ if (flags & AP4_TRUN_FLAG_DATA_OFFSET_PRESENT) {
AP4_UI32 offset = 0;
stream.ReadUI32(offset);
m_DataOffset = (AP4_SI32)offset;
--optional_fields_count;
}
- if(flags & AP4_TRUN_FLAG_FIRST_SAMPLE_FLAGS_PRESENT)
- {
+ if (flags & AP4_TRUN_FLAG_FIRST_SAMPLE_FLAGS_PRESENT) {
stream.ReadUI32(m_FirstSampleFlags);
--optional_fields_count;
}
-
- // discard unknown optional fields
- for(int i = 0; i < optional_fields_count; i++)
- {
+
+ // discard unknown optional fields
+ for (int i=0; i<optional_fields_count; i++) {
AP4_UI32 discard;
stream.ReadUI32(discard);
}
-
+
int record_fields_count = (int)ComputeRecordFieldsCount(flags);
m_Entries.SetItemCount(sample_count);
- for(unsigned int i = 0; i < sample_count; i++)
- {
- if(flags & AP4_TRUN_FLAG_SAMPLE_DURATION_PRESENT)
- {
+ for (unsigned int i=0; i<sample_count; i++) {
+ if (flags & AP4_TRUN_FLAG_SAMPLE_DURATION_PRESENT) {
stream.ReadUI32(m_Entries[i].sample_duration);
--record_fields_count;
}
- if(flags & AP4_TRUN_FLAG_SAMPLE_SIZE_PRESENT)
- {
+ if (flags & AP4_TRUN_FLAG_SAMPLE_SIZE_PRESENT) {
stream.ReadUI32(m_Entries[i].sample_size);
--record_fields_count;
}
- if(flags & AP4_TRUN_FLAG_SAMPLE_FLAGS_PRESENT)
- {
+ if (flags & AP4_TRUN_FLAG_SAMPLE_FLAGS_PRESENT) {
stream.ReadUI32(m_Entries[i].sample_flags);
--record_fields_count;
}
- if(flags & AP4_TRUN_FLAG_SAMPLE_COMPOSITION_TIME_OFFSET_PRESENT)
- {
+ if (flags & AP4_TRUN_FLAG_SAMPLE_COMPOSITION_TIME_OFFSET_PRESENT) {
stream.ReadUI32(m_Entries[i].sample_composition_time_offset);
--record_fields_count;
}
-
- // skip unknown fields
- for(int j = 0; j < record_fields_count; j++)
- {
+
+ // skip unknown fields
+ for (int j=0;j<record_fields_count; j++) {
AP4_UI32 discard;
stream.ReadUI32(discard);
}
@@ -168,44 +157,37 @@ AP4_Result
AP4_TrunAtom::WriteFields(AP4_ByteStream& stream)
{
AP4_Result result;
-
+
result = stream.WriteUI32(m_Entries.ItemCount());
- if(AP4_FAILED(result)) return result;
- if(m_Flags & AP4_TRUN_FLAG_DATA_OFFSET_PRESENT)
- {
+ if (AP4_FAILED(result)) return result;
+ if (m_Flags & AP4_TRUN_FLAG_DATA_OFFSET_PRESENT) {
result = stream.WriteUI32((AP4_UI32)m_DataOffset);
- if(AP4_FAILED(result)) return result;
+ if (AP4_FAILED(result)) return result;
}
- if(m_Flags & AP4_TRUN_FLAG_FIRST_SAMPLE_FLAGS_PRESENT)
- {
+ if (m_Flags & AP4_TRUN_FLAG_FIRST_SAMPLE_FLAGS_PRESENT) {
result = stream.WriteUI32(m_FirstSampleFlags);
- if(AP4_FAILED(result)) return result;
+ if (AP4_FAILED(result)) return result;
}
AP4_UI32 sample_count = m_Entries.ItemCount();
- for(unsigned int i = 0; i < sample_count; i++)
- {
- if(m_Flags & AP4_TRUN_FLAG_SAMPLE_DURATION_PRESENT)
- {
+ for (unsigned int i=0; i<sample_count; i++) {
+ if (m_Flags & AP4_TRUN_FLAG_SAMPLE_DURATION_PRESENT) {
result = stream.WriteUI32(m_Entries[i].sample_duration);
- if(AP4_FAILED(result)) return result;
+ if (AP4_FAILED(result)) return result;
}
- if(m_Flags & AP4_TRUN_FLAG_SAMPLE_SIZE_PRESENT)
- {
+ if (m_Flags & AP4_TRUN_FLAG_SAMPLE_SIZE_PRESENT) {
result = stream.WriteUI32(m_Entries[i].sample_size);
- if(AP4_FAILED(result)) return result;
+ if (AP4_FAILED(result)) return result;
}
- if(m_Flags & AP4_TRUN_FLAG_SAMPLE_FLAGS_PRESENT)
- {
+ if (m_Flags & AP4_TRUN_FLAG_SAMPLE_FLAGS_PRESENT) {
result = stream.WriteUI32(m_Entries[i].sample_flags);
- if(AP4_FAILED(result)) return result;
+ if (AP4_FAILED(result)) return result;
}
- if(m_Flags & AP4_TRUN_FLAG_SAMPLE_COMPOSITION_TIME_OFFSET_PRESENT)
- {
+ if (m_Flags & AP4_TRUN_FLAG_SAMPLE_COMPOSITION_TIME_OFFSET_PRESENT) {
stream.WriteUI32(m_Entries[i].sample_composition_time_offset);
- if(AP4_FAILED(result)) return result;
+ if (AP4_FAILED(result)) return result;
}
}
-
+
return AP4_SUCCESS;
}
@@ -216,19 +198,15 @@ AP4_Result
AP4_TrunAtom::InspectFields(AP4_AtomInspector& inspector)
{
inspector.AddField("sample count", m_Entries.ItemCount());
- if(m_Flags & AP4_TRUN_FLAG_DATA_OFFSET_PRESENT)
- {
+ if (m_Flags & AP4_TRUN_FLAG_DATA_OFFSET_PRESENT) {
inspector.AddField("data offset", m_DataOffset);
}
- if(m_Flags & AP4_TRUN_FLAG_FIRST_SAMPLE_FLAGS_PRESENT)
- {
+ if (m_Flags & AP4_TRUN_FLAG_FIRST_SAMPLE_FLAGS_PRESENT) {
inspector.AddField("first sample flags", m_FirstSampleFlags, AP4_AtomInspector::HINT_HEX);
}
- if(inspector.GetVerbosity() >= 1)
- {
- AP4_UI32 sample_count = m_Entries.ItemCount();
- for(unsigned int i = 0; i < sample_count; i++)
- {
+ if (inspector.GetVerbosity() >= 1) {
+ AP4_UI32 sample_count = m_Entries.ItemCount();
+ for (unsigned int i=0; i<sample_count; i++) {
char header[32];
AP4_FormatString(header, sizeof(header), "entry %04d", i);
char v0[32];
@@ -239,23 +217,19 @@ AP4_TrunAtom::InspectFields(AP4_AtomInspector& inspector)
const char* s1 = "";
const char* s2 = "";
const char* s3 = "";
- if(m_Flags & AP4_TRUN_FLAG_SAMPLE_DURATION_PRESENT)
- {
+ if (m_Flags & AP4_TRUN_FLAG_SAMPLE_DURATION_PRESENT) {
AP4_FormatString(v0, sizeof(v0), "sample duration:%d", m_Entries[i].sample_duration);
s0 = v0;
}
- if(m_Flags & AP4_TRUN_FLAG_SAMPLE_SIZE_PRESENT)
- {
+ if (m_Flags & AP4_TRUN_FLAG_SAMPLE_SIZE_PRESENT) {
AP4_FormatString(v1, sizeof(v1), "sample size:%d", m_Entries[i].sample_size);
s1 = v1;
}
- if(m_Flags & AP4_TRUN_FLAG_SAMPLE_FLAGS_PRESENT)
- {
+ if (m_Flags & AP4_TRUN_FLAG_SAMPLE_FLAGS_PRESENT) {
AP4_FormatString(v2, sizeof(v2), "sample flags:%x", m_Entries[i].sample_flags);
s2 = v2;
}
- if(m_Flags & AP4_TRUN_FLAG_SAMPLE_COMPOSITION_TIME_OFFSET_PRESENT)
- {
+ if (m_Flags & AP4_TRUN_FLAG_SAMPLE_COMPOSITION_TIME_OFFSET_PRESENT) {
AP4_FormatString(v3, sizeof(v3), "sample composition time offset:%d", m_Entries[i].sample_composition_time_offset);
s3 = v3;
}
@@ -264,6 +238,6 @@ AP4_TrunAtom::InspectFields(AP4_AtomInspector& inspector)
inspector.AddField(header, value);
}
}
-
+
return AP4_SUCCESS;
}
diff --git a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4TrunAtom.h b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4TrunAtom.h
index fe4c43700..9bdc382b3 100644
--- a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4TrunAtom.h
+++ b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4TrunAtom.h
@@ -1,6 +1,6 @@
/*****************************************************************
|
-| AP4 - trun Atoms
+| AP4 - trun Atoms
|
| Copyright 2002-2008 Axiomatic Systems, LLC
|
@@ -54,44 +54,34 @@ public:
AP4_IMPLEMENT_DYNAMIC_CAST(AP4_TrunAtom)
// types
- struct Entry
- {
+ struct Entry {
Entry() : sample_duration(0), sample_size(0), sample_flags(0), sample_composition_time_offset(0) {}
AP4_UI32 sample_duration;
AP4_UI32 sample_size;
AP4_UI32 sample_flags;
AP4_UI32 sample_composition_time_offset;
};
-
+
// class methods
static AP4_TrunAtom* Create(AP4_Size size, AP4_ByteStream& stream);
static unsigned int ComputeOptionalFieldsCount(AP4_UI32 flags);
static unsigned int ComputeRecordFieldsCount(AP4_UI32 flags);
// methods
- AP4_TrunAtom(AP4_UI32 flags,
+ AP4_TrunAtom(AP4_UI32 flags,
AP4_SI32 data_offset,
AP4_UI32 first_sample_flags);
virtual AP4_Result InspectFields(AP4_AtomInspector& inspector);
virtual AP4_Result WriteFields(AP4_ByteStream& stream);
// accessors
- AP4_SI32 GetDataOffset()
- {
- return m_DataOffset;
- }
- AP4_UI32 GetFirstSampleFlags()
- {
- return m_FirstSampleFlags;
- }
- const AP4_Array<Entry>& GetEntries()
- {
- return m_Entries;
- }
-
+ AP4_SI32 GetDataOffset() { return m_DataOffset; }
+ AP4_UI32 GetFirstSampleFlags() { return m_FirstSampleFlags; }
+ const AP4_Array<Entry>& GetEntries() { return m_Entries; }
+
private:
// methods
- AP4_TrunAtom(AP4_UI32 size,
+ AP4_TrunAtom(AP4_UI32 size,
AP4_UI32 version,
AP4_UI32 flags,
AP4_ByteStream& stream);
diff --git a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4Types.h b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4Types.h
index 0d42b8043..86409c337 100644
--- a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4Types.h
+++ b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4Types.h
@@ -52,22 +52,21 @@ typedef unsigned long AP4_Size;
// the rest depends on whether the platform supports 64-bit integers
#if defined(AP4_CONFIG_HAVE_INT64)
-// we have 64-bit integers
-typedef AP4_CONFIG_INT64_TYPE AP4_SI64;
-typedef unsigned AP4_CONFIG_INT64_TYPE AP4_UI64;
-typedef unsigned AP4_CONFIG_INT64_TYPE AP4_LargeSize;
-typedef AP4_CONFIG_INT64_TYPE AP4_Offset;
-typedef unsigned AP4_CONFIG_INT64_TYPE AP4_Position;
+ // we have 64-bit integers
+ typedef AP4_CONFIG_INT64_TYPE AP4_SI64;
+ typedef unsigned AP4_CONFIG_INT64_TYPE AP4_UI64;
+ typedef unsigned AP4_CONFIG_INT64_TYPE AP4_LargeSize;
+ typedef AP4_CONFIG_INT64_TYPE AP4_Offset;
+ typedef unsigned AP4_CONFIG_INT64_TYPE AP4_Position;
#else
-// use only 32-bit integers
-typedef struct
-{
- AP4_UI32 hi;
- AP4_UI32 lo;
-} AP4_UI64, AP4_SI64;
-typedef unsigned long AP4_LargeSize;
-typedef long AP4_Offset;
-typedef unsigned long AP4_Position;
+ // use only 32-bit integers
+ typedef struct {
+ AP4_UI32 hi;
+ AP4_UI32 lo;
+ } AP4_UI64, AP4_SI64;
+ typedef unsigned long AP4_LargeSize;
+ typedef long AP4_Offset;
+ typedef unsigned long AP4_Position;
#endif
#ifndef NULL
diff --git a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4UrlAtom.cpp b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4UrlAtom.cpp
index 0989e8d58..8659d9837 100644
--- a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4UrlAtom.cpp
+++ b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4UrlAtom.cpp
@@ -1,6 +1,6 @@
/*****************************************************************
|
-| AP4 - url Atoms
+| AP4 - url Atoms
|
| Copyright 2002-2008 Axiomatic Systems, LLC
|
@@ -41,8 +41,8 @@ AP4_UrlAtom::Create(AP4_Size size, AP4_ByteStream& stream)
{
AP4_UI32 version;
AP4_UI32 flags;
- if(AP4_FAILED(AP4_Atom::ReadFullHeader(stream, version, flags))) return NULL;
- if(version != 0) return NULL;
+ if (AP4_FAILED(AP4_Atom::ReadFullHeader(stream, version, flags))) return NULL;
+ if (version != 0) return NULL;
return new AP4_UrlAtom(size, version, flags, stream);
}
@@ -57,18 +57,16 @@ AP4_UrlAtom::AP4_UrlAtom() :
/*----------------------------------------------------------------------
| AP4_UrlAtom::AP4_UrlAtom
+---------------------------------------------------------------------*/
-AP4_UrlAtom::AP4_UrlAtom(AP4_UI32 size,
+AP4_UrlAtom::AP4_UrlAtom(AP4_UI32 size,
AP4_UI32 version,
AP4_UI32 flags,
AP4_ByteStream& stream) :
AP4_Atom(AP4_ATOM_TYPE_URL, size, version, flags)
{
- if((m_Flags & 1) == 0)
- {
+ if ((m_Flags & 1) == 0) {
// not self contained
- AP4_Size str_size = size - AP4_FULL_ATOM_HEADER_SIZE;
- if(str_size > 0)
- {
+ AP4_Size str_size = size-AP4_FULL_ATOM_HEADER_SIZE;
+ if (str_size > 0) {
char* str = new char[str_size];
stream.Read(str, str_size);
str[str_size-1] = '\0'; // force null-termination
@@ -84,22 +82,18 @@ AP4_UrlAtom::AP4_UrlAtom(AP4_UI32 size,
AP4_Result
AP4_UrlAtom::WriteFields(AP4_ByteStream& stream)
{
- if(m_Flags & 1)
- {
+ if (m_Flags & 1) {
// local ref (self contained)
return AP4_SUCCESS;
- }
- else
- {
+ } else {
// url (not self contained)
- if(m_Size32 > AP4_FULL_ATOM_HEADER_SIZE)
- {
- AP4_Result result = stream.Write(m_Url.GetChars(), m_Url.GetLength() + 1);
- if(AP4_FAILED(result)) return result;
+ if (m_Size32 > AP4_FULL_ATOM_HEADER_SIZE) {
+ AP4_Result result = stream.Write(m_Url.GetChars(), m_Url.GetLength()+1);
+ if (AP4_FAILED(result)) return result;
// pad with zeros if necessary
- AP4_Size padding = m_Size32 - (AP4_FULL_ATOM_HEADER_SIZE + m_Url.GetLength() + 1);
- while(padding--) stream.WriteUI08(0);
+ AP4_Size padding = m_Size32-(AP4_FULL_ATOM_HEADER_SIZE+m_Url.GetLength()+1);
+ while (padding--) stream.WriteUI08(0);
}
return AP4_SUCCESS;
}
@@ -111,12 +105,9 @@ AP4_UrlAtom::WriteFields(AP4_ByteStream& stream)
AP4_Result
AP4_UrlAtom::InspectFields(AP4_AtomInspector& inspector)
{
- if(m_Flags & 1)
- {
+ if (m_Flags & 1) {
inspector.AddField("location", "[local to file]");
- }
- else
- {
+ } else {
inspector.AddField("location", m_Url.GetChars());
}
diff --git a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4UrlAtom.h b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4UrlAtom.h
index 001dc8ef6..3e354f70c 100644
--- a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4UrlAtom.h
+++ b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4UrlAtom.h
@@ -1,6 +1,6 @@
/*****************************************************************
|
-| AP4 - url Atoms
+| AP4 - url Atoms
|
| Copyright 2002-2008 Axiomatic Systems, LLC
|
@@ -51,7 +51,7 @@ public:
private:
// methods
- AP4_UrlAtom(AP4_UI32 size,
+ AP4_UrlAtom(AP4_UI32 size,
AP4_UI32 version,
AP4_UI32 flags,
AP4_ByteStream& stream);
diff --git a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4Utils.cpp b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4Utils.cpp
index b7a8d81dd..ef7834a3c 100644
--- a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4Utils.cpp
+++ b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4Utils.cpp
@@ -40,7 +40,7 @@ AP4_BytesToDoubleBE(const unsigned char* bytes)
AP4_UI64 i_value = AP4_BytesToUInt64BE(bytes);
void* v_value = reinterpret_cast<void*>(&i_value);
double* d_value = reinterpret_cast<double*>(v_value);
-
+
return *d_value;
}
@@ -50,15 +50,15 @@ AP4_BytesToDoubleBE(const unsigned char* bytes)
AP4_UI64
AP4_BytesToUInt64BE(const unsigned char* bytes)
{
- return
- (((AP4_UI64)bytes[0]) << 56) |
- (((AP4_UI64)bytes[1]) << 48) |
- (((AP4_UI64)bytes[2]) << 40) |
- (((AP4_UI64)bytes[3]) << 32) |
- (((AP4_UI64)bytes[4]) << 24) |
- (((AP4_UI64)bytes[5]) << 16) |
- (((AP4_UI64)bytes[6]) << 8) |
- (((AP4_UI64)bytes[7]));
+ return
+ ( ((AP4_UI64)bytes[0])<<56 ) |
+ ( ((AP4_UI64)bytes[1])<<48 ) |
+ ( ((AP4_UI64)bytes[2])<<40 ) |
+ ( ((AP4_UI64)bytes[3])<<32 ) |
+ ( ((AP4_UI64)bytes[4])<<24 ) |
+ ( ((AP4_UI64)bytes[5])<<16 ) |
+ ( ((AP4_UI64)bytes[6])<<8 ) |
+ ( ((AP4_UI64)bytes[7]) );
}
/*----------------------------------------------------------------------
@@ -69,7 +69,7 @@ AP4_BytesFromDoubleBE(unsigned char* bytes, double value)
{
void* v_value = reinterpret_cast<void*>(&value);
AP4_UI64* i_value = reinterpret_cast<AP4_UI64*>(v_value);
-
+
AP4_BytesFromUInt64BE(bytes, *i_value);
}
@@ -86,7 +86,7 @@ AP4_BytesFromUInt64BE(unsigned char* bytes, AP4_UI64 value)
bytes[4] = (unsigned char)(value >> 24);
bytes[5] = (unsigned char)(value >> 16);
bytes[6] = (unsigned char)(value >> 8);
- bytes[7] = (unsigned char)(value);
+ bytes[7] = (unsigned char)(value );
}
/*----------------------------------------------------------------------
@@ -95,33 +95,32 @@ AP4_BytesFromUInt64BE(unsigned char* bytes, AP4_UI64 value)
AP4_UI32
AP4_DurationMsFromUnits(AP4_UI64 units, AP4_UI32 units_per_second)
{
- if(units_per_second == 0) return 0;
- return (AP4_UI32)(((double)units * 1000.0) / (double)units_per_second);
+ if (units_per_second == 0) return 0;
+ return (AP4_UI32)(((double)units*1000.0)/(double)units_per_second);
}
/*----------------------------------------------------------------------
| AP4_ConvertTime
+---------------------------------------------------------------------*/
-AP4_UI64
+AP4_UI64
AP4_ConvertTime(AP4_UI64 time_value,
AP4_UI32 from_time_scale,
AP4_UI32 to_time_scale)
{
- if(from_time_scale == 0) return 0;
- double ratio = (double)to_time_scale / (double)from_time_scale;
- return ((AP4_UI64)((double)time_value * ratio));
+ if (from_time_scale == 0) return 0;
+ double ratio = (double)to_time_scale/(double)from_time_scale;
+ return ((AP4_UI64)((double)time_value*ratio));
}
/*----------------------------------------------------------------------
| AP4_FormatFourChars
+---------------------------------------------------------------------*/
void
-AP4_FormatFourChars(char* str, AP4_UI32 value)
-{
+AP4_FormatFourChars(char* str, AP4_UI32 value) {
str[0] = (value >> 24) & 0xFF;
str[1] = (value >> 16) & 0xFF;
str[2] = (value >> 8) & 0xFF;
- str[3] = (value) & 0xFF;
+ str[3] = (value ) & 0xFF;
str[4] = '\0';
}
@@ -129,13 +128,10 @@ AP4_FormatFourChars(char* str, AP4_UI32 value)
| AP4_FormatFourCharsPrintable
+---------------------------------------------------------------------*/
void
-AP4_FormatFourCharsPrintable(char* str, AP4_UI32 value)
-{
+AP4_FormatFourCharsPrintable(char* str, AP4_UI32 value) {
AP4_FormatFourChars(str, value);
- for(int i = 0; i < 4; i++)
- {
- if(str[i] < ' ' || str[i] >= 127)
- {
+ for (int i=0; i<4; i++) {
+ if (str[i]<' ' || str[i] >= 127) {
str[i] = '.';
}
}
@@ -149,18 +145,14 @@ AP4_SplitArgs(char* arg, char*& arg0, char*& arg1)
{
arg0 = arg;
char* c = arg;
- while(*c != 0 && *c != ':')
- {
+ while (*c != 0 && *c != ':') {
c++;
}
- if(*c == ':')
- {
+ if (*c == ':') {
*c++ = '\0';
arg1 = c;
return AP4_SUCCESS;
- }
- else
- {
+ } else {
return AP4_FAILURE;
}
}
@@ -172,7 +164,7 @@ AP4_Result
AP4_SplitArgs(char* arg, char*& arg0, char*& arg1, char*& arg2)
{
AP4_Result result = AP4_SplitArgs(arg, arg0, arg1);
- if(AP4_FAILED(result)) return result;
+ if (AP4_FAILED(result)) return result;
return AP4_SplitArgs(arg1, arg1, arg2);
}
@@ -182,48 +174,24 @@ AP4_SplitArgs(char* arg, char*& arg0, char*& arg1, char*& arg2)
unsigned char
AP4_HexNibble(char c)
{
- switch(c)
- {
- case '0':
- return 0;
- case '1':
- return 1;
- case '2':
- return 2;
- case '3':
- return 3;
- case '4':
- return 4;
- case '5':
- return 5;
- case '6':
- return 6;
- case '7':
- return 7;
- case '8':
- return 8;
- case '9':
- return 9;
- case 'a':
- case 'A':
- return 10;
- case 'b':
- case 'B':
- return 11;
- case 'c':
- case 'C':
- return 12;
- case 'd':
- case 'D':
- return 13;
- case 'e':
- case 'E':
- return 14;
- case 'f':
- case 'F':
- return 15;
- default:
- return 0;
+ switch (c) {
+ case '0': return 0;
+ case '1': return 1;
+ case '2': return 2;
+ case '3': return 3;
+ case '4': return 4;
+ case '5': return 5;
+ case '6': return 6;
+ case '7': return 7;
+ case '8': return 8;
+ case '9': return 9;
+ case 'a': case 'A': return 10;
+ case 'b': case 'B': return 11;
+ case 'c': case 'C': return 12;
+ case 'd': case 'D': return 13;
+ case 'e': case 'E': return 14;
+ case 'f': case 'F': return 15;
+ default: return 0;
}
}
@@ -231,18 +199,13 @@ AP4_HexNibble(char c)
| AP4_NibbleHex
+---------------------------------------------------------------------*/
char
-AP4_NibbleHex(unsigned int nibble)
+AP4_NibbleHex(unsigned int nibble)
{
- if(nibble < 10)
- {
- return '0' + nibble;
- }
- else if(nibble < 16)
- {
- return 'A' + (nibble - 10);
- }
- else
- {
+ if (nibble < 10) {
+ return '0'+nibble;
+ } else if (nibble < 16) {
+ return 'A'+(nibble-10);
+ } else {
return ' ';
}
}
@@ -253,9 +216,8 @@ AP4_NibbleHex(unsigned int nibble)
AP4_Result
AP4_ParseHex(const char* hex, unsigned char* bytes, unsigned int count)
{
- if(AP4_StringLength(hex) != 2 * count) return AP4_ERROR_INVALID_PARAMETERS;
- for(unsigned int i = 0; i < count; i++)
- {
+ if (AP4_StringLength(hex) != 2*count) return AP4_ERROR_INVALID_PARAMETERS;
+ for (unsigned int i=0; i<count; i++) {
bytes[i] = (AP4_HexNibble(hex[2*i]) << 4) | (AP4_HexNibble(hex[2*i+1]));
}
return AP4_SUCCESS;
@@ -267,37 +229,32 @@ AP4_ParseHex(const char* hex, unsigned char* bytes, unsigned int count)
AP4_Result
AP4_FormatHex(const AP4_UI08* data, unsigned int data_size, char* hex)
{
- for(unsigned int i = 0; i < data_size; i++)
- {
- *hex++ = AP4_NibbleHex(data[i] >> 4);
- *hex++ = AP4_NibbleHex(data[i] & 0x0F);
+ for (unsigned int i=0; i<data_size; i++) {
+ *hex++ = AP4_NibbleHex(data[i]>>4);
+ *hex++ = AP4_NibbleHex(data[i]&0x0F);
}
-
+
return AP4_SUCCESS;
}
/*----------------------------------------------------------------------
| AP4_BitWriter::Write
+---------------------------------------------------------------------*/
-void
+void
AP4_BitWriter::Write(AP4_UI32 bits, unsigned int bit_count)
{
unsigned char* data = m_Data;
- if(m_BitCount + bit_count > m_DataSize * 8) return;
- data += m_BitCount / 8;
- unsigned int space = 8 - (m_BitCount % 8);
- while(bit_count)
- {
- unsigned int mask = bit_count == 32 ? 0xFFFFFFFF : ((1 << bit_count) - 1);
- if(bit_count <= space)
- {
- *data |= ((bits & mask) << (space - bit_count));
+ if (m_BitCount+bit_count > m_DataSize*8) return;
+ data += m_BitCount/8;
+ unsigned int space = 8-(m_BitCount%8);
+ while (bit_count) {
+ unsigned int mask = bit_count==32 ? 0xFFFFFFFF : ((1<<bit_count)-1);
+ if (bit_count <= space) {
+ *data |= ((bits&mask) << (space-bit_count));
m_BitCount += bit_count;
return;
- }
- else
- {
- *data |= ((bits & mask) >> (bit_count - space));
+ } else {
+ *data |= ((bits&mask) >> (bit_count-space));
++data;
m_BitCount += space;
bit_count -= space;
diff --git a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4Utils.h b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4Utils.h
index df3f9c228..e2d3b6c93 100644
--- a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4Utils.h
+++ b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4Utils.h
@@ -51,11 +51,11 @@ void AP4_BytesFromUInt64BE(unsigned char* bytes, AP4_UI64 value);
inline AP4_UI32
AP4_BytesToUInt32BE(const unsigned char* bytes)
{
- return
- (((AP4_UI32)bytes[0]) << 24) |
- (((AP4_UI32)bytes[1]) << 16) |
- (((AP4_UI32)bytes[2]) << 8) |
- (((AP4_UI32)bytes[3]));
+ return
+ ( ((AP4_UI32)bytes[0])<<24 ) |
+ ( ((AP4_UI32)bytes[1])<<16 ) |
+ ( ((AP4_UI32)bytes[2])<<8 ) |
+ ( ((AP4_UI32)bytes[3]) );
}
/*----------------------------------------------------------------------
@@ -73,10 +73,10 @@ AP4_BytesToInt32BE(const unsigned char* bytes)
inline AP4_UI32
AP4_BytesToUInt24BE(const unsigned char* bytes)
{
- return
- (((AP4_UI32)bytes[0]) << 16) |
- (((AP4_UI32)bytes[1]) << 8) |
- (((AP4_UI32)bytes[2]));
+ return
+ ( ((AP4_UI32)bytes[0])<<16 ) |
+ ( ((AP4_UI32)bytes[1])<<8 ) |
+ ( ((AP4_UI32)bytes[2]) );
}
/*----------------------------------------------------------------------
@@ -85,9 +85,9 @@ AP4_BytesToUInt24BE(const unsigned char* bytes)
inline AP4_UI16
AP4_BytesToUInt16BE(const unsigned char* bytes)
{
- return
- (((AP4_UI16)bytes[0]) << 8) |
- (((AP4_UI16)bytes[1]));
+ return
+ ( ((AP4_UI16)bytes[0])<<8 ) |
+ ( ((AP4_UI16)bytes[1]) );
}
/*----------------------------------------------------------------------
@@ -108,7 +108,7 @@ AP4_BytesFromUInt32BE(unsigned char* bytes, AP4_UI32 value)
bytes[0] = (unsigned char)(value >> 24);
bytes[1] = (unsigned char)(value >> 16);
bytes[2] = (unsigned char)(value >> 8);
- bytes[3] = (unsigned char)(value);
+ bytes[3] = (unsigned char)(value );
}
/*----------------------------------------------------------------------
@@ -119,7 +119,7 @@ AP4_BytesFromUInt24BE(unsigned char* bytes, AP4_UI32 value)
{
bytes[0] = (unsigned char)(value >> 16);
bytes[1] = (unsigned char)(value >> 8);
- bytes[2] = (unsigned char)(value);
+ bytes[2] = (unsigned char)(value );
}
/*----------------------------------------------------------------------
@@ -129,7 +129,7 @@ inline void
AP4_BytesFromUInt16BE(unsigned char* bytes, AP4_UI16 value)
{
bytes[0] = (unsigned char)(value >> 8);
- bytes[1] = (unsigned char)(value);
+ bytes[1] = (unsigned char)(value );
}
/*----------------------------------------------------------------------
@@ -187,34 +187,21 @@ AP4_SplitArgs(char* arg, char*& arg0, char*& arg1);
class AP4_BitWriter
{
public:
- AP4_BitWriter(AP4_Size size) : m_DataSize(size), m_BitCount(0)
- {
- if(size)
- {
+ AP4_BitWriter(AP4_Size size) : m_DataSize(size), m_BitCount(0) {
+ if (size) {
m_Data = new unsigned char[size];
AP4_SetMemory(m_Data, 0, size);
- }
- else
- {
+ } else {
m_Data = NULL;
}
}
- ~AP4_BitWriter()
- {
- delete m_Data;
- }
-
+ ~AP4_BitWriter() { delete m_Data; }
+
void Write(AP4_UI32 bits, unsigned int bit_count);
-
- unsigned int GetBitCount()
- {
- return m_BitCount;
- }
- const unsigned char* GetData()
- {
- return m_Data;
- }
-
+
+ unsigned int GetBitCount() { return m_BitCount; }
+ const unsigned char* GetData() { return m_Data; }
+
private:
unsigned char* m_Data;
unsigned int m_DataSize;
diff --git a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4UuidAtom.cpp b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4UuidAtom.cpp
index 27981438d..e71eced66 100644
--- a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4UuidAtom.cpp
+++ b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4UuidAtom.cpp
@@ -1,6 +1,6 @@
/*****************************************************************
|
-| AP4 - UUID Atoms
+| AP4 - UUID Atoms
|
| Copyright 2002-2008 Axiomatic Systems, LLC
|
@@ -36,7 +36,7 @@
/*----------------------------------------------------------------------
| AP4_UuidAtom::AP4_UuidAtom
+---------------------------------------------------------------------*/
-AP4_UuidAtom::AP4_UuidAtom(AP4_UI64 size, const AP4_UI08* uuid) :
+AP4_UuidAtom::AP4_UuidAtom(AP4_UI64 size, const AP4_UI08* uuid) :
AP4_Atom(AP4_ATOM_TYPE_UUID, size)
{
AP4_CopyMemory(m_Uuid, uuid, 16);
@@ -45,7 +45,7 @@ AP4_UuidAtom::AP4_UuidAtom(AP4_UI64 size, const AP4_UI08* uuid) :
/*----------------------------------------------------------------------
| AP4_UuidAtom::AP4_UuidAtom
+---------------------------------------------------------------------*/
-AP4_UuidAtom::AP4_UuidAtom(AP4_UI64 size, const AP4_UI08* uuid, AP4_UI32 version, AP4_UI32 flags) :
+AP4_UuidAtom::AP4_UuidAtom(AP4_UI64 size, const AP4_UI08* uuid, AP4_UI32 version, AP4_UI32 flags) :
AP4_Atom(AP4_ATOM_TYPE_UUID, size, false, version, flags)
{
AP4_CopyMemory(m_Uuid, uuid, 16);
@@ -54,11 +54,10 @@ AP4_UuidAtom::AP4_UuidAtom(AP4_UI64 size, const AP4_UI08* uuid, AP4_UI32 version
/*----------------------------------------------------------------------
| AP4_UuidAtom::AP4_UuidAtom
+---------------------------------------------------------------------*/
-AP4_UuidAtom::AP4_UuidAtom(AP4_UI64 size, bool is_full, AP4_ByteStream& stream) :
+AP4_UuidAtom::AP4_UuidAtom(AP4_UI64 size, bool is_full, AP4_ByteStream& stream) :
AP4_Atom(AP4_ATOM_TYPE_UUID, size)
{
- if(is_full)
- {
+ if (is_full) {
m_IsFull = true;
ReadFullHeader(stream, m_Version, m_Flags);
}
@@ -70,7 +69,7 @@ AP4_UuidAtom::AP4_UuidAtom(AP4_UI64 size, bool is_full, AP4_ByteStream& stream)
AP4_Size
AP4_UuidAtom::GetHeaderSize() const
{
- return (m_IsFull ? AP4_FULL_UUID_ATOM_HEADER_SIZE : AP4_UUID_ATOM_HEADER_SIZE) + (m_Size32 == 1 ? 8 : 0);
+ return (m_IsFull ? AP4_FULL_UUID_ATOM_HEADER_SIZE : AP4_UUID_ATOM_HEADER_SIZE)+(m_Size32==1?8:0);
}
/*----------------------------------------------------------------------
@@ -83,30 +82,28 @@ AP4_UuidAtom::WriteHeader(AP4_ByteStream& stream)
// write the size
result = stream.WriteUI32(m_Size32);
- if(AP4_FAILED(result)) return result;
+ if (AP4_FAILED(result)) return result;
// write the type
result = stream.WriteUI32(m_Type);
- if(AP4_FAILED(result)) return result;
+ if (AP4_FAILED(result)) return result;
// handle 64-bit sizes
- if(m_Size32 == 1)
- {
+ if (m_Size32 == 1) {
result = stream.WriteUI64(m_Size64);
- if(AP4_FAILED(result)) return result;
+ if (AP4_FAILED(result)) return result;
}
- // write the extended type
+ // write the extended type
result = stream.Write(m_Uuid, 16);
- if(AP4_FAILED(result)) return result;
-
+ if (AP4_FAILED(result)) return result;
+
// for full atoms, write version and flags
- if(m_IsFull)
- {
+ if (m_IsFull) {
result = stream.WriteUI08(m_Version);
- if(AP4_FAILED(result)) return result;
+ if (AP4_FAILED(result)) return result;
result = stream.WriteUI24(m_Flags);
- if(AP4_FAILED(result)) return result;
+ if (AP4_FAILED(result)) return result;
}
return AP4_SUCCESS;
@@ -121,13 +118,12 @@ AP4_UuidAtom::InspectHeader(AP4_AtomInspector& inspector)
char uuid[37];
uuid[36] = '\0';
char* dst = uuid;
- for(unsigned int i = 0; i < 16; i++)
- {
- *dst++ = AP4_NibbleHex(m_Uuid[i] >> 4);
- *dst++ = AP4_NibbleHex(m_Uuid[i] & 0x0F);
- if(i == 5 || i == 7 || i == 9 || i == 11) *dst++ = '-';
+ for (unsigned int i=0; i<16; i++) {
+ *dst++ = AP4_NibbleHex(m_Uuid[i]>>4);
+ *dst++ = AP4_NibbleHex(m_Uuid[i]&0x0F);
+ if (i == 5 || i == 7 || i == 9 || i == 11) *dst++ = '-';
}
-
+
// write atom name
char name[7];
name[0] = '[';
@@ -136,33 +132,27 @@ AP4_UuidAtom::InspectHeader(AP4_AtomInspector& inspector)
name[6] = '\0';
char header[128];
char extra[32] = "";
- if(m_IsFull)
- {
- if(m_Version && m_Flags)
- {
- AP4_FormatString(extra, sizeof(extra),
+ if (m_IsFull) {
+ if (m_Version && m_Flags) {
+ AP4_FormatString(extra, sizeof(extra),
", version=%d, flags=%x",
m_Version,
m_Flags);
- }
- else if(m_Version)
- {
- AP4_FormatString(extra, sizeof(extra),
+ } else if (m_Version) {
+ AP4_FormatString(extra, sizeof(extra),
", version=%d",
m_Version);
- }
- else if(m_Flags)
- {
- AP4_FormatString(extra, sizeof(extra),
+ } else if (m_Flags) {
+ AP4_FormatString(extra, sizeof(extra),
", flags=%x",
m_Flags);
}
}
- AP4_FormatString(header, sizeof(header),
- "{%s} size=%ld+%lld%s",
+ AP4_FormatString(header, sizeof(header),
+ "{%s} size=%ld+%lld%s",
uuid,
- GetHeaderSize(),
- GetSize() - GetHeaderSize(),
+ GetHeaderSize(),
+ GetSize()-GetHeaderSize(),
extra);
inspector.StartElement(name, header);
@@ -172,22 +162,22 @@ AP4_UuidAtom::InspectHeader(AP4_AtomInspector& inspector)
/*----------------------------------------------------------------------
| AP4_UnknownUuidAtom::AP4_UnknownUuidAtom
+---------------------------------------------------------------------*/
-AP4_UnknownUuidAtom::AP4_UnknownUuidAtom(AP4_UI64 size, AP4_ByteStream& stream) :
+AP4_UnknownUuidAtom::AP4_UnknownUuidAtom(AP4_UI64 size, AP4_ByteStream& stream) :
AP4_UuidAtom(size, false, stream)
{
// store the data
- m_Data.SetDataSize((AP4_Size)size - GetHeaderSize());
+ m_Data.SetDataSize((AP4_Size)size-GetHeaderSize());
stream.Read(m_Data.UseData(), m_Data.GetDataSize());
}
/*----------------------------------------------------------------------
| AP4_UnknownUuidAtom::AP4_UnknownUuidAtom
+---------------------------------------------------------------------*/
-AP4_UnknownUuidAtom::AP4_UnknownUuidAtom(AP4_UI64 size, const AP4_UI08* uuid, AP4_ByteStream& stream) :
+AP4_UnknownUuidAtom::AP4_UnknownUuidAtom(AP4_UI64 size, const AP4_UI08* uuid, AP4_ByteStream& stream) :
AP4_UuidAtom(size, uuid)
{
// store the data
- m_Data.SetDataSize((AP4_Size)size - GetHeaderSize());
+ m_Data.SetDataSize((AP4_Size)size-GetHeaderSize());
stream.Read(m_Data.UseData(), m_Data.GetDataSize());
}
diff --git a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4UuidAtom.h b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4UuidAtom.h
index 763fd53cd..2c425193a 100644
--- a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4UuidAtom.h
+++ b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4UuidAtom.h
@@ -1,6 +1,6 @@
/*****************************************************************
|
-| AP4 - UUID Atoms
+| AP4 - UUID Atoms
|
| Copyright 2002-2008 Axiomatic Systems, LLC
|
@@ -26,7 +26,7 @@
|
****************************************************************/
/**
-* @file
+* @file
* @brief UUID Atoms
*/
@@ -42,8 +42,8 @@
/*----------------------------------------------------------------------
| constants
+---------------------------------------------------------------------*/
-const AP4_UI32 AP4_UUID_ATOM_HEADER_SIZE = AP4_ATOM_HEADER_SIZE + 16;
-const AP4_UI32 AP4_FULL_UUID_ATOM_HEADER_SIZE = AP4_FULL_ATOM_HEADER_SIZE + 16;
+const AP4_UI32 AP4_UUID_ATOM_HEADER_SIZE = AP4_ATOM_HEADER_SIZE+16;
+const AP4_UI32 AP4_FULL_UUID_ATOM_HEADER_SIZE = AP4_FULL_ATOM_HEADER_SIZE+16;
/*----------------------------------------------------------------------
| AP4_UuidAtom
@@ -51,8 +51,7 @@ const AP4_UI32 AP4_FULL_UUID_ATOM_HEADER_SIZE = AP4_FULL_ATOM_HEADER_SIZE + 16;
/**
* Base class for uuid atoms.
*/
-class AP4_UuidAtom : public AP4_Atom
-{
+class AP4_UuidAtom : public AP4_Atom {
public:
// constructor and destructor
virtual ~AP4_UuidAtom() {};
@@ -63,11 +62,8 @@ public:
virtual AP4_Result InspectHeader(AP4_AtomInspector& inspector);
// accessors
- const AP4_UI08* GetUuid()
- {
- return m_Uuid;
- }
-
+ const AP4_UI08* GetUuid() { return m_Uuid; }
+
protected:
// members
AP4_UuidAtom(AP4_UI64 size, const AP4_UI08* uuid);
@@ -82,8 +78,7 @@ protected:
/**
* Unknown uuid atoms.
*/
-class AP4_UnknownUuidAtom : public AP4_UuidAtom
-{
+class AP4_UnknownUuidAtom : public AP4_UuidAtom {
public:
// constructors
AP4_UnknownUuidAtom(AP4_UI64 size, AP4_ByteStream& stream);
diff --git a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4VmhdAtom.cpp b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4VmhdAtom.cpp
index fc48d1ceb..0aaf37c72 100644
--- a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4VmhdAtom.cpp
+++ b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4VmhdAtom.cpp
@@ -1,6 +1,6 @@
/*****************************************************************
|
-| AP4 - vmhd Atoms
+| AP4 - vmhd Atoms
|
| Copyright 2002-2008 Axiomatic Systems, LLC
|
@@ -42,8 +42,8 @@ AP4_VmhdAtom::Create(AP4_Size size, AP4_ByteStream& stream)
{
AP4_UI32 version;
AP4_UI32 flags;
- if(AP4_FAILED(AP4_Atom::ReadFullHeader(stream, version, flags))) return NULL;
- if(version != 0) return NULL;
+ if (AP4_FAILED(AP4_Atom::ReadFullHeader(stream, version, flags))) return NULL;
+ if (version != 0) return NULL;
return new AP4_VmhdAtom(size, version, flags, stream);
}
@@ -51,7 +51,7 @@ AP4_VmhdAtom::Create(AP4_Size size, AP4_ByteStream& stream)
| AP4_VmhdAtom::AP4_VmhdAtom
+---------------------------------------------------------------------*/
AP4_VmhdAtom::AP4_VmhdAtom(AP4_UI16 graphics_mode, AP4_UI16 r, AP4_UI16 g, AP4_UI16 b) :
- AP4_Atom(AP4_ATOM_TYPE_VMHD, AP4_FULL_ATOM_HEADER_SIZE + 8, 0, 0),
+ AP4_Atom(AP4_ATOM_TYPE_VMHD, AP4_FULL_ATOM_HEADER_SIZE+8, 0, 0),
m_GraphicsMode(graphics_mode)
{
m_OpColor[0] = r;
@@ -62,7 +62,7 @@ AP4_VmhdAtom::AP4_VmhdAtom(AP4_UI16 graphics_mode, AP4_UI16 r, AP4_UI16 g, AP4_U
/*----------------------------------------------------------------------
| AP4_VmhdAtom::AP4_VmhdAtom
+---------------------------------------------------------------------*/
-AP4_VmhdAtom::AP4_VmhdAtom(AP4_UI32 size,
+AP4_VmhdAtom::AP4_VmhdAtom(AP4_UI32 size,
AP4_UI32 version,
AP4_UI32 flags,
AP4_ByteStream& stream) :
@@ -82,11 +82,11 @@ AP4_VmhdAtom::WriteFields(AP4_ByteStream& stream)
// graphics mode
result = stream.WriteUI16(m_GraphicsMode);
- if(AP4_FAILED(result)) return result;
+ if (AP4_FAILED(result)) return result;
// op color
result = stream.Write(m_OpColor, sizeof(m_OpColor));
- if(AP4_FAILED(result)) return result;
+ if (AP4_FAILED(result)) return result;
return AP4_SUCCESS;
}
@@ -100,7 +100,7 @@ AP4_VmhdAtom::InspectFields(AP4_AtomInspector& inspector)
inspector.AddField("graphics_mode", m_GraphicsMode);
char formatted[16];
AP4_FormatString(formatted, sizeof(formatted), "%04x,%04x,%04x",
- m_OpColor[0], m_OpColor[1], m_OpColor[2]);
+ m_OpColor[0], m_OpColor[1], m_OpColor[2]);
inspector.AddField("op_color", formatted);
return AP4_SUCCESS;
diff --git a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4VmhdAtom.h b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4VmhdAtom.h
index ba9f82da8..6fed056e3 100644
--- a/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4VmhdAtom.h
+++ b/src/filters/parser/MP4Splitter/AP4/Source/Core/Ap4VmhdAtom.h
@@ -1,6 +1,6 @@
/*****************************************************************
|
-| AP4 - vmhd Atoms
+| AP4 - vmhd Atoms
|
| Copyright 2002-2008 Axiomatic Systems, LLC
|
@@ -50,7 +50,7 @@ public:
private:
// methods
- AP4_VmhdAtom(AP4_UI32 size,
+ AP4_VmhdAtom(AP4_UI32 size,
AP4_UI32 version,
AP4_UI32 flags,
AP4_ByteStream& stream);
diff --git a/src/filters/parser/MP4Splitter/AP4/Source/Crypto/Ap4AesBlockCipher.cpp b/src/filters/parser/MP4Splitter/AP4/Source/Crypto/Ap4AesBlockCipher.cpp
index e084cb96d..ef0619901 100644
--- a/src/filters/parser/MP4Splitter/AP4/Source/Crypto/Ap4AesBlockCipher.cpp
+++ b/src/filters/parser/MP4Splitter/AP4/Source/Crypto/Ap4AesBlockCipher.cpp
@@ -11,23 +11,23 @@ All rights reserved.
LICENSE TERMS
-The free distribution and use of this software in both source and binary
+The free distribution and use of this software in both source and binary
form is allowed (with or without changes) provided that:
-1. distributions of this source code include the above copyright
+1. distributions of this source code include the above copyright
notice, this list of conditions and the following disclaimer;
2. distributions in binary form include the above copyright
notice, this list of conditions and the following disclaimer
in the documentation and/or other associated materials;
-3. the copyright holder's name is not used to endorse products
-built using this software without specific written permission.
+3. the copyright holder's name is not used to endorse products
+built using this software without specific written permission.
DISCLAIMER
This software is provided 'as is' with no explicit or implied warranties
-in respect of its properties, including, but not limited to, correctness
+in respect of its properties, including, but not limited to, correctness
and fitness for purpose.
-------------------------------------------------------------------------
Issue Date: 29/07/2002
@@ -46,8 +46,7 @@ typedef AP4_UI32 aes_32t;
typedef AP4_UI08 aes_08t;
typedef unsigned int aes_rval;
struct aes_ctx // the AES context for encryption
-{
- aes_32t k_sch[4*AP4_AES_BLOCK_SIZE]; // the encryption key schedule
+{ aes_32t k_sch[4*AP4_AES_BLOCK_SIZE]; // the encryption key schedule
aes_32t n_rnd; // the number of cipher rounds
aes_32t n_blk; // the number of bytes in the state
};
@@ -69,21 +68,21 @@ struct aes_ctx // the AES context for encryption
/* START OF CONFIGURATION OPTIONS
USE OF DEFINES
-
- Later in this section there are a number of defines that control the
- operation of the code. In each section, the purpose of each define is
- explained so that the relevant form can be included or excluded by
- setting either 1's or 0's respectively on the branches of the related
+
+ Later in this section there are a number of defines that control the
+ operation of the code. In each section, the purpose of each define is
+ explained so that the relevant form can be included or excluded by
+ setting either 1's or 0's respectively on the branches of the related
#if clauses.
*/
/* 1. BYTE ORDER IN 32-BIT WORDS
- To obtain the highest speed on processors with 32-bit words, this code
+ To obtain the highest speed on processors with 32-bit words, this code
needs to determine the order in which bytes are packed into such words.
- The following block of code is an attempt to capture the most obvious
- ways in which various environemnts define byte order. It may well fail,
- in which case the definitions will need to be set by editing at the
+ The following block of code is an attempt to capture the most obvious
+ ways in which various environemnts define byte order. It may well fail,
+ in which case the definitions will need to be set by editing at the
points marked **** EDIT HERE IF NECESSARY **** below.
*/
#define AES_LITTLE_ENDIAN 1234 /* byte 0 is least significant (i386) */
@@ -105,27 +104,27 @@ struct aes_ctx // the AES context for encryption
/* 2. BYTE ORDER WITHIN 32 BIT WORDS
- The fundamental data processing units in Rijndael are 8-bit bytes. The
- input, output and key input are all enumerated arrays of bytes in which
- bytes are numbered starting at zero and increasing to one less than the
- number of bytes in the array in question. This enumeration is only used
- for naming bytes and does not imply any adjacency or order relationship
- from one byte to another. When these inputs and outputs are considered
- as bit sequences, bits 8*n to 8*n+7 of the bit sequence are mapped to
- byte[n] with bit 8n+i in the sequence mapped to bit 7-i within the byte.
- In this implementation bits are numbered from 0 to 7 starting at the
+ The fundamental data processing units in Rijndael are 8-bit bytes. The
+ input, output and key input are all enumerated arrays of bytes in which
+ bytes are numbered starting at zero and increasing to one less than the
+ number of bytes in the array in question. This enumeration is only used
+ for naming bytes and does not imply any adjacency or order relationship
+ from one byte to another. When these inputs and outputs are considered
+ as bit sequences, bits 8*n to 8*n+7 of the bit sequence are mapped to
+ byte[n] with bit 8n+i in the sequence mapped to bit 7-i within the byte.
+ In this implementation bits are numbered from 0 to 7 starting at the
numerically least significant end of each byte (bit n represents 2^n).
- However, Rijndael can be implemented more efficiently using 32-bit
+ However, Rijndael can be implemented more efficiently using 32-bit
words by packing bytes into words so that bytes 4*n to 4*n+3 are placed
- into word[n]. While in principle these bytes can be assembled into words
- in any positions, this implementation only supports the two formats in
+ into word[n]. While in principle these bytes can be assembled into words
+ in any positions, this implementation only supports the two formats in
which bytes in adjacent positions within words also have adjacent byte
- numbers. This order is called big-endian if the lowest numbered bytes
- in words have the highest numeric significance and little-endian if the
- opposite applies.
-
- This code can work in either order irrespective of the order used by the
+ numbers. This order is called big-endian if the lowest numbered bytes
+ in words have the highest numeric significance and little-endian if the
+ opposite applies.
+
+ This code can work in either order irrespective of the order used by the
machine on which it runs. Normally the internal byte order will be set
to the order of the processor on which the code is to be run but this
define can be used to reverse this in special situations
@@ -138,20 +137,20 @@ struct aes_ctx // the AES context for encryption
#define INTERNAL_BYTE_ORDER AES_BIG_ENDIAN
#endif
-/* 3. FAST INPUT/OUTPUT OPERATIONS.
+/* 3. FAST INPUT/OUTPUT OPERATIONS.
- On some machines it is possible to improve speed by transferring the
- bytes in the input and output arrays to and from the internal 32-bit
- variables by addressing these arrays as if they are arrays of 32-bit
- words. On some machines this will always be possible but there may
- be a large performance penalty if the byte arrays are not aligned on
- the normal word boundaries. On other machines this technique will
+ On some machines it is possible to improve speed by transferring the
+ bytes in the input and output arrays to and from the internal 32-bit
+ variables by addressing these arrays as if they are arrays of 32-bit
+ words. On some machines this will always be possible but there may
+ be a large performance penalty if the byte arrays are not aligned on
+ the normal word boundaries. On other machines this technique will
lead to memory access errors when such 32-bit word accesses are not
- properly aligned. The option SAFE_IO avoids such problems but will
- often be slower on those machines that support misaligned access
- (especially so if care is taken to align the input and output byte
- arrays on 32-bit word boundaries). If SAFE_IO is not defined it is
- assumed that access to byte arrays as if they are arrays of 32-bit
+ properly aligned. The option SAFE_IO avoids such problems but will
+ often be slower on those machines that support misaligned access
+ (especially so if care is taken to align the input and output byte
+ arrays on 32-bit word boundaries). If SAFE_IO is not defined it is
+ assumed that access to byte arrays as if they are arrays of 32-bit
words will not cause problems when such accesses are misaligned.
*/
#if 1
@@ -161,12 +160,12 @@ struct aes_ctx // the AES context for encryption
/* 4. LOOP UNROLLING
The code for encryption and decrytpion cycles through a number of rounds
- that can be implemented either in a loop or by expanding the code into a
+ that can be implemented either in a loop or by expanding the code into a
long sequence of instructions, the latter producing a larger program but
one that will often be much faster. The latter is called loop unrolling.
There are also potential speed advantages in expanding two iterations in
a loop with half the number of iterations, which is called partial loop
- unrolling. The following options allow partial or full loop unrolling
+ unrolling. The following options allow partial or full loop unrolling
to be set independently for encryption and decryption
*/
#if 0
@@ -187,8 +186,8 @@ struct aes_ctx // the AES context for encryption
/* 5. FIXED OR DYNAMIC TABLES
- When this section is included the tables used by the code are comipled
- statically into the binary file. Otherwise they are computed once when
+ When this section is included the tables used by the code are comipled
+ statically into the binary file. Otherwise they are computed once when
the code is first used.
*/
#if 1
@@ -197,7 +196,7 @@ struct aes_ctx // the AES context for encryption
/* 6. FAST FINITE FIELD OPERATIONS
- If this section is included, tables are used to provide faster finite
+ If this section is included, tables are used to provide faster finite
field arithmetic (this has no effect if FIXED_TABLES is defined).
*/
#if 1
@@ -206,8 +205,8 @@ struct aes_ctx // the AES context for encryption
/* 7. INTERNAL STATE VARIABLE FORMAT
- The internal state of Rijndael is stored in a number of local 32-bit
- word varaibles which can be defined either as an array or as individual
+ The internal state of Rijndael is stored in a number of local 32-bit
+ word varaibles which can be defined either as an array or as individual
names variables. Include this section if you want to store these local
variables in arrays. Otherwise individual local variables will be used.
*/
@@ -217,10 +216,10 @@ struct aes_ctx // the AES context for encryption
/* In this implementation the columns of the state array are each held in
32-bit words. The state array can be held in various ways: in an array
- of words, in a number of individual word variables or in a number of
+ of words, in a number of individual word variables or in a number of
processor registers. The following define maps a variable name x and
a column number c to the way the state array variable is to be held.
- The first define below maps the state into an array x[c] whereas the
+ The first define below maps the state into an array x[c] whereas the
second form maps the state into a number of individual variables x0,
x1, etc. Another form could map individual state colums to machine
register names.
@@ -246,16 +245,16 @@ struct aes_ctx // the AES context for encryption
This cipher proceeds by repeating in a number of cycles known as 'rounds'
which are implemented by a round function which can optionally be speeded
- up using tables. The basic tables are each 256 32-bit words, with either
+ up using tables. The basic tables are each 256 32-bit words, with either
one or four tables being required for each round function depending on
how much speed is required. The encryption and decryption round functions
are different and the last encryption and decrytpion round functions are
different again making four different round functions in all.
This means that:
- 1. Normal encryption and decryption rounds can each use either 0, 1
+ 1. Normal encryption and decryption rounds can each use either 0, 1
or 4 tables and table spaces of 0, 1024 or 4096 bytes each.
- 2. The last encryption and decryption rounds can also use either 0, 1
+ 2. The last encryption and decryption rounds can also use either 0, 1
or 4 tables and table spaces of 0, 1024 or 4096 bytes each.
Include or exclude the appropriate definitions below to set the number
@@ -295,7 +294,7 @@ struct aes_ctx // the AES context for encryption
#endif
/* The decryption key schedule can be speeded up with tables in the same
- way that the round functions can. Include or exclude the following
+ way that the round functions can. Include or exclude the following
defines to set this requirement.
*/
#if 1
@@ -317,7 +316,7 @@ struct aes_ctx // the AES context for encryption
#if defined(BLOCK_SIZE) && ((BLOCK_SIZE & 3) || BLOCK_SIZE < 16 || BLOCK_SIZE > 32)
#error An illegal block size has been specified.
-#endif
+#endif
#if !defined(BLOCK_SIZE)
#define RC_LENGTH 29
@@ -332,7 +331,7 @@ struct aes_ctx // the AES context for encryption
#define LAST_ENC_ROUND NO_TABLES
#elif ENC_ROUND == ONE_TABLE && LAST_ENC_ROUND == FOUR_TABLES
#undef LAST_ENC_ROUND
-#define LAST_ENC_ROUND ONE_TABLE
+#define LAST_ENC_ROUND ONE_TABLE
#endif
#if ENC_ROUND == NO_TABLES && ENC_UNROLL != NONE
@@ -345,7 +344,7 @@ struct aes_ctx // the AES context for encryption
#define LAST_DEC_ROUND NO_TABLES
#elif DEC_ROUND == ONE_TABLE && LAST_DEC_ROUND == FOUR_TABLES
#undef LAST_DEC_ROUND
-#define LAST_DEC_ROUND ONE_TABLE
+#define LAST_DEC_ROUND ONE_TABLE
#endif
#if DEC_ROUND == NO_TABLES && DEC_UNROLL != NONE
@@ -355,11 +354,11 @@ struct aes_ctx // the AES context for encryption
/* upr(x,n): rotates bytes within words by n positions, moving bytes to
higher index positions with wrap around into low positions
- ups(x,n): moves bytes by n positions to higher index positions in
+ ups(x,n): moves bytes by n positions to higher index positions in
words but without wrap around
bval(x,n): extracts a byte from a word
- NOTE: The definitions given here are intended only for use with
+ NOTE: The definitions given here are intended only for use with
unsigned variables and with shift counts that are compile
time constants
*/
@@ -401,7 +400,7 @@ struct aes_ctx // the AES context for encryption
#if !defined(_MSC_VER)
#define _lrotl(x,n) ((((aes_32t)(x)) << n) | (((aes_32t)(x)) >> (32 - n)))
#endif
-#define bswap_32(x) ((_lrotl((x),8) & 0x00ff00ff) | (_lrotl((x),24) & 0xff00ff00))
+#define bswap_32(x) ((_lrotl((x),8) & 0x00ff00ff) | (_lrotl((x),24) & 0xff00ff00))
#endif
#define word_in(x) bswap_32(*(aes_32t*)(x))
@@ -424,9 +423,9 @@ struct aes_ctx // the AES context for encryption
give improved performance if a fast 32-bit multiply is not available. Note
that a temporary variable u needs to be defined where FFmulX is used.
-#define FFmulX(x) (u = (x) & m1, u |= (u >> 1), ((x) & m2) << 1) ^ ((u >> 3) | (u >> 6))
+#define FFmulX(x) (u = (x) & m1, u |= (u >> 1), ((x) & m2) << 1) ^ ((u >> 3) | (u >> 6))
#define m4 (0x01010101 * BPOLY)
-#define FFmulX(x) (u = (x) & m1, ((x) & m2) << 1) ^ ((u - (u >> 7)) & m4)
+#define FFmulX(x) (u = (x) & m1, ((x) & m2) << 1) ^ ((u - (u >> 7)) & m4)
*/
/* Work out which tables are needed for the different options */
@@ -651,7 +650,7 @@ void gen_tabs(void);
/*----------------------------------------------------------------------
| tables
+---------------------------------------------------------------------*/
-#if defined(FIXED_TABLES) || !defined(FF_TABLES)
+#if defined(FIXED_TABLES) || !defined(FF_TABLES)
/* finite field arithmetic operations */
@@ -773,7 +772,7 @@ void gen_tabs(void);
#define h0(x) (x)
-/* These defines are used to ensure tables are generated in the
+/* These defines are used to ensure tables are generated in the
right format depending on the internal byte order required
*/
@@ -831,16 +830,16 @@ static const aes_08t inv_s_box[256] = { isb_data(h0) };
static const aes_32t ft_tab[256] = { sb_data(u0) };
#endif
#ifdef FT4_SET
-static const aes_32t ft_tab[4][256] =
-{ { sb_data(u0) }, { sb_data(u1) }, { sb_data(u2) }, { sb_data(u3) } };
+static const aes_32t ft_tab[4][256] =
+ { { sb_data(u0) }, { sb_data(u1) }, { sb_data(u2) }, { sb_data(u3) } };
#endif
#ifdef FL1_SET
static const aes_32t fl_tab[256] = { sb_data(w0) };
#endif
#ifdef FL4_SET
-static const aes_32t fl_tab[4][256] =
-{ { sb_data(w0) }, { sb_data(w1) }, { sb_data(w2) }, { sb_data(w3) } };
+static const aes_32t fl_tab[4][256] =
+ { { sb_data(w0) }, { sb_data(w1) }, { sb_data(w2) }, { sb_data(w3) } };
#endif
#ifdef IT1_SET
@@ -848,15 +847,15 @@ static const aes_32t it_tab[256] = { isb_data(v0) };
#endif
#ifdef IT4_SET
static const aes_32t it_tab[4][256] =
-{ { isb_data(v0) }, { isb_data(v1) }, { isb_data(v2) }, { isb_data(v3) } };
+ { { isb_data(v0) }, { isb_data(v1) }, { isb_data(v2) }, { isb_data(v3) } };
#endif
#ifdef IL1_SET
static const aes_32t il_tab[256] = { isb_data(w0) };
#endif
#ifdef IL4_SET
-static const aes_32t il_tab[4][256] =
-{ { isb_data(w0) }, { isb_data(w1) }, { isb_data(w2) }, { isb_data(w3) } };
+static const aes_32t il_tab[4][256] =
+ { { isb_data(w0) }, { isb_data(w1) }, { isb_data(w2) }, { isb_data(w3) } };
#endif
#ifdef LS1_SET
@@ -864,15 +863,15 @@ static const aes_32t ls_tab[256] = { sb_data(w0) };
#endif
#ifdef LS4_SET
static const aes_32t ls_tab[4][256] =
-{ { sb_data(w0) }, { sb_data(w1) }, { sb_data(w2) }, { sb_data(w3) } };
+ { { sb_data(w0) }, { sb_data(w1) }, { sb_data(w2) }, { sb_data(w3) } };
#endif
#ifdef IM1_SET
static const aes_32t im_tab[256] = { mm_data(v0) };
#endif
#ifdef IM4_SET
-static const aes_32t im_tab[4][256] =
-{ { mm_data(v0) }, { mm_data(v1) }, { mm_data(v2) }, { mm_data(v3) } };
+static const aes_32t im_tab[4][256] =
+ { { mm_data(v0) }, { mm_data(v1) }, { mm_data(v2) }, { mm_data(v3) } };
#endif
#else /* dynamic table generation */
@@ -936,8 +935,8 @@ aes_32t im_tab[4][256];
/* Generate the tables for the dynamic table option
- It will generally be sensible to use tables to compute finite
- field multiplies and inverses but where memory is scarse this
+ It will generally be sensible to use tables to compute finite
+ field multiplies and inverses but where memory is scarse this
code might sometimes be better. But it only has effect during
initialisation so its pretty unimportant in overall terms.
*/
@@ -948,9 +947,8 @@ aes_32t im_tab[4][256];
*/
static aes_08t hibit(const aes_32t x)
-{
- aes_08t r = (aes_08t)((x >> 1) | (x >> 2));
-
+{ aes_08t r = (aes_08t)((x >> 1) | (x >> 2));
+
r |= (r >> 2);
r |= (r >> 4);
return (r + 1) >> 1;
@@ -959,8 +957,7 @@ static aes_08t hibit(const aes_32t x)
/* return the inverse of the finite field element x */
static aes_08t fi(const aes_08t x)
-{
- aes_08t p1 = x, p2 = BPOLY, n1 = hibit(x), n2 = 0x80, v1 = 1, v2 = 0;
+{ aes_08t p1 = x, p2 = BPOLY, n1 = hibit(x), n2 = 0x80, v1 = 1, v2 = 0;
if(x < 2) return x;
@@ -969,21 +966,15 @@ static aes_08t fi(const aes_08t x)
if(!n1) return v1;
while(n2 >= n1)
- {
- n2 /= n1;
- p2 ^= p1 * n2;
- v2 ^= v1 * n2;
- n2 = hibit(p2);
+ {
+ n2 /= n1; p2 ^= p1 * n2; v2 ^= v1 * n2; n2 = hibit(p2);
}
-
+
if(!n2) return v2;
while(n1 >= n2)
- {
- n1 /= n2;
- p1 ^= p2 * n1;
- v1 ^= v2 * n1;
- n1 = hibit(p1);
+ {
+ n1 /= n2; p1 ^= p2 * n1; v1 ^= v2 * n1; n1 = hibit(p1);
}
}
}
@@ -1011,8 +1002,7 @@ static aes_08t fi(const aes_08t x)
(w = (aes_32t)x, w = (w<<1)^(w<<3)^(w<<6), 0x05^(aes_08t)(w^(w>>8)))
void gen_tabs(void)
-{
- aes_32t i, w;
+{ aes_32t i, w;
#if defined(FF_TABLES)
@@ -1023,16 +1013,15 @@ void gen_tabs(void)
root is 0x03, used here to generate the tables
*/
- i = 0;
- w = 1;
+ i = 0; w = 1;
do
- {
+ {
pow[i] = (aes_08t)w;
pow[i + 255] = (aes_08t)w;
log[w] = (aes_08t)i++;
- w ^= (w << 1) ^(w & 0x80 ? WPOLY : 0);
+ w ^= (w << 1) ^ (w & 0x80 ? WPOLY : 0);
}
- while(w != 1);
+ while (w != 1);
#endif
@@ -1043,8 +1032,7 @@ void gen_tabs(void)
}
for(i = 0; i < 256; ++i)
- {
- aes_08t b;
+ { aes_08t b;
b = fwd_affine(fi((aes_08t)i));
w = bytes2word(f2(b), b, b, f3(b));
@@ -1058,9 +1046,9 @@ void gen_tabs(void)
#endif
#ifdef FT4_SET
ft_tab[0][i] = w;
- ft_tab[1][i] = upr(w, 1);
- ft_tab[2][i] = upr(w, 2);
- ft_tab[3][i] = upr(w, 3);
+ ft_tab[1][i] = upr(w,1);
+ ft_tab[2][i] = upr(w,2);
+ ft_tab[3][i] = upr(w,3);
#endif
w = bytes2word(b, 0, 0, 0);
@@ -1069,9 +1057,9 @@ void gen_tabs(void)
#endif
#ifdef FL4_SET
fl_tab[0][i] = w;
- fl_tab[1][i] = upr(w, 1);
- fl_tab[2][i] = upr(w, 2);
- fl_tab[3][i] = upr(w, 3);
+ fl_tab[1][i] = upr(w,1);
+ fl_tab[2][i] = upr(w,2);
+ fl_tab[3][i] = upr(w,3);
#endif
#ifdef LS1_SET /* table for key schedule if fl_tab above is */
@@ -1079,9 +1067,9 @@ void gen_tabs(void)
#endif
#ifdef LS4_SET
ls_tab[0][i] = w;
- ls_tab[1][i] = upr(w, 1);
- ls_tab[2][i] = upr(w, 2);
- ls_tab[3][i] = upr(w, 3);
+ ls_tab[1][i] = upr(w,1);
+ ls_tab[2][i] = upr(w,2);
+ ls_tab[3][i] = upr(w,3);
#endif
b = fi(inv_affine((aes_08t)i));
@@ -1092,9 +1080,9 @@ void gen_tabs(void)
#endif
#ifdef IM4_SET
im_tab[0][b] = w;
- im_tab[1][b] = upr(w, 1);
- im_tab[2][b] = upr(w, 2);
- im_tab[3][b] = upr(w, 3);
+ im_tab[1][b] = upr(w,1);
+ im_tab[2][b] = upr(w,2);
+ im_tab[3][b] = upr(w,3);
#endif
#ifdef ISB_SET
@@ -1105,9 +1093,9 @@ void gen_tabs(void)
#endif
#ifdef IT4_SET
it_tab[0][i] = w;
- it_tab[1][i] = upr(w, 1);
- it_tab[2][i] = upr(w, 2);
- it_tab[3][i] = upr(w, 3);
+ it_tab[1][i] = upr(w,1);
+ it_tab[2][i] = upr(w,2);
+ it_tab[3][i] = upr(w,3);
#endif
w = bytes2word(b, 0, 0, 0);
#ifdef IL1_SET /* tables for last decryption round */
@@ -1115,9 +1103,9 @@ void gen_tabs(void)
#endif
#ifdef IL4_SET
il_tab[0][i] = w;
- il_tab[1][i] = upr(w, 1);
- il_tab[2][i] = upr(w, 2);
- il_tab[3][i] = upr(w, 3);
+ il_tab[1][i] = upr(w,1);
+ il_tab[2][i] = upr(w,2);
+ il_tab[3][i] = upr(w,3);
#endif
}
@@ -1137,10 +1125,9 @@ static aes_rval aes_blk_len(unsigned int blen, aes_ctx cx[1])
if(!tab_init) gen_tabs();
#endif
- if((blen & 7) || blen < 16 || blen > 32)
- {
- cx->n_blk = 0;
- return aes_bad;
+ if((blen & 7) || blen < 16 || blen > 32)
+ {
+ cx->n_blk = 0; return aes_bad;
}
cx->n_blk = blen;
@@ -1154,10 +1141,10 @@ static aes_rval aes_blk_len(unsigned int blen, aes_ctx cx[1])
This corresponds to bit lengths of 128, 192 and 256 bits, and
to Nk values of 4, 6 and 8 respectively.
- The following macros implement a single cycle in the key
- schedule generation process. The number of cycles needed
+ The following macros implement a single cycle in the key
+ schedule generation process. The number of cycles needed
for each cx->n_col and nk value is:
-
+
nk = 4 5 6 7 8
------------------------------
cx->n_col = 4 10 9 8 7 7
@@ -1200,8 +1187,7 @@ static aes_rval aes_blk_len(unsigned int blen, aes_ctx cx[1])
#if defined(ENCRYPTION_KEY_SCHEDULE)
static aes_rval aes_enc_key(const unsigned char in_key[], unsigned int klen, aes_ctx cx[1])
-{
- aes_32t ss[8];
+{ aes_32t ss[8];
#if !defined(FIXED_TABLES)
if(!tab_init) gen_tabs();
@@ -1212,10 +1198,10 @@ static aes_rval aes_enc_key(const unsigned char in_key[], unsigned int klen, aes
#else
cx->n_blk = BLOCK_SIZE;
#endif
-
+
cx->n_blk = (cx->n_blk & ~3) | 1;
- cx->k_sch[0] = ss[0] = word_in(in_key);
+ cx->k_sch[0] = ss[0] = word_in(in_key );
cx->k_sch[1] = ss[1] = word_in(in_key + 4);
cx->k_sch[2] = ss[2] = word_in(in_key + 8);
cx->k_sch[3] = ss[3] = word_in(in_key + 12);
@@ -1224,79 +1210,53 @@ static aes_rval aes_enc_key(const unsigned char in_key[], unsigned int klen, aes
switch(klen)
{
- case 16:
- ke4(cx->k_sch, 0);
- ke4(cx->k_sch, 1);
- ke4(cx->k_sch, 2);
- ke4(cx->k_sch, 3);
- ke4(cx->k_sch, 4);
- ke4(cx->k_sch, 5);
- ke4(cx->k_sch, 6);
- ke4(cx->k_sch, 7);
- ke4(cx->k_sch, 8);
- kel4(cx->k_sch, 9);
- cx->n_rnd = 10;
- break;
- case 24:
- cx->k_sch[4] = ss[4] = word_in(in_key + 16);
- cx->k_sch[5] = ss[5] = word_in(in_key + 20);
- ke6(cx->k_sch, 0);
- ke6(cx->k_sch, 1);
- ke6(cx->k_sch, 2);
- ke6(cx->k_sch, 3);
- ke6(cx->k_sch, 4);
- ke6(cx->k_sch, 5);
- ke6(cx->k_sch, 6);
- kel6(cx->k_sch, 7);
- cx->n_rnd = 12;
- break;
- case 32:
- cx->k_sch[4] = ss[4] = word_in(in_key + 16);
- cx->k_sch[5] = ss[5] = word_in(in_key + 20);
- cx->k_sch[6] = ss[6] = word_in(in_key + 24);
- cx->k_sch[7] = ss[7] = word_in(in_key + 28);
- ke8(cx->k_sch, 0);
- ke8(cx->k_sch, 1);
- ke8(cx->k_sch, 2);
- ke8(cx->k_sch, 3);
- ke8(cx->k_sch, 4);
- ke8(cx->k_sch, 5);
- kel8(cx->k_sch, 6);
- cx->n_rnd = 14;
- break;
- default:
- cx->n_rnd = 0;
- return aes_bad;
+ case 16: ke4(cx->k_sch, 0); ke4(cx->k_sch, 1);
+ ke4(cx->k_sch, 2); ke4(cx->k_sch, 3);
+ ke4(cx->k_sch, 4); ke4(cx->k_sch, 5);
+ ke4(cx->k_sch, 6); ke4(cx->k_sch, 7);
+ ke4(cx->k_sch, 8); kel4(cx->k_sch, 9);
+ cx->n_rnd = 10; break;
+ case 24: cx->k_sch[4] = ss[4] = word_in(in_key + 16);
+ cx->k_sch[5] = ss[5] = word_in(in_key + 20);
+ ke6(cx->k_sch, 0); ke6(cx->k_sch, 1);
+ ke6(cx->k_sch, 2); ke6(cx->k_sch, 3);
+ ke6(cx->k_sch, 4); ke6(cx->k_sch, 5);
+ ke6(cx->k_sch, 6); kel6(cx->k_sch, 7);
+ cx->n_rnd = 12; break;
+ case 32: cx->k_sch[4] = ss[4] = word_in(in_key + 16);
+ cx->k_sch[5] = ss[5] = word_in(in_key + 20);
+ cx->k_sch[6] = ss[6] = word_in(in_key + 24);
+ cx->k_sch[7] = ss[7] = word_in(in_key + 28);
+ ke8(cx->k_sch, 0); ke8(cx->k_sch, 1);
+ ke8(cx->k_sch, 2); ke8(cx->k_sch, 3);
+ ke8(cx->k_sch, 4); ke8(cx->k_sch, 5);
+ kel8(cx->k_sch, 6);
+ cx->n_rnd = 14; break;
+ default: cx->n_rnd = 0; return aes_bad;
}
#else
- {
- aes_32t i, l;
+ { aes_32t i, l;
cx->n_rnd = ((klen >> 2) > nc ? (klen >> 2) : nc) + 6;
l = (nc * cx->n_rnd + nc - 1) / (klen >> 2);
switch(klen)
{
- case 16:
- for(i = 0; i < l; ++i)
- ke4(cx->k_sch, i);
- break;
- case 24:
- cx->k_sch[4] = ss[4] = word_in(in_key + 16);
- cx->k_sch[5] = ss[5] = word_in(in_key + 20);
- for(i = 0; i < l; ++i)
- ke6(cx->k_sch, i);
- break;
- case 32:
- cx->k_sch[4] = ss[4] = word_in(in_key + 16);
- cx->k_sch[5] = ss[5] = word_in(in_key + 20);
- cx->k_sch[6] = ss[6] = word_in(in_key + 24);
- cx->k_sch[7] = ss[7] = word_in(in_key + 28);
- for(i = 0; i < l; ++i)
- ke8(cx->k_sch, i);
- break;
- default:
- cx->n_rnd = 0;
- return aes_bad;
+ case 16: for(i = 0; i < l; ++i)
+ ke4(cx->k_sch, i);
+ break;
+ case 24: cx->k_sch[4] = ss[4] = word_in(in_key + 16);
+ cx->k_sch[5] = ss[5] = word_in(in_key + 20);
+ for(i = 0; i < l; ++i)
+ ke6(cx->k_sch, i);
+ break;
+ case 32: cx->k_sch[4] = ss[4] = word_in(in_key + 16);
+ cx->k_sch[5] = ss[5] = word_in(in_key + 20);
+ cx->k_sch[6] = ss[6] = word_in(in_key + 24);
+ cx->k_sch[7] = ss[7] = word_in(in_key + 28);
+ for(i = 0; i < l; ++i)
+ ke8(cx->k_sch, i);
+ break;
+ default: cx->n_rnd = 0; return aes_bad;
}
}
#endif
@@ -1394,8 +1354,7 @@ static aes_rval aes_enc_key(const unsigned char in_key[], unsigned int klen, aes
}
static aes_rval aes_dec_key(const unsigned char in_key[], unsigned int klen, aes_ctx cx[1])
-{
- aes_32t ss[8];
+{ aes_32t ss[8];
d_vars
#if !defined(FIXED_TABLES)
@@ -1410,7 +1369,7 @@ static aes_rval aes_dec_key(const unsigned char in_key[], unsigned int klen, aes
cx->n_blk = (cx->n_blk & ~3) | 2;
- cx->k_sch[0] = ss[0] = word_in(in_key);
+ cx->k_sch[0] = ss[0] = word_in(in_key );
cx->k_sch[1] = ss[1] = word_in(in_key + 4);
cx->k_sch[2] = ss[2] = word_in(in_key + 8);
cx->k_sch[3] = ss[3] = word_in(in_key + 12);
@@ -1419,79 +1378,54 @@ static aes_rval aes_dec_key(const unsigned char in_key[], unsigned int klen, aes
switch(klen)
{
- case 16:
- kdf4(cx->k_sch, 0);
- kd4(cx->k_sch, 1);
- kd4(cx->k_sch, 2);
- kd4(cx->k_sch, 3);
- kd4(cx->k_sch, 4);
- kd4(cx->k_sch, 5);
- kd4(cx->k_sch, 6);
- kd4(cx->k_sch, 7);
- kd4(cx->k_sch, 8);
- kdl4(cx->k_sch, 9);
- cx->n_rnd = 10;
- break;
- case 24:
- cx->k_sch[4] = ff(ss[4] = word_in(in_key + 16));
- cx->k_sch[5] = ff(ss[5] = word_in(in_key + 20));
- kdf6(cx->k_sch, 0);
- kd6(cx->k_sch, 1);
- kd6(cx->k_sch, 2);
- kd6(cx->k_sch, 3);
- kd6(cx->k_sch, 4);
- kd6(cx->k_sch, 5);
- kd6(cx->k_sch, 6);
- kdl6(cx->k_sch, 7);
- cx->n_rnd = 12;
- break;
- case 32:
- cx->k_sch[4] = ff(ss[4] = word_in(in_key + 16));
- cx->k_sch[5] = ff(ss[5] = word_in(in_key + 20));
- cx->k_sch[6] = ff(ss[6] = word_in(in_key + 24));
- cx->k_sch[7] = ff(ss[7] = word_in(in_key + 28));
- kdf8(cx->k_sch, 0);
- kd8(cx->k_sch, 1);
- kd8(cx->k_sch, 2);
- kd8(cx->k_sch, 3);
- kd8(cx->k_sch, 4);
- kd8(cx->k_sch, 5);
- kdl8(cx->k_sch, 6);
- cx->n_rnd = 14;
- break;
- default:
- cx->n_rnd = 0;
- return aes_bad;
+ case 16: kdf4(cx->k_sch, 0); kd4(cx->k_sch, 1);
+ kd4(cx->k_sch, 2); kd4(cx->k_sch, 3);
+ kd4(cx->k_sch, 4); kd4(cx->k_sch, 5);
+ kd4(cx->k_sch, 6); kd4(cx->k_sch, 7);
+ kd4(cx->k_sch, 8); kdl4(cx->k_sch, 9);
+ cx->n_rnd = 10; break;
+ case 24: cx->k_sch[4] = ff(ss[4] = word_in(in_key + 16));
+ cx->k_sch[5] = ff(ss[5] = word_in(in_key + 20));
+ kdf6(cx->k_sch, 0); kd6(cx->k_sch, 1);
+ kd6(cx->k_sch, 2); kd6(cx->k_sch, 3);
+ kd6(cx->k_sch, 4); kd6(cx->k_sch, 5);
+ kd6(cx->k_sch, 6); kdl6(cx->k_sch, 7);
+ cx->n_rnd = 12; break;
+ case 32: cx->k_sch[4] = ff(ss[4] = word_in(in_key + 16));
+ cx->k_sch[5] = ff(ss[5] = word_in(in_key + 20));
+ cx->k_sch[6] = ff(ss[6] = word_in(in_key + 24));
+ cx->k_sch[7] = ff(ss[7] = word_in(in_key + 28));
+ kdf8(cx->k_sch, 0); kd8(cx->k_sch, 1);
+ kd8(cx->k_sch, 2); kd8(cx->k_sch, 3);
+ kd8(cx->k_sch, 4); kd8(cx->k_sch, 5);
+ kdl8(cx->k_sch, 6);
+ cx->n_rnd = 14; break;
+ default: cx->n_rnd = 0; return aes_bad;
}
#else
- {
- aes_32t i, l;
+ { aes_32t i, l;
cx->n_rnd = ((klen >> 2) > nc ? (klen >> 2) : nc) + 6;
l = (nc * cx->n_rnd + nc - 1) / (klen >> 2);
switch(klen)
{
- case 16:
- for(i = 0; i < l; ++i)
- ke4(cx->k_sch, i);
- break;
- case 24:
- cx->k_sch[4] = ss[4] = word_in(in_key + 16);
- cx->k_sch[5] = ss[5] = word_in(in_key + 20);
- for(i = 0; i < l; ++i)
- ke6(cx->k_sch, i);
- break;
- case 32:
- cx->k_sch[4] = ss[4] = word_in(in_key + 16);
- cx->k_sch[5] = ss[5] = word_in(in_key + 20);
- cx->k_sch[6] = ss[6] = word_in(in_key + 24);
- cx->k_sch[7] = ss[7] = word_in(in_key + 28);
- for(i = 0; i < l; ++i)
- ke8(cx->k_sch, i);
- break;
- default:
- cx->n_rnd = 0;
- return aes_bad;
+ case 16:
+ for(i = 0; i < l; ++i)
+ ke4(cx->k_sch, i);
+ break;
+ case 24: cx->k_sch[4] = ss[4] = word_in(in_key + 16);
+ cx->k_sch[5] = ss[5] = word_in(in_key + 20);
+ for(i = 0; i < l; ++i)
+ ke6(cx->k_sch, i);
+ break;
+ case 32: cx->k_sch[4] = ss[4] = word_in(in_key + 16);
+ cx->k_sch[5] = ss[5] = word_in(in_key + 20);
+ cx->k_sch[6] = ss[6] = word_in(in_key + 24);
+ cx->k_sch[7] = ss[7] = word_in(in_key + 28);
+ for(i = 0; i < l; ++i)
+ ke8(cx->k_sch, i);
+ break;
+ default: cx->n_rnd = 0; return aes_bad;
}
#if (DEC_ROUND != NO_TABLES)
for(i = nc; i < nc * cx->n_rnd; ++i)
@@ -1519,10 +1453,10 @@ static aes_rval aes_dec_key(const unsigned char in_key[], unsigned int klen, aes
#define locals(y,x) x[4],y[4]
#else
#define locals(y,x) x##0,x##1,x##2,x##3,y##0,y##1,y##2,y##3
-/*
- the following defines prevent the compiler requiring the declaration
- of generated but unused variables in the fwd_var and inv_var macros
-*/
+ /*
+ the following defines prevent the compiler requiring the declaration
+ of generated but unused variables in the fwd_var and inv_var macros
+ */
#define b04 unused
#define b05 unused
#define b06 unused
@@ -1633,18 +1567,18 @@ switch(nc) \
#if defined(ENCRYPTION)
/* I am grateful to Frank Yellin for the following construction
- (and that for decryption) which, given the column (c) of the
- output state variable, gives the input state variables which
+ (and that for decryption) which, given the column (c) of the
+ output state variable, gives the input state variables which
are needed in its computation for each row (r) of the state.
- For the fixed block size options, compilers should be able to
- reduce this complex expression (and the equivalent one for
- decryption) to a static variable reference at compile time.
+ For the fixed block size options, compilers should be able to
+ reduce this complex expression (and the equivalent one for
+ decryption) to a static variable reference at compile time.
But for variable block size code, there will be some limbs on
which conditional clauses will be returned.
*/
-/* y = output word, x = input word, r = row, c = column for r = 0,
+/* y = output word, x = input word, r = row, c = column for r = 0,
1, 2 and 3 = column accessed for row r.
*/
@@ -1707,14 +1641,13 @@ switch(nc) \
#endif
static aes_rval aes_enc_blk(const unsigned char in_blk[], unsigned char out_blk[], const aes_ctx cx[1])
-{
- aes_32t locals(b0, b1);
+{ aes_32t locals(b0, b1);
const aes_32t *kp = cx->k_sch;
dec_fmvars /* declare variables for fwd_mcol() if needed */
if(!(cx->n_blk & 1)) return aes_bad;
- state_in(b0, in_blk, kp);
+ state_in(b0, in_blk, kp);
#if (ENC_UNROLL == FULL)
@@ -1722,45 +1655,40 @@ static aes_rval aes_enc_blk(const unsigned char in_blk[], unsigned char out_blk[
switch(cx->n_rnd)
{
- case 14:
- round(fwd_rnd, b1, b0, kp - 4 * nc);
- round(fwd_rnd, b0, b1, kp - 3 * nc);
- case 12:
- round(fwd_rnd, b1, b0, kp - 2 * nc);
- round(fwd_rnd, b0, b1, kp - nc);
- case 10:
- round(fwd_rnd, b1, b0, kp);
- round(fwd_rnd, b0, b1, kp + nc);
- round(fwd_rnd, b1, b0, kp + 2 * nc);
- round(fwd_rnd, b0, b1, kp + 3 * nc);
- round(fwd_rnd, b1, b0, kp + 4 * nc);
- round(fwd_rnd, b0, b1, kp + 5 * nc);
- round(fwd_rnd, b1, b0, kp + 6 * nc);
- round(fwd_rnd, b0, b1, kp + 7 * nc);
- round(fwd_rnd, b1, b0, kp + 8 * nc);
- round(fwd_lrnd, b0, b1, kp + 9 * nc);
+ case 14: round(fwd_rnd, b1, b0, kp - 4 * nc);
+ round(fwd_rnd, b0, b1, kp - 3 * nc);
+ case 12: round(fwd_rnd, b1, b0, kp - 2 * nc);
+ round(fwd_rnd, b0, b1, kp - nc);
+ case 10: round(fwd_rnd, b1, b0, kp );
+ round(fwd_rnd, b0, b1, kp + nc);
+ round(fwd_rnd, b1, b0, kp + 2 * nc);
+ round(fwd_rnd, b0, b1, kp + 3 * nc);
+ round(fwd_rnd, b1, b0, kp + 4 * nc);
+ round(fwd_rnd, b0, b1, kp + 5 * nc);
+ round(fwd_rnd, b1, b0, kp + 6 * nc);
+ round(fwd_rnd, b0, b1, kp + 7 * nc);
+ round(fwd_rnd, b1, b0, kp + 8 * nc);
+ round(fwd_lrnd, b0, b1, kp + 9 * nc);
}
#else
-
+
#if (ENC_UNROLL == PARTIAL)
- {
- aes_32t rnd;
+ { aes_32t rnd;
for(rnd = 0; rnd < (cx->n_rnd >> 1) - 1; ++rnd)
{
kp += nc;
- round(fwd_rnd, b1, b0, kp);
+ round(fwd_rnd, b1, b0, kp);
kp += nc;
- round(fwd_rnd, b0, b1, kp);
+ round(fwd_rnd, b0, b1, kp);
}
kp += nc;
round(fwd_rnd, b1, b0, kp);
#else
- {
- aes_32t rnd, *p0 = b0, *p1 = b1, *pt;
+ { aes_32t rnd, *p0 = b0, *p1 = b1, *pt;
for(rnd = 0; rnd < cx->n_rnd - 1; ++rnd)
{
kp += nc;
- round(fwd_rnd, p1, p0, kp);
+ round(fwd_rnd, p1, p0, kp);
pt = p0, p0 = p1, p1 = pt;
}
#endif
@@ -1836,8 +1764,7 @@ static aes_rval aes_enc_blk(const unsigned char in_blk[], unsigned char out_blk[
#endif
static aes_rval aes_dec_blk(const unsigned char in_blk[], unsigned char out_blk[], const aes_ctx cx[1])
-{
- aes_32t locals(b0, b1);
+{ aes_32t locals(b0, b1);
const aes_32t *kp = cx->k_sch + nc * cx->n_rnd;
dec_imvars /* declare variables for inv_mcol() if needed */
@@ -1850,45 +1777,40 @@ static aes_rval aes_dec_blk(const unsigned char in_blk[], unsigned char out_blk[
kp = cx->k_sch + 9 * nc;
switch(cx->n_rnd)
{
- case 14:
- round(inv_rnd, b1, b0, kp + 4 * nc);
- round(inv_rnd, b0, b1, kp + 3 * nc);
- case 12:
- round(inv_rnd, b1, b0, kp + 2 * nc);
- round(inv_rnd, b0, b1, kp + nc);
- case 10:
- round(inv_rnd, b1, b0, kp);
- round(inv_rnd, b0, b1, kp - nc);
- round(inv_rnd, b1, b0, kp - 2 * nc);
- round(inv_rnd, b0, b1, kp - 3 * nc);
- round(inv_rnd, b1, b0, kp - 4 * nc);
- round(inv_rnd, b0, b1, kp - 5 * nc);
- round(inv_rnd, b1, b0, kp - 6 * nc);
- round(inv_rnd, b0, b1, kp - 7 * nc);
- round(inv_rnd, b1, b0, kp - 8 * nc);
- round(inv_lrnd, b0, b1, kp - 9 * nc);
+ case 14: round(inv_rnd, b1, b0, kp + 4 * nc);
+ round(inv_rnd, b0, b1, kp + 3 * nc);
+ case 12: round(inv_rnd, b1, b0, kp + 2 * nc);
+ round(inv_rnd, b0, b1, kp + nc );
+ case 10: round(inv_rnd, b1, b0, kp );
+ round(inv_rnd, b0, b1, kp - nc);
+ round(inv_rnd, b1, b0, kp - 2 * nc);
+ round(inv_rnd, b0, b1, kp - 3 * nc);
+ round(inv_rnd, b1, b0, kp - 4 * nc);
+ round(inv_rnd, b0, b1, kp - 5 * nc);
+ round(inv_rnd, b1, b0, kp - 6 * nc);
+ round(inv_rnd, b0, b1, kp - 7 * nc);
+ round(inv_rnd, b1, b0, kp - 8 * nc);
+ round(inv_lrnd, b0, b1, kp - 9 * nc);
}
#else
-
+
#if (DEC_UNROLL == PARTIAL)
- {
- aes_32t rnd;
+ { aes_32t rnd;
for(rnd = 0; rnd < (cx->n_rnd >> 1) - 1; ++rnd)
{
- kp -= nc;
- round(inv_rnd, b1, b0, kp);
- kp -= nc;
- round(inv_rnd, b0, b1, kp);
+ kp -= nc;
+ round(inv_rnd, b1, b0, kp);
+ kp -= nc;
+ round(inv_rnd, b0, b1, kp);
}
kp -= nc;
round(inv_rnd, b1, b0, kp);
#else
- {
- aes_32t rnd, *p0 = b0, *p1 = b1, *pt;
+ { aes_32t rnd, *p0 = b0, *p1 = b1, *pt;
for(rnd = 0; rnd < cx->n_rnd - 1; ++rnd)
{
kp -= nc;
- round(inv_rnd, p1, p0, kp);
+ round(inv_rnd, p1, p0, kp);
pt = p0, p0 = p1, p1 = pt;
}
#endif
@@ -1907,16 +1829,13 @@ static aes_rval aes_dec_blk(const unsigned char in_blk[], unsigned char out_blk[
| AP4_AesBlockCipher::AP4_AesBlockCipher
+---------------------------------------------------------------------*/
AP4_AesBlockCipher::AP4_AesBlockCipher(const AP4_UI08* key,
-CipherDirection direction) :
+ CipherDirection direction) :
m_Direction(direction)
{
m_Context = new aes_ctx;
- if(direction == AP4_BlockCipher::ENCRYPT)
- {
+ if (direction == AP4_BlockCipher::ENCRYPT) {
aes_enc_key(key, AP4_AES_KEY_LENGTH, m_Context);
- }
- else
- {
+ } else {
aes_dec_key(key, AP4_AES_KEY_LENGTH, m_Context);
}
}
@@ -1932,17 +1851,14 @@ AP4_AesBlockCipher::~AP4_AesBlockCipher()
/*----------------------------------------------------------------------
| AP4_AesBlockCipher::EncryptBlock
+---------------------------------------------------------------------*/
-AP4_Result
+AP4_Result
AP4_AesBlockCipher::ProcessBlock(const AP4_UI08* block_in,
-AP4_UI08* block_out)
+ AP4_UI08* block_out)
{
aes_rval result;
- if(m_Direction == AP4_BlockCipher::ENCRYPT)
- {
+ if (m_Direction == AP4_BlockCipher::ENCRYPT) {
result = aes_enc_blk(block_in, block_out, m_Context);
- }
- else
- {
+ } else {
result = aes_dec_blk(block_in, block_out, m_Context);
}
return result == aes_good ? AP4_SUCCESS : AP4_FAILURE;
diff --git a/src/filters/parser/MP4Splitter/AP4/Source/Crypto/Ap4AesBlockCipher.h b/src/filters/parser/MP4Splitter/AP4/Source/Crypto/Ap4AesBlockCipher.h
index 724e57ebe..353cf6473 100644
--- a/src/filters/parser/MP4Splitter/AP4/Source/Crypto/Ap4AesBlockCipher.h
+++ b/src/filters/parser/MP4Splitter/AP4/Source/Crypto/Ap4AesBlockCipher.h
@@ -11,23 +11,23 @@
LICENSE TERMS
- The free distribution and use of this software in both source and binary
+ The free distribution and use of this software in both source and binary
form is allowed (with or without changes) provided that:
- 1. distributions of this source code include the above copyright
+ 1. distributions of this source code include the above copyright
notice, this list of conditions and the following disclaimer;
2. distributions in binary form include the above copyright
notice, this list of conditions and the following disclaimer
in the documentation and/or other associated materials;
- 3. the copyright holder's name is not used to endorse products
- built using this software without specific written permission.
+ 3. the copyright holder's name is not used to endorse products
+ built using this software without specific written permission.
DISCLAIMER
This software is provided 'as is' with no explicit or implied warranties
- in respect of its properties, including, but not limited to, correctness
+ in respect of its properties, including, but not limited to, correctness
and fitness for purpose.
-------------------------------------------------------------------------
Issue Date: 29/07/2002
@@ -61,13 +61,13 @@ class AP4_AesBlockCipher : public AP4_BlockCipher
{
public:
// constructor and destructor
- AP4_AesBlockCipher(const AP4_UI08* key,
+ AP4_AesBlockCipher(const AP4_UI08* key,
AP4_BlockCipher::CipherDirection direction);
- ~AP4_AesBlockCipher();
-
- // AP4_AesBlockCipher methods
- virtual AP4_Result ProcessBlock(const AP4_UI08* input,
- AP4_UI08* output);
+ ~AP4_AesBlockCipher();
+
+ // AP4_AesBlockCipher methods
+ virtual AP4_Result ProcessBlock(const AP4_UI08* input,
+ AP4_UI08* output);
private:
// members
diff --git a/src/filters/parser/MP4Splitter/AP4/Source/Crypto/Ap4Hmac.cpp b/src/filters/parser/MP4Splitter/AP4/Source/Crypto/Ap4Hmac.cpp
index 8d9e81759..387f69453 100644
--- a/src/filters/parser/MP4Splitter/AP4/Source/Crypto/Ap4Hmac.cpp
+++ b/src/filters/parser/MP4Splitter/AP4/Source/Crypto/Ap4Hmac.cpp
@@ -28,7 +28,7 @@
/*
Portions of this code are based on the code of LibTomCrypt
- that was released into public domain by Tom St Denis.
+ that was released into public domain by Tom St Denis.
*/
/*----------------------------------------------------------------------
@@ -42,21 +42,20 @@
+---------------------------------------------------------------------*/
#define AP4_SHA256_BLOCK_SIZE 64
-static const AP4_UI32 AP4_Sha256_K[64] =
-{
- 0x428a2f98UL, 0x71374491UL, 0xb5c0fbcfUL, 0xe9b5dba5UL, 0x3956c25bUL,
- 0x59f111f1UL, 0x923f82a4UL, 0xab1c5ed5UL, 0xd807aa98UL, 0x12835b01UL,
- 0x243185beUL, 0x550c7dc3UL, 0x72be5d74UL, 0x80deb1feUL, 0x9bdc06a7UL,
- 0xc19bf174UL, 0xe49b69c1UL, 0xefbe4786UL, 0x0fc19dc6UL, 0x240ca1ccUL,
- 0x2de92c6fUL, 0x4a7484aaUL, 0x5cb0a9dcUL, 0x76f988daUL, 0x983e5152UL,
- 0xa831c66dUL, 0xb00327c8UL, 0xbf597fc7UL, 0xc6e00bf3UL, 0xd5a79147UL,
- 0x06ca6351UL, 0x14292967UL, 0x27b70a85UL, 0x2e1b2138UL, 0x4d2c6dfcUL,
- 0x53380d13UL, 0x650a7354UL, 0x766a0abbUL, 0x81c2c92eUL, 0x92722c85UL,
- 0xa2bfe8a1UL, 0xa81a664bUL, 0xc24b8b70UL, 0xc76c51a3UL, 0xd192e819UL,
- 0xd6990624UL, 0xf40e3585UL, 0x106aa070UL, 0x19a4c116UL, 0x1e376c08UL,
- 0x2748774cUL, 0x34b0bcb5UL, 0x391c0cb3UL, 0x4ed8aa4aUL, 0x5b9cca4fUL,
- 0x682e6ff3UL, 0x748f82eeUL, 0x78a5636fUL, 0x84c87814UL, 0x8cc70208UL,
- 0x90befffaUL, 0xa4506cebUL, 0xbef9a3f7UL, 0xc67178f2UL
+static const AP4_UI32 AP4_Sha256_K[64] = {
+ 0x428a2f98UL, 0x71374491UL, 0xb5c0fbcfUL, 0xe9b5dba5UL, 0x3956c25bUL,
+ 0x59f111f1UL, 0x923f82a4UL, 0xab1c5ed5UL, 0xd807aa98UL, 0x12835b01UL,
+ 0x243185beUL, 0x550c7dc3UL, 0x72be5d74UL, 0x80deb1feUL, 0x9bdc06a7UL,
+ 0xc19bf174UL, 0xe49b69c1UL, 0xefbe4786UL, 0x0fc19dc6UL, 0x240ca1ccUL,
+ 0x2de92c6fUL, 0x4a7484aaUL, 0x5cb0a9dcUL, 0x76f988daUL, 0x983e5152UL,
+ 0xa831c66dUL, 0xb00327c8UL, 0xbf597fc7UL, 0xc6e00bf3UL, 0xd5a79147UL,
+ 0x06ca6351UL, 0x14292967UL, 0x27b70a85UL, 0x2e1b2138UL, 0x4d2c6dfcUL,
+ 0x53380d13UL, 0x650a7354UL, 0x766a0abbUL, 0x81c2c92eUL, 0x92722c85UL,
+ 0xa2bfe8a1UL, 0xa81a664bUL, 0xc24b8b70UL, 0xc76c51a3UL, 0xd192e819UL,
+ 0xd6990624UL, 0xf40e3585UL, 0x106aa070UL, 0x19a4c116UL, 0x1e376c08UL,
+ 0x2748774cUL, 0x34b0bcb5UL, 0x391c0cb3UL, 0x4ed8aa4aUL, 0x5b9cca4fUL,
+ 0x682e6ff3UL, 0x748f82eeUL, 0x78a5636fUL, 0x84c87814UL, 0x8cc70208UL,
+ 0x90befffaUL, 0xa4506cebUL, 0xbef9a3f7UL, 0xc67178f2UL
};
/*----------------------------------------------------------------------
@@ -67,20 +66,20 @@ class AP4_DigestSha256
public:
AP4_DigestSha256();
virtual ~AP4_DigestSha256() {}
-
+
// AP4_Hmac methods
virtual AP4_Result Update(const AP4_UI08* data, AP4_Size data_size);
virtual AP4_Result Final(AP4_DataBuffer& digest);
-
+
private:
// methods
void CompressBlock(const AP4_UI08* block);
-
+
// members
- AP4_UI64 m_Length;
+ AP4_UI64 m_Length;
AP4_UI32 m_Pending;
- AP4_UI32 m_State[8];
- AP4_UI08 m_Buffer[64];
+ AP4_UI32 m_State[8];
+ AP4_UI08 m_Buffer[64];
};
/*----------------------------------------------------------------------
@@ -97,14 +96,13 @@ class AP4_HmacSha256 : public AP4_Hmac
{
public:
AP4_HmacSha256(const AP4_UI08* key, AP4_Size key_size);
-
+
// AP4_Hmac methods
- virtual AP4_Result Update(const AP4_UI08* data, AP4_Size data_size)
- {
+ virtual AP4_Result Update(const AP4_UI08* data, AP4_Size data_size) {
return m_InnerDigest.Update(data, data_size);
}
virtual AP4_Result Final(AP4_DataBuffer& buffer);
-
+
private:
AP4_DigestSha256 m_InnerDigest;
AP4_DigestSha256 m_OuterDigest;
@@ -117,14 +115,14 @@ AP4_DigestSha256::AP4_DigestSha256() :
m_Length(0),
m_Pending(0)
{
- m_State[0] = 0x6A09E667UL;
- m_State[1] = 0xBB67AE85UL;
- m_State[2] = 0x3C6EF372UL;
- m_State[3] = 0xA54FF53AUL;
- m_State[4] = 0x510E527FUL;
- m_State[5] = 0x9B05688CUL;
- m_State[6] = 0x1F83D9ABUL;
- m_State[7] = 0x5BE0CD19UL;
+ m_State[0] = 0x6A09E667UL;
+ m_State[1] = 0xBB67AE85UL;
+ m_State[2] = 0x3C6EF372UL;
+ m_State[3] = 0xA54FF53AUL;
+ m_State[4] = 0x510E527FUL;
+ m_State[5] = 0x9B05688CUL;
+ m_State[6] = 0x1F83D9ABUL;
+ m_State[7] = 0x5BE0CD19UL;
}
/*----------------------------------------------------------------------
@@ -134,7 +132,7 @@ AP4_DigestSha256::AP4_DigestSha256() :
( ((((unsigned long) (x) & 0xFFFFFFFFUL) >> (unsigned long) ((y) & 31)) | \
((unsigned long) (x) << (unsigned long) (32 - ((y) & 31)))) & 0xFFFFFFFFUL)
#define AP4_Sha256_Ch(x,y,z) (z ^ (x & (y ^ z)))
-#define AP4_Sha256_Maj(x,y,z) (((x | y) & z) | (x & y))
+#define AP4_Sha256_Maj(x,y,z) (((x | y) & z) | (x & y))
#define AP4_Sha256_S(x, n) AP4_Sha256_RORc((x), (n))
#define AP4_Sha256_R(x, n) (((x)&0xFFFFFFFFUL)>>(n))
#define AP4_Sha256_Sigma0(x) (AP4_Sha256_S(x, 2) ^ AP4_Sha256_S(x, 13) ^ AP4_Sha256_S(x, 22))
@@ -148,50 +146,38 @@ AP4_DigestSha256::AP4_DigestSha256() :
void
AP4_DigestSha256::CompressBlock(const AP4_UI08* block)
{
- AP4_UI32 S[8], W[64];
+ AP4_UI32 S[8], W[64];
- /* copy the state into S */
- for(unsigned int i = 0; i < 8; i++)
- {
- S[i] = m_State[i];
- }
+ /* copy the state into S */
+ for (unsigned int i = 0; i < 8; i++) {
+ S[i] = m_State[i];
+ }
- /* copy the 512-bit block into W[0..15] */
- for(unsigned int i = 0; i < 16; i++)
- {
- W[i] = AP4_BytesToUInt32BE(&block[4*i]);
+ /* copy the 512-bit block into W[0..15] */
+ for (unsigned int i = 0; i < 16; i++) {
+ W[i] = AP4_BytesToUInt32BE(&block[4*i]);
}
-
- /* fill W[16..63] */
- for(unsigned int i = 16; i < AP4_SHA256_BLOCK_SIZE; i++)
- {
- W[i] = AP4_Sha256_Gamma1(W[i-2]) + W[i-7] + AP4_Sha256_Gamma0(W[i-15]) + W[i-16];
- }
-
- /* compress */
- AP4_UI32 t, t0, t1;
- for(unsigned int i = 0; i < AP4_SHA256_BLOCK_SIZE; ++i)
- {
+
+ /* fill W[16..63] */
+ for (unsigned int i = 16; i < AP4_SHA256_BLOCK_SIZE; i++) {
+ W[i] = AP4_Sha256_Gamma1(W[i-2]) + W[i-7] + AP4_Sha256_Gamma0(W[i-15]) + W[i-16];
+ }
+
+ /* compress */
+ AP4_UI32 t, t0, t1;
+ for (unsigned int i = 0; i < AP4_SHA256_BLOCK_SIZE; ++i) {
t0 = S[7] + AP4_Sha256_Sigma1(S[4]) + AP4_Sha256_Ch(S[4], S[5], S[6]) + AP4_Sha256_K[i] + W[i];
t1 = AP4_Sha256_Sigma0(S[0]) + AP4_Sha256_Maj(S[0], S[1], S[2]);
S[3] += t0;
S[7] = t0 + t1;
- t = S[7];
- S[7] = S[6];
- S[6] = S[5];
- S[5] = S[4];
- S[4] = S[3];
- S[3] = S[2];
- S[2] = S[1];
- S[1] = S[0];
- S[0] = t;
- }
-
- /* feedback */
- for(unsigned int i = 0; i < 8; i++)
- {
- m_State[i] = m_State[i] + S[i];
- }
+ t = S[7]; S[7] = S[6]; S[6] = S[5]; S[5] = S[4];
+ S[4] = S[3]; S[3] = S[2]; S[2] = S[1]; S[1] = S[0]; S[0] = t;
+ }
+
+ /* feedback */
+ for (unsigned int i = 0; i < 8; i++) {
+ m_State[i] = m_State[i] + S[i];
+ }
}
@@ -201,35 +187,29 @@ AP4_DigestSha256::CompressBlock(const AP4_UI08* block)
AP4_Result
AP4_DigestSha256::Update(const AP4_UI08* data, AP4_Size data_size)
{
- while(data_size > 0)
- {
- if(m_Pending == 0 && data_size >= AP4_SHA256_BLOCK_SIZE)
- {
- CompressBlock(data);
- m_Length += AP4_SHA256_BLOCK_SIZE * 8;
- data += AP4_SHA256_BLOCK_SIZE;
- data_size -= AP4_SHA256_BLOCK_SIZE;
- }
- else
- {
- unsigned int chunk = data_size;
- if(chunk > (AP4_SHA256_BLOCK_SIZE - m_Pending))
- {
+ while (data_size > 0) {
+ if (m_Pending == 0 && data_size >= AP4_SHA256_BLOCK_SIZE) {
+ CompressBlock(data);
+ m_Length += AP4_SHA256_BLOCK_SIZE * 8;
+ data += AP4_SHA256_BLOCK_SIZE;
+ data_size -= AP4_SHA256_BLOCK_SIZE;
+ } else {
+ unsigned int chunk = data_size;
+ if (chunk > (AP4_SHA256_BLOCK_SIZE - m_Pending)) {
chunk = AP4_SHA256_BLOCK_SIZE - m_Pending;
}
- AP4_CopyMemory(&m_Buffer[m_Pending], data, chunk);
- m_Pending += chunk;
- data += chunk;
- data_size -= chunk;
- if(m_Pending == AP4_SHA256_BLOCK_SIZE)
- {
- CompressBlock(m_Buffer);
- m_Length += 8 * AP4_SHA256_BLOCK_SIZE;
- m_Pending = 0;
- }
- }
- }
-
+ AP4_CopyMemory(&m_Buffer[m_Pending], data, chunk);
+ m_Pending += chunk;
+ data += chunk;
+ data_size -= chunk;
+ if (m_Pending == AP4_SHA256_BLOCK_SIZE) {
+ CompressBlock(m_Buffer);
+ m_Length += 8 * AP4_SHA256_BLOCK_SIZE;
+ m_Pending = 0;
+ }
+ }
+ }
+
return AP4_SUCCESS;
}
@@ -240,46 +220,42 @@ AP4_DigestSha256::Update(const AP4_UI08* data, AP4_Size data_size)
AP4_Result
AP4_DigestSha256::Final(AP4_DataBuffer& digest)
{
- /* increase the length of the message */
- m_Length += m_Pending * 8;
-
- /* append the '1' bit */
- m_Buffer[m_Pending++] = 0x80;
-
- /* if the length is currently above 56 bytes we append zeros
- * then compress. Then we can fall back to padding zeros and length
- * encoding like normal.
- */
- if(m_Pending > 56)
- {
- while(m_Pending < 64)
- {
- m_Buffer[m_Pending++] = 0;
- }
- CompressBlock(m_Buffer);
- m_Pending = 0;
- }
-
- /* pad upto 56 bytes of zeroes */
- while(m_Pending < 56)
- {
- m_Buffer[m_Pending++] = 0;
- }
-
- /* store length */
- AP4_BytesFromUInt64BE(&m_Buffer[56], m_Length);
- CompressBlock(m_Buffer);
-
- /* copy output */
+ /* increase the length of the message */
+ m_Length += m_Pending * 8;
+
+ /* append the '1' bit */
+ m_Buffer[m_Pending++] = 0x80;
+
+ /* if the length is currently above 56 bytes we append zeros
+ * then compress. Then we can fall back to padding zeros and length
+ * encoding like normal.
+ */
+ if (m_Pending > 56) {
+ while (m_Pending < 64) {
+ m_Buffer[m_Pending++] = 0;
+ }
+ CompressBlock(m_Buffer);
+ m_Pending = 0;
+ }
+
+ /* pad upto 56 bytes of zeroes */
+ while (m_Pending < 56) {
+ m_Buffer[m_Pending++] = 0;
+ }
+
+ /* store length */
+ AP4_BytesFromUInt64BE(&m_Buffer[56], m_Length);
+ CompressBlock(m_Buffer);
+
+ /* copy output */
digest.SetDataSize(32);
AP4_UI08* out = digest.UseData();
- for(unsigned int i = 0; i < 8; i++)
- {
- AP4_BytesFromUInt32BE(out, m_State[i]);
+ for (unsigned int i = 0; i < 8; i++) {
+ AP4_BytesFromUInt32BE(out, m_State[i]);
out += 4;
}
-
- return AP4_SUCCESS;
+
+ return AP4_SUCCESS;
}
/*----------------------------------------------------------------------
@@ -287,12 +263,11 @@ AP4_DigestSha256::Final(AP4_DataBuffer& digest)
+---------------------------------------------------------------------*/
AP4_HmacSha256::AP4_HmacSha256(const AP4_UI08* key, AP4_Size key_size)
{
- AP4_UI08 workspace[AP4_SHA256_BLOCK_SIZE];
-
+ AP4_UI08 workspace[AP4_SHA256_BLOCK_SIZE];
+
/* if the key is larger than the block size, use a digest of the key */
AP4_DataBuffer hk;
- if(key_size > AP4_SHA256_BLOCK_SIZE)
- {
+ if (key_size > AP4_SHA256_BLOCK_SIZE) {
AP4_DigestSha256 kdigest;
kdigest.Update(key, key_size);
kdigest.Final(hk);
@@ -301,29 +276,25 @@ AP4_HmacSha256::AP4_HmacSha256(const AP4_UI08* key, AP4_Size key_size)
}
/* compute key XOR ipad */
- for(unsigned int i = 0; i < key_size; i++)
- {
- workspace[i] = key[i] ^ 0x36;
+ for (unsigned int i = 0; i < key_size; i++) {
+ workspace[i] = key[i] ^ 0x36;
}
- for(unsigned int i = key_size; i < AP4_SHA256_BLOCK_SIZE; i++)
- {
- workspace[i] = 0x36;
+ for (unsigned int i = key_size; i < AP4_SHA256_BLOCK_SIZE; i++) {
+ workspace[i] = 0x36;
}
-
- /* start the inner digest with (key XOR ipad) */
+
+ /* start the inner digest with (key XOR ipad) */
m_InnerDigest.Update(workspace, AP4_SHA256_BLOCK_SIZE);
/* compute key XOR opad */
- for(unsigned int i = 0; i < key_size; i++)
- {
- workspace[i] = key[i] ^ 0x5c;
+ for (unsigned int i = 0; i < key_size; i++) {
+ workspace[i] = key[i] ^ 0x5c;
}
- for(unsigned int i = key_size; i < AP4_SHA256_BLOCK_SIZE; i++)
- {
- workspace[i] = 0x5c;
+ for (unsigned int i = key_size; i < AP4_SHA256_BLOCK_SIZE; i++) {
+ workspace[i] = 0x5c;
}
-
- /* start the outer digest with (key XOR opad) */
+
+ /* start the outer digest with (key XOR opad) */
m_OuterDigest.Update(workspace, AP4_SHA256_BLOCK_SIZE);
}
@@ -337,7 +308,7 @@ AP4_HmacSha256::Final(AP4_DataBuffer& mac)
AP4_DataBuffer inner;
m_InnerDigest.Final(inner);
m_OuterDigest.Update(inner.GetData(), inner.GetDataSize());
-
+
/* return the value of the outer digest */
return m_OuterDigest.Final(mac);
}
@@ -346,19 +317,14 @@ AP4_HmacSha256::Final(AP4_DataBuffer& mac)
| AP4_Hmac::Create
+---------------------------------------------------------------------*/
AP4_Result
-AP4_Hmac::Create(Algorithm algorithm,
+AP4_Hmac::Create(Algorithm algorithm,
const AP4_UI08* key,
AP4_Size key_size,
AP4_Hmac*& hmac)
{
- switch(algorithm)
- {
- case SHA256:
- hmac = new AP4_HmacSha256(key, key_size);
- return AP4_SUCCESS;
- default:
- hmac = NULL;
- return AP4_ERROR_NOT_SUPPORTED;
+ switch (algorithm) {
+ case SHA256: hmac = new AP4_HmacSha256(key, key_size); return AP4_SUCCESS;
+ default: hmac = NULL; return AP4_ERROR_NOT_SUPPORTED;
}
}
diff --git a/src/filters/parser/MP4Splitter/AP4/Source/Crypto/Ap4Hmac.h b/src/filters/parser/MP4Splitter/AP4/Source/Crypto/Ap4Hmac.h
index e8fe8d0c6..22957a0d4 100644
--- a/src/filters/parser/MP4Splitter/AP4/Source/Crypto/Ap4Hmac.h
+++ b/src/filters/parser/MP4Splitter/AP4/Source/Crypto/Ap4Hmac.h
@@ -43,17 +43,16 @@ class AP4_Hmac
{
public:
// types
- typedef enum
- {
+ typedef enum {
SHA256
} Algorithm;
-
+
// class methods
- static AP4_Result Create(Algorithm algorithm,
+ static AP4_Result Create(Algorithm algorithm,
const AP4_UI08* key,
AP4_Size key_size,
AP4_Hmac*& hmac);
-
+
// methods
virtual ~AP4_Hmac() {}
virtual AP4_Result Update(const AP4_UI08* data, AP4_Size data_size) = 0;
diff --git a/src/filters/parser/MP4Splitter/AP4/Source/Crypto/Ap4KeyWrap.cpp b/src/filters/parser/MP4Splitter/AP4/Source/Crypto/Ap4KeyWrap.cpp
index 9ab357126..3cc37f5ce 100644
--- a/src/filters/parser/MP4Splitter/AP4/Source/Crypto/Ap4KeyWrap.cpp
+++ b/src/filters/parser/MP4Splitter/AP4/Source/Crypto/Ap4KeyWrap.cpp
@@ -28,7 +28,7 @@
/*
Portions of this code are based on the code of LibTomCrypt
- that was released into public domain by Tom St Denis.
+ that was released into public domain by Tom St Denis.
*/
/*----------------------------------------------------------------------
@@ -46,59 +46,56 @@
| AP4_AesKeyWrap
+---------------------------------------------------------------------*/
AP4_Result
-AP4_AesKeyWrap(const AP4_UI08* kek,
- const AP4_UI08* cleartext_key,
+AP4_AesKeyWrap(const AP4_UI08* kek,
+ const AP4_UI08* cleartext_key,
AP4_Size cleartext_key_size,
AP4_DataBuffer& wrapped_key)
{
// check parameters
- if(cleartext_key_size % 8)
- {
+ if (cleartext_key_size % 8) {
// not a multiple of 64 bits
return AP4_ERROR_INVALID_PARAMETERS;
}
-
+
// the output size is (n+1)*64 bits
// where n is the number of 64-bit blocks
// of the cleartext key
- unsigned int n = cleartext_key_size / 8;
- wrapped_key.SetDataSize((n + 1) * 8);
-
+ unsigned int n = cleartext_key_size/8;
+ wrapped_key.SetDataSize((n+1)*8);
+
// Step 1. Initialize variables.
// Set A = IV, an initial value (0xA6)
// For i = 1 to n
// R[i] = P[i]
AP4_UI08* a = (AP4_UI08*)wrapped_key.UseData();
AP4_SetMemory(a, 0xA6, 8);
- AP4_UI08* r = a + 8;
+ AP4_UI08* r = a+8;
AP4_CopyMemory(r, cleartext_key, cleartext_key_size);
-
+
// Step 2. Calculate intermediate values.
// For j = 0 to 5
// For i=1 to n
// B = AES(K, A | R[i])
// A = MSB(64, B) ^ t where t = (n*j)+i
- // R[i] = LSB(64, B)
+ // R[i] = LSB(64, B)
AP4_AesBlockCipher block_cipher(kek, AP4_BlockCipher::ENCRYPT);
- for(unsigned int j = 0; j <= 5; j++)
- {
- r = a + 8;
- for(unsigned int i = 1; i <= n; i++)
- {
+ for (unsigned int j=0; j <= 5; j++) {
+ r = a + 8;
+ for (unsigned int i=1; i<=n; i++) {
AP4_UI08 workspace[16];
AP4_UI08 b[16];
AP4_CopyMemory(workspace, a, 8);
AP4_CopyMemory(&workspace[8], r, 8);
block_cipher.ProcessBlock(workspace, b);
AP4_CopyMemory(a, b, 8);
- a[7] ^= n * j + i;
+ a[7] ^= n*j+i;
AP4_CopyMemory(r, &b[8], 8);
r += 8;
- }
- }
-
+ }
+ }
+
// Step 3. Output the results.
- // (Nothing to do here since we've worked in-place
+ // (Nothing to do here since we've worked in-place
return AP4_SUCCESS;
}
@@ -112,25 +109,24 @@ AP4_AesKeyUnwrap(const AP4_UI08* kek,
AP4_DataBuffer& cleartext_key)
{
// check parameters
- if((wrapped_key_size % 8) || (wrapped_key_size < 24))
- {
+ if ((wrapped_key_size % 8) || (wrapped_key_size < 24)) {
// not a multiple of 64 bits or too small
return AP4_ERROR_INVALID_PARAMETERS;
}
-
+
// setup the output buffer
- unsigned int n = (wrapped_key_size / 8) - 1;
- cleartext_key.SetDataSize(n * 8);
-
+ unsigned int n = (wrapped_key_size/8)-1;
+ cleartext_key.SetDataSize(n*8);
+
// Step 1. Initialize variables.
// Set A = C[0]
// For i = 1 to n
// R[i] = C[i]
- AP4_UI08 a[8];
+ AP4_UI08 a[8];
AP4_CopyMemory(a, wrapped_key, 8);
AP4_UI08* r = (AP4_UI08*)cleartext_key.UseData();
- AP4_CopyMemory(r, wrapped_key + 8, 8 * n);
-
+ AP4_CopyMemory(r, wrapped_key+8, 8*n);
+
// Step 2. Compute intermediate values.
// For j = 5 to 0
// For i = n to 1
@@ -138,15 +134,13 @@ AP4_AesKeyUnwrap(const AP4_UI08* kek,
// A = MSB(64, B)
// R[i] = LSB(64, B)
AP4_AesBlockCipher block_cipher(kek, AP4_BlockCipher::DECRYPT);
- for(int j = 5; j >= 0; j--)
- {
- r = (AP4_UI08*)cleartext_key.UseData() + (n - 1) * 8;
- for(int i = n; i >= 1; i--)
- {
+ for (int j=5; j>=0; j--) {
+ r = (AP4_UI08*)cleartext_key.UseData()+(n-1)*8;
+ for (int i=n; i>=1; i--) {
AP4_UI08 workspace[16];
AP4_UI08 b[16];
AP4_CopyMemory(workspace, a, 8);
- workspace[7] ^= (n * j) + i;
+ workspace[7] ^= (n*j)+i;
AP4_CopyMemory(&workspace[8], r, 8);
block_cipher.ProcessBlock(workspace, b);
AP4_CopyMemory(a, b, 8);
@@ -154,7 +148,7 @@ AP4_AesKeyUnwrap(const AP4_UI08* kek,
r -= 8;
}
}
-
+
// Step 3. Output results.
// If A is an appropriate initial value (see 2.2.3),
// Then
@@ -162,14 +156,12 @@ AP4_AesKeyUnwrap(const AP4_UI08* kek,
// P[i] = R[i]
// Else
// Return an error
- for(unsigned int i = 0; i < 8; i++)
- {
- if(a[i] != 0xA6)
- {
+ for (unsigned int i=0; i<8; i++) {
+ if (a[i] != 0xA6) {
cleartext_key.SetDataSize(0);
return AP4_ERROR_INVALID_FORMAT;
}
- }
+ }
return AP4_SUCCESS;
}
diff --git a/src/filters/parser/MP4Splitter/AP4/Source/Crypto/Ap4KeyWrap.h b/src/filters/parser/MP4Splitter/AP4/Source/Crypto/Ap4KeyWrap.h
index 95ba65711..d0db038e9 100644
--- a/src/filters/parser/MP4Splitter/AP4/Source/Crypto/Ap4KeyWrap.h
+++ b/src/filters/parser/MP4Splitter/AP4/Source/Crypto/Ap4KeyWrap.h
@@ -39,11 +39,11 @@
/*----------------------------------------------------------------------
| functions
+---------------------------------------------------------------------*/
-AP4_Result AP4_AesKeyWrap(const AP4_UI08* kek,
- const AP4_UI08* cleartext_key,
+AP4_Result AP4_AesKeyWrap(const AP4_UI08* kek,
+ const AP4_UI08* cleartext_key,
AP4_Size cleartext_key_size,
AP4_DataBuffer& wrapped_key);
-
+
AP4_Result AP4_AesKeyUnwrap(const AP4_UI08* kek,
const AP4_UI08* wrapped_key,
AP4_Size wrapped_key_size,
diff --git a/src/filters/parser/MP4Splitter/AP4/Source/Crypto/Ap4StreamCipher.cpp b/src/filters/parser/MP4Splitter/AP4/Source/Crypto/Ap4StreamCipher.cpp
index cbb7d9f57..0b9320f5c 100644
--- a/src/filters/parser/MP4Splitter/AP4/Source/Crypto/Ap4StreamCipher.cpp
+++ b/src/filters/parser/MP4Splitter/AP4/Source/Crypto/Ap4StreamCipher.cpp
@@ -36,22 +36,19 @@
| AP4_CtrStreamCipher::AP4_CtrStreamCipher
+---------------------------------------------------------------------*/
AP4_CtrStreamCipher::AP4_CtrStreamCipher(AP4_BlockCipher* block_cipher,
- const AP4_UI08* salt,
- AP4_Size counter_size) :
+ const AP4_UI08* salt,
+ AP4_Size counter_size) :
m_StreamOffset(0),
m_CounterSize(counter_size),
m_BlockCipher(block_cipher)
{
- if(m_CounterSize > 16) m_CounterSize = 16;
+ if (m_CounterSize > 16) m_CounterSize = 16;
// use the salt to initialize the base counter
- if(salt)
- {
+ if (salt) {
// initialize the base counter with a salting key
AP4_CopyMemory(m_BaseCounter, salt, AP4_CIPHER_BLOCK_SIZE);
- }
- else
- {
+ } else {
// initialize the base counter with zeros
AP4_SetMemory(m_BaseCounter, 0, AP4_CIPHER_BLOCK_SIZE);
}
@@ -75,13 +72,10 @@ AP4_CtrStreamCipher::~AP4_CtrStreamCipher()
AP4_Result
AP4_CtrStreamCipher::SetIV(const AP4_UI08* counter)
{
- if(counter)
- {
+ if (counter) {
AP4_CopyMemory(&m_BaseCounter[AP4_CIPHER_BLOCK_SIZE-m_CounterSize],
counter, m_CounterSize);
- }
- else
- {
+ } else {
AP4_SetMemory(&m_BaseCounter[AP4_CIPHER_BLOCK_SIZE-m_CounterSize],
0, m_CounterSize);
}
@@ -98,19 +92,18 @@ AP4_CtrStreamCipher::SetStreamOffset(AP4_UI64 offset,
AP4_Cardinal* preroll)
{
// do nothing if we're already at that offset
- if(offset == m_StreamOffset) return AP4_SUCCESS;
+ if (offset == m_StreamOffset) return AP4_SUCCESS;
// update the offset
m_StreamOffset = offset;
// update the key stream if necessary
- if(m_StreamOffset & 0xF)
- {
+ if (m_StreamOffset & 0xF) {
UpdateKeyStream();
}
-
- if(preroll != NULL) *preroll = 0;
-
+
+ if (preroll != NULL) *preroll = 0;
+
return AP4_SUCCESS;
}
@@ -121,25 +114,23 @@ void
AP4_CtrStreamCipher::UpdateKeyStream()
{
// setup counter offset bytes
- AP4_UI64 counter_offset = m_StreamOffset / AP4_CIPHER_BLOCK_SIZE;
+ AP4_UI64 counter_offset = m_StreamOffset/AP4_CIPHER_BLOCK_SIZE;
AP4_UI08 counter_offset_bytes[8];
AP4_BytesFromUInt64BE(counter_offset_bytes, counter_offset);
-
+
// compute the new counter
AP4_UI08 counter_block[AP4_CIPHER_BLOCK_SIZE];
unsigned int carry = 0;
- for(unsigned int i = 0; i < m_CounterSize; i++)
- {
- unsigned int o = AP4_CIPHER_BLOCK_SIZE - 1 - i;
+ for (unsigned int i=0; i<m_CounterSize; i++) {
+ unsigned int o = AP4_CIPHER_BLOCK_SIZE-1-i;
unsigned int x = m_BaseCounter[o];
- unsigned int y = (i < 8) ? counter_offset_bytes[7-i] : 0;
- unsigned int sum = x + y + carry;
- counter_block[o] = (AP4_UI08)(sum & 0xFF);
- carry = ((sum >= 0x100) ? 1 : 0);
+ unsigned int y = (i<8)?counter_offset_bytes[7-i]:0;
+ unsigned int sum = x+y+carry;
+ counter_block[o] = (AP4_UI08)(sum&0xFF);
+ carry = ((sum >= 0x100)?1:0);
}
- for(unsigned int i = m_CounterSize; i < AP4_CIPHER_BLOCK_SIZE; i++)
- {
- unsigned int o = AP4_CIPHER_BLOCK_SIZE - 1 - i;
+ for (unsigned int i=m_CounterSize; i<AP4_CIPHER_BLOCK_SIZE; i++) {
+ unsigned int o = AP4_CIPHER_BLOCK_SIZE-1-i;
counter_block[o] = m_BaseCounter[o];
}
@@ -151,44 +142,40 @@ AP4_CtrStreamCipher::UpdateKeyStream()
| AP4_CtrStreamCipher::ProcessBuffer
+---------------------------------------------------------------------*/
AP4_Result
-AP4_CtrStreamCipher::ProcessBuffer(const AP4_UI08* in,
+AP4_CtrStreamCipher::ProcessBuffer(const AP4_UI08* in,
AP4_Size in_size,
- AP4_UI08* out,
+ AP4_UI08* out,
AP4_Size* out_size /* = NULL */,
bool /* is_last_buffer */)
{
- if(m_BlockCipher == NULL) return AP4_ERROR_INVALID_STATE;
-
- if(out_size != NULL && *out_size < in_size)
- {
+ if (m_BlockCipher == NULL) return AP4_ERROR_INVALID_STATE;
+
+ if (out_size != NULL && *out_size < in_size) {
return AP4_ERROR_BUFFER_TOO_SMALL;
}
- // in CTR mode, the output is the same size as the input
- if(out_size != NULL) *out_size = in_size;
+ // in CTR mode, the output is the same size as the input
+ if (out_size != NULL) *out_size = in_size;
// process all the bytes in the buffer
- while(in_size)
- {
+ while (in_size) {
// compute the number of bytes available in this chunk
- AP4_UI32 index = (AP4_UI32)(m_StreamOffset & (AP4_CIPHER_BLOCK_SIZE - 1));
+ AP4_UI32 index = (AP4_UI32)(m_StreamOffset & (AP4_CIPHER_BLOCK_SIZE-1));
AP4_UI32 chunk;
// update the key stream if we are on a boundary
- if(index == 0)
- {
+ if (index == 0) {
UpdateKeyStream();
chunk = AP4_CIPHER_BLOCK_SIZE;
}
// compute the number of bytes remaining in the chunk
chunk = AP4_CIPHER_BLOCK_SIZE - index;
- if(chunk > in_size) chunk = in_size;
+ if (chunk > in_size) chunk = in_size;
// encrypt/decrypt the chunk
AP4_UI08* x = &m_XBlock[index];
- for(AP4_UI32 i = 0; i < chunk; i++)
- {
+ for (AP4_UI32 i = 0; i < chunk; i++) {
*out++ = *in++ ^ *x++;
}
@@ -196,7 +183,7 @@ AP4_CtrStreamCipher::ProcessBuffer(const AP4_UI08* in,
m_StreamOffset += chunk;
in_size -= chunk;
}
-
+
return AP4_SUCCESS;
}
@@ -204,7 +191,7 @@ AP4_CtrStreamCipher::ProcessBuffer(const AP4_UI08* in,
| AP4_CbcStreamCipher::AP4_CbcStreamCipher
+---------------------------------------------------------------------*/
AP4_CbcStreamCipher::AP4_CbcStreamCipher(AP4_BlockCipher* block_cipher,
- CipherDirection direction) :
+ CipherDirection direction) :
m_Direction(direction),
m_StreamOffset(0),
m_OutputSkip(0),
@@ -247,43 +234,38 @@ AP4_CbcStreamCipher::SetStreamOffset(AP4_UI64 offset,
AP4_Cardinal* preroll)
{
// does not make sense for encryption
- if(m_Direction == AP4_StreamCipher::ENCRYPT) return AP4_ERROR_NOT_SUPPORTED;
-
+ if (m_Direction == AP4_StreamCipher::ENCRYPT) return AP4_ERROR_NOT_SUPPORTED;
+
// check params
- if(preroll == NULL) return AP4_ERROR_INVALID_PARAMETERS;
+ if (preroll == NULL) return AP4_ERROR_INVALID_PARAMETERS;
// reset the end of stream flag
m_Eos = false;
-
+
// special cases
- if(offset == 0)
- {
+ if (offset == 0) {
*preroll = 0;
return SetIV(m_Iv);
}
- if(offset == m_StreamOffset)
- {
+ if (offset == m_StreamOffset) {
*preroll = m_PrerollByteCount;
- m_OutputSkip = (AP4_Size)(offset % AP4_CIPHER_BLOCK_SIZE);
+ m_OutputSkip = (AP4_Size)(offset%AP4_CIPHER_BLOCK_SIZE);
return AP4_SUCCESS;
}
// other cases
- if(offset < AP4_CIPHER_BLOCK_SIZE)
- {
+ if (offset < AP4_CIPHER_BLOCK_SIZE) {
// reset the IV to the output block cache
AP4_CopyMemory(m_OutBlockCache, m_Iv, AP4_CIPHER_BLOCK_SIZE);
m_PrerollByteCount = (AP4_Cardinal) offset;
+ } else {
+ m_PrerollByteCount = (AP4_Cardinal) ((offset%AP4_CIPHER_BLOCK_SIZE)
+ + AP4_CIPHER_BLOCK_SIZE);
}
- else
- {
- m_PrerollByteCount = (AP4_Cardinal)((offset % AP4_CIPHER_BLOCK_SIZE)
- + AP4_CIPHER_BLOCK_SIZE);
- }
-
+
*preroll = m_PrerollByteCount;
m_StreamOffset = offset;
- m_OutputSkip = (AP4_Size)(offset % AP4_CIPHER_BLOCK_SIZE);
+ m_OutputSkip = (AP4_Size)(offset%AP4_CIPHER_BLOCK_SIZE);
return AP4_SUCCESS;
}
@@ -292,71 +274,60 @@ AP4_CbcStreamCipher::SetStreamOffset(AP4_UI64 offset,
| AP4_CbcStreamCipher::ProcessBuffer
+---------------------------------------------------------------------*/
AP4_Result
-AP4_CbcStreamCipher::ProcessBuffer(const AP4_UI08* in,
+AP4_CbcStreamCipher::ProcessBuffer(const AP4_UI08* in,
AP4_Size in_size,
- AP4_UI08* out,
+ AP4_UI08* out,
AP4_Size* out_size,
bool is_last_buffer /* = false */)
{
// check the parameters
- if(out_size == NULL) return AP4_ERROR_INVALID_PARAMETERS;
-
+ if (out_size == NULL) return AP4_ERROR_INVALID_PARAMETERS;
+
// check the state
- if(m_BlockCipher == NULL || m_Eos)
- {
+ if (m_BlockCipher == NULL || m_Eos) {
*out_size = 0;
return AP4_ERROR_INVALID_STATE;
}
- if(is_last_buffer) m_Eos = true;
-
+ if (is_last_buffer) m_Eos = true;
+
// if there was a previous call to SetStreamOffset that set m_PrerollByteCount,
- // we require that this call provides the at least entire preroll data
- if(m_PrerollByteCount)
- {
- if(in_size < m_PrerollByteCount)
- {
+ // we require that this call provides the at least entire preroll data
+ if (m_PrerollByteCount) {
+ if (in_size < m_PrerollByteCount) {
*out_size = 0;
return AP4_ERROR_NOT_ENOUGH_DATA;
}
}
// compute how many blocks we span
- AP4_UI64 start_block = m_StreamOffset / AP4_CIPHER_BLOCK_SIZE;
- AP4_UI64 end_block = (m_StreamOffset + in_size - m_PrerollByteCount) / AP4_CIPHER_BLOCK_SIZE;
- AP4_UI32 blocks_needed = (AP4_UI32)(end_block - start_block);
+ AP4_UI64 start_block = m_StreamOffset/AP4_CIPHER_BLOCK_SIZE;
+ AP4_UI64 end_block = (m_StreamOffset+in_size-m_PrerollByteCount)/AP4_CIPHER_BLOCK_SIZE;
+ AP4_UI32 blocks_needed = (AP4_UI32)(end_block-start_block);
- if(m_Direction == ENCRYPT)
- {
+ if (m_Direction == ENCRYPT) {
// compute how many blocks we will need to produce
unsigned int padded_in_size = in_size;
AP4_UI08 pad_byte = 0;
- if(is_last_buffer)
- {
+ if (is_last_buffer) {
++blocks_needed;
- pad_byte = AP4_CIPHER_BLOCK_SIZE - (AP4_UI08)((m_StreamOffset + in_size) % AP4_CIPHER_BLOCK_SIZE);
+ pad_byte = AP4_CIPHER_BLOCK_SIZE-(AP4_UI08)((m_StreamOffset+in_size)%AP4_CIPHER_BLOCK_SIZE);
padded_in_size += pad_byte;
}
- if(*out_size < blocks_needed * AP4_CIPHER_BLOCK_SIZE)
- {
- *out_size = blocks_needed * AP4_CIPHER_BLOCK_SIZE;
+ if (*out_size < blocks_needed*AP4_CIPHER_BLOCK_SIZE) {
+ *out_size = blocks_needed*AP4_CIPHER_BLOCK_SIZE;
return AP4_ERROR_BUFFER_TOO_SMALL;
}
- *out_size = blocks_needed * AP4_CIPHER_BLOCK_SIZE;
+ *out_size = blocks_needed*AP4_CIPHER_BLOCK_SIZE;
- unsigned int position = (unsigned int)(m_StreamOffset % AP4_CIPHER_BLOCK_SIZE);
+ unsigned int position = (unsigned int)(m_StreamOffset%AP4_CIPHER_BLOCK_SIZE);
m_StreamOffset += in_size;
- for(unsigned int x = 0; x < padded_in_size; x++)
- {
- if(x < in_size)
- {
+ for (unsigned int x=0; x<padded_in_size; x++) {
+ if (x < in_size) {
m_InBlockCache[position] = in[x] ^ m_OutBlockCache[position];
+ } else {
+ m_InBlockCache[position] = pad_byte ^ m_OutBlockCache[position];
}
- else
- {
- m_InBlockCache[position] = pad_byte ^ m_OutBlockCache[position];
- }
- if(++position == AP4_CIPHER_BLOCK_SIZE)
- {
+ if (++position == AP4_CIPHER_BLOCK_SIZE) {
// encrypt and emit a block
m_BlockCipher->ProcessBlock(m_InBlockCache, m_OutBlockCache);
AP4_CopyMemory(out, m_OutBlockCache, AP4_CIPHER_BLOCK_SIZE);
@@ -364,27 +335,21 @@ AP4_CbcStreamCipher::ProcessBuffer(const AP4_UI08* in,
position = 0;
}
}
- }
- else
- {
+ } else {
// compute how many blocks we may produce
- AP4_Size bytes_produced = blocks_needed * AP4_CIPHER_BLOCK_SIZE;
- if(bytes_produced > m_OutputSkip)
- {
+ AP4_Size bytes_produced = blocks_needed*AP4_CIPHER_BLOCK_SIZE;
+ if (bytes_produced > m_OutputSkip) {
bytes_produced -= m_OutputSkip;
}
- if(*out_size < bytes_produced)
- {
+ if (*out_size < bytes_produced) {
*out_size = bytes_produced;
return AP4_ERROR_BUFFER_TOO_SMALL;
}
*out_size = bytes_produced;
-
- // if we've just been seeked (SetStreamOffset),
- if(m_PrerollByteCount > 0)
- {
- if(m_PrerollByteCount >= AP4_CIPHER_BLOCK_SIZE)
- {
+
+ // if we've just been seeked (SetStreamOffset),
+ if (m_PrerollByteCount > 0) {
+ if (m_PrerollByteCount >= AP4_CIPHER_BLOCK_SIZE) {
// fill the outblock cache with the first 16 bytes
AP4_CopyMemory(m_OutBlockCache, in, AP4_CIPHER_BLOCK_SIZE);
in += AP4_CIPHER_BLOCK_SIZE;
@@ -393,10 +358,9 @@ AP4_CbcStreamCipher::ProcessBuffer(const AP4_UI08* in,
}
AP4_ASSERT(m_PrerollByteCount < 16);
-
+
// fill m_InBlockCache with the input for the remaining m_PrerollByteCount
- if(m_PrerollByteCount)
- {
+ if (m_PrerollByteCount) {
AP4_CopyMemory(m_InBlockCache, in, m_PrerollByteCount);
in += m_PrerollByteCount;
in_size -= m_PrerollByteCount;
@@ -404,49 +368,43 @@ AP4_CbcStreamCipher::ProcessBuffer(const AP4_UI08* in,
}
}
- unsigned int position = (unsigned int)(m_StreamOffset % AP4_CIPHER_BLOCK_SIZE);
+ unsigned int position = (unsigned int)(m_StreamOffset%AP4_CIPHER_BLOCK_SIZE);
m_StreamOffset += in_size;
- for(unsigned int x = 0; x < in_size; x++)
- {
+ for (unsigned int x=0; x<in_size; x++) {
m_InBlockCache[position] = in[x];
- if(++position == AP4_CIPHER_BLOCK_SIZE)
- {
+ if (++position == AP4_CIPHER_BLOCK_SIZE) {
// decrypt a block
AP4_UI08 out_block[AP4_CIPHER_BLOCK_SIZE];
m_BlockCipher->ProcessBlock(m_InBlockCache, out_block);
- for(unsigned int y = 0; y < AP4_CIPHER_BLOCK_SIZE; y++)
- {
+ for (unsigned int y=0; y<AP4_CIPHER_BLOCK_SIZE; y++) {
out_block[y] ^= m_OutBlockCache[y];
}
AP4_CopyMemory(m_OutBlockCache, m_InBlockCache, AP4_CIPHER_BLOCK_SIZE);
-
+
// emit the block (or partial block) to the out buffer
- unsigned int out_chunk = AP4_CIPHER_BLOCK_SIZE - m_OutputSkip;
- AP4_CopyMemory(out, out_block + m_OutputSkip, out_chunk);
+ unsigned int out_chunk = AP4_CIPHER_BLOCK_SIZE-m_OutputSkip;
+ AP4_CopyMemory(out, out_block+m_OutputSkip, out_chunk);
out += out_chunk;
position = 0;
m_OutputSkip = 0;
}
}
- if(is_last_buffer && m_Direction == DECRYPT)
- {
+ if (is_last_buffer && m_Direction == DECRYPT) {
// check that we have fed an integral number of blocks
- if(m_StreamOffset % AP4_CIPHER_BLOCK_SIZE != 0)
- {
+ if (m_StreamOffset%AP4_CIPHER_BLOCK_SIZE != 0) {
*out_size = 0;
return AP4_ERROR_INVALID_PARAMETERS;
}
// remove the padding
AP4_UI08 pad_byte = out[-1];
- if(pad_byte == 0 || pad_byte > AP4_CIPHER_BLOCK_SIZE)
- {
+ if (pad_byte == 0 || pad_byte > AP4_CIPHER_BLOCK_SIZE) {
*out_size = 0;
return AP4_ERROR_INVALID_FORMAT;
}
*out_size -= pad_byte;
}
}
-
+
return AP4_SUCCESS;
}
diff --git a/src/filters/parser/MP4Splitter/AP4/Source/Crypto/Ap4StreamCipher.h b/src/filters/parser/MP4Splitter/AP4/Source/Crypto/Ap4StreamCipher.h
index ca4893d16..9fcec8136 100644
--- a/src/filters/parser/MP4Splitter/AP4/Source/Crypto/Ap4StreamCipher.h
+++ b/src/filters/parser/MP4Splitter/AP4/Source/Crypto/Ap4StreamCipher.h
@@ -39,7 +39,7 @@
/*----------------------------------------------------------------------
| constants
+---------------------------------------------------------------------*/
-// we only support this for now
+// we only support this for now
const unsigned int AP4_CIPHER_BLOCK_SIZE = 16;
/*----------------------------------------------------------------------
@@ -49,29 +49,28 @@ class AP4_StreamCipher
{
public:
// types
- typedef enum
- {
+ typedef enum {
ENCRYPT,
DECRYPT
} CipherDirection;
-
+
// methods
virtual ~AP4_StreamCipher() {}
-
+
virtual AP4_UI64 GetStreamOffset() = 0;
-
+
virtual AP4_Result ProcessBuffer(const AP4_UI08* in,
AP4_Size in_size,
AP4_UI08* out,
AP4_Size* out_size,
bool is_last_buffer = false) = 0;
-
+
// preroll gives the number of bytes you have to preroll your input and feed
- // it through ProcessBuffer (in one shot) in order to be able to spit out
+ // it through ProcessBuffer (in one shot) in order to be able to spit out
// the output at the given offset
virtual AP4_Result SetStreamOffset(AP4_UI64 offset,
AP4_Cardinal* preroll) = 0;
-
+
virtual AP4_Result SetIV(const AP4_UI08* iv) = 0;
virtual const AP4_UI08* GetIV() = 0;
};
@@ -83,35 +82,29 @@ public:
class AP4_CtrStreamCipher : public AP4_StreamCipher
{
public:
- // methods
+ // methods
/**
* The block cipher is passed with transfer of ownership (it will
* be destroyed when this object is destroyed).
*/
- AP4_CtrStreamCipher(AP4_BlockCipher* block_cipher,
+ AP4_CtrStreamCipher(AP4_BlockCipher* block_cipher,
const AP4_UI08* salt,
AP4_Size counter_size);
~AP4_CtrStreamCipher();
-
+
// AP4_StreamCipher implementation
virtual AP4_Result SetStreamOffset(AP4_UI64 offset,
- AP4_Cardinal* preroll = NULL);
- virtual AP4_UI64 GetStreamOffset()
- {
- return m_StreamOffset;
- }
+ AP4_Cardinal* preroll = NULL);
+ virtual AP4_UI64 GetStreamOffset() { return m_StreamOffset; }
virtual AP4_Result ProcessBuffer(const AP4_UI08* in,
AP4_Size in_size,
AP4_UI08* out,
AP4_Size* out_size = NULL,
bool is_last_buffer = false);
-
+
virtual AP4_Result SetIV(const AP4_UI08* iv);
- virtual const AP4_UI08* GetIV()
- {
- return m_BaseCounter;
- }
+ virtual const AP4_UI08* GetIV() { return m_BaseCounter; }
private:
// methods
@@ -140,24 +133,18 @@ public:
*/
AP4_CbcStreamCipher(AP4_BlockCipher* block_cipher, CipherDirection direction);
~AP4_CbcStreamCipher();
-
+
// AP4_StreamCipher implementation
virtual AP4_Result SetStreamOffset(AP4_UI64 offset,
AP4_Cardinal* preroll);
- virtual AP4_UI64 GetStreamOffset()
- {
- return m_StreamOffset;
- }
+ virtual AP4_UI64 GetStreamOffset() { return m_StreamOffset; }
virtual AP4_Result ProcessBuffer(const AP4_UI08* in,
AP4_Size in_size,
AP4_UI08* out,
AP4_Size* out_size,
bool is_last_buffer = false);
virtual AP4_Result SetIV(const AP4_UI08* iv);
- virtual const AP4_UI08* GetIV()
- {
- return m_Iv;
- };
+ virtual const AP4_UI08* GetIV() { return m_Iv; };
private:
// members
diff --git a/src/filters/parser/MP4Splitter/AP4/Source/MetaData/Ap4MetaData.cpp b/src/filters/parser/MP4Splitter/AP4/Source/MetaData/Ap4MetaData.cpp
index 0a00e3ecb..5f97839d9 100644
--- a/src/filters/parser/MP4Splitter/AP4/Source/MetaData/Ap4MetaData.cpp
+++ b/src/filters/parser/MP4Splitter/AP4/Source/MetaData/Ap4MetaData.cpp
@@ -1,6 +1,6 @@
/*****************************************************************
|
-| AP4 - MetaData
+| AP4 - MetaData
|
| Copyright 2002-2008 Axiomatic Systems, LLC
|
@@ -50,8 +50,7 @@ AP4_DEFINE_DYNAMIC_CAST_ANCHOR(AP4_DataAtom)
/*----------------------------------------------------------------------
| metadata keys
+---------------------------------------------------------------------*/
-static const AP4_MetaData::KeyInfo AP4_MetaData_KeyInfos [] =
-{
+static const AP4_MetaData::KeyInfo AP4_MetaData_KeyInfos [] = {
{"Name", "Name", AP4_ATOM_TYPE_cNAM, AP4_MetaData::Value::TYPE_STRING_UTF_8},
{"Artist", "Artist", AP4_ATOM_TYPE_cART, AP4_MetaData::Value::TYPE_STRING_UTF_8},
{"AlbumArtist", "Album Artist", AP4_ATOM_TYPE_aART, AP4_MetaData::Value::TYPE_STRING_UTF_8},
@@ -98,13 +97,13 @@ static const AP4_MetaData::KeyInfo AP4_MetaData_KeyInfos [] =
{"Author", "Author", AP4_ATOM_TYPE_AUTH, AP4_MetaData::Value::TYPE_STRING_UTF_8},
};
AP4_Array<AP4_MetaData::KeyInfo> AP4_MetaData::KeyInfos(
- AP4_MetaData_KeyInfos,
- sizeof(AP4_MetaData_KeyInfos) / sizeof(KeyInfo));
+ AP4_MetaData_KeyInfos,
+ sizeof(AP4_MetaData_KeyInfos)/sizeof(KeyInfo));
/*----------------------------------------------------------------------
| genre IDs
+---------------------------------------------------------------------*/
-static const char* const Ap4Id3Genres[] =
+static const char* const Ap4Id3Genres[] =
{
"Blues",
"Classic Rock",
@@ -235,8 +234,7 @@ static const char* const Ap4Id3Genres[] =
};
static const char*
-Ap4StikNames[] =
-{
+Ap4StikNames[] = {
"Movie", // 0
"Normal", // 1
"Audiobook", // 2
@@ -246,7 +244,7 @@ Ap4StikNames[] =
"Music Video", // 6
"?", // 7
"?", // 8
- "Short Film", // 9
+ "Short Film", // 9
"TV Show", // 10
"Booklet", // 11
"?", // 12
@@ -287,8 +285,7 @@ const AP4_Size AP4_DATA_ATOM_MAX_SIZE = 0x40000000;
/*----------------------------------------------------------------------
| 3GPP localized string atoms
+---------------------------------------------------------------------*/
-const AP4_Atom::Type AP4_MetaDataAtomTypeHandler::_3gppLocalizedStringTypes[] =
-{
+const AP4_Atom::Type AP4_MetaDataAtomTypeHandler::_3gppLocalizedStringTypes[] = {
AP4_ATOM_TYPE_TITL,
AP4_ATOM_TYPE_DSCP,
AP4_ATOM_TYPE_CPRT,
@@ -296,17 +293,15 @@ const AP4_Atom::Type AP4_MetaDataAtomTypeHandler::_3gppLocalizedStringTypes[] =
AP4_ATOM_TYPE_AUTH,
AP4_ATOM_TYPE_GNRE
};
-const AP4_MetaDataAtomTypeHandler::TypeList AP4_MetaDataAtomTypeHandler::_3gppLocalizedStringTypeList =
-{
+const AP4_MetaDataAtomTypeHandler::TypeList AP4_MetaDataAtomTypeHandler::_3gppLocalizedStringTypeList = {
_3gppLocalizedStringTypes,
- sizeof(_3gppLocalizedStringTypes) / sizeof(_3gppLocalizedStringTypes[0])
+ sizeof(_3gppLocalizedStringTypes)/sizeof(_3gppLocalizedStringTypes[0])
};
/*----------------------------------------------------------------------
| other 3GPP atoms
+---------------------------------------------------------------------*/
-const AP4_Atom::Type AP4_MetaDataAtomTypeHandler::_3gppOtherTypes[] =
-{
+const AP4_Atom::Type AP4_MetaDataAtomTypeHandler::_3gppOtherTypes[] = {
AP4_ATOM_TYPE_RTNG,
AP4_ATOM_TYPE_CLSF,
AP4_ATOM_TYPE_KYWD,
@@ -314,32 +309,29 @@ const AP4_Atom::Type AP4_MetaDataAtomTypeHandler::_3gppOtherTypes[] =
AP4_ATOM_TYPE_ALBM,
AP4_ATOM_TYPE_YRRC,
};
-const AP4_MetaDataAtomTypeHandler::TypeList AP4_MetaDataAtomTypeHandler::_3gppOtherTypeList =
-{
+const AP4_MetaDataAtomTypeHandler::TypeList AP4_MetaDataAtomTypeHandler::_3gppOtherTypeList = {
_3gppOtherTypes,
- sizeof(_3gppOtherTypes) / sizeof(_3gppOtherTypes[0])
+ sizeof(_3gppOtherTypes)/sizeof(_3gppOtherTypes[0])
};
/*----------------------------------------------------------------------
| DCF string atoms
+---------------------------------------------------------------------*/
-const AP4_Atom::Type AP4_MetaDataAtomTypeHandler::DcfStringTypes[] =
-{
+const AP4_Atom::Type AP4_MetaDataAtomTypeHandler::DcfStringTypes[] = {
AP4_ATOM_TYPE_ICNU,
AP4_ATOM_TYPE_INFU,
AP4_ATOM_TYPE_CVRU,
AP4_ATOM_TYPE_LRCU
};
-const AP4_MetaDataAtomTypeHandler::TypeList AP4_MetaDataAtomTypeHandler::DcfStringTypeList =
-{
+const AP4_MetaDataAtomTypeHandler::TypeList AP4_MetaDataAtomTypeHandler::DcfStringTypeList = {
DcfStringTypes,
- sizeof(DcfStringTypes) / sizeof(DcfStringTypes[0])
+ sizeof(DcfStringTypes)/sizeof(DcfStringTypes[0])
};
/*----------------------------------------------------------------------
| atom type lists
+---------------------------------------------------------------------*/
-const AP4_Atom::Type AP4_MetaDataAtomTypeHandler::IlstTypes[] =
+const AP4_Atom::Type AP4_MetaDataAtomTypeHandler::IlstTypes[] =
{
AP4_ATOM_TYPE_dddd,
AP4_ATOM_TYPE_cNAM,
@@ -388,16 +380,15 @@ const AP4_Atom::Type AP4_MetaDataAtomTypeHandler::IlstTypes[] =
AP4_ATOM_TYPE_SOCO,
AP4_ATOM_TYPE_SOSN
};
-const AP4_MetaDataAtomTypeHandler::TypeList AP4_MetaDataAtomTypeHandler::IlstTypeList =
-{
+const AP4_MetaDataAtomTypeHandler::TypeList AP4_MetaDataAtomTypeHandler::IlstTypeList = {
IlstTypes,
- sizeof(IlstTypes) / sizeof(IlstTypes[0])
+ sizeof(IlstTypes)/sizeof(IlstTypes[0])
};
/*----------------------------------------------------------------------
| AP4_MetaDataAtomTypeHandler::CreateAtom
+---------------------------------------------------------------------*/
-AP4_Result
+AP4_Result
AP4_MetaDataAtomTypeHandler::CreateAtom(AP4_Atom::Type type,
AP4_UI32 size,
AP4_ByteStream& stream,
@@ -406,46 +397,31 @@ AP4_MetaDataAtomTypeHandler::CreateAtom(AP4_Atom::Type type,
{
atom = NULL;
- if(context == AP4_ATOM_TYPE_ILST)
- {
- if(IsTypeInList(type, IlstTypeList))
- {
+ if (context == AP4_ATOM_TYPE_ILST) {
+ if (IsTypeInList(type, IlstTypeList)) {
m_AtomFactory->PushContext(type);
atom = AP4_ContainerAtom::Create(type, size, false, false, stream, *m_AtomFactory);
m_AtomFactory->PopContext();
}
- }
- else if(type == AP4_ATOM_TYPE_DATA)
- {
- if(IsTypeInList(context, IlstTypeList))
- {
+ } else if (type == AP4_ATOM_TYPE_DATA) {
+ if (IsTypeInList(context, IlstTypeList)) {
atom = new AP4_DataAtom(size, stream);
}
- }
- else if(context == AP4_ATOM_TYPE_dddd)
- {
- if(type == AP4_ATOM_TYPE_MEAN || type == AP4_ATOM_TYPE_NAME)
- {
+ } else if (context == AP4_ATOM_TYPE_dddd) {
+ if (type == AP4_ATOM_TYPE_MEAN || type == AP4_ATOM_TYPE_NAME) {
atom = new AP4_MetaDataStringAtom(type, size, stream);
}
- }
- else if(context == AP4_ATOM_TYPE_UDTA)
- {
- if(IsTypeInList(type, _3gppLocalizedStringTypeList))
- {
+ } else if (context == AP4_ATOM_TYPE_UDTA) {
+ if (IsTypeInList(type, _3gppLocalizedStringTypeList)) {
atom = AP4_3GppLocalizedStringAtom::Create(type, size, stream);
- }
- else if(IsTypeInList(type, DcfStringTypeList))
- {
+ } else if (IsTypeInList(type, DcfStringTypeList)) {
atom = AP4_DcfStringAtom::Create(type, size, stream);
- }
- else if(type == AP4_ATOM_TYPE_DCFD)
- {
+ } else if (type == AP4_ATOM_TYPE_DCFD) {
atom = AP4_DcfdAtom::Create(size, stream);
}
}
- return atom ? AP4_SUCCESS : AP4_FAILURE;
+ return atom?AP4_SUCCESS:AP4_FAILURE;
}
/*----------------------------------------------------------------------
@@ -454,9 +430,8 @@ AP4_MetaDataAtomTypeHandler::CreateAtom(AP4_Atom::Type type,
bool
AP4_MetaDataAtomTypeHandler::IsTypeInList(AP4_Atom::Type type, const AP4_MetaDataAtomTypeHandler::TypeList& list)
{
- for(unsigned int i = 0; i < list.m_Size; i++)
- {
- if(type == list.m_Types[i]) return true;
+ for (unsigned int i=0; i<list.m_Size; i++) {
+ if (type == list.m_Types[i]) return true;
}
return false;
}
@@ -470,37 +445,30 @@ AP4_MetaData::AP4_MetaData(AP4_File* file)
AP4_Movie* movie = file->GetMovie();
// handle the movie's metadata if there is a movie in the file
- if(movie)
- {
+ if (movie) {
AP4_MoovAtom* moov = movie->GetMoovAtom();
- if(moov == NULL) return;
+ if (moov == NULL) return;
ParseMoov(moov);
- }
- else
- {
+ } else {
// if we don't have a movie, try to show metadata from a udta atom
AP4_List<AP4_Atom>& top_level_atoms = file->GetTopLevelAtoms();
-
+
AP4_List<AP4_Atom>::Item* atom_item = top_level_atoms.FirstItem();
- while(atom_item)
- {
+ while (atom_item) {
AP4_ContainerAtom* container = AP4_DYNAMIC_CAST(AP4_ContainerAtom, atom_item->GetData());
- if(container)
- {
+ if (container) {
// look for a udta in a DCF layout
AP4_Atom* udta = container->FindChild("odhe/udta");
- if(udta)
- {
+ if (udta) {
AP4_ContainerAtom* udta_container = AP4_DYNAMIC_CAST(AP4_ContainerAtom, udta);
- if(udta_container)
- {
+ if (udta_container) {
ParseUdta(udta_container, "dcf");
}
}
}
atom_item = atom_item->GetNext();
}
- }
+ }
}
/*----------------------------------------------------------------------
@@ -511,23 +479,21 @@ AP4_MetaData::ParseMoov(AP4_MoovAtom* moov)
{
// look for a 'meta' atom with 'hdlr' type 'mdir'
AP4_HdlrAtom* hdlr = AP4_DYNAMIC_CAST(AP4_HdlrAtom, moov->FindChild("udta/meta/hdlr"));
- if(hdlr == NULL || hdlr->GetHandlerType() != AP4_HANDLER_TYPE_MDIR) return AP4_ERROR_NO_SUCH_ITEM;
+ if (hdlr == NULL || hdlr->GetHandlerType() != AP4_HANDLER_TYPE_MDIR) return AP4_ERROR_NO_SUCH_ITEM;
// get the list of entries
AP4_ContainerAtom* ilst = AP4_DYNAMIC_CAST(AP4_ContainerAtom, moov->FindChild("udta/meta/ilst"));
- if(ilst == NULL) return AP4_ERROR_NO_SUCH_ITEM;
-
+ if (ilst == NULL) return AP4_ERROR_NO_SUCH_ITEM;
+
AP4_List<AP4_Atom>::Item* ilst_item = ilst->GetChildren().FirstItem();
- while(ilst_item)
- {
- AP4_ContainerAtom* entry_atom = AP4_DYNAMIC_CAST(AP4_ContainerAtom, ilst_item->GetData());
- if(entry_atom)
- {
+ while (ilst_item) {
+ AP4_ContainerAtom* entry_atom = AP4_DYNAMIC_CAST(AP4_ContainerAtom, ilst_item->GetData());
+ if (entry_atom) {
AddIlstEntries(entry_atom, "meta");
}
ilst_item = ilst_item->GetNext();
}
-
+
return AP4_SUCCESS;
}
@@ -538,35 +504,30 @@ AP4_Result
AP4_MetaData::ParseUdta(AP4_ContainerAtom* udta, const char* namespc)
{
// check that the atom is indeed a 'udta' atom
- if(udta->GetType() != AP4_ATOM_TYPE_UDTA)
- {
+ if (udta->GetType() != AP4_ATOM_TYPE_UDTA) {
return AP4_ERROR_INVALID_PARAMETERS;
}
-
+
AP4_List<AP4_Atom>::Item* udta_item = udta->GetChildren().FirstItem();
- for(; udta_item; udta_item = udta_item->GetNext())
- {
- AP4_3GppLocalizedStringAtom* _3gpp_atom = AP4_DYNAMIC_CAST(AP4_3GppLocalizedStringAtom, udta_item->GetData());
- if(_3gpp_atom)
- {
+ for (; udta_item; udta_item = udta_item->GetNext()) {
+ AP4_3GppLocalizedStringAtom* _3gpp_atom = AP4_DYNAMIC_CAST(AP4_3GppLocalizedStringAtom, udta_item->GetData());
+ if (_3gpp_atom) {
Add3GppEntry(_3gpp_atom, namespc);
continue;
- }
-
+ }
+
AP4_DcfStringAtom* dcfs_atom = AP4_DYNAMIC_CAST(AP4_DcfStringAtom, udta_item->GetData());
- if(dcfs_atom)
- {
+ if (dcfs_atom) {
AddDcfStringEntry(dcfs_atom, namespc);
continue;
- }
+ }
AP4_DcfdAtom* dcfd_atom = AP4_DYNAMIC_CAST(AP4_DcfdAtom, udta_item->GetData());
- if(dcfd_atom)
- {
+ if (dcfd_atom) {
AddDcfdEntry(dcfd_atom, namespc);
}
}
-
+
return AP4_SUCCESS;
}
@@ -588,24 +549,21 @@ AP4_MetaData::ResolveKeyName(AP4_Atom::Type atom_type, AP4_String& value)
char four_cc[5];
// look for a match in the key infos
- for(unsigned int i = 0;
- i < sizeof(AP4_MetaData_KeyInfos) / sizeof(AP4_MetaData_KeyInfos[0]);
- i++)
- {
- if(AP4_MetaData_KeyInfos[i].four_cc == atom_type)
- {
+ for (unsigned int i=0;
+ i<sizeof(AP4_MetaData_KeyInfos)/sizeof(AP4_MetaData_KeyInfos[0]);
+ i++) {
+ if (AP4_MetaData_KeyInfos[i].four_cc == atom_type) {
key_name = AP4_MetaData_KeyInfos[i].name;
break;
}
}
- if(key_name == NULL)
- {
+ if (key_name == NULL) {
// this key was not found in the key infos, create a name for it
AP4_FormatFourChars(four_cc, (AP4_UI32)atom_type);
key_name = four_cc;
}
value = key_name;
-
+
return AP4_SUCCESS;
}
@@ -617,27 +575,24 @@ AP4_MetaData::AddIlstEntries(AP4_ContainerAtom* atom, const char* namespc)
{
AP4_MetaData::Value* value = NULL;
- if(atom->GetType() == AP4_ATOM_TYPE_dddd)
- {
+ if (atom->GetType() == AP4_ATOM_TYPE_dddd) {
// look for the namespace
AP4_MetaDataStringAtom* mean = static_cast<AP4_MetaDataStringAtom*>(atom->GetChild(AP4_ATOM_TYPE_MEAN));
- if(mean == NULL) return AP4_ERROR_INVALID_FORMAT;
+ if (mean == NULL) return AP4_ERROR_INVALID_FORMAT;
// look for the name
AP4_MetaDataStringAtom* name = static_cast<AP4_MetaDataStringAtom*>(atom->GetChild(AP4_ATOM_TYPE_NAME));
- if(name == NULL) return AP4_ERROR_INVALID_FORMAT;
+ if (name == NULL) return AP4_ERROR_INVALID_FORMAT;
// get the value
AP4_DataAtom* data_atom = static_cast<AP4_DataAtom*>(atom->GetChild(AP4_ATOM_TYPE_DATA));
value = new AP4_AtomMetaDataValue(data_atom, atom->GetType());
- if(value == NULL) return AP4_ERROR_INVALID_FORMAT;
-
+ if (value == NULL) return AP4_ERROR_INVALID_FORMAT;
+
return m_Entries.Add(new Entry(name->GetValue().GetChars(),
mean->GetValue().GetChars(),
value));
- }
- else
- {
+ } else {
const char* key_name = NULL;
char four_cc[5];
@@ -647,11 +602,9 @@ AP4_MetaData::AddIlstEntries(AP4_ContainerAtom* atom, const char* namespc)
// add one entry for each data atom
AP4_List<AP4_Atom>::Item* data_item = atom->GetChildren().FirstItem();
- while(data_item)
- {
+ while (data_item) {
AP4_Atom* item_atom = data_item->GetData();
- if(item_atom->GetType() == AP4_ATOM_TYPE_DATA)
- {
+ if (item_atom->GetType() == AP4_ATOM_TYPE_DATA) {
AP4_DataAtom* data_atom = static_cast<AP4_DataAtom*>(item_atom);
value = new AP4_AtomMetaDataValue(data_atom, atom->GetType());
m_Entries.Add(new Entry(key_name, namespc, value));
@@ -671,16 +624,15 @@ AP4_MetaData::Add3GppEntry(AP4_3GppLocalizedStringAtom* atom, const char* namesp
{
AP4_String key_name;
ResolveKeyName(atom->GetType(), key_name);
-
+
const char* language = NULL;
- if(atom->GetLanguage()[0])
- {
+ if (atom->GetLanguage()[0]) {
language = atom->GetLanguage();
}
AP4_MetaData::Value* value = new AP4_StringMetaDataValue(atom->GetValue().GetChars(),
- language);
+ language);
m_Entries.Add(new Entry(key_name.GetChars(), namespc, value));
-
+
return AP4_SUCCESS;
}
@@ -692,10 +644,10 @@ AP4_MetaData::AddDcfStringEntry(AP4_DcfStringAtom* atom, const char* namespc)
{
AP4_String key_name;
ResolveKeyName(atom->GetType(), key_name);
-
+
AP4_MetaData::Value* value = new AP4_StringMetaDataValue(atom->GetValue().GetChars());
m_Entries.Add(new Entry(key_name.GetChars(), namespc, value));
-
+
return AP4_SUCCESS;
}
@@ -707,45 +659,44 @@ AP4_MetaData::AddDcfdEntry(AP4_DcfdAtom* atom, const char* namespc)
{
AP4_String key_name;
ResolveKeyName(atom->GetType(), key_name);
-
- AP4_MetaData::Value* value = new AP4_IntegerMetaDataValue(AP4_MetaData::Value::TYPE_INT_32_BE,
- atom->GetDuration());
+
+ AP4_MetaData::Value* value = new AP4_IntegerMetaDataValue(AP4_MetaData::Value::TYPE_INT_32_BE,
+ atom->GetDuration());
m_Entries.Add(new Entry(key_name.GetChars(), namespc, value));
-
+
return AP4_SUCCESS;
}
/*----------------------------------------------------------------------
| AP4_MetaData::Value::MapDataTypeToCategory
+---------------------------------------------------------------------*/
-AP4_MetaData::Value::TypeCategory
+AP4_MetaData::Value::TypeCategory
AP4_MetaData::Value::MapTypeToCategory(Type type)
{
- switch(type)
- {
- case AP4_MetaData::Value::TYPE_INT_08_BE:
- case AP4_MetaData::Value::TYPE_INT_16_BE:
- case AP4_MetaData::Value::TYPE_INT_32_BE:
- return AP4_MetaData::Value::TYPE_CATEGORY_INTEGER;
-
- case AP4_MetaData::Value::TYPE_STRING_UTF_8:
- case AP4_MetaData::Value::TYPE_STRING_UTF_16:
- case AP4_MetaData::Value::TYPE_STRING_PASCAL:
- return AP4_MetaData::Value::TYPE_CATEGORY_STRING;
-
- case AP4_MetaData::Value::TYPE_FLOAT_32_BE:
- case AP4_MetaData::Value::TYPE_FLOAT_64_BE:
- return AP4_MetaData::Value::TYPE_CATEGORY_FLOAT;
-
- default:
- return AP4_MetaData::Value::TYPE_CATEGORY_BINARY;
+ switch (type) {
+ case AP4_MetaData::Value::TYPE_INT_08_BE:
+ case AP4_MetaData::Value::TYPE_INT_16_BE:
+ case AP4_MetaData::Value::TYPE_INT_32_BE:
+ return AP4_MetaData::Value::TYPE_CATEGORY_INTEGER;
+
+ case AP4_MetaData::Value::TYPE_STRING_UTF_8:
+ case AP4_MetaData::Value::TYPE_STRING_UTF_16:
+ case AP4_MetaData::Value::TYPE_STRING_PASCAL:
+ return AP4_MetaData::Value::TYPE_CATEGORY_STRING;
+
+ case AP4_MetaData::Value::TYPE_FLOAT_32_BE:
+ case AP4_MetaData::Value::TYPE_FLOAT_64_BE:
+ return AP4_MetaData::Value::TYPE_CATEGORY_FLOAT;
+
+ default:
+ return AP4_MetaData::Value::TYPE_CATEGORY_BINARY;
}
}
/*----------------------------------------------------------------------
| AP4_MetaData::Value::GetTypeCategory
+---------------------------------------------------------------------*/
-AP4_MetaData::Value::TypeCategory
+AP4_MetaData::Value::TypeCategory
AP4_MetaData::Value::GetTypeCategory() const
{
return MapTypeToCategory(m_Type);
@@ -758,89 +709,75 @@ AP4_Result
AP4_MetaData::Entry::ToAtom(AP4_Atom*& atom) const
{
atom = NULL;
-
- if(m_Value == NULL)
- {
+
+ if (m_Value == NULL) {
return AP4_ERROR_INVALID_PARAMETERS;
}
-
- if(m_Key.GetNamespace() == "meta")
- {
+
+ if (m_Key.GetNamespace() == "meta") {
// convert the name into an atom type
- if(m_Key.GetName().GetLength() != 4)
- {
+ if (m_Key.GetName().GetLength() != 4) {
// the name is not in the right format
return AP4_ERROR_INVALID_PARAMETERS;
}
- AP4_Atom::Type atom_type = AP4_Atom::TypeFromString(m_Key.GetName().GetChars());
-
+ AP4_Atom::Type atom_type = AP4_Atom::TypeFromString(m_Key.GetName().GetChars());
+
// create a container atom for the data
AP4_ContainerAtom* container = new AP4_ContainerAtom(atom_type);
// add the data atom
AP4_DataAtom* data = new AP4_DataAtom(*m_Value);
container->AddChild(data);
-
+
atom = container;
return AP4_SUCCESS;
- }
- else if(m_Key.GetNamespace() == "dcf")
- {
+ } else if (m_Key.GetNamespace() == "dcf") {
// convert the name into an atom type
- if(m_Key.GetName().GetLength() != 4)
- {
+ if (m_Key.GetName().GetLength() != 4) {
// the name is not in the right format
return AP4_ERROR_INVALID_PARAMETERS;
}
- AP4_Atom::Type atom_type = AP4_Atom::TypeFromString(m_Key.GetName().GetChars());
+ AP4_Atom::Type atom_type = AP4_Atom::TypeFromString(m_Key.GetName().GetChars());
- if(AP4_MetaDataAtomTypeHandler::IsTypeInList(atom_type,
- AP4_MetaDataAtomTypeHandler::DcfStringTypeList))
- {
+ if (AP4_MetaDataAtomTypeHandler::IsTypeInList(atom_type,
+ AP4_MetaDataAtomTypeHandler::DcfStringTypeList)) {
AP4_String atom_value = m_Value->ToString();
atom = new AP4_DcfStringAtom(atom_type, atom_value.GetChars());
return AP4_SUCCESS;
- }
- else if(AP4_MetaDataAtomTypeHandler::IsTypeInList(atom_type,
- AP4_MetaDataAtomTypeHandler::_3gppLocalizedStringTypeList))
- {
+ } else if (AP4_MetaDataAtomTypeHandler::IsTypeInList(atom_type,
+ AP4_MetaDataAtomTypeHandler::_3gppLocalizedStringTypeList)) {
AP4_String atom_value = m_Value->ToString();
const char* language = "eng"; // default
- if(m_Value->GetLanguage().GetLength() != 0)
- {
+ if (m_Value->GetLanguage().GetLength() != 0) {
language = m_Value->GetLanguage().GetChars();
}
atom = new AP4_3GppLocalizedStringAtom(atom_type, language, atom_value.GetChars());
return AP4_SUCCESS;
- }
- else if(atom_type == AP4_ATOM_TYPE_DCFD)
- {
+ } else if (atom_type == AP4_ATOM_TYPE_DCFD) {
atom = new AP4_DcfdAtom(m_Value->ToInteger());
return AP4_SUCCESS;
}
-
- // not supported
- return AP4_ERROR_NOT_SUPPORTED;
- }
- else
- {
+
+ // not supported
+ return AP4_ERROR_NOT_SUPPORTED;
+ } else {
// create a '----' atom
AP4_ContainerAtom* container = new AP4_ContainerAtom(AP4_ATOM_TYPE_dddd);
-
+
// add a 'mean' string
container->AddChild(new AP4_MetaDataStringAtom(AP4_ATOM_TYPE_MEAN, m_Key.GetNamespace().GetChars()));
-
+
// add a 'name' string
container->AddChild(new AP4_MetaDataStringAtom(AP4_ATOM_TYPE_NAME, m_Key.GetName().GetChars()));
// add the data atom
AP4_DataAtom* data = new AP4_DataAtom(*m_Value);
container->AddChild(data);
-
+
atom = container;
return AP4_SUCCESS;
}
-
+
return AP4_ERROR_NOT_SUPPORTED;
}
@@ -850,36 +787,30 @@ AP4_MetaData::Entry::ToAtom(AP4_Atom*& atom) const
AP4_ContainerAtom*
AP4_MetaData::Entry::FindInIlst(AP4_ContainerAtom* ilst) const
{
- if(m_Key.GetNamespace() == "meta")
- {
+ if (m_Key.GetNamespace() == "meta") {
AP4_Atom::Type atom_type = AP4_Atom::TypeFromString(m_Key.GetName().GetChars());
return AP4_DYNAMIC_CAST(AP4_ContainerAtom, ilst->GetChild(atom_type));
- }
- else
- {
+ } else {
AP4_List<AP4_Atom>::Item* ilst_item = ilst->GetChildren().FirstItem();
- while(ilst_item)
- {
- AP4_ContainerAtom* entry_atom = AP4_DYNAMIC_CAST(AP4_ContainerAtom, ilst_item->GetData());
- if(entry_atom)
- {
+ while (ilst_item) {
+ AP4_ContainerAtom* entry_atom = AP4_DYNAMIC_CAST(AP4_ContainerAtom, ilst_item->GetData());
+ if (entry_atom) {
AP4_MetaDataStringAtom* mean = static_cast<AP4_MetaDataStringAtom*>(entry_atom->GetChild(AP4_ATOM_TYPE_MEAN));
AP4_MetaDataStringAtom* name = static_cast<AP4_MetaDataStringAtom*>(entry_atom->GetChild(AP4_ATOM_TYPE_NAME));
- if(mean && name &&
- mean->GetValue() == m_Key.GetNamespace() &&
- name->GetValue() == m_Key.GetName())
- {
+ if (mean && name &&
+ mean->GetValue() == m_Key.GetNamespace() &&
+ name->GetValue() == m_Key.GetName()) {
return entry_atom;
}
}
ilst_item = ilst_item->GetNext();
}
}
-
+
// not found
return NULL;
}
-
+
/*----------------------------------------------------------------------
| AP4_MetaData::Entry::AddToFileIlst
+---------------------------------------------------------------------*/
@@ -887,69 +818,61 @@ AP4_Result
AP4_MetaData::Entry::AddToFileIlst(AP4_File& file, AP4_Ordinal index)
{
// check that we have a correct entry
- if(m_Value == NULL) return AP4_ERROR_INVALID_STATE;
+ if (m_Value == NULL) return AP4_ERROR_INVALID_STATE;
// convert the entry into an atom
AP4_Atom* atom;
AP4_Result result = ToAtom(atom);
- if(AP4_FAILED(result)) return result;
+ if (AP4_FAILED(result)) return result;
AP4_ContainerAtom* entry_atom = AP4_DYNAMIC_CAST(AP4_ContainerAtom, atom);
- if(entry_atom == NULL)
- {
+ if (entry_atom == NULL) {
return AP4_ERROR_INVALID_FORMAT;
}
// look for the 'moov'
AP4_Movie* movie = file.GetMovie();
- if(movie == NULL) return AP4_ERROR_INVALID_FORMAT;
+ if (movie == NULL) return AP4_ERROR_INVALID_FORMAT;
AP4_MoovAtom* moov = movie->GetMoovAtom();
- if(moov == NULL) return AP4_ERROR_INVALID_FORMAT;
-
- // look for 'udta', and create if it does not exist
+ if (moov == NULL) return AP4_ERROR_INVALID_FORMAT;
+
+ // look for 'udta', and create if it does not exist
AP4_ContainerAtom* udta = AP4_DYNAMIC_CAST(AP4_ContainerAtom, moov->FindChild("udta", true));
- if(udta == NULL) return AP4_ERROR_INTERNAL;
-
+ if (udta == NULL) return AP4_ERROR_INTERNAL;
+
// look for 'meta', and create if it does not exist ('meta' is a FULL atom)
AP4_ContainerAtom* meta = AP4_DYNAMIC_CAST(AP4_ContainerAtom, udta->FindChild("meta", true, true));
- if(meta == NULL) return AP4_ERROR_INTERNAL;
+ if (meta == NULL) return AP4_ERROR_INTERNAL;
// look for a 'hdlr' atom type 'mdir'
AP4_HdlrAtom* hdlr = AP4_DYNAMIC_CAST(AP4_HdlrAtom, meta->FindChild("hdlr"));
- if(hdlr == NULL)
- {
+ if (hdlr == NULL) {
hdlr = new AP4_HdlrAtom(AP4_HANDLER_TYPE_MDIR, "");
meta->AddChild(hdlr);
- }
- else
- {
- if(hdlr->GetHandlerType() != AP4_HANDLER_TYPE_MDIR)
- {
+ } else {
+ if (hdlr->GetHandlerType() != AP4_HANDLER_TYPE_MDIR) {
return AP4_ERROR_INVALID_FORMAT;
}
}
// get/create the list of entries
AP4_ContainerAtom* ilst = AP4_DYNAMIC_CAST(AP4_ContainerAtom, meta->FindChild("ilst", true));
- if(ilst == NULL) return AP4_ERROR_INTERNAL;
-
+ if (ilst == NULL) return AP4_ERROR_INTERNAL;
+
// look if there is already a container for this entry
AP4_ContainerAtom* existing = FindInIlst(ilst);
- if(existing == NULL)
- {
+ if (existing == NULL) {
// just add the one we have
ilst->AddChild(entry_atom);
- }
- else
- {
+ } else {
// add the entry's data to the existing entry
AP4_DataAtom* data_atom = AP4_DYNAMIC_CAST(AP4_DataAtom, entry_atom->GetChild(AP4_ATOM_TYPE_DATA));
- if(data_atom == NULL) return AP4_ERROR_INTERNAL;
+ if (data_atom == NULL) return AP4_ERROR_INTERNAL;
entry_atom->RemoveChild(data_atom);
existing->AddChild(data_atom, index);
delete entry_atom;
}
-
- return AP4_SUCCESS;
+
+ return AP4_SUCCESS;
}
/*----------------------------------------------------------------------
@@ -959,20 +882,20 @@ AP4_Result
AP4_MetaData::Entry::AddToFileDcf(AP4_File& file, AP4_Ordinal index)
{
// check that we have a correct entry
- if(m_Value == NULL) return AP4_ERROR_INVALID_STATE;
-
+ if (m_Value == NULL) return AP4_ERROR_INVALID_STATE;
+
// look for 'odrm/odhe'
AP4_ContainerAtom* odhe = AP4_DYNAMIC_CAST(AP4_ContainerAtom, file.FindChild("odrm/odhe"));
- if(odhe == NULL) return AP4_ERROR_NO_SUCH_ITEM;
+ if (odhe == NULL) return AP4_ERROR_NO_SUCH_ITEM;
// get/create the list of entries
AP4_ContainerAtom* udta = AP4_DYNAMIC_CAST(AP4_ContainerAtom, odhe->FindChild("udta", true));
- if(udta == NULL) return AP4_ERROR_INTERNAL;
-
+ if (udta == NULL) return AP4_ERROR_INTERNAL;
+
// convert the entry into an atom
AP4_Atom* data_atom;
AP4_Result result = ToAtom(data_atom);
- if(AP4_FAILED(result)) return result;
+ if (AP4_FAILED(result)) return result;
// add the entry's data to the container
return udta->AddChild(data_atom, index);
@@ -985,19 +908,14 @@ AP4_Result
AP4_MetaData::Entry::AddToFile(AP4_File& file, AP4_Ordinal index)
{
// check that we have a correct entry
- if(m_Value == NULL) return AP4_ERROR_INVALID_STATE;
-
+ if (m_Value == NULL) return AP4_ERROR_INVALID_STATE;
+
// check the namespace of the key to know where to add the atom
- if(m_Key.GetNamespace() == "meta")
- {
+ if (m_Key.GetNamespace() == "meta") {
return AddToFileIlst(file, index);
- }
- else if(m_Key.GetNamespace() == "dcf")
- {
+ } else if (m_Key.GetNamespace() == "dcf") {
return AddToFileDcf(file, index);
- }
- else
- {
+ } else {
// custom namespace
return AddToFileIlst(file, index);
}
@@ -1011,29 +929,28 @@ AP4_MetaData::Entry::RemoveFromFileIlst(AP4_File& file, AP4_Ordinal index)
{
// look for the 'moov'
AP4_Movie* movie = file.GetMovie();
- if(movie == NULL) return AP4_ERROR_INVALID_FORMAT;
+ if (movie == NULL) return AP4_ERROR_INVALID_FORMAT;
AP4_MoovAtom* moov = movie->GetMoovAtom();
- if(moov == NULL) return AP4_ERROR_INVALID_FORMAT;
-
+ if (moov == NULL) return AP4_ERROR_INVALID_FORMAT;
+
// look for 'udta/meta/ilst'
AP4_ContainerAtom* ilst = AP4_DYNAMIC_CAST(AP4_ContainerAtom, moov->FindChild("udta/meta/ilst"));
- if(ilst == NULL) return AP4_ERROR_NO_SUCH_ITEM;
-
+ if (ilst == NULL) return AP4_ERROR_NO_SUCH_ITEM;
+
// look if there is already a container for this entry
AP4_ContainerAtom* existing = FindInIlst(ilst);
- if(existing == NULL) return AP4_ERROR_NO_SUCH_ITEM;
-
+ if (existing == NULL) return AP4_ERROR_NO_SUCH_ITEM;
+
// remove the data atom in the entry
AP4_Result result = existing->DeleteChild(AP4_ATOM_TYPE_DATA, index);
- if(AP4_FAILED(result)) return result;
-
+ if (AP4_FAILED(result)) return result;
+
// if the entry is empty, remove it
- if(existing->GetChildren().ItemCount() == 0)
- {
+ if (existing->GetChildren().ItemCount() == 0) {
ilst->RemoveChild(existing);
delete existing;
}
-
+
return AP4_SUCCESS;
}
@@ -1045,13 +962,13 @@ AP4_MetaData::Entry::RemoveFromFileDcf(AP4_File& file, AP4_Ordinal index)
{
// look for 'odrm/odhe/udta'
AP4_ContainerAtom* udta = AP4_DYNAMIC_CAST(AP4_ContainerAtom, file.FindChild("odrm/odhe/udta"));
- if(udta == NULL) return AP4_ERROR_NO_SUCH_ITEM;
-
+ if (udta == NULL) return AP4_ERROR_NO_SUCH_ITEM;
+
// remove the data atom in the entry
AP4_UI32 type = AP4_BytesToUInt32BE((const unsigned char*)m_Key.GetName().GetChars());
AP4_Result result = udta->DeleteChild(type, index);
- if(AP4_FAILED(result)) return result;
-
+ if (AP4_FAILED(result)) return result;
+
return AP4_SUCCESS;
}
@@ -1062,16 +979,11 @@ AP4_Result
AP4_MetaData::Entry::RemoveFromFile(AP4_File& file, AP4_Ordinal index)
{
// check the namespace of the key to know where to add the atom
- if(m_Key.GetNamespace() == "meta")
- {
+ if (m_Key.GetNamespace() == "meta") {
return RemoveFromFileIlst(file, index);
- }
- else if(m_Key.GetNamespace() == "dcf")
- {
+ } else if (m_Key.GetNamespace() == "dcf") {
return RemoveFromFileDcf(file, index);
- }
- else
- {
+ } else {
// unsupported namespace
return AP4_ERROR_NOT_SUPPORTED;
}
@@ -1166,151 +1078,121 @@ AP4_BinaryMetaDataValue::ToInteger() const
| AP4_AtomMetaDataValue::AP4_AtomMetaDataValue
+---------------------------------------------------------------------*/
AP4_AtomMetaDataValue::AP4_AtomMetaDataValue(AP4_DataAtom* atom,
- AP4_UI32 parent_type) :
+ AP4_UI32 parent_type) :
Value(atom->GetValueType()),
m_DataAtom(atom)
{
- switch(parent_type)
- {
- case AP4_ATOM_TYPE_GNRE:
- m_Meaning = MEANING_ID3_GENRE;
- break;
-
- case AP4_ATOM_TYPE_CPIL:
- m_Meaning = MEANING_BOOLEAN;
- break;
+ switch (parent_type) {
+ case AP4_ATOM_TYPE_GNRE:
+ m_Meaning = MEANING_ID3_GENRE;
+ break;
- case AP4_ATOM_TYPE_PGAP:
- case AP4_ATOM_TYPE_PCST:
- m_Meaning = MEANING_BOOLEAN;
- break;
+ case AP4_ATOM_TYPE_CPIL:
+ m_Meaning = MEANING_BOOLEAN;
+ break;
- case AP4_ATOM_TYPE_STIK:
- m_Meaning = MEANING_FILE_KIND;
- break;
+ case AP4_ATOM_TYPE_PGAP:
+ case AP4_ATOM_TYPE_PCST:
+ m_Meaning = MEANING_BOOLEAN;
+ break;
- case AP4_ATOM_TYPE_PURL:
- case AP4_ATOM_TYPE_EGID:
- m_Meaning = MEANING_BINARY_ENCODED_CHARS;
- break;
+ case AP4_ATOM_TYPE_STIK:
+ m_Meaning = MEANING_FILE_KIND;
+ break;
- default:
- break;
+ case AP4_ATOM_TYPE_PURL:
+ case AP4_ATOM_TYPE_EGID:
+ m_Meaning = MEANING_BINARY_ENCODED_CHARS;
+ break;
+
+ default:
+ break;
}
}
/*----------------------------------------------------------------------
| AP4_AtomMetaDataValue::ToString
+---------------------------------------------------------------------*/
-AP4_String
+AP4_String
AP4_AtomMetaDataValue::ToString() const
{
char string[256] = "";
AP4_MetaData::Value::Type value_type = m_DataAtom->GetValueType();
- switch(AP4_MetaData::Value::MapTypeToCategory(value_type))
- {
- case AP4_MetaData::Value::TYPE_CATEGORY_INTEGER:
- {
- long value;
- if(AP4_SUCCEEDED(m_DataAtom->LoadInteger(value)))
- {
- if(m_Meaning == MEANING_BOOLEAN)
- {
- if(value)
- {
- return "True";
- }
- else
- {
- return "False";
- }
- }
- else if(m_Meaning == MEANING_FILE_KIND)
+ switch (AP4_MetaData::Value::MapTypeToCategory(value_type)) {
+ case AP4_MetaData::Value::TYPE_CATEGORY_INTEGER:
{
- if(value >= 0 && ((unsigned int)value) <= sizeof(Ap4StikNames) / sizeof(Ap4StikNames[0]))
- {
- AP4_FormatString(string, sizeof(string), "(%ld) %s", value, Ap4StikNames[value]);
- }
- else
- {
- return "Unknown";
+ long value;
+ if (AP4_SUCCEEDED(m_DataAtom->LoadInteger(value))) {
+ if (m_Meaning == MEANING_BOOLEAN) {
+ if (value) {
+ return "True";
+ } else {
+ return "False";
+ }
+ } else if (m_Meaning == MEANING_FILE_KIND) {
+ if (value >= 0 && ((unsigned int)value) <= sizeof(Ap4StikNames)/sizeof(Ap4StikNames[0])) {
+ AP4_FormatString(string, sizeof(string), "(%ld) %s", value, Ap4StikNames[value]);
+ } else {
+ return "Unknown";
+ }
+ } else {
+ AP4_FormatString(string, sizeof(string), "%ld", value);
+ }
}
+ return AP4_String((const char*)string);
+ break;
}
- else
- {
- AP4_FormatString(string, sizeof(string), "%ld", value);
- }
- }
- return AP4_String((const char*)string);
- break;
- }
-
- case AP4_MetaData::Value::TYPE_CATEGORY_STRING:
- {
- AP4_String* category_string;
- if(AP4_SUCCEEDED(m_DataAtom->LoadString(category_string)))
- {
- AP4_String result(*category_string);
- delete category_string;
- return result;
- }
- break;
- }
- case AP4_MetaData::Value::TYPE_CATEGORY_BINARY:
- {
- AP4_DataBuffer data;
- if(AP4_SUCCEEDED(m_DataAtom->LoadBytes(data)))
- {
- if(m_Meaning == MEANING_ID3_GENRE && data.GetDataSize() == 2)
+ case AP4_MetaData::Value::TYPE_CATEGORY_STRING:
{
- unsigned int genre = (data.GetData()[0]) * 256 + data.GetData()[1];
- if(genre >= 1 && genre <= sizeof(Ap4Id3Genres) / sizeof(Ap4Id3Genres[0]))
- {
- AP4_FormatString(string, sizeof(string), "(%d) %s", genre, Ap4Id3Genres[genre-1]);
- return AP4_String((const char*)string);
- }
- else
- {
- return "Unknown";
+ AP4_String* category_string;
+ if (AP4_SUCCEEDED(m_DataAtom->LoadString(category_string))) {
+ AP4_String result(*category_string);
+ delete category_string;
+ return result;
}
+ break;
}
- else if(m_Meaning == MEANING_BINARY_ENCODED_CHARS)
- {
- AP4_String result;
- result.Assign((const char*)data.GetData(), data.GetDataSize());
- return result;
- }
- else
+
+ case AP4_MetaData::Value::TYPE_CATEGORY_BINARY:
{
- unsigned int dump_length = data.GetDataSize();
- bool truncate = false;
- if(dump_length > 16)
- {
- dump_length = 16;
- truncate = true;
- }
- char* out = string;
- for(unsigned int i = 0; i < dump_length; i++)
- {
- AP4_FormatString(out, sizeof(string) - (out - string), "%02x ", data.GetData()[i]);
- out += 3;
- }
- if(truncate)
- {
- *out++ = '.';
- *out++ = '.';
- *out++ = '.';
- *out++ = ' ';
+ AP4_DataBuffer data;
+ if (AP4_SUCCEEDED(m_DataAtom->LoadBytes(data))) {
+ if (m_Meaning == MEANING_ID3_GENRE && data.GetDataSize() == 2) {
+ unsigned int genre = (data.GetData()[0])*256+data.GetData()[1];
+ if (genre >= 1 && genre <= sizeof(Ap4Id3Genres)/sizeof(Ap4Id3Genres[0])) {
+ AP4_FormatString(string, sizeof(string), "(%d) %s", genre, Ap4Id3Genres[genre-1]);
+ return AP4_String((const char*)string);
+ } else {
+ return "Unknown";
+ }
+ } else if (m_Meaning == MEANING_BINARY_ENCODED_CHARS) {
+ AP4_String result;
+ result.Assign((const char*)data.GetData(), data.GetDataSize());
+ return result;
+ } else {
+ unsigned int dump_length = data.GetDataSize();
+ bool truncate = false;
+ if (dump_length > 16) {
+ dump_length = 16;
+ truncate = true;
+ }
+ char* out = string;
+ for (unsigned int i=0; i<dump_length; i++) {
+ AP4_FormatString(out, sizeof(string)-(out-string), "%02x ", data.GetData()[i]);
+ out += 3;
+ }
+ if (truncate) {
+ *out++='.'; *out++='.'; *out++='.'; *out++=' ';
+ }
+ AP4_FormatString(out, sizeof(string)-(out-string), "[%ld bytes]", data.GetDataSize());
+ }
}
- AP4_FormatString(out, sizeof(string) - (out - string), "[%ld bytes]", data.GetDataSize());
+ return AP4_String(string);
}
- }
- return AP4_String(string);
- }
- default:
- return AP4_String();
+ default:
+ return AP4_String();
}
return AP4_String();
@@ -1328,16 +1210,13 @@ AP4_AtomMetaDataValue::ToBytes(AP4_DataBuffer& bytes) const
/*----------------------------------------------------------------------
| AP4_AtomMetaDataValue::ToInteger
+---------------------------------------------------------------------*/
-long
+long
AP4_AtomMetaDataValue::ToInteger() const
{
long value;
- if(AP4_SUCCEEDED(m_DataAtom->LoadInteger(value)))
- {
+ if (AP4_SUCCEEDED(m_DataAtom->LoadInteger(value))) {
return value;
- }
- else
- {
+ } else {
return 0;
}
}
@@ -1352,81 +1231,70 @@ AP4_DataAtom::AP4_DataAtom(const AP4_MetaData::Value& value) :
AP4_MemoryByteStream* memory = new AP4_MemoryByteStream(256);
AP4_Size payload_size = 8;
m_Source = memory;
-
- switch(value.GetType())
- {
- case AP4_MetaData::Value::TYPE_STRING_UTF_8:
- {
- m_DataType = DATA_TYPE_STRING_UTF_8;
- AP4_String string_value = value.ToString();
- if(string_value.GetLength())
- {
- memory->Write(string_value.GetChars(), string_value.GetLength());
+
+ switch (value.GetType()) {
+ case AP4_MetaData::Value::TYPE_STRING_UTF_8: {
+ m_DataType = DATA_TYPE_STRING_UTF_8;
+ AP4_String string_value = value.ToString();
+ if (string_value.GetLength()) {
+ memory->Write(string_value.GetChars(), string_value.GetLength());
+ }
+ payload_size += string_value.GetLength();
+ break;
+ }
+
+ case AP4_MetaData::Value::TYPE_INT_08_BE: {
+ m_DataType = DATA_TYPE_SIGNED_INT_BE;
+ AP4_UI08 int_value = (AP4_UI08)value.ToInteger();
+ memory->Write(&int_value, 1);
+ payload_size += 1;
+ break;
+ }
+
+ case AP4_MetaData::Value::TYPE_INT_16_BE: {
+ m_DataType = DATA_TYPE_SIGNED_INT_BE;
+ AP4_UI16 int_value = (AP4_UI16)value.ToInteger();
+ memory->Write(&int_value, 2);
+ payload_size += 2;
+ break;
}
- payload_size += string_value.GetLength();
- break;
- }
-
- case AP4_MetaData::Value::TYPE_INT_08_BE:
- {
- m_DataType = DATA_TYPE_SIGNED_INT_BE;
- AP4_UI08 int_value = (AP4_UI08)value.ToInteger();
- memory->Write(&int_value, 1);
- payload_size += 1;
- break;
- }
-
- case AP4_MetaData::Value::TYPE_INT_16_BE:
- {
- m_DataType = DATA_TYPE_SIGNED_INT_BE;
- AP4_UI16 int_value = (AP4_UI16)value.ToInteger();
- memory->Write(&int_value, 2);
- payload_size += 2;
- break;
- }
- case AP4_MetaData::Value::TYPE_INT_32_BE:
- {
- m_DataType = DATA_TYPE_SIGNED_INT_BE;
- AP4_UI32 int_value = (AP4_UI32)value.ToInteger();
- memory->Write(&int_value, 4);
- payload_size += 4;
- break;
- }
+ case AP4_MetaData::Value::TYPE_INT_32_BE: {
+ m_DataType = DATA_TYPE_SIGNED_INT_BE;
+ AP4_UI32 int_value = (AP4_UI32)value.ToInteger();
+ memory->Write(&int_value, 4);
+ payload_size += 4;
+ break;
+ }
- case AP4_MetaData::Value::TYPE_JPEG:
- m_DataType = DATA_TYPE_JPEG;
- // FALLTHROUGH
- case AP4_MetaData::Value::TYPE_GIF:
- if(m_DataType == DATA_TYPE_BINARY) m_DataType = DATA_TYPE_GIF;
- // FALLTHROUGH
- case AP4_MetaData::Value::TYPE_BINARY:
- {
- AP4_DataBuffer buffer;
- value.ToBytes(buffer);
- if(buffer.GetDataSize())
- {
- memory->Write(buffer.GetData(), buffer.GetDataSize());
+ case AP4_MetaData::Value::TYPE_JPEG:
+ m_DataType = DATA_TYPE_JPEG;
+ // FALLTHROUGH
+ case AP4_MetaData::Value::TYPE_GIF:
+ if (m_DataType == DATA_TYPE_BINARY) m_DataType = DATA_TYPE_GIF;
+ // FALLTHROUGH
+ case AP4_MetaData::Value::TYPE_BINARY: {
+ AP4_DataBuffer buffer;
+ value.ToBytes(buffer);
+ if (buffer.GetDataSize()) {
+ memory->Write(buffer.GetData(), buffer.GetDataSize());
+ }
+ payload_size += buffer.GetDataSize();
+ break;
}
- payload_size += buffer.GetDataSize();
- break;
- }
- default:
- break;
+ default:
+ break;
}
-
+
const AP4_String& language = value.GetLanguage();
- if(language == "en")
- {
+ if (language == "en") {
m_DataLang = LANGUAGE_ENGLISH;
- }
- else
- {
+ } else {
// default
m_DataLang = LANGUAGE_ENGLISH;
}
-
+
m_Size32 += payload_size;
}
@@ -1436,18 +1304,16 @@ AP4_DataAtom::AP4_DataAtom(const AP4_MetaData::Value& value) :
AP4_DataAtom::AP4_DataAtom(AP4_UI32 size, AP4_ByteStream& stream) :
AP4_Atom(AP4_ATOM_TYPE_DATA, size)
{
- if(size < AP4_ATOM_HEADER_SIZE + 8) return;
+ if (size < AP4_ATOM_HEADER_SIZE+8) return;
AP4_UI32 i;
- stream.ReadUI32(i);
- m_DataType = (DataType)i;
- stream.ReadUI32(i);
- m_DataLang = (DataLang)i;
+ stream.ReadUI32(i); m_DataType = (DataType)i;
+ stream.ReadUI32(i); m_DataLang = (DataLang)i;
// the stream for the data is a substream of this source
AP4_Position data_offset;
stream.Tell(data_offset);
- AP4_Size data_size = size - AP4_ATOM_HEADER_SIZE - 8;
+ AP4_Size data_size = size-AP4_ATOM_HEADER_SIZE-8;
m_Source = new AP4_SubStream(stream, data_offset, data_size);
}
@@ -1465,44 +1331,38 @@ AP4_DataAtom::~AP4_DataAtom()
AP4_MetaData::Value::Type
AP4_DataAtom::GetValueType()
{
- switch(m_DataType)
- {
- case DATA_TYPE_BINARY:
- return AP4_MetaData::Value::TYPE_BINARY;
-
- case DATA_TYPE_SIGNED_INT_BE:
- switch(m_Size32 - 16)
- {
- case 1:
- return AP4_MetaData::Value::TYPE_INT_08_BE;
- case 2:
- return AP4_MetaData::Value::TYPE_INT_16_BE;
- case 4:
- return AP4_MetaData::Value::TYPE_INT_32_BE;
- default:
+ switch (m_DataType) {
+ case DATA_TYPE_BINARY:
return AP4_MetaData::Value::TYPE_BINARY;
- }
- break;
-
- case DATA_TYPE_STRING_UTF_8:
- return AP4_MetaData::Value::TYPE_STRING_UTF_8;
-
- case DATA_TYPE_STRING_UTF_16:
- return AP4_MetaData::Value::TYPE_STRING_UTF_16;
-
- case DATA_TYPE_STRING_PASCAL:
- return AP4_MetaData::Value::TYPE_STRING_PASCAL;
-
- case DATA_TYPE_GIF:
- return AP4_MetaData::Value::TYPE_GIF;
- case DATA_TYPE_JPEG:
- return AP4_MetaData::Value::TYPE_JPEG;
+ case DATA_TYPE_SIGNED_INT_BE:
+ switch (m_Size32-16) {
+ case 1: return AP4_MetaData::Value::TYPE_INT_08_BE;
+ case 2: return AP4_MetaData::Value::TYPE_INT_16_BE;
+ case 4: return AP4_MetaData::Value::TYPE_INT_32_BE;
+ default: return AP4_MetaData::Value::TYPE_BINARY;
+ }
+ break;
+
+ case DATA_TYPE_STRING_UTF_8:
+ return AP4_MetaData::Value::TYPE_STRING_UTF_8;
+
+ case DATA_TYPE_STRING_UTF_16:
+ return AP4_MetaData::Value::TYPE_STRING_UTF_16;
+
+ case DATA_TYPE_STRING_PASCAL:
+ return AP4_MetaData::Value::TYPE_STRING_PASCAL;
+
+ case DATA_TYPE_GIF:
+ return AP4_MetaData::Value::TYPE_GIF;
+
+ case DATA_TYPE_JPEG:
+ return AP4_MetaData::Value::TYPE_JPEG;
- default:
- return AP4_MetaData::Value::TYPE_BINARY;
+ default:
+ return AP4_MetaData::Value::TYPE_BINARY;
}
-
+
return AP4_MetaData::Value::TYPE_BINARY;
}
@@ -1514,8 +1374,7 @@ AP4_DataAtom::WriteFields(AP4_ByteStream& stream)
{
stream.WriteUI32(m_DataType);
stream.WriteUI32(m_DataLang);
- if(m_Source)
- {
+ if (m_Source) {
AP4_LargeSize size = 0;
m_Source->GetSize(size);
m_Source->Seek(0);
@@ -1533,20 +1392,15 @@ AP4_DataAtom::InspectFields(AP4_AtomInspector& inspector)
{
inspector.AddField("type", m_DataType);
inspector.AddField("lang", m_DataLang);
- if(m_DataType == DATA_TYPE_STRING_UTF_8)
- {
+ if (m_DataType == DATA_TYPE_STRING_UTF_8) {
AP4_String* str;
- if(AP4_SUCCEEDED(LoadString(str)))
- {
+ if (AP4_SUCCEEDED(LoadString(str))) {
inspector.AddField("value", str->GetChars());
delete str;
}
- }
- else if(m_DataType == DATA_TYPE_SIGNED_INT_BE)
- {
+ } else if (m_DataType == DATA_TYPE_SIGNED_INT_BE) {
long value;
- if(AP4_SUCCEEDED(LoadInteger(value)))
- {
+ if (AP4_SUCCEEDED(LoadInteger(value))) {
inspector.AddField("value", value);
}
}
@@ -1560,24 +1414,20 @@ AP4_DataAtom::InspectFields(AP4_AtomInspector& inspector)
AP4_Result
AP4_DataAtom::LoadString(AP4_String*& string)
{
- if(m_Source == NULL)
- {
+ if (m_Source == NULL) {
string = new AP4_String();
return AP4_SUCCESS;
- }
- else
- {
+ } else {
// create a string with enough capactiy for the data
AP4_LargeSize size = 0;
m_Source->GetSize(size);
- if(size > AP4_DATA_ATOM_MAX_SIZE) return AP4_ERROR_OUT_OF_RANGE;
+ if (size > AP4_DATA_ATOM_MAX_SIZE) return AP4_ERROR_OUT_OF_RANGE;
string = new AP4_String((AP4_Size)size);
// read from the start of the stream
m_Source->Seek(0);
AP4_Result result = m_Source->Read(string->UseChars(), (AP4_Size)size);
- if(AP4_FAILED(result))
- {
+ if (AP4_FAILED(result)) {
delete string;
string = NULL;
}
@@ -1592,19 +1442,17 @@ AP4_DataAtom::LoadString(AP4_String*& string)
AP4_Result
AP4_DataAtom::LoadBytes(AP4_DataBuffer& bytes)
{
- if(m_Source == NULL)
- {
+ if (m_Source == NULL) {
bytes.SetDataSize(0);
return AP4_SUCCESS;
}
AP4_LargeSize size = 0;
m_Source->GetSize(size);
- if(size > AP4_DATA_ATOM_MAX_SIZE) return AP4_ERROR_OUT_OF_RANGE;
+ if (size > AP4_DATA_ATOM_MAX_SIZE) return AP4_ERROR_OUT_OF_RANGE;
bytes.SetDataSize((AP4_Size)size);
m_Source->Seek(0);
AP4_Result result = m_Source->Read(bytes.UseData(), (AP4_Size)size);
- if(AP4_FAILED(result))
- {
+ if (AP4_FAILED(result)) {
bytes.SetDataSize(0);
}
return result;
@@ -1614,36 +1462,25 @@ AP4_DataAtom::LoadBytes(AP4_DataBuffer& bytes)
| AP4_DataAtom::LoadInteger
+---------------------------------------------------------------------*/
AP4_Result
-AP4_DataAtom::LoadInteger(long& value)
+AP4_DataAtom::LoadInteger(long& value)
{
AP4_Result result = AP4_FAILURE;
value = 0;
- if(m_Source == NULL) return AP4_SUCCESS;
+ if (m_Source == NULL) return AP4_SUCCESS;
AP4_LargeSize size = 0;
m_Source->GetSize(size);
- if(size > 4)
- {
+ if (size > 4) {
return AP4_ERROR_OUT_OF_RANGE;
}
unsigned char bytes[4];
m_Source->Seek(0);
m_Source->Read(bytes, (AP4_Size)size);
result = AP4_SUCCESS;
- switch(size)
- {
- case 1:
- value = bytes[0];
- break;
- case 2:
- value = AP4_BytesToInt16BE(bytes);
- break;
- case 4:
- value = AP4_BytesToInt32BE(bytes);
- break;
- default:
- value = 0;
- result = AP4_ERROR_INVALID_FORMAT;
- break;
+ switch (size) {
+ case 1: value = bytes[0]; break;
+ case 2: value = AP4_BytesToInt16BE(bytes); break;
+ case 4: value = AP4_BytesToInt32BE(bytes); break;
+ default: value = 0; result = AP4_ERROR_INVALID_FORMAT; break;
}
return result;
}
@@ -1655,7 +1492,7 @@ AP4_MetaDataStringAtom::AP4_MetaDataStringAtom(Type type, const char* value) :
AP4_Atom(type, AP4_ATOM_HEADER_SIZE),
m_Value(value)
{
- m_Size32 += 4 + m_Value.GetLength();
+ m_Size32 += 4+m_Value.GetLength();
}
/*----------------------------------------------------------------------
@@ -1663,7 +1500,7 @@ AP4_MetaDataStringAtom::AP4_MetaDataStringAtom(Type type, const char* value) :
+---------------------------------------------------------------------*/
AP4_MetaDataStringAtom::AP4_MetaDataStringAtom(Type type, AP4_UI32 size, AP4_ByteStream& stream) :
AP4_Atom(type, size),
- m_Value((AP4_Size)(size - AP4_ATOM_HEADER_SIZE - 4))
+ m_Value((AP4_Size)(size-AP4_ATOM_HEADER_SIZE-4))
{
stream.ReadUI32(m_Reserved);
stream.Read(m_Value.UseChars(), m_Value.GetLength());
@@ -1693,55 +1530,54 @@ AP4_MetaDataStringAtom::InspectFields(AP4_AtomInspector& inspector)
| AP4_3GppLocalizedStringAtom::Create
+---------------------------------------------------------------------*/
AP4_3GppLocalizedStringAtom*
-AP4_3GppLocalizedStringAtom::Create(Type type, AP4_UI32 size, AP4_ByteStream& stream)
+AP4_3GppLocalizedStringAtom::Create(Type type, AP4_UI32 size, AP4_ByteStream& stream)
{
AP4_UI32 version;
AP4_UI32 flags;
- if(AP4_FAILED(AP4_Atom::ReadFullHeader(stream, version, flags))) return NULL;
- if(version != 0) return NULL;
+ if (AP4_FAILED(AP4_Atom::ReadFullHeader(stream, version, flags))) return NULL;
+ if (version != 0) return NULL;
return new AP4_3GppLocalizedStringAtom(type, size, version, flags, stream);
}
/*----------------------------------------------------------------------
| AP4_3GppLocalizedStringAtom::AP4_3GppLocalizedStringAtom
+---------------------------------------------------------------------*/
-AP4_3GppLocalizedStringAtom::AP4_3GppLocalizedStringAtom(Type type,
- const char* language,
- const char* value) :
- AP4_Atom(type, AP4_FULL_ATOM_HEADER_SIZE + 2, 0, 0),
+AP4_3GppLocalizedStringAtom::AP4_3GppLocalizedStringAtom(Type type,
+ const char* language,
+ const char* value) :
+ AP4_Atom(type, AP4_FULL_ATOM_HEADER_SIZE+2, 0, 0),
m_Value(value)
{
m_Language[0] = language[0];
m_Language[1] = language[1];
m_Language[2] = language[2];
m_Language[3] = language[3];
-
- m_Size32 += m_Value.GetLength() + 1;
+
+ m_Size32 += m_Value.GetLength()+1;
}
/*----------------------------------------------------------------------
| AP4_3GppLocalizedStringAtom::AP4_3GppLocalizedStringAtom
+---------------------------------------------------------------------*/
-AP4_3GppLocalizedStringAtom::AP4_3GppLocalizedStringAtom(Type type,
- AP4_UI32 size,
- AP4_UI32 version,
- AP4_UI32 flags,
- AP4_ByteStream& stream) :
+AP4_3GppLocalizedStringAtom::AP4_3GppLocalizedStringAtom(Type type,
+ AP4_UI32 size,
+ AP4_UI32 version,
+ AP4_UI32 flags,
+ AP4_ByteStream& stream) :
AP4_Atom(type, size, version, flags)
{
// read the language code
AP4_UI16 packed_language;
stream.ReadUI16(packed_language);
- m_Language[0] = 0x60 + ((packed_language >> 10) & 0x1F);
- m_Language[1] = 0x60 + ((packed_language >> 5) & 0x1F);
- m_Language[2] = 0x60 + ((packed_language) & 0x1F);
+ m_Language[0] = 0x60+((packed_language>>10)&0x1F);
+ m_Language[1] = 0x60+((packed_language>> 5)&0x1F);
+ m_Language[2] = 0x60+((packed_language )&0x1F);
m_Language[3] = '\0';
-
+
// read the value (should be a NULL-terminated string, but we'll
// allow for strings that are not terminated)
- if(size > AP4_FULL_ATOM_HEADER_SIZE + 2)
- {
- AP4_UI32 value_size = size - (AP4_FULL_ATOM_HEADER_SIZE + 2);
+ if (size > AP4_FULL_ATOM_HEADER_SIZE+2) {
+ AP4_UI32 value_size = size-(AP4_FULL_ATOM_HEADER_SIZE+2);
char* value = new char[value_size];
stream.Read(value, value_size);
m_Value.Assign(value, value_size);
@@ -1755,20 +1591,18 @@ AP4_3GppLocalizedStringAtom::AP4_3GppLocalizedStringAtom(Type type,
AP4_Result
AP4_3GppLocalizedStringAtom::WriteFields(AP4_ByteStream& stream)
{
- AP4_UI16 packed_language = ((m_Language[0] - 0x60) << 10) |
- ((m_Language[1] - 0x60) << 5) |
- ((m_Language[2] - 0x60));
+ AP4_UI16 packed_language = ((m_Language[0]-0x60)<<10) |
+ ((m_Language[1]-0x60)<< 5) |
+ ((m_Language[2]-0x60));
stream.WriteUI16(packed_language);
- AP4_Size payload_size = (AP4_UI32)GetSize() - GetHeaderSize();
- if(payload_size < 2) return AP4_ERROR_INVALID_FORMAT;
- AP4_Size value_size = m_Value.GetLength() + 1;
- if(value_size > payload_size - 2)
- {
- value_size = payload_size - 2;
+ AP4_Size payload_size = (AP4_UI32)GetSize()-GetHeaderSize();
+ if (payload_size < 2) return AP4_ERROR_INVALID_FORMAT;
+ AP4_Size value_size = m_Value.GetLength()+1;
+ if (value_size > payload_size-2) {
+ value_size = payload_size-2;
}
stream.Write(m_Value.GetChars(), value_size);
- for(unsigned int i = value_size; i < payload_size - 2; i++)
- {
+ for (unsigned int i=value_size; i<payload_size-2; i++) {
stream.WriteUI08(0);
}
return AP4_SUCCESS;
@@ -1789,12 +1623,12 @@ AP4_3GppLocalizedStringAtom::InspectFields(AP4_AtomInspector& inspector)
| AP4_DcfStringAtom::Create
+---------------------------------------------------------------------*/
AP4_DcfStringAtom*
-AP4_DcfStringAtom::Create(Type type, AP4_UI32 size, AP4_ByteStream& stream)
+AP4_DcfStringAtom::Create(Type type, AP4_UI32 size, AP4_ByteStream& stream)
{
AP4_UI32 version;
AP4_UI32 flags;
- if(AP4_FAILED(AP4_Atom::ReadFullHeader(stream, version, flags))) return NULL;
- if(version != 0) return NULL;
+ if (AP4_FAILED(AP4_Atom::ReadFullHeader(stream, version, flags))) return NULL;
+ if (version != 0) return NULL;
return new AP4_DcfStringAtom(type, size, version, flags, stream);
}
@@ -1811,16 +1645,15 @@ AP4_DcfStringAtom::AP4_DcfStringAtom(Type type, const char* value) :
/*----------------------------------------------------------------------
| AP4_DcfStringAtom::AP4_DcfStringAtom
+---------------------------------------------------------------------*/
-AP4_DcfStringAtom::AP4_DcfStringAtom(Type type,
- AP4_UI32 size,
+AP4_DcfStringAtom::AP4_DcfStringAtom(Type type,
+ AP4_UI32 size,
AP4_UI32 version,
AP4_UI32 flags,
AP4_ByteStream& stream) :
AP4_Atom(type, size, version, flags)
{
- if(size > AP4_FULL_ATOM_HEADER_SIZE)
- {
- AP4_UI32 value_size = size - (AP4_FULL_ATOM_HEADER_SIZE);
+ if (size > AP4_FULL_ATOM_HEADER_SIZE) {
+ AP4_UI32 value_size = size-(AP4_FULL_ATOM_HEADER_SIZE);
char* value = new char[value_size];
stream.Read(value, value_size);
m_Value.Assign(value, value_size);
@@ -1834,7 +1667,7 @@ AP4_DcfStringAtom::AP4_DcfStringAtom(Type type,
AP4_Result
AP4_DcfStringAtom::WriteFields(AP4_ByteStream& stream)
{
- if(m_Value.GetLength()) stream.Write(m_Value.GetChars(), m_Value.GetLength());
+ if (m_Value.GetLength()) stream.Write(m_Value.GetChars(), m_Value.GetLength());
return AP4_SUCCESS;
}
@@ -1852,13 +1685,13 @@ AP4_DcfStringAtom::InspectFields(AP4_AtomInspector& inspector)
| AP4_DcfdAtom::Create
+---------------------------------------------------------------------*/
AP4_DcfdAtom*
-AP4_DcfdAtom::Create(AP4_UI32 size, AP4_ByteStream& stream)
+AP4_DcfdAtom::Create(AP4_UI32 size, AP4_ByteStream& stream)
{
AP4_UI32 version;
AP4_UI32 flags;
- if(AP4_FAILED(AP4_Atom::ReadFullHeader(stream, version, flags))) return NULL;
- if(version != 0) return NULL;
- if(size != AP4_FULL_ATOM_HEADER_SIZE + 4) return NULL;
+ if (AP4_FAILED(AP4_Atom::ReadFullHeader(stream, version, flags))) return NULL;
+ if (version != 0) return NULL;
+ if (size != AP4_FULL_ATOM_HEADER_SIZE+4) return NULL;
return new AP4_DcfdAtom(version, flags, stream);
}
@@ -1868,7 +1701,7 @@ AP4_DcfdAtom::Create(AP4_UI32 size, AP4_ByteStream& stream)
AP4_DcfdAtom::AP4_DcfdAtom(AP4_UI32 version,
AP4_UI32 flags,
AP4_ByteStream& stream) :
- AP4_Atom(AP4_ATOM_TYPE_DCFD, AP4_FULL_ATOM_HEADER_SIZE + 4, version, flags)
+ AP4_Atom(AP4_ATOM_TYPE_DCFD, AP4_FULL_ATOM_HEADER_SIZE+4, version, flags)
{
stream.ReadUI32(m_Duration);
}
@@ -1877,7 +1710,7 @@ AP4_DcfdAtom::AP4_DcfdAtom(AP4_UI32 version,
| AP4_DcfdAtom::AP4_DcfdAtom
+---------------------------------------------------------------------*/
AP4_DcfdAtom::AP4_DcfdAtom(AP4_UI32 duration) :
- AP4_Atom(AP4_ATOM_TYPE_DCFD, AP4_FULL_ATOM_HEADER_SIZE + 4, 0, 0),
+ AP4_Atom(AP4_ATOM_TYPE_DCFD, AP4_FULL_ATOM_HEADER_SIZE+4, 0, 0),
m_Duration(duration)
{
}
diff --git a/src/filters/parser/MP4Splitter/AP4/Source/MetaData/Ap4MetaData.h b/src/filters/parser/MP4Splitter/AP4/Source/MetaData/Ap4MetaData.h
index b8d488b7b..491365f11 100644
--- a/src/filters/parser/MP4Splitter/AP4/Source/MetaData/Ap4MetaData.h
+++ b/src/filters/parser/MP4Splitter/AP4/Source/MetaData/Ap4MetaData.h
@@ -1,6 +1,6 @@
/*****************************************************************
|
-| AP4 - MetaData
+| AP4 - MetaData
|
| Copyright 2002-2008 Axiomatic Systems, LLC
|
@@ -53,98 +53,90 @@ class AP4_DcfdAtom;
/*----------------------------------------------------------------------
| metadata keys
+---------------------------------------------------------------------*/
-const AP4_Atom::Type AP4_ATOM_TYPE_DATA = AP4_ATOM_TYPE('d', 'a', 't', 'a'); // data
-const AP4_Atom::Type AP4_ATOM_TYPE_MEAN = AP4_ATOM_TYPE('m', 'e', 'a', 'n'); // namespace
-const AP4_Atom::Type AP4_ATOM_TYPE_NAME = AP4_ATOM_TYPE('n', 'a', 'm', 'e'); // name
-const AP4_Atom::Type AP4_ATOM_TYPE_dddd = AP4_ATOM_TYPE('-', '-', '-', '-'); // free form
-const AP4_Atom::Type AP4_ATOM_TYPE_cNAM = AP4_ATOM_TYPE(0xA9, 'n', 'a', 'm'); // name
-const AP4_Atom::Type AP4_ATOM_TYPE_cART = AP4_ATOM_TYPE(0xA9, 'A', 'R', 'T'); // artist
-const AP4_Atom::Type AP4_ATOM_TYPE_cCOM = AP4_ATOM_TYPE(0xA9, 'c', 'o', 'm'); // composer
-const AP4_Atom::Type AP4_ATOM_TYPE_cWRT = AP4_ATOM_TYPE(0xA9, 'w', 'r', 't'); // writer
-const AP4_Atom::Type AP4_ATOM_TYPE_cALB = AP4_ATOM_TYPE(0xA9, 'a', 'l', 'b'); // album
-const AP4_Atom::Type AP4_ATOM_TYPE_cGEN = AP4_ATOM_TYPE(0xA9, 'g', 'e', 'n'); // genre
-const AP4_Atom::Type AP4_ATOM_TYPE_cGRP = AP4_ATOM_TYPE(0xA9, 'g', 'r', 'p'); // group
-const AP4_Atom::Type AP4_ATOM_TYPE_cDAY = AP4_ATOM_TYPE(0xA9, 'd', 'a', 'y'); // date
-const AP4_Atom::Type AP4_ATOM_TYPE_cTOO = AP4_ATOM_TYPE(0xA9, 't', 'o', 'o'); // tool
-const AP4_Atom::Type AP4_ATOM_TYPE_cCMT = AP4_ATOM_TYPE(0xA9, 'c', 'm', 't'); // comment
-const AP4_Atom::Type AP4_ATOM_TYPE_cLYR = AP4_ATOM_TYPE(0xA9, 'l', 'y', 'r'); // lyrics
-const AP4_Atom::Type AP4_ATOM_TYPE_TRKN = AP4_ATOM_TYPE('t', 'r', 'k', 'n'); // track#
-const AP4_Atom::Type AP4_ATOM_TYPE_DISK = AP4_ATOM_TYPE('d', 'i', 's', 'k'); // disk#
-const AP4_Atom::Type AP4_ATOM_TYPE_COVR = AP4_ATOM_TYPE('c', 'o', 'v', 'r'); // cover art
-const AP4_Atom::Type AP4_ATOM_TYPE_DESC = AP4_ATOM_TYPE('d', 'e', 's', 'c'); // description
-const AP4_Atom::Type AP4_ATOM_TYPE_CPIL = AP4_ATOM_TYPE('c', 'p', 'i', 'l'); // compilation?
-const AP4_Atom::Type AP4_ATOM_TYPE_TMPO = AP4_ATOM_TYPE('t', 'm', 'p', 'o'); // tempo
-const AP4_Atom::Type AP4_ATOM_TYPE_apID = AP4_ATOM_TYPE('a', 'p', 'I', 'D');
-const AP4_Atom::Type AP4_ATOM_TYPE_cnID = AP4_ATOM_TYPE('c', 'n', 'I', 'D');
-const AP4_Atom::Type AP4_ATOM_TYPE_cmID = AP4_ATOM_TYPE('c', 'm', 'I', 'D');
-const AP4_Atom::Type AP4_ATOM_TYPE_atID = AP4_ATOM_TYPE('a', 't', 'I', 'D');
-const AP4_Atom::Type AP4_ATOM_TYPE_plID = AP4_ATOM_TYPE('p', 'l', 'I', 'D');
-const AP4_Atom::Type AP4_ATOM_TYPE_geID = AP4_ATOM_TYPE('g', 'e', 'I', 'D');
-const AP4_Atom::Type AP4_ATOM_TYPE_sfID = AP4_ATOM_TYPE('s', 'f', 'I', 'D');
-const AP4_Atom::Type AP4_ATOM_TYPE_akID = AP4_ATOM_TYPE('a', 'k', 'I', 'D');
-const AP4_Atom::Type AP4_ATOM_TYPE_aART = AP4_ATOM_TYPE('a', 'A', 'R', 'T');
-const AP4_Atom::Type AP4_ATOM_TYPE_TVNN = AP4_ATOM_TYPE('t', 'v', 'n', 'n'); // TV network
-const AP4_Atom::Type AP4_ATOM_TYPE_TVSH = AP4_ATOM_TYPE('t', 'v', 's', 'h'); // TV show
-const AP4_Atom::Type AP4_ATOM_TYPE_TVEN = AP4_ATOM_TYPE('t', 'v', 'e', 'n'); // TV episode name
-const AP4_Atom::Type AP4_ATOM_TYPE_TVSN = AP4_ATOM_TYPE('t', 'v', 's', 'n'); // TV show season #
-const AP4_Atom::Type AP4_ATOM_TYPE_TVES = AP4_ATOM_TYPE('t', 'v', 'e', 's'); // TV show episode #
-const AP4_Atom::Type AP4_ATOM_TYPE_STIK = AP4_ATOM_TYPE('s', 't', 'i', 'k');
-const AP4_Atom::Type AP4_ATOM_TYPE_PCST = AP4_ATOM_TYPE('p', 'c', 's', 't'); // Podcast?
-const AP4_Atom::Type AP4_ATOM_TYPE_PURD = AP4_ATOM_TYPE('p', 'u', 'r', 'd'); //
-const AP4_Atom::Type AP4_ATOM_TYPE_PURL = AP4_ATOM_TYPE('p', 'u', 'r', 'l'); // Podcast URL (binary)
-const AP4_Atom::Type AP4_ATOM_TYPE_EGID = AP4_ATOM_TYPE('e', 'g', 'i', 'd'); //
-const AP4_Atom::Type AP4_ATOM_TYPE_PGAP = AP4_ATOM_TYPE('p', 'g', 'a', 'p'); // Gapless Playback
-const AP4_Atom::Type AP4_ATOM_TYPE_CATG = AP4_ATOM_TYPE('c', 'a', 't', 'g'); // Category
-const AP4_Atom::Type AP4_ATOM_TYPE_KEYW = AP4_ATOM_TYPE('k', 'e', 'y', 'w'); // Keywords
-const AP4_Atom::Type AP4_ATOM_TYPE_SONM = AP4_ATOM_TYPE('s', 'o', 'n', 'm'); // Sort-Order: Name
-const AP4_Atom::Type AP4_ATOM_TYPE_SOAL = AP4_ATOM_TYPE('s', 'o', 'a', 'l'); // Sort-Order: Album
-const AP4_Atom::Type AP4_ATOM_TYPE_SOAR = AP4_ATOM_TYPE('s', 'o', 'a', 'r'); // Sort-Order: Artist
-const AP4_Atom::Type AP4_ATOM_TYPE_SOAA = AP4_ATOM_TYPE('s', 'o', 'a', 'a'); // Sort-Order: Album Artist
-const AP4_Atom::Type AP4_ATOM_TYPE_SOCO = AP4_ATOM_TYPE('s', 'o', 'c', 'o'); // Sort-Order: Composer
-const AP4_Atom::Type AP4_ATOM_TYPE_SOSN = AP4_ATOM_TYPE('s', 'o', 's', 'n'); // Sort-Order: Show
-
-const AP4_Atom::Type AP4_ATOM_TYPE_TITL = AP4_ATOM_TYPE('t', 'i', 't', 'l'); // 3GPP: title
-const AP4_Atom::Type AP4_ATOM_TYPE_DSCP = AP4_ATOM_TYPE('d', 's', 'c', 'p'); // 3GPP: description
-const AP4_Atom::Type AP4_ATOM_TYPE_CPRT = AP4_ATOM_TYPE('c', 'p', 'r', 't'); // 3GPP, ISO or ILST: copyright
-const AP4_Atom::Type AP4_ATOM_TYPE_PERF = AP4_ATOM_TYPE('p', 'e', 'r', 'f'); // 3GPP: performer
-const AP4_Atom::Type AP4_ATOM_TYPE_AUTH = AP4_ATOM_TYPE('a', 'u', 't', 'h'); // 3GPP: author
-const AP4_Atom::Type AP4_ATOM_TYPE_GNRE = AP4_ATOM_TYPE('g', 'n', 'r', 'e'); // 3GPP or ILST: genre (in 3GPP -> string, in ILST -> ID3v1 index + 1)
-const AP4_Atom::Type AP4_ATOM_TYPE_RTNG = AP4_ATOM_TYPE('r', 't', 'n', 'g'); // 3GPP or ILST: rating
-const AP4_Atom::Type AP4_ATOM_TYPE_CLSF = AP4_ATOM_TYPE('c', 'l', 's', 'f'); // 3GPP: classification
-const AP4_Atom::Type AP4_ATOM_TYPE_KYWD = AP4_ATOM_TYPE('k', 'y', 'w', 'd'); // 3GPP: keywords
-const AP4_Atom::Type AP4_ATOM_TYPE_LOCI = AP4_ATOM_TYPE('l', 'o', 'c', 'i'); // 3GPP: location information
-const AP4_Atom::Type AP4_ATOM_TYPE_ALBM = AP4_ATOM_TYPE('a', 'l', 'b', 'm'); // 3GPP: album title and track number
-const AP4_Atom::Type AP4_ATOM_TYPE_YRRC = AP4_ATOM_TYPE('y', 'r', 'r', 'c'); // 3GPP: recording year
-const AP4_Atom::Type AP4_ATOM_TYPE_TSEL = AP4_ATOM_TYPE('t', 's', 'e', 'l'); // 3GPP: track selection
-
-const AP4_Atom::Type AP4_ATOM_TYPE_ICNU = AP4_ATOM_TYPE('i', 'c', 'n', 'u'); // DCF: icon URI (OMA DCF 2.1)
-const AP4_Atom::Type AP4_ATOM_TYPE_INFU = AP4_ATOM_TYPE('i', 'n', 'f', 'u'); // DCF: info URI (OMA DCF 2.1)
-const AP4_Atom::Type AP4_ATOM_TYPE_CVRU = AP4_ATOM_TYPE('c', 'v', 'r', 'u'); // DCF: cover art URI (OMA DCF 2.1)
-const AP4_Atom::Type AP4_ATOM_TYPE_LRCU = AP4_ATOM_TYPE('l', 'r', 'c', 'u'); // DCF: lyrics URI (OMA DCF 2.1)
-const AP4_Atom::Type AP4_ATOM_TYPE_DCFD = AP4_ATOM_TYPE('d', 'c', 'f', 'D'); // DCF: duration (OMarlin)
+const AP4_Atom::Type AP4_ATOM_TYPE_DATA = AP4_ATOM_TYPE('d','a','t','a'); // data
+const AP4_Atom::Type AP4_ATOM_TYPE_MEAN = AP4_ATOM_TYPE('m','e','a','n'); // namespace
+const AP4_Atom::Type AP4_ATOM_TYPE_NAME = AP4_ATOM_TYPE('n','a','m','e'); // name
+const AP4_Atom::Type AP4_ATOM_TYPE_dddd = AP4_ATOM_TYPE('-','-','-','-'); // free form
+const AP4_Atom::Type AP4_ATOM_TYPE_cNAM = AP4_ATOM_TYPE(0xA9,'n','a','m'); // name
+const AP4_Atom::Type AP4_ATOM_TYPE_cART = AP4_ATOM_TYPE(0xA9,'A','R','T'); // artist
+const AP4_Atom::Type AP4_ATOM_TYPE_cCOM = AP4_ATOM_TYPE(0xA9,'c','o','m'); // composer
+const AP4_Atom::Type AP4_ATOM_TYPE_cWRT = AP4_ATOM_TYPE(0xA9,'w','r','t'); // writer
+const AP4_Atom::Type AP4_ATOM_TYPE_cALB = AP4_ATOM_TYPE(0xA9,'a','l','b'); // album
+const AP4_Atom::Type AP4_ATOM_TYPE_cGEN = AP4_ATOM_TYPE(0xA9,'g','e','n'); // genre
+const AP4_Atom::Type AP4_ATOM_TYPE_cGRP = AP4_ATOM_TYPE(0xA9,'g','r','p'); // group
+const AP4_Atom::Type AP4_ATOM_TYPE_cDAY = AP4_ATOM_TYPE(0xA9,'d','a','y'); // date
+const AP4_Atom::Type AP4_ATOM_TYPE_cTOO = AP4_ATOM_TYPE(0xA9,'t','o','o'); // tool
+const AP4_Atom::Type AP4_ATOM_TYPE_cCMT = AP4_ATOM_TYPE(0xA9,'c','m','t'); // comment
+const AP4_Atom::Type AP4_ATOM_TYPE_cLYR = AP4_ATOM_TYPE(0xA9,'l','y','r'); // lyrics
+const AP4_Atom::Type AP4_ATOM_TYPE_TRKN = AP4_ATOM_TYPE('t','r','k','n'); // track#
+const AP4_Atom::Type AP4_ATOM_TYPE_DISK = AP4_ATOM_TYPE('d','i','s','k'); // disk#
+const AP4_Atom::Type AP4_ATOM_TYPE_COVR = AP4_ATOM_TYPE('c','o','v','r'); // cover art
+const AP4_Atom::Type AP4_ATOM_TYPE_DESC = AP4_ATOM_TYPE('d','e','s','c'); // description
+const AP4_Atom::Type AP4_ATOM_TYPE_CPIL = AP4_ATOM_TYPE('c','p','i','l'); // compilation?
+const AP4_Atom::Type AP4_ATOM_TYPE_TMPO = AP4_ATOM_TYPE('t','m','p','o'); // tempo
+const AP4_Atom::Type AP4_ATOM_TYPE_apID = AP4_ATOM_TYPE('a','p','I','D');
+const AP4_Atom::Type AP4_ATOM_TYPE_cnID = AP4_ATOM_TYPE('c','n','I','D');
+const AP4_Atom::Type AP4_ATOM_TYPE_cmID = AP4_ATOM_TYPE('c','m','I','D');
+const AP4_Atom::Type AP4_ATOM_TYPE_atID = AP4_ATOM_TYPE('a','t','I','D');
+const AP4_Atom::Type AP4_ATOM_TYPE_plID = AP4_ATOM_TYPE('p','l','I','D');
+const AP4_Atom::Type AP4_ATOM_TYPE_geID = AP4_ATOM_TYPE('g','e','I','D');
+const AP4_Atom::Type AP4_ATOM_TYPE_sfID = AP4_ATOM_TYPE('s','f','I','D');
+const AP4_Atom::Type AP4_ATOM_TYPE_akID = AP4_ATOM_TYPE('a','k','I','D');
+const AP4_Atom::Type AP4_ATOM_TYPE_aART = AP4_ATOM_TYPE('a','A','R','T');
+const AP4_Atom::Type AP4_ATOM_TYPE_TVNN = AP4_ATOM_TYPE('t','v','n','n'); // TV network
+const AP4_Atom::Type AP4_ATOM_TYPE_TVSH = AP4_ATOM_TYPE('t','v','s','h'); // TV show
+const AP4_Atom::Type AP4_ATOM_TYPE_TVEN = AP4_ATOM_TYPE('t','v','e','n'); // TV episode name
+const AP4_Atom::Type AP4_ATOM_TYPE_TVSN = AP4_ATOM_TYPE('t','v','s','n'); // TV show season #
+const AP4_Atom::Type AP4_ATOM_TYPE_TVES = AP4_ATOM_TYPE('t','v','e','s'); // TV show episode #
+const AP4_Atom::Type AP4_ATOM_TYPE_STIK = AP4_ATOM_TYPE('s','t','i','k');
+const AP4_Atom::Type AP4_ATOM_TYPE_PCST = AP4_ATOM_TYPE('p','c','s','t'); // Podcast?
+const AP4_Atom::Type AP4_ATOM_TYPE_PURD = AP4_ATOM_TYPE('p','u','r','d'); //
+const AP4_Atom::Type AP4_ATOM_TYPE_PURL = AP4_ATOM_TYPE('p','u','r','l'); // Podcast URL (binary)
+const AP4_Atom::Type AP4_ATOM_TYPE_EGID = AP4_ATOM_TYPE('e','g','i','d'); //
+const AP4_Atom::Type AP4_ATOM_TYPE_PGAP = AP4_ATOM_TYPE('p','g','a','p'); // Gapless Playback
+const AP4_Atom::Type AP4_ATOM_TYPE_CATG = AP4_ATOM_TYPE('c','a','t','g'); // Category
+const AP4_Atom::Type AP4_ATOM_TYPE_KEYW = AP4_ATOM_TYPE('k','e','y','w'); // Keywords
+const AP4_Atom::Type AP4_ATOM_TYPE_SONM = AP4_ATOM_TYPE('s','o','n','m'); // Sort-Order: Name
+const AP4_Atom::Type AP4_ATOM_TYPE_SOAL = AP4_ATOM_TYPE('s','o','a','l'); // Sort-Order: Album
+const AP4_Atom::Type AP4_ATOM_TYPE_SOAR = AP4_ATOM_TYPE('s','o','a','r'); // Sort-Order: Artist
+const AP4_Atom::Type AP4_ATOM_TYPE_SOAA = AP4_ATOM_TYPE('s','o','a','a'); // Sort-Order: Album Artist
+const AP4_Atom::Type AP4_ATOM_TYPE_SOCO = AP4_ATOM_TYPE('s','o','c','o'); // Sort-Order: Composer
+const AP4_Atom::Type AP4_ATOM_TYPE_SOSN = AP4_ATOM_TYPE('s','o','s','n'); // Sort-Order: Show
+
+const AP4_Atom::Type AP4_ATOM_TYPE_TITL = AP4_ATOM_TYPE('t','i','t','l'); // 3GPP: title
+const AP4_Atom::Type AP4_ATOM_TYPE_DSCP = AP4_ATOM_TYPE('d','s','c','p'); // 3GPP: description
+const AP4_Atom::Type AP4_ATOM_TYPE_CPRT = AP4_ATOM_TYPE('c','p','r','t'); // 3GPP, ISO or ILST: copyright
+const AP4_Atom::Type AP4_ATOM_TYPE_PERF = AP4_ATOM_TYPE('p','e','r','f'); // 3GPP: performer
+const AP4_Atom::Type AP4_ATOM_TYPE_AUTH = AP4_ATOM_TYPE('a','u','t','h'); // 3GPP: author
+const AP4_Atom::Type AP4_ATOM_TYPE_GNRE = AP4_ATOM_TYPE('g','n','r','e'); // 3GPP or ILST: genre (in 3GPP -> string, in ILST -> ID3v1 index + 1)
+const AP4_Atom::Type AP4_ATOM_TYPE_RTNG = AP4_ATOM_TYPE('r','t','n','g'); // 3GPP or ILST: rating
+const AP4_Atom::Type AP4_ATOM_TYPE_CLSF = AP4_ATOM_TYPE('c','l','s','f'); // 3GPP: classification
+const AP4_Atom::Type AP4_ATOM_TYPE_KYWD = AP4_ATOM_TYPE('k','y','w','d'); // 3GPP: keywords
+const AP4_Atom::Type AP4_ATOM_TYPE_LOCI = AP4_ATOM_TYPE('l','o','c','i'); // 3GPP: location information
+const AP4_Atom::Type AP4_ATOM_TYPE_ALBM = AP4_ATOM_TYPE('a','l','b','m'); // 3GPP: album title and track number
+const AP4_Atom::Type AP4_ATOM_TYPE_YRRC = AP4_ATOM_TYPE('y','r','r','c'); // 3GPP: recording year
+const AP4_Atom::Type AP4_ATOM_TYPE_TSEL = AP4_ATOM_TYPE('t','s','e','l'); // 3GPP: track selection
+
+const AP4_Atom::Type AP4_ATOM_TYPE_ICNU = AP4_ATOM_TYPE('i','c','n','u'); // DCF: icon URI (OMA DCF 2.1)
+const AP4_Atom::Type AP4_ATOM_TYPE_INFU = AP4_ATOM_TYPE('i','n','f','u'); // DCF: info URI (OMA DCF 2.1)
+const AP4_Atom::Type AP4_ATOM_TYPE_CVRU = AP4_ATOM_TYPE('c','v','r','u'); // DCF: cover art URI (OMA DCF 2.1)
+const AP4_Atom::Type AP4_ATOM_TYPE_LRCU = AP4_ATOM_TYPE('l','r','c','u'); // DCF: lyrics URI (OMA DCF 2.1)
+const AP4_Atom::Type AP4_ATOM_TYPE_DCFD = AP4_ATOM_TYPE('d','c','f','D'); // DCF: duration (OMarlin)
/*----------------------------------------------------------------------
| AP4_MetaData
+---------------------------------------------------------------------*/
-class AP4_MetaData
-{
+class AP4_MetaData {
public:
- class Key
- {
+ class Key {
public:
// constructors
Key(const char* name, const char* ns) :
- m_Name(name), m_Namespace(ns) {}
+ m_Name(name), m_Namespace(ns) {}
// methods
- const AP4_String& GetNamespace() const
- {
- return m_Namespace;
- }
- const AP4_String& GetName() const
- {
- return m_Name;
- }
+ const AP4_String& GetNamespace() const { return m_Namespace; }
+ const AP4_String& GetName() const { return m_Name; }
private:
// members
@@ -152,12 +144,10 @@ public:
const AP4_String m_Namespace;
};
- class Value
- {
+ class Value {
public:
- // types
- typedef enum
- {
+ // types
+ typedef enum {
TYPE_BINARY,
TYPE_STRING_UTF_8,
TYPE_STRING_UTF_16,
@@ -171,55 +161,41 @@ public:
TYPE_FLOAT_64_BE
} Type;
- typedef enum
- {
+ typedef enum {
TYPE_CATEGORY_STRING,
TYPE_CATEGORY_BINARY,
TYPE_CATEGORY_INTEGER,
TYPE_CATEGORY_FLOAT
} TypeCategory;
- typedef enum
- {
+ typedef enum {
MEANING_UNKNOWN,
MEANING_ID3_GENRE,
MEANING_BOOLEAN,
MEANING_FILE_KIND,
MEANING_BINARY_ENCODED_CHARS
} Meaning;
-
+
// destructor
virtual ~Value() {}
// methods
- Type GetType() const
- {
- return m_Type;
- }
+ Type GetType() const { return m_Type; }
TypeCategory GetTypeCategory() const;
- Meaning GetMeaning() const
- {
- return m_Meaning;
- }
- const AP4_String& GetLanguage() const
- {
- return m_Language;
- }
- void SetLanguage(const char* language)
- {
- m_Language = language;
- }
+ Meaning GetMeaning() const { return m_Meaning; }
+ const AP4_String& GetLanguage() const { return m_Language; }
+ void SetLanguage(const char* language) { m_Language = language; }
virtual AP4_String ToString() const = 0;
virtual AP4_Result ToBytes(AP4_DataBuffer& bytes) const = 0;
virtual long ToInteger() const = 0;
-
+
protected:
// class methods
static TypeCategory MapTypeToCategory(Type type);
-
+
// constructor
- Value(Type type,
- Meaning meaning = MEANING_UNKNOWN,
+ Value(Type type,
+ Meaning meaning = MEANING_UNKNOWN,
const char* language = NULL) :
m_Type(type), m_Meaning(meaning), m_Language(language) {}
@@ -228,9 +204,8 @@ public:
Meaning m_Meaning;
AP4_String m_Language;
};
-
- class KeyInfo
- {
+
+ class KeyInfo {
public:
// members
const char* name;
@@ -239,18 +214,14 @@ public:
Value::Type value_type;
};
- class Entry
- {
+ class Entry {
public:
// constructor
Entry(const char* name, const char* ns, Value* value) :
- m_Key(name, ns), m_Value(value) {}
+ m_Key(name, ns), m_Value(value) {}
// destructor
- ~Entry()
- {
- delete m_Value;
- }
+ ~Entry() { delete m_Value; }
// methods
AP4_Result AddToFile(AP4_File& file, AP4_Ordinal index = 0);
@@ -264,7 +235,7 @@ public:
// members
Key m_Key;
- Value* m_Value;
+ Value* m_Value;
};
// class members
@@ -272,19 +243,16 @@ public:
// constructor
AP4_MetaData(AP4_File* file);
-
+
// methods
AP4_Result ParseMoov(AP4_MoovAtom* moov);
AP4_Result ParseUdta(AP4_ContainerAtom* udta, const char* namespc);
-
+
// destructor
~AP4_MetaData();
// accessors
- const AP4_List<Entry>& GetEntries() const
- {
- return m_Entries;
- }
+ const AP4_List<Entry>& GetEntries() const { return m_Entries; }
// methods
AP4_Result ResolveKeyName(AP4_Atom::Type atom_type, AP4_String& value);
@@ -292,7 +260,7 @@ public:
AP4_Result Add3GppEntry(AP4_3GppLocalizedStringAtom* atom, const char* namespc);
AP4_Result AddDcfStringEntry(AP4_DcfStringAtom* atom, const char* namespc);
AP4_Result AddDcfdEntry(AP4_DcfdAtom* atom, const char* namespc);
-
+
private:
// members
AP4_List<Entry> m_Entries;
@@ -306,7 +274,7 @@ class AP4_MetaDataAtomTypeHandler : public AP4_AtomFactory::TypeHandler
public:
// constructor
AP4_MetaDataAtomTypeHandler(AP4_AtomFactory* atom_factory) :
- m_AtomFactory(atom_factory) {}
+ m_AtomFactory(atom_factory) {}
virtual AP4_Result CreateAtom(AP4_Atom::Type type,
AP4_UI32 size,
AP4_ByteStream& stream,
@@ -314,12 +282,11 @@ public:
AP4_Atom*& atom);
// types
- struct TypeList
- {
+ struct TypeList {
const AP4_Atom::Type* m_Types;
AP4_Size m_Size;
};
-
+
// class constants
static const AP4_Atom::Type IlstTypes[];
static const TypeList IlstTypeList;
@@ -329,7 +296,7 @@ public:
static const TypeList _3gppOtherTypeList;
static const AP4_Atom::Type DcfStringTypes[];
static const TypeList DcfStringTypeList;
-
+
// class methods
static bool IsTypeInList(AP4_Atom::Type type, const TypeList& list);
@@ -354,9 +321,9 @@ public:
protected:
// constructor
- AP4_MetaDataTag(AP4_UI32 data_type,
+ AP4_MetaDataTag(AP4_UI32 data_type,
AP4_UI32 data_lang,
- AP4_Size size,
+ AP4_Size size,
AP4_ByteStream& stream);
};
@@ -371,29 +338,23 @@ public:
// factory method
static AP4_3GppLocalizedStringAtom* Create(Type type, AP4_UI32 size, AP4_ByteStream& stream);
-
+
// constructor
AP4_3GppLocalizedStringAtom(Type type, const char* language, const char* value);
- AP4_3GppLocalizedStringAtom(Type type,
- AP4_UI32 size,
+ AP4_3GppLocalizedStringAtom(Type type,
+ AP4_UI32 size,
AP4_UI32 version,
AP4_UI32 flags,
AP4_ByteStream& stream);
-
+
// AP4_Atom methods
virtual AP4_Result InspectFields(AP4_AtomInspector& inspector);
virtual AP4_Result WriteFields(AP4_ByteStream& stream);
-
+
// methods
- const char* GetLanguage() const
- {
- return m_Language;
- }
- const AP4_String& GetValue() const
- {
- return m_Value;
- }
-
+ const char* GetLanguage() const { return m_Language; }
+ const AP4_String& GetValue() const { return m_Value; }
+
private:
// members
char m_Language[4];
@@ -410,25 +371,22 @@ public:
// factory method
static AP4_DcfStringAtom* Create(Type type, AP4_UI32 size, AP4_ByteStream& stream);
-
+
// constructor
AP4_DcfStringAtom(Type type, const char* value);
- AP4_DcfStringAtom(Type type,
- AP4_UI32 size,
+ AP4_DcfStringAtom(Type type,
+ AP4_UI32 size,
AP4_UI32 version,
AP4_UI32 flags,
AP4_ByteStream& stream);
-
+
// AP4_Atom methods
virtual AP4_Result InspectFields(AP4_AtomInspector& inspector);
virtual AP4_Result WriteFields(AP4_ByteStream& stream);
-
+
// methods
- const AP4_String& GetValue() const
- {
- return m_Value;
- }
-
+ const AP4_String& GetValue() const { return m_Value; }
+
private:
// members
AP4_String m_Value;
@@ -444,23 +402,20 @@ public:
// factory method
static AP4_DcfdAtom* Create(AP4_UI32 size, AP4_ByteStream& stream);
-
+
// constructors
AP4_DcfdAtom(AP4_UI32 version,
AP4_UI32 flags,
AP4_ByteStream& stream);
AP4_DcfdAtom(AP4_UI32 duration);
-
+
// AP4_Atom methods
virtual AP4_Result InspectFields(AP4_AtomInspector& inspector);
virtual AP4_Result WriteFields(AP4_ByteStream& stream);
-
+
// methods
- AP4_UI32 GetDuration() const
- {
- return m_Duration;
- }
-
+ AP4_UI32 GetDuration() const { return m_Duration; }
+
private:
// members
AP4_UI32 m_Duration;
@@ -481,10 +436,7 @@ public:
virtual AP4_Result WriteFields(AP4_ByteStream& stream);
// methods
- const AP4_String& GetValue()
- {
- return m_Value;
- }
+ const AP4_String& GetValue() { return m_Value; }
private:
// members
@@ -500,8 +452,7 @@ class AP4_DataAtom : public AP4_Atom
public:
AP4_IMPLEMENT_DYNAMIC_CAST_D(AP4_DataAtom, AP4_Atom)
- typedef enum
- {
+ typedef enum {
DATA_TYPE_BINARY = 0,
DATA_TYPE_STRING_UTF_8 = 1,
DATA_TYPE_STRING_UTF_16 = 2,
@@ -513,8 +464,7 @@ public:
DATA_TYPE_FLOAT_64_BE = 23
} DataType;
- typedef enum
- {
+ typedef enum {
LANGUAGE_ENGLISH = 0
} DataLang;
@@ -530,16 +480,10 @@ public:
virtual AP4_Result WriteFields(AP4_ByteStream& stream);
// accessors
- DataType GetDataType()
- {
- return m_DataType;
- }
- DataLang GetDataLang()
- {
- return m_DataLang;
- }
+ DataType GetDataType() { return m_DataType; }
+ DataLang GetDataLang() { return m_DataLang; }
AP4_MetaData::Value::Type GetValueType();
-
+
// methods
AP4_Result LoadString(AP4_String*& string);
AP4_Result LoadBytes(AP4_DataBuffer& bytes);
@@ -555,19 +499,18 @@ private:
/*----------------------------------------------------------------------
| AP4_StringMetaDataValue
+---------------------------------------------------------------------*/
-class AP4_StringMetaDataValue : public AP4_MetaData::Value
-{
+class AP4_StringMetaDataValue : public AP4_MetaData::Value {
public:
// constructor
- AP4_StringMetaDataValue(const char* value, const char* language = NULL) :
- Value(TYPE_STRING_UTF_8, MEANING_UNKNOWN, language),
+ AP4_StringMetaDataValue(const char* value, const char* language=NULL) :
+ Value(TYPE_STRING_UTF_8, MEANING_UNKNOWN, language),
m_Value(value) {}
// AP4_MetaData::Value methods
virtual AP4_String ToString() const;
virtual AP4_Result ToBytes(AP4_DataBuffer& bytes) const;
virtual long ToInteger() const;
-
+
private:
// members
AP4_String m_Value;
@@ -576,8 +519,7 @@ private:
/*----------------------------------------------------------------------
| AP4_IntegerMetaDataValue
+---------------------------------------------------------------------*/
-class AP4_IntegerMetaDataValue : public AP4_MetaData::Value
-{
+class AP4_IntegerMetaDataValue : public AP4_MetaData::Value {
public:
// constructor
AP4_IntegerMetaDataValue(Type type, long value) :
@@ -587,7 +529,7 @@ public:
virtual AP4_String ToString() const;
virtual AP4_Result ToBytes(AP4_DataBuffer& bytes) const;
virtual long ToInteger() const;
-
+
private:
// members
long m_Value;
@@ -596,8 +538,7 @@ private:
/*----------------------------------------------------------------------
| AP4_BinaryMetaDataValue
+---------------------------------------------------------------------*/
-class AP4_BinaryMetaDataValue : public AP4_MetaData::Value
-{
+class AP4_BinaryMetaDataValue : public AP4_MetaData::Value {
public:
// constructor
AP4_BinaryMetaDataValue(Type type, const AP4_UI08* data, AP4_Size size) :
@@ -607,7 +548,7 @@ public:
virtual AP4_String ToString() const;
virtual AP4_Result ToBytes(AP4_DataBuffer& bytes) const;
virtual long ToInteger() const;
-
+
private:
// members
AP4_DataBuffer m_Value;
diff --git a/src/filters/parser/MP4Splitter/Ap4AsyncReaderStream.cpp b/src/filters/parser/MP4Splitter/Ap4AsyncReaderStream.cpp
index c77a070b0..2721e811d 100644
--- a/src/filters/parser/MP4Splitter/Ap4AsyncReaderStream.cpp
+++ b/src/filters/parser/MP4Splitter/Ap4AsyncReaderStream.cpp
@@ -1,54 +1,54 @@
#include "stdafx.h"
#include "Ap4AsyncReaderStream.h"
-AP4_AsyncReaderStream::AP4_AsyncReaderStream(CBaseSplitterFile* pFile)
- : m_refs(1)
- , m_pFile(pFile)
+AP4_AsyncReaderStream::AP4_AsyncReaderStream(CBaseSplitterFile* pFile)
+ : m_refs(1)
+ , m_pFile(pFile)
{
- ASSERT(pFile);
+ ASSERT(pFile);
}
AP4_AsyncReaderStream::~AP4_AsyncReaderStream()
{
- ASSERT(m_refs == 0);
+ ASSERT(m_refs == 0);
}
void AP4_AsyncReaderStream::AddReference()
{
- ASSERT(m_refs > 0);
- ++m_refs;
+ ASSERT(m_refs > 0);
+ ++m_refs;
}
void AP4_AsyncReaderStream::Release()
{
- ASSERT(m_refs > 0);
- if(--m_refs == 0) delete this;
+ ASSERT(m_refs > 0);
+ if(--m_refs == 0) delete this;
}
AP4_Result AP4_AsyncReaderStream::ReadPartial(void* buffer, AP4_Size bytesToRead, AP4_Size& bytesRead)
{
- AP4_Size bytesAvail = (AP4_Size)m_pFile->GetRemaining();
+ AP4_Size bytesAvail = (AP4_Size)m_pFile->GetRemaining();
- if(bytesAvail < bytesToRead)
- {
- bytesRead = bytesAvail;
- bytesToRead = bytesAvail;
- }
+ if(bytesAvail < bytesToRead)
+ {
+ bytesRead = bytesAvail;
+ bytesToRead = bytesAvail;
+ }
- if(bytesAvail == 0)
- {
- return AP4_ERROR_EOS;
- }
+ if(bytesAvail == 0)
+ {
+ return AP4_ERROR_EOS;
+ }
- if(FAILED(m_pFile->ByteRead((BYTE*)buffer, bytesToRead)))
- {
- bytesRead = 0;
- return AP4_ERROR_READ_FAILED;
- }
+ if(FAILED(m_pFile->ByteRead((BYTE*)buffer, bytesToRead)))
+ {
+ bytesRead = 0;
+ return AP4_ERROR_READ_FAILED;
+ }
- bytesRead = bytesToRead;
+ bytesRead = bytesToRead;
- return AP4_SUCCESS;
+ return AP4_SUCCESS;
}
AP4_Result AP4_AsyncReaderStream::WritePartial(const void* buffer, AP4_Size bytesToWrite, AP4_Size& bytesWritten)
@@ -58,18 +58,18 @@ AP4_Result AP4_AsyncReaderStream::WritePartial(const void* buffer, AP4_Size byte
AP4_Result AP4_AsyncReaderStream::Seek(AP4_Position offset)
{
- m_pFile->Seek(offset);
- return m_pFile->GetPos() == offset ? AP4_SUCCESS : AP4_FAILURE;
+ m_pFile->Seek(offset);
+ return m_pFile->GetPos() == offset ? AP4_SUCCESS : AP4_FAILURE;
}
AP4_Result AP4_AsyncReaderStream::Tell(AP4_Position& offset)
{
- offset = (AP4_Offset)m_pFile->GetPos();
- return AP4_SUCCESS;
+ offset = (AP4_Offset)m_pFile->GetPos();
+ return AP4_SUCCESS;
}
AP4_Result AP4_AsyncReaderStream::GetSize(AP4_LargeSize& size)
{
- size = m_pFile->GetLength();
- return AP4_SUCCESS;
+ size = m_pFile->GetLength();
+ return AP4_SUCCESS;
} \ No newline at end of file
diff --git a/src/filters/parser/MP4Splitter/Ap4AsyncReaderStream.h b/src/filters/parser/MP4Splitter/Ap4AsyncReaderStream.h
index 0c8512ee9..28e5f1c06 100644
--- a/src/filters/parser/MP4Splitter/Ap4AsyncReaderStream.h
+++ b/src/filters/parser/MP4Splitter/Ap4AsyncReaderStream.h
@@ -16,19 +16,19 @@
class AP4_AsyncReaderStream : public AP4_ByteStream
{
- int m_refs;
- CBaseSplitterFile* m_pFile;
+ int m_refs;
+ CBaseSplitterFile* m_pFile;
public:
- AP4_AsyncReaderStream(CBaseSplitterFile* pFile);
- virtual ~AP4_AsyncReaderStream();
+ AP4_AsyncReaderStream(CBaseSplitterFile* pFile);
+ virtual ~AP4_AsyncReaderStream();
- void AddReference();
- void Release();
+ void AddReference();
+ void Release();
- virtual AP4_Result ReadPartial(void* buffer, AP4_Size bytesToRead, AP4_Size& bytesRead);
- virtual AP4_Result WritePartial(const void* buffer, AP4_Size bytesToWrite, AP4_Size& bytesWritten);
- virtual AP4_Result Seek(AP4_Position offset);
- virtual AP4_Result Tell(AP4_Position& offset);
- virtual AP4_Result GetSize(AP4_LargeSize& size);
+ virtual AP4_Result ReadPartial(void* buffer, AP4_Size bytesToRead, AP4_Size& bytesRead);
+ virtual AP4_Result WritePartial(const void* buffer, AP4_Size bytesToWrite, AP4_Size& bytesWritten);
+ virtual AP4_Result Seek(AP4_Position offset);
+ virtual AP4_Result Tell(AP4_Position& offset);
+ virtual AP4_Result GetSize(AP4_LargeSize& size);
}; \ No newline at end of file
diff --git a/src/filters/parser/MP4Splitter/MP4Splitter.cpp b/src/filters/parser/MP4Splitter/MP4Splitter.cpp
index 394dea364..cd5f370cf 100644
--- a/src/filters/parser/MP4Splitter/MP4Splitter.cpp
+++ b/src/filters/parser/MP4Splitter/MP4Splitter.cpp
@@ -1,4 +1,4 @@
-/*
+/*
* Copyright (C) 2003-2006 Gabest
* http://www.gabest.org
*
@@ -6,15 +6,15 @@
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2, or (at your option)
* any later version.
- *
+ *
* This Program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with GNU Make; see the file COPYING. If not, write to
- * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
+ * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
* http://www.gnu.org/copyleft/gpl.html
*
*/
@@ -41,61 +41,61 @@
const AMOVIESETUP_MEDIATYPE sudPinTypesIn[] =
{
- {&MEDIATYPE_Stream, &MEDIASUBTYPE_MP4},
- {&MEDIATYPE_Stream, &MEDIASUBTYPE_NULL},
+ {&MEDIATYPE_Stream, &MEDIASUBTYPE_MP4},
+ {&MEDIATYPE_Stream, &MEDIASUBTYPE_NULL},
};
const AMOVIESETUP_PIN sudpPins[] =
{
- {L"Input", FALSE, FALSE, FALSE, FALSE, &CLSID_NULL, NULL, countof(sudPinTypesIn), sudPinTypesIn},
- {L"Output", FALSE, TRUE, FALSE, FALSE, &CLSID_NULL, NULL, 0, NULL}
+ {L"Input", FALSE, FALSE, FALSE, FALSE, &CLSID_NULL, NULL, countof(sudPinTypesIn), sudPinTypesIn},
+ {L"Output", FALSE, TRUE, FALSE, FALSE, &CLSID_NULL, NULL, 0, NULL}
};
const AMOVIESETUP_FILTER sudFilter[] =
{
- {&__uuidof(CMP4SplitterFilter), L"MPC - MP4 Splitter", MERIT_NORMAL, countof(sudpPins), sudpPins, CLSID_LegacyAmFilterCategory},
- {&__uuidof(CMP4SourceFilter), L"MPC - MP4 Source", MERIT_NORMAL, 0, NULL, CLSID_LegacyAmFilterCategory},
- {&__uuidof(CMPEG4VideoSplitterFilter), L"MPC - MPEG4 Video Splitter", MERIT_NORMAL, countof(sudpPins), sudpPins, CLSID_LegacyAmFilterCategory},
- {&__uuidof(CMPEG4VideoSourceFilter), L"MPC - MPEG4 Video Source", MERIT_NORMAL, 0, NULL, CLSID_LegacyAmFilterCategory},
+ {&__uuidof(CMP4SplitterFilter), L"MPC - MP4 Splitter", MERIT_NORMAL, countof(sudpPins), sudpPins, CLSID_LegacyAmFilterCategory},
+ {&__uuidof(CMP4SourceFilter), L"MPC - MP4 Source", MERIT_NORMAL, 0, NULL, CLSID_LegacyAmFilterCategory},
+ {&__uuidof(CMPEG4VideoSplitterFilter), L"MPC - MPEG4 Video Splitter", MERIT_NORMAL, countof(sudpPins), sudpPins, CLSID_LegacyAmFilterCategory},
+ {&__uuidof(CMPEG4VideoSourceFilter), L"MPC - MPEG4 Video Source", MERIT_NORMAL, 0, NULL, CLSID_LegacyAmFilterCategory},
};
CFactoryTemplate g_Templates[] =
{
- {sudFilter[0].strName, sudFilter[0].clsID, CreateInstance<CMP4SplitterFilter>, NULL, &sudFilter[0]},
- {sudFilter[1].strName, sudFilter[1].clsID, CreateInstance<CMP4SourceFilter>, NULL, &sudFilter[1]},
- {sudFilter[2].strName, sudFilter[2].clsID, CreateInstance<CMPEG4VideoSplitterFilter>, NULL, &sudFilter[2]},
- {sudFilter[3].strName, sudFilter[3].clsID, CreateInstance<CMPEG4VideoSourceFilter>, NULL, &sudFilter[3]},
+ {sudFilter[0].strName, sudFilter[0].clsID, CreateInstance<CMP4SplitterFilter>, NULL, &sudFilter[0]},
+ {sudFilter[1].strName, sudFilter[1].clsID, CreateInstance<CMP4SourceFilter>, NULL, &sudFilter[1]},
+ {sudFilter[2].strName, sudFilter[2].clsID, CreateInstance<CMPEG4VideoSplitterFilter>, NULL, &sudFilter[2]},
+ {sudFilter[3].strName, sudFilter[3].clsID, CreateInstance<CMPEG4VideoSourceFilter>, NULL, &sudFilter[3]},
};
int g_cTemplates = countof(g_Templates);
STDAPI DllRegisterServer()
{
- DeleteRegKey(_T("Media Type\\Extensions\\"), _T(".mp4"));
- DeleteRegKey(_T("Media Type\\Extensions\\"), _T(".mov"));
+ DeleteRegKey(_T("Media Type\\Extensions\\"), _T(".mp4"));
+ DeleteRegKey(_T("Media Type\\Extensions\\"), _T(".mov"));
- CAtlList<CString> chkbytes;
+ CAtlList<CString> chkbytes;
- // mp4
- chkbytes.AddTail(_T("4,4,,66747970")); // ftyp
- chkbytes.AddTail(_T("4,4,,6d6f6f76")); // moov
- chkbytes.AddTail(_T("4,4,,6d646174")); // mdat
- chkbytes.AddTail(_T("4,4,,736b6970")); // skip
- chkbytes.AddTail(_T("4,12,ffffffff00000000ffffffff,77696465027fe3706d646174")); // wide ? mdat
+ // mp4
+ chkbytes.AddTail(_T("4,4,,66747970")); // ftyp
+ chkbytes.AddTail(_T("4,4,,6d6f6f76")); // moov
+ chkbytes.AddTail(_T("4,4,,6d646174")); // mdat
+ chkbytes.AddTail(_T("4,4,,736b6970")); // skip
+ chkbytes.AddTail(_T("4,12,ffffffff00000000ffffffff,77696465027fe3706d646174")); // wide ? mdat
- // mpeg4 video
- chkbytes.AddTail(_T("3,3,,000001"));
+ // mpeg4 video
+ chkbytes.AddTail(_T("3,3,,000001"));
- RegisterSourceFilter(CLSID_AsyncReader, MEDIASUBTYPE_MP4, chkbytes, NULL);
+ RegisterSourceFilter(CLSID_AsyncReader, MEDIASUBTYPE_MP4, chkbytes, NULL);
- return AMovieDllRegisterServer2(TRUE);
+ return AMovieDllRegisterServer2(TRUE);
}
STDAPI DllUnregisterServer()
{
- UnRegisterSourceFilter(MEDIASUBTYPE_MP4);
+ UnRegisterSourceFilter(MEDIASUBTYPE_MP4);
- return AMovieDllRegisterServer2(FALSE);
+ return AMovieDllRegisterServer2(FALSE);
}
#include "../../FilterApp.h"
@@ -104,15 +104,15 @@ CFilterApp theApp;
#endif
-AP4_Result GetDataBuffer(AP4_Atom* atom, AP4_DataBuffer& db)
+AP4_Result GetDataBuffer (AP4_Atom* atom, AP4_DataBuffer& db)
{
- AP4_MemoryByteStream* mbs = new AP4_MemoryByteStream(db);
- AP4_Result res;
+ AP4_MemoryByteStream* mbs = new AP4_MemoryByteStream(db);
+ AP4_Result res;
- res = atom->Write(*mbs);
- mbs->Release(); // Release delete the object!
+ res = atom->Write (*mbs);
+ mbs->Release(); // Release delete the object!
- return res;
+ return res;
}
@@ -121,7 +121,7 @@ AP4_Result GetDataBuffer(AP4_Atom* atom, AP4_DataBuffer& db)
//
CMP4SplitterFilter::CMP4SplitterFilter(LPUNKNOWN pUnk, HRESULT* phr)
- : CBaseSplitterFilter(NAME("CMP4SplitterFilter"), pUnk, phr, __uuidof(this))
+ : CBaseSplitterFilter(NAME("CMP4SplitterFilter"), pUnk, phr, __uuidof(this))
{
}
@@ -131,1191 +131,1145 @@ CMP4SplitterFilter::~CMP4SplitterFilter()
HRESULT CMP4SplitterFilter::CreateOutputs(IAsyncReader* pAsyncReader)
{
- CheckPointer(pAsyncReader, E_POINTER);
-
- HRESULT hr = E_FAIL;
-
- m_trackpos.RemoveAll();
-
- m_pFile.Free();
- m_pFile.Attach(DNew CMP4SplitterFile(pAsyncReader, hr));
- if(!m_pFile) return E_OUTOFMEMORY;
- if(FAILED(hr))
- {
- m_pFile.Free();
- return hr;
- }
-
- m_rtNewStart = m_rtCurrent = 0;
- m_rtNewStop = m_rtStop = m_rtDuration = 0;
-
- m_framesize.SetSize(640, 480);
-
- if(AP4_Movie* movie = (AP4_Movie*)m_pFile->GetMovie())
- {
- for(AP4_List<AP4_Track>::Item* item = movie->GetTracks().FirstItem();
- item;
- item = item->GetNext())
- {
- AP4_Track* track = item->GetData();
-
- if(track->GetType() != AP4_Track::TYPE_VIDEO
- && track->GetType() != AP4_Track::TYPE_AUDIO
- && track->GetType() != AP4_Track::TYPE_TEXT
- && track->GetType() != AP4_Track::TYPE_SUBP)
- continue;
-
- AP4_Sample sample;
-
- if(!AP4_SUCCEEDED(track->GetSample(0, sample)) || sample.GetDescriptionIndex() == 0xFFFFFFFF)
- continue;
-
- CStringW TrackName = UTF8To16(track->GetTrackName().GetChars());
- CStringA TrackLanguage = track->GetTrackLanguage().GetChars();
-
- CAtlArray<CMediaType> mts;
-
- CMediaType mt;
- mt.SetSampleSize(1);
-
- VIDEOINFOHEADER* vih = NULL;
- WAVEFORMATEX* wfe = NULL;
-
- AP4_DataBuffer empty;
-
- if(AP4_SampleDescription* desc = track->GetSampleDescription(sample.GetDescriptionIndex()))
- {
- AP4_MpegSampleDescription* mpeg_desc = NULL;
-
- if(desc->GetType() == AP4_SampleDescription::TYPE_MPEG)
- {
- mpeg_desc = dynamic_cast<AP4_MpegSampleDescription*>(desc);
- }
- else if(desc->GetType() == AP4_SampleDescription::TYPE_PROTECTED)
- {
- AP4_ProtectedSampleDescription* isma_desc = dynamic_cast<AP4_ProtectedSampleDescription*>(desc);
- mpeg_desc = dynamic_cast<AP4_MpegSampleDescription*>(isma_desc->GetOriginalSampleDescription());
- }
-
- if(AP4_MpegVideoSampleDescription* video_desc =
- dynamic_cast<AP4_MpegVideoSampleDescription*>(mpeg_desc))
- {
- const AP4_DataBuffer& di = video_desc->GetDecoderInfo();
- //if(!di) di = &empty;
-
- mt.majortype = MEDIATYPE_Video;
- mt.formattype = FORMAT_VideoInfo;
- vih = (VIDEOINFOHEADER*)mt.AllocFormatBuffer(sizeof(VIDEOINFOHEADER) + di.GetDataSize());
- memset(vih, 0, mt.FormatLength());
- vih->dwBitRate = video_desc->GetAvgBitrate() / 8;
- vih->bmiHeader.biSize = sizeof(vih->bmiHeader);
- vih->bmiHeader.biWidth = (LONG)video_desc->GetWidth();
- vih->bmiHeader.biHeight = (LONG)video_desc->GetHeight();
- memcpy(vih + 1, di.GetData(), di.GetDataSize());
-
- switch(video_desc->GetObjectTypeId())
- {
- case AP4_OTI_MPEG4_VISUAL:
- mt.subtype = FOURCCMap('v4pm');
- mt.formattype = FORMAT_MPEG2Video;
- {
- MPEG2VIDEOINFO* vih = (MPEG2VIDEOINFO*)mt.AllocFormatBuffer(FIELD_OFFSET(MPEG2VIDEOINFO, dwSequenceHeader) + di.GetDataSize());
- memset(vih, 0, mt.FormatLength());
- vih->hdr.bmiHeader.biSize = sizeof(vih->hdr.bmiHeader);
- vih->hdr.bmiHeader.biWidth = (LONG)video_desc->GetWidth();
- vih->hdr.bmiHeader.biHeight = (LONG)video_desc->GetHeight();
- vih->hdr.bmiHeader.biCompression = 'v4pm';
- vih->hdr.bmiHeader.biPlanes = 1;
- vih->hdr.bmiHeader.biBitCount = 24;
- vih->hdr.dwPictAspectRatioX = vih->hdr.bmiHeader.biWidth;
- vih->hdr.dwPictAspectRatioY = vih->hdr.bmiHeader.biHeight;
- vih->cbSequenceHeader = di.GetDataSize();
- memcpy(vih->dwSequenceHeader, di.GetData(), di.GetDataSize());
- mts.Add(mt);
- mt.subtype = FOURCCMap(vih->hdr.bmiHeader.biCompression = 'V4PM');
- mts.Add(mt);
- }
- break;
- case AP4_OTI_MPEG2_VISUAL_SIMPLE:
- case AP4_OTI_MPEG2_VISUAL_MAIN:
- case AP4_OTI_MPEG2_VISUAL_SNR:
- case AP4_OTI_MPEG2_VISUAL_SPATIAL:
- case AP4_OTI_MPEG2_VISUAL_HIGH:
- case AP4_OTI_MPEG2_VISUAL_422:
- mt.subtype = MEDIASUBTYPE_MPEG2_VIDEO;
- {
- m_pFile->Seek(sample.GetOffset());
- CBaseSplitterFileEx::seqhdr h;
- CMediaType mt2;
- if(m_pFile->Read(h, sample.GetSize(), &mt2))
- mt = mt2;
- }
- mts.Add(mt);
- break;
- case AP4_OTI_MPEG1_VISUAL: // ???
- mt.subtype = MEDIASUBTYPE_MPEG1Payload;
- {
- m_pFile->Seek(sample.GetOffset());
- CBaseSplitterFileEx::seqhdr h;
- CMediaType mt2;
- if(m_pFile->Read(h, sample.GetSize(), &mt2))
- mt = mt2;
- }
- mts.Add(mt);
- break;
- }
-
- if(mt.subtype == GUID_NULL)
- {
- TRACE(_T("Unknown video OBI: %02x\n"), video_desc->GetObjectTypeId());
- }
- }
- else if(AP4_MpegAudioSampleDescription* audio_desc =
- dynamic_cast<AP4_MpegAudioSampleDescription*>(mpeg_desc))
- {
- const AP4_DataBuffer& di = audio_desc->GetDecoderInfo();
- //if(!di) di = &empty;
-
- mt.majortype = MEDIATYPE_Audio;
- mt.formattype = FORMAT_WaveFormatEx;
-
- wfe = (WAVEFORMATEX*)mt.AllocFormatBuffer(sizeof(WAVEFORMATEX) + di.GetDataSize());
- memset(wfe, 0, mt.FormatLength());
- wfe->nSamplesPerSec = audio_desc->GetSampleRate();
- wfe->nAvgBytesPerSec = audio_desc->GetAvgBitrate() / 8;
- wfe->nChannels = audio_desc->GetChannelCount();
- wfe->wBitsPerSample = audio_desc->GetSampleSize();
- wfe->cbSize = (WORD)di.GetDataSize();
- memcpy(wfe + 1, di.GetData(), di.GetDataSize());
-
- switch(audio_desc->GetObjectTypeId())
- {
- case AP4_OTI_MPEG4_AUDIO:
- case AP4_OTI_MPEG2_AAC_AUDIO_MAIN: // ???
- case AP4_OTI_MPEG2_AAC_AUDIO_LC: // ???
- case AP4_OTI_MPEG2_AAC_AUDIO_SSRP: // ???
- mt.subtype = FOURCCMap(wfe->wFormatTag = WAVE_FORMAT_AAC);
- if(wfe->cbSize >= 2) wfe->nChannels = (((BYTE*)(wfe + 1))[1] >> 3) & 0xf;
- mts.Add(mt);
- break;
- case AP4_OTI_MPEG2_PART3_AUDIO: // ???
- case AP4_OTI_MPEG1_AUDIO:
- mt.subtype = FOURCCMap(wfe->wFormatTag = WAVE_FORMAT_MP3);
- {
- m_pFile->Seek(sample.GetOffset());
- CBaseSplitterFileEx::mpahdr h;
- CMediaType mt2;
- if(m_pFile->Read(h, sample.GetSize(), false, &mt2))
- mt = mt2;
- }
- mts.Add(mt);
- break;
- }
-
- if(mt.subtype == GUID_NULL)
- {
- TRACE(_T("Unknown audio OBI: %02x\n"), audio_desc->GetObjectTypeId());
- }
- }
- else if(AP4_MpegSystemSampleDescription* system_desc =
- dynamic_cast<AP4_MpegSystemSampleDescription*>(desc))
- {
- const AP4_DataBuffer& di = system_desc->GetDecoderInfo();
- //if(!di) di = &empty;
-
- switch(system_desc->GetObjectTypeId())
- {
- case AP4_NERO_VOBSUB:
- if(di.GetDataSize() >= 16 * 4)
- {
- CSize size(720, 576);
- if(AP4_TkhdAtom* tkhd = dynamic_cast<AP4_TkhdAtom*>(track->GetTrakAtom()->GetChild(AP4_ATOM_TYPE_TKHD)))
- {
- size.cx = tkhd->GetWidth() >> 16;
- size.cy = tkhd->GetHeight() >> 16;
- }
-
- const AP4_Byte* pal = di.GetData();
- CAtlList<CStringA> sl;
- for(int i = 0; i < 16 * 4; i += 4)
- {
- BYTE y = (pal[i+1] - 16) * 255 / 219;
- BYTE u = pal[i+2];
- BYTE v = pal[i+3];
- BYTE r = (BYTE)min(max(1.0 * y + 1.4022 * (v - 128), 0), 255);
- BYTE g = (BYTE)min(max(1.0 * y - 0.3456 * (u - 128) - 0.7145 * (v - 128), 0), 255);
- BYTE b = (BYTE)min(max(1.0 * y + 1.7710 * (u - 128), 0) , 255);
- CStringA str;
- str.Format("%02x%02x%02x", r, g, b);
- sl.AddTail(str);
- }
-
- CStringA hdr;
- hdr.Format(
- "# VobSub index file, v7 (do not modify this line!)\n"
- "size: %dx%d\n"
- "palette: %s\n",
- size.cx, size.cy,
- Implode(sl, ','));
-
- mt.majortype = MEDIATYPE_Subtitle;
- mt.subtype = MEDIASUBTYPE_VOBSUB;
- mt.formattype = FORMAT_SubtitleInfo;
- SUBTITLEINFO* si = (SUBTITLEINFO*)mt.AllocFormatBuffer(sizeof(SUBTITLEINFO) + hdr.GetLength());
- memset(si, 0, mt.FormatLength());
- si->dwOffset = sizeof(SUBTITLEINFO);
- strcpy_s(si->IsoLang, countof(si->IsoLang), CStringA(TrackLanguage));
- wcscpy_s(si->TrackName, countof(si->TrackName), TrackName);
- memcpy(si + 1, (LPCSTR)hdr, hdr.GetLength());
- mts.Add(mt);
- }
- break;
- }
-
- if(mt.subtype == GUID_NULL)
- {
- TRACE(_T("Unknown audio OBI: %02x\n"), system_desc->GetObjectTypeId());
- }
- }
- else if(desc->GetType() == AP4_SampleDescription::TYPE_AVC)
- {
- AP4_AvcSampleDescription* avc1 = dynamic_cast<AP4_AvcSampleDescription*>(desc);
-
- const AP4_DataBuffer& di = avc1->GetRawBytes();
-
- const AP4_Byte* data = di.GetData();
- AP4_Size size = di.GetDataSize();
-
- mt.majortype = MEDIATYPE_Video;
- mt.subtype = FOURCCMap('1cva');
- mt.formattype = FORMAT_MPEG2Video;
-
- MPEG2VIDEOINFO* vih = (MPEG2VIDEOINFO*)mt.AllocFormatBuffer(FIELD_OFFSET(MPEG2VIDEOINFO, dwSequenceHeader) + size - 7);
- memset(vih, 0, mt.FormatLength());
- vih->hdr.bmiHeader.biSize = sizeof(vih->hdr.bmiHeader);
- vih->hdr.bmiHeader.biWidth = (LONG)avc1->GetWidth();
- vih->hdr.bmiHeader.biHeight = (LONG)avc1->GetHeight();
- vih->hdr.bmiHeader.biCompression = '1cva';
- vih->hdr.bmiHeader.biPlanes = 1;
- vih->hdr.bmiHeader.biBitCount = 24;
- vih->hdr.dwPictAspectRatioX = vih->hdr.bmiHeader.biWidth;
- vih->hdr.dwPictAspectRatioY = vih->hdr.bmiHeader.biHeight;
- if(item->GetData()->GetSampleCount() > 1)
- vih->hdr.AvgTimePerFrame = MulDiv(item->GetData()->GetDurationMs(), 10000, item->GetData()->GetSampleCount() - 1);
- vih->dwProfile = data[1];
- vih->dwLevel = data[3];
- vih->dwFlags = (data[4] & 3) + 1;
-
- vih->cbSequenceHeader = 0;
-
- BYTE* src = (BYTE*)data + 5;
- BYTE* dst = (BYTE*)vih->dwSequenceHeader;
-
- BYTE* src_end = (BYTE*)data + size;
- BYTE* dst_end = (BYTE*)vih->dwSequenceHeader + size;
-
- for(int i = 0; i < 2; i++)
- {
- for(int n = *src++ & 0x1f; n > 0; n--)
- {
- int len = ((src[0] << 8) | src[1]) + 2;
- if(src + len > src_end || dst + len > dst_end)
- {
- ASSERT(0);
- break;
- }
- memcpy(dst, src, len);
- src += len;
- dst += len;
- vih->cbSequenceHeader += len;
- }
- }
-
- mts.Add(mt);
-
- mt.subtype = FOURCCMap(vih->hdr.bmiHeader.biCompression = '1CVA');
- mts.Add(mt);
- }
- }
- if(AP4_StsdAtom* stsd = dynamic_cast<AP4_StsdAtom*>(
- track->GetTrakAtom()->FindChild("mdia/minf/stbl/stsd")))
- {
-
- for(AP4_List<AP4_Atom>::Item* item = stsd->GetChildren().FirstItem();
- item;
- item = item->GetNext())
- {
- AP4_Atom* atom = item->GetData();
- AP4_DataBuffer db;
-
- GetDataBuffer(atom, db);
-
- AP4_Atom::Type type = atom->GetType();
-
- if((type & 0xffff0000) == AP4_ATOM_TYPE('m', 's', 0, 0))
- {
- type &= 0xffff;
- }
- else if(type == AP4_ATOM_TYPE__MP3)
- {
- type = 0x0055;
- }
- else if((type == AP4_ATOM_TYPE_AC_3) || (type == AP4_ATOM_TYPE_SAC3))
- {
- type = 0x2000;
- }
- else
- {
- type =
- ((type >> 24) & 0x000000ff) |
- ((type >> 8) & 0x0000ff00) |
- ((type << 8) & 0x00ff0000) |
- ((type << 24) & 0xff000000);
- }
-
- if(AP4_VisualSampleEntry* vse = dynamic_cast<AP4_VisualSampleEntry*>(atom))
- {
- mt.majortype = MEDIATYPE_Video;
- mt.subtype = FOURCCMap(type);
- mt.formattype = FORMAT_VideoInfo;
- vih = (VIDEOINFOHEADER*)mt.AllocFormatBuffer(sizeof(VIDEOINFOHEADER) + db.GetDataSize());
- memset(vih, 0, mt.FormatLength());
- vih->bmiHeader.biSize = sizeof(vih->bmiHeader);
- vih->bmiHeader.biWidth = (LONG)vse->GetWidth();
- vih->bmiHeader.biHeight = (LONG)vse->GetHeight();
- vih->bmiHeader.biCompression = type;
- memcpy(vih + 1, db.GetData(), db.GetDataSize());
- mts.Add(mt);
-
- char buff[5];
- memcpy(buff, &type, 4);
- buff[4] = 0;
-
- strlwr((char*)&buff);
- AP4_Atom::Type typelwr = *(AP4_Atom::Type*)buff;
-
- if(typelwr != type)
- {
- mt.subtype = FOURCCMap(vih->bmiHeader.biCompression = typelwr);
- mts.Add(mt);
- }
-
- strupr((char*)&buff);
- AP4_Atom::Type typeupr = *(AP4_Atom::Type*)buff;
-
- if(typeupr != type)
- {
- mt.subtype = FOURCCMap(vih->bmiHeader.biCompression = typeupr);
- mts.Add(mt);
- }
-
- break;
- }
- else if(AP4_AudioSampleEntry* ase = dynamic_cast<AP4_AudioSampleEntry*>(atom))
- {
- mt.majortype = MEDIATYPE_Audio;
- mt.subtype = FOURCCMap(type);
- mt.formattype = FORMAT_WaveFormatEx;
- wfe = (WAVEFORMATEX*)mt.AllocFormatBuffer(sizeof(WAVEFORMATEX) + db.GetDataSize());
- memset(wfe, 0, mt.FormatLength());
- if(!(type & 0xffff0000)) wfe->wFormatTag = (WORD)type;
- wfe->nSamplesPerSec = ase->GetSampleRate();
- wfe->nChannels = ase->GetChannelCount();
- wfe->wBitsPerSample = ase->GetSampleSize();
- wfe->nBlockAlign = ase->GetBytesPerFrame();
- wfe->cbSize = db.GetDataSize();
- memcpy(wfe + 1, db.GetData(), db.GetDataSize());
- mts.Add(mt);
- break;
- }
-
- else if(dynamic_cast<AP4_TextSampleEntry*>(atom)
- || dynamic_cast<AP4_Tx3gSampleEntry*>(atom))
- {
- mt.majortype = MEDIATYPE_Subtitle;
- mt.subtype = MEDIASUBTYPE_ASS2;
- mt.formattype = FORMAT_SubtitleInfo;
- CStringA hdr;
- hdr.Format(
- "[Script Info]\n"
- "ScriptType: v4.00++\n"
- "ScaledBorderAndShadow: yes\n"
- "PlayResX: %d\n"
- "PlayResY: %d\n"
- "[V4++ Styles]\n"
- "Style: Text,Arial,12,&H00ffffff,&H0000ffff,&H00000000,&H80000000,0,0,0,0,100,100,0,0.00,3,0,0,2,0,0,0,0,1,1\n",
- // "Style: Text,Arial,12,&H00ffffff,&H0000ffff,&H00000000,&H80000000,0,0,0,0,100,100,0,0.00,1,0,0,2,0,0,0,0,1,1\n",
- m_framesize.cx,
- m_framesize.cy);
- SUBTITLEINFO* si = (SUBTITLEINFO*)mt.AllocFormatBuffer(sizeof(SUBTITLEINFO) + hdr.GetLength());
- memset(si, 0, mt.FormatLength());
- si->dwOffset = sizeof(SUBTITLEINFO);
- strcpy_s(si->IsoLang, countof(si->IsoLang), CStringA(TrackLanguage));
- wcscpy_s(si->TrackName, countof(si->TrackName), TrackName);
- memcpy(si + 1, (LPCSTR)hdr, hdr.GetLength());
- mts.Add(mt);
- }
-
- }
- }
-
- if(mts.IsEmpty()) continue;
-
- REFERENCE_TIME rtDuration = 10000i64 * track->GetDurationMs();
- if(m_rtDuration < rtDuration) m_rtDuration = rtDuration;
-
- DWORD id = track->GetId();
-
- CStringW name, lang;
- name.Format(L"Output %d", id);
-
- if(!TrackName.IsEmpty())
- {
- name = TrackName;
- }
-
- if(!TrackLanguage.IsEmpty())
- {
- if(TrackLanguage != L"und") name += " (" + TrackLanguage + ")";
- }
-
- for(int i = 0, j = mts.GetCount(); i < j; i++)
- {
- BITMAPINFOHEADER bih;
- if(ExtractBIH(&mts[i], &bih))
- {
- m_framesize.cx = bih.biWidth;
- m_framesize.cy = abs(bih.biHeight);
- }
- }
-
- CAutoPtr<CBaseSplitterOutputPin> pPinOut(DNew CBaseSplitterOutputPin(mts, name, this, this, &hr));
-
- if(!TrackName.IsEmpty()) pPinOut->SetProperty(L"NAME", TrackName);
- if(!TrackLanguage.IsEmpty()) pPinOut->SetProperty(L"LANG", CStringW(TrackLanguage));
-
- EXECUTE_ASSERT(SUCCEEDED(AddOutputPin(id, pPinOut)));
-
- m_trackpos[id] = trackpos();
-
- if(mts.GetCount() == 1 && mts[0].subtype == MEDIASUBTYPE_ASS2)
- {
- LPCWSTR postfix = L" (plain text)";
-
- mts[0].subtype = MEDIASUBTYPE_UTF8;
-
- SUBTITLEINFO* si = (SUBTITLEINFO*)mts[0].ReallocFormatBuffer(sizeof(SUBTITLEINFO));
- wcscat(si->TrackName, postfix);
-
- id ^= 0x80402010; // FIXME: until fixing, let's hope there won't be another track like this...
-
- CAutoPtr<CBaseSplitterOutputPin> pPinOut(DNew CBaseSplitterOutputPin(mts, name + postfix, this, this, &hr));
-
- if(!TrackName.IsEmpty()) pPinOut->SetProperty(L"NAME", TrackName + postfix);
- if(!TrackLanguage.IsEmpty()) pPinOut->SetProperty(L"LANG", CStringW(TrackLanguage));
-
- EXECUTE_ASSERT(SUCCEEDED(AddOutputPin(id, pPinOut)));
- }
- }
-
- if(AP4_ChplAtom* chpl = dynamic_cast<AP4_ChplAtom*>(movie->GetMoovAtom()->FindChild("udta/chpl")))
- {
- AP4_Array<AP4_ChplAtom::AP4_Chapter>& chapters = chpl->GetChapters();
-
- for(AP4_Cardinal i = 0; i < chapters.ItemCount(); i++)
- {
- AP4_ChplAtom::AP4_Chapter& chapter = chapters[i];
- ChapAppend(chapter.Time, UTF8To16(ConvertMBCS(chapter.Name.GetChars(), ANSI_CHARSET, CP_UTF8))); // this is b0rked, thx to nero :P
- }
-
- ChapSort();
- }
-
- if(AP4_ContainerAtom* ilst = dynamic_cast<AP4_ContainerAtom*>(movie->GetMoovAtom()->FindChild("udta/meta/ilst")))
- {
- CStringW title, artist, writer, album, year, appl, desc, gen, track;
-
- for(AP4_List<AP4_Atom>::Item* item = ilst->GetChildren().FirstItem();
- item;
- item = item->GetNext())
- {
- if(AP4_ContainerAtom* atom = dynamic_cast<AP4_ContainerAtom*>(item->GetData()))
- {
- if(AP4_DataAtom* data = dynamic_cast<AP4_DataAtom*>(atom->GetChild(AP4_ATOM_TYPE_DATA)))
- {
- // TODO : BENTOMIGRATION
- //const AP4_DataBuffer* db = data->GetData();
-
- //if(atom->GetType() == AP4_ATOM_TYPE_TRKN)
- //{
- // if(db->GetDataSize() >= 4)
- // {
- // unsigned short n = (db->GetData()[2] << 8) | db->GetData()[3];
- // if(n > 0 && n < 100) track.Format(L"%02d", n);
- // else if(n >= 100) track.Format(L"%d", n);
- // }
- //}
- //else
- //{
- // CStringW str = UTF8To16(CStringA((LPCSTR)db->GetData(), db->GetDataSize()));
-
- // switch(atom->GetType())
- // {
- // case AP4_ATOM_TYPE_NAM: title = str; break;
- // case AP4_ATOM_TYPE_ART: artist = str; break;
- // case AP4_ATOM_TYPE_WRT: writer = str; break;
- // case AP4_ATOM_TYPE_ALB: album = str; break;
- // case AP4_ATOM_TYPE_DAY: year = str; break;
- // case AP4_ATOM_TYPE_TOO: appl = str; break;
- // case AP4_ATOM_TYPE_CMT: desc = str; break;
- // case AP4_ATOM_TYPE_GEN: gen = str; break;
- // }
- //}
- }
- }
- }
-
- if(!title.IsEmpty())
- {
- if(!track.IsEmpty()) title = track + L" - " + title;
- if(!album.IsEmpty()) title = album + L" - " + title;
- if(!year.IsEmpty()) title += L" - " + year;
- if(!gen.IsEmpty()) title += L" - " + gen;
- SetProperty(L"TITL", title);
- }
-
- if(!artist.IsEmpty()) SetProperty(L"AUTH", artist);
- else if(!writer.IsEmpty()) SetProperty(L"AUTH", writer);
-
- if(!appl.IsEmpty()) SetProperty(L"APPL", appl);
-
- if(!desc.IsEmpty()) SetProperty(L"DESC", desc);
- }
- }
-
- m_rtNewStop = m_rtStop = m_rtDuration;
-
- return m_pOutputs.GetCount() > 0 ? S_OK : E_FAIL;
+ CheckPointer(pAsyncReader, E_POINTER);
+
+ HRESULT hr = E_FAIL;
+
+ m_trackpos.RemoveAll();
+
+ m_pFile.Free();
+ m_pFile.Attach(DNew CMP4SplitterFile(pAsyncReader, hr));
+ if(!m_pFile) return E_OUTOFMEMORY;
+ if(FAILED(hr)) {m_pFile.Free(); return hr;}
+
+ m_rtNewStart = m_rtCurrent = 0;
+ m_rtNewStop = m_rtStop = m_rtDuration = 0;
+
+ m_framesize.SetSize(640, 480);
+
+ if(AP4_Movie* movie = (AP4_Movie*)m_pFile->GetMovie())
+ {
+ for(AP4_List<AP4_Track>::Item* item = movie->GetTracks().FirstItem();
+ item;
+ item = item->GetNext())
+ {
+ AP4_Track* track = item->GetData();
+
+ if(track->GetType() != AP4_Track::TYPE_VIDEO
+ && track->GetType() != AP4_Track::TYPE_AUDIO
+ && track->GetType() != AP4_Track::TYPE_TEXT
+ && track->GetType() != AP4_Track::TYPE_SUBP)
+ continue;
+
+ AP4_Sample sample;
+
+ if(!AP4_SUCCEEDED(track->GetSample(0, sample)) || sample.GetDescriptionIndex() == 0xFFFFFFFF)
+ continue;
+
+ CStringW TrackName = UTF8To16(track->GetTrackName().GetChars());
+ CStringA TrackLanguage = track->GetTrackLanguage().GetChars();
+
+ CAtlArray<CMediaType> mts;
+
+ CMediaType mt;
+ mt.SetSampleSize(1);
+
+ VIDEOINFOHEADER* vih = NULL;
+ WAVEFORMATEX* wfe = NULL;
+
+ AP4_DataBuffer empty;
+
+ if(AP4_SampleDescription* desc = track->GetSampleDescription(sample.GetDescriptionIndex()))
+ {
+ AP4_MpegSampleDescription* mpeg_desc = NULL;
+
+ if(desc->GetType() == AP4_SampleDescription::TYPE_MPEG)
+ {
+ mpeg_desc = dynamic_cast<AP4_MpegSampleDescription*>(desc);
+ }
+ else if(desc->GetType() == AP4_SampleDescription::TYPE_PROTECTED)
+ {
+ AP4_ProtectedSampleDescription* isma_desc = dynamic_cast<AP4_ProtectedSampleDescription*>(desc);
+ mpeg_desc = dynamic_cast<AP4_MpegSampleDescription*>(isma_desc->GetOriginalSampleDescription());
+ }
+
+ if(AP4_MpegVideoSampleDescription* video_desc =
+ dynamic_cast<AP4_MpegVideoSampleDescription*>(mpeg_desc))
+ {
+ const AP4_DataBuffer& di = video_desc->GetDecoderInfo();
+ //if(!di) di = &empty;
+
+ mt.majortype = MEDIATYPE_Video;
+ mt.formattype = FORMAT_VideoInfo;
+ vih = (VIDEOINFOHEADER*)mt.AllocFormatBuffer(sizeof(VIDEOINFOHEADER) + di.GetDataSize());
+ memset(vih, 0, mt.FormatLength());
+ vih->dwBitRate = video_desc->GetAvgBitrate()/8;
+ vih->bmiHeader.biSize = sizeof(vih->bmiHeader);
+ vih->bmiHeader.biWidth = (LONG)video_desc->GetWidth();
+ vih->bmiHeader.biHeight = (LONG)video_desc->GetHeight();
+ memcpy(vih + 1, di.GetData(), di.GetDataSize());
+
+ switch(video_desc->GetObjectTypeId())
+ {
+ case AP4_OTI_MPEG4_VISUAL:
+ mt.subtype = FOURCCMap('v4pm');
+ mt.formattype = FORMAT_MPEG2Video;
+ {
+ MPEG2VIDEOINFO* vih = (MPEG2VIDEOINFO*)mt.AllocFormatBuffer(FIELD_OFFSET(MPEG2VIDEOINFO, dwSequenceHeader) + di.GetDataSize());
+ memset(vih, 0, mt.FormatLength());
+ vih->hdr.bmiHeader.biSize = sizeof(vih->hdr.bmiHeader);
+ vih->hdr.bmiHeader.biWidth = (LONG)video_desc->GetWidth();
+ vih->hdr.bmiHeader.biHeight = (LONG)video_desc->GetHeight();
+ vih->hdr.bmiHeader.biCompression = 'v4pm';
+ vih->hdr.bmiHeader.biPlanes = 1;
+ vih->hdr.bmiHeader.biBitCount = 24;
+ vih->hdr.dwPictAspectRatioX = vih->hdr.bmiHeader.biWidth;
+ vih->hdr.dwPictAspectRatioY = vih->hdr.bmiHeader.biHeight;
+ vih->cbSequenceHeader = di.GetDataSize();
+ memcpy(vih->dwSequenceHeader, di.GetData(), di.GetDataSize());
+ mts.Add(mt);
+ mt.subtype = FOURCCMap(vih->hdr.bmiHeader.biCompression = 'V4PM');
+ mts.Add(mt);
+ }
+ break;
+ case AP4_OTI_MPEG2_VISUAL_SIMPLE:
+ case AP4_OTI_MPEG2_VISUAL_MAIN:
+ case AP4_OTI_MPEG2_VISUAL_SNR:
+ case AP4_OTI_MPEG2_VISUAL_SPATIAL:
+ case AP4_OTI_MPEG2_VISUAL_HIGH:
+ case AP4_OTI_MPEG2_VISUAL_422:
+ mt.subtype = MEDIASUBTYPE_MPEG2_VIDEO;
+ {
+ m_pFile->Seek(sample.GetOffset());
+ CBaseSplitterFileEx::seqhdr h;
+ CMediaType mt2;
+ if(m_pFile->Read(h, sample.GetSize(), &mt2))
+ mt = mt2;
+ }
+ mts.Add(mt);
+ break;
+ case AP4_OTI_MPEG1_VISUAL: // ???
+ mt.subtype = MEDIASUBTYPE_MPEG1Payload;
+ {
+ m_pFile->Seek(sample.GetOffset());
+ CBaseSplitterFileEx::seqhdr h;
+ CMediaType mt2;
+ if(m_pFile->Read(h, sample.GetSize(), &mt2))
+ mt = mt2;
+ }
+ mts.Add(mt);
+ break;
+ }
+
+ if(mt.subtype == GUID_NULL)
+ {
+ TRACE(_T("Unknown video OBI: %02x\n"), video_desc->GetObjectTypeId());
+ }
+ }
+ else if(AP4_MpegAudioSampleDescription* audio_desc =
+ dynamic_cast<AP4_MpegAudioSampleDescription*>(mpeg_desc))
+ {
+ const AP4_DataBuffer& di = audio_desc->GetDecoderInfo();
+ //if(!di) di = &empty;
+
+ mt.majortype = MEDIATYPE_Audio;
+ mt.formattype = FORMAT_WaveFormatEx;
+
+ wfe = (WAVEFORMATEX*)mt.AllocFormatBuffer(sizeof(WAVEFORMATEX) + di.GetDataSize());
+ memset(wfe, 0, mt.FormatLength());
+ wfe->nSamplesPerSec = audio_desc->GetSampleRate();
+ wfe->nAvgBytesPerSec = audio_desc->GetAvgBitrate()/8;
+ wfe->nChannels = audio_desc->GetChannelCount();
+ wfe->wBitsPerSample = audio_desc->GetSampleSize();
+ wfe->cbSize = (WORD)di.GetDataSize();
+ memcpy(wfe + 1, di.GetData(), di.GetDataSize());
+
+ switch(audio_desc->GetObjectTypeId())
+ {
+ case AP4_OTI_MPEG4_AUDIO:
+ case AP4_OTI_MPEG2_AAC_AUDIO_MAIN: // ???
+ case AP4_OTI_MPEG2_AAC_AUDIO_LC: // ???
+ case AP4_OTI_MPEG2_AAC_AUDIO_SSRP: // ???
+ mt.subtype = FOURCCMap(wfe->wFormatTag = WAVE_FORMAT_AAC);
+ if(wfe->cbSize >= 2) wfe->nChannels = (((BYTE*)(wfe+1))[1]>>3) & 0xf;
+ mts.Add(mt);
+ break;
+ case AP4_OTI_MPEG2_PART3_AUDIO: // ???
+ case AP4_OTI_MPEG1_AUDIO:
+ mt.subtype = FOURCCMap(wfe->wFormatTag = WAVE_FORMAT_MP3);
+ {
+ m_pFile->Seek(sample.GetOffset());
+ CBaseSplitterFileEx::mpahdr h;
+ CMediaType mt2;
+ if(m_pFile->Read(h, sample.GetSize(), false, &mt2))
+ mt = mt2;
+ }
+ mts.Add(mt);
+ break;
+ }
+
+ if(mt.subtype == GUID_NULL)
+ {
+ TRACE(_T("Unknown audio OBI: %02x\n"), audio_desc->GetObjectTypeId());
+ }
+ }
+ else if(AP4_MpegSystemSampleDescription* system_desc =
+ dynamic_cast<AP4_MpegSystemSampleDescription*>(desc))
+ {
+ const AP4_DataBuffer& di = system_desc->GetDecoderInfo();
+ //if(!di) di = &empty;
+
+ switch(system_desc->GetObjectTypeId())
+ {
+ case AP4_NERO_VOBSUB:
+ if(di.GetDataSize() >= 16*4)
+ {
+ CSize size(720, 576);
+ if(AP4_TkhdAtom* tkhd = dynamic_cast<AP4_TkhdAtom*>(track->GetTrakAtom()->GetChild(AP4_ATOM_TYPE_TKHD)))
+ {
+ size.cx = tkhd->GetWidth()>>16;
+ size.cy = tkhd->GetHeight()>>16;
+ }
+
+ const AP4_Byte* pal = di.GetData();
+ CAtlList<CStringA> sl;
+ for(int i = 0; i < 16*4; i += 4)
+ {
+ BYTE y = (pal[i+1]-16)*255/219;
+ BYTE u = pal[i+2];
+ BYTE v = pal[i+3];
+ BYTE r = (BYTE)min(max(1.0*y + 1.4022*(v-128), 0), 255);
+ BYTE g = (BYTE)min(max(1.0*y - 0.3456*(u-128) - 0.7145*(v-128), 0), 255);
+ BYTE b = (BYTE)min(max(1.0*y + 1.7710*(u-128), 0) , 255);
+ CStringA str;
+ str.Format("%02x%02x%02x", r, g, b);
+ sl.AddTail(str);
+ }
+
+ CStringA hdr;
+ hdr.Format(
+ "# VobSub index file, v7 (do not modify this line!)\n"
+ "size: %dx%d\n"
+ "palette: %s\n",
+ size.cx, size.cy,
+ Implode(sl, ','));
+
+ mt.majortype = MEDIATYPE_Subtitle;
+ mt.subtype = MEDIASUBTYPE_VOBSUB;
+ mt.formattype = FORMAT_SubtitleInfo;
+ SUBTITLEINFO* si = (SUBTITLEINFO*)mt.AllocFormatBuffer(sizeof(SUBTITLEINFO) + hdr.GetLength());
+ memset(si, 0, mt.FormatLength());
+ si->dwOffset = sizeof(SUBTITLEINFO);
+ strcpy_s(si->IsoLang, countof(si->IsoLang), CStringA(TrackLanguage));
+ wcscpy_s(si->TrackName, countof(si->TrackName), TrackName);
+ memcpy(si + 1, (LPCSTR)hdr, hdr.GetLength());
+ mts.Add(mt);
+ }
+ break;
+ }
+
+ if(mt.subtype == GUID_NULL)
+ {
+ TRACE(_T("Unknown audio OBI: %02x\n"), system_desc->GetObjectTypeId());
+ }
+ }
+ else if(desc->GetType() == AP4_SampleDescription::TYPE_AVC)
+ {
+ AP4_AvcSampleDescription* avc1 = dynamic_cast<AP4_AvcSampleDescription*>(desc);
+
+ const AP4_DataBuffer& di = avc1->GetRawBytes();
+
+ const AP4_Byte* data = di.GetData();
+ AP4_Size size = di.GetDataSize();
+
+ mt.majortype = MEDIATYPE_Video;
+ mt.subtype = FOURCCMap('1cva');
+ mt.formattype = FORMAT_MPEG2Video;
+
+ MPEG2VIDEOINFO* vih = (MPEG2VIDEOINFO*)mt.AllocFormatBuffer(FIELD_OFFSET(MPEG2VIDEOINFO, dwSequenceHeader) + size - 7);
+ memset(vih, 0, mt.FormatLength());
+ vih->hdr.bmiHeader.biSize = sizeof(vih->hdr.bmiHeader);
+ vih->hdr.bmiHeader.biWidth = (LONG)avc1->GetWidth();
+ vih->hdr.bmiHeader.biHeight = (LONG)avc1->GetHeight();
+ vih->hdr.bmiHeader.biCompression = '1cva';
+ vih->hdr.bmiHeader.biPlanes = 1;
+ vih->hdr.bmiHeader.biBitCount = 24;
+ vih->hdr.dwPictAspectRatioX = vih->hdr.bmiHeader.biWidth;
+ vih->hdr.dwPictAspectRatioY = vih->hdr.bmiHeader.biHeight;
+ if (item->GetData()->GetSampleCount() > 1)
+ vih->hdr.AvgTimePerFrame = MulDiv(item->GetData()->GetDurationMs(), 10000, item->GetData()->GetSampleCount()-1);
+ vih->dwProfile = data[1];
+ vih->dwLevel = data[3];
+ vih->dwFlags = (data[4] & 3) + 1;
+
+ vih->cbSequenceHeader = 0;
+
+ BYTE* src = (BYTE*)data + 5;
+ BYTE* dst = (BYTE*)vih->dwSequenceHeader;
+
+ BYTE* src_end = (BYTE*)data + size;
+ BYTE* dst_end = (BYTE*)vih->dwSequenceHeader + size;
+
+ for(int i = 0; i < 2; i++)
+ {
+ for(int n = *src++ & 0x1f; n > 0; n--)
+ {
+ int len = ((src[0] << 8) | src[1]) + 2;
+ if(src + len > src_end || dst + len > dst_end) {ASSERT(0); break;}
+ memcpy(dst, src, len);
+ src += len;
+ dst += len;
+ vih->cbSequenceHeader += len;
+ }
+ }
+
+ mts.Add(mt);
+
+ mt.subtype = FOURCCMap(vih->hdr.bmiHeader.biCompression = '1CVA');
+ mts.Add(mt);
+ }
+ }
+ if(AP4_StsdAtom* stsd = dynamic_cast<AP4_StsdAtom*>(
+ track->GetTrakAtom()->FindChild("mdia/minf/stbl/stsd")))
+ {
+
+ for(AP4_List<AP4_Atom>::Item* item = stsd->GetChildren().FirstItem();
+ item;
+ item = item->GetNext())
+ {
+ AP4_Atom* atom = item->GetData();
+ AP4_DataBuffer db;
+
+ GetDataBuffer (atom, db);
+
+ AP4_Atom::Type type = atom->GetType();
+
+ if((type & 0xffff0000) == AP4_ATOM_TYPE('m', 's', 0, 0))
+ {
+ type &= 0xffff;
+ }
+ else if(type == AP4_ATOM_TYPE__MP3)
+ {
+ type = 0x0055;
+ }
+ else if((type == AP4_ATOM_TYPE_AC_3) || (type == AP4_ATOM_TYPE_SAC3))
+ {
+ type = 0x2000;
+ }
+ else
+ {
+ type =
+ ((type >> 24) & 0x000000ff) |
+ ((type >> 8) & 0x0000ff00) |
+ ((type << 8) & 0x00ff0000) |
+ ((type << 24) & 0xff000000);
+ }
+
+ if(AP4_VisualSampleEntry* vse = dynamic_cast<AP4_VisualSampleEntry*>(atom))
+ {
+ mt.majortype = MEDIATYPE_Video;
+ mt.subtype = FOURCCMap(type);
+ mt.formattype = FORMAT_VideoInfo;
+ vih = (VIDEOINFOHEADER*)mt.AllocFormatBuffer(sizeof(VIDEOINFOHEADER)+db.GetDataSize());
+ memset(vih, 0, mt.FormatLength());
+ vih->bmiHeader.biSize = sizeof(vih->bmiHeader);
+ vih->bmiHeader.biWidth = (LONG)vse->GetWidth();
+ vih->bmiHeader.biHeight = (LONG)vse->GetHeight();
+ vih->bmiHeader.biCompression = type;
+ memcpy(vih+1, db.GetData(), db.GetDataSize());
+ mts.Add(mt);
+
+ char buff[5];
+ memcpy(buff, &type, 4);
+ buff[4] = 0;
+
+ strlwr((char*)&buff);
+ AP4_Atom::Type typelwr = *(AP4_Atom::Type*)buff;
+
+ if(typelwr != type)
+ {
+ mt.subtype = FOURCCMap(vih->bmiHeader.biCompression = typelwr);
+ mts.Add(mt);
+ }
+
+ strupr((char*)&buff);
+ AP4_Atom::Type typeupr = *(AP4_Atom::Type*)buff;
+
+ if(typeupr != type)
+ {
+ mt.subtype = FOURCCMap(vih->bmiHeader.biCompression = typeupr);
+ mts.Add(mt);
+ }
+
+ break;
+ }
+ else if(AP4_AudioSampleEntry* ase = dynamic_cast<AP4_AudioSampleEntry*>(atom))
+ {
+ mt.majortype = MEDIATYPE_Audio;
+ mt.subtype = FOURCCMap(type);
+ mt.formattype = FORMAT_WaveFormatEx;
+ wfe = (WAVEFORMATEX*)mt.AllocFormatBuffer(sizeof(WAVEFORMATEX) + db.GetDataSize());
+ memset(wfe, 0, mt.FormatLength());
+ if(!(type & 0xffff0000)) wfe->wFormatTag = (WORD)type;
+ wfe->nSamplesPerSec = ase->GetSampleRate();
+ wfe->nChannels = ase->GetChannelCount();
+ wfe->wBitsPerSample = ase->GetSampleSize();
+ wfe->nBlockAlign = ase->GetBytesPerFrame();
+ wfe->cbSize = db.GetDataSize();
+ memcpy(wfe+1, db.GetData(), db.GetDataSize());
+ mts.Add(mt);
+ break;
+ }
+
+ else if(dynamic_cast<AP4_TextSampleEntry*>(atom)
+ || dynamic_cast<AP4_Tx3gSampleEntry*>(atom))
+ {
+ mt.majortype = MEDIATYPE_Subtitle;
+ mt.subtype = MEDIASUBTYPE_ASS2;
+ mt.formattype = FORMAT_SubtitleInfo;
+ CStringA hdr;
+ hdr.Format(
+ "[Script Info]\n"
+ "ScriptType: v4.00++\n"
+ "ScaledBorderAndShadow: yes\n"
+ "PlayResX: %d\n"
+ "PlayResY: %d\n"
+ "[V4++ Styles]\n"
+ "Style: Text,Arial,12,&H00ffffff,&H0000ffff,&H00000000,&H80000000,0,0,0,0,100,100,0,0.00,3,0,0,2,0,0,0,0,1,1\n",
+ // "Style: Text,Arial,12,&H00ffffff,&H0000ffff,&H00000000,&H80000000,0,0,0,0,100,100,0,0.00,1,0,0,2,0,0,0,0,1,1\n",
+ m_framesize.cx,
+ m_framesize.cy);
+ SUBTITLEINFO* si = (SUBTITLEINFO*)mt.AllocFormatBuffer(sizeof(SUBTITLEINFO) + hdr.GetLength());
+ memset(si, 0, mt.FormatLength());
+ si->dwOffset = sizeof(SUBTITLEINFO);
+ strcpy_s(si->IsoLang, countof(si->IsoLang), CStringA(TrackLanguage));
+ wcscpy_s(si->TrackName, countof(si->TrackName), TrackName);
+ memcpy(si + 1, (LPCSTR)hdr, hdr.GetLength());
+ mts.Add(mt);
+ }
+
+ }
+ }
+
+ if(mts.IsEmpty()) continue;
+
+ REFERENCE_TIME rtDuration = 10000i64 * track->GetDurationMs();
+ if(m_rtDuration < rtDuration) m_rtDuration = rtDuration;
+
+ DWORD id = track->GetId();
+
+ CStringW name, lang;
+ name.Format(L"Output %d", id);
+
+ if(!TrackName.IsEmpty())
+ {
+ name = TrackName;
+ }
+
+ if(!TrackLanguage.IsEmpty())
+ {
+ if(TrackLanguage != L"und") name += " (" + TrackLanguage + ")";
+ }
+
+ for(int i = 0, j = mts.GetCount(); i < j; i++)
+ {
+ BITMAPINFOHEADER bih;
+ if(ExtractBIH(&mts[i], &bih))
+ {
+ m_framesize.cx = bih.biWidth;
+ m_framesize.cy = abs(bih.biHeight);
+ }
+ }
+
+ CAutoPtr<CBaseSplitterOutputPin> pPinOut(DNew CBaseSplitterOutputPin(mts, name, this, this, &hr));
+
+ if(!TrackName.IsEmpty()) pPinOut->SetProperty(L"NAME", TrackName);
+ if(!TrackLanguage.IsEmpty()) pPinOut->SetProperty(L"LANG", CStringW(TrackLanguage));
+
+ EXECUTE_ASSERT(SUCCEEDED(AddOutputPin(id, pPinOut)));
+
+ m_trackpos[id] = trackpos();
+
+ if(mts.GetCount() == 1 && mts[0].subtype == MEDIASUBTYPE_ASS2)
+ {
+ LPCWSTR postfix = L" (plain text)";
+
+ mts[0].subtype = MEDIASUBTYPE_UTF8;
+
+ SUBTITLEINFO* si = (SUBTITLEINFO*)mts[0].ReallocFormatBuffer(sizeof(SUBTITLEINFO));
+ wcscat(si->TrackName, postfix);
+
+ id ^= 0x80402010; // FIXME: until fixing, let's hope there won't be another track like this...
+
+ CAutoPtr<CBaseSplitterOutputPin> pPinOut(DNew CBaseSplitterOutputPin(mts, name + postfix, this, this, &hr));
+
+ if(!TrackName.IsEmpty()) pPinOut->SetProperty(L"NAME", TrackName + postfix);
+ if(!TrackLanguage.IsEmpty()) pPinOut->SetProperty(L"LANG", CStringW(TrackLanguage));
+
+ EXECUTE_ASSERT(SUCCEEDED(AddOutputPin(id, pPinOut)));
+ }
+ }
+
+ if(AP4_ChplAtom* chpl = dynamic_cast<AP4_ChplAtom*>(movie->GetMoovAtom()->FindChild("udta/chpl")))
+ {
+ AP4_Array<AP4_ChplAtom::AP4_Chapter>& chapters = chpl->GetChapters();
+
+ for(AP4_Cardinal i = 0; i < chapters.ItemCount(); i++)
+ {
+ AP4_ChplAtom::AP4_Chapter& chapter = chapters[i];
+ ChapAppend(chapter.Time, UTF8To16(ConvertMBCS(chapter.Name.GetChars(), ANSI_CHARSET, CP_UTF8))); // this is b0rked, thx to nero :P
+ }
+
+ ChapSort();
+ }
+
+ if(AP4_ContainerAtom* ilst = dynamic_cast<AP4_ContainerAtom*>(movie->GetMoovAtom()->FindChild("udta/meta/ilst")))
+ {
+ CStringW title, artist, writer, album, year, appl, desc, gen, track;
+
+ for(AP4_List<AP4_Atom>::Item* item = ilst->GetChildren().FirstItem();
+ item;
+ item = item->GetNext())
+ {
+ if(AP4_ContainerAtom* atom = dynamic_cast<AP4_ContainerAtom*>(item->GetData()))
+ {
+ if(AP4_DataAtom* data = dynamic_cast<AP4_DataAtom*>(atom->GetChild(AP4_ATOM_TYPE_DATA)))
+ {
+ // TODO : BENTOMIGRATION
+ //const AP4_DataBuffer* db = data->GetData();
+
+ //if(atom->GetType() == AP4_ATOM_TYPE_TRKN)
+ //{
+ // if(db->GetDataSize() >= 4)
+ // {
+ // unsigned short n = (db->GetData()[2] << 8) | db->GetData()[3];
+ // if(n > 0 && n < 100) track.Format(L"%02d", n);
+ // else if(n >= 100) track.Format(L"%d", n);
+ // }
+ //}
+ //else
+ //{
+ // CStringW str = UTF8To16(CStringA((LPCSTR)db->GetData(), db->GetDataSize()));
+
+ // switch(atom->GetType())
+ // {
+ // case AP4_ATOM_TYPE_NAM: title = str; break;
+ // case AP4_ATOM_TYPE_ART: artist = str; break;
+ // case AP4_ATOM_TYPE_WRT: writer = str; break;
+ // case AP4_ATOM_TYPE_ALB: album = str; break;
+ // case AP4_ATOM_TYPE_DAY: year = str; break;
+ // case AP4_ATOM_TYPE_TOO: appl = str; break;
+ // case AP4_ATOM_TYPE_CMT: desc = str; break;
+ // case AP4_ATOM_TYPE_GEN: gen = str; break;
+ // }
+ //}
+ }
+ }
+ }
+
+ if(!title.IsEmpty())
+ {
+ if(!track.IsEmpty()) title = track + L" - " + title;
+ if(!album.IsEmpty()) title = album + L" - " + title;
+ if(!year.IsEmpty()) title += L" - " + year;
+ if(!gen.IsEmpty()) title += L" - " + gen;
+ SetProperty(L"TITL", title);
+ }
+
+ if(!artist.IsEmpty()) SetProperty(L"AUTH", artist);
+ else if(!writer.IsEmpty()) SetProperty(L"AUTH", writer);
+
+ if(!appl.IsEmpty()) SetProperty(L"APPL", appl);
+
+ if(!desc.IsEmpty()) SetProperty(L"DESC", desc);
+ }
+ }
+
+ m_rtNewStop = m_rtStop = m_rtDuration;
+
+ return m_pOutputs.GetCount() > 0 ? S_OK : E_FAIL;
}
bool CMP4SplitterFilter::DemuxInit()
{
- AP4_Movie* movie = (AP4_Movie*)m_pFile->GetMovie();
+ AP4_Movie* movie = (AP4_Movie*)m_pFile->GetMovie();
- POSITION pos = m_trackpos.GetStartPosition();
- while(pos)
- {
- CAtlMap<AP4_Ordinal, trackpos>::CPair* pPair = m_trackpos.GetNext(pos);
+ POSITION pos = m_trackpos.GetStartPosition();
+ while(pos)
+ {
+ CAtlMap<AP4_Ordinal, trackpos>::CPair* pPair = m_trackpos.GetNext(pos);
- pPair->m_value.index = 0;
- pPair->m_value.ts = 0;
+ pPair->m_value.index = 0;
+ pPair->m_value.ts = 0;
- AP4_Track* track = movie->GetTrack(pPair->m_key);
+ AP4_Track* track = movie->GetTrack(pPair->m_key);
- AP4_Sample sample;
- if(AP4_SUCCEEDED(track->GetSample(0, sample)))
- pPair->m_value.ts = sample.GetCts();
- }
+ AP4_Sample sample;
+ if(AP4_SUCCEEDED(track->GetSample(0, sample)))
+ pPair->m_value.ts = sample.GetCts();
+ }
- return true;
+ return true;
}
void CMP4SplitterFilter::DemuxSeek(REFERENCE_TIME rt)
{
- REFERENCE_TIME ts = (rt / 10000);
-
- AP4_Movie* movie = (AP4_Movie*)m_pFile->GetMovie();
-
- POSITION pos = m_trackpos.GetStartPosition();
- while(pos)
- {
- CAtlMap<AP4_Ordinal, trackpos>::CPair* pPair = m_trackpos.GetNext(pos);
-
- AP4_Track* track = movie->GetTrack(pPair->m_key);
-
- if(AP4_FAILED(track->GetSampleIndexForTimeStampMs(ts, pPair->m_value.index)))
- pPair->m_value.index = 0;
-
- AP4_Sample sample;
- if(AP4_SUCCEEDED(track->GetSample(pPair->m_value.index, sample)))
- pPair->m_value.ts = sample.GetCts();
-
- // FIXME: slow search & stss->m_Entries is private
-
- if(AP4_StssAtom* stss = dynamic_cast<AP4_StssAtom*>(track->GetTrakAtom()->FindChild("mdia/minf/stbl/stss")))
- {
- const AP4_Array<AP4_UI32>& Entries = stss->GetEntries();
- if(Entries.ItemCount() > 0)
- {
- AP4_Cardinal i = -1;
- while(++i < Entries.ItemCount() && Entries[i] - 1 <= pPair->m_value.index);
- if(i > 0) i--;
- pPair->m_value.index = Entries[i] - 1;
- }
- }
- }
+ REFERENCE_TIME ts = (rt / 10000);
+
+ AP4_Movie* movie = (AP4_Movie*)m_pFile->GetMovie();
+
+ POSITION pos = m_trackpos.GetStartPosition();
+ while(pos)
+ {
+ CAtlMap<AP4_Ordinal, trackpos>::CPair* pPair = m_trackpos.GetNext(pos);
+
+ AP4_Track* track = movie->GetTrack(pPair->m_key);
+
+ if(AP4_FAILED(track->GetSampleIndexForTimeStampMs(ts, pPair->m_value.index)))
+ pPair->m_value.index = 0;
+
+ AP4_Sample sample;
+ if(AP4_SUCCEEDED(track->GetSample(pPair->m_value.index, sample)))
+ pPair->m_value.ts = sample.GetCts();
+
+ // FIXME: slow search & stss->m_Entries is private
+
+ if(AP4_StssAtom* stss = dynamic_cast<AP4_StssAtom*>(track->GetTrakAtom()->FindChild("mdia/minf/stbl/stss")))
+ {
+ const AP4_Array<AP4_UI32>& Entries = stss->GetEntries();
+ if(Entries.ItemCount() > 0)
+ {
+ AP4_Cardinal i = -1;
+ while(++i < Entries.ItemCount() && Entries[i]-1 <= pPair->m_value.index);
+ if(i > 0) i--;
+ pPair->m_value.index = Entries[i]-1;
+ }
+ }
+ }
}
-struct SSACharacter
-{
- CString pre, post;
- WCHAR c;
-};
+struct SSACharacter {CString pre, post; WCHAR c;};
static CStringW ConvertTX3GToSSA(
- CStringW str,
- const AP4_Tx3gSampleEntry::AP4_Tx3gDescription& desc,
- CStringW font,
- const AP4_Byte* mods,
- int size,
- CSize framesize,
- CPoint translation,
- int durationms,
- CRect& rbox)
+ CStringW str,
+ const AP4_Tx3gSampleEntry::AP4_Tx3gDescription& desc,
+ CStringW font,
+ const AP4_Byte* mods,
+ int size,
+ CSize framesize,
+ CPoint translation,
+ int durationms,
+ CRect& rbox)
{
- int str_len = str.GetLength();
-
- SSACharacter* chars = DNew SSACharacter[str_len];
- for(int i = 0; i < str_len; i++) chars[i].c = str[i];
- str.Empty();
-
- //
-
- rbox.SetRect(desc.TextBox.Left, desc.TextBox.Top, desc.TextBox.Right, desc.TextBox.Bottom);
-
- int align = 2;
- signed char h = (signed char)desc.HorizontalJustification;
- signed char v = (signed char)desc.VerticalJustification;
- if(h == 0 && v < 0) align = 1;
- else if(h > 0 && v < 0) align = 2;
- else if(h < 0 && v < 0) align = 3;
- else if(h == 0 && v > 0) align = 4;
- else if(h > 0 && v > 0) align = 5;
- else if(h < 0 && v > 0) align = 6;
- else if(h == 0 && v == 0) align = 7;
- else if(h > 0 && v == 0) align = 8;
- else if(h < 0 && v == 0) align = 9;
- str.Format(L"{\\an%d}%s", align, CStringW(str));
-
- if(!font.CompareNoCase(L"serif")) font = L"Times New Roman";
- else if(!font.CompareNoCase(L"sans-serif")) font = L"Arial";
- else if(!font.CompareNoCase(L"monospace")) font = L"Courier New";
- str.Format(L"{\\fn%s}%s", font, CStringW(str));
-
- const AP4_Byte* fclr = (const AP4_Byte*)&desc.Style.Font.Color;
-
- CStringW font_color;
- font_color.Format(L"{\\1c%02x%02x%02x\\1a%02x}", fclr[2], fclr[1], fclr[0], 255 - fclr[3]);
- str = font_color + str;
-
- str.Format(L"%s{\\2c%02x%02x%02x\\2a%02x}", CString(str), fclr[2], fclr[1], fclr[0], 255 - fclr[3]);
-
- CStringW font_size;
- font_size.Format(L"{\\fs%d}", desc.Style.Font.Size);
- str = font_size + str;
-
- CStringW font_flags;
- font_flags.Format(L"{\\b%d\\i%d\\u%d}",
- (desc.Style.Font.Face & 1) ? 1 : 0,
- (desc.Style.Font.Face & 2) ? 1 : 0,
- (desc.Style.Font.Face & 4) ? 1 : 0);
- str = font_flags + str;
-
- //
-
- const AP4_Byte* hclr = (const AP4_Byte*)&desc.BackgroundColor;
-
- while(size > 8)
- {
- DWORD tag_size = (mods[0] << 24) | (mods[1] << 16) | (mods[2] << 8) | (mods[3]);
- mods += 4;
- DWORD tag = (mods[0] << 24) | (mods[1] << 16) | (mods[2] << 8) | (mods[3]);
- mods += 4;
-
- size -= tag_size;
- tag_size -= 8;
- const AP4_Byte* next = mods + tag_size;
-
- if(tag == 'styl')
- {
- WORD styl_count = (mods[0] << 8) | (mods[1]);
- mods += 2;
-
- while(styl_count-- > 0)
- {
- WORD start = (mods[0] << 8) | (mods[1]);
- mods += 2;
- WORD end = (mods[0] << 8) | (mods[1]);
- mods += 2;
- WORD font_id = (mods[0] << 8) | (mods[1]);
- mods += 2;
- WORD flags = mods[0];
- mods += 1;
- WORD size = mods[0];
- mods += 1;
- const AP4_Byte* color = mods;
- mods += 4;
-
- if(end > str_len) end = str_len;
-
- if(start < end)
- {
- CStringW s;
-
- s.Format(L"{\\1c%02x%02x%02x\\1a%02x}", color[2], color[1], color[0], 255 - color[3]);
- chars[start].pre += s;
- chars[end-1].post += font_color;
-
- s.Format(L"{\\fs%d}", size);
- chars[start].pre += s;
- chars[end-1].post += font_size;
-
- s.Format(L"{\\b%d\\i%d\\u%d}", (flags & 1) ? 1 : 0, (flags & 2) ? 1 : 0, (flags & 4) ? 1 : 0);
- chars[start].pre += s;
- chars[end-1].post += font_flags;
- }
- }
- }
- else if(tag == 'hclr')
- {
- hclr = mods;
- }
- else if(tag == 'hlit')
- {
- WORD start = (mods[0] << 8) | (mods[1]);
- mods += 2;
- WORD end = (mods[0] << 8) | (mods[1]);
- mods += 2;
-
- if(end > str_len) end = str_len;
-
- if(start < end)
- {
- CStringW s;
-
- s.Format(L"{\\3c%02x%02x%02x\\3a%02x}", hclr[2], hclr[1], hclr[0], 255 - hclr[3]);
- chars[start].pre += s;
- chars[end-1].post += font_color;
-
- chars[start].pre += L"{\\bord0.1}";
- chars[end-1].post += L"{\\bord}";
- }
- }
- else if(tag == 'blnk')
- {
- WORD start = (mods[0] << 8) | (mods[1]);
- mods += 2;
- WORD end = (mods[0] << 8) | (mods[1]);
- mods += 2;
-
- if(end > str_len) end = str_len;
-
- if(start < end)
- {
- // cheap...
-
- for(int i = 0, alpha = 255; i < durationms; i += 750, alpha = 255 - alpha)
- {
- CStringW s;
- s.Format(L"{\\t(%d, %d, \\alpha&H%02x&)}", i, i + 750, alpha);
- chars[start].pre += s;
- }
-
- chars[end-1].post += L"{\\alpha}";
- }
- }
- else if(tag == 'tbox')
- {
- rbox.top = (mods[0] << 8) | (mods[1]);
- mods += 2;
- rbox.left = (mods[0] << 8) | (mods[1]);
- mods += 2;
- rbox.bottom = (mods[0] << 8) | (mods[1]);
- mods += 2;
- rbox.right = (mods[0] << 8) | (mods[1]);
- mods += 2;
- }
- else if(tag == 'krok' && !(desc.DisplayFlags & 0x800))
- {
- DWORD start_time = (mods[0] << 24) | (mods[1] << 16) | (mods[2] << 8) | (mods[3]);
- mods += 4;
- WORD krok_count = (mods[0] << 8) | (mods[1]);
- mods += 2;
-
- while(krok_count-- > 0)
- {
- DWORD end_time = (mods[0] << 24) | (mods[1] << 16) | (mods[2] << 8) | (mods[3]);
- mods += 4;
- WORD start = (mods[0] << 8) | (mods[1]);
- mods += 2;
- WORD end = (mods[0] << 8) | (mods[1]);
- mods += 2;
-
- if(end > str_len) end = str_len;
-
- if(start < end)
- {
- CStringW s;
-
- s.Format(L"{\\kt%d\\kf%d}", start_time / 10, (end_time - start_time) / 10);
- chars[start].pre += s;
- s.Format(L"{\\1c%02x%02x%02x\\1a%02x}", hclr[2], hclr[1], hclr[0], 255 - hclr[3]);
- chars[start].pre += s;
- chars[end-1].post += L"{\\kt}" + font_color;
- }
-
- start_time = end_time;
- }
- }
-
- mods = next;
- }
-
- // continous karaoke
-
- if(desc.DisplayFlags & 0x800)
- {
- CStringW s;
-
- s.Format(L"{\\1c%02x%02x%02x\\1a%02x}", hclr[2], hclr[1], hclr[0], 255 - hclr[3]);
- str += s;
-
- int breaks = 0;
-
- for(int i = 0, j = 0; i <= str_len; i++)
- {
- if(chars[i].c == '\n' /*|| chars[i].c == ' '*/)
- {
- breaks++;
- }
- }
-
- if(str_len > breaks)
- {
- float dur = (float)max(durationms - 500, 0) / 10;
-
- for(int i = 0, j = 0; i <= str_len; i++)
- {
- if(i == str_len || chars[i].c == '\n' /*|| chars[i].c == ' '*/)
- {
- s.Format(L"{\\kf%d}", (int)(dur *(i - j) / (str_len - breaks)));
- chars[j].pre += s;
- j = i + 1;
- }
- }
- }
- }
-
- //
-
- for(int i = 0; i < str_len; i++)
- {
- str += chars[i].pre;
- str += chars[i].c;
- if(desc.DisplayFlags & 0x20000) str += L"\\N";
- str += chars[i].post;
- }
-
- delete [] chars;
-
- //
-
- if(rbox.IsRectEmpty()) rbox.SetRect(0, 0, framesize.cx, framesize.cy);
- rbox.OffsetRect(translation);
-
- CRect rbox2 = rbox;
- rbox2.DeflateRect(2, 2);
-
- CRect r(0, 0, 0, 0);
- if(rbox2.Height() > 0)
- {
- r.top = rbox2.top;
- r.bottom = framesize.cy - rbox2.bottom;
- }
- if(rbox2.Width() > 0)
- {
- r.left = rbox2.left;
- r.right = framesize.cx - rbox2.right;
- }
-
- CStringW hdr;
- hdr.Format(L"0,0,Text,,%d,%d,%d,%d,,{\\clip(%d,%d,%d,%d)}",
- r.left, r.right, r.top, r.bottom,
- rbox.left, rbox.top, rbox.right, rbox.bottom);
-
- //
-
- return hdr + str;
+ int str_len = str.GetLength();
+
+ SSACharacter* chars = DNew SSACharacter[str_len];
+ for(int i = 0; i < str_len; i++) chars[i].c = str[i];
+ str.Empty();
+
+ //
+
+ rbox.SetRect(desc.TextBox.Left, desc.TextBox.Top, desc.TextBox.Right, desc.TextBox.Bottom);
+
+ int align = 2;
+ signed char h = (signed char)desc.HorizontalJustification;
+ signed char v = (signed char)desc.VerticalJustification;
+ if(h == 0 && v < 0) align = 1;
+ else if(h > 0 && v < 0) align = 2;
+ else if(h < 0 && v < 0) align = 3;
+ else if(h == 0 && v > 0) align = 4;
+ else if(h > 0 && v > 0) align = 5;
+ else if(h < 0 && v > 0) align = 6;
+ else if(h == 0 && v == 0) align = 7;
+ else if(h > 0 && v == 0) align = 8;
+ else if(h < 0 && v == 0) align = 9;
+ str.Format(L"{\\an%d}%s", align, CStringW(str));
+
+ if(!font.CompareNoCase(L"serif")) font = L"Times New Roman";
+ else if(!font.CompareNoCase(L"sans-serif")) font = L"Arial";
+ else if(!font.CompareNoCase(L"monospace")) font = L"Courier New";
+ str.Format(L"{\\fn%s}%s", font, CStringW(str));
+
+ const AP4_Byte* fclr = (const AP4_Byte*)&desc.Style.Font.Color;
+
+ CStringW font_color;
+ font_color.Format(L"{\\1c%02x%02x%02x\\1a%02x}", fclr[2], fclr[1], fclr[0], 255 - fclr[3]);
+ str = font_color + str;
+
+ str.Format(L"%s{\\2c%02x%02x%02x\\2a%02x}", CString(str), fclr[2], fclr[1], fclr[0], 255 - fclr[3]);
+
+ CStringW font_size;
+ font_size.Format(L"{\\fs%d}", desc.Style.Font.Size);
+ str = font_size + str;
+
+ CStringW font_flags;
+ font_flags.Format(L"{\\b%d\\i%d\\u%d}",
+ (desc.Style.Font.Face&1) ? 1 : 0,
+ (desc.Style.Font.Face&2) ? 1 : 0,
+ (desc.Style.Font.Face&4) ? 1 : 0);
+ str = font_flags + str;
+
+ //
+
+ const AP4_Byte* hclr = (const AP4_Byte*)&desc.BackgroundColor;
+
+ while(size > 8)
+ {
+ DWORD tag_size = (mods[0]<<24)|(mods[1]<<16)|(mods[2]<<8)|(mods[3]); mods += 4;
+ DWORD tag = (mods[0]<<24)|(mods[1]<<16)|(mods[2]<<8)|(mods[3]); mods += 4;
+
+ size -= tag_size;
+ tag_size -= 8;
+ const AP4_Byte* next = mods + tag_size;
+
+ if(tag == 'styl')
+ {
+ WORD styl_count = (mods[0]<<8)|(mods[1]); mods += 2;
+
+ while(styl_count-- > 0)
+ {
+ WORD start = (mods[0]<<8)|(mods[1]); mods += 2;
+ WORD end = (mods[0]<<8)|(mods[1]); mods += 2;
+ WORD font_id = (mods[0]<<8)|(mods[1]); mods += 2;
+ WORD flags = mods[0]; mods += 1;
+ WORD size = mods[0]; mods += 1;
+ const AP4_Byte* color = mods; mods += 4;
+
+ if(end > str_len) end = str_len;
+
+ if(start < end)
+ {
+ CStringW s;
+
+ s.Format(L"{\\1c%02x%02x%02x\\1a%02x}", color[2], color[1], color[0], 255 - color[3]);
+ chars[start].pre += s;
+ chars[end-1].post += font_color;
+
+ s.Format(L"{\\fs%d}", size);
+ chars[start].pre += s;
+ chars[end-1].post += font_size;
+
+ s.Format(L"{\\b%d\\i%d\\u%d}", (flags&1) ? 1 : 0, (flags&2) ? 1 : 0, (flags&4) ? 1 : 0);
+ chars[start].pre += s;
+ chars[end-1].post += font_flags;
+ }
+ }
+ }
+ else if(tag == 'hclr')
+ {
+ hclr = mods;
+ }
+ else if(tag == 'hlit')
+ {
+ WORD start = (mods[0]<<8)|(mods[1]); mods += 2;
+ WORD end = (mods[0]<<8)|(mods[1]); mods += 2;
+
+ if(end > str_len) end = str_len;
+
+ if(start < end)
+ {
+ CStringW s;
+
+ s.Format(L"{\\3c%02x%02x%02x\\3a%02x}", hclr[2], hclr[1], hclr[0], 255 - hclr[3]);
+ chars[start].pre += s;
+ chars[end-1].post += font_color;
+
+ chars[start].pre += L"{\\bord0.1}";
+ chars[end-1].post += L"{\\bord}";
+ }
+ }
+ else if(tag == 'blnk')
+ {
+ WORD start = (mods[0]<<8)|(mods[1]); mods += 2;
+ WORD end = (mods[0]<<8)|(mods[1]); mods += 2;
+
+ if(end > str_len) end = str_len;
+
+ if(start < end)
+ {
+ // cheap...
+
+ for(int i = 0, alpha = 255; i < durationms; i += 750, alpha = 255 - alpha)
+ {
+ CStringW s;
+ s.Format(L"{\\t(%d, %d, \\alpha&H%02x&)}", i, i + 750, alpha);
+ chars[start].pre += s;
+ }
+
+ chars[end-1].post += L"{\\alpha}";
+ }
+ }
+ else if(tag == 'tbox')
+ {
+ rbox.top = (mods[0]<<8)|(mods[1]); mods += 2;
+ rbox.left = (mods[0]<<8)|(mods[1]); mods += 2;
+ rbox.bottom = (mods[0]<<8)|(mods[1]); mods += 2;
+ rbox.right = (mods[0]<<8)|(mods[1]); mods += 2;
+ }
+ else if(tag == 'krok' && !(desc.DisplayFlags & 0x800))
+ {
+ DWORD start_time = (mods[0]<<24)|(mods[1]<<16)|(mods[2]<<8)|(mods[3]); mods += 4;
+ WORD krok_count = (mods[0]<<8)|(mods[1]); mods += 2;
+
+ while(krok_count-- > 0)
+ {
+ DWORD end_time = (mods[0]<<24)|(mods[1]<<16)|(mods[2]<<8)|(mods[3]); mods += 4;
+ WORD start = (mods[0]<<8)|(mods[1]); mods += 2;
+ WORD end = (mods[0]<<8)|(mods[1]); mods += 2;
+
+ if(end > str_len) end = str_len;
+
+ if(start < end)
+ {
+ CStringW s;
+
+ s.Format(L"{\\kt%d\\kf%d}", start_time/10, (end_time - start_time)/10);
+ chars[start].pre += s;
+ s.Format(L"{\\1c%02x%02x%02x\\1a%02x}", hclr[2], hclr[1], hclr[0], 255 - hclr[3]);
+ chars[start].pre += s;
+ chars[end-1].post += L"{\\kt}" + font_color;
+ }
+
+ start_time = end_time;
+ }
+ }
+
+ mods = next;
+ }
+
+ // continous karaoke
+
+ if(desc.DisplayFlags & 0x800)
+ {
+ CStringW s;
+
+ s.Format(L"{\\1c%02x%02x%02x\\1a%02x}", hclr[2], hclr[1], hclr[0], 255 - hclr[3]);
+ str += s;
+
+ int breaks = 0;
+
+ for(int i = 0, j = 0; i <= str_len; i++)
+ {
+ if(chars[i].c == '\n' /*|| chars[i].c == ' '*/)
+ {
+ breaks++;
+ }
+ }
+
+ if(str_len > breaks)
+ {
+ float dur = (float)max(durationms - 500, 0) / 10;
+
+ for(int i = 0, j = 0; i <= str_len; i++)
+ {
+ if(i == str_len || chars[i].c == '\n' /*|| chars[i].c == ' '*/)
+ {
+ s.Format(L"{\\kf%d}", (int)(dur * (i - j) / (str_len - breaks)));
+ chars[j].pre += s;
+ j = i+1;
+ }
+ }
+ }
+ }
+
+ //
+
+ for(int i = 0; i < str_len; i++)
+ {
+ str += chars[i].pre;
+ str += chars[i].c;
+ if(desc.DisplayFlags & 0x20000) str += L"\\N";
+ str += chars[i].post;
+ }
+
+ delete [] chars;
+
+ //
+
+ if(rbox.IsRectEmpty()) rbox.SetRect(0, 0, framesize.cx, framesize.cy);
+ rbox.OffsetRect(translation);
+
+ CRect rbox2 = rbox;
+ rbox2.DeflateRect(2, 2);
+
+ CRect r(0,0,0,0);
+ if(rbox2.Height() > 0) {r.top = rbox2.top; r.bottom = framesize.cy - rbox2.bottom;}
+ if(rbox2.Width() > 0) {r.left = rbox2.left; r.right = framesize.cx - rbox2.right;}
+
+ CStringW hdr;
+ hdr.Format(L"0,0,Text,,%d,%d,%d,%d,,{\\clip(%d,%d,%d,%d)}",
+ r.left, r.right, r.top, r.bottom,
+ rbox.left, rbox.top, rbox.right, rbox.bottom);
+
+ //
+
+ return hdr + str;
}
bool CMP4SplitterFilter::DemuxLoop()
{
- HRESULT hr = S_OK;
+ HRESULT hr = S_OK;
- AP4_Movie* movie = (AP4_Movie*)m_pFile->GetMovie();
+ AP4_Movie* movie = (AP4_Movie*)m_pFile->GetMovie();
- while(SUCCEEDED(hr) && !CheckRequest(NULL))
- {
- CAtlMap<AP4_Ordinal, trackpos>::CPair* pPairNext = NULL;
- REFERENCE_TIME rtNext = 0;
+ while(SUCCEEDED(hr) && !CheckRequest(NULL))
+ {
+ CAtlMap<AP4_Ordinal, trackpos>::CPair* pPairNext = NULL;
+ REFERENCE_TIME rtNext = 0;
- POSITION pos = m_trackpos.GetStartPosition();
- while(pos)
- {
- CAtlMap<AP4_Ordinal, trackpos>::CPair* pPair = m_trackpos.GetNext(pos);
+ POSITION pos = m_trackpos.GetStartPosition();
+ while(pos)
+ {
+ CAtlMap<AP4_Ordinal, trackpos>::CPair* pPair = m_trackpos.GetNext(pos);
- AP4_Track* track = movie->GetTrack(pPair->m_key);
+ AP4_Track* track = movie->GetTrack(pPair->m_key);
- CBaseSplitterOutputPin* pPin = GetOutputPin((DWORD)track->GetId());
- if(!pPin->IsConnected()) continue;
+ CBaseSplitterOutputPin* pPin = GetOutputPin((DWORD)track->GetId());
+ if(!pPin->IsConnected()) continue;
- REFERENCE_TIME rt = (REFERENCE_TIME)(10000000.0 / track->GetMediaTimeScale() * pPair->m_value.ts);
+ REFERENCE_TIME rt = (REFERENCE_TIME)(10000000.0 / track->GetMediaTimeScale() * pPair->m_value.ts);
- if(pPair->m_value.index < track->GetSampleCount() && (!pPairNext || rt < rtNext))
- {
- pPairNext = pPair;
- rtNext = rt;
- }
- }
+ if(pPair->m_value.index < track->GetSampleCount() && (!pPairNext || rt < rtNext))
+ {
+ pPairNext = pPair;
+ rtNext = rt;
+ }
+ }
- if(!pPairNext) break;
+ if(!pPairNext) break;
- AP4_Track* track = movie->GetTrack(pPairNext->m_key);
+ AP4_Track* track = movie->GetTrack(pPairNext->m_key);
- CBaseSplitterOutputPin* pPin = GetOutputPin((DWORD)track->GetId());
+ CBaseSplitterOutputPin* pPin = GetOutputPin((DWORD)track->GetId());
- AP4_Sample sample;
- AP4_DataBuffer data;
+ AP4_Sample sample;
+ AP4_DataBuffer data;
- if(pPin && pPin->IsConnected() && AP4_SUCCEEDED(track->ReadSample(pPairNext->m_value.index, sample, data)))
- {
- const CMediaType& mt = pPin->CurrentMediaType();
+ if(pPin && pPin->IsConnected() && AP4_SUCCEEDED(track->ReadSample(pPairNext->m_value.index, sample, data)))
+ {
+ const CMediaType& mt = pPin->CurrentMediaType();
- CAutoPtr<Packet> p(DNew Packet());
- p->TrackNumber = (DWORD)track->GetId();
- p->rtStart = (REFERENCE_TIME)(10000000.0 / track->GetMediaTimeScale() * sample.GetCts());
- p->rtStop = p->rtStart + (REFERENCE_TIME)(10000000.0 / track->GetMediaTimeScale() * sample.GetDuration());
- p->bSyncPoint = TRUE;
+ CAutoPtr<Packet> p(DNew Packet());
+ p->TrackNumber = (DWORD)track->GetId();
+ p->rtStart = (REFERENCE_TIME)(10000000.0 / track->GetMediaTimeScale() * sample.GetCts());
+ p->rtStop = p->rtStart + (REFERENCE_TIME)(10000000.0 / track->GetMediaTimeScale() * sample.GetDuration());
+ p->bSyncPoint = TRUE;
- // FIXME: slow search & stss->m_Entries is private
+ // FIXME: slow search & stss->m_Entries is private
- if(AP4_StssAtom* stss = dynamic_cast<AP4_StssAtom*>(track->GetTrakAtom()->FindChild("mdia/minf/stbl/stss")))
- {
- if(stss->GetEntries().ItemCount() > 0)
- {
- p->bSyncPoint = FALSE;
+ if(AP4_StssAtom* stss = dynamic_cast<AP4_StssAtom*>(track->GetTrakAtom()->FindChild("mdia/minf/stbl/stss")))
+ {
+ if(stss->GetEntries().ItemCount() > 0)
+ {
+ p->bSyncPoint = FALSE;
- AP4_Cardinal i = -1;
- while(++i < stss->GetEntries().ItemCount())
- if(stss->GetEntries()[i] - 1 == pPairNext->m_value.index)
- p->bSyncPoint = TRUE;
- }
- }
+ AP4_Cardinal i = -1;
+ while(++i < stss->GetEntries().ItemCount())
+ if(stss->GetEntries()[i]-1 == pPairNext->m_value.index)
+ p->bSyncPoint = TRUE;
+ }
+ }
- //
+ //
- if(track->GetType() == AP4_Track::TYPE_AUDIO && data.GetDataSize() == 1)
- {
- WAVEFORMATEX* wfe = (WAVEFORMATEX*)mt.Format();
+ if(track->GetType() == AP4_Track::TYPE_AUDIO && data.GetDataSize() == 1)
+ {
+ WAVEFORMATEX* wfe = (WAVEFORMATEX*)mt.Format();
- int nBlockAlign = 1200;
+ int nBlockAlign = 1200;
- if(wfe->nBlockAlign > 1)
- {
- nBlockAlign = wfe->nBlockAlign;
- pPairNext->m_value.index -= pPairNext->m_value.index % wfe->nBlockAlign;
- }
+ if(wfe->nBlockAlign > 1)
+ {
+ nBlockAlign = wfe->nBlockAlign;
+ pPairNext->m_value.index -= pPairNext->m_value.index % wfe->nBlockAlign;
+ }
// p->rtStop = p->rtStart;
- AP4_UI32 nAP4SampleDuration = 0;
+ AP4_UI32 nAP4SampleDuration = 0;
- int fFirst = true;
+ int fFirst = true;
- while(AP4_SUCCEEDED(track->ReadSample(pPairNext->m_value.index, sample, data)))
- {
- AP4_Size size = data.GetDataSize();
- const AP4_Byte* ptr = data.GetData();
- for(int i = 0; i < size; i++) p->Add(ptr[i]);
+ while(AP4_SUCCEEDED(track->ReadSample(pPairNext->m_value.index, sample, data)))
+ {
+ AP4_Size size = data.GetDataSize();
+ const AP4_Byte* ptr = data.GetData();
+ for(int i = 0; i < size; i++) p->Add(ptr[i]);
//int x = p->GetCount();
//if (x>4 && p->GetAt(x-4)==0x91 && p->GetAt(x-3)==0x11 && p->GetAt(x-2)==0x19 && p->GetAt(x-1)==0x90)
// printf("gotcha");
- if(fFirst)
- {
- p->rtStart = p->rtStop = (REFERENCE_TIME)(10000000.0 / track->GetMediaTimeScale() * sample.GetCts());
- fFirst = false;
- }
- nAP4SampleDuration += sample.GetDuration();
-
- if(pPairNext->m_value.index + 1 >= track->GetSampleCount() || p->GetCount() >= nBlockAlign)
- break;
-
- pPairNext->m_value.index++;
- }
-
- p->rtStop = p->rtStart + (REFERENCE_TIME)(10000000.0 / track->GetMediaTimeScale() * nAP4SampleDuration);
- }
- else if(track->GetType() == AP4_Track::TYPE_TEXT)
- {
- CStringA dlgln_bkg, dlgln_plaintext;
-
- const AP4_Byte* ptr = data.GetData();
- AP4_Size avail = data.GetDataSize();
-
- if(avail > 2)
- {
- AP4_UI16 size = (ptr[0] << 8) | ptr[1];
-
- if(size <= avail - 2)
- {
- CStringA str;
-
- if(size >= 2 && ptr[2] == 0xfe && ptr[3] == 0xff)
- {
- CStringW wstr = CStringW((LPCWSTR)&ptr[2], size / 2);
- for(int i = 0; i < wstr.GetLength(); i++) wstr.SetAt(i, ((WORD)wstr[i] >> 8) | ((WORD)wstr[i] << 8));
- str = UTF16To8(wstr);
- }
- else
- {
- str = CStringA((LPCSTR)&ptr[2], size);
- }
-
- CStringA dlgln = str;
-
- if(mt.subtype == MEDIASUBTYPE_ASS2)
- {
- AP4_SampleDescription* desc = track->GetSampleDescription(sample.GetDescriptionIndex());
-
- dlgln = "0,0,Text,,0000,0000,0000,0000,," + str;
- dlgln_plaintext = str;
-
- CPoint translation(0, 0);
- if(AP4_TkhdAtom* tkhd = dynamic_cast<AP4_TkhdAtom*>(track->GetTrakAtom()->GetChild(AP4_ATOM_TYPE_TKHD)))
- {
- float x, y;
- tkhd->GetTranslation(x, y);
- translation.SetPoint((int)x, (int)y);
- }
- }
-
- dlgln.Replace("\r", "");
- dlgln.Replace("\n", "\\N");
-
- p->SetData((LPCSTR)dlgln, dlgln.GetLength());
- }
- }
-
- if(!dlgln_bkg.IsEmpty())
- {
- CAutoPtr<Packet> p2(DNew Packet());
- p2->TrackNumber = p->TrackNumber;
- p2->rtStart = p->rtStart;
- p2->rtStop = p->rtStop;
- p2->bSyncPoint = p->bSyncPoint;
- p2->SetData((LPCSTR)dlgln_bkg, dlgln_bkg.GetLength());
- hr = DeliverPacket(p2);
- }
-
- if(!dlgln_plaintext.IsEmpty())
- {
- CAutoPtr<Packet> p2(DNew Packet());
- p2->TrackNumber = p->TrackNumber ^ 0x80402010;
- p2->rtStart = p->rtStart;
- p2->rtStop = p->rtStop;
- p2->bSyncPoint = p->bSyncPoint;
- p2->SetData((LPCSTR)dlgln_plaintext, dlgln_plaintext.GetLength());
- hr = DeliverPacket(p2);
- }
- }
- else
- {
- p->SetData(data.GetData(), data.GetDataSize());
- }
-
- hr = DeliverPacket(p);
- }
-
- {
- AP4_Sample sample;
- if(AP4_SUCCEEDED(track->GetSample(++pPairNext->m_value.index, sample)))
- pPairNext->m_value.ts = sample.GetCts();
- }
-
- }
-
- return true;
+ if(fFirst) {p->rtStart = p->rtStop = (REFERENCE_TIME)(10000000.0 / track->GetMediaTimeScale() * sample.GetCts()); fFirst = false;}
+ nAP4SampleDuration += sample.GetDuration();
+
+ if(pPairNext->m_value.index+1 >= track->GetSampleCount() || p->GetCount() >= nBlockAlign)
+ break;
+
+ pPairNext->m_value.index++;
+ }
+
+ p->rtStop = p->rtStart + (REFERENCE_TIME)(10000000.0 / track->GetMediaTimeScale() * nAP4SampleDuration);
+ }
+ else if(track->GetType() == AP4_Track::TYPE_TEXT)
+ {
+ CStringA dlgln_bkg, dlgln_plaintext;
+
+ const AP4_Byte* ptr = data.GetData();
+ AP4_Size avail = data.GetDataSize();
+
+ if(avail > 2)
+ {
+ AP4_UI16 size = (ptr[0] << 8) | ptr[1];
+
+ if(size <= avail-2)
+ {
+ CStringA str;
+
+ if(size >= 2 && ptr[2] == 0xfe && ptr[3] == 0xff)
+ {
+ CStringW wstr = CStringW((LPCWSTR)&ptr[2], size/2);
+ for(int i = 0; i < wstr.GetLength(); i++) wstr.SetAt(i, ((WORD)wstr[i] >> 8) | ((WORD)wstr[i] << 8));
+ str = UTF16To8(wstr);
+ }
+ else
+ {
+ str = CStringA((LPCSTR)&ptr[2], size);
+ }
+
+ CStringA dlgln = str;
+
+ if(mt.subtype == MEDIASUBTYPE_ASS2)
+ {
+ AP4_SampleDescription* desc = track->GetSampleDescription(sample.GetDescriptionIndex());
+
+ dlgln = "0,0,Text,,0000,0000,0000,0000,," + str;
+ dlgln_plaintext = str;
+
+ CPoint translation(0, 0);
+ if(AP4_TkhdAtom* tkhd = dynamic_cast<AP4_TkhdAtom*>(track->GetTrakAtom()->GetChild(AP4_ATOM_TYPE_TKHD)))
+ {
+ float x, y;
+ tkhd->GetTranslation(x, y);
+ translation.SetPoint((int)x, (int)y);
+ }
+ }
+
+ dlgln.Replace("\r", "");
+ dlgln.Replace("\n", "\\N");
+
+ p->SetData((LPCSTR)dlgln, dlgln.GetLength());
+ }
+ }
+
+ if(!dlgln_bkg.IsEmpty())
+ {
+ CAutoPtr<Packet> p2(DNew Packet());
+ p2->TrackNumber = p->TrackNumber;
+ p2->rtStart = p->rtStart;
+ p2->rtStop = p->rtStop;
+ p2->bSyncPoint = p->bSyncPoint;
+ p2->SetData((LPCSTR)dlgln_bkg, dlgln_bkg.GetLength());
+ hr = DeliverPacket(p2);
+ }
+
+ if(!dlgln_plaintext.IsEmpty())
+ {
+ CAutoPtr<Packet> p2(DNew Packet());
+ p2->TrackNumber = p->TrackNumber ^ 0x80402010;
+ p2->rtStart = p->rtStart;
+ p2->rtStop = p->rtStop;
+ p2->bSyncPoint = p->bSyncPoint;
+ p2->SetData((LPCSTR)dlgln_plaintext, dlgln_plaintext.GetLength());
+ hr = DeliverPacket(p2);
+ }
+ }
+ else
+ {
+ p->SetData(data.GetData(), data.GetDataSize());
+ }
+
+ hr = DeliverPacket(p);
+ }
+
+ {
+ AP4_Sample sample;
+ if(AP4_SUCCEEDED(track->GetSample(++pPairNext->m_value.index, sample)))
+ pPairNext->m_value.ts = sample.GetCts();
+ }
+
+ }
+
+ return true;
}
// IKeyFrameInfo
STDMETHODIMP CMP4SplitterFilter::GetKeyFrameCount(UINT& nKFs)
{
- CheckPointer(m_pFile, E_UNEXPECTED);
+ CheckPointer(m_pFile, E_UNEXPECTED);
- if(!m_pFile) return E_UNEXPECTED;
+ if(!m_pFile) return E_UNEXPECTED;
- AP4_Movie* movie = (AP4_Movie*)m_pFile->GetMovie();
+ AP4_Movie* movie = (AP4_Movie*)m_pFile->GetMovie();
- POSITION pos = m_trackpos.GetStartPosition();
- while(pos)
- {
- CAtlMap<AP4_Ordinal, trackpos>::CPair* pPair = m_trackpos.GetNext(pos);
+ POSITION pos = m_trackpos.GetStartPosition();
+ while(pos)
+ {
+ CAtlMap<AP4_Ordinal, trackpos>::CPair* pPair = m_trackpos.GetNext(pos);
- AP4_Track* track = movie->GetTrack(pPair->m_key);
+ AP4_Track* track = movie->GetTrack(pPair->m_key);
- if(track->GetType() != AP4_Track::TYPE_VIDEO)
- continue;
+ if(track->GetType() != AP4_Track::TYPE_VIDEO)
+ continue;
- if(AP4_StssAtom* stss = dynamic_cast<AP4_StssAtom*>(track->GetTrakAtom()->FindChild("mdia/minf/stbl/stss")))
- {
- nKFs = stss->GetEntries().ItemCount();
- return S_OK;
- }
- }
+ if(AP4_StssAtom* stss = dynamic_cast<AP4_StssAtom*>(track->GetTrakAtom()->FindChild("mdia/minf/stbl/stss")))
+ {
+ nKFs = stss->GetEntries().ItemCount();
+ return S_OK;
+ }
+ }
- return E_FAIL;
+ return E_FAIL;
}
STDMETHODIMP CMP4SplitterFilter::GetKeyFrames(const GUID* pFormat, REFERENCE_TIME* pKFs, UINT& nKFs)
{
- CheckPointer(pFormat, E_POINTER);
- CheckPointer(pKFs, E_POINTER);
- CheckPointer(m_pFile, E_UNEXPECTED);
+ CheckPointer(pFormat, E_POINTER);
+ CheckPointer(pKFs, E_POINTER);
+ CheckPointer(m_pFile, E_UNEXPECTED);
- if(*pFormat != TIME_FORMAT_MEDIA_TIME) return E_INVALIDARG;
+ if(*pFormat != TIME_FORMAT_MEDIA_TIME) return E_INVALIDARG;
- if(!m_pFile) return E_UNEXPECTED;
+ if(!m_pFile) return E_UNEXPECTED;
- AP4_Movie* movie = (AP4_Movie*)m_pFile->GetMovie();
+ AP4_Movie* movie = (AP4_Movie*)m_pFile->GetMovie();
- POSITION pos = m_trackpos.GetStartPosition();
- while(pos)
- {
- CAtlMap<AP4_Ordinal, trackpos>::CPair* pPair = m_trackpos.GetNext(pos);
+ POSITION pos = m_trackpos.GetStartPosition();
+ while(pos)
+ {
+ CAtlMap<AP4_Ordinal, trackpos>::CPair* pPair = m_trackpos.GetNext(pos);
- AP4_Track* track = movie->GetTrack(pPair->m_key);
+ AP4_Track* track = movie->GetTrack(pPair->m_key);
- if(track->GetType() != AP4_Track::TYPE_VIDEO)
- continue;
+ if(track->GetType() != AP4_Track::TYPE_VIDEO)
+ continue;
- if(AP4_StssAtom* stss = dynamic_cast<AP4_StssAtom*>(track->GetTrakAtom()->FindChild("mdia/minf/stbl/stss")))
- {
- nKFs = 0;
+ if(AP4_StssAtom* stss = dynamic_cast<AP4_StssAtom*>(track->GetTrakAtom()->FindChild("mdia/minf/stbl/stss")))
+ {
+ nKFs = 0;
- for(AP4_Cardinal i = 0; i < stss->GetEntries().ItemCount(); i++)
- {
- AP4_Sample sample;
- if(AP4_SUCCEEDED(track->GetSample(stss->GetEntries()[i] - 1, sample)))
- pKFs[nKFs++] = 10000000i64 * sample.GetCts() / track->GetMediaTimeScale();
- }
+ for(AP4_Cardinal i = 0; i < stss->GetEntries().ItemCount(); i++)
+ {
+ AP4_Sample sample;
+ if(AP4_SUCCEEDED(track->GetSample(stss->GetEntries()[i]-1, sample)))
+ pKFs[nKFs++] = 10000000i64 * sample.GetCts() / track->GetMediaTimeScale();
+ }
- return S_OK;
- }
- }
+ return S_OK;
+ }
+ }
- return E_FAIL;
+ return E_FAIL;
}
//
@@ -1323,10 +1277,10 @@ STDMETHODIMP CMP4SplitterFilter::GetKeyFrames(const GUID* pFormat, REFERENCE_TIM
//
CMP4SourceFilter::CMP4SourceFilter(LPUNKNOWN pUnk, HRESULT* phr)
- : CMP4SplitterFilter(pUnk, phr)
+ : CMP4SplitterFilter(pUnk, phr)
{
- m_clsid = __uuidof(this);
- m_pInput.Free();
+ m_clsid = __uuidof(this);
+ m_pInput.Free();
}
//
@@ -1334,315 +1288,291 @@ CMP4SourceFilter::CMP4SourceFilter(LPUNKNOWN pUnk, HRESULT* phr)
//
CMPEG4VideoSplitterFilter::CMPEG4VideoSplitterFilter(LPUNKNOWN pUnk, HRESULT* phr)
- : CBaseSplitterFilter(NAME("CMPEG4VideoSplitterFilter"), pUnk, phr, __uuidof(this))
+ : CBaseSplitterFilter(NAME("CMPEG4VideoSplitterFilter"), pUnk, phr, __uuidof(this))
{
}
void CMPEG4VideoSplitterFilter::SkipUserData()
{
- m_pFile->BitByteAlign();
- while(m_pFile->BitRead(32, true) == 0x000001b2)
- while(m_pFile->BitRead(24, true) != 0x000001)
- m_pFile->BitRead(8);
+ m_pFile->BitByteAlign();
+ while(m_pFile->BitRead(32, true) == 0x000001b2)
+ while(m_pFile->BitRead(24, true) != 0x000001)
+ m_pFile->BitRead(8);
}
HRESULT CMPEG4VideoSplitterFilter::CreateOutputs(IAsyncReader* pAsyncReader)
{
- CheckPointer(pAsyncReader, E_POINTER);
-
- HRESULT hr = E_FAIL;
-
- m_pFile.Free();
- m_pFile.Attach(DNew CBaseSplitterFileEx(pAsyncReader, hr));
- if(!m_pFile) return E_OUTOFMEMORY;
- if(FAILED(hr))
- {
- m_pFile.Free();
- return hr;
- }
-
- m_rtNewStart = m_rtCurrent = 0;
- m_rtNewStop = m_rtStop = m_rtDuration = 0;
-
- // TODO
-
- DWORD width = 0;
- DWORD height = 0;
- BYTE parx = 1;
- BYTE pary = 1;
- REFERENCE_TIME atpf = 400000;
-
- if(m_pFile->BitRead(24, true) != 0x000001)
- return E_FAIL;
-
- BYTE id;
- while(m_pFile->NextMpegStartCode(id, 1024 - m_pFile->GetPos()))
- {
- if(id == 0xb5)
- {
- BYTE is_visual_object_identifier = (BYTE)m_pFile->BitRead(1);
-
- if(is_visual_object_identifier)
- {
- BYTE visual_object_verid = (BYTE)m_pFile->BitRead(4);
- BYTE visual_object_priority = (BYTE)m_pFile->BitRead(3);
- }
-
- BYTE visual_object_type = (BYTE)m_pFile->BitRead(4);
-
- if(visual_object_type == 1 || visual_object_type == 2)
- {
- BYTE video_signal_type = (BYTE)m_pFile->BitRead(1);
-
- if(video_signal_type)
- {
- BYTE video_format = (BYTE)m_pFile->BitRead(3);
- BYTE video_range = (BYTE)m_pFile->BitRead(1);
- BYTE colour_description = (BYTE)m_pFile->BitRead(1);
-
- if(colour_description)
- {
- BYTE colour_primaries = (BYTE)m_pFile->BitRead(8);
- BYTE transfer_characteristics = (BYTE)m_pFile->BitRead(8);
- BYTE matrix_coefficients = (BYTE)m_pFile->BitRead(8);
- }
- }
- }
-
- SkipUserData();
-
- if(visual_object_type == 1)
- {
- if(m_pFile->BitRead(24) != 0x000001)
- break;
-
- BYTE video_object_start_code = (BYTE)m_pFile->BitRead(8);
- if(video_object_start_code < 0x00 || video_object_start_code > 0x1f)
- break;
-
- if(m_pFile->BitRead(24) != 0x000001)
- break;
-
- BYTE video_object_layer_start_code = (DWORD)m_pFile->BitRead(8);
- if(video_object_layer_start_code < 0x20 || video_object_layer_start_code > 0x2f)
- break;
-
- BYTE random_accessible_vol = (BYTE)m_pFile->BitRead(1);
- BYTE video_object_type_indication = (BYTE)m_pFile->BitRead(8);
-
- if(video_object_type_indication == 0x12) // Fine Granularity Scalable
- break; // huh
-
- BYTE is_object_layer_identifier = (BYTE)m_pFile->BitRead(1);
-
- BYTE video_object_layer_verid = 0;
-
- if(is_object_layer_identifier)
- {
- video_object_layer_verid = (BYTE)m_pFile->BitRead(4);
- BYTE video_object_layer_priority = (BYTE)m_pFile->BitRead(3);
- }
-
- BYTE aspect_ratio_info = (BYTE)m_pFile->BitRead(4);
-
- switch(aspect_ratio_info)
- {
- default:
- ASSERT(0);
- break;
- case 1:
- parx = 1;
- pary = 1;
- break;
- case 2:
- parx = 12;
- pary = 11;
- break;
- case 3:
- parx = 10;
- pary = 11;
- break;
- case 4:
- parx = 16;
- pary = 11;
- break;
- case 5:
- parx = 40;
- pary = 33;
- break;
- case 15:
- parx = (BYTE)m_pFile->BitRead(8);
- pary = (BYTE)m_pFile->BitRead(8);
- break;
- }
-
- BYTE vol_control_parameters = (BYTE)m_pFile->BitRead(1);
-
- if(vol_control_parameters)
- {
- BYTE chroma_format = (BYTE)m_pFile->BitRead(2);
- BYTE low_delay = (BYTE)m_pFile->BitRead(1);
- BYTE vbv_parameters = (BYTE)m_pFile->BitRead(1);
-
- if(vbv_parameters)
- {
- WORD first_half_bit_rate = (WORD)m_pFile->BitRead(15);
- if(!m_pFile->BitRead(1)) break;
- WORD latter_half_bit_rate = (WORD)m_pFile->BitRead(15);
- if(!m_pFile->BitRead(1)) break;
- WORD first_half_vbv_buffer_size = (WORD)m_pFile->BitRead(15);
- if(!m_pFile->BitRead(1)) break;
-
- BYTE latter_half_vbv_buffer_size = (BYTE)m_pFile->BitRead(3);
- WORD first_half_vbv_occupancy = (WORD)m_pFile->BitRead(11);
- if(!m_pFile->BitRead(1)) break;
- WORD latter_half_vbv_occupancy = (WORD)m_pFile->BitRead(15);
- if(!m_pFile->BitRead(1)) break;
- }
- }
-
- BYTE video_object_layer_shape = (BYTE)m_pFile->BitRead(2);
-
- if(video_object_layer_shape == 3 && video_object_layer_verid != 1)
- {
- BYTE video_object_layer_shape_extension = (BYTE)m_pFile->BitRead(4);
- }
-
- if(!m_pFile->BitRead(1)) break;
- WORD vop_time_increment_resolution = (WORD)m_pFile->BitRead(16);
- if(!m_pFile->BitRead(1)) break;
- BYTE fixed_vop_rate = (BYTE)m_pFile->BitRead(1);
-
- if(fixed_vop_rate)
- {
- int bits = 0;
- for(WORD i = vop_time_increment_resolution; i; i /= 2)
- bits++;
-
- WORD fixed_vop_time_increment = m_pFile->BitRead(bits);
-
- if(fixed_vop_time_increment)
- {
- atpf = 10000000i64 * fixed_vop_time_increment / vop_time_increment_resolution;
- }
- }
-
- if(video_object_layer_shape != 2)
- {
- if(video_object_layer_shape == 0)
- {
- if(!m_pFile->BitRead(1)) break;
- width = (WORD)m_pFile->BitRead(13);
- if(!m_pFile->BitRead(1)) break;
- height = (WORD)m_pFile->BitRead(13);
- if(!m_pFile->BitRead(1)) break;
- }
-
- BYTE interlaced = (BYTE)m_pFile->BitRead(1);
- BYTE obmc_disable = (BYTE)m_pFile->BitRead(1);
-
- // ...
- }
- }
- }
- else if(id == 0xb6)
- {
- m_seqhdrsize = m_pFile->GetPos() - 4;
- }
- }
-
- if(!width || !height)
- return E_FAIL;
-
- CAtlArray<CMediaType> mts;
-
- CMediaType mt;
- mt.SetSampleSize(1);
-
- mt.majortype = MEDIATYPE_Video;
- mt.subtype = FOURCCMap('v4pm');
- mt.formattype = FORMAT_MPEG2Video;
- MPEG2VIDEOINFO* vih = (MPEG2VIDEOINFO*)mt.AllocFormatBuffer(FIELD_OFFSET(MPEG2VIDEOINFO, dwSequenceHeader) + m_seqhdrsize);
- memset(vih, 0, mt.FormatLength());
- vih->hdr.bmiHeader.biSize = sizeof(vih->hdr.bmiHeader);
- vih->hdr.bmiHeader.biWidth = width;
- vih->hdr.bmiHeader.biHeight = height;
- vih->hdr.bmiHeader.biCompression = 'v4pm';
- vih->hdr.bmiHeader.biPlanes = 1;
- vih->hdr.bmiHeader.biBitCount = 24;
- vih->hdr.AvgTimePerFrame = atpf;
- vih->hdr.dwPictAspectRatioX = width * parx;
- vih->hdr.dwPictAspectRatioY = height * pary;
- vih->cbSequenceHeader = m_seqhdrsize;
- m_pFile->Seek(0);
- m_pFile->ByteRead((BYTE*)vih->dwSequenceHeader, m_seqhdrsize);
- mts.Add(mt);
- mt.subtype = FOURCCMap(vih->hdr.bmiHeader.biCompression = 'V4PM');
- mts.Add(mt);
-
- CAutoPtr<CBaseSplitterOutputPin> pPinOut(DNew CBaseSplitterOutputPin(mts, L"Video", this, this, &hr));
- EXECUTE_ASSERT(SUCCEEDED(AddOutputPin(0, pPinOut)));
-
- m_rtNewStop = m_rtStop = m_rtDuration;
-
- return m_pOutputs.GetCount() > 0 ? S_OK : E_FAIL;
+ CheckPointer(pAsyncReader, E_POINTER);
+
+ HRESULT hr = E_FAIL;
+
+ m_pFile.Free();
+ m_pFile.Attach(DNew CBaseSplitterFileEx(pAsyncReader, hr));
+ if(!m_pFile) return E_OUTOFMEMORY;
+ if(FAILED(hr)) {m_pFile.Free(); return hr;}
+
+ m_rtNewStart = m_rtCurrent = 0;
+ m_rtNewStop = m_rtStop = m_rtDuration = 0;
+
+ // TODO
+
+ DWORD width = 0;
+ DWORD height = 0;
+ BYTE parx = 1;
+ BYTE pary = 1;
+ REFERENCE_TIME atpf = 400000;
+
+ if(m_pFile->BitRead(24, true) != 0x000001)
+ return E_FAIL;
+
+ BYTE id;
+ while(m_pFile->NextMpegStartCode(id, 1024 - m_pFile->GetPos()))
+ {
+ if(id == 0xb5)
+ {
+ BYTE is_visual_object_identifier = (BYTE)m_pFile->BitRead(1);
+
+ if(is_visual_object_identifier)
+ {
+ BYTE visual_object_verid = (BYTE)m_pFile->BitRead(4);
+ BYTE visual_object_priority = (BYTE)m_pFile->BitRead(3);
+ }
+
+ BYTE visual_object_type = (BYTE)m_pFile->BitRead(4);
+
+ if(visual_object_type == 1 || visual_object_type == 2)
+ {
+ BYTE video_signal_type = (BYTE)m_pFile->BitRead(1);
+
+ if(video_signal_type)
+ {
+ BYTE video_format = (BYTE)m_pFile->BitRead(3);
+ BYTE video_range = (BYTE)m_pFile->BitRead(1);
+ BYTE colour_description = (BYTE)m_pFile->BitRead(1);
+
+ if(colour_description)
+ {
+ BYTE colour_primaries = (BYTE)m_pFile->BitRead(8);
+ BYTE transfer_characteristics = (BYTE)m_pFile->BitRead(8);
+ BYTE matrix_coefficients = (BYTE)m_pFile->BitRead(8);
+ }
+ }
+ }
+
+ SkipUserData();
+
+ if(visual_object_type == 1)
+ {
+ if(m_pFile->BitRead(24) != 0x000001)
+ break;
+
+ BYTE video_object_start_code = (BYTE)m_pFile->BitRead(8);
+ if(video_object_start_code < 0x00 || video_object_start_code > 0x1f)
+ break;
+
+ if(m_pFile->BitRead(24) != 0x000001)
+ break;
+
+ BYTE video_object_layer_start_code = (DWORD)m_pFile->BitRead(8);
+ if(video_object_layer_start_code < 0x20 || video_object_layer_start_code > 0x2f)
+ break;
+
+ BYTE random_accessible_vol = (BYTE)m_pFile->BitRead(1);
+ BYTE video_object_type_indication = (BYTE)m_pFile->BitRead(8);
+
+ if(video_object_type_indication == 0x12) // Fine Granularity Scalable
+ break; // huh
+
+ BYTE is_object_layer_identifier = (BYTE)m_pFile->BitRead(1);
+
+ BYTE video_object_layer_verid = 0;
+
+ if(is_object_layer_identifier)
+ {
+ video_object_layer_verid = (BYTE)m_pFile->BitRead(4);
+ BYTE video_object_layer_priority = (BYTE)m_pFile->BitRead(3);
+ }
+
+ BYTE aspect_ratio_info = (BYTE)m_pFile->BitRead(4);
+
+ switch(aspect_ratio_info)
+ {
+ default: ASSERT(0); break;
+ case 1: parx = 1; pary = 1; break;
+ case 2: parx = 12; pary = 11; break;
+ case 3: parx = 10; pary = 11; break;
+ case 4: parx = 16; pary = 11; break;
+ case 5: parx = 40; pary = 33; break;
+ case 15: parx = (BYTE)m_pFile->BitRead(8); pary = (BYTE)m_pFile->BitRead(8); break;
+ }
+
+ BYTE vol_control_parameters = (BYTE)m_pFile->BitRead(1);
+
+ if(vol_control_parameters)
+ {
+ BYTE chroma_format = (BYTE)m_pFile->BitRead(2);
+ BYTE low_delay = (BYTE)m_pFile->BitRead(1);
+ BYTE vbv_parameters = (BYTE)m_pFile->BitRead(1);
+
+ if(vbv_parameters)
+ {
+ WORD first_half_bit_rate = (WORD)m_pFile->BitRead(15);
+ if(!m_pFile->BitRead(1)) break;
+ WORD latter_half_bit_rate = (WORD)m_pFile->BitRead(15);
+ if(!m_pFile->BitRead(1)) break;
+ WORD first_half_vbv_buffer_size = (WORD)m_pFile->BitRead(15);
+ if(!m_pFile->BitRead(1)) break;
+
+ BYTE latter_half_vbv_buffer_size = (BYTE)m_pFile->BitRead(3);
+ WORD first_half_vbv_occupancy = (WORD)m_pFile->BitRead(11);
+ if(!m_pFile->BitRead(1)) break;
+ WORD latter_half_vbv_occupancy = (WORD)m_pFile->BitRead(15);
+ if(!m_pFile->BitRead(1)) break;
+ }
+ }
+
+ BYTE video_object_layer_shape = (BYTE)m_pFile->BitRead(2);
+
+ if(video_object_layer_shape == 3 && video_object_layer_verid != 1)
+ {
+ BYTE video_object_layer_shape_extension = (BYTE)m_pFile->BitRead(4);
+ }
+
+ if(!m_pFile->BitRead(1)) break;
+ WORD vop_time_increment_resolution = (WORD)m_pFile->BitRead(16);
+ if(!m_pFile->BitRead(1)) break;
+ BYTE fixed_vop_rate = (BYTE)m_pFile->BitRead(1);
+
+ if(fixed_vop_rate)
+ {
+ int bits = 0;
+ for(WORD i = vop_time_increment_resolution; i; i /= 2)
+ bits++;
+
+ WORD fixed_vop_time_increment = m_pFile->BitRead(bits);
+
+ if(fixed_vop_time_increment)
+ {
+ atpf = 10000000i64 * fixed_vop_time_increment / vop_time_increment_resolution;
+ }
+ }
+
+ if(video_object_layer_shape != 2)
+ {
+ if(video_object_layer_shape == 0)
+ {
+ if(!m_pFile->BitRead(1)) break;
+ width = (WORD)m_pFile->BitRead(13);
+ if(!m_pFile->BitRead(1)) break;
+ height = (WORD)m_pFile->BitRead(13);
+ if(!m_pFile->BitRead(1)) break;
+ }
+
+ BYTE interlaced = (BYTE)m_pFile->BitRead(1);
+ BYTE obmc_disable = (BYTE)m_pFile->BitRead(1);
+
+ // ...
+ }
+ }
+ }
+ else if(id == 0xb6)
+ {
+ m_seqhdrsize = m_pFile->GetPos() - 4;
+ }
+ }
+
+ if(!width || !height)
+ return E_FAIL;
+
+ CAtlArray<CMediaType> mts;
+
+ CMediaType mt;
+ mt.SetSampleSize(1);
+
+ mt.majortype = MEDIATYPE_Video;
+ mt.subtype = FOURCCMap('v4pm');
+ mt.formattype = FORMAT_MPEG2Video;
+ MPEG2VIDEOINFO* vih = (MPEG2VIDEOINFO*)mt.AllocFormatBuffer(FIELD_OFFSET(MPEG2VIDEOINFO, dwSequenceHeader) + m_seqhdrsize);
+ memset(vih, 0, mt.FormatLength());
+ vih->hdr.bmiHeader.biSize = sizeof(vih->hdr.bmiHeader);
+ vih->hdr.bmiHeader.biWidth = width;
+ vih->hdr.bmiHeader.biHeight = height;
+ vih->hdr.bmiHeader.biCompression = 'v4pm';
+ vih->hdr.bmiHeader.biPlanes = 1;
+ vih->hdr.bmiHeader.biBitCount = 24;
+ vih->hdr.AvgTimePerFrame = atpf;
+ vih->hdr.dwPictAspectRatioX = width*parx;
+ vih->hdr.dwPictAspectRatioY = height*pary;
+ vih->cbSequenceHeader = m_seqhdrsize;
+ m_pFile->Seek(0);
+ m_pFile->ByteRead((BYTE*)vih->dwSequenceHeader, m_seqhdrsize);
+ mts.Add(mt);
+ mt.subtype = FOURCCMap(vih->hdr.bmiHeader.biCompression = 'V4PM');
+ mts.Add(mt);
+
+ CAutoPtr<CBaseSplitterOutputPin> pPinOut(DNew CBaseSplitterOutputPin(mts, L"Video", this, this, &hr));
+ EXECUTE_ASSERT(SUCCEEDED(AddOutputPin(0, pPinOut)));
+
+ m_rtNewStop = m_rtStop = m_rtDuration;
+
+ return m_pOutputs.GetCount() > 0 ? S_OK : E_FAIL;
}
bool CMPEG4VideoSplitterFilter::DemuxInit()
{
- return true;
+ return true;
}
void CMPEG4VideoSplitterFilter::DemuxSeek(REFERENCE_TIME rt)
{
- ASSERT(rt == 0);
+ ASSERT(rt == 0);
- m_pFile->Seek(m_seqhdrsize);
+ m_pFile->Seek(m_seqhdrsize);
}
bool CMPEG4VideoSplitterFilter::DemuxLoop()
{
- HRESULT hr = S_OK;
-
- CAutoPtr<Packet> p;
-
- REFERENCE_TIME rt = 0;
- REFERENCE_TIME atpf = ((MPEG2VIDEOINFO*)GetOutputPin(0)->CurrentMediaType().Format())->hdr.AvgTimePerFrame;
-
- DWORD sync = ~0;
-
- while(SUCCEEDED(hr) && !CheckRequest(NULL) && m_pFile->GetRemaining())
- {
- for(int i = 0; i < 65536; i++) // don't call CheckRequest so often
- {
- bool eof = !m_pFile->GetRemaining();
-
- if(p && !p->IsEmpty() && (m_pFile->BitRead(32, true) == 0x000001b6 || eof))
- {
- hr = DeliverPacket(p);
- }
-
- if(eof) break;
-
- if(!p)
- {
- p.Attach(DNew Packet());
- p->SetCount(0, 1024);
- p->TrackNumber = 0;
- p->rtStart = rt;
- p->rtStop = rt + atpf;
- p->bSyncPoint = FALSE;
- rt += atpf;
- // rt = Packet::INVALID_TIME;
- }
-
- BYTE b;
- m_pFile->ByteRead(&b, 1);
- p->Add(b);
- }
- }
-
- return true;
+ HRESULT hr = S_OK;
+
+ CAutoPtr<Packet> p;
+
+ REFERENCE_TIME rt = 0;
+ REFERENCE_TIME atpf = ((MPEG2VIDEOINFO*)GetOutputPin(0)->CurrentMediaType().Format())->hdr.AvgTimePerFrame;
+
+ DWORD sync = ~0;
+
+ while(SUCCEEDED(hr) && !CheckRequest(NULL) && m_pFile->GetRemaining())
+ {
+ for(int i = 0; i < 65536; i++) // don't call CheckRequest so often
+ {
+ bool eof = !m_pFile->GetRemaining();
+
+ if(p && !p->IsEmpty() && (m_pFile->BitRead(32, true) == 0x000001b6 || eof))
+ {
+ hr = DeliverPacket(p);
+ }
+
+ if(eof) break;
+
+ if(!p)
+ {
+ p.Attach(DNew Packet());
+ p->SetCount(0, 1024);
+ p->TrackNumber = 0;
+ p->rtStart = rt;
+ p->rtStop = rt + atpf;
+ p->bSyncPoint = FALSE;
+ rt += atpf;
+ // rt = Packet::INVALID_TIME;
+ }
+
+ BYTE b;
+ m_pFile->ByteRead(&b, 1);
+ p->Add(b);
+ }
+ }
+
+ return true;
}
//
@@ -1650,8 +1580,8 @@ bool CMPEG4VideoSplitterFilter::DemuxLoop()
//
CMPEG4VideoSourceFilter::CMPEG4VideoSourceFilter(LPUNKNOWN pUnk, HRESULT* phr)
- : CMPEG4VideoSplitterFilter(pUnk, phr)
+ : CMPEG4VideoSplitterFilter(pUnk, phr)
{
- m_clsid = __uuidof(this);
- m_pInput.Free();
+ m_clsid = __uuidof(this);
+ m_pInput.Free();
}
diff --git a/src/filters/parser/MP4Splitter/MP4Splitter.h b/src/filters/parser/MP4Splitter/MP4Splitter.h
index eca140155..e7b36dc04 100644
--- a/src/filters/parser/MP4Splitter/MP4Splitter.h
+++ b/src/filters/parser/MP4Splitter/MP4Splitter.h
@@ -1,4 +1,4 @@
-/*
+/*
* Copyright (C) 2003-2006 Gabest
* http://www.gabest.org
*
@@ -6,15 +6,15 @@
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2, or (at your option)
* any later version.
- *
+ *
* This Program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with GNU Make; see the file COPYING. If not, write to
- * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
+ * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
* http://www.gnu.org/copyleft/gpl.html
*
*/
@@ -29,37 +29,33 @@
[uuid("61F47056-E400-43d3-AF1E-AB7DFFD4C4AD")]
class CMP4SplitterFilter : public CBaseSplitterFilter
{
- struct trackpos
- {
- unsigned int /*AP4_Ordinal*/ index;
- unsigned __int64 /*AP4_TimeStamp*/ ts;
- };
- CAtlMap<unsigned int, trackpos> m_trackpos;
- CSize m_framesize;
+ struct trackpos {unsigned int /*AP4_Ordinal*/ index; unsigned __int64 /*AP4_TimeStamp*/ ts;};
+ CAtlMap<unsigned int, trackpos> m_trackpos;
+ CSize m_framesize;
protected:
- CAutoPtr<CMP4SplitterFile> m_pFile;
- HRESULT CreateOutputs(IAsyncReader* pAsyncReader);
+ CAutoPtr<CMP4SplitterFile> m_pFile;
+ HRESULT CreateOutputs(IAsyncReader* pAsyncReader);
- bool DemuxInit();
- void DemuxSeek(REFERENCE_TIME rt);
- bool DemuxLoop();
+ bool DemuxInit();
+ void DemuxSeek(REFERENCE_TIME rt);
+ bool DemuxLoop();
public:
- CMP4SplitterFilter(LPUNKNOWN pUnk, HRESULT* phr);
- virtual ~CMP4SplitterFilter();
+ CMP4SplitterFilter(LPUNKNOWN pUnk, HRESULT* phr);
+ virtual ~CMP4SplitterFilter();
- // IKeyFrameInfo
+ // IKeyFrameInfo
- STDMETHODIMP_(HRESULT) GetKeyFrameCount(UINT& nKFs);
- STDMETHODIMP_(HRESULT) GetKeyFrames(const GUID* pFormat, REFERENCE_TIME* pKFs, UINT& nKFs);
+ STDMETHODIMP_(HRESULT) GetKeyFrameCount(UINT& nKFs);
+ STDMETHODIMP_(HRESULT) GetKeyFrames(const GUID* pFormat, REFERENCE_TIME* pKFs, UINT& nKFs);
};
[uuid("3CCC052E-BDEE-408a-BEA7-90914EF2964B")]
class CMP4SourceFilter : public CMP4SplitterFilter
{
public:
- CMP4SourceFilter(LPUNKNOWN pUnk, HRESULT* phr);
+ CMP4SourceFilter(LPUNKNOWN pUnk, HRESULT* phr);
};
// for raw mpeg4 elementary streams:
@@ -67,25 +63,25 @@ public:
[uuid("D3D9D58B-45B5-48AB-B199-B8C40560AEC7")]
class CMPEG4VideoSplitterFilter : public CBaseSplitterFilter
{
- __int64 m_seqhdrsize;
- int NextStartCode();
- void SkipUserData();
+ __int64 m_seqhdrsize;
+ int NextStartCode();
+ void SkipUserData();
protected:
- CAutoPtr<CBaseSplitterFileEx> m_pFile;
- HRESULT CreateOutputs(IAsyncReader* pAsyncReader);
+ CAutoPtr<CBaseSplitterFileEx> m_pFile;
+ HRESULT CreateOutputs(IAsyncReader* pAsyncReader);
- bool DemuxInit();
- void DemuxSeek(REFERENCE_TIME rt);
- bool DemuxLoop();
+ bool DemuxInit();
+ void DemuxSeek(REFERENCE_TIME rt);
+ bool DemuxLoop();
public:
- CMPEG4VideoSplitterFilter(LPUNKNOWN pUnk, HRESULT* phr);
+ CMPEG4VideoSplitterFilter(LPUNKNOWN pUnk, HRESULT* phr);
};
[uuid("E2B98EEA-EE55-4E9B-A8C1-6E5288DF785A")]
class CMPEG4VideoSourceFilter : public CMPEG4VideoSplitterFilter
{
public:
- CMPEG4VideoSourceFilter(LPUNKNOWN pUnk, HRESULT* phr);
+ CMPEG4VideoSourceFilter(LPUNKNOWN pUnk, HRESULT* phr);
};
diff --git a/src/filters/parser/MP4Splitter/MP4SplitterFile.cpp b/src/filters/parser/MP4Splitter/MP4SplitterFile.cpp
index d498e104c..c28950291 100644
--- a/src/filters/parser/MP4Splitter/MP4SplitterFile.cpp
+++ b/src/filters/parser/MP4Splitter/MP4SplitterFile.cpp
@@ -2,39 +2,39 @@
#include "MP4SplitterFile.h"
#include "Ap4AsyncReaderStream.h"
-CMP4SplitterFile::CMP4SplitterFile(IAsyncReader* pReader, HRESULT& hr)
- : CBaseSplitterFileEx(pReader, hr, DEFAULT_CACHE_LENGTH, false)
- , m_pAp4File(NULL)
+CMP4SplitterFile::CMP4SplitterFile(IAsyncReader* pReader, HRESULT& hr)
+ : CBaseSplitterFileEx(pReader, hr, DEFAULT_CACHE_LENGTH, false)
+ , m_pAp4File(NULL)
{
- if(FAILED(hr)) return;
+ if(FAILED(hr)) return;
- hr = Init();
+ hr = Init();
}
CMP4SplitterFile::~CMP4SplitterFile()
{
- delete(AP4_File*)m_pAp4File;
+ delete (AP4_File*)m_pAp4File;
}
void* /* AP4_Movie* */ CMP4SplitterFile::GetMovie()
{
- ASSERT(m_pAp4File);
- return m_pAp4File ? ((AP4_File*)m_pAp4File)->GetMovie() : NULL;
+ ASSERT(m_pAp4File);
+ return m_pAp4File ? ((AP4_File*)m_pAp4File)->GetMovie() : NULL;
}
HRESULT CMP4SplitterFile::Init()
{
- Seek(0);
+ Seek(0);
- delete(AP4_File*)m_pAp4File;
+ delete (AP4_File*)m_pAp4File;
- AP4_ByteStream* stream = DNew AP4_AsyncReaderStream(this);
+ AP4_ByteStream* stream = DNew AP4_AsyncReaderStream(this);
- m_pAp4File = DNew AP4_File(*stream);
+ m_pAp4File = DNew AP4_File(*stream);
+
+ AP4_Movie* movie = ((AP4_File*)m_pAp4File)->GetMovie();
- AP4_Movie* movie = ((AP4_File*)m_pAp4File)->GetMovie();
+ stream->Release();
- stream->Release();
-
- return movie ? S_OK : E_FAIL;
+ return movie ? S_OK : E_FAIL;
}
diff --git a/src/filters/parser/MP4Splitter/MP4SplitterFile.h b/src/filters/parser/MP4Splitter/MP4SplitterFile.h
index ac8377c88..ef1557b9f 100644
--- a/src/filters/parser/MP4Splitter/MP4SplitterFile.h
+++ b/src/filters/parser/MP4Splitter/MP4SplitterFile.h
@@ -5,13 +5,13 @@
class CMP4SplitterFile : public CBaseSplitterFileEx
{
- void* /* AP4_File* */ m_pAp4File;
+ void* /* AP4_File* */ m_pAp4File;
- HRESULT Init();
+ HRESULT Init();
public:
- CMP4SplitterFile(IAsyncReader* pReader, HRESULT& hr);
- virtual ~CMP4SplitterFile();
+ CMP4SplitterFile(IAsyncReader* pReader, HRESULT& hr);
+ virtual ~CMP4SplitterFile();
- void* /* AP4_Movie* */ GetMovie();
+ void* /* AP4_Movie* */ GetMovie();
};
diff --git a/src/filters/parser/MP4Splitter/resource.h b/src/filters/parser/MP4Splitter/resource.h
index 42227a3a6..f9afd652d 100644
--- a/src/filters/parser/MP4Splitter/resource.h
+++ b/src/filters/parser/MP4Splitter/resource.h
@@ -3,7 +3,7 @@
// Used by MP4Splitter.rc
// Next default values for new objects
-//
+//
#ifdef APSTUDIO_INVOKED
#ifndef APSTUDIO_READONLY_SYMBOLS
#define _APS_NEXT_RESOURCE_VALUE 101
diff --git a/src/filters/parser/MP4Splitter/stdafx.cpp b/src/filters/parser/MP4Splitter/stdafx.cpp
index 13a771bb8..ae7410104 100644
--- a/src/filters/parser/MP4Splitter/stdafx.cpp
+++ b/src/filters/parser/MP4Splitter/stdafx.cpp
@@ -1,4 +1,4 @@
-/*
+/*
* Copyright (C) 2003-2006 Gabest
* http://www.gabest.org
*
@@ -6,15 +6,15 @@
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2, or (at your option)
* any later version.
- *
+ *
* This Program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with GNU Make; see the file COPYING. If not, write to
- * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
+ * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
* http://www.gnu.org/copyleft/gpl.html
*
*/
diff --git a/src/filters/parser/MP4Splitter/stdafx.h b/src/filters/parser/MP4Splitter/stdafx.h
index 089cf8fa0..e8beccd47 100644
--- a/src/filters/parser/MP4Splitter/stdafx.h
+++ b/src/filters/parser/MP4Splitter/stdafx.h
@@ -1,4 +1,4 @@
-/*
+/*
* Copyright (C) 2003-2006 Gabest
* http://www.gabest.org
*
@@ -6,15 +6,15 @@
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2, or (at your option)
* any later version.
- *
+ *
* This Program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with GNU Make; see the file COPYING. If not, write to
- * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
+ * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
* http://www.gnu.org/copyleft/gpl.html
*
*/
diff --git a/src/filters/parser/MatroskaSplitter/MatroskaFile.cpp b/src/filters/parser/MatroskaSplitter/MatroskaFile.cpp
index 8f65f751b..620b2cc2a 100644
--- a/src/filters/parser/MatroskaSplitter/MatroskaFile.cpp
+++ b/src/filters/parser/MatroskaSplitter/MatroskaFile.cpp
@@ -1,4 +1,4 @@
-/*
+/*
* Copyright (C) 2003-2006 Gabest
* http://www.gabest.org
*
@@ -6,15 +6,15 @@
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2, or (at your option)
* any later version.
- *
+ *
* This Program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with GNU Make; see the file COPYING. If not, write to
- * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
+ * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
* http://www.gnu.org/copyleft/gpl.html
*
*/
@@ -29,15 +29,15 @@
static void LOG(LPCTSTR fmt, ...)
{
- va_list args;
- va_start(args, fmt);
- if(FILE* f = _tfopen(_T("c:\\matroskasplitterlog.txt"), _T("at")))
- {
- fseek(f, 0, 2);
- _vftprintf(f, fmt, args);
- fclose(f);
- }
- va_end(args);
+ va_list args;
+ va_start(args, fmt);
+ if(FILE* f = _tfopen(_T("c:\\matroskasplitterlog.txt"), _T("at")))
+ {
+ fseek(f, 0, 2);
+ _vftprintf(f, fmt, args);
+ fclose(f);
+ }
+ va_end(args);
}
using namespace MatroskaReader;
@@ -52,1245 +52,888 @@ using namespace MatroskaReader;
{ \
switch(pMN->m_id) \
{ \
-
+
#define EndChunk \
} \
} \
while(pMN->Next()); \
\
return S_OK; \
-
+
static void bswap(BYTE* s, int len)
{
- for(BYTE* d = s + len - 1; s < d; s++, d--)
- *s ^= *d, *d ^= *s, *s ^= *d;
+ for(BYTE* d = s + len-1; s < d; s++, d--)
+ *s ^= *d, *d ^= *s, *s ^= *d;
}
//
// CMatroskaFile
//
-CMatroskaFile::CMatroskaFile(IAsyncReader* pAsyncReader, HRESULT& hr)
- : CBaseSplitterFile(pAsyncReader, hr, DEFAULT_CACHE_LENGTH, false)
- , m_rtOffset(0)
+CMatroskaFile::CMatroskaFile(IAsyncReader* pAsyncReader, HRESULT& hr)
+ : CBaseSplitterFile(pAsyncReader, hr, DEFAULT_CACHE_LENGTH, false)
+ , m_rtOffset(0)
{
- if(FAILED(hr)) return;
- hr = Init();
+ if(FAILED(hr)) return;
+ hr = Init();
}
HRESULT CMatroskaFile::Init()
{
- DWORD dw;
- if(FAILED(Read(dw)) || dw != 0x1A45DFA3)
- return E_FAIL;
+ DWORD dw;
+ if(FAILED(Read(dw)) || dw != 0x1A45DFA3)
+ return E_FAIL;
- CMatroskaNode Root(this);
- if(FAILED(Parse(&Root)))
- return E_FAIL;
+ CMatroskaNode Root(this);
+ if(FAILED(Parse(&Root)))
+ return E_FAIL;
- CAutoPtr<CMatroskaNode> pSegment, pCluster;
- if((pSegment = Root.Child(0x18538067))
- && (pCluster = pSegment->Child(0x1F43B675)))
- {
- Cluster c0;
- c0.ParseTimeCode(pCluster);
- m_rtOffset = m_segment.GetRefTime(c0.TimeCode);
- }
+ CAutoPtr<CMatroskaNode> pSegment, pCluster;
+ if((pSegment = Root.Child(0x18538067))
+ && (pCluster = pSegment->Child(0x1F43B675)))
+ {
+ Cluster c0;
+ c0.ParseTimeCode(pCluster);
+ m_rtOffset = m_segment.GetRefTime(c0.TimeCode);
+ }
- return S_OK;
+ return S_OK;
}
template <class T>
HRESULT CMatroskaFile::Read(T& var)
{
- HRESULT hr = ByteRead((BYTE*)&var, sizeof(var));
- if(S_OK == hr) bswap((BYTE*)&var, sizeof(var));
- return hr;
+ HRESULT hr = ByteRead((BYTE*)&var, sizeof(var));
+ if(S_OK == hr) bswap((BYTE*)&var, sizeof(var));
+ return hr;
}
HRESULT CMatroskaFile::Parse(CMatroskaNode* pMN0)
{
- BeginChunk
-case 0x1A45DFA3:
- m_ebml.Parse(pMN);
- if(m_ebml.DocType != DOCTYPE || m_ebml.DocTypeReadVersion > DOCTYPEVERSION)
- return E_FAIL;
- break;
-case 0x18538067:
- if(m_segment.SegmentInfo.SegmentUID.IsEmpty()) m_segment.ParseMinimal(pMN);
- break;
- EndChunk
+ BeginChunk
+ case 0x1A45DFA3:
+ m_ebml.Parse(pMN);
+ if(m_ebml.DocType != DOCTYPE || m_ebml.DocTypeReadVersion > DOCTYPEVERSION)
+ return E_FAIL;
+ break;
+ case 0x18538067: if(m_segment.SegmentInfo.SegmentUID.IsEmpty()) m_segment.ParseMinimal(pMN); break;
+ EndChunk
}
//
HRESULT EBML::Parse(CMatroskaNode* pMN0)
{
- BeginChunk
-case 0x4286:
- EBMLVersion.Parse(pMN);
- break;
-case 0x42F7:
- EBMLReadVersion.Parse(pMN);
- break;
-case 0x42F2:
- EBMLMaxIDLength.Parse(pMN);
- break;
-case 0x42F3:
- EBMLMaxSizeLength.Parse(pMN);
- break;
-case 0x4282:
- DocType.Parse(pMN);
- break;
-case 0x4287:
- DocTypeVersion.Parse(pMN);
- break;
-case 0x4285:
- DocTypeReadVersion.Parse(pMN);
- break;
- EndChunk
+ BeginChunk
+ case 0x4286: EBMLVersion.Parse(pMN); break;
+ case 0x42F7: EBMLReadVersion.Parse(pMN); break;
+ case 0x42F2: EBMLMaxIDLength.Parse(pMN); break;
+ case 0x42F3: EBMLMaxSizeLength.Parse(pMN); break;
+ case 0x4282: DocType.Parse(pMN); break;
+ case 0x4287: DocTypeVersion.Parse(pMN); break;
+ case 0x4285: DocTypeReadVersion.Parse(pMN); break;
+ EndChunk
}
HRESULT Segment::Parse(CMatroskaNode* pMN0)
{
- pos = pMN0->GetPos();
-
- BeginChunk
-case 0x1549A966:
- SegmentInfo.Parse(pMN);
- break;
-case 0x114D9B74:
- MetaSeekInfo.Parse(pMN);
- break;
-case 0x1654AE6B:
- Tracks.Parse(pMN);
- break;
-case 0x1F43B675:
- Clusters.Parse(pMN);
- break;
-case 0x1C53BB6B:
- Cues.Parse(pMN);
- break;
-case 0x1941A469:
- Attachments.Parse(pMN);
- break;
-case 0x1043A770:
- Chapters.Parse(pMN);
- break;
+ pos = pMN0->GetPos();
+
+ BeginChunk
+ case 0x1549A966: SegmentInfo.Parse(pMN); break;
+ case 0x114D9B74: MetaSeekInfo.Parse(pMN); break;
+ case 0x1654AE6B: Tracks.Parse(pMN); break;
+ case 0x1F43B675: Clusters.Parse(pMN); break;
+ case 0x1C53BB6B: Cues.Parse(pMN); break;
+ case 0x1941A469: Attachments.Parse(pMN); break;
+ case 0x1043A770: Chapters.Parse(pMN); break;
// case 0x1254C367: Tags.Parse(pMN); break;
- EndChunk
+ EndChunk
}
HRESULT Segment::ParseMinimal(CMatroskaNode* pMN0)
{
- CheckPointer(pMN0, E_POINTER);
-
- pos = pMN0->GetPos();
- len = pMN0->m_len;
-
- CAutoPtr<CMatroskaNode> pMN = pMN0->Child();
- if(!pMN) return S_FALSE;
-
- int n = 0;
-
- do
- {
- switch(pMN->m_id)
- {
- case 0x1549A966:
- SegmentInfo.Parse(pMN);
- n++;
- break;
- case 0x114D9B74:
- MetaSeekInfo.Parse(pMN);
- n++;
- break;
- case 0x1654AE6B:
- Tracks.Parse(pMN);
- n++;
- break;
- case 0x1C53BB6B:
- Cues.Parse(pMN);
- break;
- }
- }
- while(n < 3 && pMN->Next());
-
- if(!pMN->IsRandomAccess())
- {
- return S_OK;
- }
-
- while(MatroskaReader::QWORD pos = pMN->FindPos(0x114D9B74, pMN->GetPos()))
- {
- pMN->SeekTo(pos);
- pMN->Parse();
- if(pMN->m_id != 0x114D9B74)
- {
- ASSERT(0);
- break;
- }
- MetaSeekInfo.Parse(pMN);
- }
-
- if(n == 3)
- {
- if(Cues.IsEmpty() && (pMN = pMN0->Child(0x1C53BB6B, false)))
- {
- do
- {
- Cues.Parse(pMN);
- }
- while(pMN->Next(true));
- }
-
- if(Chapters.IsEmpty() && (pMN = pMN0->Child(0x1043A770, false)))
- {
- do
- {
- Chapters.Parse(pMN); /*BIG UGLY HACK:*/
- break;
- }
- while(pMN->Next(true));
- }
-
- if(Attachments.IsEmpty() && (pMN = pMN0->Child(0x1941A469, false)))
- {
- do
- {
- Attachments.Parse(pMN); /*BIG UGLY HACK:*/
- break;
- }
- while(pMN->Next(true));
- }
- }
-
- return S_OK;
+ CheckPointer(pMN0, E_POINTER);
+
+ pos = pMN0->GetPos();
+ len = pMN0->m_len;
+
+ CAutoPtr<CMatroskaNode> pMN = pMN0->Child();
+ if(!pMN) return S_FALSE;
+
+ int n = 0;
+
+ do
+ {
+ switch(pMN->m_id)
+ {
+ case 0x1549A966: SegmentInfo.Parse(pMN); n++; break;
+ case 0x114D9B74: MetaSeekInfo.Parse(pMN); n++; break;
+ case 0x1654AE6B: Tracks.Parse(pMN); n++; break;
+ case 0x1C53BB6B: Cues.Parse(pMN); break;
+ }
+ }
+ while(n < 3 && pMN->Next());
+
+ if(!pMN->IsRandomAccess())
+ {
+ return S_OK;
+ }
+
+ while(MatroskaReader::QWORD pos = pMN->FindPos(0x114D9B74, pMN->GetPos()))
+ {
+ pMN->SeekTo(pos);
+ pMN->Parse();
+ if(pMN->m_id != 0x114D9B74) {ASSERT(0); break;}
+ MetaSeekInfo.Parse(pMN);
+ }
+
+ if(n == 3)
+ {
+ if(Cues.IsEmpty() && (pMN = pMN0->Child(0x1C53BB6B, false)))
+ {
+ do {Cues.Parse(pMN);} while(pMN->Next(true));
+ }
+
+ if(Chapters.IsEmpty() && (pMN = pMN0->Child(0x1043A770, false)))
+ {
+ do {Chapters.Parse(pMN); /*BIG UGLY HACK:*/ break;} while(pMN->Next(true));
+ }
+
+ if(Attachments.IsEmpty() && (pMN = pMN0->Child(0x1941A469, false)))
+ {
+ do {Attachments.Parse(pMN); /*BIG UGLY HACK:*/ break;} while (pMN->Next(true));
+ }
+ }
+
+ return S_OK;
}
UINT64 Segment::GetMasterTrack()
{
- UINT64 TrackNumber = 0, AltTrackNumber = 0;
-
- POSITION pos1 = Tracks.GetHeadPosition();
- while(pos1 && TrackNumber == 0)
- {
- Track* pT = Tracks.GetNext(pos1);
+ UINT64 TrackNumber = 0, AltTrackNumber = 0;
- POSITION pos2 = pT->TrackEntries.GetHeadPosition();
- while(pos2 && TrackNumber == 0)
- {
- TrackEntry* pTE = pT->TrackEntries.GetNext(pos2);
-
- if(pTE->TrackType == TrackEntry::TypeVideo)
- {
- TrackNumber = pTE->TrackNumber;
- break;
- }
- else if(pTE->TrackType == TrackEntry::TypeAudio && AltTrackNumber == 0)
- {
- AltTrackNumber = pTE->TrackNumber;
- }
- }
- }
+ POSITION pos1 = Tracks.GetHeadPosition();
+ while(pos1 && TrackNumber == 0)
+ {
+ Track* pT = Tracks.GetNext(pos1);
+
+ POSITION pos2 = pT->TrackEntries.GetHeadPosition();
+ while(pos2 && TrackNumber == 0)
+ {
+ TrackEntry* pTE = pT->TrackEntries.GetNext(pos2);
+
+ if(pTE->TrackType == TrackEntry::TypeVideo)
+ {
+ TrackNumber = pTE->TrackNumber;
+ break;
+ }
+ else if(pTE->TrackType == TrackEntry::TypeAudio && AltTrackNumber == 0)
+ {
+ AltTrackNumber = pTE->TrackNumber;
+ }
+ }
+ }
- if(TrackNumber == 0) TrackNumber = AltTrackNumber;
- if(TrackNumber == 0) TrackNumber = 1;
+ if(TrackNumber == 0) TrackNumber = AltTrackNumber;
+ if(TrackNumber == 0) TrackNumber = 1;
- return TrackNumber;
+ return TrackNumber;
}
ChapterAtom* ChapterAtom::FindChapterAtom(UINT64 id)
{
- if(ChapterUID == id)
- return(this);
+ if(ChapterUID == id)
+ return(this);
- POSITION pos = ChapterAtoms.GetHeadPosition();
- while(pos)
- {
- ChapterAtom* ca = ChapterAtoms.GetNext(pos)->FindChapterAtom(id);
- if(ca) return ca;
- }
+ POSITION pos = ChapterAtoms.GetHeadPosition();
+ while(pos)
+ {
+ ChapterAtom* ca = ChapterAtoms.GetNext(pos)->FindChapterAtom(id);
+ if(ca) return ca;
+ }
- return(NULL);
+ return(NULL);
}
ChapterAtom* Segment::FindChapterAtom(UINT64 id, int nEditionEntry)
{
- POSITION pos1 = Chapters.GetHeadPosition();
- while(pos1)
- {
- Chapter* c = Chapters.GetNext(pos1);
-
- POSITION pos2 = c->EditionEntries.GetHeadPosition();
- while(pos2)
- {
- EditionEntry* ee = c->EditionEntries.GetNext(pos2);
-
- if(nEditionEntry-- == 0)
- {
- return id == 0 ? ee : ee->FindChapterAtom(id);
- }
- }
- }
+ POSITION pos1 = Chapters.GetHeadPosition();
+ while(pos1)
+ {
+ Chapter* c = Chapters.GetNext(pos1);
+
+ POSITION pos2 = c->EditionEntries.GetHeadPosition();
+ while(pos2)
+ {
+ EditionEntry* ee = c->EditionEntries.GetNext(pos2);
+
+ if(nEditionEntry-- == 0)
+ {
+ return id == 0 ? ee : ee->FindChapterAtom(id);
+ }
+ }
+ }
- return(NULL);
+ return(NULL);
}
HRESULT Info::Parse(CMatroskaNode* pMN0)
{
- BeginChunk
-case 0x73A4:
- SegmentUID.Parse(pMN);
- break;
-case 0x7384:
- SegmentFilename.Parse(pMN);
- break;
-case 0x3CB923:
- PrevUID.Parse(pMN);
- break;
-case 0x3C83AB:
- PrevFilename.Parse(pMN);
- break;
-case 0x3EB923:
- NextUID.Parse(pMN);
- break;
-case 0x3E83BB:
- NextFilename.Parse(pMN);
- break;
-case 0x2AD7B1:
- TimeCodeScale.Parse(pMN);
- break;
-case 0x4489:
- Duration.Parse(pMN);
- break;
-case 0x4461:
- DateUTC.Parse(pMN);
- break;
-case 0x7BA9:
- Title.Parse(pMN);
- break;
-case 0x4D80:
- MuxingApp.Parse(pMN);
- break;
-case 0x5741:
- WritingApp.Parse(pMN);
- break;
- EndChunk
+ BeginChunk
+ case 0x73A4: SegmentUID.Parse(pMN); break;
+ case 0x7384: SegmentFilename.Parse(pMN); break;
+ case 0x3CB923: PrevUID.Parse(pMN); break;
+ case 0x3C83AB: PrevFilename.Parse(pMN); break;
+ case 0x3EB923: NextUID.Parse(pMN); break;
+ case 0x3E83BB: NextFilename.Parse(pMN); break;
+ case 0x2AD7B1: TimeCodeScale.Parse(pMN); break;
+ case 0x4489: Duration.Parse(pMN); break;
+ case 0x4461: DateUTC.Parse(pMN); break;
+ case 0x7BA9: Title.Parse(pMN); break;
+ case 0x4D80: MuxingApp.Parse(pMN); break;
+ case 0x5741: WritingApp.Parse(pMN); break;
+ EndChunk
}
HRESULT Seek::Parse(CMatroskaNode* pMN0)
{
- BeginChunk
-case 0x4DBB:
- SeekHeads.Parse(pMN);
- break;
- EndChunk
+ BeginChunk
+ case 0x4DBB: SeekHeads.Parse(pMN); break;
+ EndChunk
}
HRESULT SeekHead::Parse(CMatroskaNode* pMN0)
{
- BeginChunk
-case 0x53AB:
- SeekID.Parse(pMN);
- break;
-case 0x53AC:
- SeekPosition.Parse(pMN);
- break;
- EndChunk
+ BeginChunk
+ case 0x53AB: SeekID.Parse(pMN); break;
+ case 0x53AC: SeekPosition.Parse(pMN); break;
+ EndChunk
}
HRESULT Track::Parse(CMatroskaNode* pMN0)
{
- BeginChunk
-case 0xAE:
- TrackEntries.Parse(pMN);
- break;
- EndChunk
+ BeginChunk
+ case 0xAE: TrackEntries.Parse(pMN); break;
+ EndChunk
}
HRESULT TrackEntry::Parse(CMatroskaNode* pMN0)
{
- BeginChunk
-case 0xD7:
- TrackNumber.Parse(pMN);
- break;
-case 0x73C5:
- TrackUID.Parse(pMN);
- break;
-case 0x83:
- TrackType.Parse(pMN);
- break;
-case 0xB9:
- FlagEnabled.Parse(pMN);
- break;
-case 0x88:
- FlagDefault.Parse(pMN);
- break;
-case 0x9C:
- FlagLacing.Parse(pMN);
- break;
-case 0x6DE7:
- MinCache.Parse(pMN);
- break;
-case 0x6DF8:
- MaxCache.Parse(pMN);
- break;
-case 0x536E:
- Name.Parse(pMN);
- break;
-case 0x22B59C:
- Language.Parse(pMN);
- break;
-case 0x86:
- CodecID.Parse(pMN);
- break;
-case 0x63A2:
- CodecPrivate.Parse(pMN);
- break;
-case 0x258688:
- CodecName.Parse(pMN);
- break;
-case 0x3A9697:
- CodecSettings.Parse(pMN);
- break;
-case 0x3B4040:
- CodecInfoURL.Parse(pMN);
- break;
-case 0x26B240:
- CodecDownloadURL.Parse(pMN);
- break;
-case 0xAA:
- CodecDecodeAll.Parse(pMN);
- break;
-case 0x6FAB:
- TrackOverlay.Parse(pMN);
- break;
-case 0x23E383:
-case 0x2383E3:
- DefaultDuration.Parse(pMN);
- break;
-case 0x23314F:
- TrackTimecodeScale.Parse(pMN);
- break;
-case 0xE0:
- if(S_OK == v.Parse(pMN)) DescType |= DescVideo;
- break;
-case 0xE1:
- if(S_OK == a.Parse(pMN)) DescType |= DescAudio;
- break;
-case 0x6D80:
- ces.Parse(pMN);
- break;
- EndChunk
+ BeginChunk
+ case 0xD7: TrackNumber.Parse(pMN); break;
+ case 0x73C5: TrackUID.Parse(pMN); break;
+ case 0x83: TrackType.Parse(pMN); break;
+ case 0xB9: FlagEnabled.Parse(pMN); break;
+ case 0x88: FlagDefault.Parse(pMN); break;
+ case 0x9C: FlagLacing.Parse(pMN); break;
+ case 0x6DE7: MinCache.Parse(pMN); break;
+ case 0x6DF8: MaxCache.Parse(pMN); break;
+ case 0x536E: Name.Parse(pMN); break;
+ case 0x22B59C: Language.Parse(pMN); break;
+ case 0x86: CodecID.Parse(pMN); break;
+ case 0x63A2: CodecPrivate.Parse(pMN); break;
+ case 0x258688: CodecName.Parse(pMN); break;
+ case 0x3A9697: CodecSettings.Parse(pMN); break;
+ case 0x3B4040: CodecInfoURL.Parse(pMN); break;
+ case 0x26B240: CodecDownloadURL.Parse(pMN); break;
+ case 0xAA: CodecDecodeAll.Parse(pMN); break;
+ case 0x6FAB: TrackOverlay.Parse(pMN); break;
+ case 0x23E383: case 0x2383E3: DefaultDuration.Parse(pMN); break;
+ case 0x23314F: TrackTimecodeScale.Parse(pMN); break;
+ case 0xE0: if(S_OK == v.Parse(pMN)) DescType |= DescVideo; break;
+ case 0xE1: if(S_OK == a.Parse(pMN)) DescType |= DescAudio; break;
+ case 0x6D80: ces.Parse(pMN); break;
+ EndChunk
}
static int cesort(const void* a, const void* b)
{
- UINT64 ce1 = (static_cast<ContentEncoding*>(const_cast<void *>(a)))->ContentEncodingOrder;
- UINT64 ce2 = (static_cast<ContentEncoding*>(const_cast<void *>(b)))->ContentEncodingOrder;
+ UINT64 ce1 = (static_cast<ContentEncoding*>(const_cast<void *>(a)))->ContentEncodingOrder;
+ UINT64 ce2 = (static_cast<ContentEncoding*>(const_cast<void *>(b)))->ContentEncodingOrder;
- return (int)ce1 - (int)ce2;
-//return static_cast<int>(ce1) - static_cast<int>(ce2);
+ return (int)ce1 - (int)ce2;
+//return static_cast<int>(ce1) - static_cast<int>(ce2);
}
bool TrackEntry::Expand(CBinary& data, UINT64 Scope)
{
- if(ces.ce.GetCount() == 0) return(true);
-
- CAtlArray<ContentEncoding*> cearray;
- POSITION pos = ces.ce.GetHeadPosition();
- while(pos) cearray.Add(ces.ce.GetNext(pos));
- qsort(cearray.GetData(), cearray.GetCount(), sizeof(ContentEncoding*), cesort);
-
- for(int i = cearray.GetCount() - 1; i >= 0; i--)
- {
- ContentEncoding* ce = cearray[i];
+ if(ces.ce.GetCount() == 0) return(true);
- if(!(ce->ContentEncodingScope & Scope))
- continue;
+ CAtlArray<ContentEncoding*> cearray;
+ POSITION pos = ces.ce.GetHeadPosition();
+ while(pos) cearray.Add(ces.ce.GetNext(pos));
+ qsort(cearray.GetData(), cearray.GetCount(), sizeof(ContentEncoding*), cesort);
- if(ce->ContentEncodingType == ContentEncoding::Compression)
- {
- if(!data.Decompress(ce->cc))
- return(false);
- }
- else if(ce->ContentEncodingType == ContentEncoding::Encryption)
- {
- // TODO
- return(false);
- }
- }
+ for(int i = cearray.GetCount()-1; i >= 0; i--)
+ {
+ ContentEncoding* ce = cearray[i];
+
+ if(!(ce->ContentEncodingScope & Scope))
+ continue;
+
+ if(ce->ContentEncodingType == ContentEncoding::Compression)
+ {
+ if(!data.Decompress(ce->cc))
+ return(false);
+ }
+ else if(ce->ContentEncodingType == ContentEncoding::Encryption)
+ {
+ // TODO
+ return(false);
+ }
+ }
- return(true);
+ return(true);
}
HRESULT Video::Parse(CMatroskaNode* pMN0)
{
- BeginChunk
-case 0x9A:
- FlagInterlaced.Parse(pMN);
- break;
-case 0x53B8:
- StereoMode.Parse(pMN);
- break;
-case 0xB0:
- PixelWidth.Parse(pMN);
- break;
-case 0xBA:
- PixelHeight.Parse(pMN);
- break;
-case 0x54B0:
- DisplayWidth.Parse(pMN);
- break;
-case 0x54BA:
- DisplayHeight.Parse(pMN);
- break;
-case 0x54B2:
- DisplayUnit.Parse(pMN);
- break;
-case 0x54B3:
- AspectRatioType.Parse(pMN);
- break;
-case 0x2EB524:
- ColourSpace.Parse(pMN);
- break;
-case 0x2FB523:
- GammaValue.Parse(pMN);
- break;
-case 0x2383E3:
- FramePerSec.Parse(pMN);
- break;
- EndChunk
+ BeginChunk
+ case 0x9A: FlagInterlaced.Parse(pMN); break;
+ case 0x53B8: StereoMode.Parse(pMN); break;
+ case 0xB0: PixelWidth.Parse(pMN); break;
+ case 0xBA: PixelHeight.Parse(pMN); break;
+ case 0x54B0: DisplayWidth.Parse(pMN); break;
+ case 0x54BA: DisplayHeight.Parse(pMN); break;
+ case 0x54B2: DisplayUnit.Parse(pMN); break;
+ case 0x54B3: AspectRatioType.Parse(pMN); break;
+ case 0x2EB524: ColourSpace.Parse(pMN); break;
+ case 0x2FB523: GammaValue.Parse(pMN); break;
+ case 0x2383E3: FramePerSec.Parse(pMN); break;
+ EndChunk
}
HRESULT Audio::Parse(CMatroskaNode* pMN0)
{
- BeginChunk
-case 0xB5:
- SamplingFrequency.Parse(pMN);
- break;
-case 0x78B5:
- OutputSamplingFrequency.Parse(pMN);
- break;
-case 0x9F:
- Channels.Parse(pMN);
- break;
-case 0x7D7B:
- ChannelPositions.Parse(pMN);
- break;
-case 0x6264:
- BitDepth.Parse(pMN);
- break;
- EndChunk
+ BeginChunk
+ case 0xB5: SamplingFrequency.Parse(pMN); break;
+ case 0x78B5: OutputSamplingFrequency.Parse(pMN); break;
+ case 0x9F: Channels.Parse(pMN); break;
+ case 0x7D7B: ChannelPositions.Parse(pMN); break;
+ case 0x6264: BitDepth.Parse(pMN); break;
+ EndChunk
}
HRESULT ContentEncodings::Parse(CMatroskaNode* pMN0)
{
- BeginChunk
-case 0x6240:
- ce.Parse(pMN);
- break;
- EndChunk
+ BeginChunk
+ case 0x6240: ce.Parse(pMN); break;
+ EndChunk
}
HRESULT ContentEncoding::Parse(CMatroskaNode* pMN0)
{
- BeginChunk
-case 0x5031:
- ContentEncodingOrder.Parse(pMN);
- break;
-case 0x5032:
- ContentEncodingScope.Parse(pMN);
- break;
-case 0x5033:
- ContentEncodingType.Parse(pMN);
- break;
-case 0x5034:
- cc.Parse(pMN);
- break;
-case 0x5035:
- ce.Parse(pMN);
- break;
- EndChunk
+ BeginChunk
+ case 0x5031: ContentEncodingOrder.Parse(pMN); break;
+ case 0x5032: ContentEncodingScope.Parse(pMN); break;
+ case 0x5033: ContentEncodingType.Parse(pMN); break;
+ case 0x5034: cc.Parse(pMN); break;
+ case 0x5035: ce.Parse(pMN); break;
+ EndChunk
}
HRESULT ContentCompression::Parse(CMatroskaNode* pMN0)
{
- BeginChunk
-case 0x4254:
- ContentCompAlgo.Parse(pMN);
- break;
-case 0x4255:
- ContentCompSettings.Parse(pMN);
- break;
- EndChunk
+ BeginChunk
+ case 0x4254: ContentCompAlgo.Parse(pMN); break;
+ case 0x4255: ContentCompSettings.Parse(pMN); break;
+ EndChunk
}
HRESULT ContentEncryption::Parse(CMatroskaNode* pMN0)
{
- BeginChunk
-case 0x47e1:
- ContentEncAlgo.Parse(pMN);
- break;
-case 0x47e2:
- ContentEncKeyID.Parse(pMN);
- break;
-case 0x47e3:
- ContentSignature.Parse(pMN);
- break;
-case 0x47e4:
- ContentSigKeyID.Parse(pMN);
- break;
-case 0x47e5:
- ContentSigAlgo.Parse(pMN);
- break;
-case 0x47e6:
- ContentSigHashAlgo.Parse(pMN);
- break;
- EndChunk
+ BeginChunk
+ case 0x47e1: ContentEncAlgo.Parse(pMN); break;
+ case 0x47e2: ContentEncKeyID.Parse(pMN); break;
+ case 0x47e3: ContentSignature.Parse(pMN); break;
+ case 0x47e4: ContentSigKeyID.Parse(pMN); break;
+ case 0x47e5: ContentSigAlgo.Parse(pMN); break;
+ case 0x47e6: ContentSigHashAlgo.Parse(pMN); break;
+ EndChunk
}
HRESULT Cluster::Parse(CMatroskaNode* pMN0)
{
- BeginChunk
-case 0xE7:
- TimeCode.Parse(pMN);
- break;
-case 0xA7:
- Position.Parse(pMN);
- break;
-case 0xAB:
- PrevSize.Parse(pMN);
- break;
-case 0xA0:
- BlockGroups.Parse(pMN, true);
- break;
-case 0xA3:
- SimpleBlocks.Parse(pMN, true);
- break;
- EndChunk
+ BeginChunk
+ case 0xE7: TimeCode.Parse(pMN); break;
+ case 0xA7: Position.Parse(pMN); break;
+ case 0xAB: PrevSize.Parse(pMN); break;
+ case 0xA0: BlockGroups.Parse(pMN, true); break;
+ case 0xA3: SimpleBlocks.Parse(pMN, true); break;
+ EndChunk
}
HRESULT Cluster::ParseTimeCode(CMatroskaNode* pMN0)
{
- BeginChunk
-case 0xE7:
- TimeCode.Parse(pMN);
- return S_OK;
- EndChunk
+ BeginChunk
+ case 0xE7: TimeCode.Parse(pMN); return S_OK;
+ EndChunk
}
HRESULT BlockGroup::Parse(CMatroskaNode* pMN0, bool fFull)
{
- BeginChunk
-case 0xA1:
- Block.Parse(pMN, fFull);
- break;
-case 0xA2: /* TODO: multiple virt blocks? */
- ;
- break;
-case 0x9B:
- BlockDuration.Parse(pMN);
- break;
-case 0xFA:
- ReferencePriority.Parse(pMN);
- break;
-case 0xFB:
- ReferenceBlock.Parse(pMN);
- break;
-case 0xFD:
- ReferenceVirtual.Parse(pMN);
- break;
-case 0xA4:
- CodecState.Parse(pMN);
- break;
-case 0xE8:
- TimeSlices.Parse(pMN);
- break;
-case 0x75A1:
- if(fFull) ba.Parse(pMN);
- break;
- EndChunk
+ BeginChunk
+ case 0xA1: Block.Parse(pMN, fFull); break;
+ case 0xA2: /* TODO: multiple virt blocks? */; break;
+ case 0x9B: BlockDuration.Parse(pMN); break;
+ case 0xFA: ReferencePriority.Parse(pMN); break;
+ case 0xFB: ReferenceBlock.Parse(pMN); break;
+ case 0xFD: ReferenceVirtual.Parse(pMN); break;
+ case 0xA4: CodecState.Parse(pMN); break;
+ case 0xE8: TimeSlices.Parse(pMN); break;
+ case 0x75A1: if(fFull) ba.Parse(pMN); break;
+ EndChunk
}
HRESULT SimpleBlock::Parse(CMatroskaNode* pMN, bool fFull)
{
- pMN->SeekTo(pMN->m_start);
-
- TrackNumber.Parse(pMN);
- CShort s;
- s.Parse(pMN);
- TimeCode.Set(s);
- Lacing.Parse(pMN);
-
- if(!fFull) return S_OK;
-
- CAtlList<MatroskaReader::QWORD> lens;
- MatroskaReader::QWORD tlen = 0;
- MatroskaReader::QWORD FrameSize;
- BYTE FramesInLaceLessOne;
-
- switch((Lacing & 0x06) >> 1)
- {
- case 0:
- // No lacing
- lens.AddTail((pMN->m_start + pMN->m_len) - (pMN->GetPos() + tlen));
- break;
- case 1:
- // Xiph lacing
- BYTE n;
- pMN->Read(n);
- while(n-- > 0)
- {
- BYTE b;
- MatroskaReader::QWORD len = 0;
- do
- {
- pMN->Read(b);
- len += b;
- }
- while(b == 0xff);
- lens.AddTail(len);
- tlen += len;
- }
- lens.AddTail((pMN->m_start + pMN->m_len) - (pMN->GetPos() + tlen));
- break;
- case 2:
- // Fixed-size lacing
- pMN->Read(FramesInLaceLessOne);
- FramesInLaceLessOne++;
- FrameSize = ((pMN->m_start + pMN->m_len) - (pMN->GetPos() + tlen)) / FramesInLaceLessOne;
- while(FramesInLaceLessOne-- > 0)
- lens.AddTail(FrameSize);
- break;
- case 3:
- // EBML lacing
- pMN->Read(FramesInLaceLessOne);
-
- CLength FirstFrameSize;
- FirstFrameSize.Parse(pMN);
- lens.AddTail(FirstFrameSize);
- FramesInLaceLessOne--;
- tlen = FirstFrameSize;
-
- CSignedLength DiffSize;
- FrameSize = FirstFrameSize;
- while(FramesInLaceLessOne--)
- {
- DiffSize.Parse(pMN);
- FrameSize += DiffSize;
- lens.AddTail(FrameSize);
- tlen += FrameSize;
- }
- lens.AddTail((pMN->m_start + pMN->m_len) - (pMN->GetPos() + tlen));
- break;
- }
-
- POSITION pos = lens.GetHeadPosition();
- while(pos)
- {
- MatroskaReader::QWORD len = lens.GetNext(pos);
- CAutoPtr<CBinary> p(DNew CBinary());
- p->SetCount((INT_PTR)len);
- pMN->Read(p->GetData(), len);
- BlockData.AddTail(p);
- }
-
- return S_OK;
+ pMN->SeekTo(pMN->m_start);
+
+ TrackNumber.Parse(pMN);
+ CShort s; s.Parse(pMN); TimeCode.Set(s);
+ Lacing.Parse(pMN);
+
+ if(!fFull) return S_OK;
+
+ CAtlList<MatroskaReader::QWORD> lens;
+ MatroskaReader::QWORD tlen = 0;
+ MatroskaReader::QWORD FrameSize;
+ BYTE FramesInLaceLessOne;
+
+ switch((Lacing & 0x06) >> 1)
+ {
+ case 0:
+ // No lacing
+ lens.AddTail((pMN->m_start+pMN->m_len) - (pMN->GetPos()+tlen));
+ break;
+ case 1:
+ // Xiph lacing
+ BYTE n;
+ pMN->Read(n);
+ while(n-- > 0)
+ {
+ BYTE b;
+ MatroskaReader::QWORD len = 0;
+ do {pMN->Read(b); len += b;} while(b == 0xff);
+ lens.AddTail(len);
+ tlen += len;
+ }
+ lens.AddTail((pMN->m_start+pMN->m_len) - (pMN->GetPos()+tlen));
+ break;
+ case 2:
+ // Fixed-size lacing
+ pMN->Read(FramesInLaceLessOne);
+ FramesInLaceLessOne++;
+ FrameSize = ((pMN->m_start+pMN->m_len) - (pMN->GetPos()+tlen)) / FramesInLaceLessOne;
+ while(FramesInLaceLessOne-- > 0)
+ lens.AddTail(FrameSize);
+ break;
+ case 3:
+ // EBML lacing
+ pMN->Read(FramesInLaceLessOne);
+
+ CLength FirstFrameSize;
+ FirstFrameSize.Parse(pMN);
+ lens.AddTail(FirstFrameSize);
+ FramesInLaceLessOne--;
+ tlen = FirstFrameSize;
+
+ CSignedLength DiffSize;
+ FrameSize = FirstFrameSize;
+ while(FramesInLaceLessOne--)
+ {
+ DiffSize.Parse(pMN);
+ FrameSize += DiffSize;
+ lens.AddTail(FrameSize);
+ tlen += FrameSize;
+ }
+ lens.AddTail((pMN->m_start+pMN->m_len) - (pMN->GetPos()+tlen));
+ break;
+ }
+
+ POSITION pos = lens.GetHeadPosition();
+ while(pos)
+ {
+ MatroskaReader::QWORD len = lens.GetNext(pos);
+ CAutoPtr<CBinary> p(DNew CBinary());
+ p->SetCount((INT_PTR)len);
+ pMN->Read(p->GetData(), len);
+ BlockData.AddTail(p);
+ }
+
+ return S_OK;
}
HRESULT BlockAdditions::Parse(CMatroskaNode* pMN0)
{
- BeginChunk
-case 0xA6:
- bm.Parse(pMN);
- break;
- EndChunk
+ BeginChunk
+ case 0xA6: bm.Parse(pMN); break;
+ EndChunk
}
HRESULT BlockMore::Parse(CMatroskaNode* pMN0)
{
- BeginChunk
-case 0xEE:
- BlockAddID.Parse(pMN);
- break;
-case 0xA5:
- BlockAdditional.Parse(pMN);
- break;
- EndChunk
+ BeginChunk
+ case 0xEE: BlockAddID.Parse(pMN); break;
+ case 0xA5: BlockAdditional.Parse(pMN); break;
+ EndChunk
}
HRESULT TimeSlice::Parse(CMatroskaNode* pMN0)
{
- BeginChunk
-case 0xCC:
- LaceNumber.Parse(pMN);
- break;
-case 0xCD:
- FrameNumber.Parse(pMN);
- break;
-case 0xCE:
- Delay.Parse(pMN);
- break;
-case 0xCF:
- Duration.Parse(pMN);
- break;
- EndChunk
+ BeginChunk
+ case 0xCC: LaceNumber.Parse(pMN); break;
+ case 0xCD: FrameNumber.Parse(pMN); break;
+ case 0xCE: Delay.Parse(pMN); break;
+ case 0xCF: Duration.Parse(pMN); break;
+ EndChunk
}
HRESULT Cue::Parse(CMatroskaNode* pMN0)
{
- BeginChunk
-case 0xBB:
- CuePoints.Parse(pMN);
- break;
- EndChunk
+ BeginChunk
+ case 0xBB: CuePoints.Parse(pMN); break;
+ EndChunk
}
HRESULT CuePoint::Parse(CMatroskaNode* pMN0)
{
- BeginChunk
-case 0xB3:
- CueTime.Parse(pMN);
- break;
-case 0xB7:
- CueTrackPositions.Parse(pMN);
- break;
- EndChunk
+ BeginChunk
+ case 0xB3: CueTime.Parse(pMN); break;
+ case 0xB7: CueTrackPositions.Parse(pMN); break;
+ EndChunk
}
HRESULT CueTrackPosition::Parse(CMatroskaNode* pMN0)
{
- BeginChunk
-case 0xF7:
- CueTrack.Parse(pMN);
- break;
-case 0xF1:
- CueClusterPosition.Parse(pMN);
- break;
-case 0x5387:
- CueBlockNumber.Parse(pMN);
- break;
-case 0xEA:
- CueCodecState.Parse(pMN);
- break;
-case 0xDB:
- CueReferences.Parse(pMN);
- break;
- EndChunk
+ BeginChunk
+ case 0xF7: CueTrack.Parse(pMN); break;
+ case 0xF1: CueClusterPosition.Parse(pMN); break;
+ case 0x5387: CueBlockNumber.Parse(pMN); break;
+ case 0xEA: CueCodecState.Parse(pMN); break;
+ case 0xDB: CueReferences.Parse(pMN); break;
+ EndChunk
}
HRESULT CueReference::Parse(CMatroskaNode* pMN0)
{
- BeginChunk
-case 0x96:
- CueRefTime.Parse(pMN);
- break;
-case 0x97:
- CueRefCluster.Parse(pMN);
- break;
-case 0x535F:
- CueRefNumber.Parse(pMN);
- break;
-case 0xEB:
- CueRefCodecState.Parse(pMN);
- break;
- EndChunk
+ BeginChunk
+ case 0x96: CueRefTime.Parse(pMN); break;
+ case 0x97: CueRefCluster.Parse(pMN); break;
+ case 0x535F: CueRefNumber.Parse(pMN); break;
+ case 0xEB: CueRefCodecState.Parse(pMN); break;
+ EndChunk
}
HRESULT Attachment::Parse(CMatroskaNode* pMN0)
{
- BeginChunk
-case 0x61A7:
- AttachedFiles.Parse(pMN);
- break;
- EndChunk
+ BeginChunk
+ case 0x61A7: AttachedFiles.Parse(pMN); break;
+ EndChunk
}
HRESULT AttachedFile::Parse(CMatroskaNode* pMN0)
{
- BeginChunk
-case 0x467E:
- FileDescription.Parse(pMN);
- break;
-case 0x466E:
- FileName.Parse(pMN);
- break;
-case 0x4660:
- FileMimeType.Parse(pMN);
- break;
-case 0x465C: // binary
- FileDataLen = (INT_PTR)pMN->m_len;
- FileDataPos = pMN->m_start;
- break;
-case 0x46AE:
- FileUID.Parse(pMN);
- break;
- EndChunk
+ BeginChunk
+ case 0x467E: FileDescription.Parse(pMN); break;
+ case 0x466E: FileName.Parse(pMN); break;
+ case 0x4660: FileMimeType.Parse(pMN); break;
+ case 0x465C: // binary
+ FileDataLen = (INT_PTR)pMN->m_len;
+ FileDataPos = pMN->m_start;
+ break;
+ case 0x46AE: FileUID.Parse(pMN); break;
+ EndChunk
}
HRESULT Chapter::Parse(CMatroskaNode* pMN0)
{
- BeginChunk
-case 0x45B9:
- EditionEntries.Parse(pMN);
- break;
- EndChunk
+ BeginChunk
+ case 0x45B9: EditionEntries.Parse(pMN); break;
+ EndChunk
}
HRESULT EditionEntry::Parse(CMatroskaNode* pMN0)
{
- BeginChunk
-case 0xB6:
- ChapterAtoms.Parse(pMN);
- break;
- EndChunk
+ BeginChunk
+ case 0xB6: ChapterAtoms.Parse(pMN); break;
+ EndChunk
}
HRESULT ChapterAtom::Parse(CMatroskaNode* pMN0)
{
- BeginChunk
-case 0x73C4:
- ChapterUID.Parse(pMN);
- break;
-case 0x91:
- ChapterTimeStart.Parse(pMN);
- break;
-case 0x92:
- ChapterTimeEnd.Parse(pMN);
- break;
-// case 0x8F: // TODO
-case 0x80:
- ChapterDisplays.Parse(pMN);
- break;
-case 0xB6:
- ChapterAtoms.Parse(pMN);
- break;
-case 0x98:
- ChapterFlagHidden.Parse(pMN);
- break;
-case 0x4598:
- ChapterFlagEnabled.Parse(pMN);
- break;
- EndChunk
+ BeginChunk
+ case 0x73C4: ChapterUID.Parse(pMN); break;
+ case 0x91: ChapterTimeStart.Parse(pMN); break;
+ case 0x92: ChapterTimeEnd.Parse(pMN); break;
+// case 0x8F: // TODO
+ case 0x80: ChapterDisplays.Parse(pMN); break;
+ case 0xB6: ChapterAtoms.Parse(pMN); break;
+ case 0x98: ChapterFlagHidden.Parse(pMN); break;
+ case 0x4598: ChapterFlagEnabled.Parse(pMN); break;
+ EndChunk
}
HRESULT ChapterDisplay::Parse(CMatroskaNode* pMN0)
{
- BeginChunk
-case 0x85:
- ChapString.Parse(pMN);
- break;
-case 0x437C:
- ChapLanguage.Parse(pMN);
- break;
-case 0x437E:
- ChapCountry.Parse(pMN);
- break;
- EndChunk
+ BeginChunk
+ case 0x85: ChapString.Parse(pMN); break;
+ case 0x437C: ChapLanguage.Parse(pMN); break;
+ case 0x437E: ChapCountry.Parse(pMN); break;
+ EndChunk
}
//
HRESULT CBinary::Parse(CMatroskaNode* pMN)
{
- ASSERT(pMN->m_len <= INT_MAX);
- SetCount((INT_PTR)pMN->m_len);
- return pMN->Read(GetData(), pMN->m_len);
+ ASSERT(pMN->m_len <= INT_MAX);
+ SetCount((INT_PTR)pMN->m_len);
+ return pMN->Read(GetData(), pMN->m_len);
}
bool CBinary::Compress(ContentCompression& cc)
{
- if(cc.ContentCompAlgo == ContentCompression::ZLIB)
- {
- int res;
- z_stream c_stream;
-
- c_stream.zalloc = (alloc_func)0;
- c_stream.zfree = (free_func)0;
- c_stream.opaque = (voidpf)0;
-
- if(Z_OK != (res = deflateInit(&c_stream, 9)))
- return(false);
-
- c_stream.next_in = GetData();
- c_stream.avail_in = GetCount();
-
- BYTE* dst = NULL;
- int n = 0;
- do
- {
- dst = (BYTE*)realloc(dst, ++n * 10);
- c_stream.next_out = &dst[(n-1)*10];
- c_stream.avail_out = 10;
- if(Z_OK != (res = deflate(&c_stream, Z_FINISH)) && Z_STREAM_END != res)
- {
- free(dst);
- return(false);
- }
- }
- while(0 == c_stream.avail_out && Z_STREAM_END != res);
-
- deflateEnd(&c_stream);
-
- SetCount(c_stream.total_out);
- memcpy(GetData(), dst, GetCount());
-
- free(dst);
-
- return(true);
- }
+ if(cc.ContentCompAlgo == ContentCompression::ZLIB)
+ {
+ int res;
+ z_stream c_stream;
+
+ c_stream.zalloc = (alloc_func)0;
+ c_stream.zfree = (free_func)0;
+ c_stream.opaque = (voidpf)0;
+
+ if(Z_OK != (res = deflateInit(&c_stream, 9)))
+ return(false);
+
+ c_stream.next_in = GetData();
+ c_stream.avail_in = GetCount();
+
+ BYTE* dst = NULL;
+ int n = 0;
+ do
+ {
+ dst = (BYTE*)realloc(dst, ++n*10);
+ c_stream.next_out = &dst[(n-1)*10];
+ c_stream.avail_out = 10;
+ if(Z_OK != (res = deflate(&c_stream, Z_FINISH)) && Z_STREAM_END != res)
+ {
+ free(dst);
+ return(false);
+ }
+ }
+ while(0 == c_stream.avail_out && Z_STREAM_END != res);
+
+ deflateEnd(&c_stream);
+
+ SetCount(c_stream.total_out);
+ memcpy(GetData(), dst, GetCount());
+
+ free(dst);
+
+ return(true);
+ }
- return(false);
+ return(false);
}
bool CBinary::Decompress(ContentCompression& cc)
{
- if(cc.ContentCompAlgo == ContentCompression::ZLIB)
- {
- int res;
- z_stream d_stream;
-
- d_stream.zalloc = (alloc_func)0;
- d_stream.zfree = (free_func)0;
- d_stream.opaque = (voidpf)0;
-
- if(Z_OK != (res = inflateInit(&d_stream)))
- return(false);
-
- d_stream.next_in = GetData();
- d_stream.avail_in = GetCount();
-
- BYTE* dst = NULL;
- int n = 0;
- do
- {
- dst = (unsigned char *)realloc(dst, ++n * 1000);
- d_stream.next_out = &dst[(n-1)*1000];
- d_stream.avail_out = 1000;
- if(Z_OK != (res = inflate(&d_stream, Z_NO_FLUSH)) && Z_STREAM_END != res)
- {
- free(dst);
- return(false);
- }
- }
- while(0 == d_stream.avail_out && 0 != d_stream.avail_in && Z_STREAM_END != res);
-
- inflateEnd(&d_stream);
-
- SetCount(d_stream.total_out);
- memcpy(GetData(), dst, GetCount());
-
- free(dst);
-
- return(true);
- }
- else if(cc.ContentCompAlgo == ContentCompression::HDRSTRIP)
- {
- InsertArrayAt(0, &cc.ContentCompSettings);
- }
+ if(cc.ContentCompAlgo == ContentCompression::ZLIB)
+ {
+ int res;
+ z_stream d_stream;
+
+ d_stream.zalloc = (alloc_func)0;
+ d_stream.zfree = (free_func)0;
+ d_stream.opaque = (voidpf)0;
+
+ if(Z_OK != (res = inflateInit(&d_stream)))
+ return(false);
+
+ d_stream.next_in = GetData();
+ d_stream.avail_in = GetCount();
+
+ BYTE* dst = NULL;
+ int n = 0;
+ do
+ {
+ dst = (unsigned char *)realloc(dst, ++n*1000);
+ d_stream.next_out = &dst[(n-1)*1000];
+ d_stream.avail_out = 1000;
+ if(Z_OK != (res = inflate(&d_stream, Z_NO_FLUSH)) && Z_STREAM_END != res)
+ {
+ free(dst);
+ return(false);
+ }
+ }
+ while(0 == d_stream.avail_out && 0 != d_stream.avail_in && Z_STREAM_END != res);
+
+ inflateEnd(&d_stream);
+
+ SetCount(d_stream.total_out);
+ memcpy(GetData(), dst, GetCount());
+
+ free(dst);
+
+ return(true);
+ }
+ else if(cc.ContentCompAlgo == ContentCompression::HDRSTRIP)
+ {
+ InsertArrayAt(0, &cc.ContentCompSettings);
+ }
- return(false);
+ return(false);
}
HRESULT CANSI::Parse(CMatroskaNode* pMN)
{
- Empty();
+ Empty();
- MatroskaReader::QWORD len = pMN->m_len;
- CHAR c;
- while(len-- > 0 && SUCCEEDED(pMN->Read(c)))
- *this += c;
+ MatroskaReader::QWORD len = pMN->m_len;
+ CHAR c;
+ while(len-- > 0 && SUCCEEDED(pMN->Read(c)))
+ *this += c;
- return(len == -1 ? S_OK : E_FAIL);
+ return(len == -1 ? S_OK : E_FAIL);
}
HRESULT CUTF8::Parse(CMatroskaNode* pMN)
{
- Empty();
- CAutoVectorPtr<BYTE> buff;
- if(!buff.Allocate((UINT)pMN->m_len + 1) || S_OK != pMN->Read(buff, pMN->m_len))
- return E_FAIL;
- buff[pMN->m_len] = 0;
- CStringW::operator = (UTF8To16((LPCSTR)(BYTE*)buff));
- return S_OK;
+ Empty();
+ CAutoVectorPtr<BYTE> buff;
+ if(!buff.Allocate((UINT)pMN->m_len + 1) || S_OK != pMN->Read(buff, pMN->m_len))
+ return E_FAIL;
+ buff[pMN->m_len] = 0;
+ CStringW::operator = (UTF8To16((LPCSTR)(BYTE*)buff));
+ return S_OK;
}
HRESULT CUInt::Parse(CMatroskaNode* pMN)
{
- m_val = 0;
- for(int i = 0; i < (int)pMN->m_len; i++)
- {
- m_val <<= 8;
- HRESULT hr = pMN->Read(*(BYTE*)&m_val);
- if(FAILED(hr)) return hr;
- }
- m_fValid = true;
- return S_OK;
+ m_val = 0;
+ for(int i = 0; i < (int)pMN->m_len; i++)
+ {
+ m_val <<= 8;
+ HRESULT hr = pMN->Read(*(BYTE*)&m_val);
+ if(FAILED(hr)) return hr;
+ }
+ m_fValid = true;
+ return S_OK;
}
HRESULT CInt::Parse(CMatroskaNode* pMN)
{
- m_val = 0;
- for(int i = 0; i < (int)pMN->m_len; i++)
- {
- HRESULT hr = pMN->Read(*((BYTE*)&m_val + 7 - i));
- if(FAILED(hr)) return hr;
- }
- m_val >>= (8 - pMN->m_len) * 8;
- m_fValid = true;
- return S_OK;
+ m_val = 0;
+ for(int i = 0; i < (int)pMN->m_len; i++)
+ {
+ HRESULT hr = pMN->Read(*((BYTE*)&m_val+7-i));
+ if(FAILED(hr)) return hr;
+ }
+ m_val >>= (8-pMN->m_len)*8;
+ m_fValid = true;
+ return S_OK;
}
HRESULT CFloat::Parse(CMatroskaNode* pMN)
{
- HRESULT hr = E_FAIL;
- m_val = 0;
+ HRESULT hr = E_FAIL;
+ m_val = 0;
- if(pMN->m_len == 4)
- {
- float val = 0;
- hr = pMN->Read(val);
- m_val = val;
- }
- else if(pMN->m_len == 8)
- {
- hr = pMN->Read(m_val);
- }
- if(SUCCEEDED(hr))
- m_fValid = true;
- return hr;
+ if(pMN->m_len == 4)
+ {
+ float val = 0;
+ hr = pMN->Read(val);
+ m_val = val;
+ } else if(pMN->m_len == 8) {
+ hr = pMN->Read(m_val);
+ }
+ if(SUCCEEDED(hr))
+ m_fValid = true;
+ return hr;
}
template<class T, class BASE>
HRESULT CSimpleVar<T, BASE>::Parse(CMatroskaNode* pMN)
{
- m_val = 0;
- m_fValid = true;
- return pMN->Read(m_val);
+ m_val = 0;
+ m_fValid = true;
+ return pMN->Read(m_val);
}
HRESULT CID::Parse(CMatroskaNode* pMN)
{
- m_val = 0;
-
- BYTE b = 0;
- HRESULT hr = pMN->Read(b);
- if(FAILED(hr)) return hr;
-
- int nMoreBytes = 0;
-
- if((b & 0x80) == 0x80)
- {
- m_val = b & 0xff;
- nMoreBytes = 0;
- }
- else if((b & 0xc0) == 0x40)
- {
- m_val = b & 0x7f;
- nMoreBytes = 1;
- }
- else if((b & 0xe0) == 0x20)
- {
- m_val = b & 0x3f;
- nMoreBytes = 2;
- }
- else if((b & 0xf0) == 0x10)
- {
- m_val = b & 0x1f;
- nMoreBytes = 3;
- }
- else return E_FAIL;
-
- while(nMoreBytes-- > 0)
- {
- m_val <<= 8;
- hr = pMN->Read(*(BYTE*)&m_val);
- if(FAILED(hr)) return hr;
- }
-
- m_fValid = true;
-
- return S_OK;
+ m_val = 0;
+
+ BYTE b = 0;
+ HRESULT hr = pMN->Read(b);
+ if(FAILED(hr)) return hr;
+
+ int nMoreBytes = 0;
+
+ if((b&0x80) == 0x80) {m_val = b&0xff; nMoreBytes = 0;}
+ else if((b&0xc0) == 0x40) {m_val = b&0x7f; nMoreBytes = 1;}
+ else if((b&0xe0) == 0x20) {m_val = b&0x3f; nMoreBytes = 2;}
+ else if((b&0xf0) == 0x10) {m_val = b&0x1f; nMoreBytes = 3;}
+ else return E_FAIL;
+
+ while(nMoreBytes-- > 0)
+ {
+ m_val <<= 8;
+ hr = pMN->Read(*(BYTE*)&m_val);
+ if(FAILED(hr)) return hr;
+ }
+
+ m_fValid = true;
+
+ return S_OK;
}
HRESULT CLength::Parse(CMatroskaNode* pMN)
{
- m_val = 0;
-
- BYTE b = 0;
- HRESULT hr = pMN->Read(b);
- if(FAILED(hr)) return hr;
-
- int nMoreBytes = 0, nMoreBytesTmp = 0;
-
- if((b & 0x80) == 0x80)
- {
- m_val = b & 0x7f;
- nMoreBytes = 0;
- }
- else if((b & 0xc0) == 0x40)
- {
- m_val = b & 0x3f;
- nMoreBytes = 1;
- }
- else if((b & 0xe0) == 0x20)
- {
- m_val = b & 0x1f;
- nMoreBytes = 2;
- }
- else if((b & 0xf0) == 0x10)
- {
- m_val = b & 0x0f;
- nMoreBytes = 3;
- }
- else if((b & 0xf8) == 0x08)
- {
- m_val = b & 0x07;
- nMoreBytes = 4;
- }
- else if((b & 0xfc) == 0x04)
- {
- m_val = b & 0x03;
- nMoreBytes = 5;
- }
- else if((b & 0xfe) == 0x02)
- {
- m_val = b & 0x01;
- nMoreBytes = 6;
- }
- else if((b & 0xff) == 0x01)
- {
- m_val = b & 0x00;
- nMoreBytes = 7;
- }
- else return E_FAIL;
-
- nMoreBytesTmp = nMoreBytes;
-
- MatroskaReader::QWORD UnknownSize = (1i64 << (7 * (nMoreBytes + 1))) - 1;
-
- while(nMoreBytes-- > 0)
- {
- m_val <<= 8;
- hr = pMN->Read(*(BYTE*)&m_val);
- if(FAILED(hr)) return hr;
- }
-
- if(m_val == UnknownSize)
- {
- m_val = pMN->GetLength() - pMN->GetPos();
- TRACE(_T("CLength: Unspecified chunk size at %I64d (corrected to %I64d)\n"), pMN->GetPos(), m_val);
- }
-
- if(m_fSigned)
- m_val -= (UnknownSize >> 1);
-
- m_fValid = true;
-
- return S_OK;
+ m_val = 0;
+
+ BYTE b = 0;
+ HRESULT hr = pMN->Read(b);
+ if(FAILED(hr)) return hr;
+
+ int nMoreBytes = 0, nMoreBytesTmp = 0;
+
+ if((b&0x80) == 0x80) {m_val = b&0x7f; nMoreBytes = 0;}
+ else if((b&0xc0) == 0x40) {m_val = b&0x3f; nMoreBytes = 1;}
+ else if((b&0xe0) == 0x20) {m_val = b&0x1f; nMoreBytes = 2;}
+ else if((b&0xf0) == 0x10) {m_val = b&0x0f; nMoreBytes = 3;}
+ else if((b&0xf8) == 0x08) {m_val = b&0x07; nMoreBytes = 4;}
+ else if((b&0xfc) == 0x04) {m_val = b&0x03; nMoreBytes = 5;}
+ else if((b&0xfe) == 0x02) {m_val = b&0x01; nMoreBytes = 6;}
+ else if((b&0xff) == 0x01) {m_val = b&0x00; nMoreBytes = 7;}
+ else return E_FAIL;
+
+ nMoreBytesTmp = nMoreBytes;
+
+ MatroskaReader::QWORD UnknownSize = (1i64<<(7*(nMoreBytes+1)))-1;
+
+ while(nMoreBytes-- > 0)
+ {
+ m_val <<= 8;
+ hr = pMN->Read(*(BYTE*)&m_val);
+ if(FAILED(hr)) return hr;
+ }
+
+ if(m_val == UnknownSize)
+ {
+ m_val = pMN->GetLength() - pMN->GetPos();
+ TRACE(_T("CLength: Unspecified chunk size at %I64d (corrected to %I64d)\n"), pMN->GetPos(), m_val);
+ }
+
+ if(m_fSigned)
+ m_val -= (UnknownSize >> 1);
+
+ m_fValid = true;
+
+ return S_OK;
}
/*
HRESULT CSignedLength::Parse(CMatroskaNode* pMN)
@@ -1343,232 +986,214 @@ HRESULT CSignedLength::Parse(CMatroskaNode* pMN)
template<class T>
HRESULT CNode<T>::Parse(CMatroskaNode* pMN)
{
- CAutoPtr<T> p(DNew T());
- HRESULT hr = E_OUTOFMEMORY;
- if(!p || FAILED(hr = p->Parse(pMN))) return hr;
- AddTail(p);
- return S_OK;
+ CAutoPtr<T> p(DNew T());
+ HRESULT hr = E_OUTOFMEMORY;
+ if(!p || FAILED(hr = p->Parse(pMN))) return hr;
+ AddTail(p);
+ return S_OK;
}
HRESULT CBlockGroupNode::Parse(CMatroskaNode* pMN, bool fFull)
{
- CAutoPtr<BlockGroup> p(DNew BlockGroup());
- HRESULT hr = E_OUTOFMEMORY;
- if(!p || FAILED(hr = p->Parse(pMN, fFull))) return hr;
- AddTail(p);
- return S_OK;
+ CAutoPtr<BlockGroup> p(DNew BlockGroup());
+ HRESULT hr = E_OUTOFMEMORY;
+ if(!p || FAILED(hr = p->Parse(pMN, fFull))) return hr;
+ AddTail(p);
+ return S_OK;
}
HRESULT CSimpleBlockNode::Parse(CMatroskaNode* pMN, bool fFull)
{
- CAutoPtr<SimpleBlock> p(DNew SimpleBlock());
- HRESULT hr = E_OUTOFMEMORY;
- if(!p || FAILED(hr = p->Parse(pMN, fFull))) return hr;
- AddTail(p);
- return S_OK;
+ CAutoPtr<SimpleBlock> p(DNew SimpleBlock());
+ HRESULT hr = E_OUTOFMEMORY;
+ if(!p || FAILED(hr = p->Parse(pMN, fFull))) return hr;
+ AddTail(p);
+ return S_OK;
}
///////////////////////////////
CMatroskaNode::CMatroskaNode(CMatroskaFile* pMF)
- : m_pMF(pMF)
- , m_pParent(NULL)
+ : m_pMF(pMF)
+ , m_pParent(NULL)
{
- ASSERT(m_pMF);
- m_start = m_filepos = 0;
- m_len.Set(m_pMF ? m_pMF->GetLength() : 0);
+ ASSERT(m_pMF);
+ m_start = m_filepos = 0;
+ m_len.Set(m_pMF ? m_pMF->GetLength() : 0);
}
CMatroskaNode::CMatroskaNode(CMatroskaNode* pParent)
- : m_pMF(pParent->m_pMF)
- , m_pParent(pParent)
+ : m_pMF(pParent->m_pMF)
+ , m_pParent(pParent)
{
- Parse();
+ Parse();
}
HRESULT CMatroskaNode::Parse()
{
- m_filepos = GetPos();
- if(FAILED(m_id.Parse(this)) || FAILED(m_len.Parse(this)))
- return E_FAIL;
- m_start = GetPos();
- return S_OK;
+ m_filepos = GetPos();
+ if(FAILED(m_id.Parse(this)) || FAILED(m_len.Parse(this)))
+ return E_FAIL;
+ m_start = GetPos();
+ return S_OK;
}
CAutoPtr<CMatroskaNode> CMatroskaNode::Child(DWORD id, bool fSearch)
{
- if(m_len == 0) return CAutoPtr<CMatroskaNode>();
- SeekTo(m_start);
- CAutoPtr<CMatroskaNode> pMN(DNew CMatroskaNode(this));
- if(id && !pMN->Find(id, fSearch)) pMN.Free();
- return pMN;
+ if(m_len == 0) return CAutoPtr<CMatroskaNode>();
+ SeekTo(m_start);
+ CAutoPtr<CMatroskaNode> pMN(DNew CMatroskaNode(this));
+ if(id && !pMN->Find(id, fSearch)) pMN.Free();
+ return pMN;
}
bool CMatroskaNode::Next(bool fSame)
{
- if(!m_pParent)
- return(false);
+ if(!m_pParent)
+ return(false);
- CID id = m_id;
+ CID id = m_id;
- while(m_start + m_len < m_pParent->m_start + m_pParent->m_len)
- {
- SeekTo(m_start + m_len);
+ while(m_start+m_len < m_pParent->m_start+m_pParent->m_len)
+ {
+ SeekTo(m_start+m_len);
- if(FAILED(Parse()))
- {
- if(!Resync())
- return(false);
- }
+ if(FAILED(Parse()))
+ {
+ if(!Resync())
+ return(false);
+ }
- if(!fSame || m_id == id)
- return(true);
- }
+ if(!fSame || m_id == id)
+ return(true);
+ }
- return(false);
+ return(false);
}
bool CMatroskaNode::Find(DWORD id, bool fSearch)
{
- MatroskaReader::QWORD pos = m_pParent && m_pParent->m_id == 0x18538067 /*segment?*/
- ? FindPos(id)
- : 0;
+ MatroskaReader::QWORD pos = m_pParent && m_pParent->m_id == 0x18538067 /*segment?*/
+ ? FindPos(id)
+ : 0;
- if(pos)
- {
- SeekTo(pos);
- Parse();
- }
- else if(fSearch)
- {
- while(m_id != id && Next());
- }
+ if(pos)
+ {
+ SeekTo(pos);
+ Parse();
+ }
+ else if(fSearch)
+ {
+ while(m_id != id && Next());
+ }
- return(m_id == id);
+ return(m_id == id);
}
-void CMatroskaNode::SeekTo(MatroskaReader::QWORD pos)
-{
- m_pMF->Seek(pos);
-}
-MatroskaReader::QWORD CMatroskaNode::GetPos()
-{
- return m_pMF->GetPos();
-}
-MatroskaReader::QWORD CMatroskaNode::GetLength()
-{
- return m_pMF->GetLength();
-}
-template <class T>
-HRESULT CMatroskaNode::Read(T& var)
-{
- return m_pMF->Read(var);
-}
-HRESULT CMatroskaNode::Read(BYTE* pData, MatroskaReader::QWORD len)
-{
- return m_pMF->ByteRead(pData, len);
-}
+void CMatroskaNode::SeekTo(MatroskaReader::QWORD pos) {m_pMF->Seek(pos);}
+MatroskaReader::QWORD CMatroskaNode::GetPos() {return m_pMF->GetPos();}
+MatroskaReader::QWORD CMatroskaNode::GetLength() {return m_pMF->GetLength();}
+template <class T>
+HRESULT CMatroskaNode::Read(T& var) {return m_pMF->Read(var);}
+HRESULT CMatroskaNode::Read(BYTE* pData, MatroskaReader::QWORD len) {return m_pMF->ByteRead(pData, len);}
MatroskaReader::QWORD CMatroskaNode::FindPos(DWORD id, MatroskaReader::QWORD start)
{
- Segment& sm = m_pMF->m_segment;
+ Segment& sm = m_pMF->m_segment;
- POSITION pos = sm.MetaSeekInfo.GetHeadPosition();
- while(pos)
- {
- Seek* s = sm.MetaSeekInfo.GetNext(pos);
-
- POSITION pos2 = s->SeekHeads.GetHeadPosition();
- while(pos2)
- {
- SeekHead* sh = s->SeekHeads.GetNext(pos2);
- if(sh->SeekID == id && sh->SeekPosition + sm.pos >= start)
- return sh->SeekPosition + sm.pos;
- }
- }
+ POSITION pos = sm.MetaSeekInfo.GetHeadPosition();
+ while(pos)
+ {
+ Seek* s = sm.MetaSeekInfo.GetNext(pos);
+
+ POSITION pos2 = s->SeekHeads.GetHeadPosition();
+ while(pos2)
+ {
+ SeekHead* sh = s->SeekHeads.GetNext(pos2);
+ if(sh->SeekID == id && sh->SeekPosition+sm.pos >= start)
+ return sh->SeekPosition+sm.pos;
+ }
+ }
- return 0;
+ return 0;
}
CAutoPtr<CMatroskaNode> CMatroskaNode::Copy()
{
- CAutoPtr<CMatroskaNode> pNewNode(DNew CMatroskaNode(m_pMF));
- pNewNode->m_pParent = m_pParent;
- pNewNode->m_id.Set(m_id);
- pNewNode->m_len.Set(m_len);
- pNewNode->m_filepos = m_filepos;
- pNewNode->m_start = m_start;
- return(pNewNode);
+ CAutoPtr<CMatroskaNode> pNewNode(DNew CMatroskaNode(m_pMF));
+ pNewNode->m_pParent = m_pParent;
+ pNewNode->m_id.Set(m_id);
+ pNewNode->m_len.Set(m_len);
+ pNewNode->m_filepos = m_filepos;
+ pNewNode->m_start = m_start;
+ return(pNewNode);
}
CAutoPtr<CMatroskaNode> CMatroskaNode::GetFirstBlock()
{
- CAutoPtr<CMatroskaNode> pNode = Child();
- do
- {
- if(pNode->m_id == 0xA0 || pNode->m_id == 0xA3) return pNode;
- }
- while(pNode->Next());
- return CAutoPtr<CMatroskaNode>();
+ CAutoPtr<CMatroskaNode> pNode = Child();
+ do {if(pNode->m_id == 0xA0 || pNode->m_id == 0xA3) return pNode;}
+ while(pNode->Next());
+ return CAutoPtr<CMatroskaNode>();
}
bool CMatroskaNode::NextBlock()
{
- if(!m_pParent)
- return(false);
+ if(!m_pParent)
+ return(false);
- CID id = m_id;
+ CID id = m_id;
- while(m_start + m_len < m_pParent->m_start + m_pParent->m_len)
- {
- SeekTo(m_start + m_len);
+ while(m_start+m_len < m_pParent->m_start+m_pParent->m_len)
+ {
+ SeekTo(m_start+m_len);
- if(FAILED(Parse()))
- {
- if(!Resync())
- return(false);
- }
+ if(FAILED(Parse()))
+ {
+ if(!Resync())
+ return(false);
+ }
- if(m_id == 0xA0 || m_id == 0xA3)
- return(true);
- }
+ if(m_id == 0xA0 || m_id == 0xA3)
+ return(true);
+ }
- return(false);
+ return(false);
}
bool CMatroskaNode::Resync()
{
- if(m_pParent->m_id == 0x18538067) /*segment?*/
- {
- SeekTo(m_filepos);
+ if(m_pParent->m_id == 0x18538067) /*segment?*/
+ {
+ SeekTo(m_filepos);
- for(BYTE b = 0; S_OK == Read(b); b = 0)
- {
- if((b & 0xf0) != 0x10)
- continue;
+ for(BYTE b = 0; S_OK == Read(b); b = 0)
+ {
+ if((b&0xf0) != 0x10)
+ continue;
DWORD dw = b;
- Read((BYTE*)&dw + 1, 3);
- bswap((BYTE*)&dw, 4);
-
- switch(dw)
- {
- case 0x1549A966: // SegmentInfo
- case 0x114D9B74: // MetaSeekInfo
- case 0x1654AE6B: // Tracks
- case 0x1F43B675: // Clusters
- case 0x1C53BB6B: // Cues
- case 0x1941A469: // Attachments
- case 0x1043A770: // Chapters
- case 0x1254C367: // Tags
- SeekTo(GetPos() - 4);
- return(SUCCEEDED(Parse()));
- default:
- SeekTo(GetPos() - 3);
- break;
- }
- }
- }
-
- return(false);
+ Read((BYTE*)&dw+1, 3);
+ bswap((BYTE*)&dw, 4);
+
+ switch(dw)
+ {
+ case 0x1549A966: // SegmentInfo
+ case 0x114D9B74: // MetaSeekInfo
+ case 0x1654AE6B: // Tracks
+ case 0x1F43B675: // Clusters
+ case 0x1C53BB6B: // Cues
+ case 0x1941A469: // Attachments
+ case 0x1043A770: // Chapters
+ case 0x1254C367: // Tags
+ SeekTo(GetPos()-4);
+ return(SUCCEEDED(Parse()));
+ default:
+ SeekTo(GetPos()-3);
+ break;
+ }
+ }
+ }
+
+ return(false);
}
diff --git a/src/filters/parser/MatroskaSplitter/MatroskaFile.h b/src/filters/parser/MatroskaSplitter/MatroskaFile.h
index fd3a0420d..d1106ee24 100644
--- a/src/filters/parser/MatroskaSplitter/MatroskaFile.h
+++ b/src/filters/parser/MatroskaSplitter/MatroskaFile.h
@@ -1,4 +1,4 @@
-/*
+/*
* Copyright (C) 2003-2006 Gabest
* http://www.gabest.org
*
@@ -6,15 +6,15 @@
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2, or (at your option)
* any later version.
- *
+ *
* This Program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with GNU Make; see the file COPYING. If not, write to
- * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
+ * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
* http://www.gnu.org/copyleft/gpl.html
*
*/
@@ -27,568 +27,449 @@
namespace MatroskaReader
{
-class CMatroskaNode;
-
-typedef unsigned __int64 QWORD;
-
-class CANSI : public CStringA
-{
-public:
- HRESULT Parse(CMatroskaNode* pMN);
-};
-class CUTF8 : public CStringW
-{
-public:
- HRESULT Parse(CMatroskaNode* pMN);
-};
-
-template<class T, class BASE>
-class CSimpleVar
-{
-protected:
- T m_val;
- bool m_fValid;
-public:
- CSimpleVar(T val = 0) : m_val(val), m_fValid(false) {}
- BASE& operator = (const BASE& v)
- {
- m_val = v.m_val;
- m_fValid = true;
- return(*this);
- }
- BASE& operator = (T val)
- {
- m_val = val;
- m_fValid = true;
- return(*this);
- }
- operator T() const
- {
- return m_val;
- }
- BASE& Set(T val)
- {
- m_val = val;
- m_fValid = true;
- return(*(BASE*)this);
- }
- bool IsValid() const
- {
- return m_fValid;
- }
- virtual HRESULT Parse(CMatroskaNode* pMN);
-};
-
-class CUInt : public CSimpleVar<UINT64, CUInt>
-{
-public:
- HRESULT Parse(CMatroskaNode* pMN);
-};
-class CInt : public CSimpleVar<INT64, CInt>
-{
-public:
- HRESULT Parse(CMatroskaNode* pMN);
-};
-class CByte : public CSimpleVar<BYTE, CByte> {};
-class CShort : public CSimpleVar<short, CShort> {};
-class CFloat : public CSimpleVar<double, CFloat>
-{
-public:
- HRESULT Parse(CMatroskaNode* pMN);
-};
-class CID : public CSimpleVar<DWORD, CID>
-{
-public:
- HRESULT Parse(CMatroskaNode* pMN);
-};
-class CLength : public CSimpleVar<UINT64, CLength>
-{
- bool m_fSigned;
-public:
- CLength(bool fSigned = false) : m_fSigned(fSigned) {} HRESULT Parse(CMatroskaNode* pMN);
-};
-class CSignedLength : public CLength
-{
-public:
- CSignedLength() : CLength(true) {}};
-
-class ContentCompression;
-
-class CBinary : public CAtlArray<BYTE>
-{
-public:
- CBinary& operator = (const CBinary& b)
- {
- Copy(b);
- return(*this);
- }
- CStringA ToString()
- {
- return CStringA((LPCSTR)GetData(), GetCount());
- }
- bool Compress(ContentCompression& cc), Decompress(ContentCompression& cc);
- HRESULT Parse(CMatroskaNode* pMN);
-};
-
-template<class T>
-class CNode : public CAutoPtrList<T>
-{
-public:
- HRESULT Parse(CMatroskaNode* pMN);
-};
-
-class EBML
-{
-public:
- CUInt EBMLVersion, EBMLReadVersion;
- CUInt EBMLMaxIDLength, EBMLMaxSizeLength;
- CANSI DocType;
- CUInt DocTypeVersion, DocTypeReadVersion;
-
- HRESULT Parse(CMatroskaNode* pMN);
-};
-
-class Info
-{
-public:
- CBinary SegmentUID, PrevUID, NextUID;
- CUTF8 SegmentFilename, PrevFilename, NextFilename;
- CUInt TimeCodeScale; // [ns], default: 1.000.000
- CFloat Duration;
- CInt DateUTC;
- CUTF8 Title, MuxingApp, WritingApp;
-
- Info()
- {
- TimeCodeScale.Set(1000000ui64);
- }
- HRESULT Parse(CMatroskaNode* pMN);
-};
-
-class SeekHead
-{
-public:
- CID SeekID;
- CUInt SeekPosition;
-
- HRESULT Parse(CMatroskaNode* pMN);
-};
-
-class Seek
-{
-public:
- CNode<SeekHead> SeekHeads;
-
- HRESULT Parse(CMatroskaNode* pMN);
-};
-
-class TimeSlice
-{
-public:
- CUInt LaceNumber, FrameNumber;
- CUInt Delay, Duration;
-
- HRESULT Parse(CMatroskaNode* pMN);
-};
-
-class SimpleBlock
-{
-public:
- CLength TrackNumber;
- CInt TimeCode;
- CByte Lacing;
- CAutoPtrList<CBinary> BlockData;
-
- HRESULT Parse(CMatroskaNode* pMN, bool fFull);
-};
-
-class BlockMore
-{
-public:
- CInt BlockAddID;
- CBinary BlockAdditional;
-
- BlockMore()
- {
- BlockAddID.Set(1);
- }
- HRESULT Parse(CMatroskaNode* pMN);
-};
-
-class BlockAdditions
-{
-public:
- CNode<BlockMore> bm;
-
- HRESULT Parse(CMatroskaNode* pMN);
-};
-
-class BlockGroup
-{
-public:
- SimpleBlock Block;
+ class CMatroskaNode;
+
+ typedef unsigned __int64 QWORD;
+
+ class CANSI : public CStringA {public: HRESULT Parse(CMatroskaNode* pMN);};
+ class CUTF8 : public CStringW {public: HRESULT Parse(CMatroskaNode* pMN);};
+
+ template<class T, class BASE>
+ class CSimpleVar
+ {
+ protected:
+ T m_val;
+ bool m_fValid;
+ public:
+ CSimpleVar(T val = 0) : m_val(val), m_fValid(false) {}
+ BASE& operator = (const BASE& v) {m_val = v.m_val; m_fValid = true; return(*this);}
+ BASE& operator = (T val) {m_val = val; m_fValid = true; return(*this);}
+ operator T() const {return m_val;}
+ BASE& Set(T val) {m_val = val; m_fValid = true; return(*(BASE*)this);}
+ bool IsValid() const {return m_fValid;}
+ virtual HRESULT Parse(CMatroskaNode* pMN);
+ };
+
+ class CUInt : public CSimpleVar<UINT64, CUInt> {public: HRESULT Parse(CMatroskaNode* pMN);};
+ class CInt : public CSimpleVar<INT64, CInt> {public: HRESULT Parse(CMatroskaNode* pMN);};
+ class CByte : public CSimpleVar<BYTE, CByte> {};
+ class CShort : public CSimpleVar<short, CShort> {};
+ class CFloat : public CSimpleVar<double, CFloat> {public: HRESULT Parse(CMatroskaNode* pMN);};
+ class CID : public CSimpleVar<DWORD, CID> {public: HRESULT Parse(CMatroskaNode* pMN);};
+ class CLength : public CSimpleVar<UINT64, CLength> {bool m_fSigned; public: CLength(bool fSigned = false) : m_fSigned(fSigned) {} HRESULT Parse(CMatroskaNode* pMN);};
+ class CSignedLength : public CLength {public: CSignedLength() : CLength(true) {}};
+
+ class ContentCompression;
+
+ class CBinary : public CAtlArray<BYTE>
+ {
+ public:
+ CBinary& operator = (const CBinary& b) {Copy(b); return(*this);}
+ CStringA ToString() {return CStringA((LPCSTR)GetData(), GetCount());}
+ bool Compress(ContentCompression& cc), Decompress(ContentCompression& cc);
+ HRESULT Parse(CMatroskaNode* pMN);
+ };
+
+ template<class T>
+ class CNode : public CAutoPtrList<T> {public: HRESULT Parse(CMatroskaNode* pMN);};
+
+ class EBML
+ {
+ public:
+ CUInt EBMLVersion, EBMLReadVersion;
+ CUInt EBMLMaxIDLength, EBMLMaxSizeLength;
+ CANSI DocType;
+ CUInt DocTypeVersion, DocTypeReadVersion;
+
+ HRESULT Parse(CMatroskaNode* pMN);
+ };
+
+ class Info
+ {
+ public:
+ CBinary SegmentUID, PrevUID, NextUID;
+ CUTF8 SegmentFilename, PrevFilename, NextFilename;
+ CUInt TimeCodeScale; // [ns], default: 1.000.000
+ CFloat Duration;
+ CInt DateUTC;
+ CUTF8 Title, MuxingApp, WritingApp;
+
+ Info() {TimeCodeScale.Set(1000000ui64);}
+ HRESULT Parse(CMatroskaNode* pMN);
+ };
+
+ class SeekHead
+ {
+ public:
+ CID SeekID;
+ CUInt SeekPosition;
+
+ HRESULT Parse(CMatroskaNode* pMN);
+ };
+
+ class Seek
+ {
+ public:
+ CNode<SeekHead> SeekHeads;
+
+ HRESULT Parse(CMatroskaNode* pMN);
+ };
+
+ class TimeSlice
+ {
+ public:
+ CUInt LaceNumber, FrameNumber;
+ CUInt Delay, Duration;
+
+ HRESULT Parse(CMatroskaNode* pMN);
+ };
+
+ class SimpleBlock
+ {
+ public:
+ CLength TrackNumber;
+ CInt TimeCode;
+ CByte Lacing;
+ CAutoPtrList<CBinary> BlockData;
+
+ HRESULT Parse(CMatroskaNode* pMN, bool fFull);
+ };
+
+ class BlockMore
+ {
+ public:
+ CInt BlockAddID;
+ CBinary BlockAdditional;
+
+ BlockMore() {BlockAddID.Set(1);}
+ HRESULT Parse(CMatroskaNode* pMN);
+ };
+
+ class BlockAdditions
+ {
+ public:
+ CNode<BlockMore> bm;
+
+ HRESULT Parse(CMatroskaNode* pMN);
+ };
+
+ class BlockGroup
+ {
+ public:
+ SimpleBlock Block;
// BlockVirtual
- CUInt BlockDuration;
- CUInt ReferencePriority;
- CInt ReferenceBlock;
- CInt ReferenceVirtual;
- CBinary CodecState;
- CNode<TimeSlice> TimeSlices;
- BlockAdditions ba;
-
- HRESULT Parse(CMatroskaNode* pMN, bool fFull);
-};
-
-class CBlockGroupNode : public CNode<BlockGroup>
-{
-public:
- HRESULT Parse(CMatroskaNode* pMN, bool fFull);
-};
-
-class CSimpleBlockNode : public CNode<SimpleBlock>
-{
-public:
- HRESULT Parse(CMatroskaNode* pMN, bool fFull);
-};
-
-class Cluster
-{
-public:
- CUInt TimeCode, Position, PrevSize;
- CBlockGroupNode BlockGroups;
- CSimpleBlockNode SimpleBlocks;
-
- HRESULT Parse(CMatroskaNode* pMN);
- HRESULT ParseTimeCode(CMatroskaNode* pMN);
-};
-
-class Video
-{
-public:
- CUInt FlagInterlaced, StereoMode;
- CUInt PixelWidth, PixelHeight, DisplayWidth, DisplayHeight, DisplayUnit;
- CUInt AspectRatioType;
- CUInt ColourSpace;
- CFloat GammaValue;
- CFloat FramePerSec;
-
- HRESULT Parse(CMatroskaNode* pMN);
-};
-
-class Audio
-{
-public:
- CFloat SamplingFrequency;
- CFloat OutputSamplingFrequency;
- CUInt Channels;
- CBinary ChannelPositions;
- CUInt BitDepth;
-
- Audio()
- {
- SamplingFrequency.Set(8000.0);
- Channels.Set(1);
- }
- HRESULT Parse(CMatroskaNode* pMN);
-};
-
-class ContentCompression
-{
-public:
- CUInt ContentCompAlgo;
- enum {ZLIB, BZLIB, LZO1X, HDRSTRIP};
- CBinary ContentCompSettings;
-
- ContentCompression()
- {
- ContentCompAlgo.Set(ZLIB);
- }
- HRESULT Parse(CMatroskaNode* pMN);
-};
-
-class ContentEncryption
-{
-public:
- CUInt ContentEncAlgo;
- enum {UNKE, DES, THREEDES, TWOFISH, BLOWFISH, AES};
- CBinary ContentEncKeyID, ContentSignature, ContentSigKeyID;
- CUInt ContentSigAlgo;
- enum {UNKS, RSA};
- CUInt ContentSigHashAlgo;
- enum {UNKSH, SHA1_160, MD5};
-
- ContentEncryption()
- {
- ContentEncAlgo.Set(0);
- ContentSigAlgo.Set(0);
- ContentSigHashAlgo.Set(0);
- }
- HRESULT Parse(CMatroskaNode* pMN);
-};
-
-class ContentEncoding
-{
-public:
- CUInt ContentEncodingOrder;
- CUInt ContentEncodingScope;
- enum {AllFrameContents = 1, TracksPrivateData = 2};
- CUInt ContentEncodingType;
- enum {Compression, Encryption};
- ContentCompression cc;
- ContentEncryption ce;
-
- ContentEncoding()
- {
- ContentEncodingOrder.Set(0);
- ContentEncodingScope.Set(AllFrameContents);
- ContentEncodingType.Set(Compression);
- }
- HRESULT Parse(CMatroskaNode* pMN);
-};
-
-class ContentEncodings
-{
-public:
- CNode<ContentEncoding> ce;
-
- ContentEncodings() {}
- HRESULT Parse(CMatroskaNode* pMN);
-};
-
-class TrackEntry
-{
-public:
- enum {TypeVideo = 1, TypeAudio = 2, TypeComplex = 3, TypeLogo = 0x10, TypeSubtitle = 0x11, TypeControl = 0x20};
- CUInt TrackNumber, TrackUID, TrackType;
- CUInt FlagEnabled, FlagDefault, FlagLacing;
- CUInt MinCache, MaxCache;
- CUTF8 Name;
- CANSI Language;
- CBinary CodecID;
- CBinary CodecPrivate;
- CUTF8 CodecName;
- CUTF8 CodecSettings;
- CANSI CodecInfoURL;
- CANSI CodecDownloadURL;
- CUInt CodecDecodeAll;
- CUInt TrackOverlay;
- CUInt DefaultDuration;
- CFloat TrackTimecodeScale;
- enum {NoDesc = 0, DescVideo = 1, DescAudio = 2};
- int DescType;
- Video v;
- Audio a;
- ContentEncodings ces;
- TrackEntry()
- {
- DescType = NoDesc;
- FlagEnabled.Set(1);
- FlagDefault.Set(1);
- FlagLacing.Set(1);
- }
- HRESULT Parse(CMatroskaNode* pMN);
-
- bool Expand(CBinary& data, UINT64 Scope);
-};
-
-class Track
-{
-public:
- CNode<TrackEntry> TrackEntries;
-
- HRESULT Parse(CMatroskaNode* pMN);
-};
-
-class CueReference
-{
-public:
- CUInt CueRefTime, CueRefCluster, CueRefNumber, CueRefCodecState;
-
- HRESULT Parse(CMatroskaNode* pMN);
-};
-
-class CueTrackPosition
-{
-public:
- CUInt CueTrack, CueClusterPosition, CueBlockNumber, CueCodecState;
- CNode<CueReference> CueReferences;
-
- HRESULT Parse(CMatroskaNode* pMN);
-};
-
-class CuePoint
-{
-public:
- CUInt CueTime;
- CNode<CueTrackPosition> CueTrackPositions;
-
- HRESULT Parse(CMatroskaNode* pMN);
-};
-
-class Cue
-{
-public:
- CNode<CuePoint> CuePoints;
-
- HRESULT Parse(CMatroskaNode* pMN);
-};
-
-class AttachedFile
-{
-public:
- CUTF8 FileDescription;
- CUTF8 FileName;
- CANSI FileMimeType;
- QWORD FileDataPos, FileDataLen; // BYTE* FileData
- CUInt FileUID;
-
- AttachedFile()
- {
- FileDataPos = FileDataLen = 0;
- }
- HRESULT Parse(CMatroskaNode* pMN);
-};
-
-class Attachment
-{
-public:
- CNode<AttachedFile> AttachedFiles;
-
- HRESULT Parse(CMatroskaNode* pMN);
-};
-
-class ChapterDisplay
-{
-public:
- CUTF8 ChapString;
- CANSI ChapLanguage;
- CANSI ChapCountry;
-
- ChapterDisplay()
- {
- ChapLanguage.CStringA::operator = ("eng");
- }
- HRESULT Parse(CMatroskaNode* pMN);
-};
-
-class ChapterAtom
-{
-public:
- CUInt ChapterUID;
- CUInt ChapterTimeStart, ChapterTimeEnd, ChapterFlagHidden, ChapterFlagEnabled;
+ CUInt BlockDuration;
+ CUInt ReferencePriority;
+ CInt ReferenceBlock;
+ CInt ReferenceVirtual;
+ CBinary CodecState;
+ CNode<TimeSlice> TimeSlices;
+ BlockAdditions ba;
+
+ HRESULT Parse(CMatroskaNode* pMN, bool fFull);
+ };
+
+ class CBlockGroupNode : public CNode<BlockGroup>
+ {
+ public:
+ HRESULT Parse(CMatroskaNode* pMN, bool fFull);
+ };
+
+ class CSimpleBlockNode : public CNode<SimpleBlock>
+ {
+ public:
+ HRESULT Parse(CMatroskaNode* pMN, bool fFull);
+ };
+
+ class Cluster
+ {
+ public:
+ CUInt TimeCode, Position, PrevSize;
+ CBlockGroupNode BlockGroups;
+ CSimpleBlockNode SimpleBlocks;
+
+ HRESULT Parse(CMatroskaNode* pMN);
+ HRESULT ParseTimeCode(CMatroskaNode* pMN);
+ };
+
+ class Video
+ {
+ public:
+ CUInt FlagInterlaced, StereoMode;
+ CUInt PixelWidth, PixelHeight, DisplayWidth, DisplayHeight, DisplayUnit;
+ CUInt AspectRatioType;
+ CUInt ColourSpace;
+ CFloat GammaValue;
+ CFloat FramePerSec;
+
+ HRESULT Parse(CMatroskaNode* pMN);
+ };
+
+ class Audio
+ {
+ public:
+ CFloat SamplingFrequency;
+ CFloat OutputSamplingFrequency;
+ CUInt Channels;
+ CBinary ChannelPositions;
+ CUInt BitDepth;
+
+ Audio() {SamplingFrequency.Set(8000.0); Channels.Set(1);}
+ HRESULT Parse(CMatroskaNode* pMN);
+ };
+
+ class ContentCompression
+ {
+ public:
+ CUInt ContentCompAlgo; enum {ZLIB, BZLIB, LZO1X, HDRSTRIP};
+ CBinary ContentCompSettings;
+
+ ContentCompression() {ContentCompAlgo.Set(ZLIB);}
+ HRESULT Parse(CMatroskaNode* pMN);
+ };
+
+ class ContentEncryption
+ {
+ public:
+ CUInt ContentEncAlgo; enum {UNKE, DES, THREEDES, TWOFISH, BLOWFISH, AES};
+ CBinary ContentEncKeyID, ContentSignature, ContentSigKeyID;
+ CUInt ContentSigAlgo; enum {UNKS, RSA};
+ CUInt ContentSigHashAlgo; enum {UNKSH, SHA1_160, MD5};
+
+ ContentEncryption() {ContentEncAlgo.Set(0); ContentSigAlgo.Set(0); ContentSigHashAlgo.Set(0);}
+ HRESULT Parse(CMatroskaNode* pMN);
+ };
+
+ class ContentEncoding
+ {
+ public:
+ CUInt ContentEncodingOrder;
+ CUInt ContentEncodingScope; enum {AllFrameContents = 1, TracksPrivateData = 2};
+ CUInt ContentEncodingType; enum {Compression, Encryption};
+ ContentCompression cc;
+ ContentEncryption ce;
+
+ ContentEncoding() {ContentEncodingOrder.Set(0); ContentEncodingScope.Set(AllFrameContents); ContentEncodingType.Set(Compression);}
+ HRESULT Parse(CMatroskaNode* pMN);
+ };
+
+ class ContentEncodings
+ {
+ public:
+ CNode<ContentEncoding> ce;
+
+ ContentEncodings() {}
+ HRESULT Parse(CMatroskaNode* pMN);
+ };
+
+ class TrackEntry
+ {
+ public:
+ enum {TypeVideo = 1, TypeAudio = 2, TypeComplex = 3, TypeLogo = 0x10, TypeSubtitle = 0x11, TypeControl = 0x20};
+ CUInt TrackNumber, TrackUID, TrackType;
+ CUInt FlagEnabled, FlagDefault, FlagLacing;
+ CUInt MinCache, MaxCache;
+ CUTF8 Name;
+ CANSI Language;
+ CBinary CodecID;
+ CBinary CodecPrivate;
+ CUTF8 CodecName;
+ CUTF8 CodecSettings;
+ CANSI CodecInfoURL;
+ CANSI CodecDownloadURL;
+ CUInt CodecDecodeAll;
+ CUInt TrackOverlay;
+ CUInt DefaultDuration;
+ CFloat TrackTimecodeScale;
+ enum {NoDesc = 0, DescVideo = 1, DescAudio = 2};
+ int DescType;
+ Video v;
+ Audio a;
+ ContentEncodings ces;
+ TrackEntry() {DescType = NoDesc; FlagEnabled.Set(1); FlagDefault.Set(1); FlagLacing.Set(1); }
+ HRESULT Parse(CMatroskaNode* pMN);
+
+ bool Expand(CBinary& data, UINT64 Scope);
+ };
+
+ class Track
+ {
+ public:
+ CNode<TrackEntry> TrackEntries;
+
+ HRESULT Parse(CMatroskaNode* pMN);
+ };
+
+ class CueReference
+ {
+ public:
+ CUInt CueRefTime, CueRefCluster, CueRefNumber, CueRefCodecState;
+
+ HRESULT Parse(CMatroskaNode* pMN);
+ };
+
+ class CueTrackPosition
+ {
+ public:
+ CUInt CueTrack, CueClusterPosition, CueBlockNumber, CueCodecState;
+ CNode<CueReference> CueReferences;
+
+ HRESULT Parse(CMatroskaNode* pMN);
+ };
+
+ class CuePoint
+ {
+ public:
+ CUInt CueTime;
+ CNode<CueTrackPosition> CueTrackPositions;
+
+ HRESULT Parse(CMatroskaNode* pMN);
+ };
+
+ class Cue
+ {
+ public:
+ CNode<CuePoint> CuePoints;
+
+ HRESULT Parse(CMatroskaNode* pMN);
+ };
+
+ class AttachedFile
+ {
+ public:
+ CUTF8 FileDescription;
+ CUTF8 FileName;
+ CANSI FileMimeType;
+ QWORD FileDataPos, FileDataLen; // BYTE* FileData
+ CUInt FileUID;
+
+ AttachedFile() {FileDataPos = FileDataLen = 0;}
+ HRESULT Parse(CMatroskaNode* pMN);
+ };
+
+ class Attachment
+ {
+ public:
+ CNode<AttachedFile> AttachedFiles;
+
+ HRESULT Parse(CMatroskaNode* pMN);
+ };
+
+ class ChapterDisplay
+ {
+ public:
+ CUTF8 ChapString;
+ CANSI ChapLanguage;
+ CANSI ChapCountry;
+
+ ChapterDisplay() {ChapLanguage.CStringA::operator = ("eng");}
+ HRESULT Parse(CMatroskaNode* pMN);
+ };
+
+ class ChapterAtom
+ {
+ public:
+ CUInt ChapterUID;
+ CUInt ChapterTimeStart, ChapterTimeEnd, ChapterFlagHidden, ChapterFlagEnabled;
// CNode<CUInt> ChapterTracks; // TODO
- CNode<ChapterDisplay> ChapterDisplays;
- CNode<ChapterAtom> ChapterAtoms;
-
- ChapterAtom()
- {
- ChapterUID.Set(rand());
- ChapterFlagHidden.Set(0);
- ChapterFlagEnabled.Set(1);
- }
- HRESULT Parse(CMatroskaNode* pMN);
- ChapterAtom* FindChapterAtom(UINT64 id);
-};
-
-class EditionEntry : public ChapterAtom
-{
-public:
- HRESULT Parse(CMatroskaNode* pMN);
-};
-
-class Chapter
-{
-public:
- CNode<EditionEntry> EditionEntries;
-
- HRESULT Parse(CMatroskaNode* pMN);
-};
-
-class Segment
-{
-public:
- QWORD pos, len;
- Info SegmentInfo;
- CNode<Seek> MetaSeekInfo;
- CNode<Cluster> Clusters;
- CNode<Track> Tracks;
- CNode<Cue> Cues;
- CNode<Attachment> Attachments;
- CNode<Chapter> Chapters;
- // TODO: Chapters
- // TODO: Tags
-
- HRESULT Parse(CMatroskaNode* pMN);
- HRESULT ParseMinimal(CMatroskaNode* pMN);
-
- UINT64 GetMasterTrack();
-
- REFERENCE_TIME GetRefTime(INT64 t) const
- {
- return t * (REFERENCE_TIME)(SegmentInfo.TimeCodeScale) / 100;
- }
- ChapterAtom* FindChapterAtom(UINT64 id, int nEditionEntry = 0);
-};
-
-class CMatroskaFile : public CBaseSplitterFile
-{
-public:
- CMatroskaFile(IAsyncReader* pAsyncReader, HRESULT& hr);
- virtual ~CMatroskaFile() {}
-
- HRESULT Init();
-
- //using CBaseSplitterFile::Read;
- template <class T> HRESULT Read(T& var);
-
- EBML m_ebml;
- Segment m_segment;
- REFERENCE_TIME m_rtOffset;
-
- HRESULT Parse(CMatroskaNode* pMN);
-};
-
-class CMatroskaNode
-{
- CMatroskaNode* m_pParent;
- CMatroskaFile* m_pMF;
-
- bool Resync();
-
-public:
- CID m_id;
- CLength m_len;
- QWORD m_filepos, m_start;
-
- HRESULT Parse();
-
-public:
- CMatroskaNode(CMatroskaFile* pMF); // creates the root
- CMatroskaNode(CMatroskaNode* pParent);
-
- CMatroskaNode* Parent()
- {
- return m_pParent;
- }
- CAutoPtr<CMatroskaNode> Child(DWORD id = 0, bool fSearch = true);
- bool Next(bool fSame = false);
- bool Find(DWORD id, bool fSearch = true);
-
- QWORD FindPos(DWORD id, QWORD start = 0);
-
- void SeekTo(QWORD pos);
- QWORD GetPos(), GetLength();
- template <class T> HRESULT Read(T& var);
- HRESULT Read(BYTE* pData, QWORD len);
-
- CAutoPtr<CMatroskaNode> Copy();
-
- CAutoPtr<CMatroskaNode> GetFirstBlock();
- bool NextBlock();
-
- bool IsRandomAccess()
- {
- return m_pMF->IsRandomAccess();
- }
-};
+ CNode<ChapterDisplay> ChapterDisplays;
+ CNode<ChapterAtom> ChapterAtoms;
+
+ ChapterAtom() {ChapterUID.Set(rand());ChapterFlagHidden.Set(0);ChapterFlagEnabled.Set(1);}
+ HRESULT Parse(CMatroskaNode* pMN);
+ ChapterAtom* FindChapterAtom(UINT64 id);
+ };
+
+ class EditionEntry : public ChapterAtom
+ {
+ public:
+ HRESULT Parse(CMatroskaNode* pMN);
+ };
+
+ class Chapter
+ {
+ public:
+ CNode<EditionEntry> EditionEntries;
+
+ HRESULT Parse(CMatroskaNode* pMN);
+ };
+
+ class Segment
+ {
+ public:
+ QWORD pos, len;
+ Info SegmentInfo;
+ CNode<Seek> MetaSeekInfo;
+ CNode<Cluster> Clusters;
+ CNode<Track> Tracks;
+ CNode<Cue> Cues;
+ CNode<Attachment> Attachments;
+ CNode<Chapter> Chapters;
+ // TODO: Chapters
+ // TODO: Tags
+
+ HRESULT Parse(CMatroskaNode* pMN);
+ HRESULT ParseMinimal(CMatroskaNode* pMN);
+
+ UINT64 GetMasterTrack();
+
+ REFERENCE_TIME GetRefTime(INT64 t) const {return t*(REFERENCE_TIME)(SegmentInfo.TimeCodeScale)/100;}
+ ChapterAtom* FindChapterAtom(UINT64 id, int nEditionEntry = 0);
+ };
+
+ class CMatroskaFile : public CBaseSplitterFile
+ {
+ public:
+ CMatroskaFile(IAsyncReader* pAsyncReader, HRESULT& hr);
+ virtual ~CMatroskaFile() {}
+
+ HRESULT Init();
+
+ //using CBaseSplitterFile::Read;
+ template <class T> HRESULT Read(T& var);
+
+ EBML m_ebml;
+ Segment m_segment;
+ REFERENCE_TIME m_rtOffset;
+
+ HRESULT Parse(CMatroskaNode* pMN);
+ };
+
+ class CMatroskaNode
+ {
+ CMatroskaNode* m_pParent;
+ CMatroskaFile* m_pMF;
+
+ bool Resync();
+
+ public:
+ CID m_id;
+ CLength m_len;
+ QWORD m_filepos, m_start;
+
+ HRESULT Parse();
+
+ public:
+ CMatroskaNode(CMatroskaFile* pMF); // creates the root
+ CMatroskaNode(CMatroskaNode* pParent);
+
+ CMatroskaNode* Parent() {return m_pParent;}
+ CAutoPtr<CMatroskaNode> Child(DWORD id = 0, bool fSearch = true);
+ bool Next(bool fSame = false);
+ bool Find(DWORD id, bool fSearch = true);
+
+ QWORD FindPos(DWORD id, QWORD start = 0);
+
+ void SeekTo(QWORD pos);
+ QWORD GetPos(), GetLength();
+ template <class T> HRESULT Read(T& var);
+ HRESULT Read(BYTE* pData, QWORD len);
+
+ CAutoPtr<CMatroskaNode> Copy();
+
+ CAutoPtr<CMatroskaNode> GetFirstBlock();
+ bool NextBlock();
+
+ bool IsRandomAccess() {return m_pMF->IsRandomAccess();}
+ };
}
diff --git a/src/filters/parser/MatroskaSplitter/MatroskaSplitter.cpp b/src/filters/parser/MatroskaSplitter/MatroskaSplitter.cpp
index e07e8121c..3922eda99 100644
--- a/src/filters/parser/MatroskaSplitter/MatroskaSplitter.cpp
+++ b/src/filters/parser/MatroskaSplitter/MatroskaSplitter.cpp
@@ -1,4 +1,4 @@
-/*
+/*
* Copyright (C) 2003-2006 Gabest
* http://www.gabest.org
*
@@ -6,15 +6,15 @@
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2, or (at your option)
* any later version.
- *
+ *
* This Program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with GNU Make; see the file COPYING. If not, write to
- * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
+ * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
* http://www.gnu.org/copyleft/gpl.html
*
*/
@@ -32,9 +32,9 @@ using namespace MatroskaReader;
#ifdef REGISTER_FILTER
const AMOVIESETUP_MEDIATYPE sudPinTypesIn[] =
-{
- {&MEDIATYPE_Stream, &MEDIASUBTYPE_Matroska},
- {&MEDIATYPE_Stream, &MEDIASUBTYPE_NULL}
+{
+ {&MEDIATYPE_Stream, &MEDIASUBTYPE_Matroska},
+ {&MEDIATYPE_Stream, &MEDIASUBTYPE_NULL}
};
const AMOVIESETUP_PIN sudpPins[] =
@@ -45,34 +45,34 @@ const AMOVIESETUP_PIN sudpPins[] =
const AMOVIESETUP_FILTER sudFilter[] =
{
- {&__uuidof(CMatroskaSplitterFilter), L"MPC - Matroska Splitter", MERIT_NORMAL, countof(sudpPins), sudpPins, CLSID_LegacyAmFilterCategory},
- {&__uuidof(CMatroskaSourceFilter), L"MPC - Matroska Source", MERIT_NORMAL, 0, NULL, CLSID_LegacyAmFilterCategory},
+ {&__uuidof(CMatroskaSplitterFilter), L"MPC - Matroska Splitter", MERIT_NORMAL, countof(sudpPins), sudpPins, CLSID_LegacyAmFilterCategory},
+ {&__uuidof(CMatroskaSourceFilter), L"MPC - Matroska Source", MERIT_NORMAL, 0, NULL, CLSID_LegacyAmFilterCategory},
};
CFactoryTemplate g_Templates[] =
{
- {sudFilter[0].strName, sudFilter[0].clsID, CreateInstance<CMatroskaSplitterFilter>, NULL, &sudFilter[0]},
- {sudFilter[1].strName, sudFilter[1].clsID, CreateInstance<CMatroskaSourceFilter>, NULL, &sudFilter[1]},
+ {sudFilter[0].strName, sudFilter[0].clsID, CreateInstance<CMatroskaSplitterFilter>, NULL, &sudFilter[0]},
+ {sudFilter[1].strName, sudFilter[1].clsID, CreateInstance<CMatroskaSourceFilter>, NULL, &sudFilter[1]},
};
int g_cTemplates = countof(g_Templates);
STDAPI DllRegisterServer()
{
- RegisterSourceFilter(
- __uuidof(CMatroskaSourceFilter),
- MEDIASUBTYPE_Matroska,
- _T("0,4,,1A45DFA3"),
- _T(".mkv"), _T(".mka"), _T(".mks"), NULL);
+ RegisterSourceFilter(
+ __uuidof(CMatroskaSourceFilter),
+ MEDIASUBTYPE_Matroska,
+ _T("0,4,,1A45DFA3"),
+ _T(".mkv"), _T(".mka"), _T(".mks"), NULL);
- return AMovieDllRegisterServer2(TRUE);
+ return AMovieDllRegisterServer2(TRUE);
}
STDAPI DllUnregisterServer()
{
- UnRegisterSourceFilter(MEDIASUBTYPE_Matroska);
+ UnRegisterSourceFilter(MEDIASUBTYPE_Matroska);
- return AMovieDllRegisterServer2(FALSE);
+ return AMovieDllRegisterServer2(FALSE);
}
#include "../../FilterApp.h"
@@ -86,7 +86,7 @@ CFilterApp theApp;
//
CMatroskaSplitterFilter::CMatroskaSplitterFilter(LPUNKNOWN pUnk, HRESULT* phr)
- : CBaseSplitterFilter(NAME("CMatroskaSplitterFilter"), pUnk, phr, __uuidof(this))
+ : CBaseSplitterFilter(NAME("CMatroskaSplitterFilter"), pUnk, phr, __uuidof(this))
{
}
@@ -96,1023 +96,1001 @@ CMatroskaSplitterFilter::~CMatroskaSplitterFilter()
STDMETHODIMP CMatroskaSplitterFilter::NonDelegatingQueryInterface(REFIID riid, void** ppv)
{
- CheckPointer(ppv, E_POINTER);
+ CheckPointer(ppv, E_POINTER);
- return
- QI(ITrackInfo)
- __super::NonDelegatingQueryInterface(riid, ppv);
+ return
+ QI(ITrackInfo)
+ __super::NonDelegatingQueryInterface(riid, ppv);
}
#include <vector>
HRESULT CMatroskaSplitterFilter::CreateOutputs(IAsyncReader* pAsyncReader)
{
- CheckPointer(pAsyncReader, E_POINTER);
-
- HRESULT hr = E_FAIL;
-
- m_pFile.Free();
- m_pTrackEntryMap.RemoveAll();
- m_pOrderedTrackArray.RemoveAll();
-
- CAtlArray<CMatroskaSplitterOutputPin*> pinOut;
- CAtlArray<TrackEntry*> pinOutTE;
-
- m_pFile.Attach(DNew CMatroskaFile(pAsyncReader, hr));
- if(!m_pFile) return E_OUTOFMEMORY;
- if(FAILED(hr))
- {
- m_pFile.Free();
- return hr;
- }
-
- m_rtNewStart = m_rtCurrent = 0;
- m_rtNewStop = m_rtStop = m_rtDuration = 0;
-
- int iVideo = 1, iAudio = 1, iSubtitle = 1;
-
- POSITION pos = m_pFile->m_segment.Tracks.GetHeadPosition();
- while(pos)
- {
- Track* pT = m_pFile->m_segment.Tracks.GetNext(pos);
-
- POSITION pos2 = pT->TrackEntries.GetHeadPosition();
- while(pos2)
- {
- TrackEntry* pTE = pT->TrackEntries.GetNext(pos2);
-
- bool isSub = false;
-
- if(!pTE->Expand(pTE->CodecPrivate, ContentEncoding::TracksPrivateData))
- continue;
-
- CStringA CodecID = pTE->CodecID.ToString();
-
- CStringW Name;
- Name.Format(L"Output %I64d", (UINT64)pTE->TrackNumber);
-
- CMediaType mt;
- CAtlArray<CMediaType> mts;
-
- mt.SetSampleSize(1);
-
- if(pTE->TrackType == TrackEntry::TypeVideo)
- {
- Name.Format(L"Video %d", iVideo++);
-
- mt.majortype = MEDIATYPE_Video;
-
- if(CodecID == "V_MS/VFW/FOURCC")
- {
- mt.formattype = FORMAT_VideoInfo;
- VIDEOINFOHEADER* pvih = (VIDEOINFOHEADER*)mt.AllocFormatBuffer(sizeof(VIDEOINFOHEADER) + pTE->CodecPrivate.GetCount() - sizeof(BITMAPINFOHEADER));
- memset(mt.Format(), 0, mt.FormatLength());
- memcpy(&pvih->bmiHeader, pTE->CodecPrivate.GetData(), pTE->CodecPrivate.GetCount());
- mt.subtype = FOURCCMap(pvih->bmiHeader.biCompression);
- switch(pvih->bmiHeader.biCompression)
- {
- case BI_RGB:
- case BI_BITFIELDS:
- mt.subtype =
- pvih->bmiHeader.biBitCount == 1 ? MEDIASUBTYPE_RGB1 :
- pvih->bmiHeader.biBitCount == 4 ? MEDIASUBTYPE_RGB4 :
- pvih->bmiHeader.biBitCount == 8 ? MEDIASUBTYPE_RGB8 :
- pvih->bmiHeader.biBitCount == 16 ? MEDIASUBTYPE_RGB565 :
- pvih->bmiHeader.biBitCount == 24 ? MEDIASUBTYPE_RGB24 :
- pvih->bmiHeader.biBitCount == 32 ? MEDIASUBTYPE_ARGB32 :
- MEDIASUBTYPE_NULL;
- break;
+ CheckPointer(pAsyncReader, E_POINTER);
+
+ HRESULT hr = E_FAIL;
+
+ m_pFile.Free();
+ m_pTrackEntryMap.RemoveAll();
+ m_pOrderedTrackArray.RemoveAll();
+
+ CAtlArray<CMatroskaSplitterOutputPin*> pinOut;
+ CAtlArray<TrackEntry*> pinOutTE;
+
+ m_pFile.Attach(DNew CMatroskaFile(pAsyncReader, hr));
+ if(!m_pFile) return E_OUTOFMEMORY;
+ if(FAILED(hr)) {m_pFile.Free(); return hr;}
+
+ m_rtNewStart = m_rtCurrent = 0;
+ m_rtNewStop = m_rtStop = m_rtDuration = 0;
+
+ int iVideo = 1, iAudio = 1, iSubtitle = 1;
+
+ POSITION pos = m_pFile->m_segment.Tracks.GetHeadPosition();
+ while(pos)
+ {
+ Track* pT = m_pFile->m_segment.Tracks.GetNext(pos);
+
+ POSITION pos2 = pT->TrackEntries.GetHeadPosition();
+ while(pos2)
+ {
+ TrackEntry* pTE = pT->TrackEntries.GetNext(pos2);
+
+ bool isSub = false;
+
+ if(!pTE->Expand(pTE->CodecPrivate, ContentEncoding::TracksPrivateData))
+ continue;
+
+ CStringA CodecID = pTE->CodecID.ToString();
+
+ CStringW Name;
+ Name.Format(L"Output %I64d", (UINT64)pTE->TrackNumber);
+
+ CMediaType mt;
+ CAtlArray<CMediaType> mts;
+
+ mt.SetSampleSize(1);
+
+ if(pTE->TrackType == TrackEntry::TypeVideo)
+ {
+ Name.Format(L"Video %d", iVideo++);
+
+ mt.majortype = MEDIATYPE_Video;
+
+ if(CodecID == "V_MS/VFW/FOURCC")
+ {
+ mt.formattype = FORMAT_VideoInfo;
+ VIDEOINFOHEADER* pvih = (VIDEOINFOHEADER*)mt.AllocFormatBuffer(sizeof(VIDEOINFOHEADER) + pTE->CodecPrivate.GetCount() - sizeof(BITMAPINFOHEADER));
+ memset(mt.Format(), 0, mt.FormatLength());
+ memcpy(&pvih->bmiHeader, pTE->CodecPrivate.GetData(), pTE->CodecPrivate.GetCount());
+ mt.subtype = FOURCCMap(pvih->bmiHeader.biCompression);
+ switch(pvih->bmiHeader.biCompression)
+ {
+ case BI_RGB: case BI_BITFIELDS: mt.subtype =
+ pvih->bmiHeader.biBitCount == 1 ? MEDIASUBTYPE_RGB1 :
+ pvih->bmiHeader.biBitCount == 4 ? MEDIASUBTYPE_RGB4 :
+ pvih->bmiHeader.biBitCount == 8 ? MEDIASUBTYPE_RGB8 :
+ pvih->bmiHeader.biBitCount == 16 ? MEDIASUBTYPE_RGB565 :
+ pvih->bmiHeader.biBitCount == 24 ? MEDIASUBTYPE_RGB24 :
+ pvih->bmiHeader.biBitCount == 32 ? MEDIASUBTYPE_ARGB32 :
+ MEDIASUBTYPE_NULL;
+ break;
// case BI_RLE8: mt.subtype = MEDIASUBTYPE_RGB8; break;
// case BI_RLE4: mt.subtype = MEDIASUBTYPE_RGB4; break;
- }
- mts.Add(mt);
- }
- else if(CodecID == "V_UNCOMPRESSED")
- {
- }
- else if(CodecID.Find("V_MPEG4/ISO/AVC") == 0 && pTE->CodecPrivate.GetCount() >= 6)
- {
- BYTE sps = pTE->CodecPrivate[5] & 0x1f;
-
- std::vector<BYTE> avcC;
- for(int i = 0, j = pTE->CodecPrivate.GetCount(); i < j; i++)
- avcC.push_back(pTE->CodecPrivate[i]);
-
- std::vector<BYTE> sh;
-
- unsigned jj = 6;
-
- while(sps--)
- {
- if(jj + 2 > avcC.size())
- goto avcfail;
- unsigned spslen = ((unsigned)avcC[jj] << 8) | avcC[jj+1];
- if(jj + 2 + spslen > avcC.size())
- goto avcfail;
- unsigned cur = sh.size();
- sh.resize(cur + spslen + 2, 0);
- std::copy(avcC.begin() + jj, avcC.begin() + jj + 2 + spslen, sh.begin() + cur);
- jj += 2 + spslen;
- }
-
- if(jj + 1 > avcC.size())
- continue;
-
- unsigned pps = avcC[jj++];
-
- while(pps--)
- {
- if(jj + 2 > avcC.size())
- goto avcfail;
- unsigned ppslen = ((unsigned)avcC[jj] << 8) | avcC[jj+1];
- if(jj + 2 + ppslen > avcC.size())
- goto avcfail;
- unsigned cur = sh.size();
- sh.resize(cur + ppslen + 2, 0);
- std::copy(avcC.begin() + jj, avcC.begin() + jj + 2 + ppslen, sh.begin() + cur);
- jj += 2 + ppslen;
- }
-
- goto avcsuccess;
+ }
+ mts.Add(mt);
+ }
+ else if(CodecID == "V_UNCOMPRESSED")
+ {
+ }
+ else if(CodecID.Find("V_MPEG4/ISO/AVC") == 0 && pTE->CodecPrivate.GetCount() >= 6)
+ {
+ BYTE sps = pTE->CodecPrivate[5] & 0x1f;
+
+ std::vector<BYTE> avcC;
+ for(int i = 0, j = pTE->CodecPrivate.GetCount(); i < j; i++)
+ avcC.push_back(pTE->CodecPrivate[i]);
+
+ std::vector<BYTE> sh;
+
+ unsigned jj = 6;
+
+ while (sps--) {
+ if (jj + 2 > avcC.size())
+ goto avcfail;
+ unsigned spslen = ((unsigned)avcC[jj] << 8) | avcC[jj+1];
+ if (jj + 2 + spslen > avcC.size())
+ goto avcfail;
+ unsigned cur = sh.size();
+ sh.resize(cur + spslen + 2, 0);
+ std::copy(avcC.begin() + jj, avcC.begin() + jj + 2 + spslen,sh.begin() + cur);
+ jj += 2 + spslen;
+ }
+
+ if (jj + 1 > avcC.size())
+ continue;
+
+ unsigned pps = avcC[jj++];
+
+ while (pps--) {
+ if (jj + 2 > avcC.size())
+ goto avcfail;
+ unsigned ppslen = ((unsigned)avcC[jj] << 8) | avcC[jj+1];
+ if (jj + 2 + ppslen > avcC.size())
+ goto avcfail;
+ unsigned cur = sh.size();
+ sh.resize(cur + ppslen + 2, 0);
+ std::copy(avcC.begin() + jj, avcC.begin() + jj + 2 + ppslen, sh.begin() + cur);
+ jj += 2 + ppslen;
+ }
+
+ goto avcsuccess;
avcfail:
- continue;
+ continue;
avcsuccess:
- CAtlArray<BYTE> data;
- data.SetCount(sh.size());
- std::copy(sh.begin(), sh.end(), data.GetData());
-
- mt.subtype = FOURCCMap('1CVA');
- mt.formattype = FORMAT_MPEG2Video;
- MPEG2VIDEOINFO* pm2vi = (MPEG2VIDEOINFO*)mt.AllocFormatBuffer(FIELD_OFFSET(MPEG2VIDEOINFO, dwSequenceHeader) + data.GetCount());
- memset(mt.Format(), 0, mt.FormatLength());
- pm2vi->hdr.bmiHeader.biSize = sizeof(pm2vi->hdr.bmiHeader);
- pm2vi->hdr.bmiHeader.biWidth = (LONG)pTE->v.PixelWidth;
- pm2vi->hdr.bmiHeader.biHeight = (LONG)pTE->v.PixelHeight;
- pm2vi->hdr.bmiHeader.biCompression = '1CVA';
- pm2vi->hdr.bmiHeader.biPlanes = 1;
- pm2vi->hdr.bmiHeader.biBitCount = 24;
- pm2vi->dwProfile = pTE->CodecPrivate[1];
- pm2vi->dwLevel = pTE->CodecPrivate[3];
- pm2vi->dwFlags = (pTE->CodecPrivate[4] & 3) + 1;
- BYTE* pSequenceHeader = (BYTE*)pm2vi->dwSequenceHeader;
- memcpy(pSequenceHeader, data.GetData(), data.GetCount());
- pm2vi->cbSequenceHeader = data.GetCount();
- mts.Add(mt);
- }
- else if(CodecID.Find("V_MPEG4/") == 0)
- {
- mt.subtype = FOURCCMap('V4PM');
- mt.formattype = FORMAT_MPEG2Video;
- MPEG2VIDEOINFO* pm2vi = (MPEG2VIDEOINFO*)mt.AllocFormatBuffer(FIELD_OFFSET(MPEG2VIDEOINFO, dwSequenceHeader) + pTE->CodecPrivate.GetCount());
- memset(mt.Format(), 0, mt.FormatLength());
- pm2vi->hdr.bmiHeader.biSize = sizeof(pm2vi->hdr.bmiHeader);
- pm2vi->hdr.bmiHeader.biWidth = (LONG)pTE->v.PixelWidth;
- pm2vi->hdr.bmiHeader.biHeight = (LONG)pTE->v.PixelHeight;
- pm2vi->hdr.bmiHeader.biCompression = 'V4PM';
- pm2vi->hdr.bmiHeader.biPlanes = 1;
- pm2vi->hdr.bmiHeader.biBitCount = 24;
- BYTE* pSequenceHeader = (BYTE*)pm2vi->dwSequenceHeader;
- memcpy(pSequenceHeader, pTE->CodecPrivate.GetData(), pTE->CodecPrivate.GetCount());
- pm2vi->cbSequenceHeader = pTE->CodecPrivate.GetCount();
- mts.Add(mt);
- }
- else if(CodecID.Find("V_REAL/RV") == 0)
- {
- mt.subtype = FOURCCMap('00VR' + ((CodecID[9] - 0x30) << 16));
- mt.formattype = FORMAT_VideoInfo;
- VIDEOINFOHEADER* pvih = (VIDEOINFOHEADER*)mt.AllocFormatBuffer(sizeof(VIDEOINFOHEADER) + pTE->CodecPrivate.GetCount());
- memset(mt.Format(), 0, mt.FormatLength());
- memcpy(mt.Format() + sizeof(VIDEOINFOHEADER), pTE->CodecPrivate.GetData(), pTE->CodecPrivate.GetCount());
- pvih->bmiHeader.biSize = sizeof(pvih->bmiHeader);
- pvih->bmiHeader.biWidth = (LONG)pTE->v.PixelWidth;
- pvih->bmiHeader.biHeight = (LONG)pTE->v.PixelHeight;
- pvih->bmiHeader.biCompression = mt.subtype.Data1;
- mts.Add(mt);
- }
- else if(CodecID == "V_DIRAC")
- {
- mt.subtype = MEDIASUBTYPE_DiracVideo;
- mt.formattype = FORMAT_DiracVideoInfo;
- DIRACINFOHEADER* dvih = (DIRACINFOHEADER*)mt.AllocFormatBuffer(FIELD_OFFSET(DIRACINFOHEADER, dwSequenceHeader) + pTE->CodecPrivate.GetCount());
- memset(mt.Format(), 0, mt.FormatLength());
- dvih->hdr.bmiHeader.biSize = sizeof(dvih->hdr.bmiHeader);
- dvih->hdr.bmiHeader.biWidth = (LONG)pTE->v.PixelWidth;
- dvih->hdr.bmiHeader.biHeight = (LONG)pTE->v.PixelHeight;
- dvih->hdr.dwPictAspectRatioX = dvih->hdr.bmiHeader.biWidth;
- dvih->hdr.dwPictAspectRatioY = dvih->hdr.bmiHeader.biHeight;
-
- BYTE* pSequenceHeader = (BYTE*)dvih->dwSequenceHeader;
- memcpy(pSequenceHeader, pTE->CodecPrivate.GetData(), pTE->CodecPrivate.GetCount());
- dvih->cbSequenceHeader = pTE->CodecPrivate.GetCount();
-
- mts.Add(mt);
- }
- else if(CodecID == "V_MPEG2")
- {
- BYTE* seqhdr = pTE->CodecPrivate.GetData();
- DWORD len = pTE->CodecPrivate.GetCount();
- int w = pTE->v.PixelWidth;
- int h = pTE->v.PixelHeight;
-
- if(MakeMPEG2MediaType(mt, seqhdr, len, w, h))
- mts.Add(mt);
- }
- else if(CodecID == "V_THEORA")
- {
- BYTE* thdr = pTE->CodecPrivate.GetData() + 3;
-
- mt.majortype = MEDIATYPE_Video;
- mt.subtype = FOURCCMap('OEHT');
- mt.formattype = FORMAT_MPEG2_VIDEO;
- MPEG2VIDEOINFO* vih = (MPEG2VIDEOINFO*)mt.AllocFormatBuffer(sizeof(MPEG2VIDEOINFO) + pTE->CodecPrivate.GetCount());
- memset(mt.Format(), 0, mt.FormatLength());
- vih->hdr.bmiHeader.biSize = sizeof(vih->hdr.bmiHeader);
- vih->hdr.bmiHeader.biWidth = *(WORD*)&thdr[10] >> 4;
- vih->hdr.bmiHeader.biHeight = *(WORD*)&thdr[12] >> 4;
- vih->hdr.bmiHeader.biCompression = 'OEHT';
- vih->hdr.bmiHeader.biPlanes = 1;
- vih->hdr.bmiHeader.biBitCount = 24;
- int nFpsNum = (thdr[22] << 24) | (thdr[23] << 16) | (thdr[24] << 8) | thdr[25];
- int nFpsDenum = (thdr[26] << 24) | (thdr[27] << 16) | (thdr[28] << 8) | thdr[29];
- if(nFpsNum) vih->hdr.AvgTimePerFrame = (REFERENCE_TIME)(10000000.0 * nFpsDenum / nFpsNum);
- vih->hdr.dwPictAspectRatioX = (thdr[14] << 16) | (thdr[15] << 8) | thdr[16];
- vih->hdr.dwPictAspectRatioY = (thdr[17] << 16) | (thdr[18] << 8) | thdr[19];
- mt.bFixedSizeSamples = 0;
-
- vih->cbSequenceHeader = pTE->CodecPrivate.GetCount();
- memcpy(&vih->dwSequenceHeader, pTE->CodecPrivate.GetData(), vih->cbSequenceHeader);
-
- mts.Add(mt);
- }
- /*
- else if(CodecID == "V_DSHOW/MPEG1VIDEO") // V_MPEG1
- {
- mt.majortype = MEDIATYPE_Video;
- mt.subtype = MEDIASUBTYPE_MPEG1Payload;
- mt.formattype = FORMAT_MPEGVideo;
- MPEG1VIDEOINFO* pm1vi = (MPEG1VIDEOINFO*)mt.AllocFormatBuffer(pTE->CodecPrivate.GetCount());
- memcpy(pm1vi, pTE->CodecPrivate.GetData(), pTE->CodecPrivate.GetCount());
- mt.SetSampleSize(pm1vi->hdr.bmiHeader.biWidth*pm1vi->hdr.bmiHeader.biHeight*4);
- mts.Add(mt);
- }
- */
- REFERENCE_TIME AvgTimePerFrame = 0;
+ CAtlArray<BYTE> data;
+ data.SetCount(sh.size());
+ std::copy(sh.begin(), sh.end(), data.GetData());
+
+ mt.subtype = FOURCCMap('1CVA');
+ mt.formattype = FORMAT_MPEG2Video;
+ MPEG2VIDEOINFO* pm2vi = (MPEG2VIDEOINFO*)mt.AllocFormatBuffer(FIELD_OFFSET(MPEG2VIDEOINFO, dwSequenceHeader) + data.GetCount());
+ memset(mt.Format(), 0, mt.FormatLength());
+ pm2vi->hdr.bmiHeader.biSize = sizeof(pm2vi->hdr.bmiHeader);
+ pm2vi->hdr.bmiHeader.biWidth = (LONG)pTE->v.PixelWidth;
+ pm2vi->hdr.bmiHeader.biHeight = (LONG)pTE->v.PixelHeight;
+ pm2vi->hdr.bmiHeader.biCompression = '1CVA';
+ pm2vi->hdr.bmiHeader.biPlanes = 1;
+ pm2vi->hdr.bmiHeader.biBitCount = 24;
+ pm2vi->dwProfile = pTE->CodecPrivate[1];
+ pm2vi->dwLevel = pTE->CodecPrivate[3];
+ pm2vi->dwFlags = (pTE->CodecPrivate[4] & 3) + 1;
+ BYTE* pSequenceHeader = (BYTE*)pm2vi->dwSequenceHeader;
+ memcpy(pSequenceHeader, data.GetData(), data.GetCount());
+ pm2vi->cbSequenceHeader = data.GetCount();
+ mts.Add(mt);
+ }
+ else if(CodecID.Find("V_MPEG4/") == 0)
+ {
+ mt.subtype = FOURCCMap('V4PM');
+ mt.formattype = FORMAT_MPEG2Video;
+ MPEG2VIDEOINFO* pm2vi = (MPEG2VIDEOINFO*)mt.AllocFormatBuffer(FIELD_OFFSET(MPEG2VIDEOINFO, dwSequenceHeader) + pTE->CodecPrivate.GetCount());
+ memset(mt.Format(), 0, mt.FormatLength());
+ pm2vi->hdr.bmiHeader.biSize = sizeof(pm2vi->hdr.bmiHeader);
+ pm2vi->hdr.bmiHeader.biWidth = (LONG)pTE->v.PixelWidth;
+ pm2vi->hdr.bmiHeader.biHeight = (LONG)pTE->v.PixelHeight;
+ pm2vi->hdr.bmiHeader.biCompression = 'V4PM';
+ pm2vi->hdr.bmiHeader.biPlanes = 1;
+ pm2vi->hdr.bmiHeader.biBitCount = 24;
+ BYTE* pSequenceHeader = (BYTE*)pm2vi->dwSequenceHeader;
+ memcpy(pSequenceHeader, pTE->CodecPrivate.GetData(), pTE->CodecPrivate.GetCount());
+ pm2vi->cbSequenceHeader = pTE->CodecPrivate.GetCount();
+ mts.Add(mt);
+ }
+ else if(CodecID.Find("V_REAL/RV") == 0)
+ {
+ mt.subtype = FOURCCMap('00VR' + ((CodecID[9]-0x30)<<16));
+ mt.formattype = FORMAT_VideoInfo;
+ VIDEOINFOHEADER* pvih = (VIDEOINFOHEADER*)mt.AllocFormatBuffer(sizeof(VIDEOINFOHEADER) + pTE->CodecPrivate.GetCount());
+ memset(mt.Format(), 0, mt.FormatLength());
+ memcpy(mt.Format() + sizeof(VIDEOINFOHEADER), pTE->CodecPrivate.GetData(), pTE->CodecPrivate.GetCount());
+ pvih->bmiHeader.biSize = sizeof(pvih->bmiHeader);
+ pvih->bmiHeader.biWidth = (LONG)pTE->v.PixelWidth;
+ pvih->bmiHeader.biHeight = (LONG)pTE->v.PixelHeight;
+ pvih->bmiHeader.biCompression = mt.subtype.Data1;
+ mts.Add(mt);
+ }
+ else if(CodecID == "V_DIRAC")
+ {
+ mt.subtype = MEDIASUBTYPE_DiracVideo;
+ mt.formattype = FORMAT_DiracVideoInfo;
+ DIRACINFOHEADER* dvih = (DIRACINFOHEADER*)mt.AllocFormatBuffer(FIELD_OFFSET(DIRACINFOHEADER, dwSequenceHeader) + pTE->CodecPrivate.GetCount());
+ memset(mt.Format(), 0, mt.FormatLength());
+ dvih->hdr.bmiHeader.biSize = sizeof(dvih->hdr.bmiHeader);
+ dvih->hdr.bmiHeader.biWidth = (LONG)pTE->v.PixelWidth;
+ dvih->hdr.bmiHeader.biHeight = (LONG)pTE->v.PixelHeight;
+ dvih->hdr.dwPictAspectRatioX = dvih->hdr.bmiHeader.biWidth;
+ dvih->hdr.dwPictAspectRatioY = dvih->hdr.bmiHeader.biHeight;
+
+ BYTE* pSequenceHeader = (BYTE*)dvih->dwSequenceHeader;
+ memcpy(pSequenceHeader, pTE->CodecPrivate.GetData(), pTE->CodecPrivate.GetCount());
+ dvih->cbSequenceHeader = pTE->CodecPrivate.GetCount();
+
+ mts.Add(mt);
+ }
+ else if(CodecID == "V_MPEG2")
+ {
+ BYTE* seqhdr = pTE->CodecPrivate.GetData();
+ DWORD len = pTE->CodecPrivate.GetCount();
+ int w = pTE->v.PixelWidth;
+ int h = pTE->v.PixelHeight;
+
+ if(MakeMPEG2MediaType(mt, seqhdr, len, w, h))
+ mts.Add(mt);
+ }
+ else if(CodecID == "V_THEORA")
+ {
+ BYTE* thdr = pTE->CodecPrivate.GetData() + 3;
+
+ mt.majortype = MEDIATYPE_Video;
+ mt.subtype = FOURCCMap('OEHT');
+ mt.formattype = FORMAT_MPEG2_VIDEO;
+ MPEG2VIDEOINFO* vih = (MPEG2VIDEOINFO*)mt.AllocFormatBuffer(sizeof(MPEG2VIDEOINFO) + pTE->CodecPrivate.GetCount());
+ memset(mt.Format(), 0, mt.FormatLength());
+ vih->hdr.bmiHeader.biSize = sizeof(vih->hdr.bmiHeader);
+ vih->hdr.bmiHeader.biWidth = *(WORD*)&thdr[10] >> 4;
+ vih->hdr.bmiHeader.biHeight = *(WORD*)&thdr[12] >> 4;
+ vih->hdr.bmiHeader.biCompression = 'OEHT';
+ vih->hdr.bmiHeader.biPlanes = 1;
+ vih->hdr.bmiHeader.biBitCount = 24;
+ int nFpsNum = (thdr[22]<<24)|(thdr[23]<<16)|(thdr[24]<<8)|thdr[25];
+ int nFpsDenum = (thdr[26]<<24)|(thdr[27]<<16)|(thdr[28]<<8)|thdr[29];
+ if(nFpsNum) vih->hdr.AvgTimePerFrame = (REFERENCE_TIME)(10000000.0 * nFpsDenum / nFpsNum);
+ vih->hdr.dwPictAspectRatioX = (thdr[14]<<16)|(thdr[15]<<8)|thdr[16];
+ vih->hdr.dwPictAspectRatioY = (thdr[17]<<16)|(thdr[18]<<8)|thdr[19];
+ mt.bFixedSizeSamples = 0;
+
+ vih->cbSequenceHeader = pTE->CodecPrivate.GetCount();
+ memcpy (&vih->dwSequenceHeader, pTE->CodecPrivate.GetData(), vih->cbSequenceHeader);
+
+ mts.Add(mt);
+ }
+/*
+ else if(CodecID == "V_DSHOW/MPEG1VIDEO") // V_MPEG1
+ {
+ mt.majortype = MEDIATYPE_Video;
+ mt.subtype = MEDIASUBTYPE_MPEG1Payload;
+ mt.formattype = FORMAT_MPEGVideo;
+ MPEG1VIDEOINFO* pm1vi = (MPEG1VIDEOINFO*)mt.AllocFormatBuffer(pTE->CodecPrivate.GetCount());
+ memcpy(pm1vi, pTE->CodecPrivate.GetData(), pTE->CodecPrivate.GetCount());
+ mt.SetSampleSize(pm1vi->hdr.bmiHeader.biWidth*pm1vi->hdr.bmiHeader.biHeight*4);
+ mts.Add(mt);
+ }
+*/
+ REFERENCE_TIME AvgTimePerFrame = 0;
if(pTE->v.FramePerSec > 0)
- AvgTimePerFrame = (REFERENCE_TIME)(10000000i64 / pTE->v.FramePerSec);
- else if(pTE->DefaultDuration > 0)
- AvgTimePerFrame = (REFERENCE_TIME)pTE->DefaultDuration / 100;
-
- if(AvgTimePerFrame)
- {
- for(int i = 0; i < mts.GetCount(); i++)
- {
- if(mts[i].formattype == FORMAT_VideoInfo
- || mts[i].formattype == FORMAT_VideoInfo2
- || mts[i].formattype == FORMAT_MPEG2Video)
- {
- ((VIDEOINFOHEADER*)mts[i].Format())->AvgTimePerFrame = AvgTimePerFrame;
- }
- }
- }
-
- if(pTE->v.DisplayWidth != 0 && pTE->v.DisplayHeight != 0)
- {
- for(int i = 0; i < mts.GetCount(); i++)
- {
- if(mts[i].formattype == FORMAT_VideoInfo)
- {
- DWORD vih1 = FIELD_OFFSET(VIDEOINFOHEADER, bmiHeader);
- DWORD vih2 = FIELD_OFFSET(VIDEOINFOHEADER2, bmiHeader);
- DWORD bmi = mts[i].FormatLength() - FIELD_OFFSET(VIDEOINFOHEADER, bmiHeader);
- mt.formattype = FORMAT_VideoInfo2;
- mt.AllocFormatBuffer(vih2 + bmi);
- memcpy(mt.Format(), mts[i].Format(), vih1);
- memset(mt.Format() + vih1, 0, vih2 - vih1);
- memcpy(mt.Format() + vih2, mts[i].Format() + vih1, bmi);
- ((VIDEOINFOHEADER2*)mt.Format())->dwPictAspectRatioX = (DWORD)pTE->v.DisplayWidth;
- ((VIDEOINFOHEADER2*)mt.Format())->dwPictAspectRatioY = (DWORD)pTE->v.DisplayHeight;
- mts.InsertAt(i++, mt);
- }
- else if(mts[i].formattype == FORMAT_MPEG2Video)
- {
- ((MPEG2VIDEOINFO*)mts[i].Format())->hdr.dwPictAspectRatioX = (DWORD)pTE->v.DisplayWidth;
- ((MPEG2VIDEOINFO*)mts[i].Format())->hdr.dwPictAspectRatioY = (DWORD)pTE->v.DisplayHeight;
- }
- }
- }
- }
- else if(pTE->TrackType == TrackEntry::TypeAudio)
- {
- Name.Format(L"Audio %d", iAudio++);
-
- mt.majortype = MEDIATYPE_Audio;
- mt.formattype = FORMAT_WaveFormatEx;
- WAVEFORMATEX* wfe = (WAVEFORMATEX*)mt.AllocFormatBuffer(sizeof(WAVEFORMATEX));
- memset(wfe, 0, mt.FormatLength());
- wfe->nChannels = (WORD)pTE->a.Channels;
- wfe->nSamplesPerSec = (DWORD)pTE->a.SamplingFrequency;
- wfe->wBitsPerSample = (WORD)pTE->a.BitDepth;
- wfe->nBlockAlign = (WORD)((wfe->nChannels * wfe->wBitsPerSample) / 8);
- wfe->nAvgBytesPerSec = wfe->nSamplesPerSec * wfe->nBlockAlign;
- mt.SetSampleSize(256000);
-
- static CAtlMap<CStringA, int, CStringElementTraits<CStringA> > id2ft;
-
- if(id2ft.IsEmpty())
- {
- id2ft["A_MPEG/L3"] = WAVE_FORMAT_MP3;
- id2ft["A_MPEG/L2"] = WAVE_FORMAT_MPEG;
- id2ft["A_AC3"] = WAVE_FORMAT_DOLBY_AC3;
- id2ft["A_DTS"] = WAVE_FORMAT_DVD_DTS;
- id2ft["A_EAC3"] = WAVE_FORMAT_DOLBY_AC3;
- id2ft["A_PCM/INT/LIT"] = WAVE_FORMAT_PCM;
- id2ft["A_PCM/FLOAT/IEEE"] = WAVE_FORMAT_IEEE_FLOAT;
- id2ft["A_AAC"] = -WAVE_FORMAT_AAC;
- id2ft["A_FLAC"] = -WAVE_FORMAT_FLAC;
- id2ft["A_WAVPACK4"] = -WAVE_FORMAT_WAVPACK4;
- id2ft["A_TTA1"] = WAVE_FORMAT_TTA1;
- id2ft["A_TRUEHD"] = WAVE_FORMAT_DOLBY_AC3;
- id2ft["A_MLP"] = WAVE_FORMAT_DOLBY_AC3;
- }
-
- int wFormatTag;
- if(id2ft.Lookup(CodecID, wFormatTag))
- {
- if(wFormatTag < 0)
- {
- wFormatTag = -wFormatTag;
- wfe->cbSize = pTE->CodecPrivate.GetCount();
- wfe = (WAVEFORMATEX*)mt.ReallocFormatBuffer(sizeof(WAVEFORMATEX) + pTE->CodecPrivate.GetCount());
- memcpy(wfe + 1, pTE->CodecPrivate.GetData(), pTE->CodecPrivate.GetCount());
- }
-
- mt.subtype = FOURCCMap(wfe->wFormatTag = wFormatTag);
- mts.Add(mt);
-
- if(wFormatTag == WAVE_FORMAT_FLAC)
- {
- mt.subtype = MEDIASUBTYPE_FLAC_FRAMED;
- mts.InsertAt(0, mt);
- }
- }
- else if(CodecID == "A_VORBIS")
- {
- BYTE* p = pTE->CodecPrivate.GetData();
- CAtlArray<int> sizes;
- for(BYTE n = *p++; n > 0; n--)
- {
- int size = 0;
- do
- {
- size += *p;
- }
- while(*p++ == 0xff);
- sizes.Add(size);
- }
-
- int totalsize = 0;
- for(int i = 0; i < sizes.GetCount(); i++)
- totalsize += sizes[i];
-
- sizes.Add(pTE->CodecPrivate.GetCount() - (p - pTE->CodecPrivate.GetData()) - totalsize);
- totalsize += sizes[sizes.GetCount()-1];
-
- if(sizes.GetCount() == 3)
- {
- mt.subtype = MEDIASUBTYPE_Vorbis2;
- mt.formattype = FORMAT_VorbisFormat2;
- VORBISFORMAT2* pvf2 = (VORBISFORMAT2*)mt.AllocFormatBuffer(sizeof(VORBISFORMAT2) + totalsize);
- memset(pvf2, 0, mt.FormatLength());
- pvf2->Channels = (WORD)pTE->a.Channels;
- pvf2->SamplesPerSec = (DWORD)pTE->a.SamplingFrequency;
- pvf2->BitsPerSample = (DWORD)pTE->a.BitDepth;
- BYTE* p2 = mt.Format() + sizeof(VORBISFORMAT2);
- for(int i = 0; i < sizes.GetCount(); p += sizes[i], p2 += sizes[i], i++)
- memcpy(p2, p, pvf2->HeaderSize[i] = sizes[i]);
-
- mts.Add(mt);
- }
-
- mt.subtype = MEDIASUBTYPE_Vorbis;
- mt.formattype = FORMAT_VorbisFormat;
- VORBISFORMAT* vf = (VORBISFORMAT*)mt.AllocFormatBuffer(sizeof(VORBISFORMAT));
- memset(vf, 0, mt.FormatLength());
- vf->nChannels = (WORD)pTE->a.Channels;
- vf->nSamplesPerSec = (DWORD)pTE->a.SamplingFrequency;
- vf->nMinBitsPerSec = vf->nMaxBitsPerSec = vf->nAvgBitsPerSec = -1;
- mts.Add(mt);
- }
- else if(CodecID == "A_MS/ACM")
- {
- wfe = (WAVEFORMATEX*)mt.AllocFormatBuffer(pTE->CodecPrivate.GetCount());
- memcpy(wfe, (WAVEFORMATEX*)pTE->CodecPrivate.GetData(), pTE->CodecPrivate.GetCount());
- mt.subtype = FOURCCMap(wfe->wFormatTag);
- mts.Add(mt);
- }
- else if(CodecID.Find("A_AAC/") == 0)
- {
- mt.subtype = FOURCCMap(wfe->wFormatTag = WAVE_FORMAT_AAC);
- wfe = (WAVEFORMATEX*)mt.ReallocFormatBuffer(sizeof(WAVEFORMATEX) + 5);
- wfe->cbSize = 2;
-
- int profile;
-
- if(CodecID.Find("/MAIN") > 0) profile = 0;
- else if(CodecID.Find("/SBR") > 0) profile = -1;
- else if(CodecID.Find("/LC") > 0) profile = 1;
- else if(CodecID.Find("/SSR") > 0) profile = 2;
- else if(CodecID.Find("/LTP") > 0) profile = 3;
- else continue;
-
- WORD cbSize = MakeAACInitData((BYTE*)(wfe + 1), profile, wfe->nSamplesPerSec, pTE->a.Channels);
-
- mts.Add(mt);
-
- if(profile < 0)
- {
- wfe->cbSize = cbSize;
- wfe->nSamplesPerSec *= 2;
- wfe->nAvgBytesPerSec *= 2;
-
- mts.InsertAt(0, mt);
- }
- }
- else if(CodecID.Find("A_REAL/") == 0 && CodecID.GetLength() >= 11)
- {
- mt.subtype = FOURCCMap((DWORD)CodecID[7] | ((DWORD)CodecID[8] << 8) | ((DWORD)CodecID[9] << 16) | ((DWORD)CodecID[10] << 24));
- mt.bTemporalCompression = TRUE;
- wfe->cbSize = pTE->CodecPrivate.GetCount();
- wfe = (WAVEFORMATEX*)mt.ReallocFormatBuffer(sizeof(WAVEFORMATEX) + pTE->CodecPrivate.GetCount());
- memcpy(wfe + 1, pTE->CodecPrivate.GetData(), pTE->CodecPrivate.GetCount());
- wfe->cbSize = 0; // IMPORTANT: this is screwed, but cbSize has to be 0 and the extra data from codec priv must be after WAVEFORMATEX
- mts.Add(mt);
- }
- }
- else if(pTE->TrackType == TrackEntry::TypeSubtitle)
- {
- if(iSubtitle == 1) InstallFonts();
-
- Name.Format(L"Subtitle %d", iSubtitle++);
-
- mt.SetSampleSize(1);
-
- if(CodecID == "S_TEXT/ASCII")
- {
- mt.majortype = MEDIATYPE_Text;
- mt.subtype = MEDIASUBTYPE_NULL;
- mt.formattype = FORMAT_None;
- mts.Add(mt);
- isSub = true;
- }
- else
- {
- mt.majortype = MEDIATYPE_Subtitle;
- mt.formattype = FORMAT_SubtitleInfo;
- SUBTITLEINFO* psi = (SUBTITLEINFO*)mt.AllocFormatBuffer(sizeof(SUBTITLEINFO) + pTE->CodecPrivate.GetCount());
- memset(psi, 0, mt.FormatLength());
- strncpy(psi->IsoLang, pTE->Language, countof(psi->IsoLang) - 1);
- wcsncpy(psi->TrackName, pTE->Name, countof(psi->TrackName) - 1);
- memcpy(mt.pbFormat + (psi->dwOffset = sizeof(SUBTITLEINFO)), pTE->CodecPrivate.GetData(), pTE->CodecPrivate.GetCount());
-
- mt.subtype =
- CodecID == "S_TEXT/UTF8" ? MEDIASUBTYPE_UTF8 :
- CodecID == "S_TEXT/SSA" || CodecID == "S_SSA" ? MEDIASUBTYPE_SSA :
- CodecID == "S_TEXT/ASS" || CodecID == "S_ASS" ? MEDIASUBTYPE_ASS :
- CodecID == "S_TEXT/SSF" || CodecID == "S_SSF" ? MEDIASUBTYPE_SSF :
- CodecID == "S_TEXT/USF" || CodecID == "S_USF" ? MEDIASUBTYPE_USF :
- CodecID == "S_VOBSUB" ? MEDIASUBTYPE_VOBSUB :
- MEDIASUBTYPE_NULL;
-
- if(mt.subtype != MEDIASUBTYPE_NULL)
- {
- mts.Add(mt);
- isSub = true;
- }
- }
- }
-
- if(mts.IsEmpty())
- {
- TRACE(_T("CMatroskaSourceFilter: Unsupported TrackType %s (%I64d)\n"), CString(CodecID), (UINT64)pTE->TrackType);
- continue;
- }
-
- Name = CStringW(pTE->Language.IsEmpty() ? L"English" : CStringW(ISO6392ToLanguage(pTE->Language)))
- + (pTE->Name.IsEmpty() ? L"" : L", " + pTE->Name)
- + (L" (" + Name + L")");
-
- HRESULT hr;
-
- CAutoPtr<CBaseSplitterOutputPin> pPinOut(DNew CMatroskaSplitterOutputPin((int)pTE->MinCache, pTE->DefaultDuration / 100, mts, Name, this, this, &hr));
- if(!pTE->Name.IsEmpty()) pPinOut->SetProperty(L"NAME", pTE->Name);
- if(pTE->Language.GetLength() == 3) pPinOut->SetProperty(L"LANG", CStringW(CString(pTE->Language)));
-
- if(!isSub)
- {
- pinOut.InsertAt((iVideo + iAudio - 3), DNew CMatroskaSplitterOutputPin((int)pTE->MinCache, pTE->DefaultDuration / 100, mts, Name, this, this, &hr), 1);
- pinOutTE.InsertAt((iVideo + iAudio - 3), pTE, 1);
- }
- else
- {
- pinOut.Add(DNew CMatroskaSplitterOutputPin((int)pTE->MinCache, pTE->DefaultDuration / 100, mts, Name, this, this, &hr));
- pinOutTE.Add(pTE);
- }
-
- }
- }
-
- for(int i = 0; i < pinOut.GetCount(); i++)
- {
-
- CAutoPtr<CBaseSplitterOutputPin> pPinOut;
- pPinOut.Attach(pinOut[i]);
- TrackEntry* pTE = pinOutTE[i];
-
- AddOutputPin((DWORD)pTE->TrackNumber, pPinOut);
- m_pTrackEntryMap[(DWORD)pTE->TrackNumber] = pTE;
- m_pOrderedTrackArray.Add(pTE);
- }
-
-
- Info& info = m_pFile->m_segment.SegmentInfo;
-
- if(m_pFile->IsRandomAccess())
- {
- m_rtDuration = (REFERENCE_TIME)(info.Duration * info.TimeCodeScale / 100);
- }
-
- m_rtNewStop = m_rtStop = m_rtDuration;
+ AvgTimePerFrame = (REFERENCE_TIME)(10000000i64 / pTE->v.FramePerSec);
+ else if(pTE->DefaultDuration > 0)
+ AvgTimePerFrame = (REFERENCE_TIME)pTE->DefaultDuration / 100;
+
+ if(AvgTimePerFrame)
+ {
+ for(int i = 0; i < mts.GetCount(); i++)
+ {
+ if(mts[i].formattype == FORMAT_VideoInfo
+ || mts[i].formattype == FORMAT_VideoInfo2
+ || mts[i].formattype == FORMAT_MPEG2Video)
+ {
+ ((VIDEOINFOHEADER*)mts[i].Format())->AvgTimePerFrame = AvgTimePerFrame;
+ }
+ }
+ }
+
+ if(pTE->v.DisplayWidth != 0 && pTE->v.DisplayHeight != 0)
+ {
+ for(int i = 0; i < mts.GetCount(); i++)
+ {
+ if(mts[i].formattype == FORMAT_VideoInfo)
+ {
+ DWORD vih1 = FIELD_OFFSET(VIDEOINFOHEADER, bmiHeader);
+ DWORD vih2 = FIELD_OFFSET(VIDEOINFOHEADER2, bmiHeader);
+ DWORD bmi = mts[i].FormatLength() - FIELD_OFFSET(VIDEOINFOHEADER, bmiHeader);
+ mt.formattype = FORMAT_VideoInfo2;
+ mt.AllocFormatBuffer(vih2 + bmi);
+ memcpy(mt.Format(), mts[i].Format(), vih1);
+ memset(mt.Format() + vih1, 0, vih2 - vih1);
+ memcpy(mt.Format() + vih2, mts[i].Format() + vih1, bmi);
+ ((VIDEOINFOHEADER2*)mt.Format())->dwPictAspectRatioX = (DWORD)pTE->v.DisplayWidth;
+ ((VIDEOINFOHEADER2*)mt.Format())->dwPictAspectRatioY = (DWORD)pTE->v.DisplayHeight;
+ mts.InsertAt(i++, mt);
+ }
+ else if(mts[i].formattype == FORMAT_MPEG2Video)
+ {
+ ((MPEG2VIDEOINFO*)mts[i].Format())->hdr.dwPictAspectRatioX = (DWORD)pTE->v.DisplayWidth;
+ ((MPEG2VIDEOINFO*)mts[i].Format())->hdr.dwPictAspectRatioY = (DWORD)pTE->v.DisplayHeight;
+ }
+ }
+ }
+ }
+ else if(pTE->TrackType == TrackEntry::TypeAudio)
+ {
+ Name.Format(L"Audio %d", iAudio++);
+
+ mt.majortype = MEDIATYPE_Audio;
+ mt.formattype = FORMAT_WaveFormatEx;
+ WAVEFORMATEX* wfe = (WAVEFORMATEX*)mt.AllocFormatBuffer(sizeof(WAVEFORMATEX));
+ memset(wfe, 0, mt.FormatLength());
+ wfe->nChannels = (WORD)pTE->a.Channels;
+ wfe->nSamplesPerSec = (DWORD)pTE->a.SamplingFrequency;
+ wfe->wBitsPerSample = (WORD)pTE->a.BitDepth;
+ wfe->nBlockAlign = (WORD)((wfe->nChannels * wfe->wBitsPerSample) / 8);
+ wfe->nAvgBytesPerSec = wfe->nSamplesPerSec * wfe->nBlockAlign;
+ mt.SetSampleSize(256000);
+
+ static CAtlMap<CStringA, int, CStringElementTraits<CStringA> > id2ft;
+
+ if(id2ft.IsEmpty())
+ {
+ id2ft["A_MPEG/L3"] = WAVE_FORMAT_MP3;
+ id2ft["A_MPEG/L2"] = WAVE_FORMAT_MPEG;
+ id2ft["A_AC3"] = WAVE_FORMAT_DOLBY_AC3;
+ id2ft["A_DTS"] = WAVE_FORMAT_DVD_DTS;
+ id2ft["A_EAC3"] = WAVE_FORMAT_DOLBY_AC3;
+ id2ft["A_PCM/INT/LIT"] = WAVE_FORMAT_PCM;
+ id2ft["A_PCM/FLOAT/IEEE"] = WAVE_FORMAT_IEEE_FLOAT;
+ id2ft["A_AAC"] = -WAVE_FORMAT_AAC;
+ id2ft["A_FLAC"] = -WAVE_FORMAT_FLAC;
+ id2ft["A_WAVPACK4"] = -WAVE_FORMAT_WAVPACK4;
+ id2ft["A_TTA1"] = WAVE_FORMAT_TTA1;
+ id2ft["A_TRUEHD"] = WAVE_FORMAT_DOLBY_AC3;
+ id2ft["A_MLP"] = WAVE_FORMAT_DOLBY_AC3;
+ }
+
+ int wFormatTag;
+ if(id2ft.Lookup(CodecID, wFormatTag))
+ {
+ if(wFormatTag < 0)
+ {
+ wFormatTag = -wFormatTag;
+ wfe->cbSize = pTE->CodecPrivate.GetCount();
+ wfe = (WAVEFORMATEX*)mt.ReallocFormatBuffer(sizeof(WAVEFORMATEX) + pTE->CodecPrivate.GetCount());
+ memcpy(wfe + 1, pTE->CodecPrivate.GetData(), pTE->CodecPrivate.GetCount());
+ }
+
+ mt.subtype = FOURCCMap(wfe->wFormatTag = wFormatTag);
+ mts.Add(mt);
+
+ if(wFormatTag == WAVE_FORMAT_FLAC)
+ {
+ mt.subtype = MEDIASUBTYPE_FLAC_FRAMED;
+ mts.InsertAt(0, mt);
+ }
+ }
+ else if(CodecID == "A_VORBIS")
+ {
+ BYTE* p = pTE->CodecPrivate.GetData();
+ CAtlArray<int> sizes;
+ for(BYTE n = *p++; n > 0; n--)
+ {
+ int size = 0;
+ do {size += *p;} while(*p++ == 0xff);
+ sizes.Add(size);
+ }
+
+ int totalsize = 0;
+ for(int i = 0; i < sizes.GetCount(); i++)
+ totalsize += sizes[i];
+
+ sizes.Add(pTE->CodecPrivate.GetCount() - (p - pTE->CodecPrivate.GetData()) - totalsize);
+ totalsize += sizes[sizes.GetCount()-1];
+
+ if(sizes.GetCount() == 3)
+ {
+ mt.subtype = MEDIASUBTYPE_Vorbis2;
+ mt.formattype = FORMAT_VorbisFormat2;
+ VORBISFORMAT2* pvf2 = (VORBISFORMAT2*)mt.AllocFormatBuffer(sizeof(VORBISFORMAT2) + totalsize);
+ memset(pvf2, 0, mt.FormatLength());
+ pvf2->Channels = (WORD)pTE->a.Channels;
+ pvf2->SamplesPerSec = (DWORD)pTE->a.SamplingFrequency;
+ pvf2->BitsPerSample = (DWORD)pTE->a.BitDepth;
+ BYTE* p2 = mt.Format() + sizeof(VORBISFORMAT2);
+ for(int i = 0; i < sizes.GetCount(); p += sizes[i], p2 += sizes[i], i++)
+ memcpy(p2, p, pvf2->HeaderSize[i] = sizes[i]);
+
+ mts.Add(mt);
+ }
+
+ mt.subtype = MEDIASUBTYPE_Vorbis;
+ mt.formattype = FORMAT_VorbisFormat;
+ VORBISFORMAT* vf = (VORBISFORMAT*)mt.AllocFormatBuffer(sizeof(VORBISFORMAT));
+ memset(vf, 0, mt.FormatLength());
+ vf->nChannels = (WORD)pTE->a.Channels;
+ vf->nSamplesPerSec = (DWORD)pTE->a.SamplingFrequency;
+ vf->nMinBitsPerSec = vf->nMaxBitsPerSec = vf->nAvgBitsPerSec = -1;
+ mts.Add(mt);
+ }
+ else if(CodecID == "A_MS/ACM")
+ {
+ wfe = (WAVEFORMATEX*)mt.AllocFormatBuffer(pTE->CodecPrivate.GetCount());
+ memcpy(wfe, (WAVEFORMATEX*)pTE->CodecPrivate.GetData(), pTE->CodecPrivate.GetCount());
+ mt.subtype = FOURCCMap(wfe->wFormatTag);
+ mts.Add(mt);
+ }
+ else if(CodecID.Find("A_AAC/") == 0)
+ {
+ mt.subtype = FOURCCMap(wfe->wFormatTag = WAVE_FORMAT_AAC);
+ wfe = (WAVEFORMATEX*)mt.ReallocFormatBuffer(sizeof(WAVEFORMATEX) + 5);
+ wfe->cbSize = 2;
+
+ int profile;
+
+ if(CodecID.Find("/MAIN") > 0) profile = 0;
+ else if(CodecID.Find("/SBR") > 0) profile = -1;
+ else if(CodecID.Find("/LC") > 0) profile = 1;
+ else if(CodecID.Find("/SSR") > 0) profile = 2;
+ else if(CodecID.Find("/LTP") > 0) profile = 3;
+ else continue;
+
+ WORD cbSize = MakeAACInitData((BYTE*)(wfe + 1), profile, wfe->nSamplesPerSec, pTE->a.Channels);
+
+ mts.Add(mt);
+
+ if(profile < 0)
+ {
+ wfe->cbSize = cbSize;
+ wfe->nSamplesPerSec *= 2;
+ wfe->nAvgBytesPerSec *= 2;
+
+ mts.InsertAt(0, mt);
+ }
+ }
+ else if(CodecID.Find("A_REAL/") == 0 && CodecID.GetLength() >= 11)
+ {
+ mt.subtype = FOURCCMap((DWORD)CodecID[7]|((DWORD)CodecID[8]<<8)|((DWORD)CodecID[9]<<16)|((DWORD)CodecID[10]<<24));
+ mt.bTemporalCompression = TRUE;
+ wfe->cbSize = pTE->CodecPrivate.GetCount();
+ wfe = (WAVEFORMATEX*)mt.ReallocFormatBuffer(sizeof(WAVEFORMATEX) + pTE->CodecPrivate.GetCount());
+ memcpy(wfe + 1, pTE->CodecPrivate.GetData(), pTE->CodecPrivate.GetCount());
+ wfe->cbSize = 0; // IMPORTANT: this is screwed, but cbSize has to be 0 and the extra data from codec priv must be after WAVEFORMATEX
+ mts.Add(mt);
+ }
+ }
+ else if(pTE->TrackType == TrackEntry::TypeSubtitle)
+ {
+ if(iSubtitle == 1) InstallFonts();
+
+ Name.Format(L"Subtitle %d", iSubtitle++);
+
+ mt.SetSampleSize(1);
+
+ if(CodecID == "S_TEXT/ASCII")
+ {
+ mt.majortype = MEDIATYPE_Text;
+ mt.subtype = MEDIASUBTYPE_NULL;
+ mt.formattype = FORMAT_None;
+ mts.Add(mt);
+ isSub = true;
+ }
+ else
+ {
+ mt.majortype = MEDIATYPE_Subtitle;
+ mt.formattype = FORMAT_SubtitleInfo;
+ SUBTITLEINFO* psi = (SUBTITLEINFO*)mt.AllocFormatBuffer(sizeof(SUBTITLEINFO) + pTE->CodecPrivate.GetCount());
+ memset(psi, 0, mt.FormatLength());
+ strncpy(psi->IsoLang, pTE->Language, countof(psi->IsoLang)-1);
+ wcsncpy(psi->TrackName, pTE->Name, countof(psi->TrackName)-1);
+ memcpy(mt.pbFormat + (psi->dwOffset = sizeof(SUBTITLEINFO)), pTE->CodecPrivate.GetData(), pTE->CodecPrivate.GetCount());
+
+ mt.subtype =
+ CodecID == "S_TEXT/UTF8" ? MEDIASUBTYPE_UTF8 :
+ CodecID == "S_TEXT/SSA" || CodecID == "S_SSA" ? MEDIASUBTYPE_SSA :
+ CodecID == "S_TEXT/ASS" || CodecID == "S_ASS" ? MEDIASUBTYPE_ASS :
+ CodecID == "S_TEXT/SSF" || CodecID == "S_SSF" ? MEDIASUBTYPE_SSF :
+ CodecID == "S_TEXT/USF" || CodecID == "S_USF" ? MEDIASUBTYPE_USF :
+ CodecID == "S_VOBSUB" ? MEDIASUBTYPE_VOBSUB :
+ MEDIASUBTYPE_NULL;
+
+ if(mt.subtype != MEDIASUBTYPE_NULL) {
+ mts.Add(mt);
+ isSub = true;
+ }
+ }
+ }
+
+ if(mts.IsEmpty())
+ {
+ TRACE(_T("CMatroskaSourceFilter: Unsupported TrackType %s (%I64d)\n"), CString(CodecID), (UINT64)pTE->TrackType);
+ continue;
+ }
+
+ Name = CStringW(pTE->Language.IsEmpty() ? L"English" : CStringW(ISO6392ToLanguage(pTE->Language)))
+ + (pTE->Name.IsEmpty() ? L"" : L", " + pTE->Name)
+ + (L" (" + Name + L")");
+
+ HRESULT hr;
+
+ CAutoPtr<CBaseSplitterOutputPin> pPinOut(DNew CMatroskaSplitterOutputPin((int)pTE->MinCache, pTE->DefaultDuration/100, mts, Name, this, this, &hr));
+ if(!pTE->Name.IsEmpty()) pPinOut->SetProperty(L"NAME", pTE->Name);
+ if(pTE->Language.GetLength() == 3) pPinOut->SetProperty(L"LANG", CStringW(CString(pTE->Language)));
+
+ if (!isSub) {
+ pinOut.InsertAt((iVideo+iAudio-3),DNew CMatroskaSplitterOutputPin((int)pTE->MinCache, pTE->DefaultDuration/100, mts, Name, this, this, &hr),1);
+ pinOutTE.InsertAt((iVideo+iAudio-3),pTE,1);
+ } else {
+ pinOut.Add(DNew CMatroskaSplitterOutputPin((int)pTE->MinCache, pTE->DefaultDuration/100, mts, Name, this, this, &hr));
+ pinOutTE.Add(pTE);
+ }
+
+ }
+ }
+
+ for(int i = 0; i < pinOut.GetCount(); i++) {
+
+ CAutoPtr<CBaseSplitterOutputPin> pPinOut;
+ pPinOut.Attach(pinOut[i]);
+ TrackEntry* pTE = pinOutTE[i];
+
+ AddOutputPin((DWORD)pTE->TrackNumber, pPinOut);
+ m_pTrackEntryMap[(DWORD)pTE->TrackNumber] = pTE;
+ m_pOrderedTrackArray.Add(pTE);
+ }
+
+
+ Info& info = m_pFile->m_segment.SegmentInfo;
+
+ if(m_pFile->IsRandomAccess())
+ {
+ m_rtDuration = (REFERENCE_TIME)(info.Duration * info.TimeCodeScale / 100);
+ }
+
+ m_rtNewStop = m_rtStop = m_rtDuration;
#ifdef DEBUG
- /*
- for(int i = 1, j = GetChapterCount(CHAPTER_ROOT_ID); i <= j; i++)
- {
- UINT id = GetChapterId(CHAPTER_ROOT_ID, i);
- struct ChapterElement ce;
- BOOL b = GetChapterInfo(id, &ce);
- BSTR bstr = GetChapterStringInfo(id, "eng", "");
- if(bstr) ::SysFreeString(bstr);
- }
- */
+ /*
+ for(int i = 1, j = GetChapterCount(CHAPTER_ROOT_ID); i <= j; i++)
+ {
+ UINT id = GetChapterId(CHAPTER_ROOT_ID, i);
+ struct ChapterElement ce;
+ BOOL b = GetChapterInfo(id, &ce);
+ BSTR bstr = GetChapterStringInfo(id, "eng", "");
+ if(bstr) ::SysFreeString(bstr);
+ }
+ */
#endif
- SetProperty(L"TITL", info.Title);
- // TODO
+ SetProperty(L"TITL", info.Title);
+ // TODO
- // resources
+ // resources
- {
- POSITION pos = m_pFile->m_segment.Attachments.GetHeadPosition();
- while(pos)
- {
- Attachment* pA = m_pFile->m_segment.Attachments.GetNext(pos);
+ {
+ POSITION pos = m_pFile->m_segment.Attachments.GetHeadPosition();
+ while(pos)
+ {
+ Attachment* pA = m_pFile->m_segment.Attachments.GetNext(pos);
- POSITION pos = pA->AttachedFiles.GetHeadPosition();
- while(pos)
- {
- AttachedFile* pF = pA->AttachedFiles.GetNext(pos);
+ POSITION pos = pA->AttachedFiles.GetHeadPosition();
+ while(pos)
+ {
+ AttachedFile* pF = pA->AttachedFiles.GetNext(pos);
- CAtlArray<BYTE> pData;
- pData.SetCount(pF->FileDataLen);
- m_pFile->Seek(pF->FileDataPos);
- if(SUCCEEDED(m_pFile->ByteRead(pData.GetData(), pData.GetCount())))
- ResAppend(pF->FileName, pF->FileDescription, CStringW(pF->FileMimeType), pData.GetData(), pData.GetCount());
- }
- }
- }
+ CAtlArray<BYTE> pData;
+ pData.SetCount(pF->FileDataLen);
+ m_pFile->Seek(pF->FileDataPos);
+ if(SUCCEEDED(m_pFile->ByteRead(pData.GetData(), pData.GetCount())))
+ ResAppend(pF->FileName, pF->FileDescription, CStringW(pF->FileMimeType), pData.GetData(), pData.GetCount());
+ }
+ }
+ }
- // chapters
+ // chapters
- if(ChapterAtom* caroot = m_pFile->m_segment.FindChapterAtom(0))
- {
- CStringA str;
- str.ReleaseBufferSetLength(GetLocaleInfoA(LOCALE_USER_DEFAULT, LOCALE_SISO639LANGNAME, str.GetBuffer(3), 3));
- CStringA ChapLanguage = CStringA(ISO6391To6392(str));
- if(ChapLanguage.GetLength() < 3) ChapLanguage = "eng";
+ if(ChapterAtom* caroot = m_pFile->m_segment.FindChapterAtom(0))
+ {
+ CStringA str;
+ str.ReleaseBufferSetLength(GetLocaleInfoA(LOCALE_USER_DEFAULT, LOCALE_SISO639LANGNAME, str.GetBuffer(3), 3));
+ CStringA ChapLanguage = CStringA(ISO6391To6392(str));
+ if(ChapLanguage.GetLength() < 3) ChapLanguage = "eng";
- SetupChapters(ChapLanguage, caroot);
- }
+ SetupChapters(ChapLanguage, caroot);
+ }
- return m_pOutputs.GetCount() > 0 ? S_OK : E_FAIL;
+ return m_pOutputs.GetCount() > 0 ? S_OK : E_FAIL;
}
void CMatroskaSplitterFilter::SetupChapters(LPCSTR lng, ChapterAtom* parent, int level)
{
- CStringW tabs('+', level);
+ CStringW tabs('+', level);
- if(!tabs.IsEmpty()) tabs += ' ';
+ if(!tabs.IsEmpty()) tabs += ' ';
- POSITION pos = parent->ChapterAtoms.GetHeadPosition();
- while(pos)
- {
- // ChapUID zero not allow by Matroska specs
- UINT64 ChapUID = parent->ChapterAtoms.GetNext(pos)->ChapterUID;
- ChapterAtom* ca = (ChapUID == 0) ? NULL : m_pFile->m_segment.FindChapterAtom(ChapUID);
+ POSITION pos = parent->ChapterAtoms.GetHeadPosition();
+ while(pos)
+ {
+ // ChapUID zero not allow by Matroska specs
+ UINT64 ChapUID = parent->ChapterAtoms.GetNext(pos)->ChapterUID;
+ ChapterAtom* ca = (ChapUID == 0) ? NULL : m_pFile->m_segment.FindChapterAtom(ChapUID);
- if(ca)
- {
- CStringW name, first;
+ if(ca)
+ {
+ CStringW name, first;
- POSITION pos = ca->ChapterDisplays.GetHeadPosition();
- while(pos)
- {
- ChapterDisplay* cd = ca->ChapterDisplays.GetNext(pos);
- if(first.IsEmpty()) first = cd->ChapString;
- if(cd->ChapLanguage == lng) name = cd->ChapString;
- }
+ POSITION pos = ca->ChapterDisplays.GetHeadPosition();
+ while(pos)
+ {
+ ChapterDisplay* cd = ca->ChapterDisplays.GetNext(pos);
+ if(first.IsEmpty()) first = cd->ChapString;
+ if(cd->ChapLanguage == lng) name = cd->ChapString;
+ }
- name = tabs + (!name.IsEmpty() ? name : first);
+ name = tabs + (!name.IsEmpty() ? name : first);
- ChapAppend(ca->ChapterTimeStart / 100 - m_pFile->m_rtOffset, name);
+ ChapAppend(ca->ChapterTimeStart / 100 - m_pFile->m_rtOffset, name);
- if(!ca->ChapterAtoms.IsEmpty())
- {
- SetupChapters(lng, ca, level + 1);
- }
- }
- }
+ if(!ca->ChapterAtoms.IsEmpty())
+ {
+ SetupChapters(lng, ca, level+1);
+ }
+ }
+ }
}
void CMatroskaSplitterFilter::InstallFonts()
{
- POSITION pos = m_pFile->m_segment.Attachments.GetHeadPosition();
- while(pos)
- {
- Attachment* pA = m_pFile->m_segment.Attachments.GetNext(pos);
-
- POSITION p2 = pA->AttachedFiles.GetHeadPosition();
- while(p2)
- {
- AttachedFile* pF = pA->AttachedFiles.GetNext(p2);
-
- if(pF->FileMimeType == "application/x-truetype-font")
- {
- // assume this is a font resource
-
- if(BYTE* pData = DNew BYTE[(UINT)pF->FileDataLen])
- {
- m_pFile->Seek(pF->FileDataPos);
-
- if(SUCCEEDED(m_pFile->ByteRead(pData, pF->FileDataLen)))
- m_fontinst.InstallFont(pData, (UINT)pF->FileDataLen);
-
- delete [] pData;
- }
- }
- }
- }
+ POSITION pos = m_pFile->m_segment.Attachments.GetHeadPosition();
+ while(pos)
+ {
+ Attachment* pA = m_pFile->m_segment.Attachments.GetNext(pos);
+
+ POSITION p2 = pA->AttachedFiles.GetHeadPosition();
+ while(p2)
+ {
+ AttachedFile* pF = pA->AttachedFiles.GetNext(p2);
+
+ if(pF->FileMimeType == "application/x-truetype-font")
+ {
+ // assume this is a font resource
+
+ if(BYTE* pData = DNew BYTE[(UINT)pF->FileDataLen])
+ {
+ m_pFile->Seek(pF->FileDataPos);
+
+ if(SUCCEEDED(m_pFile->ByteRead(pData, pF->FileDataLen)))
+ m_fontinst.InstallFont(pData, (UINT)pF->FileDataLen);
+
+ delete [] pData;
+ }
+ }
+ }
+ }
}
void CMatroskaSplitterFilter::SendVorbisHeaderSample()
{
- HRESULT hr;
-
- POSITION pos = m_pTrackEntryMap.GetStartPosition();
- while(pos)
- {
- DWORD TrackNumber = 0;
- TrackEntry* pTE = NULL;
- m_pTrackEntryMap.GetNextAssoc(pos, TrackNumber, pTE);
-
- CBaseSplitterOutputPin* pPin = GetOutputPin(TrackNumber);
-
- if(!(pTE && pPin && pPin->IsConnected()))
- continue;
-
- if(pTE->CodecID.ToString() == "A_VORBIS" && pPin->CurrentMediaType().subtype == MEDIASUBTYPE_Vorbis
- && pTE->CodecPrivate.GetCount() > 0)
- {
- BYTE* ptr = pTE->CodecPrivate.GetData();
-
- CAtlList<int> sizes;
- long last = 0;
- for(BYTE n = *ptr++; n > 0; n--)
- {
- int size = 0;
- do
- {
- size += *ptr;
- }
- while(*ptr++ == 0xff);
- sizes.AddTail(size);
- last += size;
- }
- sizes.AddTail(pTE->CodecPrivate.GetCount() - (ptr - pTE->CodecPrivate.GetData()) - last);
-
- hr = S_OK;
-
- POSITION pos = sizes.GetHeadPosition();
- while(pos && SUCCEEDED(hr))
- {
- long len = sizes.GetNext(pos);
-
- CAutoPtr<Packet> p(DNew Packet());
- p->TrackNumber = (DWORD)pTE->TrackNumber;
- p->rtStart = 0;
- p->rtStop = 1;
- p->bSyncPoint = FALSE;
-
- p->SetData(ptr, len);
- ptr += len;
-
- hr = DeliverPacket(p);
- }
-
- if(FAILED(hr))
- TRACE(_T("ERROR: Vorbis initialization failed for stream %I64d\n"), TrackNumber);
- }
- }
+ HRESULT hr;
+
+ POSITION pos = m_pTrackEntryMap.GetStartPosition();
+ while(pos)
+ {
+ DWORD TrackNumber = 0;
+ TrackEntry* pTE = NULL;
+ m_pTrackEntryMap.GetNextAssoc(pos, TrackNumber, pTE);
+
+ CBaseSplitterOutputPin* pPin = GetOutputPin(TrackNumber);
+
+ if(!(pTE && pPin && pPin->IsConnected()))
+ continue;
+
+ if(pTE->CodecID.ToString() == "A_VORBIS" && pPin->CurrentMediaType().subtype == MEDIASUBTYPE_Vorbis
+ && pTE->CodecPrivate.GetCount() > 0)
+ {
+ BYTE* ptr = pTE->CodecPrivate.GetData();
+
+ CAtlList<int> sizes;
+ long last = 0;
+ for(BYTE n = *ptr++; n > 0; n--)
+ {
+ int size = 0;
+ do {size += *ptr;} while(*ptr++ == 0xff);
+ sizes.AddTail(size);
+ last += size;
+ }
+ sizes.AddTail(pTE->CodecPrivate.GetCount() - (ptr - pTE->CodecPrivate.GetData()) - last);
+
+ hr = S_OK;
+
+ POSITION pos = sizes.GetHeadPosition();
+ while(pos && SUCCEEDED(hr))
+ {
+ long len = sizes.GetNext(pos);
+
+ CAutoPtr<Packet> p(DNew Packet());
+ p->TrackNumber = (DWORD)pTE->TrackNumber;
+ p->rtStart = 0; p->rtStop = 1;
+ p->bSyncPoint = FALSE;
+
+ p->SetData(ptr, len);
+ ptr += len;
+
+ hr = DeliverPacket(p);
+ }
+
+ if(FAILED(hr))
+ TRACE(_T("ERROR: Vorbis initialization failed for stream %I64d\n"), TrackNumber);
+ }
+ }
}
bool CMatroskaSplitterFilter::DemuxInit()
{
- CMatroskaNode Root(m_pFile);
- if(!m_pFile
- || !(m_pSegment = Root.Child(0x18538067))
- || !(m_pCluster = m_pSegment->Child(0x1F43B675)))
- return(false);
+ CMatroskaNode Root(m_pFile);
+ if(!m_pFile
+ || !(m_pSegment = Root.Child(0x18538067))
+ || !(m_pCluster = m_pSegment->Child(0x1F43B675)))
+ return(false);
- // reindex if needed
+ // reindex if needed
- if(m_pFile->IsRandomAccess() && m_pFile->m_segment.Cues.GetCount() == 0)
- {
- m_nOpenProgress = 0;
- m_pFile->m_segment.SegmentInfo.Duration.Set(0);
+ if(m_pFile->IsRandomAccess() && m_pFile->m_segment.Cues.GetCount() == 0)
+ {
+ m_nOpenProgress = 0;
+ m_pFile->m_segment.SegmentInfo.Duration.Set(0);
- UINT64 TrackNumber = m_pFile->m_segment.GetMasterTrack();
+ UINT64 TrackNumber = m_pFile->m_segment.GetMasterTrack();
- CAutoPtr<Cue> pCue(DNew Cue());
+ CAutoPtr<Cue> pCue(DNew Cue());
- do
- {
- Cluster c;
- c.ParseTimeCode(m_pCluster);
+ do
+ {
+ Cluster c;
+ c.ParseTimeCode(m_pCluster);
- m_pFile->m_segment.SegmentInfo.Duration.Set((float)c.TimeCode - m_pFile->m_rtOffset / 10000);
+ m_pFile->m_segment.SegmentInfo.Duration.Set((float)c.TimeCode - m_pFile->m_rtOffset/10000);
- CAutoPtr<CuePoint> pCuePoint(DNew CuePoint());
- CAutoPtr<CueTrackPosition> pCueTrackPosition(DNew CueTrackPosition());
- pCuePoint->CueTime.Set(c.TimeCode);
- pCueTrackPosition->CueTrack.Set(TrackNumber);
- pCueTrackPosition->CueClusterPosition.Set(m_pCluster->m_filepos - m_pSegment->m_start);
- pCuePoint->CueTrackPositions.AddTail(pCueTrackPosition);
- pCue->CuePoints.AddTail(pCuePoint);
+ CAutoPtr<CuePoint> pCuePoint(DNew CuePoint());
+ CAutoPtr<CueTrackPosition> pCueTrackPosition(DNew CueTrackPosition());
+ pCuePoint->CueTime.Set(c.TimeCode);
+ pCueTrackPosition->CueTrack.Set(TrackNumber);
+ pCueTrackPosition->CueClusterPosition.Set(m_pCluster->m_filepos - m_pSegment->m_start);
+ pCuePoint->CueTrackPositions.AddTail(pCueTrackPosition);
+ pCue->CuePoints.AddTail(pCuePoint);
- m_nOpenProgress = m_pFile->GetPos() * 100 / m_pFile->GetLength();
+ m_nOpenProgress = m_pFile->GetPos()*100/m_pFile->GetLength();
- DWORD cmd;
- if(CheckRequest(&cmd))
- {
- if(cmd == CMD_EXIT) m_fAbort = true;
- else Reply(S_OK);
- }
- }
- while(!m_fAbort && m_pCluster->Next(true));
+ DWORD cmd;
+ if(CheckRequest(&cmd))
+ {
+ if(cmd == CMD_EXIT) m_fAbort = true;
+ else Reply(S_OK);
+ }
+ }
+ while(!m_fAbort && m_pCluster->Next(true));
- m_nOpenProgress = 100;
+ m_nOpenProgress = 100;
- if(!m_fAbort) m_pFile->m_segment.Cues.AddTail(pCue);
+ if(!m_fAbort) m_pFile->m_segment.Cues.AddTail(pCue);
- m_fAbort = false;
- }
+ m_fAbort = false;
+ }
- m_pCluster.Free();
- m_pBlock.Free();
+ m_pCluster.Free();
+ m_pBlock.Free();
- return(true);
+ return(true);
}
void CMatroskaSplitterFilter::DemuxSeek(REFERENCE_TIME rt)
{
- m_pCluster = m_pSegment->Child(0x1F43B675);
- m_pBlock.Free();
-
- if(rt > 0)
- {
- rt += m_pFile->m_rtOffset;
-
- MatroskaReader::QWORD lastCueClusterPosition = -1;
-
- Segment& s = m_pFile->m_segment;
-
- UINT64 TrackNumber = s.GetMasterTrack();
-
- POSITION pos1 = s.Cues.GetHeadPosition();
- while(pos1)
- {
- Cue* pCue = s.Cues.GetNext(pos1);
-
- POSITION pos2 = pCue->CuePoints.GetTailPosition();
- while(pos2)
- {
- CuePoint* pCuePoint = pCue->CuePoints.GetPrev(pos2);
-
- if(rt < s.GetRefTime(pCuePoint->CueTime))
- continue;
-
- POSITION pos3 = pCuePoint->CueTrackPositions.GetHeadPosition();
- while(pos3)
- {
- CueTrackPosition* pCueTrackPositions = pCuePoint->CueTrackPositions.GetNext(pos3);
-
- if(TrackNumber != pCueTrackPositions->CueTrack)
- continue;
-
- if(lastCueClusterPosition == pCueTrackPositions->CueClusterPosition)
- continue;
-
- lastCueClusterPosition = pCueTrackPositions->CueClusterPosition;
-
- m_pCluster->SeekTo(m_pSegment->m_start + pCueTrackPositions->CueClusterPosition);
- m_pCluster->Parse();
-
- bool fFoundKeyFrame = false;
- /*
- if(pCueTrackPositions->CueBlockNumber > 0)
- {
- // TODO: CueBlockNumber only tells the block num of the track and not for all mixed in the cluster
- m_nLastBlock = (int)pCueTrackPositions->CueBlockNumber;
- fFoundKeyFrame = true;
- }
- else
- */
- {
- Cluster c;
- c.ParseTimeCode(m_pCluster);
-
- if(CAutoPtr<CMatroskaNode> pBlock = m_pCluster->GetFirstBlock())
- {
- bool fPassedCueTime = false;
-
- do
- {
- CBlockGroupNode bgn;
-
- if(pBlock->m_id == 0xA0)
- {
- bgn.Parse(pBlock, true);
- }
- else if(pBlock->m_id == 0xA3)
- {
- CAutoPtr<BlockGroup> bg(DNew BlockGroup());
- bg->Block.Parse(pBlock, true);
- if(!(bg->Block.Lacing & 0x80)) bg->ReferenceBlock.Set(0); // not a kf
- bgn.AddTail(bg);
- }
-
- POSITION pos4 = bgn.GetHeadPosition();
- while(!fPassedCueTime && pos4)
- {
- BlockGroup* bg = bgn.GetNext(pos4);
-
- if(bg->Block.TrackNumber == pCueTrackPositions->CueTrack && rt < s.GetRefTime(c.TimeCode + bg->Block.TimeCode)
- || rt + 5000000i64 < s.GetRefTime(c.TimeCode + bg->Block.TimeCode)) // allow 500ms difference between tracks, just in case intreleaving wasn't that much precise
- {
- fPassedCueTime = true;
- }
- else if(bg->Block.TrackNumber == pCueTrackPositions->CueTrack && !bg->ReferenceBlock.IsValid())
- {
- fFoundKeyFrame = true;
- m_pBlock = pBlock->Copy();
- }
- }
- }
- while(!fPassedCueTime && pBlock->NextBlock());
- }
- }
-
- if(fFoundKeyFrame)
- pos1 = pos2 = pos3 = NULL;
- }
- }
- }
-
- if(!m_pBlock)
- {
- m_pCluster = m_pSegment->Child(0x1F43B675);
- }
- }
+ m_pCluster = m_pSegment->Child(0x1F43B675);
+ m_pBlock.Free();
+
+ if(rt > 0)
+ {
+ rt += m_pFile->m_rtOffset;
+
+ MatroskaReader::QWORD lastCueClusterPosition = -1;
+
+ Segment& s = m_pFile->m_segment;
+
+ UINT64 TrackNumber = s.GetMasterTrack();
+
+ POSITION pos1 = s.Cues.GetHeadPosition();
+ while(pos1)
+ {
+ Cue* pCue = s.Cues.GetNext(pos1);
+
+ POSITION pos2 = pCue->CuePoints.GetTailPosition();
+ while(pos2)
+ {
+ CuePoint* pCuePoint = pCue->CuePoints.GetPrev(pos2);
+
+ if(rt < s.GetRefTime(pCuePoint->CueTime))
+ continue;
+
+ POSITION pos3 = pCuePoint->CueTrackPositions.GetHeadPosition();
+ while(pos3)
+ {
+ CueTrackPosition* pCueTrackPositions = pCuePoint->CueTrackPositions.GetNext(pos3);
+
+ if(TrackNumber != pCueTrackPositions->CueTrack)
+ continue;
+
+ if(lastCueClusterPosition == pCueTrackPositions->CueClusterPosition)
+ continue;
+
+ lastCueClusterPosition = pCueTrackPositions->CueClusterPosition;
+
+ m_pCluster->SeekTo(m_pSegment->m_start + pCueTrackPositions->CueClusterPosition);
+ m_pCluster->Parse();
+
+ bool fFoundKeyFrame = false;
+/*
+ if(pCueTrackPositions->CueBlockNumber > 0)
+ {
+ // TODO: CueBlockNumber only tells the block num of the track and not for all mixed in the cluster
+ m_nLastBlock = (int)pCueTrackPositions->CueBlockNumber;
+ fFoundKeyFrame = true;
+ }
+ else
+*/
+ {
+ Cluster c;
+ c.ParseTimeCode(m_pCluster);
+
+ if(CAutoPtr<CMatroskaNode> pBlock = m_pCluster->GetFirstBlock())
+ {
+ bool fPassedCueTime = false;
+
+ do
+ {
+ CBlockGroupNode bgn;
+
+ if(pBlock->m_id == 0xA0)
+ {
+ bgn.Parse(pBlock, true);
+ }
+ else if(pBlock->m_id == 0xA3)
+ {
+ CAutoPtr<BlockGroup> bg(DNew BlockGroup());
+ bg->Block.Parse(pBlock, true);
+ if(!(bg->Block.Lacing & 0x80)) bg->ReferenceBlock.Set(0); // not a kf
+ bgn.AddTail(bg);
+ }
+
+ POSITION pos4 = bgn.GetHeadPosition();
+ while(!fPassedCueTime && pos4)
+ {
+ BlockGroup* bg = bgn.GetNext(pos4);
+
+ if(bg->Block.TrackNumber == pCueTrackPositions->CueTrack && rt < s.GetRefTime(c.TimeCode + bg->Block.TimeCode)
+ || rt + 5000000i64 < s.GetRefTime(c.TimeCode + bg->Block.TimeCode)) // allow 500ms difference between tracks, just in case intreleaving wasn't that much precise
+ {
+ fPassedCueTime = true;
+ }
+ else if(bg->Block.TrackNumber == pCueTrackPositions->CueTrack && !bg->ReferenceBlock.IsValid())
+ {
+ fFoundKeyFrame = true;
+ m_pBlock = pBlock->Copy();
+ }
+ }
+ }
+ while(!fPassedCueTime && pBlock->NextBlock());
+ }
+ }
+
+ if(fFoundKeyFrame)
+ pos1 = pos2 = pos3 = NULL;
+ }
+ }
+ }
+
+ if(!m_pBlock)
+ {
+ m_pCluster = m_pSegment->Child(0x1F43B675);
+ }
+ }
}
bool CMatroskaSplitterFilter::DemuxLoop()
{
- HRESULT hr = S_OK;
-
- SendVorbisHeaderSample(); // HACK: init vorbis decoder with the headers
-
- do
- {
- Cluster c;
- c.ParseTimeCode(m_pCluster);
-
- if(!m_pBlock) m_pBlock = m_pCluster->GetFirstBlock();
- if(!m_pBlock) continue;
-
- do
- {
- CBlockGroupNode bgn;
-
- if(m_pBlock->m_id == 0xA0)
- {
- bgn.Parse(m_pBlock, true);
- }
- else if(m_pBlock->m_id == 0xA3)
- {
- CAutoPtr<BlockGroup> bg(DNew BlockGroup());
- bg->Block.Parse(m_pBlock, true);
- if(!(bg->Block.Lacing & 0x80)) bg->ReferenceBlock.Set(0); // not a kf
- bgn.AddTail(bg);
- }
-
- while(bgn.GetCount() && SUCCEEDED(hr))
- {
- CAutoPtr<MatroskaPacket> p(DNew MatroskaPacket());
- p->bg = bgn.RemoveHead();
-
- p->bSyncPoint = !p->bg->ReferenceBlock.IsValid();
- p->TrackNumber = (DWORD)p->bg->Block.TrackNumber;
-
- TrackEntry* pTE = m_pTrackEntryMap[p->TrackNumber];
- if(!pTE) continue;
-
- p->rtStart = m_pFile->m_segment.GetRefTime((REFERENCE_TIME)c.TimeCode + p->bg->Block.TimeCode);
- p->rtStop = p->rtStart + (p->bg->BlockDuration.IsValid() ? m_pFile->m_segment.GetRefTime(p->bg->BlockDuration) : 1);
-
- // Fix subtitle with duration = 0
- if(pTE->TrackType == TrackEntry::TypeSubtitle && !p->bg->BlockDuration.IsValid())
- {
- p->bg->BlockDuration.Set(1); // just setting it to be valid
- p->rtStop = p->rtStart;
- }
-
- POSITION pos = p->bg->Block.BlockData.GetHeadPosition();
- while(pos)
- {
- CBinary* pb = p->bg->Block.BlockData.GetNext(pos);
- pTE->Expand(*pb, ContentEncoding::AllFrameContents);
- }
-
- // HACK
- p->rtStart -= m_pFile->m_rtOffset;
- p->rtStop -= m_pFile->m_rtOffset;
-
- hr = DeliverPacket(p);
- }
- }
- while(m_pBlock->NextBlock() && SUCCEEDED(hr) && !CheckRequest(NULL));
-
- m_pBlock.Free();
- }
- while(m_pFile->GetPos() < m_pFile->m_segment.pos + m_pFile->m_segment.len
- && m_pCluster->Next(true) && SUCCEEDED(hr) && !CheckRequest(NULL));
-
- m_pCluster.Free();
-
- return(true);
+ HRESULT hr = S_OK;
+
+ SendVorbisHeaderSample(); // HACK: init vorbis decoder with the headers
+
+ do
+ {
+ Cluster c;
+ c.ParseTimeCode(m_pCluster);
+
+ if(!m_pBlock) m_pBlock = m_pCluster->GetFirstBlock();
+ if(!m_pBlock) continue;
+
+ do
+ {
+ CBlockGroupNode bgn;
+
+ if(m_pBlock->m_id == 0xA0)
+ {
+ bgn.Parse(m_pBlock, true);
+ }
+ else if(m_pBlock->m_id == 0xA3)
+ {
+ CAutoPtr<BlockGroup> bg(DNew BlockGroup());
+ bg->Block.Parse(m_pBlock, true);
+ if(!(bg->Block.Lacing & 0x80)) bg->ReferenceBlock.Set(0); // not a kf
+ bgn.AddTail(bg);
+ }
+
+ while(bgn.GetCount() && SUCCEEDED(hr))
+ {
+ CAutoPtr<MatroskaPacket> p(DNew MatroskaPacket());
+ p->bg = bgn.RemoveHead();
+
+ p->bSyncPoint = !p->bg->ReferenceBlock.IsValid();
+ p->TrackNumber = (DWORD)p->bg->Block.TrackNumber;
+
+ TrackEntry* pTE = m_pTrackEntryMap[p->TrackNumber];
+ if(!pTE) continue;
+
+ p->rtStart = m_pFile->m_segment.GetRefTime((REFERENCE_TIME)c.TimeCode + p->bg->Block.TimeCode);
+ p->rtStop = p->rtStart + (p->bg->BlockDuration.IsValid() ? m_pFile->m_segment.GetRefTime(p->bg->BlockDuration) : 1);
+
+ // Fix subtitle with duration = 0
+ if(pTE->TrackType == TrackEntry::TypeSubtitle && !p->bg->BlockDuration.IsValid())
+ {
+ p->bg->BlockDuration.Set(1); // just setting it to be valid
+ p->rtStop = p->rtStart;
+ }
+
+ POSITION pos = p->bg->Block.BlockData.GetHeadPosition();
+ while(pos)
+ {
+ CBinary* pb = p->bg->Block.BlockData.GetNext(pos);
+ pTE->Expand(*pb, ContentEncoding::AllFrameContents);
+ }
+
+ // HACK
+ p->rtStart -= m_pFile->m_rtOffset;
+ p->rtStop -= m_pFile->m_rtOffset;
+
+ hr = DeliverPacket(p);
+ }
+ }
+ while(m_pBlock->NextBlock() && SUCCEEDED(hr) && !CheckRequest(NULL));
+
+ m_pBlock.Free();
+ }
+ while(m_pFile->GetPos() < m_pFile->m_segment.pos + m_pFile->m_segment.len
+ && m_pCluster->Next(true) && SUCCEEDED(hr) && !CheckRequest(NULL));
+
+ m_pCluster.Free();
+
+ return(true);
}
// IKeyFrameInfo
STDMETHODIMP CMatroskaSplitterFilter::GetKeyFrameCount(UINT& nKFs)
{
- if(!m_pFile) return E_UNEXPECTED;
+ if(!m_pFile) return E_UNEXPECTED;
- HRESULT hr = S_OK;
+ HRESULT hr = S_OK;
- nKFs = 0;
+ nKFs = 0;
- POSITION pos = m_pFile->m_segment.Cues.GetHeadPosition();
- while(pos) nKFs += m_pFile->m_segment.Cues.GetNext(pos)->CuePoints.GetCount();
+ POSITION pos = m_pFile->m_segment.Cues.GetHeadPosition();
+ while(pos) nKFs += m_pFile->m_segment.Cues.GetNext(pos)->CuePoints.GetCount();
- return hr;
+ return hr;
}
STDMETHODIMP CMatroskaSplitterFilter::GetKeyFrames(const GUID* pFormat, REFERENCE_TIME* pKFs, UINT& nKFs)
{
- CheckPointer(pFormat, E_POINTER);
- CheckPointer(pKFs, E_POINTER);
+ CheckPointer(pFormat, E_POINTER);
+ CheckPointer(pKFs, E_POINTER);
- if(!m_pFile) return E_UNEXPECTED;
- if(*pFormat != TIME_FORMAT_MEDIA_TIME) return E_INVALIDARG;
+ if(!m_pFile) return E_UNEXPECTED;
+ if(*pFormat != TIME_FORMAT_MEDIA_TIME) return E_INVALIDARG;
- UINT nKFsTmp = 0;
+ UINT nKFsTmp = 0;
- POSITION pos1 = m_pFile->m_segment.Cues.GetHeadPosition();
- while(pos1 && nKFsTmp < nKFs)
- {
- Cue* pCue = m_pFile->m_segment.Cues.GetNext(pos1);
+ POSITION pos1 = m_pFile->m_segment.Cues.GetHeadPosition();
+ while(pos1 && nKFsTmp < nKFs)
+ {
+ Cue* pCue = m_pFile->m_segment.Cues.GetNext(pos1);
- POSITION pos2 = pCue->CuePoints.GetHeadPosition();
- while(pos2 && nKFsTmp < nKFs)
- pKFs[nKFsTmp++] = m_pFile->m_segment.GetRefTime(pCue->CuePoints.GetNext(pos2)->CueTime);
- }
+ POSITION pos2 = pCue->CuePoints.GetHeadPosition();
+ while(pos2 && nKFsTmp < nKFs)
+ pKFs[nKFsTmp++] = m_pFile->m_segment.GetRefTime(pCue->CuePoints.GetNext(pos2)->CueTime);
+ }
- nKFs = nKFsTmp;
+ nKFs = nKFsTmp;
- return S_OK;
+ return S_OK;
}
//
@@ -1120,10 +1098,10 @@ STDMETHODIMP CMatroskaSplitterFilter::GetKeyFrames(const GUID* pFormat, REFERENC
//
CMatroskaSourceFilter::CMatroskaSourceFilter(LPUNKNOWN pUnk, HRESULT* phr)
- : CMatroskaSplitterFilter(pUnk, phr)
+ : CMatroskaSplitterFilter(pUnk, phr)
{
- m_clsid = __uuidof(this);
- m_pInput.Free();
+ m_clsid = __uuidof(this);
+ m_pInput.Free();
}
//
@@ -1131,12 +1109,12 @@ CMatroskaSourceFilter::CMatroskaSourceFilter(LPUNKNOWN pUnk, HRESULT* phr)
//
CMatroskaSplitterOutputPin::CMatroskaSplitterOutputPin(
- int nMinCache, REFERENCE_TIME rtDefaultDuration,
- CAtlArray<CMediaType>& mts, LPCWSTR pName, CBaseFilter* pFilter, CCritSec* pLock, HRESULT* phr)
- : CBaseSplitterOutputPin(mts, pName, pFilter, pLock, phr)
- , m_nMinCache(nMinCache), m_rtDefaultDuration(rtDefaultDuration)
+ int nMinCache, REFERENCE_TIME rtDefaultDuration,
+ CAtlArray<CMediaType>& mts, LPCWSTR pName, CBaseFilter* pFilter, CCritSec* pLock, HRESULT* phr)
+ : CBaseSplitterOutputPin(mts, pName, pFilter, pLock, phr)
+ , m_nMinCache(nMinCache), m_rtDefaultDuration(rtDefaultDuration)
{
- m_nMinCache = 1;//max(m_nMinCache, 1);
+ m_nMinCache = 1;//max(m_nMinCache, 1);
}
CMatroskaSplitterOutputPin::~CMatroskaSplitterOutputPin()
@@ -1145,268 +1123,264 @@ CMatroskaSplitterOutputPin::~CMatroskaSplitterOutputPin()
HRESULT CMatroskaSplitterOutputPin::DeliverEndFlush()
{
- {
- CAutoLock cAutoLock(&m_csQueue);
- m_packets.RemoveAll();
- m_rob.RemoveAll();
- m_tos.RemoveAll();
- }
-
- return __super::DeliverEndFlush();
+ {
+ CAutoLock cAutoLock(&m_csQueue);
+ m_packets.RemoveAll();
+ m_rob.RemoveAll();
+ m_tos.RemoveAll();
+ }
+
+ return __super::DeliverEndFlush();
}
HRESULT CMatroskaSplitterOutputPin::DeliverEndOfStream()
{
- CAutoLock cAutoLock(&m_csQueue);
+ CAutoLock cAutoLock(&m_csQueue);
- // send out the last remaining packets from the queue
+ // send out the last remaining packets from the queue
- while(m_rob.GetCount())
- {
- MatroskaPacket* mp = m_rob.RemoveHead();
- if(m_rob.GetCount() && !mp->bg->BlockDuration.IsValid())
- mp->rtStop = m_rob.GetHead()->rtStart;
- else if(m_rob.GetCount() == 0 && m_rtDefaultDuration > 0)
- mp->rtStop = mp->rtStart + m_rtDefaultDuration;
+ while(m_rob.GetCount())
+ {
+ MatroskaPacket* mp = m_rob.RemoveHead();
+ if(m_rob.GetCount() && !mp->bg->BlockDuration.IsValid())
+ mp->rtStop = m_rob.GetHead()->rtStart;
+ else if(m_rob.GetCount() == 0 && m_rtDefaultDuration > 0)
+ mp->rtStop = mp->rtStart + m_rtDefaultDuration;
- timeoverride to = {mp->rtStart, mp->rtStop};
- m_tos.AddTail(to);
- }
+ timeoverride to = {mp->rtStart, mp->rtStop};
+ m_tos.AddTail(to);
+ }
- while(m_packets.GetCount())
- {
- HRESULT hr = DeliverBlock(m_packets.RemoveHead());
- if(hr != S_OK) return hr;
- }
+ while(m_packets.GetCount())
+ {
+ HRESULT hr = DeliverBlock(m_packets.RemoveHead());
+ if(hr != S_OK) return hr;
+ }
- return __super::DeliverEndOfStream();
+ return __super::DeliverEndOfStream();
}
HRESULT CMatroskaSplitterOutputPin::DeliverPacket(CAutoPtr<Packet> p)
{
- MatroskaPacket* mp = dynamic_cast<MatroskaPacket*>(p.m_p);
- if(!mp) return __super::DeliverPacket(p);
-
- // don't try to understand what's happening here, it's magic
-
- CAutoLock cAutoLock(&m_csQueue);
-
- CAutoPtr<MatroskaPacket> p2;
- p.Detach();
- p2.Attach(mp);
- m_packets.AddTail(p2);
-
- POSITION pos = m_rob.GetTailPosition();
- for(int i = m_nMinCache - 1; i > 0 && pos && mp->bg->ReferencePriority < m_rob.GetAt(pos)->bg->ReferencePriority; i--)
- m_rob.GetPrev(pos);
-
- if(!pos) m_rob.AddHead(mp);
- else m_rob.InsertAfter(pos, mp);
-
- mp = NULL;
-
- if(m_rob.GetCount() == m_nMinCache + 1)
- {
- ASSERT(m_nMinCache > 0);
- pos = m_rob.GetHeadPosition();
- MatroskaPacket* mp1 = m_rob.GetNext(pos);
- MatroskaPacket* mp2 = m_rob.GetNext(pos);
- if(!mp1->bg->BlockDuration.IsValid())
- {
- mp1->bg->BlockDuration.Set(1); // just to set it valid
-
- if(mp1->rtStart >= mp2->rtStart)
- {
- /* CString str;
- str.Format(_T("mp1->rtStart (%I64d) >= mp2->rtStart (%I64d)!!!\n"), mp1->rtStart, mp2->rtStart);
- AfxMessageBox(str);
- */
- // TRACE(_T("mp1->rtStart (%I64d) >= mp2->rtStart (%I64d)!!!\n"), mp1->rtStart, mp2->rtStart);
- }
- else
- {
- mp1->rtStop = mp2->rtStart;
- }
- }
- }
-
- while(m_packets.GetCount())
- {
- mp = m_packets.GetHead();
- if(!mp->bg->BlockDuration.IsValid()) break;
-
- mp = m_rob.RemoveHead();
- timeoverride to = {mp->rtStart, mp->rtStop};
- m_tos.AddTail(to);
-
- HRESULT hr = DeliverBlock(m_packets.RemoveHead());
- if(hr != S_OK) return hr;
- }
-
- return S_OK;
+ MatroskaPacket* mp = dynamic_cast<MatroskaPacket*>(p.m_p);
+ if(!mp) return __super::DeliverPacket(p);
+
+ // don't try to understand what's happening here, it's magic
+
+ CAutoLock cAutoLock(&m_csQueue);
+
+ CAutoPtr<MatroskaPacket> p2;
+ p.Detach();
+ p2.Attach(mp);
+ m_packets.AddTail(p2);
+
+ POSITION pos = m_rob.GetTailPosition();
+ for(int i = m_nMinCache-1; i > 0 && pos && mp->bg->ReferencePriority < m_rob.GetAt(pos)->bg->ReferencePriority; i--)
+ m_rob.GetPrev(pos);
+
+ if(!pos) m_rob.AddHead(mp);
+ else m_rob.InsertAfter(pos, mp);
+
+ mp = NULL;
+
+ if(m_rob.GetCount() == m_nMinCache+1)
+ {
+ ASSERT(m_nMinCache > 0);
+ pos = m_rob.GetHeadPosition();
+ MatroskaPacket* mp1 = m_rob.GetNext(pos);
+ MatroskaPacket* mp2 = m_rob.GetNext(pos);
+ if(!mp1->bg->BlockDuration.IsValid())
+ {
+ mp1->bg->BlockDuration.Set(1); // just to set it valid
+
+ if(mp1->rtStart >= mp2->rtStart)
+ {
+/* CString str;
+ str.Format(_T("mp1->rtStart (%I64d) >= mp2->rtStart (%I64d)!!!\n"), mp1->rtStart, mp2->rtStart);
+ AfxMessageBox(str);
+*/
+ // TRACE(_T("mp1->rtStart (%I64d) >= mp2->rtStart (%I64d)!!!\n"), mp1->rtStart, mp2->rtStart);
+ }
+ else
+ {
+ mp1->rtStop = mp2->rtStart;
+ }
+ }
+ }
+
+ while(m_packets.GetCount())
+ {
+ mp = m_packets.GetHead();
+ if(!mp->bg->BlockDuration.IsValid()) break;
+
+ mp = m_rob.RemoveHead();
+ timeoverride to = {mp->rtStart, mp->rtStop};
+ m_tos.AddTail(to);
+
+ HRESULT hr = DeliverBlock(m_packets.RemoveHead());
+ if(hr != S_OK) return hr;
+ }
+
+ return S_OK;
}
HRESULT CMatroskaSplitterOutputPin::DeliverBlock(MatroskaPacket* p)
{
- HRESULT hr = S_FALSE;
+ HRESULT hr = S_FALSE;
- if(m_tos.GetCount())
- {
- timeoverride to = m_tos.RemoveHead();
+ if(m_tos.GetCount())
+ {
+ timeoverride to = m_tos.RemoveHead();
// if(p->TrackNumber == 2)
- TRACE(_T("(track=%d) %I64d, %I64d -> %I64d, %I64d (buffcnt=%d)\n"),
- p->TrackNumber, p->rtStart, p->rtStop, to.rtStart, to.rtStop,
- QueueCount());
- /**/
- p->rtStart = to.rtStart;
- p->rtStop = to.rtStop;
- }
-
- REFERENCE_TIME
- rtStart = p->rtStart,
- rtDelta = (p->rtStop - p->rtStart) / p->bg->Block.BlockData.GetCount(),
- rtStop = p->rtStart + rtDelta;
-
- POSITION pos = p->bg->Block.BlockData.GetHeadPosition();
- while(pos)
- {
- CAutoPtr<Packet> tmp(DNew Packet());
- tmp->TrackNumber = p->TrackNumber;
- tmp->bDiscontinuity = p->bDiscontinuity;
- tmp->bSyncPoint = p->bSyncPoint;
- tmp->rtStart = rtStart;
- tmp->rtStop = rtStop;
- tmp->Copy(*p->bg->Block.BlockData.GetNext(pos));
- if(S_OK != (hr = DeliverPacket(tmp))) break;
-
- rtStart += rtDelta;
- rtStop += rtDelta;
-
- p->bSyncPoint = false;
- p->bDiscontinuity = false;
- }
-
- if(m_mt.subtype == FOURCCMap(WAVE_FORMAT_WAVPACK4))
- {
- POSITION pos = p->bg->ba.bm.GetHeadPosition();
- while(pos)
- {
- const BlockMore* bm = p->bg->ba.bm.GetNext(pos);
- CAutoPtr<Packet> tmp(DNew Packet());
- tmp->TrackNumber = p->TrackNumber;
- tmp->bDiscontinuity = false;
- tmp->bSyncPoint = false;
- tmp->rtStart = p->rtStart;
- tmp->rtStop = p->rtStop;
- tmp->Copy(bm->BlockAdditional);
- if(S_OK != (hr = DeliverPacket(tmp))) break;
- }
- }
-
- return hr;
+ TRACE(_T("(track=%d) %I64d, %I64d -> %I64d, %I64d (buffcnt=%d)\n"),
+ p->TrackNumber, p->rtStart, p->rtStop, to.rtStart, to.rtStop,
+ QueueCount());
+/**/
+ p->rtStart = to.rtStart;
+ p->rtStop = to.rtStop;
+ }
+
+ REFERENCE_TIME
+ rtStart = p->rtStart,
+ rtDelta = (p->rtStop - p->rtStart) / p->bg->Block.BlockData.GetCount(),
+ rtStop = p->rtStart + rtDelta;
+
+ POSITION pos = p->bg->Block.BlockData.GetHeadPosition();
+ while(pos)
+ {
+ CAutoPtr<Packet> tmp(DNew Packet());
+ tmp->TrackNumber = p->TrackNumber;
+ tmp->bDiscontinuity = p->bDiscontinuity;
+ tmp->bSyncPoint = p->bSyncPoint;
+ tmp->rtStart = rtStart;
+ tmp->rtStop = rtStop;
+ tmp->Copy(*p->bg->Block.BlockData.GetNext(pos));
+ if(S_OK != (hr = DeliverPacket(tmp))) break;
+
+ rtStart += rtDelta;
+ rtStop += rtDelta;
+
+ p->bSyncPoint = false;
+ p->bDiscontinuity = false;
+ }
+
+ if(m_mt.subtype == FOURCCMap(WAVE_FORMAT_WAVPACK4))
+ {
+ POSITION pos = p->bg->ba.bm.GetHeadPosition();
+ while(pos)
+ {
+ const BlockMore* bm = p->bg->ba.bm.GetNext(pos);
+ CAutoPtr<Packet> tmp(DNew Packet());
+ tmp->TrackNumber = p->TrackNumber;
+ tmp->bDiscontinuity = false;
+ tmp->bSyncPoint = false;
+ tmp->rtStart = p->rtStart;
+ tmp->rtStop = p->rtStop;
+ tmp->Copy(bm->BlockAdditional);
+ if(S_OK != (hr = DeliverPacket(tmp))) break;
+ }
+ }
+
+ return hr;
}
// ITrackInfo
TrackEntry* CMatroskaSplitterFilter::GetTrackEntryAt(UINT aTrackIdx)
{
- if(aTrackIdx < 0 || aTrackIdx >= m_pOrderedTrackArray.GetCount())
- return NULL;
- return m_pOrderedTrackArray[aTrackIdx];
+ if(aTrackIdx < 0 || aTrackIdx >= m_pOrderedTrackArray.GetCount())
+ return NULL;
+ return m_pOrderedTrackArray[aTrackIdx];
}
STDMETHODIMP_(UINT) CMatroskaSplitterFilter::GetTrackCount()
-{
- return m_pTrackEntryMap.GetCount();
+{
+ return m_pTrackEntryMap.GetCount();
}
STDMETHODIMP_(BOOL) CMatroskaSplitterFilter::GetTrackInfo(UINT aTrackIdx, struct TrackElement* pStructureToFill)
{
- TrackEntry* pTE = GetTrackEntryAt(aTrackIdx);
- if(pTE == NULL)
- return FALSE;
-
- pStructureToFill->FlagDefault = !!pTE->FlagDefault;
- pStructureToFill->FlagLacing = !!pTE->FlagLacing;
- strncpy(pStructureToFill->Language, pTE->Language, 3);
- if(pStructureToFill->Language[0] == '\0')
- strncpy(pStructureToFill->Language, "eng", 3);
- pStructureToFill->Language[3] = '\0';
- pStructureToFill->MaxCache = (UINT)pTE->MaxCache;
- pStructureToFill->MinCache = (UINT)pTE->MinCache;
- pStructureToFill->Type = (BYTE)pTE->TrackType;
- return TRUE;
+ TrackEntry* pTE = GetTrackEntryAt(aTrackIdx);
+ if(pTE == NULL)
+ return FALSE;
+
+ pStructureToFill->FlagDefault = !!pTE->FlagDefault;
+ pStructureToFill->FlagLacing = !!pTE->FlagLacing;
+ strncpy(pStructureToFill->Language, pTE->Language, 3);
+ if(pStructureToFill->Language[0] == '\0')
+ strncpy(pStructureToFill->Language, "eng", 3);
+ pStructureToFill->Language[3] = '\0';
+ pStructureToFill->MaxCache = (UINT)pTE->MaxCache;
+ pStructureToFill->MinCache = (UINT)pTE->MinCache;
+ pStructureToFill->Type = (BYTE)pTE->TrackType;
+ return TRUE;
}
STDMETHODIMP_(BOOL) CMatroskaSplitterFilter::GetTrackExtendedInfo(UINT aTrackIdx, void* pStructureToFill)
{
- TrackEntry* pTE = GetTrackEntryAt(aTrackIdx);
- if(pTE == NULL)
- return FALSE;
-
- if(pTE->TrackType == TrackEntry::TypeVideo)
- {
- TrackExtendedInfoVideo* pTEIV = (TrackExtendedInfoVideo*)pStructureToFill;
- pTEIV->AspectRatioType = (BYTE)pTE->v.AspectRatioType;
- pTEIV->DisplayUnit = (BYTE)pTE->v.DisplayUnit;
- pTEIV->DisplayWidth = (UINT)pTE->v.DisplayWidth;
- pTEIV->DisplayHeight = (UINT)pTE->v.DisplayHeight;
- pTEIV->Interlaced = !!pTE->v.FlagInterlaced;
- pTEIV->PixelWidth = (UINT)pTE->v.PixelWidth;
- pTEIV->PixelHeight = (UINT)pTE->v.PixelHeight;
- }
- else if(pTE->TrackType == TrackEntry::TypeAudio)
- {
- TrackExtendedInfoAudio* pTEIA = (TrackExtendedInfoAudio*)pStructureToFill;
- pTEIA->BitDepth = (UINT)pTE->a.BitDepth;
- pTEIA->Channels = (UINT)pTE->a.Channels;
- pTEIA->OutputSamplingFrequency = pTE->a.OutputSamplingFrequency;
- pTEIA->SamplingFreq = pTE->a.SamplingFrequency;
- }
- else
- {
- return FALSE;
- }
-
- return TRUE;
+ TrackEntry* pTE = GetTrackEntryAt(aTrackIdx);
+ if(pTE == NULL)
+ return FALSE;
+
+ if(pTE->TrackType == TrackEntry::TypeVideo)
+ {
+ TrackExtendedInfoVideo* pTEIV = (TrackExtendedInfoVideo*)pStructureToFill;
+ pTEIV->AspectRatioType = (BYTE)pTE->v.AspectRatioType;
+ pTEIV->DisplayUnit = (BYTE)pTE->v.DisplayUnit;
+ pTEIV->DisplayWidth = (UINT)pTE->v.DisplayWidth;
+ pTEIV->DisplayHeight = (UINT)pTE->v.DisplayHeight;
+ pTEIV->Interlaced = !!pTE->v.FlagInterlaced;
+ pTEIV->PixelWidth = (UINT)pTE->v.PixelWidth;
+ pTEIV->PixelHeight = (UINT)pTE->v.PixelHeight;
+ } else if(pTE->TrackType == TrackEntry::TypeAudio) {
+ TrackExtendedInfoAudio* pTEIA = (TrackExtendedInfoAudio*)pStructureToFill;
+ pTEIA->BitDepth = (UINT)pTE->a.BitDepth;
+ pTEIA->Channels = (UINT)pTE->a.Channels;
+ pTEIA->OutputSamplingFrequency = pTE->a.OutputSamplingFrequency;
+ pTEIA->SamplingFreq = pTE->a.SamplingFrequency;
+ } else {
+ return FALSE;
+ }
+
+ return TRUE;
}
STDMETHODIMP_(BSTR) CMatroskaSplitterFilter::GetTrackName(UINT aTrackIdx)
{
- TrackEntry* pTE = GetTrackEntryAt(aTrackIdx);
- if(pTE == NULL)
- return NULL;
- return pTE->Name.AllocSysString();
+ TrackEntry* pTE = GetTrackEntryAt(aTrackIdx);
+ if(pTE == NULL)
+ return NULL;
+ return pTE->Name.AllocSysString();
}
STDMETHODIMP_(BSTR) CMatroskaSplitterFilter::GetTrackCodecID(UINT aTrackIdx)
{
- TrackEntry* pTE = GetTrackEntryAt(aTrackIdx);
- if(pTE == NULL)
- return NULL;
- return pTE->CodecID.ToString().AllocSysString();
+ TrackEntry* pTE = GetTrackEntryAt(aTrackIdx);
+ if(pTE == NULL)
+ return NULL;
+ return pTE->CodecID.ToString().AllocSysString();
}
STDMETHODIMP_(BSTR) CMatroskaSplitterFilter::GetTrackCodecName(UINT aTrackIdx)
{
- TrackEntry* pTE = GetTrackEntryAt(aTrackIdx);
- if(pTE == NULL)
- return NULL;
- return pTE->CodecName.AllocSysString();
+ TrackEntry* pTE = GetTrackEntryAt(aTrackIdx);
+ if(pTE == NULL)
+ return NULL;
+ return pTE->CodecName.AllocSysString();
}
STDMETHODIMP_(BSTR) CMatroskaSplitterFilter::GetTrackCodecInfoURL(UINT aTrackIdx)
{
- TrackEntry* pTE = GetTrackEntryAt(aTrackIdx);
- if(pTE == NULL)
- return NULL;
- return pTE->CodecInfoURL.AllocSysString();
+ TrackEntry* pTE = GetTrackEntryAt(aTrackIdx);
+ if(pTE == NULL)
+ return NULL;
+ return pTE->CodecInfoURL.AllocSysString();
}
STDMETHODIMP_(BSTR) CMatroskaSplitterFilter::GetTrackCodecDownloadURL(UINT aTrackIdx)
{
- TrackEntry* pTE = GetTrackEntryAt(aTrackIdx);
- if(pTE == NULL)
- return NULL;
- return pTE->CodecDownloadURL.AllocSysString();
+ TrackEntry* pTE = GetTrackEntryAt(aTrackIdx);
+ if(pTE == NULL)
+ return NULL;
+ return pTE->CodecDownloadURL.AllocSysString();
}
diff --git a/src/filters/parser/MatroskaSplitter/MatroskaSplitter.h b/src/filters/parser/MatroskaSplitter/MatroskaSplitter.h
index 5c9d44a58..05eb7d814 100644
--- a/src/filters/parser/MatroskaSplitter/MatroskaSplitter.h
+++ b/src/filters/parser/MatroskaSplitter/MatroskaSplitter.h
@@ -1,4 +1,4 @@
-/*
+/*
* Copyright (C) 2003-2006 Gabest
* http://www.gabest.org
*
@@ -6,15 +6,15 @@
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2, or (at your option)
* any later version.
- *
+ *
* This Program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with GNU Make; see the file COPYING. If not, write to
- * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
+ * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
* http://www.gnu.org/copyleft/gpl.html
*
*/
@@ -30,98 +30,92 @@
class MatroskaPacket : public Packet
{
protected:
- int GetDataSize()
- {
- int size = 0;
- POSITION pos = bg->Block.BlockData.GetHeadPosition();
- while(pos)
- {
- size += bg->Block.BlockData.GetNext(pos)->GetCount();
- }
- return size;
- }
+ int GetDataSize()
+ {
+ int size = 0;
+ POSITION pos = bg->Block.BlockData.GetHeadPosition();
+ while(pos) {size += bg->Block.BlockData.GetNext(pos)->GetCount();}
+ return size;
+ }
public:
- CAutoPtr<MatroskaReader::BlockGroup> bg;
+ CAutoPtr<MatroskaReader::BlockGroup> bg;
};
class CMatroskaSplitterOutputPin : public CBaseSplitterOutputPin
{
- HRESULT DeliverBlock(MatroskaPacket* p);
+ HRESULT DeliverBlock(MatroskaPacket* p);
- int m_nMinCache;
- REFERENCE_TIME m_rtDefaultDuration;
+ int m_nMinCache;
+ REFERENCE_TIME m_rtDefaultDuration;
- CCritSec m_csQueue;
- CAutoPtrList<MatroskaPacket> m_packets;
- CAtlList<MatroskaPacket*> m_rob;
+ CCritSec m_csQueue;
+ CAutoPtrList<MatroskaPacket> m_packets;
+ CAtlList<MatroskaPacket*> m_rob;
- typedef struct
- {
- REFERENCE_TIME rtStart, rtStop;
- } timeoverride;
- CAtlList<timeoverride> m_tos;
+ typedef struct {REFERENCE_TIME rtStart, rtStop;} timeoverride;
+ CAtlList<timeoverride> m_tos;
protected:
- HRESULT DeliverPacket(CAutoPtr<Packet> p);
+ HRESULT DeliverPacket(CAutoPtr<Packet> p);
public:
- CMatroskaSplitterOutputPin(
- int nMinCache, REFERENCE_TIME rtDefaultDuration,
- CAtlArray<CMediaType>& mts, LPCWSTR pName, CBaseFilter* pFilter, CCritSec* pLock, HRESULT* phr);
- virtual ~CMatroskaSplitterOutputPin();
+ CMatroskaSplitterOutputPin(
+ int nMinCache, REFERENCE_TIME rtDefaultDuration,
+ CAtlArray<CMediaType>& mts, LPCWSTR pName, CBaseFilter* pFilter, CCritSec* pLock, HRESULT* phr);
+ virtual ~CMatroskaSplitterOutputPin();
- HRESULT DeliverEndFlush();
- HRESULT DeliverEndOfStream();
+ HRESULT DeliverEndFlush();
+ HRESULT DeliverEndOfStream();
};
[uuid("149D2E01-C32E-4939-80F6-C07B81015A7A")]
class CMatroskaSplitterFilter : public CBaseSplitterFilter, public ITrackInfo
{
- void SetupChapters(LPCSTR lng, MatroskaReader::ChapterAtom* parent, int level = 0);
- void InstallFonts();
- void SendVorbisHeaderSample();
+ void SetupChapters(LPCSTR lng, MatroskaReader::ChapterAtom* parent, int level = 0);
+ void InstallFonts();
+ void SendVorbisHeaderSample();
- CAutoPtr<MatroskaReader::CMatroskaNode> m_pSegment, m_pCluster, m_pBlock;
+ CAutoPtr<MatroskaReader::CMatroskaNode> m_pSegment, m_pCluster, m_pBlock;
protected:
- CAutoPtr<MatroskaReader::CMatroskaFile> m_pFile;
- HRESULT CreateOutputs(IAsyncReader* pAsyncReader);
+ CAutoPtr<MatroskaReader::CMatroskaFile> m_pFile;
+ HRESULT CreateOutputs(IAsyncReader* pAsyncReader);
- CAtlMap<DWORD, MatroskaReader::TrackEntry*> m_pTrackEntryMap;
- CAtlArray<MatroskaReader::TrackEntry* > m_pOrderedTrackArray;
- MatroskaReader::TrackEntry* GetTrackEntryAt(UINT aTrackIdx);
+ CAtlMap<DWORD, MatroskaReader::TrackEntry*> m_pTrackEntryMap;
+ CAtlArray<MatroskaReader::TrackEntry* > m_pOrderedTrackArray;
+ MatroskaReader::TrackEntry* GetTrackEntryAt(UINT aTrackIdx);
- bool DemuxInit();
- void DemuxSeek(REFERENCE_TIME rt);
- bool DemuxLoop();
+ bool DemuxInit();
+ void DemuxSeek(REFERENCE_TIME rt);
+ bool DemuxLoop();
public:
- CMatroskaSplitterFilter(LPUNKNOWN pUnk, HRESULT* phr);
- virtual ~CMatroskaSplitterFilter();
+ CMatroskaSplitterFilter(LPUNKNOWN pUnk, HRESULT* phr);
+ virtual ~CMatroskaSplitterFilter();
- DECLARE_IUNKNOWN;
+ DECLARE_IUNKNOWN;
STDMETHODIMP NonDelegatingQueryInterface(REFIID riid, void** ppv);
- // IKeyFrameInfo
+ // IKeyFrameInfo
- STDMETHODIMP GetKeyFrameCount(UINT& nKFs);
- STDMETHODIMP GetKeyFrames(const GUID* pFormat, REFERENCE_TIME* pKFs, UINT& nKFs);
+ STDMETHODIMP GetKeyFrameCount(UINT& nKFs);
+ STDMETHODIMP GetKeyFrames(const GUID* pFormat, REFERENCE_TIME* pKFs, UINT& nKFs);
- // ITrackInfo
+ // ITrackInfo
- STDMETHODIMP_(UINT) GetTrackCount();
- STDMETHODIMP_(BOOL) GetTrackInfo(UINT aTrackIdx, struct TrackElement* pStructureToFill);
- STDMETHODIMP_(BOOL) GetTrackExtendedInfo(UINT aTrackIdx, void* pStructureToFill);
- STDMETHODIMP_(BSTR) GetTrackName(UINT aTrackIdx);
- STDMETHODIMP_(BSTR) GetTrackCodecID(UINT aTrackIdx);
- STDMETHODIMP_(BSTR) GetTrackCodecName(UINT aTrackIdx);
- STDMETHODIMP_(BSTR) GetTrackCodecInfoURL(UINT aTrackIdx);
- STDMETHODIMP_(BSTR) GetTrackCodecDownloadURL(UINT aTrackIdx);
+ STDMETHODIMP_(UINT) GetTrackCount();
+ STDMETHODIMP_(BOOL) GetTrackInfo(UINT aTrackIdx, struct TrackElement* pStructureToFill);
+ STDMETHODIMP_(BOOL) GetTrackExtendedInfo(UINT aTrackIdx, void* pStructureToFill);
+ STDMETHODIMP_(BSTR) GetTrackName(UINT aTrackIdx);
+ STDMETHODIMP_(BSTR) GetTrackCodecID(UINT aTrackIdx);
+ STDMETHODIMP_(BSTR) GetTrackCodecName(UINT aTrackIdx);
+ STDMETHODIMP_(BSTR) GetTrackCodecInfoURL(UINT aTrackIdx);
+ STDMETHODIMP_(BSTR) GetTrackCodecDownloadURL(UINT aTrackIdx);
};
[uuid("0A68C3B5-9164-4a54-AFAF-995B2FF0E0D4")]
class CMatroskaSourceFilter : public CMatroskaSplitterFilter
{
public:
- CMatroskaSourceFilter(LPUNKNOWN pUnk, HRESULT* phr);
+ CMatroskaSourceFilter(LPUNKNOWN pUnk, HRESULT* phr);
};
diff --git a/src/filters/parser/MatroskaSplitter/resource.h b/src/filters/parser/MatroskaSplitter/resource.h
index dc322a964..1cd7111d9 100644
--- a/src/filters/parser/MatroskaSplitter/resource.h
+++ b/src/filters/parser/MatroskaSplitter/resource.h
@@ -3,7 +3,7 @@
// Used by MatroskaSplitter.rc
// Next default values for new objects
-//
+//
#ifdef APSTUDIO_INVOKED
#ifndef APSTUDIO_READONLY_SYMBOLS
#define _APS_NEXT_RESOURCE_VALUE 101
diff --git a/src/filters/parser/MatroskaSplitter/stdafx.cpp b/src/filters/parser/MatroskaSplitter/stdafx.cpp
index 0378caf4c..c3b346d99 100644
--- a/src/filters/parser/MatroskaSplitter/stdafx.cpp
+++ b/src/filters/parser/MatroskaSplitter/stdafx.cpp
@@ -1,4 +1,4 @@
-/*
+/*
* Copyright (C) 2003-2006 Gabest
* http://www.gabest.org
*
@@ -6,15 +6,15 @@
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2, or (at your option)
* any later version.
- *
+ *
* This Program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with GNU Make; see the file COPYING. If not, write to
- * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
+ * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
* http://www.gnu.org/copyleft/gpl.html
*
*/
diff --git a/src/filters/parser/MatroskaSplitter/stdafx.h b/src/filters/parser/MatroskaSplitter/stdafx.h
index ec6ed9d77..5f53f59b5 100644
--- a/src/filters/parser/MatroskaSplitter/stdafx.h
+++ b/src/filters/parser/MatroskaSplitter/stdafx.h
@@ -1,4 +1,4 @@
-/*
+/*
* Copyright (C) 2003-2006 Gabest
* http://www.gabest.org
*
@@ -6,15 +6,15 @@
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2, or (at your option)
* any later version.
- *
+ *
* This Program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with GNU Make; see the file COPYING. If not, write to
- * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
+ * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
* http://www.gnu.org/copyleft/gpl.html
*
*/
diff --git a/src/filters/parser/MpaSplitter/MpaSplitter.cpp b/src/filters/parser/MpaSplitter/MpaSplitter.cpp
index 19321de65..bf0e20e91 100644
--- a/src/filters/parser/MpaSplitter/MpaSplitter.cpp
+++ b/src/filters/parser/MpaSplitter/MpaSplitter.cpp
@@ -1,4 +1,4 @@
-/*
+/*
* Copyright (C) 2003-2006 Gabest
* http://www.gabest.org
*
@@ -6,15 +6,15 @@
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2, or (at your option)
* any later version.
- *
+ *
* This Program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with GNU Make; see the file COPYING. If not, write to
- * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
+ * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
* http://www.gnu.org/copyleft/gpl.html
*
*/
@@ -28,44 +28,44 @@
#ifdef REGISTER_FILTER
const AMOVIESETUP_MEDIATYPE sudPinTypesIn[] =
-{
- {&MEDIATYPE_Stream, &MEDIASUBTYPE_MPEG1Audio},
- {&MEDIATYPE_Stream, &MEDIASUBTYPE_NULL}
+{
+ {&MEDIATYPE_Stream, &MEDIASUBTYPE_MPEG1Audio},
+ {&MEDIATYPE_Stream, &MEDIASUBTYPE_NULL}
};
const AMOVIESETUP_PIN sudpPins[] =
{
- {L"Input", FALSE, FALSE, FALSE, FALSE, &CLSID_NULL, NULL, countof(sudPinTypesIn), sudPinTypesIn},
- {L"Output", FALSE, TRUE, FALSE, FALSE, &CLSID_NULL, NULL, 0, NULL}
+ {L"Input", FALSE, FALSE, FALSE, FALSE, &CLSID_NULL, NULL, countof(sudPinTypesIn), sudPinTypesIn},
+ {L"Output", FALSE, TRUE, FALSE, FALSE, &CLSID_NULL, NULL, 0, NULL}
};
const AMOVIESETUP_FILTER sudFilter[] =
{
- {&__uuidof(CMpaSplitterFilter), L"MPC - Mpa Splitter", MERIT_NORMAL + 1, countof(sudpPins), sudpPins, CLSID_LegacyAmFilterCategory},
- {&__uuidof(CMpaSourceFilter), L"MPC - Mpa Source", MERIT_NORMAL + 1, 0, NULL, CLSID_LegacyAmFilterCategory},
+ {&__uuidof(CMpaSplitterFilter), L"MPC - Mpa Splitter", MERIT_NORMAL+1, countof(sudpPins), sudpPins, CLSID_LegacyAmFilterCategory},
+ {&__uuidof(CMpaSourceFilter), L"MPC - Mpa Source", MERIT_NORMAL+1, 0, NULL, CLSID_LegacyAmFilterCategory},
};
CFactoryTemplate g_Templates[] =
{
- {sudFilter[0].strName, sudFilter[0].clsID, CreateInstance<CMpaSplitterFilter>, NULL, &sudFilter[0]},
- {sudFilter[1].strName, sudFilter[1].clsID, CreateInstance<CMpaSourceFilter>, NULL, &sudFilter[1]},
+ {sudFilter[0].strName, sudFilter[0].clsID, CreateInstance<CMpaSplitterFilter>, NULL, &sudFilter[0]},
+ {sudFilter[1].strName, sudFilter[1].clsID, CreateInstance<CMpaSourceFilter>, NULL, &sudFilter[1]},
};
int g_cTemplates = countof(g_Templates);
STDAPI DllRegisterServer()
{
- CAtlList<CString> chkbytes;
- chkbytes.AddTail(_T("0,2,FFE0,FFE0"));
- chkbytes.AddTail(_T("0,10,FFFFFF00000080808080,49443300000000000000"));
- RegisterSourceFilter(CLSID_AsyncReader, MEDIASUBTYPE_MPEG1Audio, chkbytes, NULL);
+ CAtlList<CString> chkbytes;
+ chkbytes.AddTail(_T("0,2,FFE0,FFE0"));
+ chkbytes.AddTail(_T("0,10,FFFFFF00000080808080,49443300000000000000"));
+ RegisterSourceFilter(CLSID_AsyncReader, MEDIASUBTYPE_MPEG1Audio, chkbytes, NULL);
- return AMovieDllRegisterServer2(TRUE);
+ return AMovieDllRegisterServer2(TRUE);
}
STDAPI DllUnregisterServer()
{
- return AMovieDllRegisterServer2(FALSE);
+ return AMovieDllRegisterServer2(FALSE);
}
#include "../../FilterApp.h"
@@ -79,7 +79,7 @@ CFilterApp theApp;
//
CMpaSplitterFilter::CMpaSplitterFilter(LPUNKNOWN pUnk, HRESULT* phr)
- : CBaseSplitterFilter(NAME("CMpaSplitterFilter"), pUnk, phr, __uuidof(this))
+ : CBaseSplitterFilter(NAME("CMpaSplitterFilter"), pUnk, phr, __uuidof(this))
{
}
@@ -87,113 +87,105 @@ STDMETHODIMP CMpaSplitterFilter::NonDelegatingQueryInterface(REFIID riid, void**
{
CheckPointer(ppv, E_POINTER);
- return
- __super::NonDelegatingQueryInterface(riid, ppv);
+ return
+ __super::NonDelegatingQueryInterface(riid, ppv);
}
HRESULT CMpaSplitterFilter::CreateOutputs(IAsyncReader* pAsyncReader)
{
- CheckPointer(pAsyncReader, E_POINTER);
+ CheckPointer(pAsyncReader, E_POINTER);
- HRESULT hr = E_FAIL;
+ HRESULT hr = E_FAIL;
- m_pFile.Free();
+ m_pFile.Free();
- m_pFile.Attach(DNew CMpaSplitterFile(pAsyncReader, hr));
- if(!m_pFile) return E_OUTOFMEMORY;
- if(FAILED(hr))
- {
- m_pFile.Free();
- return hr;
- }
+ m_pFile.Attach(DNew CMpaSplitterFile(pAsyncReader, hr));
+ if(!m_pFile) return E_OUTOFMEMORY;
+ if(FAILED(hr)) {m_pFile.Free(); return hr;}
- CAtlArray<CMediaType> mts;
- mts.Add(m_pFile->GetMediaType());
+ CAtlArray<CMediaType> mts;
+ mts.Add(m_pFile->GetMediaType());
- CAutoPtr<CBaseSplitterOutputPin> pPinOut(DNew CBaseSplitterOutputPin(mts, L"Audio", this, this, &hr));
- AddOutputPin(0, pPinOut);
+ CAutoPtr<CBaseSplitterOutputPin> pPinOut(DNew CBaseSplitterOutputPin(mts, L"Audio", this, this, &hr));
+ AddOutputPin(0, pPinOut);
- m_rtNewStart = m_rtCurrent = 0;
- m_rtNewStop = m_rtStop = m_rtDuration = m_pFile->GetDuration();
+ m_rtNewStart = m_rtCurrent = 0;
+ m_rtNewStop = m_rtStop = m_rtDuration = m_pFile->GetDuration();
- CStringW str, title;
- if(m_pFile->m_tags.Lookup('TIT2', str)) title = str;
- if(m_pFile->m_tags.Lookup('TYER', str) && !title.IsEmpty() && !str.IsEmpty()) title += L" (" + str + L")";
- if(!title.IsEmpty()) SetProperty(L"TITL", title);
- if(m_pFile->m_tags.Lookup('TPE1', str)) SetProperty(L"AUTH", str);
- if(m_pFile->m_tags.Lookup('TCOP', str)) SetProperty(L"CPYR", str);
- if(m_pFile->m_tags.Lookup('COMM', str)) SetProperty(L"DESC", str);
+ CStringW str, title;
+ if(m_pFile->m_tags.Lookup('TIT2', str)) title = str;
+ if(m_pFile->m_tags.Lookup('TYER', str) && !title.IsEmpty() && !str.IsEmpty()) title += L" (" + str + L")";
+ if(!title.IsEmpty()) SetProperty(L"TITL", title);
+ if(m_pFile->m_tags.Lookup('TPE1', str)) SetProperty(L"AUTH", str);
+ if(m_pFile->m_tags.Lookup('TCOP', str)) SetProperty(L"CPYR", str);
+ if(m_pFile->m_tags.Lookup('COMM', str)) SetProperty(L"DESC", str);
- return m_pOutputs.GetCount() > 0 ? S_OK : E_FAIL;
+ return m_pOutputs.GetCount() > 0 ? S_OK : E_FAIL;
}
STDMETHODIMP CMpaSplitterFilter::GetDuration(LONGLONG* pDuration)
{
- CheckPointer(pDuration, E_POINTER);
- CheckPointer(m_pFile, VFW_E_NOT_CONNECTED);
+ CheckPointer(pDuration, E_POINTER);
+ CheckPointer(m_pFile, VFW_E_NOT_CONNECTED);
- *pDuration = m_pFile->GetDuration();
+ *pDuration = m_pFile->GetDuration();
- return S_OK;
+ return S_OK;
}
bool CMpaSplitterFilter::DemuxInit()
{
- if(!m_pFile) return(false);
+ if(!m_pFile) return(false);
- // TODO
+ // TODO
- return(true);
+ return(true);
}
void CMpaSplitterFilter::DemuxSeek(REFERENCE_TIME rt)
{
- __int64 startpos = m_pFile->GetStartPos();
- __int64 endpos = m_pFile->GetEndPos();
-
- if(rt <= 0 || m_pFile->GetDuration() <= 0)
- {
- m_pFile->Seek(startpos);
- m_rtStart = 0;
- }
- else
- {
- m_pFile->Seek(startpos + (__int64)((1.0 * rt / m_pFile->GetDuration()) *(endpos - startpos)));
- m_rtStart = rt;
- }
+ __int64 startpos = m_pFile->GetStartPos();
+ __int64 endpos = m_pFile->GetEndPos();
+
+ if(rt <= 0 || m_pFile->GetDuration() <= 0)
+ {
+ m_pFile->Seek(startpos);
+ m_rtStart = 0;
+ }
+ else
+ {
+ m_pFile->Seek(startpos + (__int64)((1.0 * rt / m_pFile->GetDuration()) * (endpos - startpos)));
+ m_rtStart = rt;
+ }
}
bool CMpaSplitterFilter::DemuxLoop()
{
- HRESULT hr = S_OK;
+ HRESULT hr = S_OK;
- int FrameSize;
- REFERENCE_TIME rtDuration;
+ int FrameSize;
+ REFERENCE_TIME rtDuration;
- while(SUCCEEDED(hr) && !CheckRequest(NULL) && m_pFile->GetPos() < m_pFile->GetEndPos() - 9)
- {
- if(!m_pFile->Sync(FrameSize, rtDuration))
- {
- Sleep(1);
- continue;
- }
+ while(SUCCEEDED(hr) && !CheckRequest(NULL) && m_pFile->GetPos() < m_pFile->GetEndPos() - 9)
+ {
+ if(!m_pFile->Sync(FrameSize, rtDuration)) {Sleep(1); continue;}
- CAutoPtr<Packet> p(DNew Packet());
- p->SetCount(FrameSize);
- m_pFile->ByteRead(p->GetData(), FrameSize);
+ CAutoPtr<Packet> p(DNew Packet());
+ p->SetCount(FrameSize);
+ m_pFile->ByteRead(p->GetData(), FrameSize);
- p->TrackNumber = 0;
- p->rtStart = m_rtStart;
- p->rtStop = m_rtStart + rtDuration;
- p->bSyncPoint = TRUE;
+ p->TrackNumber = 0;
+ p->rtStart = m_rtStart;
+ p->rtStop = m_rtStart + rtDuration;
+ p->bSyncPoint = TRUE;
- hr = DeliverPacket(p);
+ hr = DeliverPacket(p);
- m_rtStart += rtDuration;
- }
+ m_rtStart += rtDuration;
+ }
- return(true);
+ return(true);
}
//
@@ -201,8 +193,8 @@ bool CMpaSplitterFilter::DemuxLoop()
//
CMpaSourceFilter::CMpaSourceFilter(LPUNKNOWN pUnk, HRESULT* phr)
- : CMpaSplitterFilter(pUnk, phr)
+ : CMpaSplitterFilter(pUnk, phr)
{
- m_clsid = __uuidof(this);
- m_pInput.Free();
+ m_clsid = __uuidof(this);
+ m_pInput.Free();
}
diff --git a/src/filters/parser/MpaSplitter/MpaSplitter.h b/src/filters/parser/MpaSplitter/MpaSplitter.h
index f3658dcdd..c2ce4c934 100644
--- a/src/filters/parser/MpaSplitter/MpaSplitter.h
+++ b/src/filters/parser/MpaSplitter/MpaSplitter.h
@@ -1,4 +1,4 @@
-/*
+/*
* Copyright (C) 2003-2006 Gabest
* http://www.gabest.org
*
@@ -6,15 +6,15 @@
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2, or (at your option)
* any later version.
- *
+ *
* This Program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with GNU Make; see the file COPYING. If not, write to
- * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
+ * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
* http://www.gnu.org/copyleft/gpl.html
*
*/
@@ -27,22 +27,22 @@
[uuid("0E9D4BF7-CBCB-46C7-BD80-4EF223A3DC2B")]
class CMpaSplitterFilter : public CBaseSplitterFilter
{
- REFERENCE_TIME m_rtStart;
+ REFERENCE_TIME m_rtStart;
protected:
- CAutoPtr<CMpaSplitterFile> m_pFile;
- HRESULT CreateOutputs(IAsyncReader* pAsyncReader);
+ CAutoPtr<CMpaSplitterFile> m_pFile;
+ HRESULT CreateOutputs(IAsyncReader* pAsyncReader);
- STDMETHODIMP GetDuration(LONGLONG* pDuration);
+ STDMETHODIMP GetDuration(LONGLONG* pDuration);
- bool DemuxInit();
- void DemuxSeek(REFERENCE_TIME rt);
- bool DemuxLoop();
+ bool DemuxInit();
+ void DemuxSeek(REFERENCE_TIME rt);
+ bool DemuxLoop();
public:
- CMpaSplitterFilter(LPUNKNOWN pUnk, HRESULT* phr);
+ CMpaSplitterFilter(LPUNKNOWN pUnk, HRESULT* phr);
- DECLARE_IUNKNOWN
+ DECLARE_IUNKNOWN
STDMETHODIMP NonDelegatingQueryInterface(REFIID riid, void** ppv);
};
@@ -50,5 +50,5 @@ public:
class CMpaSourceFilter : public CMpaSplitterFilter
{
public:
- CMpaSourceFilter(LPUNKNOWN pUnk, HRESULT* phr);
+ CMpaSourceFilter(LPUNKNOWN pUnk, HRESULT* phr);
}; \ No newline at end of file
diff --git a/src/filters/parser/MpaSplitter/MpaSplitterFile.cpp b/src/filters/parser/MpaSplitter/MpaSplitterFile.cpp
index 507fc5894..1590eee37 100644
--- a/src/filters/parser/MpaSplitter/MpaSplitterFile.cpp
+++ b/src/filters/parser/MpaSplitter/MpaSplitterFile.cpp
@@ -1,4 +1,4 @@
-/*
+/*
* Copyright (C) 2003-2006 Gabest
* http://www.gabest.org
*
@@ -6,15 +6,15 @@
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2, or (at your option)
* any later version.
- *
+ *
* This Program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with GNU Make; see the file COPYING. If not, write to
- * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
+ * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
* http://www.gnu.org/copyleft/gpl.html
*
*/
@@ -28,322 +28,322 @@
//
-static const LPCTSTR s_genre[] =
+static const LPCTSTR s_genre[] =
{
- _T("Blues"), _T("Classic Rock"), _T("Country"), _T("Dance"),
- _T("Disco"), _T("Funk"), _T("Grunge"), _T("Hip-Hop"),
- _T("Jazz"), _T("Metal"), _T("New Age"), _T("Oldies"),
- _T("Other"), _T("Pop"), _T("R&B"), _T("Rap"),
- _T("Reggae"), _T("Rock"), _T("Techno"), _T("Industrial"),
- _T("Alternative"), _T("Ska"), _T("Death Metal"), _T("Pranks"),
- _T("Soundtrack"), _T("Euro-Techno"), _T("Ambient"), _T("Trip-Hop"),
- _T("Vocal"), _T("Jazz+Funk"), _T("Fusion"), _T("Trance"),
- _T("Classical"), _T("Instrumental"), _T("Acid"), _T("House"),
- _T("Game"), _T("Sound Clip"), _T("Gospel"), _T("Noise"),
- _T("Alternative Rock"), _T("Bass"), _T("Soul"), _T("Punk"),
- _T("Space"), _T("Meditative"), _T("Instrumental Pop"), _T("Instrumental Rock"),
- _T("Ethnic"), _T("Gothic"), _T("Darkwave"), _T("Techno-Industrial"),
- _T("Electronic"), _T("Pop-Folk"), _T("Eurodance"), _T("Dream"),
- _T("Southern Rock"), _T("Comedy"), _T("Cult"), _T("Gangsta"),
- _T("Top 40"), _T("Christian Rap"), _T("Pop/Funk"), _T("Jungle"),
- _T("Native US"), _T("Cabaret"), _T("New Wave"), _T("Psychadelic"),
- _T("Rave"), _T("Showtunes"), _T("Trailer"), _T("Lo-Fi"),
- _T("Tribal"), _T("Acid Punk"), _T("Acid Jazz"), _T("Polka"),
- _T("Retro"), _T("Musical"), _T("Rock & Roll"), _T("Hard Rock"),
- _T("Folk"), _T("Folk-Rock"), _T("National Folk"), _T("Swing"),
- _T("Fast Fusion"), _T("Bebob"), _T("Latin"), _T("Revival"),
- _T("Celtic"), _T("Bluegrass"), _T("Avantgarde"), _T("Gothic Rock"),
- _T("Progressive Rock"), _T("Psychedelic Rock"), _T("Symphonic Rock"), _T("Slow Rock"),
- _T("Big Band"), _T("Chorus"), _T("Easy Listening"), _T("Acoustic"),
- _T("Humour"), _T("Speech"), _T("Chanson"), _T("Opera"),
- _T("Chamber Music"), _T("Sonata"), _T("Symphony"), _T("Booty Bass"),
- _T("Primus"), _T("Porn Groove"), _T("Satire"), _T("Slow Jam"),
- _T("Club"), _T("Tango"), _T("Samba"), _T("Folklore"),
- _T("Ballad"), _T("Power Ballad"), _T("Rhytmic Soul"), _T("Freestyle"),
- _T("Duet"), _T("Punk Rock"), _T("Drum Solo"), _T("Acapella"),
- _T("Euro-House"), _T("Dance Hall"), _T("Goa"), _T("Drum & Bass"),
- _T("Club-House"), _T("Hardcore"), _T("Terror"), _T("Indie"),
- _T("BritPop"), _T("Negerpunk"), _T("Polsk Punk"), _T("Beat"),
- _T("Christian Gangsta"), _T("Heavy Metal"), _T("Black Metal"),
- _T("Crossover"), _T("Contemporary C"), _T("Christian Rock"), _T("Merengue"), _T("Salsa"),
- _T("Thrash Metal"), _T("Anime"), _T("JPop"), _T("SynthPop"),
+ _T("Blues"), _T("Classic Rock"), _T("Country"), _T("Dance"),
+ _T("Disco"), _T("Funk"), _T("Grunge"), _T("Hip-Hop"),
+ _T("Jazz"), _T("Metal"), _T("New Age"), _T("Oldies"),
+ _T("Other"), _T("Pop"), _T("R&B"), _T("Rap"),
+ _T("Reggae"), _T("Rock"), _T("Techno"), _T("Industrial"),
+ _T("Alternative"), _T("Ska"), _T("Death Metal"), _T("Pranks"),
+ _T("Soundtrack"), _T("Euro-Techno"), _T("Ambient"), _T("Trip-Hop"),
+ _T("Vocal"), _T("Jazz+Funk"), _T("Fusion"), _T("Trance"),
+ _T("Classical"), _T("Instrumental"), _T("Acid"), _T("House"),
+ _T("Game"), _T("Sound Clip"), _T("Gospel"), _T("Noise"),
+ _T("Alternative Rock"), _T("Bass"), _T("Soul"), _T("Punk"),
+ _T("Space"), _T("Meditative"), _T("Instrumental Pop"), _T("Instrumental Rock"),
+ _T("Ethnic"), _T("Gothic"), _T("Darkwave"), _T("Techno-Industrial"),
+ _T("Electronic"), _T("Pop-Folk"), _T("Eurodance"), _T("Dream"),
+ _T("Southern Rock"), _T("Comedy"), _T("Cult"), _T("Gangsta"),
+ _T("Top 40"), _T("Christian Rap"), _T("Pop/Funk"), _T("Jungle"),
+ _T("Native US"), _T("Cabaret"), _T("New Wave"), _T("Psychadelic"),
+ _T("Rave"), _T("Showtunes"), _T("Trailer"), _T("Lo-Fi"),
+ _T("Tribal"), _T("Acid Punk"), _T("Acid Jazz"), _T("Polka"),
+ _T("Retro"), _T("Musical"), _T("Rock & Roll"), _T("Hard Rock"),
+ _T("Folk"), _T("Folk-Rock"), _T("National Folk"), _T("Swing"),
+ _T("Fast Fusion"), _T("Bebob"), _T("Latin"), _T("Revival"),
+ _T("Celtic"), _T("Bluegrass"), _T("Avantgarde"), _T("Gothic Rock"),
+ _T("Progressive Rock"), _T("Psychedelic Rock"), _T("Symphonic Rock"), _T("Slow Rock"),
+ _T("Big Band"), _T("Chorus"), _T("Easy Listening"), _T("Acoustic"),
+ _T("Humour"), _T("Speech"), _T("Chanson"), _T("Opera"),
+ _T("Chamber Music"), _T("Sonata"), _T("Symphony"), _T("Booty Bass"),
+ _T("Primus"), _T("Porn Groove"), _T("Satire"), _T("Slow Jam"),
+ _T("Club"), _T("Tango"), _T("Samba"), _T("Folklore"),
+ _T("Ballad"), _T("Power Ballad"), _T("Rhytmic Soul"), _T("Freestyle"),
+ _T("Duet"), _T("Punk Rock"), _T("Drum Solo"), _T("Acapella"),
+ _T("Euro-House"), _T("Dance Hall"), _T("Goa"), _T("Drum & Bass"),
+ _T("Club-House"), _T("Hardcore"), _T("Terror"), _T("Indie"),
+ _T("BritPop"), _T("Negerpunk"), _T("Polsk Punk"), _T("Beat"),
+ _T("Christian Gangsta"), _T("Heavy Metal"), _T("Black Metal"),
+ _T("Crossover"), _T("Contemporary C"), _T("Christian Rock"), _T("Merengue"), _T("Salsa"),
+ _T("Thrash Metal"), _T("Anime"), _T("JPop"), _T("SynthPop"),
};
//
CMpaSplitterFile::CMpaSplitterFile(IAsyncReader* pAsyncReader, HRESULT& hr)
- : CBaseSplitterFileEx(pAsyncReader, hr, DEFAULT_CACHE_LENGTH, false)
- , m_mode(none)
- , m_rtDuration(0)
- , m_startpos(0)
- , m_endpos(0)
- , m_totalbps(0)
+ : CBaseSplitterFileEx(pAsyncReader, hr, DEFAULT_CACHE_LENGTH, false)
+ , m_mode(none)
+ , m_rtDuration(0)
+ , m_startpos(0)
+ , m_endpos(0)
+ , m_totalbps(0)
{
- if(SUCCEEDED(hr)) hr = Init();
+ if(SUCCEEDED(hr)) hr = Init();
}
HRESULT CMpaSplitterFile::Init()
{
- m_startpos = 0;
- m_endpos = GetLength();
-
- Seek(0);
-
- if(BitRead(24, true) == 0x000001)
- return E_FAIL;
-
- if(m_endpos > 128 && IsRandomAccess())
- {
- Seek(m_endpos - 128);
-
- if(BitRead(24) == 'TAG')
- {
- m_endpos -= 128;
-
- CStringA str;
-
- // title
- ByteRead((BYTE*)str.GetBufferSetLength(30), 30);
- m_tags['TIT2'] = CStringW(str).Trim();
-
- // artist
- ByteRead((BYTE*)str.GetBufferSetLength(30), 30);
- m_tags['TPE1'] = CStringW(str).Trim();
-
- // album
- ByteRead((BYTE*)str.GetBufferSetLength(30), 30);
- m_tags['TALB'] = CStringW(str).Trim();
-
- // year
- ByteRead((BYTE*)str.GetBufferSetLength(4), 4);
- m_tags['TYER'] = CStringW(str).Trim();
-
- // comment
- ByteRead((BYTE*)str.GetBufferSetLength(30), 30);
- m_tags['COMM'] = CStringW(str).Trim();
-
- // track
- LPCSTR s = str;
- if(s[28] == 0 && s[29] != 0)
- m_tags['TRCK'].Format(L"%d", s[29]);
-
- // genre
- BYTE genre = (BYTE)BitRead(8);
- if(genre < countof(s_genre))
- m_tags['TCON'] = CStringW(s_genre[genre]);
- }
- }
-
- Seek(0);
-
- while(BitRead(24, true) == 'ID3')
- {
- BitRead(24);
-
- BYTE major = (BYTE)BitRead(8);
- BYTE revision = (BYTE)BitRead(8);
-
- BYTE flags = (BYTE)BitRead(8);
- DWORD size = 0;
- if(BitRead(1) != 0) return E_FAIL;
- size |= BitRead(7) << 21;
- if(BitRead(1) != 0) return E_FAIL;
- size |= BitRead(7) << 14;
- if(BitRead(1) != 0) return E_FAIL;
- size |= BitRead(7) << 7;
- if(BitRead(1) != 0) return E_FAIL;
- size |= BitRead(7);
-
- m_startpos = GetPos() + size;
-
- // TODO: read extended header
-
- if(major <= 4)
- {
- __int64 pos = GetPos();
-
- while(pos < m_startpos)
- {
- Seek(pos);
-
- DWORD tag = (DWORD)BitRead(32);
- DWORD size = 0;
- size |= BitRead(8) << 24;
- size |= BitRead(8) << 16;
- size |= BitRead(8) << 8;
- size |= BitRead(8);
- WORD flags = (WORD)BitRead(16);
-
- pos += 4 + 4 + 2 + size;
-
- if(!size || pos >= m_startpos)
- break;
-
- if(tag == 'TIT2'
- || tag == 'TPE1'
- || tag == 'TALB'
- || tag == 'TYER'
- || tag == 'COMM'
- || tag == 'TRCK')
- {
- BYTE encoding = (BYTE)BitRead(8);
- size--;
-
- WORD bom = (WORD)BitRead(16, true);
-
- CStringA str;
- CStringW wstr;
-
- if(encoding > 0 && size >= 2 && bom == 0xfffe)
- {
- BitRead(16);
- size = (size - 2) / 2;
- ByteRead((BYTE*)wstr.GetBufferSetLength(size), size * 2);
- m_tags[tag] = wstr.Trim();
- }
- else if(encoding > 0 && size >= 2 && bom == 0xfeff)
- {
- BitRead(16);
- size = (size - 2) / 2;
- ByteRead((BYTE*)wstr.GetBufferSetLength(size), size * 2);
- for(int i = 0, j = wstr.GetLength(); i < j; i++) wstr.SetAt(i, (wstr[i] << 8) | (wstr[i] >> 8));
- m_tags[tag] = wstr.Trim();
- }
- else
- {
- ByteRead((BYTE*)str.GetBufferSetLength(size), size);
- m_tags[tag] = (encoding > 0 ? UTF8To16(str) : CStringW(str)).Trim();
- }
- }
- }
- }
-
- Seek(m_startpos);
-
- for(int i = 0; i < (1 << 20) && m_startpos < m_endpos && BitRead(8, true) == 0; i++)
- BitRead(8), m_startpos++;
- }
-
- __int64 searchlen = min(m_endpos - m_startpos, m_startpos > 0 ? 0x200 : 7);
-
- __int64 startpos;
-
- Seek(m_startpos);
-
- if(m_mode == none && Read(m_mpahdr, searchlen, true, &m_mt))
- {
- m_mode = mpa;
-
- startpos = GetPos() - 4;
-
- // make sure the first frame is followed by another of the same kind (validates m_mpahdr basically)
- Seek(startpos + m_mpahdr.FrameSize);
- if(!Sync(4)) m_mode = none;
- }
-
- Seek(m_startpos);
-
- if(m_mode == none && Read(m_aachdr, searchlen, &m_mt))
- {
- m_mode = mp4a;
-
- startpos = GetPos() - (m_aachdr.fcrc ? 7 : 9);
-
- // make sure the first frame is followed by another of the same kind (validates m_aachdr basically)
- Seek(startpos + m_aachdr.aac_frame_length);
- if(!Sync(9)) m_mode = none;
- }
-
- if(m_mode == none)
- return E_FAIL;
-
- m_startpos = startpos;
-
- int FrameSize;
- REFERENCE_TIME rtFrameDur, rtPrevDur = -1;
- clock_t start = clock();
- int i = 0;
- while(Sync(FrameSize, rtFrameDur) && (clock() - start) < CLOCKS_PER_SEC)
- {
- TRACE(_T("%I64d\n"), m_rtDuration);
- Seek(GetPos() + FrameSize);
- i = rtPrevDur == m_rtDuration ? i + 1 : 0;
- if(i == 10) break;
- rtPrevDur = m_rtDuration;
- }
-
- return S_OK;
+ m_startpos = 0;
+ m_endpos = GetLength();
+
+ Seek(0);
+
+ if(BitRead(24, true) == 0x000001)
+ return E_FAIL;
+
+ if(m_endpos > 128 && IsRandomAccess())
+ {
+ Seek(m_endpos - 128);
+
+ if(BitRead(24) == 'TAG')
+ {
+ m_endpos -= 128;
+
+ CStringA str;
+
+ // title
+ ByteRead((BYTE*)str.GetBufferSetLength(30), 30);
+ m_tags['TIT2'] = CStringW(str).Trim();
+
+ // artist
+ ByteRead((BYTE*)str.GetBufferSetLength(30), 30);
+ m_tags['TPE1'] = CStringW(str).Trim();
+
+ // album
+ ByteRead((BYTE*)str.GetBufferSetLength(30), 30);
+ m_tags['TALB'] = CStringW(str).Trim();
+
+ // year
+ ByteRead((BYTE*)str.GetBufferSetLength(4), 4);
+ m_tags['TYER'] = CStringW(str).Trim();
+
+ // comment
+ ByteRead((BYTE*)str.GetBufferSetLength(30), 30);
+ m_tags['COMM'] = CStringW(str).Trim();
+
+ // track
+ LPCSTR s = str;
+ if(s[28] == 0 && s[29] != 0)
+ m_tags['TRCK'].Format(L"%d", s[29]);
+
+ // genre
+ BYTE genre = (BYTE)BitRead(8);
+ if(genre < countof(s_genre))
+ m_tags['TCON'] = CStringW(s_genre[genre]);
+ }
+ }
+
+ Seek(0);
+
+ while(BitRead(24, true) == 'ID3')
+ {
+ BitRead(24);
+
+ BYTE major = (BYTE)BitRead(8);
+ BYTE revision = (BYTE)BitRead(8);
+
+ BYTE flags = (BYTE)BitRead(8);
+ DWORD size = 0;
+ if(BitRead(1) != 0) return E_FAIL;
+ size |= BitRead(7) << 21;
+ if(BitRead(1) != 0) return E_FAIL;
+ size |= BitRead(7) << 14;
+ if(BitRead(1) != 0) return E_FAIL;
+ size |= BitRead(7) << 7;
+ if(BitRead(1) != 0) return E_FAIL;
+ size |= BitRead(7);
+
+ m_startpos = GetPos() + size;
+
+ // TODO: read extended header
+
+ if(major <= 4)
+ {
+ __int64 pos = GetPos();
+
+ while(pos < m_startpos)
+ {
+ Seek(pos);
+
+ DWORD tag = (DWORD)BitRead(32);
+ DWORD size = 0;
+ size |= BitRead(8) << 24;
+ size |= BitRead(8) << 16;
+ size |= BitRead(8) << 8;
+ size |= BitRead(8);
+ WORD flags = (WORD)BitRead(16);
+
+ pos += 4+4+2+size;
+
+ if(!size || pos >= m_startpos)
+ break;
+
+ if(tag == 'TIT2'
+ || tag == 'TPE1'
+ || tag == 'TALB'
+ || tag == 'TYER'
+ || tag == 'COMM'
+ || tag == 'TRCK')
+ {
+ BYTE encoding = (BYTE)BitRead(8);
+ size--;
+
+ WORD bom = (WORD)BitRead(16, true);
+
+ CStringA str;
+ CStringW wstr;
+
+ if(encoding > 0 && size >= 2 && bom == 0xfffe)
+ {
+ BitRead(16);
+ size = (size - 2) / 2;
+ ByteRead((BYTE*)wstr.GetBufferSetLength(size), size*2);
+ m_tags[tag] = wstr.Trim();
+ }
+ else if(encoding > 0 && size >= 2 && bom == 0xfeff)
+ {
+ BitRead(16);
+ size = (size - 2) / 2;
+ ByteRead((BYTE*)wstr.GetBufferSetLength(size), size*2);
+ for(int i = 0, j = wstr.GetLength(); i < j; i++) wstr.SetAt(i, (wstr[i]<<8)|(wstr[i]>>8));
+ m_tags[tag] = wstr.Trim();
+ }
+ else
+ {
+ ByteRead((BYTE*)str.GetBufferSetLength(size), size);
+ m_tags[tag] = (encoding > 0 ? UTF8To16(str) : CStringW(str)).Trim();
+ }
+ }
+ }
+ }
+
+ Seek(m_startpos);
+
+ for(int i = 0; i < (1<<20) && m_startpos < m_endpos && BitRead(8, true) == 0; i++)
+ BitRead(8), m_startpos++;
+ }
+
+ __int64 searchlen = min(m_endpos - m_startpos, m_startpos > 0 ? 0x200 : 7);
+
+ __int64 startpos;
+
+ Seek(m_startpos);
+
+ if(m_mode == none && Read(m_mpahdr, searchlen, true, &m_mt))
+ {
+ m_mode = mpa;
+
+ startpos = GetPos() - 4;
+
+ // make sure the first frame is followed by another of the same kind (validates m_mpahdr basically)
+ Seek(startpos + m_mpahdr.FrameSize);
+ if(!Sync(4)) m_mode = none;
+ }
+
+ Seek(m_startpos);
+
+ if(m_mode == none && Read(m_aachdr, searchlen, &m_mt))
+ {
+ m_mode = mp4a;
+
+ startpos = GetPos() - (m_aachdr.fcrc?7:9);
+
+ // make sure the first frame is followed by another of the same kind (validates m_aachdr basically)
+ Seek(startpos + m_aachdr.aac_frame_length);
+ if(!Sync(9)) m_mode = none;
+ }
+
+ if(m_mode == none)
+ return E_FAIL;
+
+ m_startpos = startpos;
+
+ int FrameSize;
+ REFERENCE_TIME rtFrameDur, rtPrevDur = -1;
+ clock_t start = clock();
+ int i = 0;
+ while(Sync(FrameSize, rtFrameDur) && (clock() - start) < CLOCKS_PER_SEC)
+ {
+ TRACE(_T("%I64d\n"), m_rtDuration);
+ Seek(GetPos() + FrameSize);
+ i = rtPrevDur == m_rtDuration ? i+1 : 0;
+ if(i == 10) break;
+ rtPrevDur = m_rtDuration;
+ }
+
+ return S_OK;
}
bool CMpaSplitterFile::Sync(int limit)
{
- int FrameSize;
- REFERENCE_TIME rtDuration;
- return Sync(FrameSize, rtDuration, limit);
+ int FrameSize;
+ REFERENCE_TIME rtDuration;
+ return Sync(FrameSize, rtDuration, limit);
}
bool CMpaSplitterFile::Sync(int& FrameSize, REFERENCE_TIME& rtDuration, int limit)
{
- __int64 endpos = min(m_endpos, GetPos() + limit);
-
- if(m_mode == mpa)
- {
- while(GetPos() <= endpos - 4)
- {
- mpahdr h;
-
- if(Read(h, endpos - GetPos(), true)
- && m_mpahdr.version == h.version
- && m_mpahdr.layer == h.layer
- && m_mpahdr.channels == h.channels)
- {
- Seek(GetPos() - 4);
- AdjustDuration(h.nBytesPerSec);
-
- FrameSize = h.FrameSize;
- rtDuration = h.rtDuration;
-
- return true;
- }
- }
- }
- else if(m_mode == mp4a)
- {
- while(GetPos() <= endpos - 9)
- {
- aachdr h;
-
- if(Read(h, endpos - GetPos())
- && m_aachdr.version == h.version
- && m_aachdr.layer == h.layer
- && m_aachdr.channels == h.channels)
- {
- Seek(GetPos() - (h.fcrc ? 7 : 9));
- AdjustDuration(h.nBytesPerSec);
- Seek(GetPos() + (h.fcrc ? 7 : 9));
-
- FrameSize = h.FrameSize;
- rtDuration = h.rtDuration;
-
- return true;
- }
- }
- }
-
- return false;
+ __int64 endpos = min(m_endpos, GetPos() + limit);
+
+ if(m_mode == mpa)
+ {
+ while(GetPos() <= endpos - 4)
+ {
+ mpahdr h;
+
+ if(Read(h, endpos - GetPos(), true)
+ && m_mpahdr.version == h.version
+ && m_mpahdr.layer == h.layer
+ && m_mpahdr.channels == h.channels)
+ {
+ Seek(GetPos() - 4);
+ AdjustDuration(h.nBytesPerSec);
+
+ FrameSize = h.FrameSize;
+ rtDuration = h.rtDuration;
+
+ return true;
+ }
+ }
+ }
+ else if(m_mode == mp4a)
+ {
+ while(GetPos() <= endpos - 9)
+ {
+ aachdr h;
+
+ if(Read(h, endpos - GetPos())
+ && m_aachdr.version == h.version
+ && m_aachdr.layer == h.layer
+ && m_aachdr.channels == h.channels)
+ {
+ Seek(GetPos() - (h.fcrc?7:9));
+ AdjustDuration(h.nBytesPerSec);
+ Seek(GetPos() + (h.fcrc?7:9));
+
+ FrameSize = h.FrameSize;
+ rtDuration = h.rtDuration;
+
+ return true;
+ }
+ }
+ }
+
+ return false;
}
void CMpaSplitterFile::AdjustDuration(int nBytesPerSec)
{
- ASSERT(nBytesPerSec);
-
- int rValue;
- if(!m_pos2bps.Lookup(GetPos(), rValue))
- {
- m_totalbps += nBytesPerSec;
- if(!m_totalbps) return;
- m_pos2bps.SetAt(GetPos(), nBytesPerSec);
- __int64 avgbps = m_totalbps / m_pos2bps.GetCount();
- m_rtDuration = 10000000i64 * (m_endpos - m_startpos) / avgbps;
- }
+ ASSERT(nBytesPerSec);
+
+ int rValue;
+ if(!m_pos2bps.Lookup(GetPos(), rValue))
+ {
+ m_totalbps += nBytesPerSec;
+ if(!m_totalbps) return;
+ m_pos2bps.SetAt(GetPos(), nBytesPerSec);
+ __int64 avgbps = m_totalbps / m_pos2bps.GetCount();
+ m_rtDuration = 10000000i64 * (m_endpos - m_startpos) / avgbps;
+ }
}
diff --git a/src/filters/parser/MpaSplitter/MpaSplitterFile.h b/src/filters/parser/MpaSplitter/MpaSplitterFile.h
index cf392e48d..ee2e0d799 100644
--- a/src/filters/parser/MpaSplitter/MpaSplitterFile.h
+++ b/src/filters/parser/MpaSplitter/MpaSplitterFile.h
@@ -1,4 +1,4 @@
-/*
+/*
* Copyright (C) 2003-2006 Gabest
* http://www.gabest.org
*
@@ -6,15 +6,15 @@
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2, or (at your option)
* any later version.
- *
+ *
* This Program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with GNU Make; see the file COPYING. If not, write to
- * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
+ * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
* http://www.gnu.org/copyleft/gpl.html
*
*/
@@ -25,44 +25,32 @@
class CMpaSplitterFile : public CBaseSplitterFileEx
{
- CMediaType m_mt;
- REFERENCE_TIME m_rtDuration;
+ CMediaType m_mt;
+ REFERENCE_TIME m_rtDuration;
- enum {none, mpa, mp4a} m_mode;
+ enum {none, mpa, mp4a} m_mode;
- mpahdr m_mpahdr;
- aachdr m_aachdr;
- __int64 m_startpos, m_endpos;
+ mpahdr m_mpahdr;
+ aachdr m_aachdr;
+ __int64 m_startpos, m_endpos;
- __int64 m_totalbps;
- CRBMap<__int64, int> m_pos2bps;
+ __int64 m_totalbps;
+ CRBMap<__int64, int> m_pos2bps;
- HRESULT Init();
- void AdjustDuration(int nBytesPerSec);
+ HRESULT Init();
+ void AdjustDuration(int nBytesPerSec);
public:
- CMpaSplitterFile(IAsyncReader* pAsyncReader, HRESULT& hr);
+ CMpaSplitterFile(IAsyncReader* pAsyncReader, HRESULT& hr);
- CAtlMap<DWORD, CStringW> m_tags;
+ CAtlMap<DWORD, CStringW> m_tags;
- const CMediaType& GetMediaType()
- {
- return m_mt;
- }
- REFERENCE_TIME GetDuration()
- {
- return IsRandomAccess() ? m_rtDuration : 0;
- }
+ const CMediaType& GetMediaType() {return m_mt;}
+ REFERENCE_TIME GetDuration() {return IsRandomAccess() ? m_rtDuration : 0;}
- __int64 GetStartPos()
- {
- return m_startpos;
- }
- __int64 GetEndPos()
- {
- return m_endpos;
- }
+ __int64 GetStartPos() {return m_startpos;}
+ __int64 GetEndPos() {return m_endpos;}
- bool Sync(int limit = 0x2000);
- bool Sync(int& FrameSize, REFERENCE_TIME& rtDuration, int limit = 0x2000);
+ bool Sync(int limit = 0x2000);
+ bool Sync(int& FrameSize, REFERENCE_TIME& rtDuration, int limit = 0x2000);
};
diff --git a/src/filters/parser/MpaSplitter/resource.h b/src/filters/parser/MpaSplitter/resource.h
index 35d6f689e..c2fcfb22b 100644
--- a/src/filters/parser/MpaSplitter/resource.h
+++ b/src/filters/parser/MpaSplitter/resource.h
@@ -4,7 +4,7 @@
//
// Next default values for new objects
-//
+//
#ifdef APSTUDIO_INVOKED
#ifndef APSTUDIO_READONLY_SYMBOLS
#define _APS_NEXT_RESOURCE_VALUE 101
diff --git a/src/filters/parser/MpaSplitter/stdafx.cpp b/src/filters/parser/MpaSplitter/stdafx.cpp
index 9f8db70c3..845bd92b0 100644
--- a/src/filters/parser/MpaSplitter/stdafx.cpp
+++ b/src/filters/parser/MpaSplitter/stdafx.cpp
@@ -1,4 +1,4 @@
-/*
+/*
* Copyright (C) 2003-2006 Gabest
* http://www.gabest.org
*
@@ -6,15 +6,15 @@
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2, or (at your option)
* any later version.
- *
+ *
* This Program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with GNU Make; see the file COPYING. If not, write to
- * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
+ * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
* http://www.gnu.org/copyleft/gpl.html
*
*/
diff --git a/src/filters/parser/MpaSplitter/stdafx.h b/src/filters/parser/MpaSplitter/stdafx.h
index 2dff0522c..32d2f51d8 100644
--- a/src/filters/parser/MpaSplitter/stdafx.h
+++ b/src/filters/parser/MpaSplitter/stdafx.h
@@ -1,4 +1,4 @@
-/*
+/*
* Copyright (C) 2003-2006 Gabest
* http://www.gabest.org
*
@@ -6,15 +6,15 @@
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2, or (at your option)
* any later version.
- *
+ *
* This Program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with GNU Make; see the file COPYING. If not, write to
- * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
+ * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
* http://www.gnu.org/copyleft/gpl.html
*
*/
diff --git a/src/filters/parser/MpegSplitter/MpegSplitter.cpp b/src/filters/parser/MpegSplitter/MpegSplitter.cpp
index 52021c8af..732f23068 100644
--- a/src/filters/parser/MpegSplitter/MpegSplitter.cpp
+++ b/src/filters/parser/MpegSplitter/MpegSplitter.cpp
@@ -1,4 +1,4 @@
-/*
+/*
* (C) 2003-2006 Gabest
* (C) 2006-2010 see AUTHORS
* http://www.gabest.org
@@ -7,15 +7,15 @@
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2, or (at your option)
* any later version.
- *
+ *
* This Program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with GNU Make; see the file COPYING. If not, write to
- * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
+ * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
* http://www.gnu.org/copyleft/gpl.html
*
*/
@@ -33,12 +33,12 @@
const AMOVIESETUP_MEDIATYPE sudPinTypesIn[] =
{
- {&MEDIATYPE_Stream, &MEDIASUBTYPE_MPEG1System},
+ {&MEDIATYPE_Stream, &MEDIASUBTYPE_MPEG1System},
// {&MEDIATYPE_Stream, &MEDIASUBTYPE_MPEG1VideoCD}, // cdxa filter should take care of this
- {&MEDIATYPE_Stream, &MEDIASUBTYPE_MPEG2_PROGRAM},
- {&MEDIATYPE_Stream, &MEDIASUBTYPE_MPEG2_TRANSPORT},
- {&MEDIATYPE_Stream, &MEDIASUBTYPE_MPEG2_PVA},
- {&MEDIATYPE_Stream, &MEDIASUBTYPE_NULL},
+ {&MEDIATYPE_Stream, &MEDIASUBTYPE_MPEG2_PROGRAM},
+ {&MEDIATYPE_Stream, &MEDIASUBTYPE_MPEG2_TRANSPORT},
+ {&MEDIATYPE_Stream, &MEDIASUBTYPE_MPEG2_PVA},
+ {&MEDIATYPE_Stream, &MEDIASUBTYPE_NULL},
};
const AMOVIESETUP_PIN sudpPins[] =
@@ -49,33 +49,33 @@ const AMOVIESETUP_PIN sudpPins[] =
const AMOVIESETUP_FILTER sudFilter[] =
{
- {&__uuidof(CMpegSplitterFilter), L"MPC - Mpeg Splitter (Gabest)", MERIT_NORMAL + 1, countof(sudpPins), sudpPins, CLSID_LegacyAmFilterCategory},
- {&__uuidof(CMpegSourceFilter), L"MPC - Mpeg Source (Gabest)", MERIT_UNLIKELY, 0, NULL, CLSID_LegacyAmFilterCategory},
+ {&__uuidof(CMpegSplitterFilter), L"MPC - Mpeg Splitter (Gabest)", MERIT_NORMAL+1, countof(sudpPins), sudpPins, CLSID_LegacyAmFilterCategory},
+ {&__uuidof(CMpegSourceFilter), L"MPC - Mpeg Source (Gabest)", MERIT_UNLIKELY, 0, NULL, CLSID_LegacyAmFilterCategory},
};
CFactoryTemplate g_Templates[] =
{
- {sudFilter[0].strName, sudFilter[0].clsID, CreateInstance<CMpegSplitterFilter>, NULL, &sudFilter[0]},
- {sudFilter[1].strName, sudFilter[1].clsID, CreateInstance<CMpegSourceFilter>, NULL, &sudFilter[1]},
+ {sudFilter[0].strName, sudFilter[0].clsID, CreateInstance<CMpegSplitterFilter>, NULL, &sudFilter[0]},
+ {sudFilter[1].strName, sudFilter[1].clsID, CreateInstance<CMpegSourceFilter>, NULL, &sudFilter[1]},
};
int g_cTemplates = countof(g_Templates);
STDAPI DllRegisterServer()
{
- DeleteRegKey(_T("Media Type\\Extensions\\"), _T(".ts"));
+ DeleteRegKey(_T("Media Type\\Extensions\\"), _T(".ts"));
- RegisterSourceFilter(CLSID_AsyncReader, MEDIASUBTYPE_MPEG1System, _T("0,16,FFFFFFFFF100010001800001FFFFFFFF,000001BA2100010001800001000001BB"), NULL);
- RegisterSourceFilter(CLSID_AsyncReader, MEDIASUBTYPE_MPEG2_PROGRAM, _T("0,5,FFFFFFFFC0,000001BA40"), NULL);
- RegisterSourceFilter(CLSID_AsyncReader, MEDIASUBTYPE_MPEG2_PVA, _T("0,8,fffffc00ffe00000,4156000055000000"), NULL);
+ RegisterSourceFilter(CLSID_AsyncReader, MEDIASUBTYPE_MPEG1System, _T("0,16,FFFFFFFFF100010001800001FFFFFFFF,000001BA2100010001800001000001BB"), NULL);
+ RegisterSourceFilter(CLSID_AsyncReader, MEDIASUBTYPE_MPEG2_PROGRAM, _T("0,5,FFFFFFFFC0,000001BA40"), NULL);
+ RegisterSourceFilter(CLSID_AsyncReader, MEDIASUBTYPE_MPEG2_PVA, _T("0,8,fffffc00ffe00000,4156000055000000"), NULL);
- CAtlList<CString> chkbytes;
- chkbytes.AddTail(_T("0,1,,47,188,1,,47,376,1,,47"));
- chkbytes.AddTail(_T("4,1,,47,196,1,,47,388,1,,47"));
- chkbytes.AddTail(_T("0,4,,54467263,1660,1,,47")); // TFrc
- RegisterSourceFilter(CLSID_AsyncReader, MEDIASUBTYPE_MPEG2_TRANSPORT, chkbytes, NULL);
+ CAtlList<CString> chkbytes;
+ chkbytes.AddTail(_T("0,1,,47,188,1,,47,376,1,,47"));
+ chkbytes.AddTail(_T("4,1,,47,196,1,,47,388,1,,47"));
+ chkbytes.AddTail(_T("0,4,,54467263,1660,1,,47")); // TFrc
+ RegisterSourceFilter(CLSID_AsyncReader, MEDIASUBTYPE_MPEG2_TRANSPORT, chkbytes, NULL);
- return AMovieDllRegisterServer2(TRUE);
+ return AMovieDllRegisterServer2(TRUE);
}
STDAPI DllUnregisterServer()
@@ -83,7 +83,7 @@ STDAPI DllUnregisterServer()
// UnRegisterSourceFilter(MEDIASUBTYPE_MPEG1System);
// UnRegisterSourceFilter(MEDIASUBTYPE_MPEG2_PROGRAM);
- return AMovieDllRegisterServer2(FALSE);
+ return AMovieDllRegisterServer2(FALSE);
}
#include "../../FilterApp.h"
@@ -97,8 +97,8 @@ CFilterApp theApp;
//
CMpegSplitterFilter::CMpegSplitterFilter(LPUNKNOWN pUnk, HRESULT* phr, const CLSID& clsid)
- : CBaseSplitterFilter(NAME("CMpegSplitterFilter"), pUnk, phr, clsid)
- , m_pPipoBimbo(false)
+ : CBaseSplitterFilter(NAME("CMpegSplitterFilter"), pUnk, phr, clsid)
+ , m_pPipoBimbo(false)
{
}
@@ -106,1050 +106,1014 @@ STDMETHODIMP CMpegSplitterFilter::NonDelegatingQueryInterface(REFIID riid, void*
{
CheckPointer(ppv, E_POINTER);
- return
- QI(IAMStreamSelect)
- __super::NonDelegatingQueryInterface(riid, ppv);
+ return
+ QI(IAMStreamSelect)
+ __super::NonDelegatingQueryInterface(riid, ppv);
}
STDMETHODIMP CMpegSplitterFilter::GetClassID(CLSID* pClsID)
{
- CheckPointer(pClsID, E_POINTER);
-
- if(m_pPipoBimbo)
- {
- memcpy(pClsID, &CLSID_WMAsfReader, sizeof(GUID));
- return S_OK;
- }
- else
- return __super::GetClassID(pClsID);
+ CheckPointer (pClsID, E_POINTER);
+
+ if (m_pPipoBimbo)
+ {
+ memcpy (pClsID, &CLSID_WMAsfReader, sizeof (GUID));
+ return S_OK;
+ }
+ else
+ return __super::GetClassID(pClsID);
}
void CMpegSplitterFilter::ReadClipInfo(LPCOLESTR pszFileName)
{
- if(wcslen(pszFileName) > 0)
- {
- WCHAR Drive[_MAX_DRIVE];
- WCHAR Dir[_MAX_PATH];
- WCHAR Filename[_MAX_PATH];
- WCHAR Ext[_MAX_EXT];
-
- if(_wsplitpath_s(pszFileName, Drive, countof(Drive), Dir, countof(Dir), Filename, countof(Filename), Ext, countof(Ext)) == 0)
- {
- CString strClipInfo;
-
- if(Drive[0])
- strClipInfo.Format(_T("%s\\%s\\..\\CLIPINF\\%s.clpi"), Drive, Dir, Filename);
- else
- strClipInfo.Format(_T("%s\\..\\CLIPINF\\%s.clpi"), Dir, Filename);
-
- m_ClipInfo.ReadInfo(strClipInfo);
- }
- }
+ if (wcslen (pszFileName) > 0)
+ {
+ WCHAR Drive[_MAX_DRIVE];
+ WCHAR Dir[_MAX_PATH];
+ WCHAR Filename[_MAX_PATH];
+ WCHAR Ext[_MAX_EXT];
+
+ if (_wsplitpath_s (pszFileName, Drive, countof(Drive), Dir, countof(Dir), Filename, countof(Filename), Ext, countof(Ext)) == 0)
+ {
+ CString strClipInfo;
+
+ if (Drive[0])
+ strClipInfo.Format (_T("%s\\%s\\..\\CLIPINF\\%s.clpi"), Drive, Dir, Filename);
+ else
+ strClipInfo.Format (_T("%s\\..\\CLIPINF\\%s.clpi"), Dir, Filename);
+
+ m_ClipInfo.ReadInfo (strClipInfo);
+ }
+ }
}
STDMETHODIMP CMpegSplitterFilter::Load(LPCOLESTR pszFileName, const AM_MEDIA_TYPE* pmt)
{
- HRESULT hr;
-
- return __super::Load(pszFileName, pmt);
+ HRESULT hr;
+
+ return __super::Load (pszFileName, pmt);
}
HRESULT CMpegSplitterFilter::DemuxNextPacket(REFERENCE_TIME rtStartOffset)
{
- HRESULT hr;
- BYTE b;
-
- if(m_pFile->m_type == CMpegSplitterFile::ps || m_pFile->m_type == CMpegSplitterFile::es)
- {
- if(!m_pFile->NextMpegStartCode(b))
- return S_FALSE;
-
- if(b == 0xba) // program stream header
- {
- CMpegSplitterFile::pshdr h;
- if(!m_pFile->Read(h))
- return S_FALSE;
- }
- else if(b == 0xbb) // program stream system header
- {
- CMpegSplitterFile::pssyshdr h;
- if(!m_pFile->Read(h))
- return S_FALSE;
- }
+ HRESULT hr;
+ BYTE b;
+
+ if(m_pFile->m_type == CMpegSplitterFile::ps || m_pFile->m_type == CMpegSplitterFile::es)
+ {
+ if(!m_pFile->NextMpegStartCode(b))
+ return S_FALSE;
+
+ if(b == 0xba) // program stream header
+ {
+ CMpegSplitterFile::pshdr h;
+ if(!m_pFile->Read(h))
+ return S_FALSE;
+ }
+ else if(b == 0xbb) // program stream system header
+ {
+ CMpegSplitterFile::pssyshdr h;
+ if(!m_pFile->Read(h))
+ return S_FALSE;
+ }
#if (EVO_SUPPORT == 0)
- else if(b >= 0xbd && b < 0xf0) // pes packet
+ else if(b >= 0xbd && b < 0xf0) // pes packet
#else
- else if((b >= 0xbd && b < 0xf0) || (b == 0xfd)) // pes packet
+ else if((b >= 0xbd && b < 0xf0) || (b == 0xfd)) // pes packet
#endif
- {
- CMpegSplitterFile::peshdr h;
-
- if(!m_pFile->Read(h, b) || !h.len) return S_FALSE;
-
- if(h.type == CMpegSplitterFile::mpeg2 && h.scrambling)
- {
- ASSERT(0);
- return E_FAIL;
- }
-
- __int64 pos = m_pFile->GetPos();
-
- DWORD TrackNumber = m_pFile->AddStream(0, b, h.len);
-
- if(GetOutputPin(TrackNumber))
- {
- CAutoPtr<Packet> p(DNew Packet());
-
- p->TrackNumber = TrackNumber;
- p->bSyncPoint = !!h.fpts;
- p->bAppendable = !h.fpts;
- p->rtStart = h.fpts ? (h.pts - rtStartOffset) : Packet::INVALID_TIME;
- p->rtStop = p->rtStart + 1;
- p->SetCount(h.len - (size_t)(m_pFile->GetPos() - pos));
-
- m_pFile->ByteRead(p->GetData(), h.len - (m_pFile->GetPos() - pos));
-
- hr = DeliverPacket(p);
- }
- m_pFile->Seek(pos + h.len);
- }
- }
- else if(m_pFile->m_type == CMpegSplitterFile::ts)
- {
- CMpegSplitterFile::trhdr h;
-
- if(!m_pFile->Read(h))
- return S_FALSE;
-
-
- __int64 pos = m_pFile->GetPos();
-
- if(h.payload && h.payloadstart)
- m_pFile->UpdatePrograms(h);
-
- if(h.payload && h.pid >= 16 && h.pid < 0x1fff && !h.scrambling)
- {
- DWORD TrackNumber = h.pid;
-
- CMpegSplitterFile::peshdr h2;
-
- if(h.payloadstart && m_pFile->NextMpegStartCode(b, 4) && m_pFile->Read(h2, b)) // pes packet
- {
- if(h2.type == CMpegSplitterFile::mpeg2 && h2.scrambling)
- {
- ASSERT(0);
- return E_FAIL;
- }
- TrackNumber = m_pFile->AddStream(h.pid, b, h.bytes - (DWORD)(m_pFile->GetPos() - pos));
- }
-
- if(GetOutputPin(TrackNumber))
- {
- CAutoPtr<Packet> p(DNew Packet());
-
- p->TrackNumber = TrackNumber;
- p->bSyncPoint = !!h2.fpts;
- p->bAppendable = !h2.fpts;
-
- if(h.fPCR)
- {
- CRefTime rtNow;
- StreamTime(rtNow);
- TRACE("Now=%S PCR=%S\n", ReftimeToString(rtNow.m_time), ReftimeToString(h.PCR));
- }
- if(h2.fpts && h.pid == 241)
- {
- TRACE("Sub=%S\n", ReftimeToString(h2.pts - rtStartOffset));
- }
-
- p->rtStart = h2.fpts ? (h2.pts - rtStartOffset) : Packet::INVALID_TIME;
- p->rtStop = p->rtStart + 1;
- p->SetCount(h.bytes - (size_t)(m_pFile->GetPos() - pos));
-
- int nBytes = int(h.bytes - (m_pFile->GetPos() - pos));
- m_pFile->ByteRead(p->GetData(), nBytes);
-
- hr = DeliverPacket(p);
- }
- }
-
- m_pFile->Seek(h.next);
- }
- else if(m_pFile->m_type == CMpegSplitterFile::pva)
- {
- CMpegSplitterFile::pvahdr h;
- if(!m_pFile->Read(h))
- return S_FALSE;
-
- DWORD TrackNumber = h.streamid;
-
- __int64 pos = m_pFile->GetPos();
-
- if(GetOutputPin(TrackNumber))
- {
- CAutoPtr<Packet> p(DNew Packet());
-
- p->TrackNumber = TrackNumber;
- p->bSyncPoint = !!h.fpts;
- p->bAppendable = !h.fpts;
- p->rtStart = h.fpts ? (h.pts - rtStartOffset) : Packet::INVALID_TIME;
- p->rtStop = p->rtStart + 1;
- p->SetCount(h.length);
-
- m_pFile->ByteRead(p->GetData(), h.length);
- hr = DeliverPacket(p);
- }
-
- m_pFile->Seek(pos + h.length);
- }
-
- return S_OK;
+ {
+ CMpegSplitterFile::peshdr h;
+
+ if(!m_pFile->Read(h, b) || !h.len) return S_FALSE;
+
+ if(h.type == CMpegSplitterFile::mpeg2 && h.scrambling)
+ {
+ ASSERT(0);
+ return E_FAIL;
+ }
+
+ __int64 pos = m_pFile->GetPos();
+
+ DWORD TrackNumber = m_pFile->AddStream(0, b, h.len);
+
+ if(GetOutputPin(TrackNumber))
+ {
+ CAutoPtr<Packet> p(DNew Packet());
+
+ p->TrackNumber = TrackNumber;
+ p->bSyncPoint = !!h.fpts;
+ p->bAppendable = !h.fpts;
+ p->rtStart = h.fpts ? (h.pts - rtStartOffset) : Packet::INVALID_TIME;
+ p->rtStop = p->rtStart+1;
+ p->SetCount(h.len - (size_t)(m_pFile->GetPos() - pos));
+
+ m_pFile->ByteRead(p->GetData(), h.len - (m_pFile->GetPos() - pos));
+
+ hr = DeliverPacket(p);
+ }
+ m_pFile->Seek(pos + h.len);
+ }
+ }
+ else if(m_pFile->m_type == CMpegSplitterFile::ts)
+ {
+ CMpegSplitterFile::trhdr h;
+
+ if(!m_pFile->Read(h))
+ return S_FALSE;
+
+
+ __int64 pos = m_pFile->GetPos();
+
+ if(h.payload && h.payloadstart)
+ m_pFile->UpdatePrograms(h);
+
+ if(h.payload && h.pid >= 16 && h.pid < 0x1fff && !h.scrambling)
+ {
+ DWORD TrackNumber = h.pid;
+
+ CMpegSplitterFile::peshdr h2;
+
+ if(h.payloadstart && m_pFile->NextMpegStartCode(b, 4) && m_pFile->Read(h2, b)) // pes packet
+ {
+ if(h2.type == CMpegSplitterFile::mpeg2 && h2.scrambling)
+ {
+ ASSERT(0);
+ return E_FAIL;
+ }
+ TrackNumber = m_pFile->AddStream(h.pid, b, h.bytes - (DWORD)(m_pFile->GetPos() - pos));
+ }
+
+ if(GetOutputPin(TrackNumber))
+ {
+ CAutoPtr<Packet> p(DNew Packet());
+
+ p->TrackNumber = TrackNumber;
+ p->bSyncPoint = !!h2.fpts;
+ p->bAppendable = !h2.fpts;
+
+ if (h.fPCR)
+ {
+ CRefTime rtNow;
+ StreamTime(rtNow);
+ TRACE ("Now=%S PCR=%S\n", ReftimeToString(rtNow.m_time), ReftimeToString(h.PCR));
+ }
+ if (h2.fpts && h.pid == 241)
+ {
+ TRACE ("Sub=%S\n", ReftimeToString(h2.pts - rtStartOffset));
+ }
+
+ p->rtStart = h2.fpts ? (h2.pts - rtStartOffset) : Packet::INVALID_TIME;
+ p->rtStop = p->rtStart+1;
+ p->SetCount(h.bytes - (size_t)(m_pFile->GetPos() - pos));
+
+ int nBytes = int(h.bytes - (m_pFile->GetPos() - pos));
+ m_pFile->ByteRead(p->GetData(), nBytes);
+
+ hr = DeliverPacket(p);
+ }
+ }
+
+ m_pFile->Seek(h.next);
+ }
+ else if(m_pFile->m_type == CMpegSplitterFile::pva)
+ {
+ CMpegSplitterFile::pvahdr h;
+ if(!m_pFile->Read(h))
+ return S_FALSE;
+
+ DWORD TrackNumber = h.streamid;
+
+ __int64 pos = m_pFile->GetPos();
+
+ if(GetOutputPin(TrackNumber))
+ {
+ CAutoPtr<Packet> p(DNew Packet());
+
+ p->TrackNumber = TrackNumber;
+ p->bSyncPoint = !!h.fpts;
+ p->bAppendable = !h.fpts;
+ p->rtStart = h.fpts ? (h.pts - rtStartOffset) : Packet::INVALID_TIME;
+ p->rtStop = p->rtStart+1;
+ p->SetCount(h.length);
+
+ m_pFile->ByteRead(p->GetData(), h.length);
+ hr = DeliverPacket(p);
+ }
+
+ m_pFile->Seek(pos + h.length);
+ }
+
+ return S_OK;
}
//
HRESULT CMpegSplitterFilter::CreateOutputs(IAsyncReader* pAsyncReader)
{
- CheckPointer(pAsyncReader, E_POINTER);
-
- HRESULT hr = E_FAIL;
-
- m_pFile.Free();
-
- ReadClipInfo(GetPartFilename(pAsyncReader));
- m_pFile.Attach(DNew CMpegSplitterFile(pAsyncReader, hr, m_ClipInfo.IsHdmv(), m_ClipInfo));
-
- if(!m_pFile) return E_OUTOFMEMORY;
-
- if(FAILED(hr))
- {
- m_pFile.Free();
- return hr;
- }
-
- // Create
- if(m_ClipInfo.IsHdmv())
- {
- for(int i = 0; i < m_ClipInfo.GetStreamNumber(); i++)
- {
- CHdmvClipInfo::Stream* stream = m_ClipInfo.GetStreamByIndex(i);
- if(stream->m_Type == PRESENTATION_GRAPHICS_STREAM)
- {
- m_pFile->AddHdmvPGStream(stream->m_PID, stream->m_LanguageCode);
- }
- }
- }
-
- m_rtNewStart = m_rtCurrent = 0;
- m_rtNewStop = m_rtStop = m_rtDuration = 0;
-
- for(int i = 0; i < countof(m_pFile->m_streams); i++)
- {
- POSITION pos = m_pFile->m_streams[i].GetHeadPosition();
- while(pos)
- {
- CMpegSplitterFile::stream& s = m_pFile->m_streams[i].GetNext(pos);
-
- CAtlArray<CMediaType> mts;
- mts.Add(s.mt);
-
- CStringW name = CMpegSplitterFile::CStreamList::ToString(i);
-
- CAutoPtr<CBaseSplitterOutputPin> pPinOut(DNew CMpegSplitterOutputPin(mts, name, this, this, &hr));
- if(i == CMpegSplitterFile::subpic)
- (static_cast<CMpegSplitterOutputPin*>(pPinOut.m_p))->SetMaxShift(_I64_MAX);
- if(S_OK == AddOutputPin(s, pPinOut))
- break;
- }
- }
-
- if(m_pFile->IsRandomAccess() && m_pFile->m_rate)
- {
- m_rtNewStop = m_rtStop = m_rtDuration = 10000000i64 * m_pFile->GetLength() / m_pFile->m_rate;
- }
-
- return m_pOutputs.GetCount() > 0 ? S_OK : E_FAIL;
+ CheckPointer(pAsyncReader, E_POINTER);
+
+ HRESULT hr = E_FAIL;
+
+ m_pFile.Free();
+
+ ReadClipInfo (GetPartFilename(pAsyncReader));
+ m_pFile.Attach(DNew CMpegSplitterFile(pAsyncReader, hr, m_ClipInfo.IsHdmv(), m_ClipInfo));
+
+ if(!m_pFile) return E_OUTOFMEMORY;
+
+ if(FAILED(hr))
+ {
+ m_pFile.Free();
+ return hr;
+ }
+
+ // Create
+ if (m_ClipInfo.IsHdmv())
+ {
+ for (int i=0; i<m_ClipInfo.GetStreamNumber(); i++)
+ {
+ CHdmvClipInfo::Stream* stream = m_ClipInfo.GetStreamByIndex (i);
+ if (stream->m_Type == PRESENTATION_GRAPHICS_STREAM)
+ {
+ m_pFile->AddHdmvPGStream (stream->m_PID, stream->m_LanguageCode);
+ }
+ }
+ }
+
+ m_rtNewStart = m_rtCurrent = 0;
+ m_rtNewStop = m_rtStop = m_rtDuration = 0;
+
+ for(int i = 0; i < countof(m_pFile->m_streams); i++)
+ {
+ POSITION pos = m_pFile->m_streams[i].GetHeadPosition();
+ while(pos)
+ {
+ CMpegSplitterFile::stream& s = m_pFile->m_streams[i].GetNext(pos);
+
+ CAtlArray<CMediaType> mts;
+ mts.Add(s.mt);
+
+ CStringW name = CMpegSplitterFile::CStreamList::ToString(i);
+
+ CAutoPtr<CBaseSplitterOutputPin> pPinOut(DNew CMpegSplitterOutputPin(mts, name, this, this, &hr));
+ if (i == CMpegSplitterFile::subpic)
+ (static_cast<CMpegSplitterOutputPin*>(pPinOut.m_p))->SetMaxShift (_I64_MAX);
+ if(S_OK == AddOutputPin(s, pPinOut))
+ break;
+ }
+ }
+
+ if(m_pFile->IsRandomAccess() && m_pFile->m_rate)
+ {
+ m_rtNewStop = m_rtStop = m_rtDuration = 10000000i64 * m_pFile->GetLength() / m_pFile->m_rate;
+ }
+
+ return m_pOutputs.GetCount() > 0 ? S_OK : E_FAIL;
}
bool CMpegSplitterFilter::DemuxInit()
{
- if(!m_pFile) return(false);
+ if(!m_pFile) return(false);
- m_rtStartOffset = 0;
+ m_rtStartOffset = 0;
- return(true);
+ return(true);
}
void CMpegSplitterFilter::DemuxSeek(REFERENCE_TIME rt)
{
- CAtlList<CMpegSplitterFile::stream>* pMasterStream = m_pFile->GetMasterStream();
-
- if(!pMasterStream)
- {
- ASSERT(0);
- return;
- }
-
- if(m_pFile->IsStreaming())
- {
- m_pFile->Seek(max(0, m_pFile->GetLength() - 100 * 1024));
- m_rtStartOffset = m_pFile->m_rtMin + m_pFile->NextPTS(pMasterStream->GetHead());
- return;
- }
-
- REFERENCE_TIME rtPreroll = 10000000;
-
- if(rt <= rtPreroll || m_rtDuration <= 0)
- {
- m_pFile->Seek(0);
- }
- else
- {
- __int64 len = m_pFile->GetLength();
- __int64 seekpos = (__int64)(1.0 * rt / m_rtDuration * len);
- __int64 minseekpos = _I64_MAX;
-
- REFERENCE_TIME rtmax = rt - rtPreroll;
- REFERENCE_TIME rtmin = rtmax - 5000000;
-
- if(m_rtStartOffset == 0)
- for(int i = 0; i < countof(m_pFile->m_streams) - 1; i++)
- {
- POSITION pos = m_pFile->m_streams[i].GetHeadPosition();
- while(pos)
- {
- DWORD TrackNum = m_pFile->m_streams[i].GetNext(pos);
-
- CBaseSplitterOutputPin* pPin = GetOutputPin(TrackNum);
- if(pPin && pPin->IsConnected())
- {
- m_pFile->Seek(seekpos);
-
- REFERENCE_TIME pdt = _I64_MIN;
-
- for(int j = 0; j < 10; j++)
- {
- REFERENCE_TIME rt = m_pFile->NextPTS(TrackNum);
-
- if(rt < 0) break;
-
- REFERENCE_TIME dt = rt - rtmax;
- if(dt > 0 && dt == pdt) dt = 10000000i64;
-
-
- if(rtmin <= rt && rt <= rtmax || pdt > 0 && dt < 0)
- {
- minseekpos = min(minseekpos, m_pFile->GetPos());
- break;
- }
-
- m_pFile->Seek(m_pFile->GetPos() - (__int64)(1.0 * dt / m_rtDuration * len));
-
- pdt = dt;
- }
- }
- }
- }
-
- if(minseekpos != _I64_MAX)
- {
- seekpos = minseekpos;
- }
- else
- {
- // this file is probably screwed up, try plan B, seek simply by bitrate
-
- rt -= rtPreroll;
- seekpos = (__int64)(1.0 * rt / m_rtDuration * len);
- m_pFile->Seek(seekpos);
- m_rtStartOffset = m_pFile->m_rtMin + m_pFile->NextPTS(pMasterStream->GetHead()) - rt;
- }
-
- m_pFile->Seek(seekpos);
- }
+ CAtlList<CMpegSplitterFile::stream>* pMasterStream = m_pFile->GetMasterStream();
+
+ if(!pMasterStream)
+ {
+ ASSERT(0);
+ return;
+ }
+
+ if(m_pFile->IsStreaming())
+ {
+ m_pFile->Seek(max(0, m_pFile->GetLength() - 100*1024));
+ m_rtStartOffset = m_pFile->m_rtMin + m_pFile->NextPTS(pMasterStream->GetHead());
+ return;
+ }
+
+ REFERENCE_TIME rtPreroll = 10000000;
+
+ if(rt <= rtPreroll || m_rtDuration <= 0)
+ {
+ m_pFile->Seek(0);
+ }
+ else
+ {
+ __int64 len = m_pFile->GetLength();
+ __int64 seekpos = (__int64)(1.0*rt/m_rtDuration*len);
+ __int64 minseekpos = _I64_MAX;
+
+ REFERENCE_TIME rtmax = rt - rtPreroll;
+ REFERENCE_TIME rtmin = rtmax - 5000000;
+
+ if(m_rtStartOffset == 0)
+ for(int i = 0; i < countof(m_pFile->m_streams)-1; i++)
+ {
+ POSITION pos = m_pFile->m_streams[i].GetHeadPosition();
+ while(pos)
+ {
+ DWORD TrackNum = m_pFile->m_streams[i].GetNext(pos);
+
+ CBaseSplitterOutputPin* pPin = GetOutputPin(TrackNum);
+ if(pPin && pPin->IsConnected())
+ {
+ m_pFile->Seek(seekpos);
+
+ REFERENCE_TIME pdt = _I64_MIN;
+
+ for(int j = 0; j < 10; j++)
+ {
+ REFERENCE_TIME rt = m_pFile->NextPTS(TrackNum);
+
+ if(rt < 0) break;
+
+ REFERENCE_TIME dt = rt - rtmax;
+ if(dt > 0 && dt == pdt) dt = 10000000i64;
+
+
+ if(rtmin <= rt && rt <= rtmax || pdt > 0 && dt < 0)
+ {
+ minseekpos = min(minseekpos, m_pFile->GetPos());
+ break;
+ }
+
+ m_pFile->Seek(m_pFile->GetPos() - (__int64)(1.0*dt/m_rtDuration*len));
+
+ pdt = dt;
+ }
+ }
+ }
+ }
+
+ if(minseekpos != _I64_MAX)
+ {
+ seekpos = minseekpos;
+ }
+ else
+ {
+ // this file is probably screwed up, try plan B, seek simply by bitrate
+
+ rt -= rtPreroll;
+ seekpos = (__int64)(1.0*rt/m_rtDuration*len);
+ m_pFile->Seek(seekpos);
+ m_rtStartOffset = m_pFile->m_rtMin + m_pFile->NextPTS(pMasterStream->GetHead()) - rt;
+ }
+
+ m_pFile->Seek(seekpos);
+ }
}
bool CMpegSplitterFilter::DemuxLoop()
{
- REFERENCE_TIME rtStartOffset = m_rtStartOffset ? m_rtStartOffset : m_pFile->m_rtMin;
+ REFERENCE_TIME rtStartOffset = m_rtStartOffset ? m_rtStartOffset : m_pFile->m_rtMin;
- HRESULT hr = S_OK;
- while(SUCCEEDED(hr) && !CheckRequest(NULL))
- {
- if((hr = m_pFile->HasMoreData(1024 * 500)) == S_OK)
- if((hr = DemuxNextPacket(rtStartOffset)) == S_FALSE)
- Sleep(1);
- }
+ HRESULT hr = S_OK;
+ while(SUCCEEDED(hr) && !CheckRequest(NULL))
+ {
+ if((hr = m_pFile->HasMoreData(1024*500)) == S_OK)
+ if((hr = DemuxNextPacket(rtStartOffset)) == S_FALSE)
+ Sleep(1);
+ }
- return(true);
+ return(true);
}
bool CMpegSplitterFilter::BuildPlaylist(LPCTSTR pszFileName, CAtlList<CHdmvClipInfo::PlaylistItem>& Items)
{
- REFERENCE_TIME rtDuration;
- return SUCCEEDED(m_ClipInfo.ReadPlaylist(pszFileName, rtDuration, Items)) ? true : false;
+ REFERENCE_TIME rtDuration;
+ return SUCCEEDED (m_ClipInfo.ReadPlaylist (pszFileName, rtDuration, Items)) ? true : false;
}
// IAMStreamSelect
STDMETHODIMP CMpegSplitterFilter::Count(DWORD* pcStreams)
{
- CheckPointer(pcStreams, E_POINTER);
+ CheckPointer(pcStreams, E_POINTER);
- *pcStreams = 0;
+ *pcStreams = 0;
- for(int i = 0; i < countof(m_pFile->m_streams); i++)
- (*pcStreams) += m_pFile->m_streams[i].GetCount();
+ for(int i = 0; i < countof(m_pFile->m_streams); i++)
+ (*pcStreams) += m_pFile->m_streams[i].GetCount();
- return S_OK;
+ return S_OK;
}
STDMETHODIMP CMpegSplitterFilter::Enable(long lIndex, DWORD dwFlags)
{
- if(!(dwFlags & AMSTREAMSELECTENABLE_ENABLE))
- return E_NOTIMPL;
-
- for(int i = 0, j = 0; i < countof(m_pFile->m_streams); i++)
- {
- int cnt = m_pFile->m_streams[i].GetCount();
-
- if(lIndex >= j && lIndex < j + cnt)
- {
- lIndex -= j;
-
- POSITION pos = m_pFile->m_streams[i].FindIndex(lIndex);
- if(!pos) return E_UNEXPECTED;
-
- CMpegSplitterFile::stream& to = m_pFile->m_streams[i].GetAt(pos);
-
- pos = m_pFile->m_streams[i].GetHeadPosition();
- while(pos)
- {
- CMpegSplitterFile::stream& from = m_pFile->m_streams[i].GetNext(pos);
- if(!GetOutputPin(from)) continue;
-
- HRESULT hr;
- if(FAILED(hr = RenameOutputPin(from, to, &to.mt)))
- return hr;
-
- // Don't rename other pin for Hdmv!
- int iProgram;
- const CHdmvClipInfo::Stream *pClipInfo;
- const CMpegSplitterFile::program* p = m_pFile->FindProgram(to.pid, iProgram, pClipInfo);
-
- if(p != NULL && !m_ClipInfo.IsHdmv() && !m_pFile->IsHdmv())
- {
- for(int k = 0; k < countof(m_pFile->m_streams); k++)
- {
- if(k == i) continue;
-
- pos = m_pFile->m_streams[k].GetHeadPosition();
- while(pos)
- {
- CMpegSplitterFile::stream& from = m_pFile->m_streams[k].GetNext(pos);
- if(!GetOutputPin(from)) continue;
-
- for(int l = 0; l < countof(p->streams); l++)
- {
- if(const CMpegSplitterFile::stream* s = m_pFile->m_streams[k].FindStream(p->streams[l].pid))
- {
- if(from != *s)
- hr = RenameOutputPin(from, *s, &s->mt);
- break;
- }
- }
- }
- }
- }
-
- return S_OK;
- }
- }
-
- j += cnt;
- }
-
- return S_FALSE;
+ if(!(dwFlags & AMSTREAMSELECTENABLE_ENABLE))
+ return E_NOTIMPL;
+
+ for(int i = 0, j = 0; i < countof(m_pFile->m_streams); i++)
+ {
+ int cnt = m_pFile->m_streams[i].GetCount();
+
+ if(lIndex >= j && lIndex < j+cnt)
+ {
+ lIndex -= j;
+
+ POSITION pos = m_pFile->m_streams[i].FindIndex(lIndex);
+ if(!pos) return E_UNEXPECTED;
+
+ CMpegSplitterFile::stream& to = m_pFile->m_streams[i].GetAt(pos);
+
+ pos = m_pFile->m_streams[i].GetHeadPosition();
+ while(pos)
+ {
+ CMpegSplitterFile::stream& from = m_pFile->m_streams[i].GetNext(pos);
+ if(!GetOutputPin(from)) continue;
+
+ HRESULT hr;
+ if(FAILED(hr = RenameOutputPin(from, to, &to.mt)))
+ return hr;
+
+ // Don't rename other pin for Hdmv!
+ int iProgram;
+ const CHdmvClipInfo::Stream *pClipInfo;
+ const CMpegSplitterFile::program* p = m_pFile->FindProgram(to.pid, iProgram, pClipInfo);
+
+ if(p!=NULL && !m_ClipInfo.IsHdmv() && !m_pFile->IsHdmv())
+ {
+ for(int k = 0; k < countof(m_pFile->m_streams); k++)
+ {
+ if(k == i) continue;
+
+ pos = m_pFile->m_streams[k].GetHeadPosition();
+ while(pos)
+ {
+ CMpegSplitterFile::stream& from = m_pFile->m_streams[k].GetNext(pos);
+ if(!GetOutputPin(from)) continue;
+
+ for(int l = 0; l < countof(p->streams); l++)
+ {
+ if(const CMpegSplitterFile::stream* s = m_pFile->m_streams[k].FindStream(p->streams[l].pid))
+ {
+ if(from != *s)
+ hr = RenameOutputPin(from, *s, &s->mt);
+ break;
+ }
+ }
+ }
+ }
+ }
+
+ return S_OK;
+ }
+ }
+
+ j += cnt;
+ }
+
+ return S_FALSE;
}
template <typename t_CType>
t_CType GetFormatHelper(t_CType &_pInfo, const CMediaType *_pFormat)
{
- ASSERT(_pFormat->cbFormat >= sizeof(*_pInfo));
- _pInfo = (t_CType)_pFormat->pbFormat;
- return _pInfo;
+ ASSERT(_pFormat->cbFormat >= sizeof(*_pInfo));
+ _pInfo = (t_CType)_pFormat->pbFormat;
+ return _pInfo;
}
static int GetHighestBitSet32(unsigned long _Value)
{
- unsigned long Ret;
- unsigned char bNonZero = _BitScanReverse(&Ret, _Value);
- if(bNonZero)
- return Ret;
- else
- return -1;
+ unsigned long Ret;
+ unsigned char bNonZero = _BitScanReverse(&Ret, _Value);
+ if (bNonZero)
+ return Ret;
+ else
+ return -1;
}
CString FormatBitrate(double _Bitrate)
{
- CString Temp;
- if(_Bitrate > 20000000) // More than 2 mbit
- Temp.Format(L"%.2f mbit/s", double(_Bitrate) / 1000000.0);
- else
- Temp.Format(L"%.1f kbit/s", double(_Bitrate) / 1000.0);
+ CString Temp;
+ if (_Bitrate > 20000000) // More than 2 mbit
+ Temp.Format(L"%.2f mbit/s", double(_Bitrate)/1000000.0);
+ else
+ Temp.Format(L"%.1f kbit/s", double(_Bitrate)/1000.0);
- return Temp;
+ return Temp;
}
-CString FormatString(const wchar_t *pszFormat, ...)
+CString FormatString(const wchar_t *pszFormat, ... )
{
- CString Temp;
- ATLASSERT(AtlIsValidString(pszFormat));
+ CString Temp;
+ ATLASSERT( AtlIsValidString( pszFormat ) );
- va_list argList;
- va_start(argList, pszFormat);
- Temp.FormatV(pszFormat, argList);
- va_end(argList);
+ va_list argList;
+ va_start( argList, pszFormat );
+ Temp.FormatV( pszFormat, argList );
+ va_end( argList );
- return Temp;
+ return Temp;
}
LONGLONG GetMediaTypeQuality(const CMediaType *_pMediaType, int _PresentationFormat)
{
- if(_pMediaType->formattype == FORMAT_WaveFormatEx)
- {
- __int64 Ret = 0;
-
- const WAVEFORMATEX *pInfo = GetFormatHelper(pInfo, _pMediaType);
- int TypePriority = 0;
-
- if(_pMediaType->subtype == MEDIASUBTYPE_DVD_LPCM_AUDIO)
- {
- TypePriority = 12;
- }
- else if(_pMediaType->subtype == MEDIASUBTYPE_HDMV_LPCM_AUDIO)
- {
- TypePriority = 12;
- }
- else
- {
- if(_PresentationFormat == AUDIO_STREAM_DTS_HD_MASTER_AUDIO)
- TypePriority = 12;
- else if(_PresentationFormat == AUDIO_STREAM_DTS_HD)
- TypePriority = 11;
- else if(_PresentationFormat == AUDIO_STREAM_AC3_TRUE_HD)
- TypePriority = 12;
- else if(_PresentationFormat == AUDIO_STREAM_AC3_PLUS)
- TypePriority = 10;
- else
- {
- switch(pInfo->wFormatTag)
- {
- case WAVE_FORMAT_PS2_PCM:
- {
- TypePriority = 12;
- }
- break;
- case WAVE_FORMAT_PS2_ADPCM:
- {
- TypePriority = 4;
- }
- break;
- case WAVE_FORMAT_DVD_DTS:
- {
- TypePriority = 9;
- }
- break;
- case WAVE_FORMAT_DOLBY_AC3:
- {
- TypePriority = 8;
- }
- break;
- case WAVE_FORMAT_AAC:
- {
- TypePriority = 7;
- }
- break;
- case WAVE_FORMAT_MP3:
- {
- TypePriority = 6;
- }
- break;
- case WAVE_FORMAT_MPEG:
- {
- TypePriority = 5;
- }
- break;
- }
- }
- }
-
- Ret += __int64(TypePriority) * 100000000i64 * 1000000000i64;
-
- Ret += __int64(pInfo->nChannels) * 1000000i64 * 1000000000i64;
- Ret += __int64(pInfo->nSamplesPerSec) * 10i64 * 1000000000i64;
- Ret += __int64(pInfo->wBitsPerSample) * 10000000i64;
- Ret += __int64(pInfo->nAvgBytesPerSec);
-
- return Ret;
- }
-
- return 0;
+ if (_pMediaType->formattype == FORMAT_WaveFormatEx)
+ {
+ __int64 Ret = 0;
+
+ const WAVEFORMATEX *pInfo = GetFormatHelper(pInfo, _pMediaType);
+ int TypePriority = 0;
+
+ if (_pMediaType->subtype == MEDIASUBTYPE_DVD_LPCM_AUDIO)
+ {
+ TypePriority = 12;
+ }
+ else if (_pMediaType->subtype == MEDIASUBTYPE_HDMV_LPCM_AUDIO)
+ {
+ TypePriority = 12;
+ }
+ else
+ {
+ if (_PresentationFormat == AUDIO_STREAM_DTS_HD_MASTER_AUDIO)
+ TypePriority = 12;
+ else if (_PresentationFormat == AUDIO_STREAM_DTS_HD)
+ TypePriority = 11;
+ else if (_PresentationFormat == AUDIO_STREAM_AC3_TRUE_HD)
+ TypePriority = 12;
+ else if (_PresentationFormat == AUDIO_STREAM_AC3_PLUS)
+ TypePriority = 10;
+ else
+ {
+ switch (pInfo->wFormatTag)
+ {
+ case WAVE_FORMAT_PS2_PCM:
+ {
+ TypePriority = 12;
+ }
+ break;
+ case WAVE_FORMAT_PS2_ADPCM:
+ {
+ TypePriority = 4;
+ }
+ break;
+ case WAVE_FORMAT_DVD_DTS:
+ {
+ TypePriority = 9;
+ }
+ break;
+ case WAVE_FORMAT_DOLBY_AC3:
+ {
+ TypePriority = 8;
+ }
+ break;
+ case WAVE_FORMAT_AAC:
+ {
+ TypePriority = 7;
+ }
+ break;
+ case WAVE_FORMAT_MP3:
+ {
+ TypePriority = 6;
+ }
+ break;
+ case WAVE_FORMAT_MPEG:
+ {
+ TypePriority = 5;
+ }
+ break;
+ }
+ }
+ }
+
+ Ret += __int64(TypePriority) * 100000000i64 * 1000000000i64;
+
+ Ret += __int64(pInfo->nChannels) * 1000000i64 * 1000000000i64;
+ Ret += __int64(pInfo->nSamplesPerSec) * 10i64 * 1000000000i64;
+ Ret += __int64(pInfo->wBitsPerSample) * 10000000i64;
+ Ret += __int64(pInfo->nAvgBytesPerSec);
+
+ return Ret;
+ }
+
+ return 0;
}
bool CMpegSplitterFile::stream::operator < (const stream &_Other) const
{
- if(mt.majortype == MEDIATYPE_Audio && _Other.mt.majortype == MEDIATYPE_Audio)
- {
- int iProgram0;
- const CHdmvClipInfo::Stream *pClipInfo0;
- const CMpegSplitterFile::program * pProgram0 = m_pFile->FindProgram(pid, iProgram0, pClipInfo0);
- int StreamType0 = pClipInfo0 ? pClipInfo0->m_Type : pProgram0 ? pProgram0->streams[iProgram0].type : 0;
- int iProgram1;
- const CHdmvClipInfo::Stream *pClipInfo1;
- const CMpegSplitterFile::program * pProgram1 = m_pFile->FindProgram(_Other.pid, iProgram1, pClipInfo1);
- int StreamType1 = pClipInfo1 ? pClipInfo1->m_Type : pProgram1 ? pProgram1->streams[iProgram1].type : 0;
-
- if(mt.formattype == FORMAT_WaveFormatEx && _Other.mt.formattype != FORMAT_WaveFormatEx)
- return true;
- if(mt.formattype != FORMAT_WaveFormatEx && _Other.mt.formattype == FORMAT_WaveFormatEx)
- return false;
-
- LONGLONG Quality0 = GetMediaTypeQuality(&mt, StreamType0);
- LONGLONG Quality1 = GetMediaTypeQuality(&_Other.mt, StreamType1);
- if(Quality0 > Quality1)
- return true;
- if(Quality0 < Quality1)
- return false;
- }
- DWORD DefaultFirst = *this;
- DWORD DefaultSecond = _Other;
- return DefaultFirst < DefaultSecond;
+ if (mt.majortype == MEDIATYPE_Audio && _Other.mt.majortype == MEDIATYPE_Audio)
+ {
+ int iProgram0;
+ const CHdmvClipInfo::Stream *pClipInfo0;
+ const CMpegSplitterFile::program * pProgram0 = m_pFile->FindProgram(pid, iProgram0, pClipInfo0);
+ int StreamType0 = pClipInfo0 ? pClipInfo0->m_Type : pProgram0 ? pProgram0->streams[iProgram0].type : 0;
+ int iProgram1;
+ const CHdmvClipInfo::Stream *pClipInfo1;
+ const CMpegSplitterFile::program * pProgram1 = m_pFile->FindProgram(_Other.pid, iProgram1, pClipInfo1);
+ int StreamType1 = pClipInfo1 ? pClipInfo1->m_Type : pProgram1 ? pProgram1->streams[iProgram1].type : 0;
+
+ if (mt.formattype == FORMAT_WaveFormatEx && _Other.mt.formattype != FORMAT_WaveFormatEx)
+ return true;
+ if (mt.formattype != FORMAT_WaveFormatEx && _Other.mt.formattype == FORMAT_WaveFormatEx)
+ return false;
+
+ LONGLONG Quality0 = GetMediaTypeQuality(&mt, StreamType0);
+ LONGLONG Quality1 = GetMediaTypeQuality(&_Other.mt, StreamType1);
+ if (Quality0 > Quality1)
+ return true;
+ if (Quality0 < Quality1)
+ return false;
+ }
+ DWORD DefaultFirst = *this;
+ DWORD DefaultSecond = _Other;
+ return DefaultFirst < DefaultSecond;
}
CString GetMediaTypeDesc(const CMediaType *_pMediaType, const CHdmvClipInfo::Stream *pClipInfo, int _PresentationType)
{
- const WCHAR *pPresentationDesc = NULL;
-
- if(pClipInfo)
- pPresentationDesc = StreamTypeToName(pClipInfo->m_Type);
- else
- pPresentationDesc = StreamTypeToName((PES_STREAM_TYPE)_PresentationType);
-
- CString MajorType;
- CAtlList<CString> Infos;
-
- if(_pMediaType->majortype == MEDIATYPE_Video)
- {
- MajorType = "Video";
-
- if(pClipInfo)
- {
- CString name = ISO6392ToLanguage(pClipInfo->m_LanguageCode);
-
- if(!name.IsEmpty())
- Infos.AddTail(name);
- }
-
- const VIDEOINFOHEADER *pVideoInfo = NULL;
- const VIDEOINFOHEADER2 *pVideoInfo2 = NULL;
-
- if(_pMediaType->formattype == FORMAT_MPEGVideo)
- {
- Infos.AddTail(L"MPEG");
-
- const MPEG1VIDEOINFO *pInfo = GetFormatHelper(pInfo, _pMediaType);
-
- pVideoInfo = &pInfo->hdr;
-
- }
- else if(_pMediaType->formattype == FORMAT_MPEG2_VIDEO)
- {
- const MPEG2VIDEOINFO *pInfo = GetFormatHelper(pInfo, _pMediaType);
-
- pVideoInfo2 = &pInfo->hdr;
-
- bool bIsAVC = false;
-
- if(pInfo->hdr.bmiHeader.biCompression == '1CVA')
- {
- bIsAVC = true;
- Infos.AddTail(L"AVC (H.264)");
- }
- else if(pInfo->hdr.bmiHeader.biCompression == 0)
- Infos.AddTail(L"MPEG2");
- else
- {
- WCHAR Temp[5];
- memset(Temp, 0, sizeof(Temp));
- Temp[0] = (pInfo->hdr.bmiHeader.biCompression >> 0) & 0xFF;
- Temp[1] = (pInfo->hdr.bmiHeader.biCompression >> 0) & 0xFF;
- Temp[2] = (pInfo->hdr.bmiHeader.biCompression >> 0) & 0xFF;
- Temp[3] = (pInfo->hdr.bmiHeader.biCompression >> 0) & 0xFF;
- Infos.AddTail(Temp);
- }
-
- switch(pInfo->dwProfile)
- {
- case AM_MPEG2Profile_Simple:
- Infos.AddTail(L"Simple Profile");
- break;
- case AM_MPEG2Profile_Main:
- Infos.AddTail(L"Main Profile");
- break;
- case AM_MPEG2Profile_SNRScalable:
- Infos.AddTail(L"SNR Scalable Profile");
- break;
- case AM_MPEG2Profile_SpatiallyScalable:
- Infos.AddTail(L"Spatially Scalable Profile");
- break;
- case AM_MPEG2Profile_High:
- Infos.AddTail(L"High Profile");
- break;
- default:
- if(pInfo->dwProfile)
- {
- if(bIsAVC)
- {
- switch(pInfo->dwProfile)
- {
- case 44:
- Infos.AddTail(L"CAVLC Profile");
- break;
- case 66:
- Infos.AddTail(L"Baseline Profile");
- break;
- case 77:
- Infos.AddTail(L"Main Profile");
- break;
- case 88:
- Infos.AddTail(L"Extended Profile");
- break;
- case 100:
- Infos.AddTail(L"High Profile");
- break;
- case 110:
- Infos.AddTail(L"High 10 Profile");
- break;
- case 122:
- Infos.AddTail(L"High 4:2:2 Profile");
- break;
- case 244:
- Infos.AddTail(L"High 4:4:4 Profile");
- break;
-
- default:
- Infos.AddTail(FormatString(L"Profile %d", pInfo->dwProfile));
- break;
- }
- }
- else
- Infos.AddTail(FormatString(L"Profile %d", pInfo->dwProfile));
- }
- break;
- }
-
- switch(pInfo->dwLevel)
- {
- case AM_MPEG2Level_Low:
- Infos.AddTail(L"Low Level");
- break;
- case AM_MPEG2Level_Main:
- Infos.AddTail(L"Main Level");
- break;
- case AM_MPEG2Level_High1440:
- Infos.AddTail(L"High1440 Level");
- break;
- case AM_MPEG2Level_High:
- Infos.AddTail(L"High Level");
- break;
- default:
- if(pInfo->dwLevel)
- {
- if(bIsAVC)
- Infos.AddTail(FormatString(L"Level %1.1f", double(pInfo->dwLevel) / 10.0));
- else
- Infos.AddTail(FormatString(L"Level %d", pInfo->dwLevel));
- }
- break;
- }
- }
- else if(_pMediaType->formattype == FORMAT_VIDEOINFO2)
- {
- const VIDEOINFOHEADER2 *pInfo = GetFormatHelper(pInfo, _pMediaType);
-
- pVideoInfo2 = pInfo;
- bool bIsVC1 = false;
-
- DWORD CodecType = pInfo->bmiHeader.biCompression;
- if(CodecType == '1CVW')
- {
- bIsVC1 = true;
- Infos.AddTail(L"VC-1");
- }
- else if(CodecType)
- {
- WCHAR Temp[5];
- memset(Temp, 0, sizeof(Temp));
- Temp[0] = (CodecType >> 0) & 0xFF;
- Temp[1] = (CodecType >> 0) & 0xFF;
- Temp[2] = (CodecType >> 0) & 0xFF;
- Temp[3] = (CodecType >> 0) & 0xFF;
- Infos.AddTail(Temp);
- }
- }
- else if(_pMediaType->subtype == MEDIASUBTYPE_DVD_SUBPICTURE)
- {
- Infos.AddTail(L"DVD Sub Picture");
- }
- else if(_pMediaType->subtype == MEDIASUBTYPE_SVCD_SUBPICTURE)
- {
- Infos.AddTail(L"SVCD Sub Picture");
- }
- else if(_pMediaType->subtype == MEDIASUBTYPE_CVD_SUBPICTURE)
- {
- Infos.AddTail(L"CVD Sub Picture");
- }
-
- if(pVideoInfo2)
- {
- if(pVideoInfo2->bmiHeader.biWidth && pVideoInfo2->bmiHeader.biHeight)
- Infos.AddTail(FormatString(L"%dx%d", pVideoInfo2->bmiHeader.biWidth, pVideoInfo2->bmiHeader.biHeight));
- if(pVideoInfo2->AvgTimePerFrame)
- Infos.AddTail(FormatString(L"%.3f fps", 10000000.0 / double(pVideoInfo2->AvgTimePerFrame)));
- if(pVideoInfo2->dwBitRate)
- Infos.AddTail(FormatBitrate(pVideoInfo2->dwBitRate));
- }
- else if(pVideoInfo)
- {
- if(pVideoInfo->bmiHeader.biWidth && pVideoInfo->bmiHeader.biHeight)
- Infos.AddTail(FormatString(L"%dx%d", pVideoInfo->bmiHeader.biWidth, pVideoInfo->bmiHeader.biHeight));
- if(pVideoInfo->AvgTimePerFrame)
- Infos.AddTail(FormatString(L"%.3f fps", 10000000.0 / double(pVideoInfo->AvgTimePerFrame)));
- if(pVideoInfo->dwBitRate)
- Infos.AddTail(FormatBitrate(pVideoInfo->dwBitRate));
- }
-
- }
- else if(_pMediaType->majortype == MEDIATYPE_Audio)
- {
- MajorType = "Audio";
- if(pClipInfo)
- {
- CString name = ISO6392ToLanguage(pClipInfo->m_LanguageCode);
- if(!name.IsEmpty())
- Infos.AddTail(name);
- }
- if(_pMediaType->formattype == FORMAT_WaveFormatEx)
- {
- const WAVEFORMATEX *pInfo = GetFormatHelper(pInfo, _pMediaType);
-
- if(_pMediaType->subtype == MEDIASUBTYPE_DVD_LPCM_AUDIO)
- {
- Infos.AddTail(L"DVD LPCM");
- }
- else if(_pMediaType->subtype == MEDIASUBTYPE_HDMV_LPCM_AUDIO)
- {
- const WAVEFORMATEX_HDMV_LPCM *pInfoHDMV = GetFormatHelper(pInfoHDMV, _pMediaType);
- Infos.AddTail(L"HDMV LPCM");
- }
- else
- {
- switch(pInfo->wFormatTag)
- {
- case WAVE_FORMAT_PS2_PCM:
- {
- Infos.AddTail(L"PS2 PCM");
- }
- break;
- case WAVE_FORMAT_PS2_ADPCM:
- {
- Infos.AddTail(L"PS2 ADPCM");
- }
- break;
- case WAVE_FORMAT_DVD_DTS:
- {
- if(pPresentationDesc)
- Infos.AddTail(pPresentationDesc);
- else
- Infos.AddTail(L"DTS");
- }
- break;
- case WAVE_FORMAT_DOLBY_AC3:
- {
- if(pPresentationDesc)
- Infos.AddTail(pPresentationDesc);
- else
- Infos.AddTail(L"Dolby Digital");
- }
- break;
- case WAVE_FORMAT_AAC:
- {
- Infos.AddTail(L"AAC");
- }
- break;
- case WAVE_FORMAT_MP3:
- {
- Infos.AddTail(L"MP3");
- }
- break;
- case WAVE_FORMAT_MPEG:
- {
- const MPEG1WAVEFORMAT* pInfoMPEG1 = GetFormatHelper(pInfoMPEG1, _pMediaType);
-
- int layer = GetHighestBitSet32(pInfoMPEG1->fwHeadLayer) + 1;
- Infos.AddTail(FormatString(L"MPEG1 - Layer %d", layer));
- }
- break;
- }
- }
-
- if(pClipInfo && (pClipInfo->m_SampleRate == BDVM_SampleRate_48_192 || pClipInfo->m_SampleRate == BDVM_SampleRate_48_96))
- {
- switch(pClipInfo->m_SampleRate)
- {
- case BDVM_SampleRate_48_192:
- Infos.AddTail(FormatString(L"192(48) kHz"));
- break;
- case BDVM_SampleRate_48_96:
- Infos.AddTail(FormatString(L"96(48) kHz"));
- break;
- }
- }
- else if(pInfo->nSamplesPerSec)
- Infos.AddTail(FormatString(L"%.1f kHz", double(pInfo->nSamplesPerSec) / 1000.0));
- if(pInfo->nChannels)
- Infos.AddTail(FormatString(L"%d chn", pInfo->nChannels));
- if(pInfo->wBitsPerSample)
- Infos.AddTail(FormatString(L"%d bit", pInfo->wBitsPerSample));
- if(pInfo->nAvgBytesPerSec)
- Infos.AddTail(FormatBitrate(pInfo->nAvgBytesPerSec * 8));
-
- }
- }
- else if(_pMediaType->majortype == MEDIATYPE_Subtitle)
- {
- MajorType = "Subtitle";
-
- if(pPresentationDesc)
- Infos.AddTail(pPresentationDesc);
-
- if(_pMediaType->cbFormat == sizeof(SUBTITLEINFO))
- {
- const SUBTITLEINFO *pInfo = GetFormatHelper(pInfo, _pMediaType);
- CString name = ISO6392ToLanguage(pInfo->IsoLang);
-
- if(pInfo->TrackName[0])
- Infos.AddHead(pInfo->TrackName);
- if(!name.IsEmpty())
- Infos.AddHead(name);
- }
- else
- {
- if(pClipInfo)
- {
- CString name = ISO6392ToLanguage(pClipInfo->m_LanguageCode);
- if(!name.IsEmpty())
- Infos.AddHead(name);
- }
- }
- }
-
- if(!Infos.IsEmpty())
- {
- CString Ret;
-
- Ret += MajorType;
- Ret += " - ";
-
- bool bFirst = true;
-
- for(POSITION pos = Infos.GetHeadPosition(); pos; Infos.GetNext(pos))
- {
- CString& String = Infos.GetAt(pos);
-
- if(bFirst)
- Ret += String;
- else
- Ret += L", " + String;
-
- bFirst = false;
- }
-
- return Ret;
- }
- return CString();
+ const WCHAR *pPresentationDesc = NULL;
+
+ if (pClipInfo)
+ pPresentationDesc = StreamTypeToName(pClipInfo->m_Type);
+ else
+ pPresentationDesc = StreamTypeToName((PES_STREAM_TYPE)_PresentationType);
+
+ CString MajorType;
+ CAtlList<CString> Infos;
+
+ if (_pMediaType->majortype == MEDIATYPE_Video)
+ {
+ MajorType = "Video";
+
+ if (pClipInfo)
+ {
+ CString name = ISO6392ToLanguage(pClipInfo->m_LanguageCode);
+
+ if (!name.IsEmpty())
+ Infos.AddTail(name);
+ }
+
+ const VIDEOINFOHEADER *pVideoInfo = NULL;
+ const VIDEOINFOHEADER2 *pVideoInfo2 = NULL;
+
+ if (_pMediaType->formattype == FORMAT_MPEGVideo)
+ {
+ Infos.AddTail(L"MPEG");
+
+ const MPEG1VIDEOINFO *pInfo = GetFormatHelper(pInfo, _pMediaType);
+
+ pVideoInfo = &pInfo->hdr;
+
+ }
+ else if (_pMediaType->formattype == FORMAT_MPEG2_VIDEO)
+ {
+ const MPEG2VIDEOINFO *pInfo = GetFormatHelper(pInfo, _pMediaType);
+
+ pVideoInfo2 = &pInfo->hdr;
+
+ bool bIsAVC = false;
+
+ if (pInfo->hdr.bmiHeader.biCompression == '1CVA')
+ {
+ bIsAVC = true;
+ Infos.AddTail(L"AVC (H.264)");
+ }
+ else if (pInfo->hdr.bmiHeader.biCompression == 0)
+ Infos.AddTail(L"MPEG2");
+ else
+ {
+ WCHAR Temp[5];
+ memset(Temp, 0, sizeof(Temp));
+ Temp[0] = (pInfo->hdr.bmiHeader.biCompression >> 0) & 0xFF;
+ Temp[1] = (pInfo->hdr.bmiHeader.biCompression >> 0) & 0xFF;
+ Temp[2] = (pInfo->hdr.bmiHeader.biCompression >> 0) & 0xFF;
+ Temp[3] = (pInfo->hdr.bmiHeader.biCompression >> 0) & 0xFF;
+ Infos.AddTail(Temp);
+ }
+
+ switch (pInfo->dwProfile)
+ {
+ case AM_MPEG2Profile_Simple: Infos.AddTail(L"Simple Profile"); break;
+ case AM_MPEG2Profile_Main: Infos.AddTail(L"Main Profile"); break;
+ case AM_MPEG2Profile_SNRScalable: Infos.AddTail(L"SNR Scalable Profile"); break;
+ case AM_MPEG2Profile_SpatiallyScalable: Infos.AddTail(L"Spatially Scalable Profile"); break;
+ case AM_MPEG2Profile_High: Infos.AddTail(L"High Profile"); break;
+ default:
+ if (pInfo->dwProfile)
+ {
+ if (bIsAVC)
+ {
+ switch (pInfo->dwProfile)
+ {
+ case 44: Infos.AddTail(L"CAVLC Profile"); break;
+ case 66: Infos.AddTail(L"Baseline Profile"); break;
+ case 77: Infos.AddTail(L"Main Profile"); break;
+ case 88: Infos.AddTail(L"Extended Profile"); break;
+ case 100: Infos.AddTail(L"High Profile"); break;
+ case 110: Infos.AddTail(L"High 10 Profile"); break;
+ case 122: Infos.AddTail(L"High 4:2:2 Profile"); break;
+ case 244: Infos.AddTail(L"High 4:4:4 Profile"); break;
+
+ default: Infos.AddTail(FormatString(L"Profile %d", pInfo->dwProfile)); break;
+ }
+ }
+ else
+ Infos.AddTail(FormatString(L"Profile %d", pInfo->dwProfile));
+ }
+ break;
+ }
+
+ switch (pInfo->dwLevel)
+ {
+ case AM_MPEG2Level_Low: Infos.AddTail(L"Low Level"); break;
+ case AM_MPEG2Level_Main: Infos.AddTail(L"Main Level"); break;
+ case AM_MPEG2Level_High1440: Infos.AddTail(L"High1440 Level"); break;
+ case AM_MPEG2Level_High: Infos.AddTail(L"High Level"); break;
+ default:
+ if (pInfo->dwLevel)
+ {
+ if (bIsAVC)
+ Infos.AddTail(FormatString(L"Level %1.1f", double(pInfo->dwLevel)/10.0));
+ else
+ Infos.AddTail(FormatString(L"Level %d", pInfo->dwLevel));
+ }
+ break;
+ }
+ }
+ else if (_pMediaType->formattype == FORMAT_VIDEOINFO2)
+ {
+ const VIDEOINFOHEADER2 *pInfo = GetFormatHelper(pInfo, _pMediaType);
+
+ pVideoInfo2 = pInfo;
+ bool bIsVC1 = false;
+
+ DWORD CodecType = pInfo->bmiHeader.biCompression;
+ if (CodecType == '1CVW')
+ {
+ bIsVC1 = true;
+ Infos.AddTail(L"VC-1");
+ }
+ else if (CodecType)
+ {
+ WCHAR Temp[5];
+ memset(Temp, 0, sizeof(Temp));
+ Temp[0] = (CodecType >> 0) & 0xFF;
+ Temp[1] = (CodecType >> 0) & 0xFF;
+ Temp[2] = (CodecType >> 0) & 0xFF;
+ Temp[3] = (CodecType >> 0) & 0xFF;
+ Infos.AddTail(Temp);
+ }
+ }
+ else if (_pMediaType->subtype == MEDIASUBTYPE_DVD_SUBPICTURE)
+ {
+ Infos.AddTail(L"DVD Sub Picture");
+ }
+ else if (_pMediaType->subtype == MEDIASUBTYPE_SVCD_SUBPICTURE)
+ {
+ Infos.AddTail(L"SVCD Sub Picture");
+ }
+ else if (_pMediaType->subtype == MEDIASUBTYPE_CVD_SUBPICTURE)
+ {
+ Infos.AddTail(L"CVD Sub Picture");
+ }
+
+ if (pVideoInfo2)
+ {
+ if (pVideoInfo2->bmiHeader.biWidth && pVideoInfo2->bmiHeader.biHeight)
+ Infos.AddTail(FormatString(L"%dx%d", pVideoInfo2->bmiHeader.biWidth, pVideoInfo2->bmiHeader.biHeight));
+ if (pVideoInfo2->AvgTimePerFrame)
+ Infos.AddTail(FormatString(L"%.3f fps", 10000000.0/double(pVideoInfo2->AvgTimePerFrame)));
+ if (pVideoInfo2->dwBitRate)
+ Infos.AddTail(FormatBitrate(pVideoInfo2->dwBitRate));
+ }
+ else if (pVideoInfo)
+ {
+ if (pVideoInfo->bmiHeader.biWidth && pVideoInfo->bmiHeader.biHeight)
+ Infos.AddTail(FormatString(L"%dx%d", pVideoInfo->bmiHeader.biWidth, pVideoInfo->bmiHeader.biHeight));
+ if (pVideoInfo->AvgTimePerFrame)
+ Infos.AddTail(FormatString(L"%.3f fps", 10000000.0/double(pVideoInfo->AvgTimePerFrame)));
+ if (pVideoInfo->dwBitRate)
+ Infos.AddTail(FormatBitrate(pVideoInfo->dwBitRate));
+ }
+
+ }
+ else if (_pMediaType->majortype == MEDIATYPE_Audio)
+ {
+ MajorType = "Audio";
+ if (pClipInfo)
+ {
+ CString name = ISO6392ToLanguage(pClipInfo->m_LanguageCode);
+ if (!name.IsEmpty())
+ Infos.AddTail(name);
+ }
+ if (_pMediaType->formattype == FORMAT_WaveFormatEx)
+ {
+ const WAVEFORMATEX *pInfo = GetFormatHelper(pInfo, _pMediaType);
+
+ if (_pMediaType->subtype == MEDIASUBTYPE_DVD_LPCM_AUDIO)
+ {
+ Infos.AddTail(L"DVD LPCM");
+ }
+ else if (_pMediaType->subtype == MEDIASUBTYPE_HDMV_LPCM_AUDIO)
+ {
+ const WAVEFORMATEX_HDMV_LPCM *pInfoHDMV = GetFormatHelper(pInfoHDMV, _pMediaType);
+ Infos.AddTail(L"HDMV LPCM");
+ }
+ else
+ {
+ switch (pInfo->wFormatTag)
+ {
+ case WAVE_FORMAT_PS2_PCM:
+ {
+ Infos.AddTail(L"PS2 PCM");
+ }
+ break;
+ case WAVE_FORMAT_PS2_ADPCM:
+ {
+ Infos.AddTail(L"PS2 ADPCM");
+ }
+ break;
+ case WAVE_FORMAT_DVD_DTS:
+ {
+ if (pPresentationDesc)
+ Infos.AddTail(pPresentationDesc);
+ else
+ Infos.AddTail(L"DTS");
+ }
+ break;
+ case WAVE_FORMAT_DOLBY_AC3:
+ {
+ if (pPresentationDesc)
+ Infos.AddTail(pPresentationDesc);
+ else
+ Infos.AddTail(L"Dolby Digital");
+ }
+ break;
+ case WAVE_FORMAT_AAC:
+ {
+ Infos.AddTail(L"AAC");
+ }
+ break;
+ case WAVE_FORMAT_MP3:
+ {
+ Infos.AddTail(L"MP3");
+ }
+ break;
+ case WAVE_FORMAT_MPEG:
+ {
+ const MPEG1WAVEFORMAT* pInfoMPEG1 = GetFormatHelper(pInfoMPEG1, _pMediaType);
+
+ int layer = GetHighestBitSet32(pInfoMPEG1->fwHeadLayer) + 1;
+ Infos.AddTail(FormatString(L"MPEG1 - Layer %d", layer));
+ }
+ break;
+ }
+ }
+
+ if (pClipInfo && (pClipInfo->m_SampleRate == BDVM_SampleRate_48_192 || pClipInfo->m_SampleRate == BDVM_SampleRate_48_96))
+ {
+ switch (pClipInfo->m_SampleRate)
+ {
+ case BDVM_SampleRate_48_192:
+ Infos.AddTail(FormatString(L"192(48) kHz"));
+ break;
+ case BDVM_SampleRate_48_96:
+ Infos.AddTail(FormatString(L"96(48) kHz"));
+ break;
+ }
+ }
+ else if (pInfo->nSamplesPerSec)
+ Infos.AddTail(FormatString(L"%.1f kHz", double(pInfo->nSamplesPerSec)/1000.0));
+ if (pInfo->nChannels)
+ Infos.AddTail(FormatString(L"%d chn", pInfo->nChannels));
+ if (pInfo->wBitsPerSample)
+ Infos.AddTail(FormatString(L"%d bit", pInfo->wBitsPerSample));
+ if (pInfo->nAvgBytesPerSec)
+ Infos.AddTail(FormatBitrate(pInfo->nAvgBytesPerSec * 8));
+
+ }
+ }
+ else if (_pMediaType->majortype == MEDIATYPE_Subtitle)
+ {
+ MajorType = "Subtitle";
+
+ if (pPresentationDesc)
+ Infos.AddTail(pPresentationDesc);
+
+ if (_pMediaType->cbFormat == sizeof(SUBTITLEINFO))
+ {
+ const SUBTITLEINFO *pInfo = GetFormatHelper(pInfo, _pMediaType);
+ CString name = ISO6392ToLanguage(pInfo->IsoLang);
+
+ if (pInfo->TrackName[0])
+ Infos.AddHead(pInfo->TrackName);
+ if (!name.IsEmpty())
+ Infos.AddHead(name);
+ }
+ else
+ {
+ if (pClipInfo)
+ {
+ CString name = ISO6392ToLanguage(pClipInfo->m_LanguageCode);
+ if (!name.IsEmpty())
+ Infos.AddHead(name);
+ }
+ }
+ }
+
+ if (!Infos.IsEmpty())
+ {
+ CString Ret;
+
+ Ret += MajorType;
+ Ret += " - ";
+
+ bool bFirst = true;
+
+ for(POSITION pos = Infos.GetHeadPosition(); pos; Infos.GetNext(pos))
+ {
+ CString& String = Infos.GetAt(pos);
+
+ if (bFirst)
+ Ret += String;
+ else
+ Ret += L", " + String;
+
+ bFirst = false;
+ }
+
+ return Ret;
+ }
+ return CString();
}
STDMETHODIMP CMpegSplitterFilter::Info(long lIndex, AM_MEDIA_TYPE** ppmt, DWORD* pdwFlags, LCID* plcid, DWORD* pdwGroup, WCHAR** ppszName, IUnknown** ppObject, IUnknown** ppUnk)
{
- for(int i = 0, j = 0; i < countof(m_pFile->m_streams); i++)
- {
- int cnt = m_pFile->m_streams[i].GetCount();
-
- if(lIndex >= j && lIndex < j + cnt)
- {
- lIndex -= j;
-
- POSITION pos = m_pFile->m_streams[i].FindIndex(lIndex);
- if(!pos) return E_UNEXPECTED;
-
- CMpegSplitterFile::stream& s = m_pFile->m_streams[i].GetAt(pos);
- CHdmvClipInfo::Stream* pStream = m_ClipInfo.FindStream(s.pid);
-
- if(ppmt) *ppmt = CreateMediaType(&s.mt);
- if(pdwFlags) *pdwFlags = GetOutputPin(s) ? (AMSTREAMSELECTINFO_ENABLED | AMSTREAMSELECTINFO_EXCLUSIVE) : 0;
- if(plcid) *plcid = pStream ? pStream->m_LCID : 0;
- if(pdwGroup) *pdwGroup = i;
- if(ppObject) *ppObject = NULL;
- if(ppUnk) *ppUnk = NULL;
-
-
- if(ppszName)
- {
- CStringW name = CMpegSplitterFile::CStreamList::ToString(i);
-
- CStringW str;
-
- if(i == CMpegSplitterFile::subpic && s.pid == NO_SUBTITLE_PID)
- {
- str = _T("No subtitles");
- *plcid = LCID_NOSUBTITLES;
- }
- else
- {
- int iProgram;
- const CHdmvClipInfo::Stream *pClipInfo;
- const CMpegSplitterFile::program * pProgram = m_pFile->FindProgram(s.pid, iProgram, pClipInfo);
- const wchar_t *pStreamName = NULL;
- int StreamType = pClipInfo ? pClipInfo->m_Type : pProgram ? pProgram->streams[iProgram].type : 0;
- pStreamName = StreamTypeToName((PES_STREAM_TYPE)StreamType);
-
- CString FormatDesc = GetMediaTypeDesc(&s.mt, pClipInfo, StreamType);
-
- if(!FormatDesc.IsEmpty())
- str.Format(L"%s (%04x,%02x,%02x)", FormatDesc.GetString(), s.pid, s.pesid, s.ps1id); // TODO: make this nicer
- else if(pStreamName)
- str.Format(L"%s - %s (%04x,%02x,%02x)", name, pStreamName, s.pid, s.pesid, s.ps1id); // TODO: make this nicer
- else
- str.Format(L"%s (%04x,%02x,%02x)", name, s.pid, s.pesid, s.ps1id); // TODO: make this nicer
- }
-
- *ppszName = (WCHAR*)CoTaskMemAlloc((str.GetLength() + 1) * sizeof(WCHAR));
- if(*ppszName == NULL) return E_OUTOFMEMORY;
-
- wcscpy_s(*ppszName, str.GetLength() + 1, str);
- }
- }
-
- j += cnt;
- }
-
- return S_OK;
+ for(int i = 0, j = 0; i < countof(m_pFile->m_streams); i++)
+ {
+ int cnt = m_pFile->m_streams[i].GetCount();
+
+ if(lIndex >= j && lIndex < j+cnt)
+ {
+ lIndex -= j;
+
+ POSITION pos = m_pFile->m_streams[i].FindIndex(lIndex);
+ if(!pos) return E_UNEXPECTED;
+
+ CMpegSplitterFile::stream& s = m_pFile->m_streams[i].GetAt(pos);
+ CHdmvClipInfo::Stream* pStream = m_ClipInfo.FindStream (s.pid);
+
+ if(ppmt) *ppmt = CreateMediaType(&s.mt);
+ if(pdwFlags) *pdwFlags = GetOutputPin(s) ? (AMSTREAMSELECTINFO_ENABLED|AMSTREAMSELECTINFO_EXCLUSIVE) : 0;
+ if(plcid) *plcid = pStream ? pStream->m_LCID : 0;
+ if(pdwGroup) *pdwGroup = i;
+ if(ppObject) *ppObject = NULL;
+ if(ppUnk) *ppUnk = NULL;
+
+
+ if(ppszName)
+ {
+ CStringW name = CMpegSplitterFile::CStreamList::ToString(i);
+
+ CStringW str;
+
+ if (i == CMpegSplitterFile::subpic && s.pid == NO_SUBTITLE_PID)
+ {
+ str = _T("No subtitles");
+ *plcid = LCID_NOSUBTITLES;
+ }
+ else
+ {
+ int iProgram;
+ const CHdmvClipInfo::Stream *pClipInfo;
+ const CMpegSplitterFile::program * pProgram = m_pFile->FindProgram(s.pid, iProgram, pClipInfo);
+ const wchar_t *pStreamName = NULL;
+ int StreamType = pClipInfo ? pClipInfo->m_Type : pProgram ? pProgram->streams[iProgram].type : 0;
+ pStreamName = StreamTypeToName((PES_STREAM_TYPE)StreamType);
+
+ CString FormatDesc = GetMediaTypeDesc(&s.mt, pClipInfo, StreamType);
+
+ if (!FormatDesc.IsEmpty())
+ str.Format(L"%s (%04x,%02x,%02x)", FormatDesc.GetString(), s.pid, s.pesid, s.ps1id); // TODO: make this nicer
+ else if (pStreamName)
+ str.Format(L"%s - %s (%04x,%02x,%02x)", name, pStreamName, s.pid, s.pesid, s.ps1id); // TODO: make this nicer
+ else
+ str.Format(L"%s (%04x,%02x,%02x)", name, s.pid, s.pesid, s.ps1id); // TODO: make this nicer
+ }
+
+ *ppszName = (WCHAR*)CoTaskMemAlloc((str.GetLength()+1)*sizeof(WCHAR));
+ if(*ppszName == NULL) return E_OUTOFMEMORY;
+
+ wcscpy_s(*ppszName, str.GetLength()+1, str);
+ }
+ }
+
+ j += cnt;
+ }
+
+ return S_OK;
}
//
@@ -1157,9 +1121,9 @@ STDMETHODIMP CMpegSplitterFilter::Info(long lIndex, AM_MEDIA_TYPE** ppmt, DWORD*
//
CMpegSourceFilter::CMpegSourceFilter(LPUNKNOWN pUnk, HRESULT* phr, const CLSID& clsid)
- : CMpegSplitterFilter(pUnk, phr, clsid)
+ : CMpegSplitterFilter(pUnk, phr, clsid)
{
- m_pInput.Free();
+ m_pInput.Free();
}
//
@@ -1167,9 +1131,9 @@ CMpegSourceFilter::CMpegSourceFilter(LPUNKNOWN pUnk, HRESULT* phr, const CLSID&
//
CMpegSplitterOutputPin::CMpegSplitterOutputPin(CAtlArray<CMediaType>& mts, LPCWSTR pName, CBaseFilter* pFilter, CCritSec* pLock, HRESULT* phr)
- : CBaseSplitterOutputPin(mts, pName, pFilter, pLock, phr)
- , m_fHasAccessUnitDelimiters(false)
- , m_rtMaxShift(50000000)
+ : CBaseSplitterOutputPin(mts, pName, pFilter, pLock, phr)
+ , m_fHasAccessUnitDelimiters(false)
+ , m_rtMaxShift(50000000)
{
}
@@ -1179,460 +1143,456 @@ CMpegSplitterOutputPin::~CMpegSplitterOutputPin()
HRESULT CMpegSplitterOutputPin::DeliverNewSegment(REFERENCE_TIME tStart, REFERENCE_TIME tStop, double dRate)
{
- {
- CAutoLock cAutoLock(this);
- m_rtPrev = Packet::INVALID_TIME;
- m_rtOffset = 0;
- }
+ {
+ CAutoLock cAutoLock(this);
+ m_rtPrev = Packet::INVALID_TIME;
+ m_rtOffset = 0;
+ }
- return __super::DeliverNewSegment(tStart, tStop, dRate);
+ return __super::DeliverNewSegment(tStart, tStop, dRate);
}
HRESULT CMpegSplitterOutputPin::DeliverEndFlush()
{
- {
- CAutoLock cAutoLock(this);
- m_p.Free();
- m_pl.RemoveAll();
- }
+ {
+ CAutoLock cAutoLock(this);
+ m_p.Free();
+ m_pl.RemoveAll();
+ }
- return __super::DeliverEndFlush();
+ return __super::DeliverEndFlush();
}
HRESULT CMpegSplitterOutputPin::DeliverPacket(CAutoPtr<Packet> p)
{
- CAutoLock cAutoLock(this);
-
- if(p->rtStart != Packet::INVALID_TIME)
- {
- REFERENCE_TIME rt = p->rtStart + m_rtOffset;
-
- // Filter invalid PTS (if too different from previous packet)
- if(m_rtPrev != Packet::INVALID_TIME)
- if(_abs64(rt - m_rtPrev) > m_rtMaxShift)
- m_rtOffset += m_rtPrev - rt;
-
- p->rtStart += m_rtOffset;
- p->rtStop += m_rtOffset;
-
- m_rtPrev = p->rtStart;
- }
-
-
- if(p->pmt)
- {
- if(*((CMediaType *)p->pmt) != m_mt)
- SetMediaType((CMediaType*)p->pmt);
- }
-
-
- if(m_mt.subtype == MEDIASUBTYPE_AAC) // special code for aac, the currently available decoders only like whole frame samples
- {
- if(m_p && m_p->GetCount() == 1 && m_p->GetAt(0) == 0xff && !(!p->IsEmpty() && (p->GetAt(0) & 0xf6) == 0xf0))
- m_p.Free();
-
- if(!m_p)
- {
- BYTE* base = p->GetData();
- BYTE* s = base;
- BYTE* e = s + p->GetCount();
-
- for(; s < e; s++)
- {
- if(*s != 0xff) continue;
-
- if(s == e - 1 || (s[1] & 0xf6) == 0xf0)
- {
- memmove(base, s, e - s);
- p->SetCount(e - s);
- m_p = p;
- break;
- }
- }
- }
- else
- {
- m_p->Append(*p);
- }
-
- while(m_p && m_p->GetCount() > 9)
- {
- BYTE* base = m_p->GetData();
- BYTE* s = base;
- BYTE* e = s + m_p->GetCount();
- int len = ((s[3] & 3) << 11) | (s[4] << 3) | (s[5] >> 5);
- bool crc = !(s[1] & 1);
- s += 7;
- len -= 7;
- if(crc) s += 2, len -= 2;
-
- if(e - s < len)
- {
- break;
- }
-
- if(len <= 0 || e - s >= len + 2 && (s[len] != 0xff || (s[len+1] & 0xf6) != 0xf0))
- {
- m_p.Free();
- break;
- }
-
- CAutoPtr<Packet> p2(DNew Packet());
-
- p2->TrackNumber = m_p->TrackNumber;
- p2->bDiscontinuity |= m_p->bDiscontinuity;
- m_p->bDiscontinuity = false;
-
- p2->bSyncPoint = m_p->rtStart != Packet::INVALID_TIME;
- p2->rtStart = m_p->rtStart;
- m_p->rtStart = Packet::INVALID_TIME;
-
- p2->rtStop = m_p->rtStop;
- m_p->rtStop = Packet::INVALID_TIME;
- p2->pmt = m_p->pmt;
- m_p->pmt = NULL;
- p2->SetData(s, len);
-
- s += len;
- memmove(base, s, e - s);
- m_p->SetCount(e - s);
-
- HRESULT hr = __super::DeliverPacket(p2);
- if(hr != S_OK) return hr;
- }
-
- if(m_p && p)
- {
- if(!m_p->bDiscontinuity) m_p->bDiscontinuity = p->bDiscontinuity;
- if(!m_p->bSyncPoint) m_p->bSyncPoint = p->bSyncPoint;
- if(m_p->rtStart == Packet::INVALID_TIME) m_p->rtStart = p->rtStart, m_p->rtStop = p->rtStop;
- if(m_p->pmt) DeleteMediaType(m_p->pmt);
-
- m_p->pmt = p->pmt;
- p->pmt = NULL;
- }
-
- return S_OK;
- }
- else if(m_mt.subtype == FOURCCMap('1CVA') || m_mt.subtype == FOURCCMap('1cva')) // just like aac, this has to be starting nalus, more can be packed together
- {
- if(!m_p)
- {
- m_p.Attach(DNew Packet());
- m_p->TrackNumber = p->TrackNumber;
- m_p->bDiscontinuity = p->bDiscontinuity;
- p->bDiscontinuity = FALSE;
-
- m_p->bSyncPoint = p->bSyncPoint;
- p->bSyncPoint = FALSE;
-
- m_p->rtStart = p->rtStart;
- p->rtStart = Packet::INVALID_TIME;
-
- m_p->rtStop = p->rtStop;
- p->rtStop = Packet::INVALID_TIME;
- }
-
- m_p->Append(*p);
-
- BYTE* start = m_p->GetData();
- BYTE* end = start + m_p->GetCount();
-
- while(start <= end - 4 && *(DWORD*)start != 0x01000000) start++;
-
- while(start <= end - 4)
- {
- BYTE* next = start + 1;
-
- while(next <= end - 4 && *(DWORD*)next != 0x01000000) next++;
-
- if(next >= end - 4) break;
-
- int size = next - start;
-
- CH264Nalu Nalu;
- Nalu.SetBuffer(start, size, 0);
-
- CAutoPtr<Packet> p2;
-
- while(Nalu.ReadNext())
- {
- DWORD dwNalLength =
- ((Nalu.GetDataLength() >> 24) & 0x000000ff) |
- ((Nalu.GetDataLength() >> 8) & 0x0000ff00) |
- ((Nalu.GetDataLength() << 8) & 0x00ff0000) |
- ((Nalu.GetDataLength() << 24) & 0xff000000);
-
- CAutoPtr<Packet> p3(DNew Packet());
-
- p3->SetCount(Nalu.GetDataLength() + sizeof(dwNalLength));
- memcpy(p3->GetData(), &dwNalLength, sizeof(dwNalLength));
- memcpy(p3->GetData() + sizeof(dwNalLength), Nalu.GetDataBuffer(), Nalu.GetDataLength());
-
- if(p2 == NULL)
- p2 = p3;
- else
- p2->Append(*p3);
- }
-
- p2->TrackNumber = m_p->TrackNumber;
- p2->bDiscontinuity = m_p->bDiscontinuity;
- m_p->bDiscontinuity = FALSE;
-
- p2->bSyncPoint = m_p->bSyncPoint;
- m_p->bSyncPoint = FALSE;
-
- p2->rtStart = m_p->rtStart;
- m_p->rtStart = Packet::INVALID_TIME;
- p2->rtStop = m_p->rtStop;
- m_p->rtStop = Packet::INVALID_TIME;
-
- p2->pmt = m_p->pmt;
- m_p->pmt = NULL;
-
- m_pl.AddTail(p2);
-
- if(p->rtStart != Packet::INVALID_TIME)
- {
- m_p->rtStart = p->rtStart;
- m_p->rtStop = p->rtStop;
- p->rtStart = Packet::INVALID_TIME;
- }
- if(p->bDiscontinuity)
- {
- m_p->bDiscontinuity = p->bDiscontinuity;
- p->bDiscontinuity = FALSE;
- }
- if(p->bSyncPoint)
- {
- m_p->bSyncPoint = p->bSyncPoint;
- p->bSyncPoint = FALSE;
- }
- if(m_p->pmt)
- DeleteMediaType(m_p->pmt);
-
- m_p->pmt = p->pmt;
- p->pmt = NULL;
-
- start = next;
- }
- if(start > m_p->GetData())
- {
- m_p->RemoveAt(0, start - m_p->GetData());
- }
-
- for(POSITION pos = m_pl.GetHeadPosition(); pos; m_pl.GetNext(pos))
- {
- if(pos == m_pl.GetHeadPosition())
- continue;
-
- Packet* pPacket = m_pl.GetAt(pos);
- BYTE* pData = pPacket->GetData();
-
- if((pData[4] & 0x1f) == 0x09) m_fHasAccessUnitDelimiters = true;
-
- if((pData[4] & 0x1f) == 0x09 || !m_fHasAccessUnitDelimiters && pPacket->rtStart != Packet::INVALID_TIME)
- {
- p = m_pl.RemoveHead();
-
- while(pos != m_pl.GetHeadPosition())
- {
- CAutoPtr<Packet> p2 = m_pl.RemoveHead();
- p->Append(*p2);
- }
-
- HRESULT hr = __super::DeliverPacket(p);
- if(hr != S_OK) return hr;
- }
- }
-
- return S_OK;
- }
- else if(m_mt.subtype == FOURCCMap('1CVW') || m_mt.subtype == FOURCCMap('1cvw')) // just like aac, this has to be starting nalus, more can be packed together
- {
- if(!m_p)
- {
- m_p.Attach(DNew Packet());
- m_p->TrackNumber = p->TrackNumber;
- m_p->bDiscontinuity = p->bDiscontinuity;
- p->bDiscontinuity = FALSE;
-
- m_p->bSyncPoint = p->bSyncPoint;
- p->bSyncPoint = FALSE;
-
- m_p->rtStart = p->rtStart;
- p->rtStart = Packet::INVALID_TIME;
-
- m_p->rtStop = p->rtStop;
- p->rtStop = Packet::INVALID_TIME;
- }
-
- m_p->Append(*p);
-
- BYTE* start = m_p->GetData();
- BYTE* end = start + m_p->GetCount();
-
- bool bSeqFound = false;
- while(start <= end - 4)
- {
- if(*(DWORD*)start == 0x0D010000)
- {
- bSeqFound = true;
- break;
- }
- else if(*(DWORD*)start == 0x0F010000)
- break;
- start++;
- }
-
- while(start <= end - 4)
- {
- BYTE* next = start + 1;
-
- while(next <= end - 4)
- {
- if(*(DWORD*)next == 0x0D010000)
- {
- if(bSeqFound) break;
- bSeqFound = true;
- }
- else if(*(DWORD*)next == 0x0F010000)
- break;
- next++;
- }
-
- if(next >= end - 4) break;
-
- int size = next - start - 4;
-
-
- CAutoPtr<Packet> p2(DNew Packet());
- p2->TrackNumber = m_p->TrackNumber;
- p2->bDiscontinuity = m_p->bDiscontinuity;
- m_p->bDiscontinuity = FALSE;
-
- p2->bSyncPoint = m_p->bSyncPoint;
- m_p->bSyncPoint = FALSE;
-
- p2->rtStart = m_p->rtStart;
- m_p->rtStart = Packet::INVALID_TIME;
-
- p2->rtStop = m_p->rtStop;
- m_p->rtStop = Packet::INVALID_TIME;
-
- p2->pmt = m_p->pmt;
- m_p->pmt = NULL;
-
- p2->SetData(start, next - start);
-
- HRESULT hr = __super::DeliverPacket(p2);
- if(hr != S_OK) return hr;
-
- if(p->rtStart != Packet::INVALID_TIME)
- {
- m_p->rtStart = p->rtStart;
- m_p->rtStop = p->rtStop;
- p->rtStart = Packet::INVALID_TIME;
- }
- if(p->bDiscontinuity)
- {
- m_p->bDiscontinuity = p->bDiscontinuity;
- p->bDiscontinuity = FALSE;
- }
- if(p->bSyncPoint)
- {
- m_p->bSyncPoint = p->bSyncPoint;
- p->bSyncPoint = FALSE;
- }
- if(m_p->pmt)
- DeleteMediaType(m_p->pmt);
-
- m_p->pmt = p->pmt;
- p->pmt = NULL;
-
- start = next;
- bSeqFound = (*(DWORD*)start == 0x0D010000);
- }
-
- if(start > m_p->GetData())
- {
- m_p->RemoveAt(0, start - m_p->GetData());
- }
-
- return S_OK;
- }
- else if(m_mt.subtype == MEDIASUBTYPE_DTS || m_mt.subtype == MEDIASUBTYPE_WAVE_DTS) // DTS HD MA data is causing trouble, lets just remove it
- {
+ CAutoLock cAutoLock(this);
+
+ if(p->rtStart != Packet::INVALID_TIME)
+ {
+ REFERENCE_TIME rt = p->rtStart + m_rtOffset;
+
+ // Filter invalid PTS (if too different from previous packet)
+ if(m_rtPrev != Packet::INVALID_TIME)
+ if(_abs64(rt - m_rtPrev) > m_rtMaxShift)
+ m_rtOffset += m_rtPrev - rt;
+
+ p->rtStart += m_rtOffset;
+ p->rtStop += m_rtOffset;
+
+ m_rtPrev = p->rtStart;
+ }
+
+
+ if (p->pmt)
+ {
+ if (*((CMediaType *)p->pmt) != m_mt)
+ SetMediaType ((CMediaType*)p->pmt);
+ }
+
+
+ if(m_mt.subtype == MEDIASUBTYPE_AAC) // special code for aac, the currently available decoders only like whole frame samples
+ {
+ if(m_p && m_p->GetCount() == 1 && m_p->GetAt(0) == 0xff && !(!p->IsEmpty() && (p->GetAt(0) & 0xf6) == 0xf0))
+ m_p.Free();
+
+ if(!m_p)
+ {
+ BYTE* base = p->GetData();
+ BYTE* s = base;
+ BYTE* e = s + p->GetCount();
+
+ for(; s < e; s++)
+ {
+ if(*s != 0xff) continue;
+
+ if(s == e-1 || (s[1]&0xf6) == 0xf0)
+ {
+ memmove(base, s, e - s);
+ p->SetCount(e - s);
+ m_p = p;
+ break;
+ }
+ }
+ }
+ else
+ {
+ m_p->Append(*p);
+ }
+
+ while(m_p && m_p->GetCount() > 9)
+ {
+ BYTE* base = m_p->GetData();
+ BYTE* s = base;
+ BYTE* e = s + m_p->GetCount();
+ int len = ((s[3]&3)<<11)|(s[4]<<3)|(s[5]>>5);
+ bool crc = !(s[1]&1);
+ s += 7; len -= 7;
+ if(crc) s += 2, len -= 2;
+
+ if(e - s < len)
+ {
+ break;
+ }
+
+ if(len <= 0 || e - s >= len + 2 && (s[len] != 0xff || (s[len+1]&0xf6) != 0xf0))
+ {
+ m_p.Free();
+ break;
+ }
+
+ CAutoPtr<Packet> p2(DNew Packet());
+
+ p2->TrackNumber = m_p->TrackNumber;
+ p2->bDiscontinuity |= m_p->bDiscontinuity;
+ m_p->bDiscontinuity = false;
+
+ p2->bSyncPoint = m_p->rtStart != Packet::INVALID_TIME;
+ p2->rtStart = m_p->rtStart;
+ m_p->rtStart = Packet::INVALID_TIME;
+
+ p2->rtStop = m_p->rtStop;
+ m_p->rtStop = Packet::INVALID_TIME;
+ p2->pmt = m_p->pmt; m_p->pmt = NULL;
+ p2->SetData(s, len);
+
+ s += len;
+ memmove(base, s, e - s);
+ m_p->SetCount(e - s);
+
+ HRESULT hr = __super::DeliverPacket(p2);
+ if(hr != S_OK) return hr;
+ }
+
+ if(m_p && p)
+ {
+ if(!m_p->bDiscontinuity) m_p->bDiscontinuity = p->bDiscontinuity;
+ if(!m_p->bSyncPoint) m_p->bSyncPoint = p->bSyncPoint;
+ if(m_p->rtStart == Packet::INVALID_TIME) m_p->rtStart = p->rtStart, m_p->rtStop = p->rtStop;
+ if(m_p->pmt) DeleteMediaType(m_p->pmt);
+
+ m_p->pmt = p->pmt;
+ p->pmt = NULL;
+ }
+
+ return S_OK;
+ }
+ else if(m_mt.subtype == FOURCCMap('1CVA') || m_mt.subtype == FOURCCMap('1cva')) // just like aac, this has to be starting nalus, more can be packed together
+ {
+ if(!m_p)
+ {
+ m_p.Attach(DNew Packet());
+ m_p->TrackNumber = p->TrackNumber;
+ m_p->bDiscontinuity = p->bDiscontinuity;
+ p->bDiscontinuity = FALSE;
+
+ m_p->bSyncPoint = p->bSyncPoint;
+ p->bSyncPoint = FALSE;
+
+ m_p->rtStart = p->rtStart;
+ p->rtStart = Packet::INVALID_TIME;
+
+ m_p->rtStop = p->rtStop;
+ p->rtStop = Packet::INVALID_TIME;
+ }
+
+ m_p->Append(*p);
+
+ BYTE* start = m_p->GetData();
+ BYTE* end = start + m_p->GetCount();
+
+ while(start <= end-4 && *(DWORD*)start != 0x01000000) start++;
+
+ while(start <= end-4)
+ {
+ BYTE* next = start+1;
+
+ while(next <= end-4 && *(DWORD*)next != 0x01000000) next++;
+
+ if(next >= end-4) break;
+
+ int size = next - start;
+
+ CH264Nalu Nalu;
+ Nalu.SetBuffer (start, size, 0);
+
+ CAutoPtr<Packet> p2;
+
+ while (Nalu.ReadNext())
+ {
+ DWORD dwNalLength =
+ ((Nalu.GetDataLength() >> 24) & 0x000000ff) |
+ ((Nalu.GetDataLength() >> 8) & 0x0000ff00) |
+ ((Nalu.GetDataLength() << 8) & 0x00ff0000) |
+ ((Nalu.GetDataLength() << 24) & 0xff000000);
+
+ CAutoPtr<Packet> p3(DNew Packet());
+
+ p3->SetCount (Nalu.GetDataLength()+sizeof(dwNalLength));
+ memcpy (p3->GetData(), &dwNalLength, sizeof(dwNalLength));
+ memcpy (p3->GetData()+sizeof(dwNalLength), Nalu.GetDataBuffer(), Nalu.GetDataLength());
+
+ if (p2 == NULL)
+ p2 = p3;
+ else
+ p2->Append(*p3);
+ }
+
+ p2->TrackNumber = m_p->TrackNumber;
+ p2->bDiscontinuity = m_p->bDiscontinuity;
+ m_p->bDiscontinuity = FALSE;
+
+ p2->bSyncPoint = m_p->bSyncPoint;
+ m_p->bSyncPoint = FALSE;
+
+ p2->rtStart = m_p->rtStart; m_p->rtStart = Packet::INVALID_TIME;
+ p2->rtStop = m_p->rtStop;
+ m_p->rtStop = Packet::INVALID_TIME;
+
+ p2->pmt = m_p->pmt; m_p->pmt = NULL;
+
+ m_pl.AddTail(p2);
+
+ if(p->rtStart != Packet::INVALID_TIME)
+ {
+ m_p->rtStart = p->rtStart;
+ m_p->rtStop = p->rtStop;
+ p->rtStart = Packet::INVALID_TIME;
+ }
+ if(p->bDiscontinuity)
+ {
+ m_p->bDiscontinuity = p->bDiscontinuity;
+ p->bDiscontinuity = FALSE;
+ }
+ if(p->bSyncPoint)
+ {
+ m_p->bSyncPoint = p->bSyncPoint;
+ p->bSyncPoint = FALSE;
+ }
+ if(m_p->pmt)
+ DeleteMediaType(m_p->pmt);
+
+ m_p->pmt = p->pmt;
+ p->pmt = NULL;
+
+ start = next;
+ }
+ if(start > m_p->GetData())
+ {
+ m_p->RemoveAt(0, start - m_p->GetData());
+ }
+
+ for(POSITION pos = m_pl.GetHeadPosition(); pos; m_pl.GetNext(pos))
+ {
+ if(pos == m_pl.GetHeadPosition())
+ continue;
+
+ Packet* pPacket = m_pl.GetAt(pos);
+ BYTE* pData = pPacket->GetData();
+
+ if((pData[4]&0x1f) == 0x09) m_fHasAccessUnitDelimiters = true;
+
+ if((pData[4]&0x1f) == 0x09 || !m_fHasAccessUnitDelimiters && pPacket->rtStart != Packet::INVALID_TIME)
+ {
+ p = m_pl.RemoveHead();
+
+ while(pos != m_pl.GetHeadPosition())
+ {
+ CAutoPtr<Packet> p2 = m_pl.RemoveHead();
+ p->Append(*p2);
+ }
+
+ HRESULT hr = __super::DeliverPacket(p);
+ if(hr != S_OK) return hr;
+ }
+ }
+
+ return S_OK;
+ }
+ else if(m_mt.subtype == FOURCCMap('1CVW') || m_mt.subtype == FOURCCMap('1cvw')) // just like aac, this has to be starting nalus, more can be packed together
+ {
+ if(!m_p)
+ {
+ m_p.Attach(DNew Packet());
+ m_p->TrackNumber = p->TrackNumber;
+ m_p->bDiscontinuity = p->bDiscontinuity;
+ p->bDiscontinuity = FALSE;
+
+ m_p->bSyncPoint = p->bSyncPoint;
+ p->bSyncPoint = FALSE;
+
+ m_p->rtStart = p->rtStart;
+ p->rtStart = Packet::INVALID_TIME;
+
+ m_p->rtStop = p->rtStop;
+ p->rtStop = Packet::INVALID_TIME;
+ }
+
+ m_p->Append(*p);
+
+ BYTE* start = m_p->GetData();
+ BYTE* end = start + m_p->GetCount();
+
+ bool bSeqFound = false;
+ while(start <= end-4)
+ {
+ if (*(DWORD*)start == 0x0D010000)
+ {
+ bSeqFound = true;
+ break;
+ }
+ else if (*(DWORD*)start == 0x0F010000)
+ break;
+ start++;
+ }
+
+ while(start <= end-4)
+ {
+ BYTE* next = start+1;
+
+ while(next <= end-4)
+ {
+ if (*(DWORD*)next == 0x0D010000)
+ {
+ if (bSeqFound) break;
+ bSeqFound = true;
+ }
+ else if (*(DWORD*)next == 0x0F010000)
+ break;
+ next++;
+ }
+
+ if(next >= end-4) break;
+
+ int size = next - start - 4;
+
+
+ CAutoPtr<Packet> p2(DNew Packet());
+ p2->TrackNumber = m_p->TrackNumber;
+ p2->bDiscontinuity = m_p->bDiscontinuity;
+ m_p->bDiscontinuity = FALSE;
+
+ p2->bSyncPoint = m_p->bSyncPoint;
+ m_p->bSyncPoint = FALSE;
+
+ p2->rtStart = m_p->rtStart;
+ m_p->rtStart = Packet::INVALID_TIME;
+
+ p2->rtStop = m_p->rtStop;
+ m_p->rtStop = Packet::INVALID_TIME;
+
+ p2->pmt = m_p->pmt;
+ m_p->pmt = NULL;
+
+ p2->SetData(start, next - start);
+
+ HRESULT hr = __super::DeliverPacket(p2);
+ if(hr != S_OK) return hr;
+
+ if(p->rtStart != Packet::INVALID_TIME)
+ {
+ m_p->rtStart = p->rtStart;
+ m_p->rtStop = p->rtStop;
+ p->rtStart = Packet::INVALID_TIME;
+ }
+ if(p->bDiscontinuity)
+ {
+ m_p->bDiscontinuity = p->bDiscontinuity;
+ p->bDiscontinuity = FALSE;
+ }
+ if(p->bSyncPoint)
+ {
+ m_p->bSyncPoint = p->bSyncPoint;
+ p->bSyncPoint = FALSE;
+ }
+ if(m_p->pmt)
+ DeleteMediaType(m_p->pmt);
+
+ m_p->pmt = p->pmt;
+ p->pmt = NULL;
+
+ start = next;
+ bSeqFound = (*(DWORD*)start == 0x0D010000);
+ }
+
+ if(start > m_p->GetData())
+ {
+ m_p->RemoveAt(0, start - m_p->GetData());
+ }
+
+ return S_OK;
+ }
+ else if (m_mt.subtype == MEDIASUBTYPE_DTS || m_mt.subtype == MEDIASUBTYPE_WAVE_DTS) // DTS HD MA data is causing trouble, lets just remove it
+ {
#if 0
- BYTE* start = p->GetData();
- BYTE* end = start + p->GetCount();
- if(end - start < 4 && !p->pmt)
- return S_OK; // Should be invalid packet
-
- BYTE* hdr = start;
-
-
- int Type;
- // 16 bits big endian bitstream
- if(hdr[0] == 0x7f && hdr[1] == 0xfe &&
- hdr[2] == 0x80 && hdr[3] == 0x01)
- Type = 16 + 32;
-
- // 16 bits low endian bitstream
- else if(hdr[0] == 0xfe && hdr[1] == 0x7f &&
- hdr[2] == 0x01 && hdr[3] == 0x80)
- Type = 16;
-
- // 14 bits big endian bitstream
- else if(hdr[0] == 0x1f && hdr[1] == 0xff &&
- hdr[2] == 0xe8 && hdr[3] == 0x00 &&
- hdr[4] == 0x07 && (hdr[5] & 0xf0) == 0xf0)
- Type = 14 + 32;
-
- // 14 bits low endian bitstream
- else if(hdr[0] == 0xff && hdr[1] == 0x1f &&
- hdr[2] == 0x00 && hdr[3] == 0xe8 &&
- (hdr[4] & 0xf0) == 0xf0 && hdr[5] == 0x07)
- Type = 14;
-
- // no sync
- else if(!p->pmt)
- {
- return S_OK;
- }
+ BYTE* start = p->GetData();
+ BYTE* end = start + p->GetCount();
+ if (end - start < 4 && !p->pmt)
+ return S_OK; // Should be invalid packet
+
+ BYTE* hdr = start;
+
+
+ int Type;
+ // 16 bits big endian bitstream
+ if (hdr[0] == 0x7f && hdr[1] == 0xfe &&
+ hdr[2] == 0x80 && hdr[3] == 0x01)
+ Type = 16 + 32;
+
+ // 16 bits low endian bitstream
+ else if (hdr[0] == 0xfe && hdr[1] == 0x7f &&
+ hdr[2] == 0x01 && hdr[3] == 0x80)
+ Type = 16;
+
+ // 14 bits big endian bitstream
+ else if (hdr[0] == 0x1f && hdr[1] == 0xff &&
+ hdr[2] == 0xe8 && hdr[3] == 0x00 &&
+ hdr[4] == 0x07 && (hdr[5] & 0xf0) == 0xf0)
+ Type = 14 + 32;
+
+ // 14 bits low endian bitstream
+ else if (hdr[0] == 0xff && hdr[1] == 0x1f &&
+ hdr[2] == 0x00 && hdr[3] == 0xe8 &&
+ (hdr[4] & 0xf0) == 0xf0 && hdr[5] == 0x07)
+ Type = 14;
+
+ // no sync
+ else if (!p->pmt)
+ {
+ return S_OK;
+ }
#endif
- }
- else if(m_mt.subtype == MEDIASUBTYPE_HDMV_LPCM_AUDIO)
- {
- BYTE* start = p->GetData();
- p->SetData(start + 4, p->GetCount() - 4);
- }
- else
- {
- m_p.Free();
- m_pl.RemoveAll();
- }
-
- return __super::DeliverPacket(p);
+ }
+ else if (m_mt.subtype == MEDIASUBTYPE_HDMV_LPCM_AUDIO)
+ {
+ BYTE* start = p->GetData();
+ p->SetData(start + 4, p->GetCount() - 4);
+ }
+ else
+ {
+ m_p.Free();
+ m_pl.RemoveAll();
+ }
+
+ return __super::DeliverPacket(p);
}
STDMETHODIMP CMpegSplitterOutputPin::Connect(IPin* pReceivePin, const AM_MEDIA_TYPE* pmt)
{
- HRESULT hr;
- PIN_INFO PinInfo;
- GUID FilterClsid;
-
- if(SUCCEEDED(pReceivePin->QueryPinInfo(&PinInfo)))
- {
- if(SUCCEEDED(PinInfo.pFilter->GetClassID(&FilterClsid)) && (FilterClsid == CLSID_DMOWrapperFilter))
- (static_cast<CMpegSplitterFilter*>(m_pFilter))->SetPipo(true);
- PinInfo.pFilter->Release();
- }
-
- hr = __super::Connect(pReceivePin, pmt);
- (static_cast<CMpegSplitterFilter*>(m_pFilter))->SetPipo(false);
- return hr;
+ HRESULT hr;
+ PIN_INFO PinInfo;
+ GUID FilterClsid;
+
+ if (SUCCEEDED (pReceivePin->QueryPinInfo (&PinInfo)))
+ {
+ if (SUCCEEDED (PinInfo.pFilter->GetClassID(&FilterClsid)) && (FilterClsid == CLSID_DMOWrapperFilter))
+ (static_cast<CMpegSplitterFilter*>(m_pFilter))->SetPipo(true);
+ PinInfo.pFilter->Release();
+ }
+
+ hr = __super::Connect (pReceivePin, pmt);
+ (static_cast<CMpegSplitterFilter*>(m_pFilter))->SetPipo(false);
+ return hr;
}
diff --git a/src/filters/parser/MpegSplitter/MpegSplitter.h b/src/filters/parser/MpegSplitter/MpegSplitter.h
index c99aa20a5..fb20de487 100644
--- a/src/filters/parser/MpegSplitter/MpegSplitter.h
+++ b/src/filters/parser/MpegSplitter/MpegSplitter.h
@@ -1,4 +1,4 @@
-/*
+/*
* Copyright (C) 2003-2006 Gabest
* http://www.gabest.org
*
@@ -6,15 +6,15 @@
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2, or (at your option)
* any later version.
- *
+ *
* This Program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with GNU Make; see the file COPYING. If not, write to
- * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
+ * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
* http://www.gnu.org/copyleft/gpl.html
*
*/
@@ -27,66 +27,60 @@
[uuid("DC257063-045F-4BE2-BD5B-E12279C464F0")]
class CMpegSplitterFilter : public CBaseSplitterFilter, public IAMStreamSelect
{
- REFERENCE_TIME m_rtStartOffset;
- bool m_pPipoBimbo;
- CHdmvClipInfo m_ClipInfo;
+ REFERENCE_TIME m_rtStartOffset;
+ bool m_pPipoBimbo;
+ CHdmvClipInfo m_ClipInfo;
protected:
- CAutoPtr<CMpegSplitterFile> m_pFile;
- HRESULT CreateOutputs(IAsyncReader* pAsyncReader);
- void ReadClipInfo(LPCOLESTR pszFileName);
+ CAutoPtr<CMpegSplitterFile> m_pFile;
+ HRESULT CreateOutputs(IAsyncReader* pAsyncReader);
+ void ReadClipInfo(LPCOLESTR pszFileName);
- bool DemuxInit();
- void DemuxSeek(REFERENCE_TIME rt);
- bool DemuxLoop();
- bool BuildPlaylist(LPCTSTR pszFileName, CAtlList<CHdmvClipInfo::PlaylistItem>& files);
+ bool DemuxInit();
+ void DemuxSeek(REFERENCE_TIME rt);
+ bool DemuxLoop();
+ bool BuildPlaylist(LPCTSTR pszFileName, CAtlList<CHdmvClipInfo::PlaylistItem>& files);
- HRESULT DemuxNextPacket(REFERENCE_TIME rtStartOffset);
+ HRESULT DemuxNextPacket(REFERENCE_TIME rtStartOffset);
public:
- CMpegSplitterFilter(LPUNKNOWN pUnk, HRESULT* phr, const CLSID& clsid = __uuidof(CMpegSplitterFilter));
- void SetPipo(bool bPipo)
- {
- m_pPipoBimbo = bPipo;
- };
+ CMpegSplitterFilter(LPUNKNOWN pUnk, HRESULT* phr, const CLSID& clsid = __uuidof(CMpegSplitterFilter));
+ void SetPipo(bool bPipo) { m_pPipoBimbo = bPipo; };
- DECLARE_IUNKNOWN
+ DECLARE_IUNKNOWN
STDMETHODIMP NonDelegatingQueryInterface(REFIID riid, void** ppv);
- STDMETHODIMP GetClassID(CLSID* pClsID);
- STDMETHODIMP Load(LPCOLESTR pszFileName, const AM_MEDIA_TYPE* pmt);
+ STDMETHODIMP GetClassID(CLSID* pClsID);
+ STDMETHODIMP Load(LPCOLESTR pszFileName, const AM_MEDIA_TYPE* pmt);
- // IAMStreamSelect
+ // IAMStreamSelect
- STDMETHODIMP Count(DWORD* pcStreams);
- STDMETHODIMP Enable(long lIndex, DWORD dwFlags);
- STDMETHODIMP Info(long lIndex, AM_MEDIA_TYPE** ppmt, DWORD* pdwFlags, LCID* plcid, DWORD* pdwGroup, WCHAR** ppszName, IUnknown** ppObject, IUnknown** ppUnk);
+ STDMETHODIMP Count(DWORD* pcStreams);
+ STDMETHODIMP Enable(long lIndex, DWORD dwFlags);
+ STDMETHODIMP Info(long lIndex, AM_MEDIA_TYPE** ppmt, DWORD* pdwFlags, LCID* plcid, DWORD* pdwGroup, WCHAR** ppszName, IUnknown** ppObject, IUnknown** ppUnk);
};
[uuid("1365BE7A-C86A-473C-9A41-C0A6E82C9FA3")]
class CMpegSourceFilter : public CMpegSplitterFilter
{
public:
- CMpegSourceFilter(LPUNKNOWN pUnk, HRESULT* phr, const CLSID& clsid = __uuidof(CMpegSourceFilter));
+ CMpegSourceFilter(LPUNKNOWN pUnk, HRESULT* phr, const CLSID& clsid = __uuidof(CMpegSourceFilter));
};
class CMpegSplitterOutputPin : public CBaseSplitterOutputPin, protected CCritSec
{
- CAutoPtr<Packet> m_p;
- CAutoPtrList<Packet> m_pl;
- REFERENCE_TIME m_rtPrev, m_rtOffset, m_rtMaxShift;
- bool m_fHasAccessUnitDelimiters;
+ CAutoPtr<Packet> m_p;
+ CAutoPtrList<Packet> m_pl;
+ REFERENCE_TIME m_rtPrev, m_rtOffset, m_rtMaxShift;
+ bool m_fHasAccessUnitDelimiters;
protected:
- HRESULT DeliverNewSegment(REFERENCE_TIME tStart, REFERENCE_TIME tStop, double dRate);
- HRESULT DeliverPacket(CAutoPtr<Packet> p);
- HRESULT DeliverEndFlush();
+ HRESULT DeliverNewSegment(REFERENCE_TIME tStart, REFERENCE_TIME tStop, double dRate);
+ HRESULT DeliverPacket(CAutoPtr<Packet> p);
+ HRESULT DeliverEndFlush();
public:
- CMpegSplitterOutputPin(CAtlArray<CMediaType>& mts, LPCWSTR pName, CBaseFilter* pFilter, CCritSec* pLock, HRESULT* phr);
- virtual ~CMpegSplitterOutputPin();
- STDMETHODIMP Connect(IPin* pReceivePin, const AM_MEDIA_TYPE* pmt);
- void SetMaxShift(REFERENCE_TIME rtMaxShift)
- {
- m_rtMaxShift = rtMaxShift;
- };
+ CMpegSplitterOutputPin(CAtlArray<CMediaType>& mts, LPCWSTR pName, CBaseFilter* pFilter, CCritSec* pLock, HRESULT* phr);
+ virtual ~CMpegSplitterOutputPin();
+ STDMETHODIMP Connect(IPin* pReceivePin, const AM_MEDIA_TYPE* pmt);
+ void SetMaxShift(REFERENCE_TIME rtMaxShift) { m_rtMaxShift = rtMaxShift; };
};
diff --git a/src/filters/parser/MpegSplitter/MpegSplitterFile.cpp b/src/filters/parser/MpegSplitter/MpegSplitterFile.cpp
index 07ef13d37..a955a54f7 100644
--- a/src/filters/parser/MpegSplitter/MpegSplitterFile.cpp
+++ b/src/filters/parser/MpegSplitter/MpegSplitterFile.cpp
@@ -1,4 +1,4 @@
-/*
+/*
* Copyright (C) 2003-2006 Gabest
* http://www.gabest.org
*
@@ -6,15 +6,15 @@
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2, or (at your option)
* any later version.
- *
+ *
* This Program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with GNU Make; see the file COPYING. If not, write to
- * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
+ * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
* http://www.gnu.org/copyleft/gpl.html
*
*/
@@ -30,789 +30,777 @@
#define ISVALIDPID(pid) (pid >= 0x10 && pid < 0x1fff)
CMpegSplitterFile::CMpegSplitterFile(IAsyncReader* pAsyncReader, HRESULT& hr, bool bIsHdmv, CHdmvClipInfo &ClipInfo)
- : CBaseSplitterFileEx(pAsyncReader, hr, DEFAULT_CACHE_LENGTH, false, true)
- , m_type(us)
- , m_rate(0)
- , m_rtMin(0), m_rtMax(0)
- , m_posMin(0), m_posMax(0)
- , m_bIsHdmv(bIsHdmv)
- , m_ClipInfo(ClipInfo)
+ : CBaseSplitterFileEx(pAsyncReader, hr, DEFAULT_CACHE_LENGTH, false, true)
+ , m_type(us)
+ , m_rate(0)
+ , m_rtMin(0), m_rtMax(0)
+ , m_posMin(0), m_posMax(0)
+ , m_bIsHdmv(bIsHdmv)
+ , m_ClipInfo(ClipInfo)
{
- // Ugly code : to support BRD seamless playback, CMultiFiles need to update m_rtPTSOffset variable
- // each time a new part is open...
- CComQIPtr<ISyncReader> pReader = pAsyncReader;
- if(pReader) pReader->SetPTSOffset(&m_rtPTSOffset);
+ // Ugly code : to support BRD seamless playback, CMultiFiles need to update m_rtPTSOffset variable
+ // each time a new part is open...
+ CComQIPtr<ISyncReader> pReader = pAsyncReader;
+ if (pReader) pReader->SetPTSOffset (&m_rtPTSOffset);
- if(SUCCEEDED(hr)) hr = Init();
+ if(SUCCEEDED(hr)) hr = Init();
}
HRESULT CMpegSplitterFile::Init()
{
- HRESULT hr;
-
- // get the type first
-
- m_type = us;
-
- Seek(0);
-
- if(m_type == us)
- {
- if(BitRead(32, true) == 'TFrc') Seek(0x67c);
- int cnt = 0, limit = 4;
- for(trhdr h; cnt < limit && Read(h); cnt++) Seek(h.next);
- if(cnt >= limit) m_type = ts;
- }
-
- Seek(0);
-
- if(m_type == us)
- {
- int cnt = 0, limit = 4;
- for(pvahdr h; cnt < limit && Read(h); cnt++) Seek(GetPos() + h.length);
- if(cnt >= limit) m_type = pva;
- }
-
- Seek(0);
-
- if(m_type == us)
- {
- BYTE b;
- for(int i = 0; (i < 4 || GetPos() < 65536) && m_type == us && NextMpegStartCode(b); i++)
- {
- if(b == 0xba)
- {
- pshdr h;
- if(Read(h))
- {
- m_type = ps;
- m_rate = int(h.bitrate / 8);
- break;
- }
- }
- else if((b & 0xe0) == 0xc0 // audio, 110xxxxx, mpeg1/2/3
- || (b & 0xf0) == 0xe0 // video, 1110xxxx, mpeg1/2
- // || (b&0xbd) == 0xbd) // private stream 1, 0xbd, ac3/dts/lpcm/subpic
- || b == 0xbd) // private stream 1, 0xbd, ac3/dts/lpcm/subpic
- {
- peshdr h;
- if(Read(h, b) && BitRead(24, true) == 0x000001)
- m_type = es;
- }
- }
- }
-
- Seek(0);
-
- if(m_type == us)
- return E_FAIL;
-
- // min/max pts & bitrate
- m_rtMin = m_posMin = _I64_MAX;
- m_rtMax = m_posMax = 0;
-
- if(IsRandomAccess() || IsStreaming())
- {
- if(IsStreaming())
- {
- for(int i = 0; i < 20 || i < 50 && S_OK != HasMoreData(1024 * 100, 100); i++);
- }
-
- CAtlList<__int64> fps;
- for(int i = 0, j = 5; i <= j; i++)
- fps.AddTail(i * GetLength() / j);
-
- for(__int64 pfp = 0; fps.GetCount();)
- {
- __int64 fp = fps.RemoveHead();
- fp = min(GetLength() - MEGABYTE / 8, fp);
- fp = max(pfp, fp);
- __int64 nfp = fp + (pfp == 0 ? 5 * MEGABYTE : MEGABYTE / 8);
- if(FAILED(hr = SearchStreams(fp, nfp)))
- return hr;
- pfp = nfp;
- }
- }
- else
- {
- if(FAILED(hr = SearchStreams(0, MEGABYTE / 8)))
- return hr;
- }
-
- if(m_posMax - m_posMin <= 0 || m_rtMax - m_rtMin <= 0)
- return E_FAIL;
-
- int indicated_rate = m_rate;
- int detected_rate = int(10000000i64 * (m_posMax - m_posMin) / (m_rtMax - m_rtMin));
- // normally "detected" should always be less than "indicated", but sometimes it can be a few percent higher (+10% is allowed here)
- // (update: also allowing +/-50k/s)
- if(indicated_rate == 0 || ((float)detected_rate / indicated_rate) < 1.1 || abs(detected_rate - indicated_rate) < 50 * 1024)
- m_rate = detected_rate;
- else ; // TODO: in this case disable seeking, or try doing something less drastical...
-
- if(m_streams[video].GetCount())
- {
- if(!m_bIsHdmv && m_streams[subpic].GetCount())
- {
+ HRESULT hr;
+
+ // get the type first
+
+ m_type = us;
+
+ Seek(0);
+
+ if(m_type == us)
+ {
+ if(BitRead(32, true) == 'TFrc') Seek(0x67c);
+ int cnt = 0, limit = 4;
+ for(trhdr h; cnt < limit && Read(h); cnt++) Seek(h.next);
+ if(cnt >= limit) m_type = ts;
+ }
+
+ Seek(0);
+
+ if(m_type == us)
+ {
+ int cnt = 0, limit = 4;
+ for(pvahdr h; cnt < limit && Read(h); cnt++) Seek(GetPos() + h.length);
+ if(cnt >= limit) m_type = pva;
+ }
+
+ Seek(0);
+
+ if(m_type == us)
+ {
+ BYTE b;
+ for(int i = 0; (i < 4 || GetPos() < 65536) && m_type == us && NextMpegStartCode(b); i++)
+ {
+ if(b == 0xba)
+ {
+ pshdr h;
+ if(Read(h))
+ {
+ m_type = ps;
+ m_rate = int(h.bitrate/8);
+ break;
+ }
+ }
+ else if((b&0xe0) == 0xc0 // audio, 110xxxxx, mpeg1/2/3
+ || (b&0xf0) == 0xe0 // video, 1110xxxx, mpeg1/2
+ // || (b&0xbd) == 0xbd) // private stream 1, 0xbd, ac3/dts/lpcm/subpic
+ || b == 0xbd) // private stream 1, 0xbd, ac3/dts/lpcm/subpic
+ {
+ peshdr h;
+ if(Read(h, b) && BitRead(24, true) == 0x000001)
+ m_type = es;
+ }
+ }
+ }
+
+ Seek(0);
+
+ if(m_type == us)
+ return E_FAIL;
+
+ // min/max pts & bitrate
+ m_rtMin = m_posMin = _I64_MAX;
+ m_rtMax = m_posMax = 0;
+
+ if(IsRandomAccess() || IsStreaming())
+ {
+ if(IsStreaming())
+ {
+ for(int i = 0; i < 20 || i < 50 && S_OK != HasMoreData(1024*100, 100); i++);
+ }
+
+ CAtlList<__int64> fps;
+ for(int i = 0, j = 5; i <= j; i++)
+ fps.AddTail(i*GetLength()/j);
+
+ for(__int64 pfp = 0; fps.GetCount(); )
+ {
+ __int64 fp = fps.RemoveHead();
+ fp = min(GetLength() - MEGABYTE/8, fp);
+ fp = max(pfp, fp);
+ __int64 nfp = fp + (pfp == 0 ? 5*MEGABYTE : MEGABYTE/8);
+ if(FAILED(hr = SearchStreams(fp, nfp)))
+ return hr;
+ pfp = nfp;
+ }
+ }
+ else
+ {
+ if(FAILED(hr = SearchStreams(0, MEGABYTE/8)))
+ return hr;
+ }
+
+ if(m_posMax - m_posMin <= 0 || m_rtMax - m_rtMin <= 0)
+ return E_FAIL;
+
+ int indicated_rate = m_rate;
+ int detected_rate = int(10000000i64 * (m_posMax - m_posMin) / (m_rtMax - m_rtMin));
+ // normally "detected" should always be less than "indicated", but sometimes it can be a few percent higher (+10% is allowed here)
+ // (update: also allowing +/-50k/s)
+ if(indicated_rate == 0 || ((float)detected_rate / indicated_rate) < 1.1 || abs(detected_rate - indicated_rate) < 50*1024)
+ m_rate = detected_rate;
+ else ; // TODO: in this case disable seeking, or try doing something less drastical...
+
+ if(m_streams[video].GetCount())
+ {
+ if (!m_bIsHdmv && m_streams[subpic].GetCount())
+ {
#ifndef DEBUG
- stream s;
- s.mt.majortype = m_streams[subpic].GetHead().mt.majortype;
- s.mt.subtype = m_streams[subpic].GetHead().mt.subtype;
- s.mt.formattype = m_streams[subpic].GetHead().mt.formattype;
- m_streams[subpic].Insert(s, this);
+ stream s;
+ s.mt.majortype = m_streams[subpic].GetHead().mt.majortype;
+ s.mt.subtype = m_streams[subpic].GetHead().mt.subtype;
+ s.mt.formattype = m_streams[subpic].GetHead().mt.formattype;
+ m_streams[subpic].Insert(s, this);
#endif
- }
- else
- {
- // Add fake stream for "No subtitle"
- AddHdmvPGStream(NO_SUBTITLE_PID, "---");
- }
- }
+ }
+ else
+ {
+ // Add fake stream for "No subtitle"
+ AddHdmvPGStream (NO_SUBTITLE_PID, "---");
+ }
+ }
- Seek(0);
+ Seek(0);
- return S_OK;
+ return S_OK;
}
void CMpegSplitterFile::OnComplete()
{
- __int64 pos = GetPos();
-
- if(SUCCEEDED(SearchStreams(GetLength() - 500 * 1024, GetLength())))
- {
- int indicated_rate = m_rate;
- int detected_rate = int(m_rtMax > m_rtMin ? 10000000i64 * (m_posMax - m_posMin) / (m_rtMax - m_rtMin) : 0);
- // normally "detected" should always be less than "indicated", but sometimes it can be a few percent higher (+10% is allowed here)
- // (update: also allowing +/-50k/s)
- if(indicated_rate == 0 || ((float)detected_rate / indicated_rate) < 1.1 || abs(detected_rate - indicated_rate) < 50 * 1024)
- m_rate = detected_rate;
- else ; // TODO: in this case disable seeking, or try doing something less drastical...
- }
-
- Seek(pos);
+ __int64 pos = GetPos();
+
+ if(SUCCEEDED(SearchStreams(GetLength() - 500*1024, GetLength())))
+ {
+ int indicated_rate = m_rate;
+ int detected_rate = int(m_rtMax > m_rtMin ? 10000000i64 * (m_posMax - m_posMin) / (m_rtMax - m_rtMin) : 0);
+ // normally "detected" should always be less than "indicated", but sometimes it can be a few percent higher (+10% is allowed here)
+ // (update: also allowing +/-50k/s)
+ if(indicated_rate == 0 || ((float)detected_rate / indicated_rate) < 1.1 || abs(detected_rate - indicated_rate) < 50*1024)
+ m_rate = detected_rate;
+ else ; // TODO: in this case disable seeking, or try doing something less drastical...
+ }
+
+ Seek(pos);
}
REFERENCE_TIME CMpegSplitterFile::NextPTS(DWORD TrackNum)
{
- REFERENCE_TIME rt = -1;
- __int64 rtpos = -1;
+ REFERENCE_TIME rt = -1;
+ __int64 rtpos = -1;
- BYTE b;
+ BYTE b;
- while(GetRemaining())
- {
- if(m_type == ps || m_type == es)
- {
- if(!NextMpegStartCode(b)) // continue;
- {
- ASSERT(0);
- break;
- }
+ while(GetRemaining())
+ {
+ if(m_type == ps || m_type == es)
+ {
+ if(!NextMpegStartCode(b)) // continue;
+ {
+ ASSERT(0);
+ break;
+ }
- rtpos = GetPos() - 4;
+ rtpos = GetPos()-4;
#if (EVO_SUPPORT == 0)
- if(b >= 0xbd && b < 0xf0)
+ if(b >= 0xbd && b < 0xf0)
#else
- if((b >= 0xbd && b < 0xf0) || (b == 0xfd))
+ if((b >= 0xbd && b < 0xf0) || (b == 0xfd))
#endif
- {
- peshdr h;
- if(!Read(h, b) || !h.len) continue;
-
- __int64 pos = GetPos();
-
- if(h.fpts && AddStream(0, b, h.len) == TrackNum)
- {
- ASSERT(h.pts >= m_rtMin && h.pts <= m_rtMax);
- rt = h.pts;
- break;
- }
-
- Seek(pos + h.len);
- }
- }
- else if(m_type == ts)
- {
- trhdr h;
- if(!Read(h)) continue;
-
- rtpos = GetPos() - 4;
-
- if(h.payload && h.payloadstart && ISVALIDPID(h.pid))
- {
- peshdr h2;
- if(NextMpegStartCode(b, 4) && Read(h2, b)) // pes packet
- {
- if(h2.fpts && AddStream(h.pid, b, DWORD(h.bytes - (GetPos() - rtpos)) == TrackNum))
- {
- ASSERT(h2.pts >= m_rtMin && h2.pts <= m_rtMax);
- rt = h2.pts;
- break;
- }
- }
- }
-
- Seek(h.next);
- }
- else if(m_type == pva)
- {
- pvahdr h;
- if(!Read(h)) continue;
-
- if(h.fpts)
- {
- rt = h.pts;
- break;
- }
- }
- }
-
- if(rtpos >= 0) Seek(rtpos);
- if(rt >= 0) rt -= m_rtMin;
-
- return rt;
+ {
+ peshdr h;
+ if(!Read(h, b) || !h.len) continue;
+
+ __int64 pos = GetPos();
+
+ if(h.fpts && AddStream(0, b, h.len) == TrackNum)
+ {
+ ASSERT(h.pts >= m_rtMin && h.pts <= m_rtMax);
+ rt = h.pts;
+ break;
+ }
+
+ Seek(pos + h.len);
+ }
+ }
+ else if(m_type == ts)
+ {
+ trhdr h;
+ if(!Read(h)) continue;
+
+ rtpos = GetPos()-4;
+
+ if(h.payload && h.payloadstart && ISVALIDPID(h.pid))
+ {
+ peshdr h2;
+ if(NextMpegStartCode(b, 4) && Read(h2, b)) // pes packet
+ {
+ if(h2.fpts && AddStream(h.pid, b, DWORD(h.bytes - (GetPos() - rtpos)) == TrackNum))
+ {
+ ASSERT(h2.pts >= m_rtMin && h2.pts <= m_rtMax);
+ rt = h2.pts;
+ break;
+ }
+ }
+ }
+
+ Seek(h.next);
+ }
+ else if(m_type == pva)
+ {
+ pvahdr h;
+ if(!Read(h)) continue;
+
+ if(h.fpts)
+ {
+ rt = h.pts;
+ break;
+ }
+ }
+ }
+
+ if(rtpos >= 0) Seek(rtpos);
+ if(rt >= 0) rt -= m_rtMin;
+
+ return rt;
}
HRESULT CMpegSplitterFile::SearchStreams(__int64 start, __int64 stop)
{
- Seek(start);
- stop = min(stop, GetLength());
-
- while(GetPos() < stop)
- {
- BYTE b;
-
- if(m_type == ps || m_type == es)
- {
- if(!NextMpegStartCode(b)) continue;
-
- if(b == 0xba) // program stream header
- {
- pshdr h;
- if(!Read(h)) continue;
- }
- else if(b == 0xbb) // program stream system header
- {
- pssyshdr h;
- if(!Read(h)) continue;
- }
+ Seek(start);
+ stop = min(stop, GetLength());
+
+ while(GetPos() < stop)
+ {
+ BYTE b;
+
+ if(m_type == ps || m_type == es)
+ {
+ if(!NextMpegStartCode(b)) continue;
+
+ if(b == 0xba) // program stream header
+ {
+ pshdr h;
+ if(!Read(h)) continue;
+ }
+ else if(b == 0xbb) // program stream system header
+ {
+ pssyshdr h;
+ if(!Read(h)) continue;
+ }
#if (EVO_SUPPORT == 0)
- else if(b >= 0xbd && b < 0xf0) // pes packet
+ else if(b >= 0xbd && b < 0xf0) // pes packet
#else
- else if((b >= 0xbd && b < 0xf0) || (b == 0xfd)) // pes packet
+ else if((b >= 0xbd && b < 0xf0) || (b == 0xfd)) // pes packet
#endif
- {
- peshdr h;
- if(!Read(h, b)) continue;
-
- if(h.type == mpeg2 && h.scrambling)
- {
- ASSERT(0);
- return E_FAIL;
- }
-
- if(h.fpts)
- {
- if(m_rtMin == _I64_MAX)
- {
- m_rtMin = h.pts;
- m_posMin = GetPos();
- }
- if(m_rtMin < h.pts && m_rtMax < h.pts)
- {
- m_rtMax = h.pts;
- m_posMax = GetPos();
- }
- }
-
- __int64 pos = GetPos();
- AddStream(0, b, h.len);
- if(h.len) Seek(pos + h.len);
- }
- }
- else if(m_type == ts)
- {
- trhdr h;
- if(!Read(h)) continue;
-
- __int64 pos = GetPos();
-
- if(h.payload && h.payloadstart)
- UpdatePrograms(h);
-
- if(h.payload && ISVALIDPID(h.pid))
- {
- peshdr h2;
- if(h.payloadstart && NextMpegStartCode(b, 4) && Read(h2, b)) // pes packet
- {
- if(h2.type == mpeg2 && h2.scrambling)
- {
- ASSERT(0);
- return E_FAIL;
- }
-
- if(h2.fpts)
- {
- if(m_rtMin == _I64_MAX)
- {
- m_rtMin = h2.pts;
- m_posMin = GetPos();
- }
-
- if(m_rtMin < h2.pts && m_rtMax < h2.pts)
- {
- m_rtMax = h2.pts;
- m_posMax = GetPos();
- }
- }
- }
- else
- b = 0;
-
- AddStream(h.pid, b, DWORD(h.bytes - (GetPos() - pos)));
- }
-
- Seek(h.next);
- }
- else if(m_type == pva)
- {
- pvahdr h;
- if(!Read(h)) continue;
-
- if(h.fpts)
- {
- if(m_rtMin == _I64_MAX)
- {
- m_rtMin = h.pts;
- m_posMin = GetPos();
- }
-
- if(m_rtMin < h.pts && m_rtMax < h.pts)
- {
- m_rtMax = h.pts;
- m_posMax = GetPos();
- }
- }
-
- __int64 pos = GetPos();
-
- if(h.streamid == 1)
- AddStream(h.streamid, 0xe0, h.length);
- else if(h.streamid == 2)
- AddStream(h.streamid, 0xc0, h.length);
-
- if(h.length)
- Seek(pos + h.length);
- }
- }
-
- return S_OK;
+ {
+ peshdr h;
+ if(!Read(h, b)) continue;
+
+ if(h.type == mpeg2 && h.scrambling) {ASSERT(0); return E_FAIL;}
+
+ if(h.fpts)
+ {
+ if(m_rtMin == _I64_MAX) {m_rtMin = h.pts; m_posMin = GetPos();}
+ if(m_rtMin < h.pts && m_rtMax < h.pts) {m_rtMax = h.pts; m_posMax = GetPos();}
+ }
+
+ __int64 pos = GetPos();
+ AddStream(0, b, h.len);
+ if(h.len) Seek(pos + h.len);
+ }
+ }
+ else if(m_type == ts)
+ {
+ trhdr h;
+ if(!Read(h)) continue;
+
+ __int64 pos = GetPos();
+
+ if(h.payload && h.payloadstart)
+ UpdatePrograms(h);
+
+ if(h.payload && ISVALIDPID(h.pid))
+ {
+ peshdr h2;
+ if(h.payloadstart && NextMpegStartCode(b, 4) && Read(h2, b)) // pes packet
+ {
+ if(h2.type == mpeg2 && h2.scrambling)
+ {
+ ASSERT(0);
+ return E_FAIL;
+ }
+
+ if(h2.fpts)
+ {
+ if(m_rtMin == _I64_MAX)
+ {
+ m_rtMin = h2.pts;
+ m_posMin = GetPos();
+ }
+
+ if(m_rtMin < h2.pts && m_rtMax < h2.pts)
+ {
+ m_rtMax = h2.pts;
+ m_posMax = GetPos();
+ }
+ }
+ }
+ else
+ b = 0;
+
+ AddStream(h.pid, b, DWORD(h.bytes - (GetPos() - pos)));
+ }
+
+ Seek(h.next);
+ }
+ else if(m_type == pva)
+ {
+ pvahdr h;
+ if(!Read(h)) continue;
+
+ if(h.fpts)
+ {
+ if(m_rtMin == _I64_MAX)
+ {
+ m_rtMin = h.pts;
+ m_posMin = GetPos();
+ }
+
+ if(m_rtMin < h.pts && m_rtMax < h.pts)
+ {
+ m_rtMax = h.pts;
+ m_posMax = GetPos();
+ }
+ }
+
+ __int64 pos = GetPos();
+
+ if(h.streamid == 1)
+ AddStream(h.streamid, 0xe0, h.length);
+ else if(h.streamid == 2)
+ AddStream(h.streamid, 0xc0, h.length);
+
+ if(h.length)
+ Seek(pos + h.length);
+ }
+ }
+
+ return S_OK;
}
DWORD CMpegSplitterFile::AddStream(WORD pid, BYTE pesid, DWORD len)
{
- if(pid)
- {
- if(pesid) m_pid2pes[pid] = pesid;
- else m_pid2pes.Lookup(pid, pesid);
- }
+ if(pid)
+ {
+ if(pesid) m_pid2pes[pid] = pesid;
+ else m_pid2pes.Lookup(pid, pesid);
+ }
- stream s;
- s.pid = pid;
- s.pesid = pesid;
+ stream s;
+ s.pid = pid;
+ s.pesid = pesid;
- int type = unknown;
+ int type = unknown;
- if(pesid >= 0xe0 && pesid < 0xf0) // mpeg video
- {
- __int64 pos = GetPos();
+ if(pesid >= 0xe0 && pesid < 0xf0) // mpeg video
+ {
+ __int64 pos = GetPos();
- if(type == unknown)
- {
- CMpegSplitterFile::seqhdr h;
- if(!m_streams[video].Find(s) && Read(h, len, &s.mt))
- type = video;
- }
+ if(type == unknown)
+ {
+ CMpegSplitterFile::seqhdr h;
+ if(!m_streams[video].Find(s) && Read(h, len, &s.mt))
+ type = video;
+ }
- Seek(pos);
+ Seek(pos);
- if(type == unknown)
- {
+ if(type == unknown)
+ {
// CMpegSplitterFile::avchdr h; <= PPS and SPS can be present on differents packets !
- if(!m_streams[video].Find(s) && Read(avch, len, &s.mt))
- type = video;
- }
- }
- else if(pesid >= 0xc0 && pesid < 0xe0) // mpeg audio
- {
- __int64 pos = GetPos();
-
- if(type == unknown)
- {
- CMpegSplitterFile::mpahdr h;
- if(!m_streams[audio].Find(s) && Read(h, len, false, &s.mt))
- type = audio;
- }
-
- Seek(pos);
-
- if(type == unknown)
- {
- CMpegSplitterFile::aachdr h;
- if(!m_streams[audio].Find(s) && Read(h, len, &s.mt))
- type = audio;
- }
- }
- else if(pesid == 0xbd || pesid == 0xfd) // private stream 1
- {
- if(s.pid)
- {
- if(!m_streams[audio].Find(s) && !m_streams[video].Find(s))
- {
- __int64 pos = GetPos();
-
- // AC3
- if(type == unknown)
- {
- CMpegSplitterFile::ac3hdr h;
- if(Read(h, len, &s.mt))
- type = audio;
- }
-
- // DTS
- Seek(pos);
- if(type == unknown)
- {
- CMpegSplitterFile::dtshdr h;
- if(Read(h, len, &s.mt))
- type = audio;
- }
-
- // VC1
- Seek(pos);
- if(type == unknown)
- {
- CMpegSplitterFile::vc1hdr h;
- if(!m_streams[video].Find(s) && Read(h, len, &s.mt))
- type = video;
- }
-
- // DVB subtitles
- Seek(pos);
- if(type == unknown)
- {
- CMpegSplitterFile::dvbsub h;
- if(!m_streams[video].Find(s) && Read(h, len, &s.mt))
- type = subpic;
- }
-
- int iProgram;
- const CHdmvClipInfo::Stream *pClipInfo;
- const program* pProgram = FindProgram(s.pid, iProgram, pClipInfo);
- if((type == unknown) && (pProgram != NULL))
- {
- PES_STREAM_TYPE StreamType = INVALID;
-
- Seek(pos);
- StreamType = pProgram->streams[iProgram].type;
-
- switch(StreamType)
- {
- case AUDIO_STREAM_LPCM :
- {
- CMpegSplitterFile::hdmvlpcmhdr h;
- if(!m_streams[audio].Find(s) && Read(h, &s.mt))
- type = audio;
- }
- break;
- case PRESENTATION_GRAPHICS_STREAM :
- {
- CMpegSplitterFile::hdmvsubhdr h;
- if(!m_streams[subpic].Find(s) && Read(h, &s.mt, pClipInfo ? pClipInfo->m_LanguageCode : NULL))
- {
- m_bIsHdmv = true;
- type = subpic;
- }
- }
- break;
- }
- }
- }
- }
+ if(!m_streams[video].Find(s) && Read(avch, len, &s.mt))
+ type = video;
+ }
+ }
+ else if(pesid >= 0xc0 && pesid < 0xe0) // mpeg audio
+ {
+ __int64 pos = GetPos();
+
+ if(type == unknown)
+ {
+ CMpegSplitterFile::mpahdr h;
+ if(!m_streams[audio].Find(s) && Read(h, len, false, &s.mt))
+ type = audio;
+ }
+
+ Seek(pos);
+
+ if(type == unknown)
+ {
+ CMpegSplitterFile::aachdr h;
+ if(!m_streams[audio].Find(s) && Read(h, len, &s.mt))
+ type = audio;
+ }
+ }
+ else if(pesid == 0xbd || pesid == 0xfd) // private stream 1
+ {
+ if(s.pid)
+ {
+ if(!m_streams[audio].Find(s) && !m_streams[video].Find(s))
+ {
+ __int64 pos = GetPos();
+
+ // AC3
+ if(type == unknown)
+ {
+ CMpegSplitterFile::ac3hdr h;
+ if(Read(h, len, &s.mt))
+ type = audio;
+ }
+
+ // DTS
+ Seek(pos);
+ if(type == unknown)
+ {
+ CMpegSplitterFile::dtshdr h;
+ if(Read(h, len, &s.mt))
+ type = audio;
+ }
+
+ // VC1
+ Seek(pos);
+ if(type == unknown)
+ {
+ CMpegSplitterFile::vc1hdr h;
+ if(!m_streams[video].Find(s) && Read(h, len, &s.mt))
+ type = video;
+ }
+
+ // DVB subtitles
+ Seek(pos);
+ if(type == unknown)
+ {
+ CMpegSplitterFile::dvbsub h;
+ if(!m_streams[video].Find(s) && Read(h, len, &s.mt))
+ type = subpic;
+ }
+
+ int iProgram;
+ const CHdmvClipInfo::Stream *pClipInfo;
+ const program* pProgram = FindProgram (s.pid, iProgram, pClipInfo);
+ if((type == unknown) && (pProgram != NULL))
+ {
+ PES_STREAM_TYPE StreamType = INVALID;
+
+ Seek(pos);
+ StreamType = pProgram->streams[iProgram].type;
+
+ switch (StreamType)
+ {
+ case AUDIO_STREAM_LPCM :
+ {
+ CMpegSplitterFile::hdmvlpcmhdr h;
+ if(!m_streams[audio].Find(s) && Read(h, &s.mt))
+ type = audio;
+ }
+ break;
+ case PRESENTATION_GRAPHICS_STREAM :
+ {
+ CMpegSplitterFile::hdmvsubhdr h;
+ if(!m_streams[subpic].Find(s) && Read(h, &s.mt, pClipInfo ? pClipInfo->m_LanguageCode : NULL))
+ {
+ m_bIsHdmv = true;
+ type = subpic;
+ }
+ }
+ break;
+ }
+ }
+ }
+ }
#if (EVO_SUPPORT != 0)
- else if(pesid == 0xfd) // TODO EVO SUPPORT
- {
- CMpegSplitterFile::vc1hdr h;
- if(!m_streams[video].Find(s) && Read(h, len, &s.mt))
- type = video;
- }
+ else if (pesid == 0xfd) // TODO EVO SUPPORT
+ {
+ CMpegSplitterFile::vc1hdr h;
+ if(!m_streams[video].Find(s) && Read(h, len, &s.mt))
+ type = video;
+ }
#endif
- else
- {
- BYTE b = (BYTE)BitRead(8, true);
- WORD w = (WORD)BitRead(16, true);
- DWORD dw = (DWORD)BitRead(32, true);
-
- if(b >= 0x80 && b < 0x88 || w == 0x0b77) // ac3
- {
- s.ps1id = (b >= 0x80 && b < 0x88) ? (BYTE)(BitRead(32) >> 24) : 0x80;
-
- CMpegSplitterFile::ac3hdr h;
- if(!m_streams[audio].Find(s) && Read(h, len, &s.mt))
- type = audio;
- }
- else if(b >= 0x88 && b < 0x90 || dw == 0x7ffe8001) // dts
- {
- s.ps1id = (b >= 0x88 && b < 0x90) ? (BYTE)(BitRead(32) >> 24) : 0x88;
-
- CMpegSplitterFile::dtshdr h;
- if(!m_streams[audio].Find(s) && Read(h, len, &s.mt))
- type = audio;
- }
- else if(b >= 0xa0 && b < 0xa8) // lpcm
- {
- s.ps1id = (b >= 0xa0 && b < 0xa8) ? (BYTE)(BitRead(32) >> 24) : 0xa0;
-
- CMpegSplitterFile::lpcmhdr h;
- if(Read(h, &s.mt) && !m_streams[audio].Find(s)) // note the reversed order, the header should be stripped always even if it's not a new stream
- type = audio;
- }
- else if(b >= 0x20 && b < 0x40) // DVD subpic
- {
- s.ps1id = (BYTE)BitRead(8);
-
- CMpegSplitterFile::dvdspuhdr h;
- if(!m_streams[subpic].Find(s) && Read(h, &s.mt))
- type = subpic;
- }
- else if(b >= 0x70 && b < 0x80) // SVCD subpic
- {
- s.ps1id = (BYTE)BitRead(8);
-
- CMpegSplitterFile::svcdspuhdr h;
- if(!m_streams[subpic].Find(s) && Read(h, &s.mt))
- type = subpic;
- }
- else if(b >= 0x00 && b < 0x10) // CVD subpic
- {
- s.ps1id = (BYTE)BitRead(8);
-
- CMpegSplitterFile::cvdspuhdr h;
- if(!m_streams[subpic].Find(s) && Read(h, &s.mt))
- type = subpic;
- }
- else if(w == 0xffa0 || w == 0xffa1) // ps2-mpg audio
- {
- s.ps1id = (BYTE)BitRead(8);
- s.pid = (WORD)((BitRead(8) << 8) | BitRead(16)); // pid = 0xa000 | track id
-
- CMpegSplitterFile::ps2audhdr h;
- if(!m_streams[audio].Find(s) && Read(h, &s.mt))
- type = audio;
- }
- else if(w == 0xff90) // ps2-mpg ac3 or subtitles
- {
- s.ps1id = (BYTE)BitRead(8);
- s.pid = (WORD)((BitRead(8) << 8) | BitRead(16)); // pid = 0x9000 | track id
-
- w = (WORD)BitRead(16, true);
-
- if(w == 0x0b77)
- {
- CMpegSplitterFile::ac3hdr h;
- if(!m_streams[audio].Find(s) && Read(h, len, &s.mt))
- type = audio;
- }
- else if(w == 0x0000) // usually zero...
- {
- CMpegSplitterFile::ps2subhdr h;
- if(!m_streams[subpic].Find(s) && Read(h, &s.mt))
- type = subpic;
- }
- }
+ else
+ {
+ BYTE b = (BYTE)BitRead(8, true);
+ WORD w = (WORD)BitRead(16, true);
+ DWORD dw = (DWORD)BitRead(32, true);
+
+ if(b >= 0x80 && b < 0x88 || w == 0x0b77) // ac3
+ {
+ s.ps1id = (b >= 0x80 && b < 0x88) ? (BYTE)(BitRead(32) >> 24) : 0x80;
+
+ CMpegSplitterFile::ac3hdr h;
+ if(!m_streams[audio].Find(s) && Read(h, len, &s.mt))
+ type = audio;
+ }
+ else if(b >= 0x88 && b < 0x90 || dw == 0x7ffe8001) // dts
+ {
+ s.ps1id = (b >= 0x88 && b < 0x90) ? (BYTE)(BitRead(32) >> 24) : 0x88;
+
+ CMpegSplitterFile::dtshdr h;
+ if(!m_streams[audio].Find(s) && Read(h, len, &s.mt))
+ type = audio;
+ }
+ else if(b >= 0xa0 && b < 0xa8) // lpcm
+ {
+ s.ps1id = (b >= 0xa0 && b < 0xa8) ? (BYTE)(BitRead(32) >> 24) : 0xa0;
+
+ CMpegSplitterFile::lpcmhdr h;
+ if(Read(h, &s.mt) && !m_streams[audio].Find(s)) // note the reversed order, the header should be stripped always even if it's not a new stream
+ type = audio;
+ }
+ else if(b >= 0x20 && b < 0x40) // DVD subpic
+ {
+ s.ps1id = (BYTE)BitRead(8);
+
+ CMpegSplitterFile::dvdspuhdr h;
+ if(!m_streams[subpic].Find(s) && Read(h, &s.mt))
+ type = subpic;
+ }
+ else if(b >= 0x70 && b < 0x80) // SVCD subpic
+ {
+ s.ps1id = (BYTE)BitRead(8);
+
+ CMpegSplitterFile::svcdspuhdr h;
+ if(!m_streams[subpic].Find(s) && Read(h, &s.mt))
+ type = subpic;
+ }
+ else if(b >= 0x00 && b < 0x10) // CVD subpic
+ {
+ s.ps1id = (BYTE)BitRead(8);
+
+ CMpegSplitterFile::cvdspuhdr h;
+ if(!m_streams[subpic].Find(s) && Read(h, &s.mt))
+ type = subpic;
+ }
+ else if(w == 0xffa0 || w == 0xffa1) // ps2-mpg audio
+ {
+ s.ps1id = (BYTE)BitRead(8);
+ s.pid = (WORD)((BitRead(8) << 8) | BitRead(16)); // pid = 0xa000 | track id
+
+ CMpegSplitterFile::ps2audhdr h;
+ if(!m_streams[audio].Find(s) && Read(h, &s.mt))
+ type = audio;
+ }
+ else if(w == 0xff90) // ps2-mpg ac3 or subtitles
+ {
+ s.ps1id = (BYTE)BitRead(8);
+ s.pid = (WORD)((BitRead(8) << 8) | BitRead(16)); // pid = 0x9000 | track id
+
+ w = (WORD)BitRead(16, true);
+
+ if(w == 0x0b77)
+ {
+ CMpegSplitterFile::ac3hdr h;
+ if(!m_streams[audio].Find(s) && Read(h, len, &s.mt))
+ type = audio;
+ }
+ else if(w == 0x0000) // usually zero...
+ {
+ CMpegSplitterFile::ps2subhdr h;
+ if(!m_streams[subpic].Find(s) && Read(h, &s.mt))
+ type = subpic;
+ }
+ }
#if (EVO_SUPPORT != 0)
- else if(b >= 0xc0 && b < 0xc8) // dolby digital +
- {
- s.ps1id = (BYTE)BitRead(8);
- s.pid = (WORD)((BitRead(8) << 8) | BitRead(16)); // pid = 0x9000 | track id
-
- w = (WORD)BitRead(16, true);
-
- if(w == 0x0b77)
- {
- CMpegSplitterFile::ac3hdr h;
- if(!m_streams[audio].Find(s) && Read(h, len, &s.mt))
- type = audio;
- }
- }
+ else if(b >= 0xc0 && b < 0xc8) // dolby digital +
+ {
+ s.ps1id = (BYTE)BitRead(8);
+ s.pid = (WORD)((BitRead(8) << 8) | BitRead(16)); // pid = 0x9000 | track id
+
+ w = (WORD)BitRead(16, true);
+
+ if(w == 0x0b77)
+ {
+ CMpegSplitterFile::ac3hdr h;
+ if(!m_streams[audio].Find(s) && Read(h, len, &s.mt))
+ type = audio;
+ }
+ }
#endif
- }
- }
- else if(pesid == 0xbe) // padding
- {
- }
- else if(pesid == 0xbf) // private stream 2
- {
- }
-
- if(type != unknown && !m_streams[type].Find(s))
- {
- if(s.pid)
- {
- for(int i = 0; i < unknown; i++)
- {
- if(m_streams[i].Find(s))
- {
- /*ASSERT(0);*/
- return s;
- }
- }
- }
-
- m_streams[type].Insert(s, this);
- }
-
- return s;
+ }
+ }
+ else if(pesid == 0xbe) // padding
+ {
+ }
+ else if(pesid == 0xbf) // private stream 2
+ {
+ }
+
+ if(type != unknown && !m_streams[type].Find(s))
+ {
+ if(s.pid)
+ {
+ for(int i = 0; i < unknown; i++)
+ {
+ if(m_streams[i].Find(s))
+ {
+ /*ASSERT(0);*/
+ return s;
+ }
+ }
+ }
+
+ m_streams[type].Insert(s, this);
+ }
+
+ return s;
}
void CMpegSplitterFile::AddHdmvPGStream(WORD pid, const char* language_code)
{
- stream s;
+ stream s;
- s.pid = pid;
- s.pesid = 0xbd;
+ s.pid = pid;
+ s.pesid = 0xbd;
- CMpegSplitterFile::hdmvsubhdr h;
- if(!m_streams[subpic].Find(s) && Read(h, &s.mt, language_code))
- {
- m_streams[subpic].Insert(s, this);
- }
+ CMpegSplitterFile::hdmvsubhdr h;
+ if(!m_streams[subpic].Find(s) && Read(h, &s.mt, language_code))
+ {
+ m_streams[subpic].Insert(s, this);
+ }
}
CAtlList<CMpegSplitterFile::stream>* CMpegSplitterFile::GetMasterStream()
{
- return
- !m_streams[video].IsEmpty() ? &m_streams[video] :
- !m_streams[audio].IsEmpty() ? &m_streams[audio] :
- !m_streams[subpic].IsEmpty() ? &m_streams[subpic] :
- NULL;
+ return
+ !m_streams[video].IsEmpty() ? &m_streams[video] :
+ !m_streams[audio].IsEmpty() ? &m_streams[audio] :
+ !m_streams[subpic].IsEmpty() ? &m_streams[subpic] :
+ NULL;
}
void CMpegSplitterFile::UpdatePrograms(const trhdr& h)
{
- CAutoLock cAutoLock(&m_csProps);
-
- if(h.pid == 0)
- {
- trsechdr h2;
- if(Read(h2) && h2.table_id == 0)
- {
- CAtlMap<WORD, bool> newprograms;
-
- int len = h2.section_length;
- len -= 5 + 4;
-
- for(int i = len / 4; i > 0; i--)
- {
- WORD program_number = (WORD)BitRead(16);
- BYTE reserved = (BYTE)BitRead(3);
- WORD pid = (WORD)BitRead(13);
- if(program_number != 0)
- {
- m_programs[pid].program_number = program_number;
- newprograms[program_number] = true;
- }
- }
-
- POSITION pos = m_programs.GetStartPosition();
- while(pos)
- {
- const CAtlMap<WORD, program>::CPair* pPair = m_programs.GetNext(pos);
-
- if(!newprograms.Lookup(pPair->m_value.program_number))
- {
- m_programs.RemoveKey(pPair->m_key);
- }
- }
- }
- }
- else if(CAtlMap<WORD, program>::CPair* pPair = m_programs.Lookup(h.pid))
- {
- trsechdr h2;
- if(Read(h2) && h2.table_id == 2)
- {
- memset(pPair->m_value.streams, 0, sizeof(pPair->m_value.streams));
-
- int len = h2.section_length;
- len -= 5 + 4;
-
- BYTE reserved1 = (BYTE)BitRead(3);
- WORD PCR_PID = (WORD)BitRead(13);
- BYTE reserved2 = (BYTE)BitRead(4);
- WORD program_info_length = (WORD)BitRead(12);
-
- len -= 4 + program_info_length;
-
- while(program_info_length-- > 0)
- BitRead(8);
-
- for(int i = 0; i < countof(pPair->m_value.streams) && len >= 5; i++)
- {
- BYTE stream_type = (BYTE)BitRead(8);
- BYTE nreserved1 = (BYTE)BitRead(3);
- WORD pid = (WORD)BitRead(13);
- BYTE nreserved2 = (BYTE)BitRead(4);
- WORD ES_info_length = (WORD)BitRead(12);
-
- len -= 5 + ES_info_length;
-
- while(ES_info_length-- > 0)
- BitRead(8);
-
- pPair->m_value.streams[i].pid = pid;
- pPair->m_value.streams[i].type = (PES_STREAM_TYPE)stream_type;
- }
- }
- }
+ CAutoLock cAutoLock(&m_csProps);
+
+ if(h.pid == 0)
+ {
+ trsechdr h2;
+ if(Read(h2) && h2.table_id == 0)
+ {
+ CAtlMap<WORD, bool> newprograms;
+
+ int len = h2.section_length;
+ len -= 5+4;
+
+ for(int i = len/4; i > 0; i--)
+ {
+ WORD program_number = (WORD)BitRead(16);
+ BYTE reserved = (BYTE)BitRead(3);
+ WORD pid = (WORD)BitRead(13);
+ if(program_number != 0)
+ {
+ m_programs[pid].program_number = program_number;
+ newprograms[program_number] = true;
+ }
+ }
+
+ POSITION pos = m_programs.GetStartPosition();
+ while(pos)
+ {
+ const CAtlMap<WORD, program>::CPair* pPair = m_programs.GetNext(pos);
+
+ if(!newprograms.Lookup(pPair->m_value.program_number))
+ {
+ m_programs.RemoveKey(pPair->m_key);
+ }
+ }
+ }
+ }
+ else if(CAtlMap<WORD, program>::CPair* pPair = m_programs.Lookup(h.pid))
+ {
+ trsechdr h2;
+ if(Read(h2) && h2.table_id == 2)
+ {
+ memset(pPair->m_value.streams, 0, sizeof(pPair->m_value.streams));
+
+ int len = h2.section_length;
+ len -= 5+4;
+
+ BYTE reserved1 = (BYTE)BitRead(3);
+ WORD PCR_PID = (WORD)BitRead(13);
+ BYTE reserved2 = (BYTE)BitRead(4);
+ WORD program_info_length = (WORD)BitRead(12);
+
+ len -= 4+program_info_length;
+
+ while(program_info_length-- > 0)
+ BitRead(8);
+
+ for(int i = 0; i < countof(pPair->m_value.streams) && len >= 5; i++)
+ {
+ BYTE stream_type = (BYTE)BitRead(8);
+ BYTE nreserved1 = (BYTE)BitRead(3);
+ WORD pid = (WORD)BitRead(13);
+ BYTE nreserved2 = (BYTE)BitRead(4);
+ WORD ES_info_length = (WORD)BitRead(12);
+
+ len -= 5+ES_info_length;
+
+ while(ES_info_length-- > 0)
+ BitRead(8);
+
+ pPair->m_value.streams[i].pid = pid;
+ pPair->m_value.streams[i].type = (PES_STREAM_TYPE)stream_type;
+ }
+ }
+ }
}
uint32 SwapLE(const uint32 &_Value)
{
- return (_Value & 0xFF) << 24 | ((_Value >> 8) & 0xFF) << 16 | ((_Value >> 16) & 0xFF) << 8 | ((_Value >> 24) & 0xFF) << 0;
+ return (_Value & 0xFF) << 24 | ((_Value>>8) & 0xFF) << 16 | ((_Value>>16) & 0xFF) << 8 | ((_Value>>24) & 0xFF) << 0;
}
uint16 SwapLE(const uint16 &_Value)
{
- return (_Value & 0xFF) << 8 | ((_Value >> 8) & 0xFF) << 0;
+ return (_Value & 0xFF) << 8 | ((_Value>>8) & 0xFF) << 0;
}
const CMpegSplitterFile::program* CMpegSplitterFile::FindProgram(WORD pid, int &iStream, const CHdmvClipInfo::Stream * &_pClipInfo)
{
- _pClipInfo = m_ClipInfo.FindStream(pid);
+ _pClipInfo = m_ClipInfo.FindStream(pid);
- iStream = -1;
+ iStream = -1;
- POSITION pos = m_programs.GetStartPosition();
+ POSITION pos = m_programs.GetStartPosition();
- while(pos)
- {
- program* p = &m_programs.GetNextValue(pos);
+ while(pos)
+ {
+ program* p = &m_programs.GetNextValue(pos);
- for(int i = 0; i < countof(p->streams); i++)
- {
- if(p->streams[i].pid == pid)
- {
- iStream = i;
- return p;
- }
- }
- }
+ for(int i = 0; i < countof(p->streams); i++)
+ {
+ if(p->streams[i].pid == pid)
+ {
+ iStream = i;
+ return p;
+ }
+ }
+ }
- return NULL;
+ return NULL;
}
diff --git a/src/filters/parser/MpegSplitter/MpegSplitterFile.h b/src/filters/parser/MpegSplitter/MpegSplitterFile.h
index 237beb3e6..d9bee0f42 100644
--- a/src/filters/parser/MpegSplitter/MpegSplitterFile.h
+++ b/src/filters/parser/MpegSplitter/MpegSplitterFile.h
@@ -1,4 +1,4 @@
-/*
+/*
* Copyright (C) 2003-2006 Gabest
* http://www.gabest.org
*
@@ -6,15 +6,15 @@
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2, or (at your option)
* any later version.
- *
+ *
* This Program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with GNU Make; see the file COPYING. If not, write to
- * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
+ * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
* http://www.gnu.org/copyleft/gpl.html
*
*/
@@ -30,122 +30,103 @@
class CMpegSplitterFile : public CBaseSplitterFileEx
{
- CAtlMap<WORD, BYTE> m_pid2pes;
- CMpegSplitterFile::avchdr avch;
- bool m_bIsHdmv;
+ CAtlMap<WORD, BYTE> m_pid2pes;
+ CMpegSplitterFile::avchdr avch;
+ bool m_bIsHdmv;
- HRESULT Init();
+ HRESULT Init();
- void OnComplete();
+ void OnComplete();
public:
- CHdmvClipInfo &m_ClipInfo;
- CMpegSplitterFile(IAsyncReader* pAsyncReader, HRESULT& hr, bool bIsHdmv, CHdmvClipInfo &ClipInfo);
-
- REFERENCE_TIME NextPTS(DWORD TrackNum);
-
- CCritSec m_csProps;
-
- enum {us, ps, ts, es, pva} m_type;
-
- REFERENCE_TIME m_rtMin, m_rtMax;
- __int64 m_posMin, m_posMax;
- int m_rate; // byte/sec
-
- struct stream
- {
- CMpegSplitterFile *m_pFile;
- CMediaType mt;
- WORD pid;
- BYTE pesid, ps1id;
- bool operator < (const stream &_Other) const;
- struct stream()
- {
- pid = pesid = ps1id = 0;
- }
- operator DWORD() const
- {
- return pid ? pid : ((pesid << 8) | ps1id);
- }
- bool operator == (const struct stream& s) const
- {
- return (DWORD) * this == (DWORD)s;
- }
- };
-
- enum {video, audio, subpic, unknown};
-
- class CStreamList : public CAtlList<stream>
- {
- public:
- void Insert(stream& s, CMpegSplitterFile *_pFile)
- {
- s.m_pFile = _pFile;
- for(POSITION pos = GetHeadPosition(); pos; GetNext(pos))
- {
- stream& s2 = GetAt(pos);
- if(s < s2)
- {
- InsertBefore(pos, s);
- return;
- }
- }
-
- AddTail(s);
- }
-
- static CStringW ToString(int type)
- {
- return
- type == video ? L"Video" :
- type == audio ? L"Audio" :
- type == subpic ? L"Subtitle" :
- L"Unknown";
- }
-
- const stream* FindStream(int pid)
- {
- for(POSITION pos = GetHeadPosition(); pos; GetNext(pos))
- {
- const stream& s = GetAt(pos);
- if(s.pid == pid) return &s;
- }
-
- return NULL;
- }
-
- } m_streams[unknown];
-
- HRESULT SearchStreams(__int64 start, __int64 stop);
- DWORD AddStream(WORD pid, BYTE pesid, DWORD len);
- void AddHdmvPGStream(WORD pid, const char* language_code);
- CAtlList<stream>* GetMasterStream();
- bool IsHdmv()
- {
- return m_bIsHdmv;
- };
-
- struct program
- {
- WORD program_number;
- struct stream
- {
- WORD pid;
- PES_STREAM_TYPE type;
-
- };
- stream streams[64];
- struct program()
- {
- memset(this, 0, sizeof(*this));
- }
- };
-
- CAtlMap<WORD, program> m_programs;
-
- void UpdatePrograms(const trhdr& h);
- const program* FindProgram(WORD pid, int &iStream, const CHdmvClipInfo::Stream * &_pClipInfo);
-
-
+ CHdmvClipInfo &m_ClipInfo;
+ CMpegSplitterFile(IAsyncReader* pAsyncReader, HRESULT& hr, bool bIsHdmv, CHdmvClipInfo &ClipInfo);
+
+ REFERENCE_TIME NextPTS(DWORD TrackNum);
+
+ CCritSec m_csProps;
+
+ enum {us, ps, ts, es, pva} m_type;
+
+ REFERENCE_TIME m_rtMin, m_rtMax;
+ __int64 m_posMin, m_posMax;
+ int m_rate; // byte/sec
+
+ struct stream
+ {
+ CMpegSplitterFile *m_pFile;
+ CMediaType mt;
+ WORD pid;
+ BYTE pesid, ps1id;
+ bool operator < (const stream &_Other) const;
+ struct stream() {pid = pesid = ps1id = 0;}
+ operator DWORD() const {return pid ? pid : ((pesid<<8)|ps1id);}
+ bool operator == (const struct stream& s) const {return (DWORD)*this == (DWORD)s;}
+ };
+
+ enum {video, audio, subpic, unknown};
+
+ class CStreamList : public CAtlList<stream>
+ {
+ public:
+ void Insert(stream& s, CMpegSplitterFile *_pFile)
+ {
+ s.m_pFile = _pFile;
+ for(POSITION pos = GetHeadPosition(); pos; GetNext(pos))
+ {
+ stream& s2 = GetAt(pos);
+ if(s < s2) {InsertBefore(pos, s); return;}
+ }
+
+ AddTail(s);
+ }
+
+ static CStringW ToString(int type)
+ {
+ return
+ type == video ? L"Video" :
+ type == audio ? L"Audio" :
+ type == subpic ? L"Subtitle" :
+ L"Unknown";
+ }
+
+ const stream* FindStream(int pid)
+ {
+ for(POSITION pos = GetHeadPosition(); pos; GetNext(pos))
+ {
+ const stream& s = GetAt(pos);
+ if(s.pid == pid) return &s;
+ }
+
+ return NULL;
+ }
+
+ } m_streams[unknown];
+
+ HRESULT SearchStreams(__int64 start, __int64 stop);
+ DWORD AddStream(WORD pid, BYTE pesid, DWORD len);
+ void AddHdmvPGStream(WORD pid, const char* language_code);
+ CAtlList<stream>* GetMasterStream();
+ bool IsHdmv() { return m_bIsHdmv; };
+
+ struct program
+ {
+ WORD program_number;
+ struct stream
+ {
+ WORD pid;
+ PES_STREAM_TYPE type;
+
+ };
+ stream streams[64];
+ struct program() {memset(this, 0, sizeof(*this));}
+ };
+
+ CAtlMap<WORD, program> m_programs;
+
+ void UpdatePrograms(const trhdr& h);
+ const program* FindProgram(WORD pid, int &iStream, const CHdmvClipInfo::Stream * &_pClipInfo);
+
+
};
diff --git a/src/filters/parser/MpegSplitter/resource.h b/src/filters/parser/MpegSplitter/resource.h
index 51170d5ba..1ae4564c5 100644
--- a/src/filters/parser/MpegSplitter/resource.h
+++ b/src/filters/parser/MpegSplitter/resource.h
@@ -4,7 +4,7 @@
//
// Next default values for new objects
-//
+//
#ifdef APSTUDIO_INVOKED
#ifndef APSTUDIO_READONLY_SYMBOLS
#define _APS_NEXT_RESOURCE_VALUE 101
diff --git a/src/filters/parser/MpegSplitter/stdafx.cpp b/src/filters/parser/MpegSplitter/stdafx.cpp
index e1ec5adac..4284c08d9 100644
--- a/src/filters/parser/MpegSplitter/stdafx.cpp
+++ b/src/filters/parser/MpegSplitter/stdafx.cpp
@@ -1,4 +1,4 @@
-/*
+/*
* Copyright (C) 2003-2006 Gabest
* http://www.gabest.org
*
@@ -6,15 +6,15 @@
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2, or (at your option)
* any later version.
- *
+ *
* This Program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with GNU Make; see the file COPYING. If not, write to
- * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
+ * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
* http://www.gnu.org/copyleft/gpl.html
*
*/
diff --git a/src/filters/parser/MpegSplitter/stdafx.h b/src/filters/parser/MpegSplitter/stdafx.h
index c0b16b75c..aefacf4f0 100644
--- a/src/filters/parser/MpegSplitter/stdafx.h
+++ b/src/filters/parser/MpegSplitter/stdafx.h
@@ -1,4 +1,4 @@
-/*
+/*
* Copyright (C) 2003-2006 Gabest
* http://www.gabest.org
*
@@ -6,15 +6,15 @@
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2, or (at your option)
* any later version.
- *
+ *
* This Program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with GNU Make; see the file COPYING. If not, write to
- * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
+ * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
* http://www.gnu.org/copyleft/gpl.html
*
*/
diff --git a/src/filters/parser/NutSplitter/NutFile.cpp b/src/filters/parser/NutSplitter/NutFile.cpp
index 519558e33..dc72f1de8 100644
--- a/src/filters/parser/NutSplitter/NutFile.cpp
+++ b/src/filters/parser/NutSplitter/NutFile.cpp
@@ -2,126 +2,122 @@
#include "NutFile.h"
CNutFile::CNutFile(IAsyncReader* pAsyncReader, HRESULT& hr)
- : CBaseSplitterFile(pAsyncReader, hr)
+ : CBaseSplitterFile(pAsyncReader, hr)
{
- if(FAILED(hr)) return;
- hr = Init();
+ if(FAILED(hr)) return;
+ hr = Init();
}
HRESULT CNutFile::Init()
{
- Seek(0);
-
- if(BitRead(64) != NUTM)
- return E_FAIL;
-
- m_streams.RemoveAll();
-
- Seek(0);
-
- while(GetRemaining())
- {
- frame_header fh;
- fh.checksum_flag = 1;
-
- UINT64 id = 0;
-
- if(BitRead(1, true) == 0
- || (id = BitRead(64)) == NUTK)
- break;
-
- packet_header ph;
- Read(ph);
-
- if(id == NUTM)
- {
- Read(m_mh);
- }
- else if(id == NUTS)
- {
- CAutoPtr<stream_header> sh(DNew stream_header());
- Read(*sh);
- if(sh->stream_class == SC_VIDEO) Read(sh->vsh);
- else if(sh->stream_class == SC_AUDIO) Read(sh->ash);
- // else if(sh->stream_class == SC_SUBTITLE) ; // nothing to do
- m_streams.AddTail(sh);
- }
- else if(id == NUTX)
- {
- index_header ih;
- Read(ih);
- }
- else if(id == NUTI)
- {
- info_header ih;
- Read(ih);
- }
- else if(id == 0) // frame
- {
- ASSERT(0);
- break;
- }
-
- if(fh.checksum_flag)
- {
- Seek(ph.pos + ph.fptr - 4);
- ph.checksum = (UINT32)BitRead(32);
- }
-
- Seek(ph.pos + ph.fptr);
- }
-
- Seek(0);
-
- return m_streams.GetCount() ? S_OK : E_FAIL;
+ Seek(0);
+
+ if(BitRead(64) != NUTM)
+ return E_FAIL;
+
+ m_streams.RemoveAll();
+
+ Seek(0);
+
+ while(GetRemaining())
+ {
+ frame_header fh;
+ fh.checksum_flag = 1;
+
+ UINT64 id = 0;
+
+ if(BitRead(1, true) == 0
+ || (id = BitRead(64)) == NUTK)
+ break;
+
+ packet_header ph;
+ Read(ph);
+
+ if(id == NUTM)
+ {
+ Read(m_mh);
+ }
+ else if(id == NUTS)
+ {
+ CAutoPtr<stream_header> sh(DNew stream_header());
+ Read(*sh);
+ if(sh->stream_class == SC_VIDEO) Read(sh->vsh);
+ else if(sh->stream_class == SC_AUDIO) Read(sh->ash);
+ // else if(sh->stream_class == SC_SUBTITLE) ; // nothing to do
+ m_streams.AddTail(sh);
+ }
+ else if(id == NUTX)
+ {
+ index_header ih;
+ Read(ih);
+ }
+ else if(id == NUTI)
+ {
+ info_header ih;
+ Read(ih);
+ }
+ else if(id == 0) // frame
+ {
+ ASSERT(0);
+ break;
+ }
+
+ if(fh.checksum_flag)
+ {
+ Seek(ph.pos + ph.fptr - 4);
+ ph.checksum = (UINT32)BitRead(32);
+ }
+
+ Seek(ph.pos + ph.fptr);
+ }
+
+ Seek(0);
+
+ return m_streams.GetCount() ? S_OK : E_FAIL;
}
void CNutFile::Read(vint& vi)
{
- vi = 0;
- bool more;
- do
- {
- more = !!BitRead(1);
- vi = (vi << 7) | BitRead(7);
- }
- while(more);
+ vi = 0;
+ bool more;
+ do {more = !!BitRead(1); vi = (vi << 7) | BitRead(7);}
+ while(more);
}
void CNutFile::Read(svint& svi)
{
- vint vi;
- Read(vi);
- vi++;
- if(vi & 1) svi = -((svint)vi >> 1);
- else svi = ((svint)vi >> 1);
+ vint vi;
+ Read(vi);
+ vi++;
+ if(vi&1) svi = -((svint)vi>>1);
+ else svi = ((svint)vi>>1);
}
void CNutFile::Read(binary& b)
{
- vint len;
- Read(len);
- b.SetCount((INT_PTR)len);
- for(BYTE* buff = b.GetData(); len-- > 0; *buff++ = (BYTE)BitRead(8));
+ vint len;
+ Read(len);
+ b.SetCount((INT_PTR)len);
+ for(BYTE* buff = b.GetData(); len-- > 0; *buff++ = (BYTE)BitRead(8));
}
void CNutFile::Read(packet_header& ph)
{
- ph.pos = GetPos();
- Read(ph.fptr);
- Read(ph.bptr);
+ ph.pos = GetPos();
+ Read(ph.fptr);
+ Read(ph.bptr);
}
void CNutFile::Read(main_header& mh)
{
- Read(mh.version);
- Read(mh.stream_count);
+ Read(mh.version);
+ Read(mh.stream_count);
}
void CNutFile::Read(stream_header& sh)
{
- Read(sh.stream_id);
- Read(sh.stream_class);
+ Read(sh.stream_id);
+ Read(sh.stream_class);
Read(sh.fourcc);
Read(sh.average_bitrate);
Read(sh.language_code);
@@ -132,64 +128,64 @@ void CNutFile::Read(stream_header& sh)
sh.fixed_fps = BitRead(1);
sh.index_flag = BitRead(1);
sh.reserved = BitRead(6);
- while(1)
- {
- CAutoPtr<codec_specific> p(DNew codec_specific());
- Read(p->type);
- if(p->type == 0) break;
- Read(p->data);
- sh.cs.AddTail(p);
- }
+ while(1)
+ {
+ CAutoPtr<codec_specific> p(DNew codec_specific());
+ Read(p->type);
+ if(p->type == 0) break;
+ Read(p->data);
+ sh.cs.AddTail(p);
+ }
}
void CNutFile::Read(video_stream_header& vsh)
{
- Read(vsh.width);
- Read(vsh.height);
- Read(vsh.sample_width);
- Read(vsh.sample_height);
- Read(vsh.colorspace_type);
+ Read(vsh.width);
+ Read(vsh.height);
+ Read(vsh.sample_width);
+ Read(vsh.sample_height);
+ Read(vsh.colorspace_type);
}
void CNutFile::Read(audio_stream_header& ash)
{
- Read(ash.samplerate_mul);
- Read(ash.channel_count);
+ Read(ash.samplerate_mul);
+ Read(ash.channel_count);
}
void CNutFile::Read(index_header& ih)
{
- Read(ih.stream_id);
-
- vint len;
- Read(len);
- ih.ie.SetCount((INT_PTR)len);
- for(index_entry* p = ih.ie.GetData(); len-- > 0;)
- {
- Read(p->timestamp);
- Read(p->position);
- }
+ Read(ih.stream_id);
+
+ vint len;
+ Read(len);
+ ih.ie.SetCount((INT_PTR)len);
+ for(index_entry* p = ih.ie.GetData(); len-- > 0;)
+ {
+ Read(p->timestamp);
+ Read(p->position);
+ }
}
void CNutFile::Read(info_header& ih)
{
- // TODO
- /*
- for(;;){
- id v
- if(id==0) break
- name= info_table[id][0]
- type= info_table[id][1]
- if(type==NULL)
- type b
- if(name==NULL)
- name b
- if(type=="v")
- value v
- else if(type=="s")
- value s
- else
- value b
- }
- */
+ // TODO
+/*
+ for(;;){
+ id v
+ if(id==0) break
+ name= info_table[id][0]
+ type= info_table[id][1]
+ if(type==NULL)
+ type b
+ if(name==NULL)
+ name b
+ if(type=="v")
+ value v
+ else if(type=="s")
+ value s
+ else
+ value b
+ }
+*/
}
diff --git a/src/filters/parser/NutSplitter/NutFile.h b/src/filters/parser/NutSplitter/NutFile.h
index a3c5d163d..ab2a0a7e1 100644
--- a/src/filters/parser/NutSplitter/NutFile.h
+++ b/src/filters/parser/NutSplitter/NutFile.h
@@ -4,125 +4,121 @@
class CNutFile : public CBaseSplitterFile
{
- HRESULT Init();
+ HRESULT Init();
public:
#pragma pack(push, 1)
- typedef UINT64 vint;
- typedef INT64 svint;
- typedef CAtlArray<BYTE> binary;
- typedef CAtlArray<BYTE> string;
-
- struct packet_header
- {
- __int64 pos;
- vint fptr, bptr;
- UINT32 checksum;
- };
-
- struct main_header
- {
- vint version;
- vint stream_count;
- };
-
- struct codec_specific
- {
- vint type;
- binary data;
- };
-
- struct video_stream_header
- {
- vint width, height;
- vint sample_width, sample_height;
- vint colorspace_type;
- };
-
- struct audio_stream_header
- {
- vint samplerate_mul;
- vint channel_count;
- };
-
- struct stream_header
- {
+ typedef UINT64 vint;
+ typedef INT64 svint;
+ typedef CAtlArray<BYTE> binary;
+ typedef CAtlArray<BYTE> string;
+
+ struct packet_header
+ {
+ __int64 pos;
+ vint fptr, bptr;
+ UINT32 checksum;
+ };
+
+ struct main_header
+ {
+ vint version;
+ vint stream_count;
+ };
+
+ struct codec_specific
+ {
+ vint type;
+ binary data;
+ };
+
+ struct video_stream_header
+ {
+ vint width, height;
+ vint sample_width, sample_height;
+ vint colorspace_type;
+ };
+
+ struct audio_stream_header
+ {
+ vint samplerate_mul;
+ vint channel_count;
+ };
+
+ struct stream_header
+ {
+ vint stream_id;
+ vint stream_class;
+ string fourcc;
+ vint average_bitrate;
+ string language_code;
+ vint time_base_nom;
+ vint time_base_denom;
+ vint msb_timestamp_shift;
+ vint shuffle_type;
+ int fixed_fps:1;
+ int index_flag:1;
+ int reserved:6;
+ CAutoPtrList<codec_specific> cs;
+ union {video_stream_header vsh; audio_stream_header ash;};
+ vint msb_timestamp;
+ };
+
+ struct frame_header
+ {
+ BYTE zero_bit:1;
+ BYTE priority:2;
+ BYTE checksum_flag:1;
+ BYTE msb_timestamp_flag:2;
+ BYTE subpacket_type:2;
+ BYTE reserved:1;
+ };
+
+ struct index_entry
+ {
+ vint timestamp;
+ vint position;
+ };
+
+ struct index_header
+ {
vint stream_id;
- vint stream_class;
- string fourcc;
- vint average_bitrate;
- string language_code;
- vint time_base_nom;
- vint time_base_denom;
- vint msb_timestamp_shift;
- vint shuffle_type;
- int fixed_fps: 1;
- int index_flag: 1;
- int reserved: 6;
- CAutoPtrList<codec_specific> cs;
- union
- {
- video_stream_header vsh;
- audio_stream_header ash;
- };
- vint msb_timestamp;
- };
-
- struct frame_header
- {
- BYTE zero_bit: 1;
- BYTE priority: 2;
- BYTE checksum_flag: 1;
- BYTE msb_timestamp_flag: 2;
- BYTE subpacket_type: 2;
- BYTE reserved: 1;
- };
-
- struct index_entry
- {
- vint timestamp;
- vint position;
- };
-
- struct index_header
- {
- vint stream_id;
- CAtlArray<index_entry> ie;
- };
+ CAtlArray<index_entry> ie;
+ };
- struct info_header
- {
- // TODO
- vint dummy;
- };
+ struct info_header
+ {
+ // TODO
+ vint dummy;
+ };
#pragma pack(pop)
-#define NUTM 0xF9526A624E55544Dui64
-#define NUTS 0xD667773F4E555453ui64
-#define NUTK 0xCB8630874E55544Bui64
-#define NUTX 0xEBFCDE0E4E555458ui64
-#define NUTI 0xA37B64354E555449ui64
-
- enum {SC_VIDEO = 0, SC_AUDIO = 32, SC_SUBTITLE = 64};
-
- void Read(vint& v);
- void Read(svint& sv);
- void Read(binary& b);
- void Read(packet_header& ph);
- void Read(main_header& mh);
- void Read(stream_header& sh);
- void Read(video_stream_header& vsh);
- void Read(audio_stream_header& ash);
- void Read(index_header& ih);
- void Read(info_header& ih);
+ #define NUTM 0xF9526A624E55544Dui64
+ #define NUTS 0xD667773F4E555453ui64
+ #define NUTK 0xCB8630874E55544Bui64
+ #define NUTX 0xEBFCDE0E4E555458ui64
+ #define NUTI 0xA37B64354E555449ui64
+
+ enum {SC_VIDEO = 0, SC_AUDIO = 32, SC_SUBTITLE = 64};
+
+ void Read(vint& v);
+ void Read(svint& sv);
+ void Read(binary& b);
+ void Read(packet_header& ph);
+ void Read(main_header& mh);
+ void Read(stream_header& sh);
+ void Read(video_stream_header& vsh);
+ void Read(audio_stream_header& ash);
+ void Read(index_header& ih);
+ void Read(info_header& ih);
public:
- CNutFile(IAsyncReader* pAsyncReader, HRESULT& hr);
+ CNutFile(IAsyncReader* pAsyncReader, HRESULT& hr);
- main_header m_mh;
- CAutoPtrList<stream_header> m_streams;
+ main_header m_mh;
+ CAutoPtrList<stream_header> m_streams;
};
diff --git a/src/filters/parser/NutSplitter/NutSplitter.cpp b/src/filters/parser/NutSplitter/NutSplitter.cpp
index 723c38d3b..56b1f81c1 100644
--- a/src/filters/parser/NutSplitter/NutSplitter.cpp
+++ b/src/filters/parser/NutSplitter/NutSplitter.cpp
@@ -1,4 +1,4 @@
-/*
+/*
* Copyright (C) 2003-2006 Gabest
* http://www.gabest.org
*
@@ -6,15 +6,15 @@
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2, or (at your option)
* any later version.
- *
+ *
* This Program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with GNU Make; see the file COPYING. If not, write to
- * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
+ * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
* http://www.gnu.org/copyleft/gpl.html
*
*/
@@ -28,8 +28,8 @@
const AMOVIESETUP_MEDIATYPE sudPinTypesIn[] =
{
- {&MEDIATYPE_Stream, &MEDIASUBTYPE_Nut},
- {&MEDIATYPE_Stream, &MEDIASUBTYPE_NULL},
+ {&MEDIATYPE_Stream, &MEDIASUBTYPE_Nut},
+ {&MEDIATYPE_Stream, &MEDIASUBTYPE_NULL},
};
const AMOVIESETUP_PIN sudpPins[] =
@@ -40,30 +40,30 @@ const AMOVIESETUP_PIN sudpPins[] =
const AMOVIESETUP_FILTER sudFilter[] =
{
- {&__uuidof(CNutSplitterFilter), L"MPC - Nut Splitter", MERIT_NORMAL + 1, countof(sudpPins), sudpPins, CLSID_LegacyAmFilterCategory},
- {&__uuidof(CNutSourceFilter), L"MPC - Nut Source", MERIT_NORMAL + 1, 0, NULL, CLSID_LegacyAmFilterCategory},
+ {&__uuidof(CNutSplitterFilter), L"MPC - Nut Splitter", MERIT_NORMAL+1, countof(sudpPins), sudpPins, CLSID_LegacyAmFilterCategory},
+ {&__uuidof(CNutSourceFilter), L"MPC - Nut Source", MERIT_NORMAL+1, 0, NULL, CLSID_LegacyAmFilterCategory},
};
CFactoryTemplate g_Templates[] =
{
- {sudFilter[0].strName, sudFilter[0].clsID, CreateInstance<CNutSplitterFilter>, NULL, &sudFilter[0]},
- {sudFilter[1].strName, sudFilter[1].clsID, CreateInstance<CNutSourceFilter>, NULL, &sudFilter[1]},
+ {sudFilter[0].strName, sudFilter[0].clsID, CreateInstance<CNutSplitterFilter>, NULL, &sudFilter[0]},
+ {sudFilter[1].strName, sudFilter[1].clsID, CreateInstance<CNutSourceFilter>, NULL, &sudFilter[1]},
};
int g_cTemplates = countof(g_Templates);
STDAPI DllRegisterServer()
{
- RegisterSourceFilter(CLSID_AsyncReader, MEDIASUBTYPE_Nut, _T("0,8,,F9526A624E55544D"), _T(".nut"), NULL);
+ RegisterSourceFilter(CLSID_AsyncReader, MEDIASUBTYPE_Nut, _T("0,8,,F9526A624E55544D"), _T(".nut"), NULL);
- return AMovieDllRegisterServer2(TRUE);
+ return AMovieDllRegisterServer2(TRUE);
}
STDAPI DllUnregisterServer()
{
- UnRegisterSourceFilter(MEDIASUBTYPE_Nut);
+ UnRegisterSourceFilter(MEDIASUBTYPE_Nut);
- return AMovieDllRegisterServer2(FALSE);
+ return AMovieDllRegisterServer2(FALSE);
}
#include "../../FilterApp.h"
@@ -77,261 +77,253 @@ CFilterApp theApp;
//
CNutSplitterFilter::CNutSplitterFilter(LPUNKNOWN pUnk, HRESULT* phr)
- : CBaseSplitterFilter(NAME("CNutSplitterFilter"), pUnk, phr, __uuidof(this))
+ : CBaseSplitterFilter(NAME("CNutSplitterFilter"), pUnk, phr, __uuidof(this))
{
}
HRESULT CNutSplitterFilter::CreateOutputs(IAsyncReader* pAsyncReader)
{
- CheckPointer(pAsyncReader, E_POINTER);
-
- HRESULT hr = E_FAIL;
-
- m_pFile.Free();
-
- m_pFile.Attach(DNew CNutFile(pAsyncReader, hr));
- if(!m_pFile) return E_OUTOFMEMORY;
- if(FAILED(hr))
- {
- m_pFile.Free();
- return hr;
- }
-
- m_rtNewStart = m_rtCurrent = 0;
- m_rtNewStop = m_rtStop = m_rtDuration = 0;
-
- // pins
-
- POSITION pos = m_pFile->m_streams.GetHeadPosition();
- while(pos)
- {
- CNutFile::stream_header* sh = m_pFile->m_streams.GetNext(pos);
-
- CAtlArray<CMediaType> mts;
- CMediaType mt;
-
- if(sh->stream_class == CNutFile::SC_VIDEO)
- {
- CNutFile::video_stream_header& vsh = sh->vsh;
-
- mt.majortype = MEDIATYPE_Video;
- mt.subtype = FOURCCMap(*(DWORD*)sh->fourcc.GetData());
- mt.formattype = FORMAT_VideoInfo;
-
- VIDEOINFOHEADER vih;
- memset(&vih, 0, sizeof(vih));
- vih.dwBitRate = (DWORD)sh->average_bitrate;
- vih.AvgTimePerFrame = 10000000i64 * sh->time_base_nom / sh->time_base_denom;
- vih.bmiHeader.biSize = sizeof(vih.bmiHeader);
- vih.bmiHeader.biCompression = mt.subtype.Data1;
- vih.bmiHeader.biWidth = (LONG)vsh.width;
- vih.bmiHeader.biHeight = (LONG)vsh.height;
- mt.SetFormat((BYTE*)&vih, sizeof(vih));
-
- mts.Add(mt);
-
- if(vsh.sample_width && vsh.sample_height)
- {
- VIDEOINFOHEADER2 vih2;
- memset(&vih2, 0, sizeof(vih2));
- vih2.dwBitRate = vih.dwBitRate;
- vih2.AvgTimePerFrame = vih.AvgTimePerFrame;
- vih2.dwPictAspectRatioX = (DWORD)vsh.sample_width;
- vih2.dwPictAspectRatioY = (DWORD)vsh.sample_height;
- vih2.bmiHeader = vih.bmiHeader;
- mt.SetFormat((BYTE*)&vih2, sizeof(vih2));
-
- mts.InsertAt(0, mt);
- }
- }
- else if(sh->stream_class == CNutFile::SC_AUDIO)
- {
- CNutFile::audio_stream_header& ash = sh->ash;
- // TODO
- }
- else if(sh->stream_class == CNutFile::SC_SUBTITLE)
- {
- // TODO
- }
-
- if(mts.GetCount() > 0)
- {
- CAutoPtr<CBaseSplitterOutputPin> pPinOut(DNew CBaseSplitterOutputPin(mts, L"Video", this, this, &hr));
- AddOutputPin((DWORD)sh->stream_id, pPinOut);
- }
- }
-
- // TODO
- m_rtNewStop = m_rtStop = m_rtDuration = 0;
-
- return m_pOutputs.GetCount() > 0 ? S_OK : E_FAIL;
+ CheckPointer(pAsyncReader, E_POINTER);
+
+ HRESULT hr = E_FAIL;
+
+ m_pFile.Free();
+
+ m_pFile.Attach(DNew CNutFile(pAsyncReader, hr));
+ if(!m_pFile) return E_OUTOFMEMORY;
+ if(FAILED(hr)) {m_pFile.Free(); return hr;}
+
+ m_rtNewStart = m_rtCurrent = 0;
+ m_rtNewStop = m_rtStop = m_rtDuration = 0;
+
+ // pins
+
+ POSITION pos = m_pFile->m_streams.GetHeadPosition();
+ while(pos)
+ {
+ CNutFile::stream_header* sh = m_pFile->m_streams.GetNext(pos);
+
+ CAtlArray<CMediaType> mts;
+ CMediaType mt;
+
+ if(sh->stream_class == CNutFile::SC_VIDEO)
+ {
+ CNutFile::video_stream_header& vsh = sh->vsh;
+
+ mt.majortype = MEDIATYPE_Video;
+ mt.subtype = FOURCCMap(*(DWORD*)sh->fourcc.GetData());
+ mt.formattype = FORMAT_VideoInfo;
+
+ VIDEOINFOHEADER vih;
+ memset(&vih, 0, sizeof(vih));
+ vih.dwBitRate = (DWORD)sh->average_bitrate;
+ vih.AvgTimePerFrame = 10000000i64 * sh->time_base_nom / sh->time_base_denom;
+ vih.bmiHeader.biSize = sizeof(vih.bmiHeader);
+ vih.bmiHeader.biCompression = mt.subtype.Data1;
+ vih.bmiHeader.biWidth = (LONG)vsh.width;
+ vih.bmiHeader.biHeight = (LONG)vsh.height;
+ mt.SetFormat((BYTE*)&vih, sizeof(vih));
+
+ mts.Add(mt);
+
+ if(vsh.sample_width && vsh.sample_height)
+ {
+ VIDEOINFOHEADER2 vih2;
+ memset(&vih2, 0, sizeof(vih2));
+ vih2.dwBitRate = vih.dwBitRate;
+ vih2.AvgTimePerFrame = vih.AvgTimePerFrame;
+ vih2.dwPictAspectRatioX = (DWORD)vsh.sample_width;
+ vih2.dwPictAspectRatioY = (DWORD)vsh.sample_height;
+ vih2.bmiHeader = vih.bmiHeader;
+ mt.SetFormat((BYTE*)&vih2, sizeof(vih2));
+
+ mts.InsertAt(0, mt);
+ }
+ }
+ else if(sh->stream_class == CNutFile::SC_AUDIO)
+ {
+ CNutFile::audio_stream_header& ash = sh->ash;
+ // TODO
+ }
+ else if(sh->stream_class == CNutFile::SC_SUBTITLE)
+ {
+ // TODO
+ }
+
+ if(mts.GetCount() > 0)
+ {
+ CAutoPtr<CBaseSplitterOutputPin> pPinOut(DNew CBaseSplitterOutputPin(mts, L"Video", this, this, &hr));
+ AddOutputPin((DWORD)sh->stream_id, pPinOut);
+ }
+ }
+
+ // TODO
+ m_rtNewStop = m_rtStop = m_rtDuration = 0;
+
+ return m_pOutputs.GetCount() > 0 ? S_OK : E_FAIL;
}
bool CNutSplitterFilter::DemuxInit()
{
- if(!m_pFile) return(false);
- m_pFile->Seek(0);
- return(true);
+ if(!m_pFile) return(false);
+ m_pFile->Seek(0);
+ return(true);
}
void CNutSplitterFilter::DemuxSeek(REFERENCE_TIME rt)
{
- POSITION pos = m_pFile->m_streams.GetHeadPosition();
- while(pos) m_pFile->m_streams.GetNext(pos)->msb_timestamp = 0;
+ POSITION pos = m_pFile->m_streams.GetHeadPosition();
+ while(pos) m_pFile->m_streams.GetNext(pos)->msb_timestamp = 0;
if(rt <= 0)
- {
- m_pFile->Seek(0);
- }
- else
- {
- m_pFile->Seek(0);
- // TODO
- }
+ {
+ m_pFile->Seek(0);
+ }
+ else
+ {
+ m_pFile->Seek(0);
+ // TODO
+ }
}
bool CNutSplitterFilter::DemuxLoop()
{
- bool fKeyFrame = false;
-
- while(!CheckRequest(NULL) && m_pFile->GetRemaining())
- {
- CNutFile::frame_header fh;
- fh.checksum_flag = 1;
-
- UINT64 id = 0;
-
- if(m_pFile->BitRead(1, true) == 0)
- {
- fh.zero_bit = m_pFile->BitRead(1);
- fh.priority = m_pFile->BitRead(2);
- fh.checksum_flag = m_pFile->BitRead(1);
- fh.msb_timestamp_flag = m_pFile->BitRead(1);
- fh.subpacket_type = m_pFile->BitRead(2);
- fh.reserved = m_pFile->BitRead(1);
- }
- else
- {
- if((id = m_pFile->BitRead(64)) == NUTK)
- {
- fKeyFrame = true;
- continue;
- }
- }
-
- CNutFile::packet_header ph;
- m_pFile->Read(ph);
-
- if(id == 0)
- {
- CNutFile::vint stream_id;
- m_pFile->Read(stream_id);
-
- CNutFile::stream_header* sh = NULL;
-
- POSITION pos = m_pFile->m_streams.GetHeadPosition();
- while(pos)
- {
- CNutFile::stream_header* tmp = m_pFile->m_streams.GetNext(pos);
- if(tmp->stream_id == stream_id)
- {
- sh = tmp;
- break;
- }
- }
-
- if(sh)
- {
- if(fh.msb_timestamp_flag)
- m_pFile->Read(sh->msb_timestamp);
-
- CNutFile::svint lsb_timestamp = 0;
- m_pFile->Read(lsb_timestamp);
-
- TRACE(_T("[%I64d]: %I64d:%I64d\n"), stream_id, sh->msb_timestamp, lsb_timestamp);
-
- CAutoPtr<Packet> p(DNew Packet());
- p->TrackNumber = (DWORD)stream_id;
- p->bSyncPoint = fKeyFrame;
- p->rtStart = 10000i64 * ((sh->msb_timestamp << sh->msb_timestamp_shift) + lsb_timestamp)
- * sh->time_base_nom / sh->time_base_denom;
- p->rtStop = p->rtStart + 1;
-
- fKeyFrame = false;
-
- CNutFile::vint len = ph.fptr - (m_pFile->GetPos() - ph.pos);
- if(fh.checksum_flag) len -= 4;
-
- if(fh.subpacket_type == 1)
- {
- p->SetCount(len);
- m_pFile->ByteRead(p->GetData(), p->GetCount());
-
- if(FAILED(DeliverPacket(p)))
- break;
- }
- else
- {
- // TODO
- /*
- vint subpacket_count;
- Read(subpacket_count);
-
- if(fh.subpacket_type & 1)
- {
- CArray<vint> keyframe_run;
- keyframe_run.SetSize(subpacket_count);
- for(int i = 0; i < subpacket_count; i++)
- Read(keyframe_run[i]);
- }
-
- CArray<vint> timestamp_diff;
- timestamp_diff.SetSize(subpacket_count);
- CArray<vint> timestamp_diff_run;
- timestamp_diff_run.SetSize(subpacket_count);
- for(int i = 0; i < subpacket_count; i++)
- {
- Read(timestamp_diff[i]);
- if(timestamp_diff[i] & 1)
- Read(timestamp_diff_run[i]);
- }
-
- if(fh.subpacket_type & 2)
- {
- CArray<string> subpacket_size_diff;
- for(int i = 0; i < subpacket_count-1; i++)
- {
- Read(subpacket_size_diff[i]);
- }
- }
-
- for(int i = 0; i < subpacket_count; i++)
- {
- }
- */
- }
- }
- }
-
- if(fh.checksum_flag)
- {
- m_pFile->Seek(ph.pos + ph.fptr - 4);
- ph.checksum = (UINT32)m_pFile->BitRead(32);
- }
-
- m_pFile->Seek(ph.pos + ph.fptr);
- }
-
- return(true);
+ bool fKeyFrame = false;
+
+ while(!CheckRequest(NULL) && m_pFile->GetRemaining())
+ {
+ CNutFile::frame_header fh;
+ fh.checksum_flag = 1;
+
+ UINT64 id = 0;
+
+ if(m_pFile->BitRead(1, true) == 0)
+ {
+ fh.zero_bit = m_pFile->BitRead(1);
+ fh.priority = m_pFile->BitRead(2);
+ fh.checksum_flag = m_pFile->BitRead(1);
+ fh.msb_timestamp_flag = m_pFile->BitRead(1);
+ fh.subpacket_type = m_pFile->BitRead(2);
+ fh.reserved = m_pFile->BitRead(1);
+ }
+ else
+ {
+ if((id = m_pFile->BitRead(64)) == NUTK)
+ {
+ fKeyFrame = true;
+ continue;
+ }
+ }
+
+ CNutFile::packet_header ph;
+ m_pFile->Read(ph);
+
+ if(id == 0)
+ {
+ CNutFile::vint stream_id;
+ m_pFile->Read(stream_id);
+
+ CNutFile::stream_header* sh = NULL;
+
+ POSITION pos = m_pFile->m_streams.GetHeadPosition();
+ while(pos)
+ {
+ CNutFile::stream_header* tmp = m_pFile->m_streams.GetNext(pos);
+ if(tmp->stream_id == stream_id) {sh = tmp; break;}
+ }
+
+ if(sh)
+ {
+ if(fh.msb_timestamp_flag)
+ m_pFile->Read(sh->msb_timestamp);
+
+ CNutFile::svint lsb_timestamp = 0;
+ m_pFile->Read(lsb_timestamp);
+
+TRACE(_T("[%I64d]: %I64d:%I64d\n"), stream_id, sh->msb_timestamp, lsb_timestamp);
+
+ CAutoPtr<Packet> p(DNew Packet());
+ p->TrackNumber = (DWORD)stream_id;
+ p->bSyncPoint = fKeyFrame;
+ p->rtStart = 10000i64 * ((sh->msb_timestamp << sh->msb_timestamp_shift) + lsb_timestamp)
+ * sh->time_base_nom / sh->time_base_denom;
+ p->rtStop = p->rtStart+1;
+
+ fKeyFrame = false;
+
+ CNutFile::vint len = ph.fptr - (m_pFile->GetPos() - ph.pos);
+ if(fh.checksum_flag) len -= 4;
+
+ if(fh.subpacket_type == 1)
+ {
+ p->SetCount(len);
+ m_pFile->ByteRead(p->GetData(), p->GetCount());
+
+ if(FAILED(DeliverPacket(p)))
+ break;
+ }
+ else
+ {
+ // TODO
+/*
+ vint subpacket_count;
+ Read(subpacket_count);
+
+ if(fh.subpacket_type & 1)
+ {
+ CArray<vint> keyframe_run;
+ keyframe_run.SetSize(subpacket_count);
+ for(int i = 0; i < subpacket_count; i++)
+ Read(keyframe_run[i]);
+ }
+
+ CArray<vint> timestamp_diff;
+ timestamp_diff.SetSize(subpacket_count);
+ CArray<vint> timestamp_diff_run;
+ timestamp_diff_run.SetSize(subpacket_count);
+ for(int i = 0; i < subpacket_count; i++)
+ {
+ Read(timestamp_diff[i]);
+ if(timestamp_diff[i] & 1)
+ Read(timestamp_diff_run[i]);
+ }
+
+ if(fh.subpacket_type & 2)
+ {
+ CArray<string> subpacket_size_diff;
+ for(int i = 0; i < subpacket_count-1; i++)
+ {
+ Read(subpacket_size_diff[i]);
+ }
+ }
+
+ for(int i = 0; i < subpacket_count; i++)
+ {
+ }
+*/
+ }
+ }
+ }
+
+ if(fh.checksum_flag)
+ {
+ m_pFile->Seek(ph.pos + ph.fptr - 4);
+ ph.checksum = (UINT32)m_pFile->BitRead(32);
+ }
+
+ m_pFile->Seek(ph.pos + ph.fptr);
+ }
+
+ return(true);
}
// IMediaSeeking
STDMETHODIMP CNutSplitterFilter::GetDuration(LONGLONG* pDuration)
{
- CheckPointer(pDuration, E_POINTER);
- *pDuration = m_rtDuration;
- return S_OK;
+ CheckPointer(pDuration, E_POINTER);
+ *pDuration = m_rtDuration;
+ return S_OK;
}
//
@@ -339,8 +331,8 @@ STDMETHODIMP CNutSplitterFilter::GetDuration(LONGLONG* pDuration)
//
CNutSourceFilter::CNutSourceFilter(LPUNKNOWN pUnk, HRESULT* phr)
- : CNutSplitterFilter(pUnk, phr)
+ : CNutSplitterFilter(pUnk, phr)
{
- m_clsid = __uuidof(this);
- m_pInput.Free();
+ m_clsid = __uuidof(this);
+ m_pInput.Free();
}
diff --git a/src/filters/parser/NutSplitter/NutSplitter.h b/src/filters/parser/NutSplitter/NutSplitter.h
index 14d6ac51e..3eb99904d 100644
--- a/src/filters/parser/NutSplitter/NutSplitter.h
+++ b/src/filters/parser/NutSplitter/NutSplitter.h
@@ -1,4 +1,4 @@
-/*
+/*
* Copyright (C) 2003-2006 Gabest
* http://www.gabest.org
*
@@ -6,15 +6,15 @@
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2, or (at your option)
* any later version.
- *
+ *
* This Program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with GNU Make; see the file COPYING. If not, write to
- * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
+ * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
* http://www.gnu.org/copyleft/gpl.html
*
*/
@@ -25,31 +25,31 @@
#include "NutFile.h"
// {5EB7173E-AA71-4a54-BDD1-1CA57D20405F}
-DEFINE_GUID(MEDIASUBTYPE_Nut,
- 0x5eb7173e, 0xaa71, 0x4a54, 0xbd, 0xd1, 0x1c, 0xa5, 0x7d, 0x20, 0x40, 0x5f);
+DEFINE_GUID(MEDIASUBTYPE_Nut,
+0x5eb7173e, 0xaa71, 0x4a54, 0xbd, 0xd1, 0x1c, 0xa5, 0x7d, 0x20, 0x40, 0x5f);
[uuid("90514D6A-76B7-4405-88A8-B4B1EF6061C6")]
class CNutSplitterFilter : public CBaseSplitterFilter
{
- CAutoPtr<CNutFile> m_pFile;
+ CAutoPtr<CNutFile> m_pFile;
protected:
- HRESULT CreateOutputs(IAsyncReader* pAsyncReader);
+ HRESULT CreateOutputs(IAsyncReader* pAsyncReader);
- bool DemuxInit();
- void DemuxSeek(REFERENCE_TIME rt);
- bool DemuxLoop();
+ bool DemuxInit();
+ void DemuxSeek(REFERENCE_TIME rt);
+ bool DemuxLoop();
public:
- CNutSplitterFilter(LPUNKNOWN pUnk, HRESULT* phr);
+ CNutSplitterFilter(LPUNKNOWN pUnk, HRESULT* phr);
- // IMediaSeeking
- STDMETHODIMP GetDuration(LONGLONG* pDuration);
+ // IMediaSeeking
+ STDMETHODIMP GetDuration(LONGLONG* pDuration);
};
[uuid("918B5A9F-DFED-4532-83A9-9B16D83ED73F")]
class CNutSourceFilter : public CNutSplitterFilter
{
public:
- CNutSourceFilter(LPUNKNOWN pUnk, HRESULT* phr);
+ CNutSourceFilter(LPUNKNOWN pUnk, HRESULT* phr);
};
diff --git a/src/filters/parser/NutSplitter/resource.h b/src/filters/parser/NutSplitter/resource.h
index 02fc84368..80ef35412 100644
--- a/src/filters/parser/NutSplitter/resource.h
+++ b/src/filters/parser/NutSplitter/resource.h
@@ -3,7 +3,7 @@
// Used by NutSplitter.rc
// Next default values for new objects
-//
+//
#ifdef APSTUDIO_INVOKED
#ifndef APSTUDIO_READONLY_SYMBOLS
#define _APS_NEXT_RESOURCE_VALUE 101
diff --git a/src/filters/parser/NutSplitter/stdafx.cpp b/src/filters/parser/NutSplitter/stdafx.cpp
index e1ec5adac..4284c08d9 100644
--- a/src/filters/parser/NutSplitter/stdafx.cpp
+++ b/src/filters/parser/NutSplitter/stdafx.cpp
@@ -1,4 +1,4 @@
-/*
+/*
* Copyright (C) 2003-2006 Gabest
* http://www.gabest.org
*
@@ -6,15 +6,15 @@
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2, or (at your option)
* any later version.
- *
+ *
* This Program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with GNU Make; see the file COPYING. If not, write to
- * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
+ * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
* http://www.gnu.org/copyleft/gpl.html
*
*/
diff --git a/src/filters/parser/NutSplitter/stdafx.h b/src/filters/parser/NutSplitter/stdafx.h
index 0c8bbfda0..e3ebbbb58 100644
--- a/src/filters/parser/NutSplitter/stdafx.h
+++ b/src/filters/parser/NutSplitter/stdafx.h
@@ -1,4 +1,4 @@
-/*
+/*
* Copyright (C) 2003-2006 Gabest
* http://www.gabest.org
*
@@ -6,15 +6,15 @@
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2, or (at your option)
* any later version.
- *
+ *
* This Program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with GNU Make; see the file COPYING. If not, write to
- * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
+ * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
* http://www.gnu.org/copyleft/gpl.html
*
*/
diff --git a/src/filters/parser/OggSplitter/OggFile.cpp b/src/filters/parser/OggSplitter/OggFile.cpp
index 2bf8ffd25..e8a3a6d1f 100644
--- a/src/filters/parser/OggSplitter/OggFile.cpp
+++ b/src/filters/parser/OggSplitter/OggFile.cpp
@@ -2,81 +2,76 @@
#include "./oggfile.h"
COggFile::COggFile(IAsyncReader* pAsyncReader, HRESULT& hr)
- : CBaseSplitterFile(pAsyncReader, hr, DEFAULT_CACHE_LENGTH, false)
+ : CBaseSplitterFile(pAsyncReader, hr, DEFAULT_CACHE_LENGTH, false)
{
- if(FAILED(hr)) return;
- hr = Init();
+ if(FAILED(hr)) return;
+ hr = Init();
}
HRESULT COggFile::Init()
{
- Seek(0);
- if(!Sync()) return E_FAIL;
+ Seek(0);
+ if(!Sync()) return E_FAIL;
- return S_OK;
+ return S_OK;
}
bool COggFile::Sync(HANDLE hBreak)
{
- __int64 start = GetPos();
+ __int64 start = GetPos();
- DWORD dw;
- for(__int64 i = 0, j = hBreak ? GetLength() - start : 65536;
- i < j && S_OK == ByteRead((BYTE*)&dw, sizeof(dw))
- && ((i & 0xffff) || !hBreak || WaitForSingleObject(hBreak, 0) != WAIT_OBJECT_0);
- i++, Seek(start + i))
- {
- if(dw == 'SggO')
- {
- Seek(start + i);
- return(true);
- }
- }
+ DWORD dw;
+ for(__int64 i = 0, j = hBreak ? GetLength() - start : 65536;
+ i < j && S_OK == ByteRead((BYTE*)&dw, sizeof(dw))
+ && ((i&0xffff) || !hBreak || WaitForSingleObject(hBreak, 0) != WAIT_OBJECT_0);
+ i++, Seek(start + i))
+ {
+ if(dw == 'SggO')
+ {
+ Seek(start + i);
+ return(true);
+ }
+ }
- Seek(start);
+ Seek(start);
- return(false);
+ return(false);
}
bool COggFile::Read(OggPageHeader& hdr, HANDLE hBreak)
{
- return Sync(hBreak) && S_OK == ByteRead((BYTE*)&hdr, sizeof(hdr)) && hdr.capture_pattern == 'SggO';
+ return Sync(hBreak) && S_OK == ByteRead((BYTE*)&hdr, sizeof(hdr)) && hdr.capture_pattern == 'SggO';
}
bool COggFile::Read(OggPage& page, bool fFull, HANDLE hBreak)
{
- memset(&page.m_hdr, 0, sizeof(page.m_hdr));
- page.m_lens.RemoveAll();
- page.SetCount(0);
+ memset(&page.m_hdr, 0, sizeof(page.m_hdr));
+ page.m_lens.RemoveAll();
+ page.SetCount(0);
- if(!Read(page.m_hdr, hBreak))
- return(false);
+ if(!Read(page.m_hdr, hBreak))
+ return(false);
- int pagelen = 0, packetlen = 0;
- for(BYTE i = 0; i < page.m_hdr.number_page_segments; i++)
- {
- BYTE b;
+ int pagelen = 0, packetlen = 0;
+ for(BYTE i = 0; i < page.m_hdr.number_page_segments; i++)
+ {
+ BYTE b;
if(S_OK != ByteRead(&b, 1)) return(false);
- packetlen += b;
- if(1/*b < 0xff*/)
- {
- page.m_lens.AddTail(packetlen);
- pagelen += packetlen;
- packetlen = 0;
- }
- }
+ packetlen += b;
+ if(1/*b < 0xff*/) {page.m_lens.AddTail(packetlen); pagelen += packetlen; packetlen = 0;}
+ }
- if(fFull)
- {
- page.SetCount(pagelen);
- if(S_OK != ByteRead(page.GetData(), page.GetCount()))
- return(false);
- }
- else
- {
- Seek(GetPos() + pagelen);
- page.m_lens.RemoveAll();
- }
+ if(fFull)
+ {
+ page.SetCount(pagelen);
+ if(S_OK != ByteRead(page.GetData(), page.GetCount()))
+ return(false);
+ }
+ else
+ {
+ Seek(GetPos() + pagelen);
+ page.m_lens.RemoveAll();
+ }
- return(true);
+ return(true);
}
diff --git a/src/filters/parser/OggSplitter/OggFile.h b/src/filters/parser/OggSplitter/OggFile.h
index 1c748daf1..f37f01c0c 100644
--- a/src/filters/parser/OggSplitter/OggFile.h
+++ b/src/filters/parser/OggSplitter/OggFile.h
@@ -6,78 +6,70 @@
struct OggPageHeader
{
- DWORD capture_pattern;
- BYTE stream_structure_version;
- BYTE header_type_flag;
- enum {continued = 1, first = 2, last = 4};
- __int64 granule_position;
- DWORD bitstream_serial_number;
- DWORD page_sequence_number;
- DWORD CRC_checksum;
- BYTE number_page_segments;
+ DWORD capture_pattern;
+ BYTE stream_structure_version;
+ BYTE header_type_flag; enum {continued=1, first=2, last=4};
+ __int64 granule_position;
+ DWORD bitstream_serial_number;
+ DWORD page_sequence_number;
+ DWORD CRC_checksum;
+ BYTE number_page_segments;
};
struct OggVorbisIdHeader
{
- DWORD vorbis_version;
- BYTE audio_channels;
- DWORD audio_sample_rate;
- DWORD bitrate_maximum;
- DWORD bitrate_nominal;
- DWORD bitrate_minimum;
- BYTE blocksize_0: 4;
- BYTE blocksize_1: 4;
- BYTE framing_flag;
+ DWORD vorbis_version;
+ BYTE audio_channels;
+ DWORD audio_sample_rate;
+ DWORD bitrate_maximum;
+ DWORD bitrate_nominal;
+ DWORD bitrate_minimum;
+ BYTE blocksize_0:4;
+ BYTE blocksize_1:4;
+ BYTE framing_flag;
};
struct OggVideoHeader
{
- DWORD w, h;
+ DWORD w, h;
};
struct OggAudioHeader
{
- WORD nChannels, nBlockAlign;
- DWORD nAvgBytesPerSec;
+ WORD nChannels, nBlockAlign;
+ DWORD nAvgBytesPerSec;
};
struct OggStreamHeader
{
- char streamtype[8], subtype[4];
- DWORD size;
- __int64 time_unit, samples_per_unit;
- DWORD default_len;
+ char streamtype[8], subtype[4];
+ DWORD size;
+ __int64 time_unit, samples_per_unit;
+ DWORD default_len;
DWORD buffersize;
- WORD bps;
- WORD alignmentfix1;
- union
- {
- OggVideoHeader v;
- OggAudioHeader a;
- };
- DWORD alignmentfix2;
+ WORD bps;
+ WORD alignmentfix1;
+ union {OggVideoHeader v; OggAudioHeader a;};
+ DWORD alignmentfix2;
};
#pragma pack(pop)
class OggPage : public CAtlArray<BYTE>
{
public:
- OggPageHeader m_hdr;
- CAtlList<int> m_lens;
- OggPage()
- {
- memset(&m_hdr, 0, sizeof(m_hdr));
- }
+ OggPageHeader m_hdr;
+ CAtlList<int> m_lens;
+ OggPage() {memset(&m_hdr, 0, sizeof(m_hdr));}
};
class COggFile : public CBaseSplitterFile
{
- HRESULT Init();
+ HRESULT Init();
public:
- COggFile(IAsyncReader* pAsyncReader, HRESULT& hr);
+ COggFile(IAsyncReader* pAsyncReader, HRESULT& hr);
- bool Sync(HANDLE hBreak = NULL);
- bool Read(OggPageHeader& hdr, HANDLE hBreak = NULL);
- bool Read(OggPage& page, bool fFull = true, HANDLE hBreak = NULL);
+ bool Sync(HANDLE hBreak = NULL);
+ bool Read(OggPageHeader& hdr, HANDLE hBreak = NULL);
+ bool Read(OggPage& page, bool fFull = true, HANDLE hBreak = NULL);
};
diff --git a/src/filters/parser/OggSplitter/OggSplitter.cpp b/src/filters/parser/OggSplitter/OggSplitter.cpp
index 90cc25a2d..9dbb2e456 100644
--- a/src/filters/parser/OggSplitter/OggSplitter.cpp
+++ b/src/filters/parser/OggSplitter/OggSplitter.cpp
@@ -1,4 +1,4 @@
-/*
+/*
* Copyright (C) 2003-2006 Gabest
* http://www.gabest.org
*
@@ -6,15 +6,15 @@
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2, or (at your option)
* any later version.
- *
+ *
* This Program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with GNU Make; see the file COPYING. If not, write to
- * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
+ * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
* http://www.gnu.org/copyleft/gpl.html
*
*/
@@ -40,7 +40,7 @@
const AMOVIESETUP_MEDIATYPE sudPinTypesIn[] =
{
- {&MEDIATYPE_Stream, &MEDIASUBTYPE_NULL},
+ {&MEDIATYPE_Stream, &MEDIASUBTYPE_NULL},
};
const AMOVIESETUP_PIN sudpPins[] =
@@ -51,34 +51,34 @@ const AMOVIESETUP_PIN sudpPins[] =
const AMOVIESETUP_FILTER sudFilter[] =
{
- {&__uuidof(COggSplitterFilter), L"MPC - Ogg Splitter", MERIT_NORMAL + 1, countof(sudpPins), sudpPins, CLSID_LegacyAmFilterCategory},
- {&__uuidof(COggSourceFilter), L"MPC - Ogg Source", MERIT_NORMAL + 1, 0, NULL, CLSID_LegacyAmFilterCategory},
+ {&__uuidof(COggSplitterFilter), L"MPC - Ogg Splitter", MERIT_NORMAL+1, countof(sudpPins), sudpPins, CLSID_LegacyAmFilterCategory},
+ {&__uuidof(COggSourceFilter), L"MPC - Ogg Source", MERIT_NORMAL+1, 0, NULL, CLSID_LegacyAmFilterCategory},
};
CFactoryTemplate g_Templates[] =
{
- {sudFilter[0].strName, sudFilter[0].clsID, CreateInstance<COggSplitterFilter>, NULL, &sudFilter[0]},
- {sudFilter[1].strName, sudFilter[1].clsID, CreateInstance<COggSourceFilter>, NULL, &sudFilter[1]},
+ {sudFilter[0].strName, sudFilter[0].clsID, CreateInstance<COggSplitterFilter>, NULL, &sudFilter[0]},
+ {sudFilter[1].strName, sudFilter[1].clsID, CreateInstance<COggSourceFilter>, NULL, &sudFilter[1]},
};
int g_cTemplates = countof(g_Templates);
STDAPI DllRegisterServer()
{
- RegisterSourceFilter(
- CLSID_AsyncReader,
- MEDIASUBTYPE_Ogg,
- _T("0,4,,4F676753"), // OggS
- _T(".ogg"), _T(".ogm"), NULL);
+ RegisterSourceFilter(
+ CLSID_AsyncReader,
+ MEDIASUBTYPE_Ogg,
+ _T("0,4,,4F676753"), // OggS
+ _T(".ogg"), _T(".ogm"), NULL);
- return AMovieDllRegisterServer2(TRUE);
+ return AMovieDllRegisterServer2(TRUE);
}
STDAPI DllUnregisterServer()
{
- UnRegisterSourceFilter(MEDIASUBTYPE_Ogg);
+ UnRegisterSourceFilter(MEDIASUBTYPE_Ogg);
- return AMovieDllRegisterServer2(FALSE);
+ return AMovieDllRegisterServer2(FALSE);
}
#include "../../FilterApp.h"
@@ -93,56 +93,42 @@ CFilterApp theApp;
class bitstream
{
- BYTE* m_p;
- int m_len, m_pos;
+ BYTE* m_p;
+ int m_len, m_pos;
public:
- bitstream(BYTE* p, int len, bool rev = false) : m_p(p), m_len(len * 8)
- {
- m_pos = !rev ? 0 : len * 8;
- }
- bool hasbits(int cnt)
- {
- int pos = m_pos + cnt;
- return(pos >= 0 && pos < m_len);
- }
- unsigned int showbits(int cnt) // a bit unclean, but works and can read backwards too! :P
- {
- if(!hasbits(cnt))
- {
- ASSERT(0);
- return 0;
- }
- unsigned int ret = 0, off = 0;
- BYTE* p = m_p;
- if(cnt < 0)
- {
- p += (m_pos + cnt) >> 3;
- off = (m_pos + cnt) & 7;
- cnt = abs(cnt);
- ret = (*p++&(~0 << off))>>off; off = 8 - off; cnt -= off;
- }
- else
- {
- p += m_pos >> 3;
- off = m_pos & 7;
- ret = (*p++ >> off) & ((1 << min(cnt, 8)) - 1);
- off = 0;
- cnt -= 8 - off;
- }
- while(cnt > 0)
- {
- ret |= (*p++&((1 << min(cnt, 8)) - 1)) << off;
- off += 8;
- cnt -= 8;
- }
- return ret;
- }
- unsigned int getbits(int cnt)
- {
- unsigned int ret = showbits(cnt);
- m_pos += cnt;
- return ret;
- }
+ bitstream(BYTE* p, int len, bool rev = false) : m_p(p), m_len(len*8) {m_pos = !rev ? 0 : len*8;}
+ bool hasbits(int cnt)
+ {
+ int pos = m_pos+cnt;
+ return(pos >= 0 && pos < m_len);
+ }
+ unsigned int showbits(int cnt) // a bit unclean, but works and can read backwards too! :P
+ {
+ if(!hasbits(cnt)) {ASSERT(0); return 0;}
+ unsigned int ret = 0, off = 0;
+ BYTE* p = m_p;
+ if(cnt < 0)
+ {
+ p += (m_pos+cnt)>>3;
+ off = (m_pos+cnt)&7;
+ cnt = abs(cnt);
+ ret = (*p++&(~0<<off))>>off; off = 8 - off; cnt -= off;
+ }
+ else
+ {
+ p += m_pos>>3;
+ off = m_pos&7;
+ ret = (*p++>>off)&((1<<min(cnt,8))-1); off = 0; cnt -= 8 - off;
+ }
+ while(cnt > 0) {ret |= (*p++&((1<<min(cnt,8))-1)) << off; off += 8; cnt -= 8;}
+ return ret;
+ }
+ unsigned int getbits(int cnt)
+ {
+ unsigned int ret = showbits(cnt);
+ m_pos += cnt;
+ return ret;
+ }
};
//
@@ -150,7 +136,7 @@ public:
//
COggSplitterFilter::COggSplitterFilter(LPUNKNOWN pUnk, HRESULT* phr)
- : CBaseSplitterFilter(NAME("COggSplitterFilter"), pUnk, phr, __uuidof(this))
+ : CBaseSplitterFilter(NAME("COggSplitterFilter"), pUnk, phr, __uuidof(this))
{
}
@@ -160,437 +146,417 @@ COggSplitterFilter::~COggSplitterFilter()
HRESULT COggSplitterFilter::CreateOutputs(IAsyncReader* pAsyncReader)
{
- CheckPointer(pAsyncReader, E_POINTER);
-
- HRESULT hr = E_FAIL;
-
- m_pFile.Free();
-
- m_pFile.Attach(DNew COggFile(pAsyncReader, hr));
- if(!m_pFile) return E_OUTOFMEMORY;
- if(FAILED(hr))
- {
- m_pFile.Free();
- return hr;
- }
-
- m_rtNewStart = m_rtCurrent = 0;
- m_rtNewStop = m_rtStop = 0;
-
- m_rtDuration = 0;
-
- m_pFile->Seek(0);
- OggPage page;
- for(int i = 0, nWaitForMore = 0; m_pFile->Read(page); i++)
- {
- BYTE* p = page.GetData();
-
- if(!(page.m_hdr.header_type_flag & OggPageHeader::continued))
- {
- BYTE type = *p++;
-
- CStringW name;
- name.Format(L"Stream %d", i);
-
- HRESULT hr;
-
- if(type >= 0x80 && type <= 0x82 && !memcmp(p, "theora", 6))
- {
- if(type == 0x80)
- {
- name.Format(L"Theora %d", i);
- CAutoPtr<CBaseSplitterOutputPin> pPinOut;
- pPinOut.Attach(DNew COggTheoraOutputPin(page.GetData(), name, this, this, &hr));
- AddOutputPin(page.m_hdr.bitstream_serial_number, pPinOut);
- nWaitForMore++;
- }
- }
- else if(type == 1 && (page.m_hdr.header_type_flag & OggPageHeader::first))
- {
- CAutoPtr<CBaseSplitterOutputPin> pPinOut;
-
- if(!memcmp(p, "vorbis", 6))
- {
- name.Format(L"Vorbis %d", i);
- pPinOut.Attach(DNew COggVorbisOutputPin((OggVorbisIdHeader*)(p + 6), name, this, this, &hr));
- nWaitForMore++;
- }
- else if(!memcmp(p, "video", 5))
- {
- name.Format(L"Video %d", i);
- pPinOut.Attach(DNew COggVideoOutputPin((OggStreamHeader*)p, name, this, this, &hr));
- }
- else if(!memcmp(p, "audio", 5))
- {
- name.Format(L"Audio %d", i);
- pPinOut.Attach(DNew COggAudioOutputPin((OggStreamHeader*)p, name, this, this, &hr));
- }
- else if(!memcmp(p, "text", 4))
- {
- name.Format(L"Text %d", i);
- pPinOut.Attach(DNew COggTextOutputPin((OggStreamHeader*)p, name, this, this, &hr));
- }
- else if(!memcmp(p, "Direct Show Samples embedded in Ogg", 35))
- {
- name.Format(L"DirectShow %d", i);
- pPinOut.Attach(DNew COggDirectShowOutputPin((AM_MEDIA_TYPE*)(p + 35 + sizeof(GUID)), name, this, this, &hr));
- }
-
- AddOutputPin(page.m_hdr.bitstream_serial_number, pPinOut);
- }
- else if(type == 3 && !memcmp(p, "vorbis", 6))
- {
- if(COggSplitterOutputPin* pOggPin =
- dynamic_cast<COggSplitterOutputPin*>(GetOutputPin(page.m_hdr.bitstream_serial_number)))
- {
- pOggPin->AddComment(p + 6, page.GetCount() - 6 - 1);
- }
- }
- else if(type == 0x7F && page.GetCount() > 12 && *(long*)(p + 8) == 0x43614C66) // Flac
- {
- // Ogg Flac : method 1
- CAutoPtr<CBaseSplitterOutputPin> pPinOut;
- name.Format(L"Flac %d", i);
- pPinOut.Attach(DNew COggFlacOutputPin(p + 12, page.GetCount() - 14, name, this, this, &hr));
- AddOutputPin(page.m_hdr.bitstream_serial_number, pPinOut);
- }
- else if(*(long*)(p - 1) == 0x43614C66)
- {
- //bFlac = true;
- //nWaitForMore++;
- if(m_pFile->Read(page))
- {
- CAutoPtr<CBaseSplitterOutputPin> pPinOut;
- name.Format(L"Flac %d", i);
- p = page.GetData();
- pPinOut.Attach(DNew COggFlacOutputPin(p, page.GetCount(), name, this, this, &hr));
- AddOutputPin(page.m_hdr.bitstream_serial_number, pPinOut);
- }
- }
- else if(!(type & 1) && nWaitForMore == 0)
- {
- break;
- }
- }
-
- if(COggTheoraOutputPin* p = dynamic_cast<COggTheoraOutputPin*>(GetOutputPin(page.m_hdr.bitstream_serial_number)))
- {
- p->UnpackInitPage(page);
- if(p->IsInitialized()) nWaitForMore--;
- }
-
- if(COggVorbisOutputPin* p = dynamic_cast<COggVorbisOutputPin*>(GetOutputPin(page.m_hdr.bitstream_serial_number)))
- {
- p->UnpackInitPage(page);
- if(p->IsInitialized()) nWaitForMore--;
- }
- }
-
- if(m_pOutputs.IsEmpty())
- return E_FAIL;
-
- if(m_pFile->IsRandomAccess())
- {
- m_pFile->Seek(max(m_pFile->GetLength() - 65536, 0));
-
- OggPage page;
- while(m_pFile->Read(page))
- {
- COggSplitterOutputPin* pOggPin = dynamic_cast<COggSplitterOutputPin*>(GetOutputPin(page.m_hdr.bitstream_serial_number));
- if(!pOggPin || page.m_hdr.granule_position == -1) continue;
- REFERENCE_TIME rt = pOggPin->GetRefTime(page.m_hdr.granule_position);
- m_rtDuration = max(rt, m_rtDuration);
- }
- }
-
- m_rtNewStart = m_rtCurrent = 0;
- m_rtNewStop = m_rtStop = m_rtDuration;
-
- // comments
-
- {
- CAtlMap<CStringW, CStringW, CStringElementTraits<CStringW> > tagmap;
- tagmap[L"TITLE"] = L"TITL";
- tagmap[L"ARTIST"] = L"AUTH"; // not quite
- tagmap[L"COPYRIGHT"] = L"CPYR";
- tagmap[L"DESCRIPTION"] = L"DESC";
-
- POSITION pos2 = tagmap.GetStartPosition();
- while(pos2)
- {
- CStringW oggtag, dsmtag;
- tagmap.GetNextAssoc(pos2, oggtag, dsmtag);
-
- POSITION pos = m_pOutputs.GetHeadPosition();
- while(pos)
- {
- COggSplitterOutputPin* pOggPin = dynamic_cast<COggSplitterOutputPin*>((CBaseOutputPin*)m_pOutputs.GetNext(pos));
- if(!pOggPin) continue;
-
- CStringW value = pOggPin->GetComment(oggtag);
- if(!value.IsEmpty())
- {
- SetProperty(dsmtag, value);
- break;
- }
- }
- }
-
- POSITION pos = m_pOutputs.GetHeadPosition();
- while(pos && !ChapGetCount())
- {
- COggSplitterOutputPin* pOggPin = dynamic_cast<COggSplitterOutputPin*>((CBaseOutputPin*)m_pOutputs.GetNext(pos));
- if(!pOggPin) continue;
-
- for(int i = 1; pOggPin; i++)
- {
- CStringW key;
- key.Format(L"CHAPTER%02d", i);
- CStringW time = pOggPin->GetComment(key);
- if(time.IsEmpty()) break;
- key.Format(L"CHAPTER%02dNAME", i);
- CStringW name = pOggPin->GetComment(key);
- if(name.IsEmpty()) name.Format(L"Chapter %d", i);
- int h, m, s, ms;
- WCHAR c;
- if(7 != swscanf(time, L"%d%c%d%c%d%c%d", &h, &c, &m, &c, &s, &c, &ms)) break;
- REFERENCE_TIME rt = ((((REFERENCE_TIME)h * 60 + m) * 60 + s) * 1000 + ms) * 10000;
- ChapAppend(rt, name);
- }
- }
- }
-
- return m_pOutputs.GetCount() > 0 ? S_OK : E_FAIL;
+ CheckPointer(pAsyncReader, E_POINTER);
+
+ HRESULT hr = E_FAIL;
+
+ m_pFile.Free();
+
+ m_pFile.Attach(DNew COggFile(pAsyncReader, hr));
+ if(!m_pFile) return E_OUTOFMEMORY;
+ if(FAILED(hr)) {m_pFile.Free(); return hr;}
+
+ m_rtNewStart = m_rtCurrent = 0;
+ m_rtNewStop = m_rtStop = 0;
+
+ m_rtDuration = 0;
+
+ m_pFile->Seek(0);
+ OggPage page;
+ for(int i = 0, nWaitForMore = 0; m_pFile->Read(page); i++)
+ {
+ BYTE* p = page.GetData();
+
+ if(!(page.m_hdr.header_type_flag & OggPageHeader::continued))
+ {
+ BYTE type = *p++;
+
+ CStringW name;
+ name.Format(L"Stream %d", i);
+
+ HRESULT hr;
+
+ if(type >= 0x80 && type <= 0x82 && !memcmp(p, "theora", 6))
+ {
+ if(type == 0x80)
+ {
+ name.Format(L"Theora %d", i);
+ CAutoPtr<CBaseSplitterOutputPin> pPinOut;
+ pPinOut.Attach(DNew COggTheoraOutputPin(page.GetData(), name, this, this, &hr));
+ AddOutputPin(page.m_hdr.bitstream_serial_number, pPinOut);
+ nWaitForMore++;
+ }
+ }
+ else if(type == 1 && (page.m_hdr.header_type_flag & OggPageHeader::first))
+ {
+ CAutoPtr<CBaseSplitterOutputPin> pPinOut;
+
+ if(!memcmp(p, "vorbis", 6))
+ {
+ name.Format(L"Vorbis %d", i);
+ pPinOut.Attach(DNew COggVorbisOutputPin((OggVorbisIdHeader*)(p+6), name, this, this, &hr));
+ nWaitForMore++;
+ }
+ else if(!memcmp(p, "video", 5))
+ {
+ name.Format(L"Video %d", i);
+ pPinOut.Attach(DNew COggVideoOutputPin((OggStreamHeader*)p, name, this, this, &hr));
+ }
+ else if(!memcmp(p, "audio", 5))
+ {
+ name.Format(L"Audio %d", i);
+ pPinOut.Attach(DNew COggAudioOutputPin((OggStreamHeader*)p, name, this, this, &hr));
+ }
+ else if(!memcmp(p, "text", 4))
+ {
+ name.Format(L"Text %d", i);
+ pPinOut.Attach(DNew COggTextOutputPin((OggStreamHeader*)p, name, this, this, &hr));
+ }
+ else if(!memcmp(p, "Direct Show Samples embedded in Ogg", 35))
+ {
+ name.Format(L"DirectShow %d", i);
+ pPinOut.Attach(DNew COggDirectShowOutputPin((AM_MEDIA_TYPE*)(p+35+sizeof(GUID)), name, this, this, &hr));
+ }
+
+ AddOutputPin(page.m_hdr.bitstream_serial_number, pPinOut);
+ }
+ else if(type == 3 && !memcmp(p, "vorbis", 6))
+ {
+ if(COggSplitterOutputPin* pOggPin =
+ dynamic_cast<COggSplitterOutputPin*>(GetOutputPin(page.m_hdr.bitstream_serial_number)))
+ {
+ pOggPin->AddComment(p+6, page.GetCount()-6-1);
+ }
+ }
+ else if(type == 0x7F && page.GetCount()>12 && *(long*)(p+8) == 0x43614C66) // Flac
+ {
+ // Ogg Flac : method 1
+ CAutoPtr<CBaseSplitterOutputPin> pPinOut;
+ name.Format(L"Flac %d", i);
+ pPinOut.Attach(DNew COggFlacOutputPin(p+12, page.GetCount()-14, name, this, this, &hr));
+ AddOutputPin(page.m_hdr.bitstream_serial_number, pPinOut);
+ }
+ else if (*(long*)(p-1) == 0x43614C66)
+ {
+ //bFlac = true;
+ //nWaitForMore++;
+ if (m_pFile->Read(page))
+ {
+ CAutoPtr<CBaseSplitterOutputPin> pPinOut;
+ name.Format(L"Flac %d", i);
+ p = page.GetData();
+ pPinOut.Attach(DNew COggFlacOutputPin(p, page.GetCount(), name, this, this, &hr));
+ AddOutputPin(page.m_hdr.bitstream_serial_number, pPinOut);
+ }
+ }
+ else if(!(type&1) && nWaitForMore == 0)
+ {
+ break;
+ }
+ }
+
+ if(COggTheoraOutputPin* p = dynamic_cast<COggTheoraOutputPin*>(GetOutputPin(page.m_hdr.bitstream_serial_number)))
+ {
+ p->UnpackInitPage(page);
+ if(p->IsInitialized()) nWaitForMore--;
+ }
+
+ if(COggVorbisOutputPin* p = dynamic_cast<COggVorbisOutputPin*>(GetOutputPin(page.m_hdr.bitstream_serial_number)))
+ {
+ p->UnpackInitPage(page);
+ if(p->IsInitialized()) nWaitForMore--;
+ }
+ }
+
+ if(m_pOutputs.IsEmpty())
+ return E_FAIL;
+
+ if(m_pFile->IsRandomAccess())
+ {
+ m_pFile->Seek(max(m_pFile->GetLength()-65536, 0));
+
+ OggPage page;
+ while(m_pFile->Read(page))
+ {
+ COggSplitterOutputPin* pOggPin = dynamic_cast<COggSplitterOutputPin*>(GetOutputPin(page.m_hdr.bitstream_serial_number));
+ if(!pOggPin || page.m_hdr.granule_position == -1) continue;
+ REFERENCE_TIME rt = pOggPin->GetRefTime(page.m_hdr.granule_position);
+ m_rtDuration = max(rt, m_rtDuration);
+ }
+ }
+
+ m_rtNewStart = m_rtCurrent = 0;
+ m_rtNewStop = m_rtStop = m_rtDuration;
+
+ // comments
+
+ {
+ CAtlMap<CStringW, CStringW, CStringElementTraits<CStringW> > tagmap;
+ tagmap[L"TITLE"] = L"TITL";
+ tagmap[L"ARTIST"] = L"AUTH"; // not quite
+ tagmap[L"COPYRIGHT"] = L"CPYR";
+ tagmap[L"DESCRIPTION"] = L"DESC";
+
+ POSITION pos2 = tagmap.GetStartPosition();
+ while(pos2)
+ {
+ CStringW oggtag, dsmtag;
+ tagmap.GetNextAssoc(pos2, oggtag, dsmtag);
+
+ POSITION pos = m_pOutputs.GetHeadPosition();
+ while(pos)
+ {
+ COggSplitterOutputPin* pOggPin = dynamic_cast<COggSplitterOutputPin*>((CBaseOutputPin*)m_pOutputs.GetNext(pos));
+ if(!pOggPin) continue;
+
+ CStringW value = pOggPin->GetComment(oggtag);
+ if(!value.IsEmpty())
+ {
+ SetProperty(dsmtag, value);
+ break;
+ }
+ }
+ }
+
+ POSITION pos = m_pOutputs.GetHeadPosition();
+ while(pos && !ChapGetCount())
+ {
+ COggSplitterOutputPin* pOggPin = dynamic_cast<COggSplitterOutputPin*>((CBaseOutputPin*)m_pOutputs.GetNext(pos));
+ if(!pOggPin) continue;
+
+ for(int i = 1; pOggPin; i++)
+ {
+ CStringW key;
+ key.Format(L"CHAPTER%02d", i);
+ CStringW time = pOggPin->GetComment(key);
+ if(time.IsEmpty()) break;
+ key.Format(L"CHAPTER%02dNAME", i);
+ CStringW name = pOggPin->GetComment(key);
+ if(name.IsEmpty()) name.Format(L"Chapter %d", i);
+ int h, m, s, ms;
+ WCHAR c;
+ if(7 != swscanf(time, L"%d%c%d%c%d%c%d", &h, &c, &m, &c, &s, &c, &ms)) break;
+ REFERENCE_TIME rt = ((((REFERENCE_TIME)h*60+m)*60+s)*1000+ms)*10000;
+ ChapAppend(rt, name);
+ }
+ }
+ }
+
+ return m_pOutputs.GetCount() > 0 ? S_OK : E_FAIL;
}
bool COggSplitterFilter::DemuxInit()
{
- if(!m_pFile) return(false);
+ if(!m_pFile) return(false);
- return(true);
+ return(true);
}
void COggSplitterFilter::DemuxSeek(REFERENCE_TIME rt)
{
- if(rt <= 0)
- {
- m_pFile->Seek(0);
- }
- else if(m_rtDuration > 0)
- {
- // oh, the horror...
-
- __int64 len = m_pFile->GetLength();
- __int64 startpos = len * rt / m_rtDuration;
- __int64 diff = 0;
-
- REFERENCE_TIME rtMinDiff = _I64_MAX;
-
- while(1)
- {
- __int64 endpos = startpos;
- REFERENCE_TIME rtPos = -1;
-
- OggPage page;
- m_pFile->Seek(startpos);
- while(m_pFile->Read(page, false))
- {
- if(page.m_hdr.granule_position == -1) continue;
-
- COggSplitterOutputPin* pOggPin = dynamic_cast<COggSplitterOutputPin*>(GetOutputPin(page.m_hdr.bitstream_serial_number));
- if(!pOggPin)
- {
- ASSERT(0);
- continue;
- }
-
- rtPos = pOggPin->GetRefTime(page.m_hdr.granule_position);
- endpos = m_pFile->GetPos();
-
- break;
- }
-
- __int64 rtDiff = rtPos - rt;
-
- if(rtDiff < 0)
- {
- rtDiff = -rtDiff;
-
- if(rtDiff < 1000000 || rtDiff >= rtMinDiff)
- {
- m_pFile->Seek(startpos);
- break;
- }
-
- rtMinDiff = rtDiff;
- }
-
- __int64 newpos = startpos;
-
- if(rtPos < rt && rtPos < m_rtDuration)
- {
- newpos = startpos + (__int64)((1.0 * (rt - rtPos) / (m_rtDuration - rtPos)) * (len - startpos)) + 1024;
- if(newpos < endpos) newpos = endpos + 1024;
- }
- else if(rtPos > rt && rtPos > 0)
- {
- newpos = startpos - (__int64)((1.0 * (rtPos - rt) / (rtPos - 0)) * (startpos - 0)) - 1024;
- if(newpos >= startpos) newpos = startpos - 1024;
- }
- else if(rtPos == rt)
- {
- m_pFile->Seek(startpos);
- break;
- }
- else
- {
- ASSERT(0);
- m_pFile->Seek(0);
- break;
- }
-
- diff = newpos - startpos;
-
- startpos = max(min(newpos, len), 0);
- }
-
- m_pFile->Seek(startpos);
-
- POSITION pos = m_pOutputs.GetHeadPosition();
- while(pos)
- {
- COggSplitterOutputPin* pPin = dynamic_cast<COggSplitterOutputPin*>(static_cast<CBaseSplitterOutputPin*>(m_pOutputs.GetNext(pos)));
-
- if(!dynamic_cast<COggVideoOutputPin*>(pPin) && !dynamic_cast<COggTheoraOutputPin*>(pPin))
- continue;
-
- bool fKeyFrameFound = false, fSkipKeyFrame = true;
- __int64 endpos = _I64_MAX;
-
- while(!(fKeyFrameFound && !fSkipKeyFrame) && startpos > 0)
- {
- OggPage page;
- while(!(fKeyFrameFound && !fSkipKeyFrame) && m_pFile->GetPos() < endpos && m_pFile->Read(page))
- {
- if(page.m_hdr.granule_position == -1)
- continue;
-
- if(pPin != dynamic_cast<COggSplitterOutputPin*>(GetOutputPin(page.m_hdr.bitstream_serial_number)))
- continue;
-
- if(pPin->GetRefTime(page.m_hdr.granule_position) > rt)
- break;
-
- if(!fKeyFrameFound)
- {
- pPin->UnpackPage(page);
-
- CAutoPtr<OggPacket> p;
- while(p = pPin->GetPacket())
- {
- if(p->bSyncPoint)
- {
- fKeyFrameFound = true;
- fSkipKeyFrame = p->fSkip;
- }
- }
-
- if(fKeyFrameFound) break;
- }
- else
- {
- pPin->UnpackPage(page);
-
- CAutoPtr<OggPacket> p;
- while(p = pPin->GetPacket())
- {
- if(!p->fSkip)
- {
- fSkipKeyFrame = false;
- break;
- }
- }
- }
- }
-
- if(!(fKeyFrameFound && !fSkipKeyFrame))
- {
- endpos = startpos;
- startpos = max(startpos - 10 * 65536, 0);
- }
-
- m_pFile->Seek(startpos);
- }
+ if(rt <= 0 )
+ {
+ m_pFile->Seek(0);
+ }
+ else if(m_rtDuration > 0)
+ {
+ // oh, the horror...
+
+ __int64 len = m_pFile->GetLength();
+ __int64 startpos = len * rt/m_rtDuration;
+ __int64 diff = 0;
+
+ REFERENCE_TIME rtMinDiff = _I64_MAX;
+
+ while(1)
+ {
+ __int64 endpos = startpos;
+ REFERENCE_TIME rtPos = -1;
+
+ OggPage page;
+ m_pFile->Seek(startpos);
+ while(m_pFile->Read(page, false))
+ {
+ if(page.m_hdr.granule_position == -1) continue;
+
+ COggSplitterOutputPin* pOggPin = dynamic_cast<COggSplitterOutputPin*>(GetOutputPin(page.m_hdr.bitstream_serial_number));
+ if(!pOggPin) {ASSERT(0); continue;}
+
+ rtPos = pOggPin->GetRefTime(page.m_hdr.granule_position);
+ endpos = m_pFile->GetPos();
+
+ break;
+ }
+
+ __int64 rtDiff = rtPos - rt;
+
+ if(rtDiff < 0)
+ {
+ rtDiff = -rtDiff;
+
+ if(rtDiff < 1000000 || rtDiff >= rtMinDiff)
+ {
+ m_pFile->Seek(startpos);
+ break;
+ }
+
+ rtMinDiff = rtDiff;
+ }
+
+ __int64 newpos = startpos;
+
+ if(rtPos < rt && rtPos < m_rtDuration)
+ {
+ newpos = startpos + (__int64)((1.0*(rt - rtPos)/(m_rtDuration - rtPos)) * (len - startpos)) + 1024;
+ if(newpos < endpos) newpos = endpos + 1024;
+ }
+ else if(rtPos > rt && rtPos > 0)
+ {
+ newpos = startpos - (__int64)((1.0*(rtPos - rt)/(rtPos - 0)) * (startpos - 0)) - 1024;
+ if(newpos >= startpos) newpos = startpos - 1024;
+ }
+ else if(rtPos == rt)
+ {
+ m_pFile->Seek(startpos);
+ break;
+ }
+ else
+ {
+ ASSERT(0);
+ m_pFile->Seek(0);
+ break;
+ }
+
+ diff = newpos - startpos;
+
+ startpos = max(min(newpos, len), 0);
+ }
+
+ m_pFile->Seek(startpos);
+
+ POSITION pos = m_pOutputs.GetHeadPosition();
+ while(pos)
+ {
+ COggSplitterOutputPin* pPin = dynamic_cast<COggSplitterOutputPin*>(static_cast<CBaseSplitterOutputPin*>(m_pOutputs.GetNext(pos)));
+
+ if(!dynamic_cast<COggVideoOutputPin*>(pPin) && !dynamic_cast<COggTheoraOutputPin*>(pPin))
+ continue;
+
+ bool fKeyFrameFound = false, fSkipKeyFrame = true;
+ __int64 endpos = _I64_MAX;
+
+ while(!(fKeyFrameFound && !fSkipKeyFrame) && startpos > 0)
+ {
+ OggPage page;
+ while(!(fKeyFrameFound && !fSkipKeyFrame) && m_pFile->GetPos() < endpos && m_pFile->Read(page))
+ {
+ if(page.m_hdr.granule_position == -1)
+ continue;
+
+ if(pPin != dynamic_cast<COggSplitterOutputPin*>(GetOutputPin(page.m_hdr.bitstream_serial_number)))
+ continue;
+
+ if(pPin->GetRefTime(page.m_hdr.granule_position) > rt)
+ break;
+
+ if(!fKeyFrameFound)
+ {
+ pPin->UnpackPage(page);
+
+ CAutoPtr<OggPacket> p;
+ while(p = pPin->GetPacket())
+ {
+ if(p->bSyncPoint)
+ {
+ fKeyFrameFound = true;
+ fSkipKeyFrame = p->fSkip;
+ }
+ }
+
+ if(fKeyFrameFound) break;
+ }
+ else
+ {
+ pPin->UnpackPage(page);
+
+ CAutoPtr<OggPacket> p;
+ while(p = pPin->GetPacket())
+ {
+ if(!p->fSkip)
+ {
+ fSkipKeyFrame = false;
+ break;
+ }
+ }
+ }
+ }
+
+ if(!(fKeyFrameFound && !fSkipKeyFrame)) {endpos = startpos; startpos = max(startpos - 10*65536, 0);}
+
+ m_pFile->Seek(startpos);
+ }
#ifdef DEBUG
- // verify kf
+ // verify kf
- {
- fKeyFrameFound = false;
+ {
+ fKeyFrameFound = false;
- OggPage page;
- while(!fKeyFrameFound && m_pFile->Read(page))
- {
- if(page.m_hdr.granule_position == -1) continue;
+ OggPage page;
+ while(!fKeyFrameFound && m_pFile->Read(page))
+ {
+ if(page.m_hdr.granule_position == -1) continue;
- if(pPin != dynamic_cast<COggSplitterOutputPin*>(GetOutputPin(page.m_hdr.bitstream_serial_number)))
- continue;
+ if(pPin != dynamic_cast<COggSplitterOutputPin*>(GetOutputPin(page.m_hdr.bitstream_serial_number)))
+ continue;
- REFERENCE_TIME rtPos = pPin->GetRefTime(page.m_hdr.granule_position);
- if(rtPos > rt)
- break;
+ REFERENCE_TIME rtPos = pPin->GetRefTime(page.m_hdr.granule_position);
+ if(rtPos > rt)
+ break;
- pPin->UnpackPage(page);
+ pPin->UnpackPage(page);
- CAutoPtr<OggPacket> p;
- while(p = pPin->GetPacket())
- {
- if(p->bSyncPoint)
- {
- fKeyFrameFound = true;
- break;
- }
- }
- }
+ CAutoPtr<OggPacket> p;
+ while(p = pPin->GetPacket())
+ {
+ if(p->bSyncPoint)
+ {
+ fKeyFrameFound = true;
+ break;
+ }
+ }
+ }
- ASSERT(fKeyFrameFound);
+ ASSERT(fKeyFrameFound);
- m_pFile->Seek(startpos);
- }
+ m_pFile->Seek(startpos);
+ }
#endif
- break;
- }
- }
+ break;
+ }
+ }
}
bool COggSplitterFilter::DemuxLoop()
{
- HRESULT hr = S_OK;
-
- OggPage page;
- while(SUCCEEDED(hr) && !CheckRequest(NULL) && m_pFile->Read(page, true, GetRequestHandle()))
- {
- COggSplitterOutputPin* pOggPin = dynamic_cast<COggSplitterOutputPin*>(GetOutputPin(page.m_hdr.bitstream_serial_number));
- if(!pOggPin)
- {
- ASSERT(0);
- continue;
- }
- if(!pOggPin->IsConnected()) continue;
- if(FAILED(hr = pOggPin->UnpackPage(page)))
- {
- ASSERT(0);
- break;
- }
- CAutoPtr<OggPacket> p;
- while(!CheckRequest(NULL) && SUCCEEDED(hr) && (p = pOggPin->GetPacket()))
- {
- if(!p->fSkip)
- hr = DeliverPacket(p);
- }
- }
-
- return(true);
+ HRESULT hr = S_OK;
+
+ OggPage page;
+ while(SUCCEEDED(hr) && !CheckRequest(NULL) && m_pFile->Read(page, true, GetRequestHandle()))
+ {
+ COggSplitterOutputPin* pOggPin = dynamic_cast<COggSplitterOutputPin*>(GetOutputPin(page.m_hdr.bitstream_serial_number));
+ if(!pOggPin) {ASSERT(0); continue;}
+ if(!pOggPin->IsConnected()) continue;
+ if(FAILED(hr = pOggPin->UnpackPage(page))) {ASSERT(0); break;}
+ CAutoPtr<OggPacket> p;
+ while(!CheckRequest(NULL) && SUCCEEDED(hr) && (p = pOggPin->GetPacket()))
+ {
+ if(!p->fSkip)
+ hr = DeliverPacket(p);
+ }
+ }
+
+ return(true);
}
//
@@ -598,10 +564,10 @@ bool COggSplitterFilter::DemuxLoop()
//
COggSourceFilter::COggSourceFilter(LPUNKNOWN pUnk, HRESULT* phr)
- : COggSplitterFilter(pUnk, phr)
+ : COggSplitterFilter(pUnk, phr)
{
- m_clsid = __uuidof(this);
- m_pInput.Free();
+ m_clsid = __uuidof(this);
+ m_pInput.Free();
}
//
@@ -609,190 +575,190 @@ COggSourceFilter::COggSourceFilter(LPUNKNOWN pUnk, HRESULT* phr)
//
COggSplitterOutputPin::COggSplitterOutputPin(LPCWSTR pName, CBaseFilter* pFilter, CCritSec* pLock, HRESULT* phr)
- : CBaseSplitterOutputPin(pName, pFilter, pLock, phr)
+ : CBaseSplitterOutputPin(pName, pFilter, pLock, phr)
{
- ResetState(-1);
+ ResetState(-1);
}
void COggSplitterOutputPin::AddComment(BYTE* p, int len)
{
- bitstream bs(p, len);
- bs.getbits(bs.getbits(32) * 8);
- for(int n = bs.getbits(32); n-- > 0;)
- {
- CStringA str;
- for(int len = bs.getbits(32); len-- > 0;)
- str += (CHAR)bs.getbits(8);
-
- CAtlList<CStringA> sl;
- Explode(str, sl, '=', 2);
- if(sl.GetCount() == 2)
- {
- CAutoPtr<CComment> p(DNew CComment(UTF8To16(sl.GetHead()), UTF8To16(sl.GetTail())));
-
- if(p->m_key == L"LANGUAGE")
- {
- CString lang = ISO6392ToLanguage(sl.GetTail()), iso6392 = LanguageToISO6392(CString(p->m_value));
-
- if(p->m_value.GetLength() == 3 && !lang.IsEmpty())
- {
- SetName(CStringW(lang));
- SetProperty(L"LANG", p->m_value);
- }
- else if(!iso6392.IsEmpty())
- {
- SetName(p->m_value);
- SetProperty(L"LANG", CStringW(iso6392));
- }
- else
- {
- SetName(p->m_value);
- SetProperty(L"NAME", p->m_value);
- }
- }
-
- m_pComments.AddTail(p);
- }
- }
- ASSERT(bs.getbits(1) == 1);
+ bitstream bs(p, len);
+ bs.getbits(bs.getbits(32)*8);
+ for(int n = bs.getbits(32); n-- > 0; )
+ {
+ CStringA str;
+ for(int len = bs.getbits(32); len-- > 0; )
+ str += (CHAR)bs.getbits(8);
+
+ CAtlList<CStringA> sl;
+ Explode(str, sl, '=', 2);
+ if(sl.GetCount() == 2)
+ {
+ CAutoPtr<CComment> p(DNew CComment(UTF8To16(sl.GetHead()), UTF8To16(sl.GetTail())));
+
+ if(p->m_key == L"LANGUAGE")
+ {
+ CString lang = ISO6392ToLanguage(sl.GetTail()), iso6392 = LanguageToISO6392(CString(p->m_value));
+
+ if(p->m_value.GetLength() == 3 && !lang.IsEmpty())
+ {
+ SetName(CStringW(lang));
+ SetProperty(L"LANG", p->m_value);
+ }
+ else if(!iso6392.IsEmpty())
+ {
+ SetName(p->m_value);
+ SetProperty(L"LANG", CStringW(iso6392));
+ }
+ else
+ {
+ SetName(p->m_value);
+ SetProperty(L"NAME", p->m_value);
+ }
+ }
+
+ m_pComments.AddTail(p);
+ }
+ }
+ ASSERT(bs.getbits(1) == 1);
}
CStringW COggSplitterOutputPin::GetComment(CStringW key)
{
- key.MakeUpper();
- CAtlList<CStringW> sl;
- POSITION pos = m_pComments.GetHeadPosition();
- while(pos)
- {
- CComment* p = m_pComments.GetNext(pos);
- if(key == p->m_key) sl.AddTail(p->m_value);
- }
- return Implode(sl, ';');
+ key.MakeUpper();
+ CAtlList<CStringW> sl;
+ POSITION pos = m_pComments.GetHeadPosition();
+ while(pos)
+ {
+ CComment* p = m_pComments.GetNext(pos);
+ if(key == p->m_key) sl.AddTail(p->m_value);
+ }
+ return Implode(sl, ';');
}
void COggSplitterOutputPin::ResetState(DWORD seqnum)
{
- CAutoLock csAutoLock(&m_csPackets);
- m_packets.RemoveAll();
- m_lastpacket.Free();
- m_lastseqnum = seqnum;
- m_rtLast = 0;
- m_fSkip = true;
+ CAutoLock csAutoLock(&m_csPackets);
+ m_packets.RemoveAll();
+ m_lastpacket.Free();
+ m_lastseqnum = seqnum;
+ m_rtLast = 0;
+ m_fSkip = true;
}
HRESULT COggSplitterOutputPin::UnpackPage(OggPage& page)
{
- if(m_lastseqnum != page.m_hdr.page_sequence_number - 1)
- {
- ResetState(page.m_hdr.page_sequence_number);
- return S_FALSE; // FIXME
- }
- else
- {
- m_lastseqnum = page.m_hdr.page_sequence_number;
- }
+ if(m_lastseqnum != page.m_hdr.page_sequence_number-1)
+ {
+ ResetState(page.m_hdr.page_sequence_number);
+ return S_FALSE; // FIXME
+ }
+ else
+ {
+ m_lastseqnum = page.m_hdr.page_sequence_number;
+ }
- POSITION first = page.m_lens.GetHeadPosition();
- while(first && page.m_lens.GetAt(first) == 255) page.m_lens.GetNext(first);
- if(!first) first = page.m_lens.GetTailPosition();
+ POSITION first = page.m_lens.GetHeadPosition();
+ while(first && page.m_lens.GetAt(first) == 255) page.m_lens.GetNext(first);
+ if(!first) first = page.m_lens.GetTailPosition();
- POSITION last = page.m_lens.GetTailPosition();
- while(last && page.m_lens.GetAt(last) == 255) page.m_lens.GetPrev(last);
- if(!last) last = page.m_lens.GetTailPosition();
+ POSITION last = page.m_lens.GetTailPosition();
+ while(last && page.m_lens.GetAt(last) == 255) page.m_lens.GetPrev(last);
+ if(!last) last = page.m_lens.GetTailPosition();
- BYTE* pData = page.GetData();
+ BYTE* pData = page.GetData();
- int i = 0, j = 0, len = 0;
+ int i = 0, j = 0, len = 0;
for(POSITION pos = page.m_lens.GetHeadPosition(); pos; page.m_lens.GetNext(pos))
- {
- len = page.m_lens.GetAt(pos);
- j += len;
-
- if(len < 255 || pos == page.m_lens.GetTailPosition())
- {
- if(first == pos && (page.m_hdr.header_type_flag & OggPageHeader::continued))
- {
+ {
+ len = page.m_lens.GetAt(pos);
+ j += len;
+
+ if(len < 255 || pos == page.m_lens.GetTailPosition())
+ {
+ if(first == pos && (page.m_hdr.header_type_flag & OggPageHeader::continued))
+ {
// ASSERT(m_lastpacket);
- if(m_lastpacket)
- {
- int size = m_lastpacket->GetCount();
- m_lastpacket->SetCount(size + j - i);
- memcpy(m_lastpacket->GetData() + size, pData + i, j - i);
-
- CAutoLock csAutoLock(&m_csPackets);
-
- if(len < 255) m_packets.AddTail(m_lastpacket);
- }
- }
- else
- {
- CAutoPtr<OggPacket> p(DNew OggPacket());
-
- if(last == pos && page.m_hdr.granule_position != -1)
- {
- p->bDiscontinuity = m_fSkip;
- REFERENCE_TIME rtLast = m_rtLast;
- m_rtLast = GetRefTime(page.m_hdr.granule_position);
-// some bad encodings have a +/-1 frame difference from the normal timeline,
-// but these seem to cancel eachother out nicely so we can just ignore them
+ if(m_lastpacket)
+ {
+ int size = m_lastpacket->GetCount();
+ m_lastpacket->SetCount(size + j-i);
+ memcpy(m_lastpacket->GetData() + size, pData + i, j-i);
+
+ CAutoLock csAutoLock(&m_csPackets);
+
+ if(len < 255) m_packets.AddTail(m_lastpacket);
+ }
+ }
+ else
+ {
+ CAutoPtr<OggPacket> p(DNew OggPacket());
+
+ if(last == pos && page.m_hdr.granule_position != -1)
+ {
+ p->bDiscontinuity = m_fSkip;
+REFERENCE_TIME rtLast = m_rtLast;
+ m_rtLast = GetRefTime(page.m_hdr.granule_position);
+// some bad encodings have a +/-1 frame difference from the normal timeline,
+// but these seem to cancel eachother out nicely so we can just ignore them
// to make it play a bit more smooth.
- if(abs(rtLast - m_rtLast) == GetRefTime(1)) m_rtLast = rtLast; // FIXME
- m_fSkip = false;
- }
+if(abs(rtLast - m_rtLast) == GetRefTime(1)) m_rtLast = rtLast; // FIXME
+ m_fSkip = false;
+ }
- p->TrackNumber = page.m_hdr.bitstream_serial_number;
+ p->TrackNumber = page.m_hdr.bitstream_serial_number;
- if(S_OK == UnpackPacket(p, pData + i, j - i))
- {
+ if(S_OK == UnpackPacket(p, pData + i, j-i))
+ {
//if(p->TrackNumber == 1)
-//TRACE(_T("[%d]: %d, %I64d -> %I64d (skip=%d, disc=%d, sync=%d)\n"),
+//TRACE(_T("[%d]: %d, %I64d -> %I64d (skip=%d, disc=%d, sync=%d)\n"),
// (int)p->TrackNumber, p->GetCount(), p->rtStart, p->rtStop,
// (int)m_fSkip, (int)p->bDiscontinuity, (int)p->bSyncPoint);
- if(p->rtStart <= p->rtStop && p->rtStop <= p->rtStart + 10000000i64 * 60)
- {
- CAutoLock csAutoLock(&m_csPackets);
+ if(p->rtStart <= p->rtStop && p->rtStop <= p->rtStart + 10000000i64*60)
+ {
+ CAutoLock csAutoLock(&m_csPackets);
- m_rtLast = p->rtStop;
- p->fSkip = m_fSkip;
+ m_rtLast = p->rtStop;
+ p->fSkip = m_fSkip;
- if(len < 255) m_packets.AddTail(p);
- else m_lastpacket = p;
- }
- else
- {
- ASSERT(0);
- }
- }
- }
+ if(len < 255) m_packets.AddTail(p);
+ else m_lastpacket = p;
+ }
+ else
+ {
+ ASSERT(0);
+ }
+ }
+ }
- i = j;
- }
- }
+ i = j;
+ }
+ }
- return S_OK;
+ return S_OK;
}
CAutoPtr<OggPacket> COggSplitterOutputPin::GetPacket()
{
- CAutoPtr<OggPacket> p;
- CAutoLock csAutoLock(&m_csPackets);
- if(m_packets.GetCount()) p = m_packets.RemoveHead();
- return p;
+ CAutoPtr<OggPacket> p;
+ CAutoLock csAutoLock(&m_csPackets);
+ if(m_packets.GetCount()) p = m_packets.RemoveHead();
+ return p;
}
HRESULT COggSplitterOutputPin::DeliverEndFlush()
{
- ResetState();
- return __super::DeliverEndFlush();
+ ResetState();
+ return __super::DeliverEndFlush();
}
HRESULT COggSplitterOutputPin::DeliverNewSegment(REFERENCE_TIME tStart, REFERENCE_TIME tStop, double dRate)
{
- ResetState();
- return __super::DeliverNewSegment(tStart, tStop, dRate);
+ ResetState();
+ return __super::DeliverNewSegment(tStart, tStop, dRate);
}
//
@@ -800,155 +766,151 @@ HRESULT COggSplitterOutputPin::DeliverNewSegment(REFERENCE_TIME tStart, REFERENC
//
COggVorbisOutputPin::COggVorbisOutputPin(OggVorbisIdHeader* h, LPCWSTR pName, CBaseFilter* pFilter, CCritSec* pLock, HRESULT* phr)
- : COggSplitterOutputPin(pName, pFilter, pLock, phr)
+ : COggSplitterOutputPin(pName, pFilter, pLock, phr)
{
- m_audio_sample_rate = h->audio_sample_rate;
- m_blocksize[0] = 1 << h->blocksize_0;
- m_blocksize[1] = 1 << h->blocksize_1;
- m_lastblocksize = 0;
-
- CMediaType mt;
-
- mt.InitMediaType();
- mt.majortype = MEDIATYPE_Audio;
- mt.subtype = MEDIASUBTYPE_Vorbis;
- mt.formattype = FORMAT_VorbisFormat;
- VORBISFORMAT* vf = (VORBISFORMAT*)mt.AllocFormatBuffer(sizeof(VORBISFORMAT));
- memset(mt.Format(), 0, mt.FormatLength());
- vf->nChannels = h->audio_channels;
- vf->nSamplesPerSec = h->audio_sample_rate;
- vf->nAvgBitsPerSec = h->bitrate_nominal;
- vf->nMinBitsPerSec = h->bitrate_minimum;
- vf->nMaxBitsPerSec = h->bitrate_maximum;
- vf->fQuality = -1;
- mt.SetSampleSize(8192);
- m_mts.Add(mt);
-
- mt.InitMediaType();
- mt.majortype = MEDIATYPE_Audio;
- mt.subtype = MEDIASUBTYPE_Vorbis2;
- mt.formattype = FORMAT_VorbisFormat2;
- VORBISFORMAT2* vf2 = (VORBISFORMAT2*)mt.AllocFormatBuffer(sizeof(VORBISFORMAT2));
- memset(mt.Format(), 0, mt.FormatLength());
- vf2->Channels = h->audio_channels;
- vf2->SamplesPerSec = h->audio_sample_rate;
- mt.SetSampleSize(8192);
- m_mts.InsertAt(0, mt);
+ m_audio_sample_rate = h->audio_sample_rate;
+ m_blocksize[0] = 1<<h->blocksize_0;
+ m_blocksize[1] = 1<<h->blocksize_1;
+ m_lastblocksize = 0;
+
+ CMediaType mt;
+
+ mt.InitMediaType();
+ mt.majortype = MEDIATYPE_Audio;
+ mt.subtype = MEDIASUBTYPE_Vorbis;
+ mt.formattype = FORMAT_VorbisFormat;
+ VORBISFORMAT* vf = (VORBISFORMAT*)mt.AllocFormatBuffer(sizeof(VORBISFORMAT));
+ memset(mt.Format(), 0, mt.FormatLength());
+ vf->nChannels = h->audio_channels;
+ vf->nSamplesPerSec = h->audio_sample_rate;
+ vf->nAvgBitsPerSec = h->bitrate_nominal;
+ vf->nMinBitsPerSec = h->bitrate_minimum;
+ vf->nMaxBitsPerSec = h->bitrate_maximum;
+ vf->fQuality = -1;
+ mt.SetSampleSize(8192);
+ m_mts.Add(mt);
+
+ mt.InitMediaType();
+ mt.majortype = MEDIATYPE_Audio;
+ mt.subtype = MEDIASUBTYPE_Vorbis2;
+ mt.formattype = FORMAT_VorbisFormat2;
+ VORBISFORMAT2* vf2 = (VORBISFORMAT2*)mt.AllocFormatBuffer(sizeof(VORBISFORMAT2));
+ memset(mt.Format(), 0, mt.FormatLength());
+ vf2->Channels = h->audio_channels;
+ vf2->SamplesPerSec = h->audio_sample_rate;
+ mt.SetSampleSize(8192);
+ m_mts.InsertAt(0, mt);
}
HRESULT COggVorbisOutputPin::UnpackInitPage(OggPage& page)
{
- HRESULT hr = __super::UnpackPage(page);
-
- while(m_packets.GetCount())
- {
- Packet* p = m_packets.GetHead();
-
- if(p->GetCount() >= 6 && p->GetAt(0) == 0x05)
- {
- // yeah, right, we are going to be parsing this backwards! :P
- bitstream bs(p->GetData(), p->GetCount(), true);
- while(bs.hasbits(-1) && bs.getbits(-1) != 1);
- for(int cnt = 0; bs.hasbits(-8 - 16 - 16 - 1 - 6); cnt++)
- {
- unsigned int modes = bs.showbits(-6) + 1;
-
- unsigned int mapping = bs.getbits(-8);
- unsigned int transformtype = bs.getbits(-16);
- unsigned int windowtype = bs.getbits(-16);
- unsigned int blockflag = bs.getbits(-1);
-
- if(transformtype != 0 || windowtype != 0)
- {
- ASSERT(modes == cnt);
- break;
- }
-
- m_blockflags.InsertAt(0, !!blockflag);
- }
- }
-
- int cnt = m_initpackets.GetCount();
- if(cnt <= 3)
- {
- ASSERT(p->GetCount() >= 6 && p->GetAt(0) == 1 + cnt * 2);
- VORBISFORMAT2* vf2 = (VORBISFORMAT2*)m_mts[0].Format();
- vf2->HeaderSize[cnt] = p->GetCount();
- int len = m_mts[0].FormatLength();
- memcpy(
- m_mts[0].ReallocFormatBuffer(len + p->GetCount()) + len,
- p->GetData(), p->GetCount());
- }
-
- m_initpackets.AddTail(m_packets.RemoveHead());
- }
-
- return hr;
+ HRESULT hr = __super::UnpackPage(page);
+
+ while(m_packets.GetCount())
+ {
+ Packet* p = m_packets.GetHead();
+
+ if(p->GetCount() >= 6 && p->GetAt(0) == 0x05)
+ {
+ // yeah, right, we are going to be parsing this backwards! :P
+ bitstream bs(p->GetData(), p->GetCount(), true);
+ while(bs.hasbits(-1) && bs.getbits(-1) != 1);
+ for(int cnt = 0; bs.hasbits(-8-16-16-1-6); cnt++)
+ {
+ unsigned int modes = bs.showbits(-6)+1;
+
+ unsigned int mapping = bs.getbits(-8);
+ unsigned int transformtype = bs.getbits(-16);
+ unsigned int windowtype = bs.getbits(-16);
+ unsigned int blockflag = bs.getbits(-1);
+
+ if(transformtype != 0 || windowtype != 0)
+ {
+ ASSERT(modes == cnt);
+ break;
+ }
+
+ m_blockflags.InsertAt(0, !!blockflag);
+ }
+ }
+
+ int cnt = m_initpackets.GetCount();
+ if(cnt <= 3)
+ {
+ ASSERT(p->GetCount() >= 6 && p->GetAt(0) == 1+cnt*2);
+ VORBISFORMAT2* vf2 = (VORBISFORMAT2*)m_mts[0].Format();
+ vf2->HeaderSize[cnt] = p->GetCount();
+ int len = m_mts[0].FormatLength();
+ memcpy(
+ m_mts[0].ReallocFormatBuffer(len + p->GetCount()) + len,
+ p->GetData(), p->GetCount());
+ }
+
+ m_initpackets.AddTail(m_packets.RemoveHead());
+ }
+
+ return hr;
}
REFERENCE_TIME COggVorbisOutputPin::GetRefTime(__int64 granule_position)
{
- REFERENCE_TIME rt = granule_position * 10000000 / m_audio_sample_rate;
- return rt;
+ REFERENCE_TIME rt = granule_position * 10000000 / m_audio_sample_rate;
+ return rt;
}
HRESULT COggVorbisOutputPin::UnpackPacket(CAutoPtr<OggPacket>& p, BYTE* pData, int len)
{
- if(len > 0 && m_blockflags.GetCount())
- {
- bitstream bs(pData, len);
- if(bs.getbits(1) == 0)
- {
- int x = m_blockflags.GetCount() - 1, n = 0;
- while(x)
- {
- n++;
- x >>= 1;
- }
- DWORD blocksize = m_blocksize[m_blockflags[bs.getbits(n)] ? 1 : 0];
- if(m_lastblocksize) m_rtLast += GetRefTime((m_lastblocksize + blocksize) >> 2);
- m_lastblocksize = blocksize;
- }
- }
-
- p->bSyncPoint = TRUE;
- p->rtStart = m_rtLast;
- p->rtStop = m_rtLast + 1;
- p->SetData(pData, len);
-
- return S_OK;
+ if(len > 0 && m_blockflags.GetCount())
+ {
+ bitstream bs(pData, len);
+ if(bs.getbits(1) == 0)
+ {
+ int x = m_blockflags.GetCount()-1, n = 0;
+ while(x) {n++; x >>= 1;}
+ DWORD blocksize = m_blocksize[m_blockflags[bs.getbits(n)]?1:0];
+ if(m_lastblocksize) m_rtLast += GetRefTime((m_lastblocksize + blocksize) >> 2);
+ m_lastblocksize = blocksize;
+ }
+ }
+
+ p->bSyncPoint = TRUE;
+ p->rtStart = m_rtLast;
+ p->rtStop = m_rtLast+1;
+ p->SetData(pData, len);
+
+ return S_OK;
}
HRESULT COggVorbisOutputPin::DeliverPacket(CAutoPtr<OggPacket> p)
{
- if(p->GetCount() > 0 && (p->GetAt(0) & 1))
- return S_OK;
+ if(p->GetCount() > 0 && (p->GetAt(0)&1))
+ return S_OK;
- return __super::DeliverPacket(p);
+ return __super::DeliverPacket(p);
}
HRESULT COggVorbisOutputPin::DeliverNewSegment(REFERENCE_TIME tStart, REFERENCE_TIME tStop, double dRate)
{
- HRESULT hr = __super::DeliverNewSegment(tStart, tStop, dRate);
-
- m_lastblocksize = 0;
-
- if(m_mt.subtype == MEDIASUBTYPE_Vorbis)
- {
- POSITION pos = m_initpackets.GetHeadPosition();
- while(pos)
- {
- Packet* pi = m_initpackets.GetNext(pos);
- CAutoPtr<OggPacket> p(DNew OggPacket());
- p->TrackNumber = pi->TrackNumber;
- p->bDiscontinuity = p->bSyncPoint = FALSE;//TRUE;
- p->rtStart = p->rtStop = 0;
- p->Copy(*pi);
- __super::DeliverPacket(p);
- }
- }
-
- return hr;
+ HRESULT hr = __super::DeliverNewSegment(tStart, tStop, dRate);
+
+ m_lastblocksize = 0;
+
+ if(m_mt.subtype == MEDIASUBTYPE_Vorbis)
+ {
+ POSITION pos = m_initpackets.GetHeadPosition();
+ while(pos)
+ {
+ Packet* pi = m_initpackets.GetNext(pos);
+ CAutoPtr<OggPacket> p(DNew OggPacket());
+ p->TrackNumber = pi->TrackNumber;
+ p->bDiscontinuity = p->bSyncPoint = FALSE;//TRUE;
+ p->rtStart = p->rtStop = 0;
+ p->Copy(*pi);
+ __super::DeliverPacket(p);
+ }
+ }
+
+ return hr;
}
//
@@ -956,161 +918,157 @@ HRESULT COggVorbisOutputPin::DeliverNewSegment(REFERENCE_TIME tStart, REFERENCE_
//
COggFlacOutputPin::COggFlacOutputPin(BYTE* h, int nCount, LPCWSTR pName, CBaseFilter* pFilter, CCritSec* pLock, HRESULT* phr)
- : COggSplitterOutputPin(pName, pFilter, pLock, phr)
+ : COggSplitterOutputPin(pName, pFilter, pLock, phr)
{
- CGolombBuffer Buffer(h, nCount);
-
- Buffer.BitRead(1); // Last-metadata-block flag
-
- if(Buffer.BitRead(7) != 0) // Should be a STREAMINFO block
- {
- if(phr) *phr = VFW_E_INVALID_FILE_FORMAT;
- return;
- }
-
- Buffer.BitRead(24); // Length (in bytes) of metadata to follow
- Buffer.ReadShort(); // m_nMinBlocksize
- Buffer.ReadShort(); // m_nMaxBlocksize
- Buffer.BitRead(24); // m_nMinFrameSize
- Buffer.BitRead(24); // m_nMaxFrameSize
- m_nSamplesPerSec = (int)Buffer.BitRead(20);
- m_nChannels = (int)Buffer.BitRead(3) + 1;
- m_wBitsPerSample = (WORD)Buffer.BitRead(5) + 1;
- Buffer.BitRead(36); // m_i64TotalNumSamples
- m_nAvgBytesPerSec = (m_nChannels * (m_wBitsPerSample >> 3)) * m_nSamplesPerSec;
-
- CMediaType mt;
-
- mt.majortype = MEDIATYPE_Audio;
- mt.subtype = MEDIASUBTYPE_FLAC_FRAMED;
- mt.formattype = FORMAT_WaveFormatEx;
- WAVEFORMATEX* wfe = (WAVEFORMATEX*)mt.AllocFormatBuffer(sizeof(WAVEFORMATEX));
- memset(wfe, 0, sizeof(WAVEFORMATEX));
- wfe->cbSize = sizeof(WAVEFORMATEX);
- wfe->wFormatTag = WAVE_FORMAT_FLAC;
- wfe->nSamplesPerSec = m_nSamplesPerSec;
- wfe->nAvgBytesPerSec = m_nAvgBytesPerSec;
- wfe->nChannels = m_nChannels;
- wfe->nBlockAlign = 1;
- wfe->wBitsPerSample = m_wBitsPerSample;
-
- m_mts.InsertAt(0, mt);
- *phr = S_OK;
+ CGolombBuffer Buffer(h, nCount);
+
+ Buffer.BitRead(1); // Last-metadata-block flag
+
+ if (Buffer.BitRead(7) != 0) // Should be a STREAMINFO block
+ {
+ if(phr) *phr = VFW_E_INVALID_FILE_FORMAT;
+ return;
+ }
+
+ Buffer.BitRead(24); // Length (in bytes) of metadata to follow
+ Buffer.ReadShort(); // m_nMinBlocksize
+ Buffer.ReadShort(); // m_nMaxBlocksize
+ Buffer.BitRead(24); // m_nMinFrameSize
+ Buffer.BitRead(24); // m_nMaxFrameSize
+ m_nSamplesPerSec = (int)Buffer.BitRead(20);
+ m_nChannels = (int)Buffer.BitRead(3) + 1;
+ m_wBitsPerSample = (WORD)Buffer.BitRead(5) + 1;
+ Buffer.BitRead(36); // m_i64TotalNumSamples
+ m_nAvgBytesPerSec = (m_nChannels * (m_wBitsPerSample >> 3)) * m_nSamplesPerSec;
+
+ CMediaType mt;
+
+ mt.majortype = MEDIATYPE_Audio;
+ mt.subtype = MEDIASUBTYPE_FLAC_FRAMED;
+ mt.formattype = FORMAT_WaveFormatEx;
+ WAVEFORMATEX* wfe = (WAVEFORMATEX*)mt.AllocFormatBuffer(sizeof(WAVEFORMATEX));
+ memset(wfe, 0, sizeof(WAVEFORMATEX));
+ wfe->cbSize = sizeof(WAVEFORMATEX);
+ wfe->wFormatTag = WAVE_FORMAT_FLAC;
+ wfe->nSamplesPerSec = m_nSamplesPerSec;
+ wfe->nAvgBytesPerSec = m_nAvgBytesPerSec;
+ wfe->nChannels = m_nChannels;
+ wfe->nBlockAlign = 1;
+ wfe->wBitsPerSample = m_wBitsPerSample;
+
+ m_mts.InsertAt(0, mt);
+ *phr = S_OK;
}
REFERENCE_TIME COggFlacOutputPin::GetRefTime(__int64 granule_position)
{
- REFERENCE_TIME rt = (granule_position * UNITS) / m_nSamplesPerSec;
- return rt;
+ REFERENCE_TIME rt = (granule_position * UNITS) / m_nSamplesPerSec;
+ return rt;
}
HRESULT COggFlacOutputPin::UnpackPacket(CAutoPtr<OggPacket>& p, BYTE* pData, int len)
{
- if(pData[0] != 0xFF || (pData[1] & 0xFE) != 0xF8)
- {
- return S_FALSE;
- }
+ if (pData[0] != 0xFF || (pData[1] & 0xFE) != 0xF8)
+ {
+ return S_FALSE;
+ }
- p->bSyncPoint = TRUE;
- p->rtStart = m_rtLast;
- p->rtStop = m_rtLast + 1; // TODO : find packet duration !
- p->SetData(pData, len);
+ p->bSyncPoint = TRUE;
+ p->rtStart = m_rtLast;
+ p->rtStop = m_rtLast+1; // TODO : find packet duration !
+ p->SetData(pData, len);
- return S_OK;
+ return S_OK;
}
HRESULT COggFlacOutputPin::DeliverPacket(CAutoPtr<OggPacket> p)
{
- if(p->GetCount() > 0 && (p->GetAt(0) & 1))
- return S_OK;
+ if(p->GetCount() > 0 && (p->GetAt(0)&1))
+ return S_OK;
- return __super::DeliverPacket(p);
+ return __super::DeliverPacket(p);
}
HRESULT COggFlacOutputPin::DeliverNewSegment(REFERENCE_TIME tStart, REFERENCE_TIME tStop, double dRate)
{
- HRESULT hr = __super::DeliverNewSegment(tStart, tStop, dRate);
-
- m_lastblocksize = 0;
-
- if(m_mt.subtype == MEDIASUBTYPE_FLAC_FRAMED)
- {
- POSITION pos = m_initpackets.GetHeadPosition();
- while(pos)
- {
- Packet* pi = m_initpackets.GetNext(pos);
- CAutoPtr<OggPacket> p(DNew OggPacket());
- p->TrackNumber = pi->TrackNumber;
- p->bDiscontinuity = p->bSyncPoint = FALSE;//TRUE;
- p->rtStart = p->rtStop = 0;
- p->Copy(*pi);
- __super::DeliverPacket(p);
- }
- }
-
- return hr;
+ HRESULT hr = __super::DeliverNewSegment(tStart, tStop, dRate);
+
+ m_lastblocksize = 0;
+
+ if(m_mt.subtype == MEDIASUBTYPE_FLAC_FRAMED)
+ {
+ POSITION pos = m_initpackets.GetHeadPosition();
+ while(pos)
+ {
+ Packet* pi = m_initpackets.GetNext(pos);
+ CAutoPtr<OggPacket> p(DNew OggPacket());
+ p->TrackNumber = pi->TrackNumber;
+ p->bDiscontinuity = p->bSyncPoint = FALSE;//TRUE;
+ p->rtStart = p->rtStop = 0;
+ p->Copy(*pi);
+ __super::DeliverPacket(p);
+ }
+ }
+
+ return hr;
}
//
// COggDirectShowOutputPin
//
COggDirectShowOutputPin::COggDirectShowOutputPin(AM_MEDIA_TYPE* pmt, LPCWSTR pName, CBaseFilter* pFilter, CCritSec* pLock, HRESULT* phr)
- : COggSplitterOutputPin(pName, pFilter, pLock, phr)
+ : COggSplitterOutputPin(pName, pFilter, pLock, phr)
{
- CMediaType mt;
- memcpy((AM_MEDIA_TYPE*)&mt, pmt, FIELD_OFFSET(AM_MEDIA_TYPE, pUnk));
- mt.SetFormat((BYTE*)(pmt + 1), pmt->cbFormat);
- mt.SetSampleSize(1);
- if(mt.majortype == MEDIATYPE_Video) // TODO: find samples for audio and find out what to return in GetRefTime...
- m_mts.Add(mt);
+ CMediaType mt;
+ memcpy((AM_MEDIA_TYPE*)&mt, pmt, FIELD_OFFSET(AM_MEDIA_TYPE, pUnk));
+ mt.SetFormat((BYTE*)(pmt+1), pmt->cbFormat);
+ mt.SetSampleSize(1);
+ if(mt.majortype == MEDIATYPE_Video) // TODO: find samples for audio and find out what to return in GetRefTime...
+ m_mts.Add(mt);
}
REFERENCE_TIME COggDirectShowOutputPin::GetRefTime(__int64 granule_position)
{
- REFERENCE_TIME rt = 0;
-
- if(m_mt.majortype == MEDIATYPE_Video)
- {
- rt = granule_position * ((VIDEOINFOHEADER*)m_mt.Format())->AvgTimePerFrame;
- }
- else if(m_mt.majortype == MEDIATYPE_Audio)
- {
- rt = granule_position; // ((WAVEFORMATEX*)m_mt.Format())-> // TODO
- }
-
- return rt;
+ REFERENCE_TIME rt = 0;
+
+ if(m_mt.majortype == MEDIATYPE_Video)
+ {
+ rt = granule_position * ((VIDEOINFOHEADER*)m_mt.Format())->AvgTimePerFrame;
+ }
+ else if(m_mt.majortype == MEDIATYPE_Audio)
+ {
+ rt = granule_position; // ((WAVEFORMATEX*)m_mt.Format())-> // TODO
+ }
+
+ return rt;
}
HRESULT COggDirectShowOutputPin::UnpackPacket(CAutoPtr<OggPacket>& p, BYTE* pData, int len)
{
- int i = 0;
+ int i = 0;
- BYTE hdr = pData[i++];
+ BYTE hdr = pData[i++];
- if(!(hdr & 1))
- {
- // TODO: verify if this was still present in the old format (haven't found one sample yet)
- BYTE nLenBytes = (hdr >> 6) | ((hdr & 2) << 1);
- __int64 Length = 0;
- for(int j = 0; j < nLenBytes; j++)
- Length |= (__int64)pData[i++] << (j << 3);
+ if(!(hdr&1))
+ {
+ // TODO: verify if this was still present in the old format (haven't found one sample yet)
+ BYTE nLenBytes = (hdr>>6)|((hdr&2)<<1);
+ __int64 Length = 0;
+ for(int j = 0; j < nLenBytes; j++)
+ Length |= (__int64)pData[i++] << (j << 3);
- if(len < i)
- {
- ASSERT(0);
- return E_FAIL;
- }
+ if(len < i) {ASSERT(0); return E_FAIL;}
- p->bSyncPoint = !!(hdr & 8);
- p->rtStart = m_rtLast;
- p->rtStop = m_rtLast + (nLenBytes ? GetRefTime(Length) : GetRefTime(1));
- p->SetData(&pData[i], len - i);
+ p->bSyncPoint = !!(hdr&8);
+ p->rtStart = m_rtLast;
+ p->rtStop = m_rtLast + (nLenBytes ? GetRefTime(Length) : GetRefTime(1));
+ p->SetData(&pData[i], len - i);
- return S_OK;
- }
+ return S_OK;
+ }
- return S_FALSE;
+ return S_FALSE;
}
//
@@ -1118,46 +1076,42 @@ HRESULT COggDirectShowOutputPin::UnpackPacket(CAutoPtr<OggPacket>& p, BYTE* pDat
//
COggStreamOutputPin::COggStreamOutputPin(OggStreamHeader* h, LPCWSTR pName, CBaseFilter* pFilter, CCritSec* pLock, HRESULT* phr)
- : COggSplitterOutputPin(pName, pFilter, pLock, phr)
+ : COggSplitterOutputPin(pName, pFilter, pLock, phr)
{
- m_time_unit = h->time_unit;
- m_samples_per_unit = h->samples_per_unit;
- m_default_len = h->default_len;
+ m_time_unit = h->time_unit;
+ m_samples_per_unit = h->samples_per_unit;
+ m_default_len = h->default_len;
}
REFERENCE_TIME COggStreamOutputPin::GetRefTime(__int64 granule_position)
{
- return granule_position * m_time_unit / m_samples_per_unit;
+ return granule_position * m_time_unit / m_samples_per_unit;
}
HRESULT COggStreamOutputPin::UnpackPacket(CAutoPtr<OggPacket>& p, BYTE* pData, int len)
{
- int i = 0;
+ int i = 0;
- BYTE hdr = pData[i++];
+ BYTE hdr = pData[i++];
- if(!(hdr & 1))
- {
- BYTE nLenBytes = (hdr >> 6) | ((hdr & 2) << 1);
- __int64 Length = 0;
- for(int j = 0; j < nLenBytes; j++)
- Length |= (__int64)pData[i++] << (j << 3);
+ if(!(hdr&1))
+ {
+ BYTE nLenBytes = (hdr>>6)|((hdr&2)<<1);
+ __int64 Length = 0;
+ for(int j = 0; j < nLenBytes; j++)
+ Length |= (__int64)pData[i++] << (j << 3);
- if(len < i)
- {
- ASSERT(0);
- return E_FAIL;
- }
+ if(len < i) {ASSERT(0); return E_FAIL;}
- p->bSyncPoint = !!(hdr & 8);
- p->rtStart = m_rtLast;
- p->rtStop = m_rtLast + (nLenBytes ? GetRefTime(Length) : GetRefTime(m_default_len));
- p->SetData(&pData[i], len - i);
+ p->bSyncPoint = !!(hdr&8);
+ p->rtStart = m_rtLast;
+ p->rtStop = m_rtLast + (nLenBytes ? GetRefTime(Length) : GetRefTime(m_default_len));
+ p->SetData(&pData[i], len - i);
- return S_OK;
- }
+ return S_OK;
+ }
- return S_FALSE;
+ return S_FALSE;
}
//
@@ -1165,45 +1119,39 @@ HRESULT COggStreamOutputPin::UnpackPacket(CAutoPtr<OggPacket>& p, BYTE* pData, i
//
COggVideoOutputPin::COggVideoOutputPin(OggStreamHeader* h, LPCWSTR pName, CBaseFilter* pFilter, CCritSec* pLock, HRESULT* phr)
- : COggStreamOutputPin(h, pName, pFilter, pLock, phr)
+ : COggStreamOutputPin(h, pName, pFilter, pLock, phr)
{
- int extra = (int)h->size - sizeof(OggStreamHeader);
- extra = max(extra, 0);
-
- CMediaType mt;
- mt.majortype = MEDIATYPE_Video;
- mt.subtype = FOURCCMap(MAKEFOURCC(h->subtype[0], h->subtype[1], h->subtype[2], h->subtype[3]));
- mt.formattype = FORMAT_VideoInfo;
- VIDEOINFOHEADER* pvih = (VIDEOINFOHEADER*)mt.AllocFormatBuffer(sizeof(VIDEOINFOHEADER) + extra);
- memset(mt.Format(), 0, mt.FormatLength());
- memcpy(mt.Format() + sizeof(VIDEOINFOHEADER), h + 1, extra);
- pvih->AvgTimePerFrame = h->time_unit / h->samples_per_unit;
- pvih->bmiHeader.biWidth = h->v.w;
- pvih->bmiHeader.biHeight = h->v.h;
- pvih->bmiHeader.biBitCount = (WORD)h->bps;
- pvih->bmiHeader.biCompression = mt.subtype.Data1;
- switch(pvih->bmiHeader.biCompression)
- {
- case BI_RGB:
- case BI_BITFIELDS:
- mt.subtype =
- pvih->bmiHeader.biBitCount == 1 ? MEDIASUBTYPE_RGB1 :
- pvih->bmiHeader.biBitCount == 4 ? MEDIASUBTYPE_RGB4 :
- pvih->bmiHeader.biBitCount == 8 ? MEDIASUBTYPE_RGB8 :
- pvih->bmiHeader.biBitCount == 16 ? MEDIASUBTYPE_RGB565 :
- pvih->bmiHeader.biBitCount == 24 ? MEDIASUBTYPE_RGB24 :
- pvih->bmiHeader.biBitCount == 32 ? MEDIASUBTYPE_RGB32 :
- MEDIASUBTYPE_NULL;
- break;
- case BI_RLE8:
- mt.subtype = MEDIASUBTYPE_RGB8;
- break;
- case BI_RLE4:
- mt.subtype = MEDIASUBTYPE_RGB4;
- break;
- }
- mt.SetSampleSize(max(h->buffersize, 1));
- m_mts.Add(mt);
+ int extra = (int)h->size - sizeof(OggStreamHeader);
+ extra = max(extra, 0);
+
+ CMediaType mt;
+ mt.majortype = MEDIATYPE_Video;
+ mt.subtype = FOURCCMap(MAKEFOURCC(h->subtype[0],h->subtype[1],h->subtype[2],h->subtype[3]));
+ mt.formattype = FORMAT_VideoInfo;
+ VIDEOINFOHEADER* pvih = (VIDEOINFOHEADER*)mt.AllocFormatBuffer(sizeof(VIDEOINFOHEADER) + extra);
+ memset(mt.Format(), 0, mt.FormatLength());
+ memcpy(mt.Format() + sizeof(VIDEOINFOHEADER), h+1, extra);
+ pvih->AvgTimePerFrame = h->time_unit / h->samples_per_unit;
+ pvih->bmiHeader.biWidth = h->v.w;
+ pvih->bmiHeader.biHeight = h->v.h;
+ pvih->bmiHeader.biBitCount = (WORD)h->bps;
+ pvih->bmiHeader.biCompression = mt.subtype.Data1;
+ switch(pvih->bmiHeader.biCompression)
+ {
+ case BI_RGB: case BI_BITFIELDS: mt.subtype =
+ pvih->bmiHeader.biBitCount == 1 ? MEDIASUBTYPE_RGB1 :
+ pvih->bmiHeader.biBitCount == 4 ? MEDIASUBTYPE_RGB4 :
+ pvih->bmiHeader.biBitCount == 8 ? MEDIASUBTYPE_RGB8 :
+ pvih->bmiHeader.biBitCount == 16 ? MEDIASUBTYPE_RGB565 :
+ pvih->bmiHeader.biBitCount == 24 ? MEDIASUBTYPE_RGB24 :
+ pvih->bmiHeader.biBitCount == 32 ? MEDIASUBTYPE_RGB32 :
+ MEDIASUBTYPE_NULL;
+ break;
+ case BI_RLE8: mt.subtype = MEDIASUBTYPE_RGB8; break;
+ case BI_RLE4: mt.subtype = MEDIASUBTYPE_RGB4; break;
+ }
+ mt.SetSampleSize(max(h->buffersize, 1));
+ m_mts.Add(mt);
}
//
@@ -1211,27 +1159,27 @@ COggVideoOutputPin::COggVideoOutputPin(OggStreamHeader* h, LPCWSTR pName, CBaseF
//
COggAudioOutputPin::COggAudioOutputPin(OggStreamHeader* h, LPCWSTR pName, CBaseFilter* pFilter, CCritSec* pLock, HRESULT* phr)
- : COggStreamOutputPin(h, pName, pFilter, pLock, phr)
+ : COggStreamOutputPin(h, pName, pFilter, pLock, phr)
{
- int extra = (int)h->size - sizeof(OggStreamHeader);
- extra = max(extra, 0);
-
- CMediaType mt;
- mt.majortype = MEDIATYPE_Audio;
- mt.subtype = FOURCCMap(strtol(CStringA(h->subtype, 4), NULL, 16));
- mt.formattype = FORMAT_WaveFormatEx;
- WAVEFORMATEX* wfe = (WAVEFORMATEX*)mt.AllocFormatBuffer(sizeof(WAVEFORMATEX) + extra);
- memset(mt.Format(), 0, mt.FormatLength());
- memcpy(mt.Format() + sizeof(WAVEFORMATEX), h + 1, extra);
- wfe->cbSize = extra;
- wfe->wFormatTag = (WORD)mt.subtype.Data1;
- wfe->nChannels = h->a.nChannels;
- wfe->nSamplesPerSec = (DWORD)(10000000i64 * h->samples_per_unit / h->time_unit);
- wfe->wBitsPerSample = (WORD)h->bps;
- wfe->nAvgBytesPerSec = h->a.nAvgBytesPerSec; // TODO: verify for PCM
- wfe->nBlockAlign = h->a.nBlockAlign; // TODO: verify for PCM
- mt.SetSampleSize(max(h->buffersize, 1));
- m_mts.Add(mt);
+ int extra = (int)h->size - sizeof(OggStreamHeader);
+ extra = max(extra, 0);
+
+ CMediaType mt;
+ mt.majortype = MEDIATYPE_Audio;
+ mt.subtype = FOURCCMap(strtol(CStringA(h->subtype, 4), NULL, 16));
+ mt.formattype = FORMAT_WaveFormatEx;
+ WAVEFORMATEX* wfe = (WAVEFORMATEX*)mt.AllocFormatBuffer(sizeof(WAVEFORMATEX) + extra);
+ memset(mt.Format(), 0, mt.FormatLength());
+ memcpy(mt.Format() + sizeof(WAVEFORMATEX), h+1, extra);
+ wfe->cbSize = extra;
+ wfe->wFormatTag = (WORD)mt.subtype.Data1;
+ wfe->nChannels = h->a.nChannels;
+ wfe->nSamplesPerSec = (DWORD)(10000000i64 * h->samples_per_unit / h->time_unit);
+ wfe->wBitsPerSample = (WORD)h->bps;
+ wfe->nAvgBytesPerSec = h->a.nAvgBytesPerSec; // TODO: verify for PCM
+ wfe->nBlockAlign = h->a.nBlockAlign; // TODO: verify for PCM
+ mt.SetSampleSize(max(h->buffersize, 1));
+ m_mts.Add(mt);
}
//
@@ -1239,75 +1187,75 @@ COggAudioOutputPin::COggAudioOutputPin(OggStreamHeader* h, LPCWSTR pName, CBaseF
//
COggTextOutputPin::COggTextOutputPin(OggStreamHeader* h, LPCWSTR pName, CBaseFilter* pFilter, CCritSec* pLock, HRESULT* phr)
- : COggStreamOutputPin(h, pName, pFilter, pLock, phr)
+ : COggStreamOutputPin(h, pName, pFilter, pLock, phr)
{
- CMediaType mt;
- mt.majortype = MEDIATYPE_Text;
- mt.subtype = MEDIASUBTYPE_NULL;
- mt.formattype = FORMAT_None;
- mt.SetSampleSize(1);
- m_mts.Add(mt);
+ CMediaType mt;
+ mt.majortype = MEDIATYPE_Text;
+ mt.subtype = MEDIASUBTYPE_NULL;
+ mt.formattype = FORMAT_None;
+ mt.SetSampleSize(1);
+ m_mts.Add(mt);
}
// COggTheoraOutputPin
COggTheoraOutputPin::COggTheoraOutputPin(BYTE* p, LPCWSTR pName, CBaseFilter* pFilter, CCritSec* pLock, HRESULT* phr)
- : COggSplitterOutputPin(pName, pFilter, pLock, phr)
+ : COggSplitterOutputPin(pName, pFilter, pLock, phr)
{
- CMediaType mt;
- mt.majortype = MEDIATYPE_Video;
- mt.subtype = FOURCCMap('OEHT');
- mt.formattype = FORMAT_MPEG2_VIDEO;
- MPEG2VIDEOINFO* vih = (MPEG2VIDEOINFO*)mt.AllocFormatBuffer(sizeof(MPEG2VIDEOINFO));
- memset(mt.Format(), 0, mt.FormatLength());
- vih->hdr.bmiHeader.biSize = sizeof(vih->hdr.bmiHeader);
- vih->hdr.bmiHeader.biWidth = *(WORD*)&p[10] >> 4;
- vih->hdr.bmiHeader.biHeight = *(WORD*)&p[12] >> 4;
- vih->hdr.bmiHeader.biCompression = 'OEHT';
- vih->hdr.bmiHeader.biPlanes = 1;
- vih->hdr.bmiHeader.biBitCount = 24;
- m_nFpsNum = (p[22] << 24) | (p[23] << 16) | (p[24] << 8) | p[25];
- m_nFpsDenum = (p[26] << 24) | (p[27] << 16) | (p[28] << 8) | p[29];
- if(m_nFpsNum)
- {
- m_rtAvgTimePerFrame = (REFERENCE_TIME)(10000000.0 * m_nFpsDenum / m_nFpsNum);
- vih->hdr.AvgTimePerFrame = m_rtAvgTimePerFrame;
- }
- vih->hdr.dwPictAspectRatioX = (p[14] << 16) | (p[15] << 8) | p[16];
- vih->hdr.dwPictAspectRatioY = (p[17] << 16) | (p[18] << 8) | p[19];
-
- m_KfgShift = (((p[40] << 8) + p[41]) & 0x3E0) >> 5;
- m_nIndexOffset = TH_VERSION_CHECK(p[7], p[8], p[9], 3, 2, 1);
-
- if(m_KfgShift == 0) m_KfgShift = 6; // Is it really default value ?
-
- mt.bFixedSizeSamples = 0;
- m_mts.Add(mt);
+ CMediaType mt;
+ mt.majortype = MEDIATYPE_Video;
+ mt.subtype = FOURCCMap('OEHT');
+ mt.formattype = FORMAT_MPEG2_VIDEO;
+ MPEG2VIDEOINFO* vih = (MPEG2VIDEOINFO*)mt.AllocFormatBuffer(sizeof(MPEG2VIDEOINFO));
+ memset(mt.Format(), 0, mt.FormatLength());
+ vih->hdr.bmiHeader.biSize = sizeof(vih->hdr.bmiHeader);
+ vih->hdr.bmiHeader.biWidth = *(WORD*)&p[10] >> 4;
+ vih->hdr.bmiHeader.biHeight = *(WORD*)&p[12] >> 4;
+ vih->hdr.bmiHeader.biCompression = 'OEHT';
+ vih->hdr.bmiHeader.biPlanes = 1;
+ vih->hdr.bmiHeader.biBitCount = 24;
+ m_nFpsNum = (p[22]<<24)|(p[23]<<16)|(p[24]<<8)|p[25];
+ m_nFpsDenum = (p[26]<<24)|(p[27]<<16)|(p[28]<<8)|p[29];
+ if(m_nFpsNum)
+ {
+ m_rtAvgTimePerFrame = (REFERENCE_TIME)(10000000.0 * m_nFpsDenum / m_nFpsNum);
+ vih->hdr.AvgTimePerFrame = m_rtAvgTimePerFrame;
+ }
+ vih->hdr.dwPictAspectRatioX = (p[14]<<16)|(p[15]<<8)|p[16];
+ vih->hdr.dwPictAspectRatioY = (p[17]<<16)|(p[18]<<8)|p[19];
+
+ m_KfgShift = (((p[40]<<8)+p[41]) &0x3E0) >> 5;
+ m_nIndexOffset = TH_VERSION_CHECK(p[7],p[8],p[9],3,2,1);
+
+ if (m_KfgShift == 0) m_KfgShift = 6; // Is it really default value ?
+
+ mt.bFixedSizeSamples = 0;
+ m_mts.Add(mt);
}
HRESULT COggTheoraOutputPin::UnpackInitPage(OggPage& page)
{
- HRESULT hr = __super::UnpackPage(page);
-
- while(m_packets.GetCount())
- {
- Packet* p = m_packets.GetHead();
-
- CMediaType& mt = m_mts[0];
- int size = p->GetCount();
- ASSERT(size <= 0xffff);
- MPEG2VIDEOINFO* vih = (MPEG2VIDEOINFO*)mt.ReallocFormatBuffer(
- FIELD_OFFSET(MPEG2VIDEOINFO, dwSequenceHeader) +
- ((MPEG2VIDEOINFO*)mt.Format())->cbSequenceHeader +
- 2 + size);
- *(WORD*)((BYTE*)vih->dwSequenceHeader + vih->cbSequenceHeader) = (size >> 8) | (size << 8);
- memcpy((BYTE*)vih->dwSequenceHeader + vih->cbSequenceHeader + 2, p->GetData(), size);
- vih->cbSequenceHeader += 2 + size;
-
- m_initpackets.AddTail(m_packets.RemoveHead());
- }
-
- return hr;
+ HRESULT hr = __super::UnpackPage(page);
+
+ while(m_packets.GetCount())
+ {
+ Packet* p = m_packets.GetHead();
+
+ CMediaType& mt = m_mts[0];
+ int size = p->GetCount();
+ ASSERT(size <= 0xffff);
+ MPEG2VIDEOINFO* vih = (MPEG2VIDEOINFO*)mt.ReallocFormatBuffer(
+ FIELD_OFFSET(MPEG2VIDEOINFO, dwSequenceHeader) +
+ ((MPEG2VIDEOINFO*)mt.Format())->cbSequenceHeader +
+ 2 + size);
+ *(WORD*)((BYTE*)vih->dwSequenceHeader + vih->cbSequenceHeader) = (size>>8)|(size<<8);
+ memcpy((BYTE*)vih->dwSequenceHeader + vih->cbSequenceHeader + 2, p->GetData(), size);
+ vih->cbSequenceHeader += 2 + size;
+
+ m_initpackets.AddTail(m_packets.RemoveHead());
+ }
+
+ return hr;
}
REFERENCE_TIME COggTheoraOutputPin::GetRefTime(__int64 granule_position)
@@ -1315,28 +1263,28 @@ REFERENCE_TIME COggTheoraOutputPin::GetRefTime(__int64 granule_position)
LONGLONG iframe;
LONGLONG pframe;
- iframe = granule_position >> m_KfgShift;
- pframe = granule_position - (iframe << m_KfgShift);
+ iframe=granule_position>>m_KfgShift;
+ pframe=granule_position-(iframe<<m_KfgShift);
/*3.2.0 streams store the frame index in the granule position.
3.2.1 and later store the frame count.
We return the index, so adjust the value if we have a 3.2.1 or later
stream.*/
- REFERENCE_TIME rt = 0;
- rt = (iframe + pframe - m_nIndexOffset) * m_rtAvgTimePerFrame;
- return rt;
+ REFERENCE_TIME rt = 0;
+ rt = (iframe+pframe-m_nIndexOffset) * m_rtAvgTimePerFrame;
+ return rt;
}
HRESULT COggTheoraOutputPin::UnpackPacket(CAutoPtr<OggPacket>& p, BYTE* pData, int len)
{
- p->bSyncPoint = len > 0 ? !(*pData & 0x40) : TRUE;
- p->rtStart = m_rtLast;
- p->rtStop = m_rtLast + 1;
- p->SetData(pData, len);
+ p->bSyncPoint = len > 0 ? !(*pData & 0x40) : TRUE;
+ p->rtStart = m_rtLast;
+ p->rtStop = m_rtLast+1;
+ p->SetData(pData, len);
- if(!(*pData & 0x80) && m_mt.majortype == MEDIATYPE_Video)
- p->rtStop = p->rtStart + ((MPEG2VIDEOINFO*)m_mt.Format())->hdr.AvgTimePerFrame;
+ if(!(*pData & 0x80) && m_mt.majortype == MEDIATYPE_Video)
+ p->rtStop = p->rtStart + ((MPEG2VIDEOINFO*)m_mt.Format())->hdr.AvgTimePerFrame;
- return S_OK;
+ return S_OK;
}
diff --git a/src/filters/parser/OggSplitter/OggSplitter.h b/src/filters/parser/OggSplitter/OggSplitter.h
index 2a27b24fb..b033f76bb 100644
--- a/src/filters/parser/OggSplitter/OggSplitter.h
+++ b/src/filters/parser/OggSplitter/OggSplitter.h
@@ -1,4 +1,4 @@
-/*
+/*
* Copyright (C) 2003-2006 Gabest
* http://www.gabest.org
*
@@ -6,15 +6,15 @@
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2, or (at your option)
* any later version.
- *
+ *
* This Program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with GNU Make; see the file COPYING. If not, write to
- * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
+ * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
* http://www.gnu.org/copyleft/gpl.html
*
*/
@@ -29,183 +29,168 @@
class OggPacket : public Packet
{
public:
- OggPacket()
- {
- fSkip = false;
- }
- bool fSkip;
+ OggPacket() {fSkip = false;}
+ bool fSkip;
};
class COggSplitterOutputPin : public CBaseSplitterOutputPin
{
- class CComment
- {
- public:
- CStringW m_key, m_value;
- CComment(CStringW key, CStringW value) : m_key(key), m_value(value)
- {
- m_key.MakeUpper();
- }
- };
-
- CAutoPtrList<CComment> m_pComments;
+ class CComment
+ {
+ public:
+ CStringW m_key, m_value;
+ CComment(CStringW key, CStringW value) : m_key(key), m_value(value) {m_key.MakeUpper();}
+ };
+
+ CAutoPtrList<CComment> m_pComments;
protected:
- CCritSec m_csPackets;
- CAutoPtrList<OggPacket> m_packets;
- CAutoPtr<OggPacket> m_lastpacket;
- int m_lastseqnum;
- REFERENCE_TIME m_rtLast;
- bool m_fSkip;
+ CCritSec m_csPackets;
+ CAutoPtrList<OggPacket> m_packets;
+ CAutoPtr<OggPacket> m_lastpacket;
+ int m_lastseqnum;
+ REFERENCE_TIME m_rtLast;
+ bool m_fSkip;
- void ResetState(DWORD seqnum = -1);
+ void ResetState(DWORD seqnum = -1);
public:
- COggSplitterOutputPin(LPCWSTR pName, CBaseFilter* pFilter, CCritSec* pLock, HRESULT* phr);
-
- void AddComment(BYTE* p, int len);
- CStringW GetComment(CStringW key);
+ COggSplitterOutputPin(LPCWSTR pName, CBaseFilter* pFilter, CCritSec* pLock, HRESULT* phr);
- HRESULT UnpackPage(OggPage& page);
- virtual HRESULT UnpackPacket(CAutoPtr<OggPacket>& p, BYTE* pData, int len) = 0;
- virtual REFERENCE_TIME GetRefTime(__int64 granule_position) = 0;
- CAutoPtr<OggPacket> GetPacket();
+ void AddComment(BYTE* p, int len);
+ CStringW GetComment(CStringW key);
- HRESULT DeliverEndFlush();
+ HRESULT UnpackPage(OggPage& page);
+ virtual HRESULT UnpackPacket(CAutoPtr<OggPacket>& p, BYTE* pData, int len) = 0;
+ virtual REFERENCE_TIME GetRefTime(__int64 granule_position) = 0;
+ CAutoPtr<OggPacket> GetPacket();
+
+ HRESULT DeliverEndFlush();
HRESULT DeliverNewSegment(REFERENCE_TIME tStart, REFERENCE_TIME tStop, double dRate);
};
class COggVorbisOutputPin : public COggSplitterOutputPin
{
- CAutoPtrList<OggPacket> m_initpackets;
+ CAutoPtrList<OggPacket> m_initpackets;
- DWORD m_audio_sample_rate;
- DWORD m_blocksize[2], m_lastblocksize;
- CAtlArray<bool> m_blockflags;
+ DWORD m_audio_sample_rate;
+ DWORD m_blocksize[2], m_lastblocksize;
+ CAtlArray<bool> m_blockflags;
- virtual HRESULT UnpackPacket(CAutoPtr<OggPacket>& p, BYTE* pData, int len);
- virtual REFERENCE_TIME GetRefTime(__int64 granule_position);
+ virtual HRESULT UnpackPacket(CAutoPtr<OggPacket>& p, BYTE* pData, int len);
+ virtual REFERENCE_TIME GetRefTime(__int64 granule_position);
- HRESULT DeliverPacket(CAutoPtr<OggPacket> p);
+ HRESULT DeliverPacket(CAutoPtr<OggPacket> p);
HRESULT DeliverNewSegment(REFERENCE_TIME tStart, REFERENCE_TIME tStop, double dRate);
public:
- COggVorbisOutputPin(OggVorbisIdHeader* h, LPCWSTR pName, CBaseFilter* pFilter, CCritSec* pLock, HRESULT* phr);
+ COggVorbisOutputPin(OggVorbisIdHeader* h, LPCWSTR pName, CBaseFilter* pFilter, CCritSec* pLock, HRESULT* phr);
- HRESULT UnpackInitPage(OggPage& page);
- bool IsInitialized()
- {
- return m_initpackets.GetCount() >= 3;
- }
+ HRESULT UnpackInitPage(OggPage& page);
+ bool IsInitialized() {return m_initpackets.GetCount() >= 3;}
};
class COggFlacOutputPin : public COggSplitterOutputPin
{
- CAutoPtrList<OggPacket> m_initpackets;
+ CAutoPtrList<OggPacket> m_initpackets;
- int m_nSamplesPerSec;
- int m_nChannels;
- WORD m_wBitsPerSample;
- int m_nAvgBytesPerSec;
+ int m_nSamplesPerSec;
+ int m_nChannels;
+ WORD m_wBitsPerSample;
+ int m_nAvgBytesPerSec;
- DWORD m_blocksize[2], m_lastblocksize;
- CAtlArray<bool> m_blockflags;
+ DWORD m_blocksize[2], m_lastblocksize;
+ CAtlArray<bool> m_blockflags;
- virtual HRESULT UnpackPacket(CAutoPtr<OggPacket>& p, BYTE* pData, int len);
- virtual REFERENCE_TIME GetRefTime(__int64 granule_position);
+ virtual HRESULT UnpackPacket(CAutoPtr<OggPacket>& p, BYTE* pData, int len);
+ virtual REFERENCE_TIME GetRefTime(__int64 granule_position);
- HRESULT DeliverPacket(CAutoPtr<OggPacket> p);
+ HRESULT DeliverPacket(CAutoPtr<OggPacket> p);
HRESULT DeliverNewSegment(REFERENCE_TIME tStart, REFERENCE_TIME tStop, double dRate);
public:
- COggFlacOutputPin(BYTE* h, int nCount, LPCWSTR pName, CBaseFilter* pFilter, CCritSec* pLock, HRESULT* phr);
+ COggFlacOutputPin(BYTE* h, int nCount, LPCWSTR pName, CBaseFilter* pFilter, CCritSec* pLock, HRESULT* phr);
- bool IsInitialized()
- {
- return m_initpackets.GetCount() >= 3;
- }
+ bool IsInitialized() {return m_initpackets.GetCount() >= 3;}
};
class COggDirectShowOutputPin : public COggSplitterOutputPin
{
- virtual HRESULT UnpackPacket(CAutoPtr<OggPacket>& p, BYTE* pData, int len);
- virtual REFERENCE_TIME GetRefTime(__int64 granule_position);
+ virtual HRESULT UnpackPacket(CAutoPtr<OggPacket>& p, BYTE* pData, int len);
+ virtual REFERENCE_TIME GetRefTime(__int64 granule_position);
public:
- COggDirectShowOutputPin(AM_MEDIA_TYPE* pmt, LPCWSTR pName, CBaseFilter* pFilter, CCritSec* pLock, HRESULT* phr);
+ COggDirectShowOutputPin(AM_MEDIA_TYPE* pmt, LPCWSTR pName, CBaseFilter* pFilter, CCritSec* pLock, HRESULT* phr);
};
class COggStreamOutputPin : public COggSplitterOutputPin
{
- __int64 m_time_unit, m_samples_per_unit;
- DWORD m_default_len;
+ __int64 m_time_unit, m_samples_per_unit;
+ DWORD m_default_len;
- virtual HRESULT UnpackPacket(CAutoPtr<OggPacket>& p, BYTE* pData, int len);
- virtual REFERENCE_TIME GetRefTime(__int64 granule_position);
+ virtual HRESULT UnpackPacket(CAutoPtr<OggPacket>& p, BYTE* pData, int len);
+ virtual REFERENCE_TIME GetRefTime(__int64 granule_position);
public:
- COggStreamOutputPin(OggStreamHeader* h, LPCWSTR pName, CBaseFilter* pFilter, CCritSec* pLock, HRESULT* phr);
+ COggStreamOutputPin(OggStreamHeader* h, LPCWSTR pName, CBaseFilter* pFilter, CCritSec* pLock, HRESULT* phr);
};
class COggVideoOutputPin : public COggStreamOutputPin
{
public:
- COggVideoOutputPin(OggStreamHeader* h, LPCWSTR pName, CBaseFilter* pFilter, CCritSec* pLock, HRESULT* phr);
+ COggVideoOutputPin(OggStreamHeader* h, LPCWSTR pName, CBaseFilter* pFilter, CCritSec* pLock, HRESULT* phr);
};
class COggAudioOutputPin : public COggStreamOutputPin
{
public:
- COggAudioOutputPin(OggStreamHeader* h, LPCWSTR pName, CBaseFilter* pFilter, CCritSec* pLock, HRESULT* phr);
+ COggAudioOutputPin(OggStreamHeader* h, LPCWSTR pName, CBaseFilter* pFilter, CCritSec* pLock, HRESULT* phr);
};
class COggTextOutputPin : public COggStreamOutputPin
{
public:
- COggTextOutputPin(OggStreamHeader* h, LPCWSTR pName, CBaseFilter* pFilter, CCritSec* pLock, HRESULT* phr);
+ COggTextOutputPin(OggStreamHeader* h, LPCWSTR pName, CBaseFilter* pFilter, CCritSec* pLock, HRESULT* phr);
};
class COggTheoraOutputPin : public COggSplitterOutputPin
{
- CAutoPtrList<OggPacket> m_initpackets;
- LONGLONG m_KfgShift;
- int m_nIndexOffset;
- int m_nFpsNum;
- int m_nFpsDenum;
- REFERENCE_TIME m_rtAvgTimePerFrame;
+ CAutoPtrList<OggPacket> m_initpackets;
+ LONGLONG m_KfgShift;
+ int m_nIndexOffset;
+ int m_nFpsNum;
+ int m_nFpsDenum;
+ REFERENCE_TIME m_rtAvgTimePerFrame;
- virtual HRESULT UnpackPacket(CAutoPtr<OggPacket>& p, BYTE* pData, int len);
- virtual REFERENCE_TIME GetRefTime(__int64 granule_position);
+ virtual HRESULT UnpackPacket(CAutoPtr<OggPacket>& p, BYTE* pData, int len);
+ virtual REFERENCE_TIME GetRefTime(__int64 granule_position);
public:
- COggTheoraOutputPin(BYTE* p, LPCWSTR pName, CBaseFilter* pFilter, CCritSec* pLock, HRESULT* phr);
+ COggTheoraOutputPin(BYTE* p, LPCWSTR pName, CBaseFilter* pFilter, CCritSec* pLock, HRESULT* phr);
- HRESULT UnpackInitPage(OggPage& page);
- bool IsInitialized()
- {
- return m_initpackets.GetCount() >= 3;
- }
+ HRESULT UnpackInitPage(OggPage& page);
+ bool IsInitialized() {return m_initpackets.GetCount() >= 3;}
};
[uuid("9FF48807-E133-40AA-826F-9B2959E5232D")]
class COggSplitterFilter : public CBaseSplitterFilter
{
protected:
- CAutoPtr<COggFile> m_pFile;
- HRESULT CreateOutputs(IAsyncReader* pAsyncReader);
+ CAutoPtr<COggFile> m_pFile;
+ HRESULT CreateOutputs(IAsyncReader* pAsyncReader);
- bool DemuxInit();
- void DemuxSeek(REFERENCE_TIME rt);
- bool DemuxLoop();
+ bool DemuxInit();
+ void DemuxSeek(REFERENCE_TIME rt);
+ bool DemuxLoop();
public:
- COggSplitterFilter(LPUNKNOWN pUnk, HRESULT* phr);
- virtual ~COggSplitterFilter();
+ COggSplitterFilter(LPUNKNOWN pUnk, HRESULT* phr);
+ virtual ~COggSplitterFilter();
};
[uuid("6D3688CE-3E9D-42F4-92CA-8A11119D25CD")]
class COggSourceFilter : public COggSplitterFilter
{
public:
- COggSourceFilter(LPUNKNOWN pUnk, HRESULT* phr);
+ COggSourceFilter(LPUNKNOWN pUnk, HRESULT* phr);
};
diff --git a/src/filters/parser/OggSplitter/resource.h b/src/filters/parser/OggSplitter/resource.h
index 0284bfbd3..3bf040c0b 100644
--- a/src/filters/parser/OggSplitter/resource.h
+++ b/src/filters/parser/OggSplitter/resource.h
@@ -3,7 +3,7 @@
// Used by OggSplitter.rc
// Next default values for new objects
-//
+//
#ifdef APSTUDIO_INVOKED
#ifndef APSTUDIO_READONLY_SYMBOLS
#define _APS_NEXT_RESOURCE_VALUE 101
diff --git a/src/filters/parser/OggSplitter/stdafx.cpp b/src/filters/parser/OggSplitter/stdafx.cpp
index 421a0e678..804db5e5a 100644
--- a/src/filters/parser/OggSplitter/stdafx.cpp
+++ b/src/filters/parser/OggSplitter/stdafx.cpp
@@ -1,4 +1,4 @@
-/*
+/*
* Copyright (C) 2003-2006 Gabest
* http://www.gabest.org
*
@@ -6,15 +6,15 @@
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2, or (at your option)
* any later version.
- *
+ *
* This Program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with GNU Make; see the file COPYING. If not, write to
- * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
+ * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
* http://www.gnu.org/copyleft/gpl.html
*
*/
diff --git a/src/filters/parser/OggSplitter/stdafx.h b/src/filters/parser/OggSplitter/stdafx.h
index 1f7c00018..0910f1e05 100644
--- a/src/filters/parser/OggSplitter/stdafx.h
+++ b/src/filters/parser/OggSplitter/stdafx.h
@@ -1,4 +1,4 @@
-/*
+/*
* Copyright (C) 2003-2006 Gabest
* http://www.gabest.org
*
@@ -6,15 +6,15 @@
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2, or (at your option)
* any later version.
- *
+ *
* This Program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with GNU Make; see the file COPYING. If not, write to
- * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
+ * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
* http://www.gnu.org/copyleft/gpl.html
*
*/
diff --git a/src/filters/parser/RealMediaSplitter/RealMediaSplitter.cpp b/src/filters/parser/RealMediaSplitter/RealMediaSplitter.cpp
index 306fc133b..e133b8435 100644
--- a/src/filters/parser/RealMediaSplitter/RealMediaSplitter.cpp
+++ b/src/filters/parser/RealMediaSplitter/RealMediaSplitter.cpp
@@ -1,4 +1,4 @@
-/*
+/*
* Copyright (C) 2003-2006 Gabest
* http://www.gabest.org
*
@@ -6,15 +6,15 @@
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2, or (at your option)
* any later version.
- *
+ *
* This Program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with GNU Make; see the file COPYING. If not, write to
- * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
+ * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
* http://www.gnu.org/copyleft/gpl.html
*
*/
@@ -38,49 +38,45 @@
template<typename T>
static void bswap(T& var)
{
- BYTE* s = (BYTE*)&var;
- for(BYTE* d = s + sizeof(var) - 1; s < d; s++, d--)
- *s ^= *d, *d ^= *s, *s ^= *d;
+ BYTE* s = (BYTE*)&var;
+ for(BYTE* d = s + sizeof(var)-1; s < d; s++, d--)
+ *s ^= *d, *d ^= *s, *s ^= *d;
}
void rvinfo::bswap()
{
- ::bswap(dwSize);
- ::bswap(w);
- ::bswap(h);
- ::bswap(bpp);
- ::bswap(unk1);
- ::bswap(fps);
- ::bswap(type1);
- ::bswap(type2);
+ ::bswap(dwSize);
+ ::bswap(w); ::bswap(h); ::bswap(bpp);
+ ::bswap(unk1); ::bswap(fps);
+ ::bswap(type1); ::bswap(type2);
}
void rainfo::bswap()
{
- ::bswap(version1);
- ::bswap(version2);
- ::bswap(header_size);
- ::bswap(flavor);
- ::bswap(coded_frame_size);
- ::bswap(sub_packet_h);
- ::bswap(frame_size);
- ::bswap(sub_packet_size);
+ ::bswap(version1);
+ ::bswap(version2);
+ ::bswap(header_size);
+ ::bswap(flavor);
+ ::bswap(coded_frame_size);
+ ::bswap(sub_packet_h);
+ ::bswap(frame_size);
+ ::bswap(sub_packet_size);
}
void rainfo4::bswap()
{
- __super::bswap();
- ::bswap(sample_rate);
- ::bswap(sample_size);
- ::bswap(channels);
+ __super::bswap();
+ ::bswap(sample_rate);
+ ::bswap(sample_size);
+ ::bswap(channels);
}
void rainfo5::bswap()
{
- __super::bswap();
- ::bswap(sample_rate);
- ::bswap(sample_size);
- ::bswap(channels);
+ __super::bswap();
+ ::bswap(sample_rate);
+ ::bswap(sample_size);
+ ::bswap(channels);
}
using namespace RMFF;
@@ -89,7 +85,7 @@ using namespace RMFF;
const AMOVIESETUP_MEDIATYPE sudPinTypesIn[] =
{
- {&MEDIATYPE_Stream, &MEDIASUBTYPE_NULL},
+ {&MEDIATYPE_Stream, &MEDIASUBTYPE_NULL},
};
const AMOVIESETUP_PIN sudpPins[] =
@@ -100,15 +96,15 @@ const AMOVIESETUP_PIN sudpPins[] =
const AMOVIESETUP_MEDIATYPE sudPinTypesIn2[] =
{
- {&MEDIATYPE_Video, &MEDIASUBTYPE_RV20},
- {&MEDIATYPE_Video, &MEDIASUBTYPE_RV30},
- {&MEDIATYPE_Video, &MEDIASUBTYPE_RV40},
- {&MEDIATYPE_Video, &MEDIASUBTYPE_RV41},
+ {&MEDIATYPE_Video, &MEDIASUBTYPE_RV20},
+ {&MEDIATYPE_Video, &MEDIASUBTYPE_RV30},
+ {&MEDIATYPE_Video, &MEDIASUBTYPE_RV40},
+ {&MEDIATYPE_Video, &MEDIASUBTYPE_RV41},
};
const AMOVIESETUP_MEDIATYPE sudPinTypesOut2[] =
{
- {&MEDIATYPE_Video, &MEDIASUBTYPE_NULL},
+ {&MEDIATYPE_Video, &MEDIASUBTYPE_NULL},
};
const AMOVIESETUP_PIN sudpPins2[] =
@@ -119,20 +115,20 @@ const AMOVIESETUP_PIN sudpPins2[] =
const AMOVIESETUP_MEDIATYPE sudPinTypesIn3[] =
{
- {&MEDIATYPE_Audio, &MEDIASUBTYPE_14_4},
- {&MEDIATYPE_Audio, &MEDIASUBTYPE_28_8},
- {&MEDIATYPE_Audio, &MEDIASUBTYPE_ATRC},
- {&MEDIATYPE_Audio, &MEDIASUBTYPE_COOK},
- {&MEDIATYPE_Audio, &MEDIASUBTYPE_DNET},
- {&MEDIATYPE_Audio, &MEDIASUBTYPE_SIPR},
- {&MEDIATYPE_Audio, &MEDIASUBTYPE_AAC},
- {&MEDIATYPE_Audio, &MEDIASUBTYPE_RAAC},
- {&MEDIATYPE_Audio, &MEDIASUBTYPE_RACP},
+ {&MEDIATYPE_Audio, &MEDIASUBTYPE_14_4},
+ {&MEDIATYPE_Audio, &MEDIASUBTYPE_28_8},
+ {&MEDIATYPE_Audio, &MEDIASUBTYPE_ATRC},
+ {&MEDIATYPE_Audio, &MEDIASUBTYPE_COOK},
+ {&MEDIATYPE_Audio, &MEDIASUBTYPE_DNET},
+ {&MEDIATYPE_Audio, &MEDIASUBTYPE_SIPR},
+ {&MEDIATYPE_Audio, &MEDIASUBTYPE_AAC},
+ {&MEDIATYPE_Audio, &MEDIASUBTYPE_RAAC},
+ {&MEDIATYPE_Audio, &MEDIASUBTYPE_RACP},
};
const AMOVIESETUP_MEDIATYPE sudPinTypesOut3[] =
{
- {&MEDIATYPE_Audio, &MEDIASUBTYPE_PCM},
+ {&MEDIATYPE_Audio, &MEDIASUBTYPE_PCM},
};
const AMOVIESETUP_PIN sudpPins3[] =
@@ -143,16 +139,16 @@ const AMOVIESETUP_PIN sudpPins3[] =
const AMOVIESETUP_FILTER sudFilter[] =
{
- {&__uuidof(CRealMediaSplitterFilter), L"MPC - RealMedia Splitter", MERIT_NORMAL, countof(sudpPins), sudpPins, CLSID_LegacyAmFilterCategory},
- {&__uuidof(CRealMediaSourceFilter), L"MPC - RealMedia Source", MERIT_NORMAL, 0, NULL, CLSID_LegacyAmFilterCategory},
- {&__uuidof(CRealVideoDecoder), L"MPC - RealVideo Decoder", MERIT_NORMAL, countof(sudpPins2), sudpPins2, CLSID_LegacyAmFilterCategory},
- {&__uuidof(CRealAudioDecoder), L"MPC - RealAudio Decoder", MERIT_NORMAL, countof(sudpPins3), sudpPins3, CLSID_LegacyAmFilterCategory},
+ {&__uuidof(CRealMediaSplitterFilter), L"MPC - RealMedia Splitter", MERIT_NORMAL, countof(sudpPins), sudpPins, CLSID_LegacyAmFilterCategory},
+ {&__uuidof(CRealMediaSourceFilter), L"MPC - RealMedia Source", MERIT_NORMAL, 0, NULL, CLSID_LegacyAmFilterCategory},
+ {&__uuidof(CRealVideoDecoder), L"MPC - RealVideo Decoder", MERIT_NORMAL, countof(sudpPins2), sudpPins2, CLSID_LegacyAmFilterCategory},
+ {&__uuidof(CRealAudioDecoder), L"MPC - RealAudio Decoder", MERIT_NORMAL, countof(sudpPins3), sudpPins3, CLSID_LegacyAmFilterCategory},
};
CFactoryTemplate g_Templates[] =
{
- {sudFilter[0].strName, sudFilter[0].clsID, CreateInstance<CRealMediaSplitterFilter>, NULL, &sudFilter[0]},
- {sudFilter[1].strName, sudFilter[1].clsID, CreateInstance<CRealMediaSourceFilter>, NULL, &sudFilter[1]},
+ {sudFilter[0].strName, sudFilter[0].clsID, CreateInstance<CRealMediaSplitterFilter>, NULL, &sudFilter[0]},
+ {sudFilter[1].strName, sudFilter[1].clsID, CreateInstance<CRealMediaSourceFilter>, NULL, &sudFilter[1]},
{sudFilter[2].strName, sudFilter[2].clsID, CreateInstance<CRealVideoDecoder>, NULL, &sudFilter[2]},
{sudFilter[3].strName, sudFilter[3].clsID, CreateInstance<CRealAudioDecoder>, NULL, &sudFilter[3]},
};
@@ -161,16 +157,16 @@ int g_cTemplates = countof(g_Templates);
STDAPI DllRegisterServer()
{
- RegisterSourceFilter(CLSID_AsyncReader, MEDIASUBTYPE_RealMedia, _T("0,4,,2E524D46"), _T(".rm"), _T(".rmvb"), _T(".ram"), NULL);
+ RegisterSourceFilter(CLSID_AsyncReader, MEDIASUBTYPE_RealMedia, _T("0,4,,2E524D46"), _T(".rm"), _T(".rmvb"), _T(".ram"), NULL);
- return AMovieDllRegisterServer2(TRUE);
+ return AMovieDllRegisterServer2(TRUE);
}
STDAPI DllUnregisterServer()
{
- UnRegisterSourceFilter(MEDIASUBTYPE_RealMedia);
+ UnRegisterSourceFilter(MEDIASUBTYPE_RealMedia);
- return AMovieDllRegisterServer2(FALSE);
+ return AMovieDllRegisterServer2(FALSE);
}
#include "../../FilterApp.h"
@@ -184,7 +180,7 @@ CFilterApp theApp;
//
CRealMediaSplitterFilter::CRealMediaSplitterFilter(LPUNKNOWN pUnk, HRESULT* phr)
- : CBaseSplitterFilter(NAME("CRealMediaSplitterFilter"), pUnk, phr, __uuidof(this))
+ : CBaseSplitterFilter(NAME("CRealMediaSplitterFilter"), pUnk, phr, __uuidof(this))
{
}
@@ -194,592 +190,549 @@ CRealMediaSplitterFilter::~CRealMediaSplitterFilter()
HRESULT CRealMediaSplitterFilter::CreateOutputs(IAsyncReader* pAsyncReader)
{
- CheckPointer(pAsyncReader, E_POINTER);
-
- {
- DWORD dw;
- if(FAILED(pAsyncReader->SyncRead(0, 4, (BYTE*)&dw)) || dw != 'FMR.')
- return E_FAIL;
- }
-
- HRESULT hr = E_FAIL;
-
- m_pFile.Free();
-
- m_pFile.Attach(DNew CRMFile(pAsyncReader, hr));
- if(!m_pFile) return E_OUTOFMEMORY;
- if(FAILED(hr))
- {
- m_pFile.Free();
- return hr;
- }
-
- m_rtNewStart = m_rtCurrent = 0;
- m_rtNewStop = m_rtStop = 0;
-
- m_rtStop = 10000i64 * m_pFile->m_p.tDuration;
-
- POSITION pos = m_pFile->m_mps.GetHeadPosition();
- while(pos)
- {
- MediaProperies* pmp = m_pFile->m_mps.GetNext(pos);
-
- CStringW name;
- name.Format(L"Output %02d", pmp->stream);
- if(!pmp->name.IsEmpty()) name += L" (" + CStringW(pmp->name) + L")";
-
- CAtlArray<CMediaType> mts;
-
- CMediaType mt;
- mt.SetSampleSize(max(pmp->maxPacketSize * 16/**/, 1));
-
- if(pmp->mime == "video/x-pn-realvideo")
- {
- mt.majortype = MEDIATYPE_Video;
- mt.formattype = FORMAT_VideoInfo;
-
- VIDEOINFOHEADER* pvih = (VIDEOINFOHEADER*)mt.AllocFormatBuffer(sizeof(VIDEOINFOHEADER) + pmp->typeSpecData.GetCount());
- memset(mt.Format(), 0, mt.FormatLength());
- memcpy(pvih + 1, pmp->typeSpecData.GetData(), pmp->typeSpecData.GetCount());
-
- rvinfo rvi = *(rvinfo*)pmp->typeSpecData.GetData();
- rvi.bswap();
-
- ASSERT(rvi.dwSize >= FIELD_OFFSET(rvinfo, morewh));
- ASSERT(rvi.fcc1 == 'ODIV');
-
- mt.subtype = FOURCCMap(rvi.fcc2);
- if(rvi.fps > 0x10000) pvih->AvgTimePerFrame = REFERENCE_TIME(10000000i64 / ((float)rvi.fps / 0x10000));
- pvih->dwBitRate = pmp->avgBitRate;
- pvih->bmiHeader.biSize = sizeof(pvih->bmiHeader);
- pvih->bmiHeader.biWidth = rvi.w;
- pvih->bmiHeader.biHeight = rvi.h;
- pvih->bmiHeader.biPlanes = 3;
- pvih->bmiHeader.biBitCount = rvi.bpp;
- pvih->bmiHeader.biCompression = rvi.fcc2;
- pvih->bmiHeader.biSizeImage = rvi.w * rvi.h * 3 / 2;
-
- mts.Add(mt);
-
- if(pmp->width > 0 && pmp->height > 0)
- {
- BITMAPINFOHEADER bmi = pvih->bmiHeader;
- mt.formattype = FORMAT_VideoInfo2;
- VIDEOINFOHEADER2* pvih2 = (VIDEOINFOHEADER2*)mt.ReallocFormatBuffer(sizeof(VIDEOINFOHEADER2) + pmp->typeSpecData.GetCount());
- memset(mt.Format() + FIELD_OFFSET(VIDEOINFOHEADER2, dwInterlaceFlags), 0, mt.FormatLength() - FIELD_OFFSET(VIDEOINFOHEADER2, dwInterlaceFlags));
- memcpy(pvih2 + 1, pmp->typeSpecData.GetData(), pmp->typeSpecData.GetCount());
- pvih2->bmiHeader = bmi;
- pvih2->bmiHeader.biWidth = (DWORD)pmp->width;
- pvih2->bmiHeader.biHeight = (DWORD)pmp->height;
- pvih2->dwPictAspectRatioX = rvi.w;
- pvih2->dwPictAspectRatioY = rvi.h;
-
- mts.InsertAt(0, mt);
- }
- }
- else if(pmp->mime == "audio/x-pn-realaudio")
- {
- mt.majortype = MEDIATYPE_Audio;
- mt.formattype = FORMAT_WaveFormatEx;
- mt.bTemporalCompression = 1;
-
- WAVEFORMATEX* pwfe = (WAVEFORMATEX*)mt.AllocFormatBuffer(sizeof(WAVEFORMATEX) + pmp->typeSpecData.GetCount());
- memset(mt.Format(), 0, mt.FormatLength());
- memcpy(pwfe + 1, pmp->typeSpecData.GetData(), pmp->typeSpecData.GetCount());
-
- union
- {
- DWORD fcc;
- char fccstr[5];
- };
-
- fcc = 0;
- fccstr[4] = 0;
-
- BYTE* fmt = pmp->typeSpecData.GetData();
- for(int i = 0; i < pmp->typeSpecData.GetCount() - 4; i++, fmt++)
- {
- if(fmt[0] == '.' || fmt[1] == 'r' || fmt[2] == 'a')
- break;
- }
-
- rainfo rai = *(rainfo*)fmt;
- rai.bswap();
-
- BYTE* extra = NULL;
-
- if(rai.version2 == 4)
- {
- rainfo4 rai4 = *(rainfo4*)fmt;
- rai4.bswap();
- pwfe->nChannels = rai4.channels;
- pwfe->wBitsPerSample = rai4.sample_size;
- pwfe->nSamplesPerSec = rai4.sample_rate;
- pwfe->nBlockAlign = rai4.frame_size;
- BYTE* p = (BYTE*)((rainfo4*)fmt + 1);
- int len = *p++;
- p += len;
- len = *p++;
- ASSERT(len == 4);
- if(len == 4)
- fcc = MAKEFOURCC(p[0], p[1], p[2], p[3]);
- extra = p + len + 3;
- }
- else if(rai.version2 == 5)
- {
- rainfo5 rai5 = *(rainfo5*)fmt;
- rai5.bswap();
- pwfe->nChannels = rai5.channels;
- pwfe->wBitsPerSample = rai5.sample_size;
- pwfe->nSamplesPerSec = rai5.sample_rate;
- pwfe->nBlockAlign = rai5.frame_size;
- fcc = rai5.fourcc3;
- extra = fmt + sizeof(rainfo5) + 4;
- }
- else
- {
- continue;
- }
-
- _strupr(fccstr);
-
- mt.subtype = FOURCCMap(fcc);
-
- bswap(fcc);
-
- switch(fcc)
- {
- case '14_4':
- pwfe->wFormatTag = WAVE_FORMAT_14_4;
- break;
- case '28_8':
- pwfe->wFormatTag = WAVE_FORMAT_28_8;
- break;
- case 'ATRC':
- pwfe->wFormatTag = WAVE_FORMAT_ATRC;
- break;
- case 'COOK':
- pwfe->wFormatTag = WAVE_FORMAT_COOK;
- break;
- case 'DNET':
- pwfe->wFormatTag = WAVE_FORMAT_DNET;
- break;
- case 'SIPR':
- pwfe->wFormatTag = WAVE_FORMAT_SIPR;
- break;
- case 'RAAC':
- pwfe->wFormatTag = WAVE_FORMAT_RAAC;
- break;
- case 'RACP':
- pwfe->wFormatTag = WAVE_FORMAT_RACP;
- break;
- }
-
- if(pwfe->wFormatTag)
- {
- mts.Add(mt);
-
- if(fcc == 'DNET')
- {
- mt.subtype = FOURCCMap(pwfe->wFormatTag = WAVE_FORMAT_DOLBY_AC3);
- mts.InsertAt(0, mt);
- }
- else if(fcc == 'RAAC' || fcc == 'RACP')
- {
- mt.subtype = FOURCCMap(pwfe->wFormatTag = WAVE_FORMAT_AAC);
- int extralen = *(DWORD*)extra;
- extra += 4;
- ::bswap(extralen);
- ASSERT(*extra == 2); // always 2? why? what does it mean?
- if(*extra == 2)
- {
- extra++;
- extralen--;
- WAVEFORMATEX* pwfe = (WAVEFORMATEX*)mt.ReallocFormatBuffer(sizeof(WAVEFORMATEX) + extralen);
- pwfe->cbSize = extralen;
- memcpy(pwfe + 1, extra, extralen);
- }
- else
- {
- WAVEFORMATEX* pwfe = (WAVEFORMATEX*)mt.ReallocFormatBuffer(sizeof(WAVEFORMATEX) + 5);
- pwfe->cbSize = MakeAACInitData((BYTE*)(pwfe + 1), 0, pwfe->nSamplesPerSec, pwfe->nChannels);
- }
- mts.InsertAt(0, mt);
- }
- }
- }
- else if(pmp->mime == "logical-fileinfo")
- {
- CAtlMap<CStringA, CStringA, CStringElementTraits<CStringA> > lfi;
- CStringA key, value;
-
- BYTE* p = pmp->typeSpecData.GetData();
- BYTE* end = p + pmp->typeSpecData.GetCount();
- p += 8;
-
- DWORD cnt = p <= end - 4 ? *(DWORD*)p : 0;
- bswap(cnt);
- p += 4;
-
- if(cnt > 0xffff) // different format?
- {
- p += 2;
- cnt = p <= end - 4 ? *(DWORD*)p : 0;
- bswap(cnt);
- p += 4;
- }
+ CheckPointer(pAsyncReader, E_POINTER);
+
+ {
+ DWORD dw;
+ if(FAILED(pAsyncReader->SyncRead(0, 4, (BYTE*)&dw)) || dw != 'FMR.')
+ return E_FAIL;
+ }
+
+ HRESULT hr = E_FAIL;
+
+ m_pFile.Free();
+
+ m_pFile.Attach(DNew CRMFile(pAsyncReader, hr));
+ if(!m_pFile) return E_OUTOFMEMORY;
+ if(FAILED(hr)) {m_pFile.Free(); return hr;}
+
+ m_rtNewStart = m_rtCurrent = 0;
+ m_rtNewStop = m_rtStop = 0;
+
+ m_rtStop = 10000i64*m_pFile->m_p.tDuration;
+
+ POSITION pos = m_pFile->m_mps.GetHeadPosition();
+ while(pos)
+ {
+ MediaProperies* pmp = m_pFile->m_mps.GetNext(pos);
+
+ CStringW name;
+ name.Format(L"Output %02d", pmp->stream);
+ if(!pmp->name.IsEmpty()) name += L" (" + CStringW(pmp->name) + L")";
+
+ CAtlArray<CMediaType> mts;
+
+ CMediaType mt;
+ mt.SetSampleSize(max(pmp->maxPacketSize*16/**/, 1));
+
+ if(pmp->mime == "video/x-pn-realvideo")
+ {
+ mt.majortype = MEDIATYPE_Video;
+ mt.formattype = FORMAT_VideoInfo;
+
+ VIDEOINFOHEADER* pvih = (VIDEOINFOHEADER*)mt.AllocFormatBuffer(sizeof(VIDEOINFOHEADER) + pmp->typeSpecData.GetCount());
+ memset(mt.Format(), 0, mt.FormatLength());
+ memcpy(pvih + 1, pmp->typeSpecData.GetData(), pmp->typeSpecData.GetCount());
+
+ rvinfo rvi = *(rvinfo*)pmp->typeSpecData.GetData();
+ rvi.bswap();
+
+ ASSERT(rvi.dwSize >= FIELD_OFFSET(rvinfo, morewh));
+ ASSERT(rvi.fcc1 == 'ODIV');
+
+ mt.subtype = FOURCCMap(rvi.fcc2);
+ if(rvi.fps > 0x10000) pvih->AvgTimePerFrame = REFERENCE_TIME(10000000i64 / ((float)rvi.fps/0x10000));
+ pvih->dwBitRate = pmp->avgBitRate;
+ pvih->bmiHeader.biSize = sizeof(pvih->bmiHeader);
+ pvih->bmiHeader.biWidth = rvi.w;
+ pvih->bmiHeader.biHeight = rvi.h;
+ pvih->bmiHeader.biPlanes = 3;
+ pvih->bmiHeader.biBitCount = rvi.bpp;
+ pvih->bmiHeader.biCompression = rvi.fcc2;
+ pvih->bmiHeader.biSizeImage = rvi.w*rvi.h*3/2;
+
+ mts.Add(mt);
+
+ if(pmp->width > 0 && pmp->height > 0)
+ {
+ BITMAPINFOHEADER bmi = pvih->bmiHeader;
+ mt.formattype = FORMAT_VideoInfo2;
+ VIDEOINFOHEADER2* pvih2 = (VIDEOINFOHEADER2*)mt.ReallocFormatBuffer(sizeof(VIDEOINFOHEADER2) + pmp->typeSpecData.GetCount());
+ memset(mt.Format() + FIELD_OFFSET(VIDEOINFOHEADER2, dwInterlaceFlags), 0, mt.FormatLength() - FIELD_OFFSET(VIDEOINFOHEADER2, dwInterlaceFlags));
+ memcpy(pvih2 + 1, pmp->typeSpecData.GetData(), pmp->typeSpecData.GetCount());
+ pvih2->bmiHeader = bmi;
+ pvih2->bmiHeader.biWidth = (DWORD)pmp->width;
+ pvih2->bmiHeader.biHeight = (DWORD)pmp->height;
+ pvih2->dwPictAspectRatioX = rvi.w;
+ pvih2->dwPictAspectRatioY = rvi.h;
+
+ mts.InsertAt(0, mt);
+ }
+ }
+ else if(pmp->mime == "audio/x-pn-realaudio")
+ {
+ mt.majortype = MEDIATYPE_Audio;
+ mt.formattype = FORMAT_WaveFormatEx;
+ mt.bTemporalCompression = 1;
+
+ WAVEFORMATEX* pwfe = (WAVEFORMATEX*)mt.AllocFormatBuffer(sizeof(WAVEFORMATEX) + pmp->typeSpecData.GetCount());
+ memset(mt.Format(), 0, mt.FormatLength());
+ memcpy(pwfe + 1, pmp->typeSpecData.GetData(), pmp->typeSpecData.GetCount());
+
+ union {
+ DWORD fcc;
+ char fccstr[5];
+ };
+
+ fcc = 0;
+ fccstr[4] = 0;
+
+ BYTE* fmt = pmp->typeSpecData.GetData();
+ for(int i = 0; i < pmp->typeSpecData.GetCount()-4; i++, fmt++)
+ {
+ if(fmt[0] == '.' || fmt[1] == 'r' || fmt[2] == 'a')
+ break;
+ }
+
+ rainfo rai = *(rainfo*)fmt;
+ rai.bswap();
+
+ BYTE* extra = NULL;
+
+ if(rai.version2 == 4)
+ {
+ rainfo4 rai4 = *(rainfo4*)fmt;
+ rai4.bswap();
+ pwfe->nChannels = rai4.channels;
+ pwfe->wBitsPerSample = rai4.sample_size;
+ pwfe->nSamplesPerSec = rai4.sample_rate;
+ pwfe->nBlockAlign = rai4.frame_size;
+ BYTE* p = (BYTE*)((rainfo4*)fmt+1);
+ int len = *p++; p += len; len = *p++; ASSERT(len == 4);
+ if(len == 4)
+ fcc = MAKEFOURCC(p[0],p[1],p[2],p[3]);
+ extra = p + len + 3;
+ }
+ else if(rai.version2 == 5)
+ {
+ rainfo5 rai5 = *(rainfo5*)fmt;
+ rai5.bswap();
+ pwfe->nChannels = rai5.channels;
+ pwfe->wBitsPerSample = rai5.sample_size;
+ pwfe->nSamplesPerSec = rai5.sample_rate;
+ pwfe->nBlockAlign = rai5.frame_size;
+ fcc = rai5.fourcc3;
+ extra = fmt + sizeof(rainfo5) + 4;
+ }
+ else
+ {
+ continue;
+ }
+
+ _strupr(fccstr);
+
+ mt.subtype = FOURCCMap(fcc);
+
+ bswap(fcc);
+
+ switch(fcc)
+ {
+ case '14_4': pwfe->wFormatTag = WAVE_FORMAT_14_4; break;
+ case '28_8': pwfe->wFormatTag = WAVE_FORMAT_28_8; break;
+ case 'ATRC': pwfe->wFormatTag = WAVE_FORMAT_ATRC; break;
+ case 'COOK': pwfe->wFormatTag = WAVE_FORMAT_COOK; break;
+ case 'DNET': pwfe->wFormatTag = WAVE_FORMAT_DNET; break;
+ case 'SIPR': pwfe->wFormatTag = WAVE_FORMAT_SIPR; break;
+ case 'RAAC': pwfe->wFormatTag = WAVE_FORMAT_RAAC; break;
+ case 'RACP': pwfe->wFormatTag = WAVE_FORMAT_RACP; break;
+ }
+
+ if(pwfe->wFormatTag)
+ {
+ mts.Add(mt);
+
+ if(fcc == 'DNET')
+ {
+ mt.subtype = FOURCCMap(pwfe->wFormatTag = WAVE_FORMAT_DOLBY_AC3);
+ mts.InsertAt(0, mt);
+ }
+ else if(fcc == 'RAAC' || fcc == 'RACP')
+ {
+ mt.subtype = FOURCCMap(pwfe->wFormatTag = WAVE_FORMAT_AAC);
+ int extralen = *(DWORD*)extra; extra += 4;
+ ::bswap(extralen);
+ ASSERT(*extra == 2); // always 2? why? what does it mean?
+ if(*extra == 2)
+ {
+ extra++; extralen--;
+ WAVEFORMATEX* pwfe = (WAVEFORMATEX*)mt.ReallocFormatBuffer(sizeof(WAVEFORMATEX) + extralen);
+ pwfe->cbSize = extralen;
+ memcpy(pwfe + 1, extra, extralen);
+ }
+ else
+ {
+ WAVEFORMATEX* pwfe = (WAVEFORMATEX*)mt.ReallocFormatBuffer(sizeof(WAVEFORMATEX) + 5);
+ pwfe->cbSize = MakeAACInitData((BYTE*)(pwfe+1), 0, pwfe->nSamplesPerSec, pwfe->nChannels);
+ }
+ mts.InsertAt(0, mt);
+ }
+ }
+ }
+ else if(pmp->mime == "logical-fileinfo")
+ {
+ CAtlMap<CStringA, CStringA, CStringElementTraits<CStringA> > lfi;
+ CStringA key, value;
+
+ BYTE* p = pmp->typeSpecData.GetData();
+ BYTE* end = p + pmp->typeSpecData.GetCount();
+ p += 8;
+
+ DWORD cnt = p <= end-4 ? *(DWORD*)p : 0; bswap(cnt); p += 4;
+
+ if(cnt > 0xffff) // different format?
+ {
+ p += 2;
+ cnt = p <= end-4 ? *(DWORD*)p : 0; bswap(cnt); p += 4;
+ }
+
+ while(p < end-4 && cnt-- > 0)
+ {
+ BYTE* base = p;
+ DWORD len = *(DWORD*)p; bswap(len); p += 4;
+ if(base + len > end) break;
+
+ p++;
+ WORD keylen = *(WORD*)p; bswap(keylen); p += 2;
+ memcpy(key.GetBufferSetLength(keylen), p, keylen);
+ p += keylen;
+
+ p+=4;
+ WORD valuelen = *(WORD*)p; bswap(valuelen); p += 2;
+ memcpy(value.GetBufferSetLength(valuelen), p, valuelen);
+ p += valuelen;
+
+ ASSERT(p == base + len);
+ p = base + len;
+
+ lfi[key] = value;
+ }
+
+ POSITION pos = lfi.GetStartPosition();
+ while(pos)
+ {
+ lfi.GetNextAssoc(pos, key, value);
+
+ int n;
+ if(key.Find("CHAPTER") == 0 && key.Find("TIME") == key.GetLength()-4
+ && (n = strtol(key.Mid(7), NULL, 10)) > 0)
+ {
+ int h, m, s, ms;
+ char c;
+ if(7 != sscanf(value, "%d%c%d%c%d%c%d", &h, &c, &m, &c, &s, &c, &ms))
+ continue;
+
+ key.Format("CHAPTER%02dNAME", n);
+ if(!lfi.Lookup(key, value) || value.IsEmpty())
+ value.Format("Chapter %d", n);
+
+ ChapAppend(
+ ((((REFERENCE_TIME)h*60+m)*60+s)*1000+ms)*10000,
+ CStringW(CString(value)));
+ }
+ }
+ }
+
+ if(mts.IsEmpty())
+ {
+ TRACE(_T("Unsupported RealMedia stream (%d): %s\n"), pmp->stream, CString(pmp->mime));
+ continue;
+ }
+
+ HRESULT hr;
+
+ CAutoPtr<CBaseSplitterOutputPin> pPinOut(DNew CRealMediaSplitterOutputPin(mts, name, this, this, &hr));
+ if(SUCCEEDED(AddOutputPin((DWORD)pmp->stream, pPinOut)))
+ {
+ if(!m_rtStop)
+ m_pFile->m_p.tDuration = max(m_pFile->m_p.tDuration, pmp->tDuration);
+ }
+ }
+
+ pos = m_pFile->m_subs.GetHeadPosition();
+ for(DWORD stream = 0; pos; stream++)
+ {
+ CRMFile::subtitle& s = m_pFile->m_subs.GetNext(pos);
+
+ CStringW name;
+ name.Format(L"Subtitle %02d", stream);
+ if(!s.name.IsEmpty()) name += L" (" + CStringW(CString(s.name)) + L")";
+
+ CMediaType mt;
+ mt.SetSampleSize(1);
+ mt.majortype = MEDIATYPE_Text;
+
+ CAtlArray<CMediaType> mts;
+ mts.Add(mt);
+
+ HRESULT hr;
+
+ CAutoPtr<CBaseSplitterOutputPin> pPinOut(DNew CRealMediaSplitterOutputPin(mts, name, this, this, &hr));
+ AddOutputPin((DWORD)~stream, pPinOut);
+ }
+
+ m_rtDuration = m_rtNewStop = m_rtStop = 10000i64*m_pFile->m_p.tDuration;
+
+ SetProperty(L"TITL", CStringW(m_pFile->m_cd.title));
+ SetProperty(L"AUTH", CStringW(m_pFile->m_cd.author));
+ SetProperty(L"CPYR", CStringW(m_pFile->m_cd.copyright));
+ SetProperty(L"DESC", CStringW(m_pFile->m_cd.comment));
+
+ return m_pOutputs.GetCount() > 0 ? S_OK : E_FAIL;
+}
- while(p < end - 4 && cnt-- > 0)
- {
- BYTE* base = p;
- DWORD len = *(DWORD*)p;
- bswap(len);
- p += 4;
- if(base + len > end) break;
-
- p++;
- WORD keylen = *(WORD*)p;
- bswap(keylen);
- p += 2;
- memcpy(key.GetBufferSetLength(keylen), p, keylen);
- p += keylen;
-
- p += 4;
- WORD valuelen = *(WORD*)p;
- bswap(valuelen);
- p += 2;
- memcpy(value.GetBufferSetLength(valuelen), p, valuelen);
- p += valuelen;
-
- ASSERT(p == base + len);
- p = base + len;
-
- lfi[key] = value;
- }
+bool CRealMediaSplitterFilter::DemuxInit()
+{
+ if(!m_pFile) return(false);
- POSITION pos = lfi.GetStartPosition();
- while(pos)
- {
- lfi.GetNextAssoc(pos, key, value);
-
- int n;
- if(key.Find("CHAPTER") == 0 && key.Find("TIME") == key.GetLength() - 4
- && (n = strtol(key.Mid(7), NULL, 10)) > 0)
- {
- int h, m, s, ms;
- char c;
- if(7 != sscanf(value, "%d%c%d%c%d%c%d", &h, &c, &m, &c, &s, &c, &ms))
- continue;
-
- key.Format("CHAPTER%02dNAME", n);
- if(!lfi.Lookup(key, value) || value.IsEmpty())
- value.Format("Chapter %d", n);
-
- ChapAppend(
- ((((REFERENCE_TIME)h * 60 + m) * 60 + s) * 1000 + ms) * 10000,
- CStringW(CString(value)));
- }
- }
- }
+ // reindex if needed
- if(mts.IsEmpty())
- {
- TRACE(_T("Unsupported RealMedia stream (%d): %s\n"), pmp->stream, CString(pmp->mime));
- continue;
- }
+ if(m_pFile->m_irs.GetCount() == 0)
+ {
+ m_nOpenProgress = 0;
+ m_rtDuration = 0;
- HRESULT hr;
+ int stream = m_pFile->GetMasterStream();
- CAutoPtr<CBaseSplitterOutputPin> pPinOut(DNew CRealMediaSplitterOutputPin(mts, name, this, this, &hr));
- if(SUCCEEDED(AddOutputPin((DWORD)pmp->stream, pPinOut)))
- {
- if(!m_rtStop)
- m_pFile->m_p.tDuration = max(m_pFile->m_p.tDuration, pmp->tDuration);
- }
- }
+ UINT32 tLastStart = -1;
+ UINT32 nPacket = 0;
- pos = m_pFile->m_subs.GetHeadPosition();
- for(DWORD stream = 0; pos; stream++)
- {
- CRMFile::subtitle& s = m_pFile->m_subs.GetNext(pos);
+ POSITION pos = m_pFile->m_dcs.GetHeadPosition();
+ while(pos && !m_fAbort)
+ {
+ DataChunk* pdc = m_pFile->m_dcs.GetNext(pos);
- CStringW name;
- name.Format(L"Subtitle %02d", stream);
- if(!s.name.IsEmpty()) name += L" (" + CStringW(CString(s.name)) + L")";
+ m_pFile->Seek(pdc->pos);
- CMediaType mt;
- mt.SetSampleSize(1);
- mt.majortype = MEDIATYPE_Text;
+ for(UINT32 i = 0; i < pdc->nPackets && !m_fAbort; i++, nPacket++)
+ {
+ UINT64 filepos = m_pFile->GetPos();
- CAtlArray<CMediaType> mts;
- mts.Add(mt);
+ HRESULT hr;
- HRESULT hr;
+ MediaPacketHeader mph;
+ if(S_OK != (hr = m_pFile->Read(mph, false)))
+ break;
- CAutoPtr<CBaseSplitterOutputPin> pPinOut(DNew CRealMediaSplitterOutputPin(mts, name, this, this, &hr));
- AddOutputPin((DWORD)~stream, pPinOut);
- }
+ m_rtDuration = max((__int64)(10000i64*mph.tStart), m_rtDuration);
- m_rtDuration = m_rtNewStop = m_rtStop = 10000i64 * m_pFile->m_p.tDuration;
+ if(mph.stream == stream && (mph.flags&MediaPacketHeader::PN_KEYFRAME_FLAG) && tLastStart != mph.tStart)
+ {
+ CAutoPtr<IndexRecord> pir(DNew IndexRecord);
+ pir->tStart = mph.tStart;
+ pir->ptrFilePos = (UINT32)filepos;
+ pir->packet = nPacket;
+ m_pFile->m_irs.AddTail(pir);
- SetProperty(L"TITL", CStringW(m_pFile->m_cd.title));
- SetProperty(L"AUTH", CStringW(m_pFile->m_cd.author));
- SetProperty(L"CPYR", CStringW(m_pFile->m_cd.copyright));
- SetProperty(L"DESC", CStringW(m_pFile->m_cd.comment));
+ tLastStart = mph.tStart;
+ }
- return m_pOutputs.GetCount() > 0 ? S_OK : E_FAIL;
-}
+ m_nOpenProgress = m_pFile->GetPos()*100/m_pFile->GetLength();
-bool CRealMediaSplitterFilter::DemuxInit()
-{
- if(!m_pFile) return(false);
+ DWORD cmd;
+ if(CheckRequest(&cmd))
+ {
+ if(cmd == CMD_EXIT) m_fAbort = true;
+ else Reply(S_OK);
+ }
+ }
+ }
- // reindex if needed
+ m_nOpenProgress = 100;
- if(m_pFile->m_irs.GetCount() == 0)
- {
- m_nOpenProgress = 0;
- m_rtDuration = 0;
+ if(m_fAbort) m_pFile->m_irs.RemoveAll();
- int stream = m_pFile->GetMasterStream();
+ m_fAbort = false;
+ }
- UINT32 tLastStart = -1;
- UINT32 nPacket = 0;
+ m_seekpos = NULL;
+ m_seekpacket = 0;
+ m_seekfilepos = 0;
- POSITION pos = m_pFile->m_dcs.GetHeadPosition();
- while(pos && !m_fAbort)
- {
- DataChunk* pdc = m_pFile->m_dcs.GetNext(pos);
+ return(true);
+}
- m_pFile->Seek(pdc->pos);
+void CRealMediaSplitterFilter::DemuxSeek(REFERENCE_TIME rt)
+{
+ if(rt <= 0)
+ {
+ m_seekpos = m_pFile->m_dcs.GetHeadPosition();
+ m_seekpacket = 0;
+ m_seekfilepos = m_pFile->m_dcs.GetHead()->pos;
+ }
+ else
+ {
+ m_seekpos = NULL;
+
+ POSITION pos = m_pFile->m_irs.GetTailPosition();
+ while(pos && !m_seekpos)
+ {
+ IndexRecord* pir = m_pFile->m_irs.GetPrev(pos);
+ if(pir->tStart <= rt/10000)
+ {
+ m_seekpacket = pir->packet;
+
+ pos = m_pFile->m_dcs.GetTailPosition();
+ while(pos && !m_seekpos)
+ {
+ POSITION tmp = pos;
+
+ DataChunk* pdc = m_pFile->m_dcs.GetPrev(pos);
+
+ if(pdc->pos <= pir->ptrFilePos)
+ {
+ m_seekpos = tmp;
+ m_seekfilepos = pir->ptrFilePos;
+
+ POSITION pos = m_pFile->m_dcs.GetHeadPosition();
+ while(pos != m_seekpos)
+ {
+ m_seekpacket -= m_pFile->m_dcs.GetNext(pos)->nPackets;
+ }
+ }
+ }
+
+ // search the closest keyframe to the seek time (commented out 'cause rm seems to index all of its keyframes...)
+/*
+ if(m_seekpos)
+ {
+ DataChunk* pdc = m_pFile->m_dcs.GetAt(m_seekpos);
+
+ m_pFile->Seek(m_seekfilepos);
+
+ REFERENCE_TIME seektime = -1;
+ UINT32 seekstream = -1;
+
+ for(UINT32 i = m_seekpacket; i < pdc->nPackets; i++)
+ {
+ UINT64 filepos = m_pFile->GetPos();
+
+ MediaPacketHeader mph;
+ if(S_OK != m_pFile->Read(mph, false))
+ break;
+
+ if(seekstream == -1) seekstream = mph.stream;
+ if(seekstream != mph.stream) continue;
+
+ if(seektime == 10000i64*mph.tStart) continue;
+ if(rt < 10000i64*mph.tStart) break;
+
+ if((mph.flags&MediaPacketHeader::PN_KEYFRAME_FLAG))
+ {
+ m_seekpacket = i;
+ m_seekfilepos = filepos;
+ seektime = 10000i64*mph.tStart;
+ }
+ }
+ }
+*/
+ }
+ }
+
+ if(!m_seekpos)
+ {
+ m_seekpos = m_pFile->m_dcs.GetHeadPosition();
+ m_seekpacket = 0;
+ m_seekfilepos = m_pFile->m_dcs.GetAt(m_seekpos)->pos;
+ }
+ }
+}
- for(UINT32 i = 0; i < pdc->nPackets && !m_fAbort; i++, nPacket++)
- {
- UINT64 filepos = m_pFile->GetPos();
+bool CRealMediaSplitterFilter::DemuxLoop()
+{
+ HRESULT hr = S_OK;
+ POSITION pos;
- HRESULT hr;
+ pos = m_pFile->m_subs.GetHeadPosition();
+ for(DWORD stream = 0; pos && SUCCEEDED(hr) && !CheckRequest(NULL); stream++)
+ {
+ CRMFile::subtitle& s = m_pFile->m_subs.GetNext(pos);
- MediaPacketHeader mph;
- if(S_OK != (hr = m_pFile->Read(mph, false)))
- break;
+ CAutoPtr<Packet> p(DNew Packet);
- m_rtDuration = max((__int64)(10000i64 * mph.tStart), m_rtDuration);
+ p->TrackNumber = ~stream;
+ p->bSyncPoint = TRUE;
+ p->rtStart = 0;
+ p->rtStop = 1;
- if(mph.stream == stream && (mph.flags & MediaPacketHeader::PN_KEYFRAME_FLAG) && tLastStart != mph.tStart)
- {
- CAutoPtr<IndexRecord> pir(DNew IndexRecord);
- pir->tStart = mph.tStart;
- pir->ptrFilePos = (UINT32)filepos;
- pir->packet = nPacket;
- m_pFile->m_irs.AddTail(pir);
+ p->SetCount((4+1) + (2+4+(s.name.GetLength()+1)*2) + (2+4+s.data.GetLength()));
+ BYTE* ptr = p->GetData();
- tLastStart = mph.tStart;
- }
+ strcpy((char*)ptr, "GAB2"); ptr += 4+1;
- m_nOpenProgress = m_pFile->GetPos() * 100 / m_pFile->GetLength();
+ *(WORD*)ptr = 2; ptr += 2;
+ *(DWORD*)ptr = (s.name.GetLength()+1)*2; ptr += 4;
+ wcscpy((WCHAR*)ptr, CStringW(s.name)); ptr += (s.name.GetLength()+1)*2;
- DWORD cmd;
- if(CheckRequest(&cmd))
- {
- if(cmd == CMD_EXIT) m_fAbort = true;
- else Reply(S_OK);
- }
- }
- }
+ *(WORD*)ptr = 4; ptr += 2;
+ *(DWORD*)ptr = s.data.GetLength(); ptr += 4;
+ memcpy((char*)ptr, s.data, s.data.GetLength()); ptr += s.name.GetLength();
- m_nOpenProgress = 100;
+ hr = DeliverPacket(p);
+ }
- if(m_fAbort) m_pFile->m_irs.RemoveAll();
+ pos = m_seekpos;
+ while(pos && SUCCEEDED(hr) && !CheckRequest(NULL))
+ {
+ DataChunk* pdc = m_pFile->m_dcs.GetNext(pos);
- m_fAbort = false;
- }
+ m_pFile->Seek(m_seekfilepos > 0 ? m_seekfilepos : pdc->pos);
- m_seekpos = NULL;
- m_seekpacket = 0;
- m_seekfilepos = 0;
+ for(UINT32 i = m_seekpacket; i < pdc->nPackets && SUCCEEDED(hr) && !CheckRequest(NULL); i++)
+ {
+ MediaPacketHeader mph;
+ if(S_OK != (hr = m_pFile->Read(mph)))
+ break;
- return(true);
-}
+ CAutoPtr<Packet> p(DNew Packet);
+ p->TrackNumber = mph.stream;
+ p->bSyncPoint = !!(mph.flags&MediaPacketHeader::PN_KEYFRAME_FLAG);
+ p->rtStart = 10000i64*(mph.tStart);
+ p->rtStop = p->rtStart+1;
+ p->Copy(mph.pData);
+ hr = DeliverPacket(p);
+ }
-void CRealMediaSplitterFilter::DemuxSeek(REFERENCE_TIME rt)
-{
- if(rt <= 0)
- {
- m_seekpos = m_pFile->m_dcs.GetHeadPosition();
- m_seekpacket = 0;
- m_seekfilepos = m_pFile->m_dcs.GetHead()->pos;
- }
- else
- {
- m_seekpos = NULL;
-
- POSITION pos = m_pFile->m_irs.GetTailPosition();
- while(pos && !m_seekpos)
- {
- IndexRecord* pir = m_pFile->m_irs.GetPrev(pos);
- if(pir->tStart <= rt / 10000)
- {
- m_seekpacket = pir->packet;
-
- pos = m_pFile->m_dcs.GetTailPosition();
- while(pos && !m_seekpos)
- {
- POSITION tmp = pos;
-
- DataChunk* pdc = m_pFile->m_dcs.GetPrev(pos);
-
- if(pdc->pos <= pir->ptrFilePos)
- {
- m_seekpos = tmp;
- m_seekfilepos = pir->ptrFilePos;
-
- POSITION pos = m_pFile->m_dcs.GetHeadPosition();
- while(pos != m_seekpos)
- {
- m_seekpacket -= m_pFile->m_dcs.GetNext(pos)->nPackets;
- }
- }
- }
-
- // search the closest keyframe to the seek time (commented out 'cause rm seems to index all of its keyframes...)
- /*
- if(m_seekpos)
- {
- DataChunk* pdc = m_pFile->m_dcs.GetAt(m_seekpos);
-
- m_pFile->Seek(m_seekfilepos);
-
- REFERENCE_TIME seektime = -1;
- UINT32 seekstream = -1;
-
- for(UINT32 i = m_seekpacket; i < pdc->nPackets; i++)
- {
- UINT64 filepos = m_pFile->GetPos();
-
- MediaPacketHeader mph;
- if(S_OK != m_pFile->Read(mph, false))
- break;
-
- if(seekstream == -1) seekstream = mph.stream;
- if(seekstream != mph.stream) continue;
-
- if(seektime == 10000i64*mph.tStart) continue;
- if(rt < 10000i64*mph.tStart) break;
-
- if((mph.flags&MediaPacketHeader::PN_KEYFRAME_FLAG))
- {
- m_seekpacket = i;
- m_seekfilepos = filepos;
- seektime = 10000i64*mph.tStart;
- }
- }
- }
- */
- }
- }
-
- if(!m_seekpos)
- {
- m_seekpos = m_pFile->m_dcs.GetHeadPosition();
- m_seekpacket = 0;
- m_seekfilepos = m_pFile->m_dcs.GetAt(m_seekpos)->pos;
- }
- }
-}
+ m_seekpacket = 0;
+ m_seekfilepos = 0;
+ }
-bool CRealMediaSplitterFilter::DemuxLoop()
-{
- HRESULT hr = S_OK;
- POSITION pos;
-
- pos = m_pFile->m_subs.GetHeadPosition();
- for(DWORD stream = 0; pos && SUCCEEDED(hr) && !CheckRequest(NULL); stream++)
- {
- CRMFile::subtitle& s = m_pFile->m_subs.GetNext(pos);
-
- CAutoPtr<Packet> p(DNew Packet);
-
- p->TrackNumber = ~stream;
- p->bSyncPoint = TRUE;
- p->rtStart = 0;
- p->rtStop = 1;
-
- p->SetCount((4 + 1) + (2 + 4 + (s.name.GetLength() + 1) * 2) + (2 + 4 + s.data.GetLength()));
- BYTE* ptr = p->GetData();
-
- strcpy((char*)ptr, "GAB2");
- ptr += 4 + 1;
-
- *(WORD*)ptr = 2;
- ptr += 2;
- *(DWORD*)ptr = (s.name.GetLength() + 1) * 2;
- ptr += 4;
- wcscpy((WCHAR*)ptr, CStringW(s.name));
- ptr += (s.name.GetLength() + 1) * 2;
-
- *(WORD*)ptr = 4;
- ptr += 2;
- *(DWORD*)ptr = s.data.GetLength();
- ptr += 4;
- memcpy((char*)ptr, s.data, s.data.GetLength());
- ptr += s.name.GetLength();
-
- hr = DeliverPacket(p);
- }
-
- pos = m_seekpos;
- while(pos && SUCCEEDED(hr) && !CheckRequest(NULL))
- {
- DataChunk* pdc = m_pFile->m_dcs.GetNext(pos);
-
- m_pFile->Seek(m_seekfilepos > 0 ? m_seekfilepos : pdc->pos);
-
- for(UINT32 i = m_seekpacket; i < pdc->nPackets && SUCCEEDED(hr) && !CheckRequest(NULL); i++)
- {
- MediaPacketHeader mph;
- if(S_OK != (hr = m_pFile->Read(mph)))
- break;
-
- CAutoPtr<Packet> p(DNew Packet);
- p->TrackNumber = mph.stream;
- p->bSyncPoint = !!(mph.flags & MediaPacketHeader::PN_KEYFRAME_FLAG);
- p->rtStart = 10000i64 * (mph.tStart);
- p->rtStop = p->rtStart + 1;
- p->Copy(mph.pData);
- hr = DeliverPacket(p);
- }
-
- m_seekpacket = 0;
- m_seekfilepos = 0;
- }
-
- return(true);
+ return(true);
}
// IKeyFrameInfo
STDMETHODIMP CRealMediaSplitterFilter::GetKeyFrameCount(UINT& nKFs)
{
- if(!m_pFile) return E_UNEXPECTED;
- nKFs = m_pFile->m_irs.GetCount();
- return S_OK;
+ if(!m_pFile) return E_UNEXPECTED;
+ nKFs = m_pFile->m_irs.GetCount();
+ return S_OK;
}
STDMETHODIMP CRealMediaSplitterFilter::GetKeyFrames(const GUID* pFormat, REFERENCE_TIME* pKFs, UINT& nKFs)
{
- CheckPointer(pFormat, E_POINTER);
- CheckPointer(pKFs, E_POINTER);
+ CheckPointer(pFormat, E_POINTER);
+ CheckPointer(pKFs, E_POINTER);
- if(!m_pFile) return E_UNEXPECTED;
- if(*pFormat != TIME_FORMAT_MEDIA_TIME) return E_INVALIDARG;
+ if(!m_pFile) return E_UNEXPECTED;
+ if(*pFormat != TIME_FORMAT_MEDIA_TIME) return E_INVALIDARG;
- UINT nKFsTmp = 0;
- POSITION pos = m_pFile->m_irs.GetHeadPosition();
- for(int i = 0; pos && nKFsTmp < nKFs; i++)
- pKFs[nKFsTmp++] = 10000i64 * m_pFile->m_irs.GetNext(pos)->tStart;
- nKFs = nKFsTmp;
+ UINT nKFsTmp = 0;
+ POSITION pos = m_pFile->m_irs.GetHeadPosition();
+ for(int i = 0; pos && nKFsTmp < nKFs; i++)
+ pKFs[nKFsTmp++] = 10000i64*m_pFile->m_irs.GetNext(pos)->tStart;
+ nKFs = nKFsTmp;
- return S_OK;
+ return S_OK;
}
//
@@ -787,7 +740,7 @@ STDMETHODIMP CRealMediaSplitterFilter::GetKeyFrames(const GUID* pFormat, REFEREN
//
CRealMediaSplitterOutputPin::CRealMediaSplitterOutputPin(CAtlArray<CMediaType>& mts, LPCWSTR pName, CBaseFilter* pFilter, CCritSec* pLock, HRESULT* phr)
- : CBaseSplitterOutputPin(mts, pName, pFilter, pLock, phr)
+ : CBaseSplitterOutputPin(mts, pName, pFilter, pLock, phr)
{
}
@@ -797,230 +750,218 @@ CRealMediaSplitterOutputPin::~CRealMediaSplitterOutputPin()
HRESULT CRealMediaSplitterOutputPin::DeliverEndFlush()
{
- {
- CAutoLock cAutoLock(&m_csQueue);
- m_segments.Clear();
- }
+ {
+ CAutoLock cAutoLock(&m_csQueue);
+ m_segments.Clear();
+ }
- return __super::DeliverEndFlush();
+ return __super::DeliverEndFlush();
}
HRESULT CRealMediaSplitterOutputPin::DeliverSegments()
{
- HRESULT hr;
-
- if(m_segments.GetCount() == 0)
- {
- m_segments.Clear();
- return S_OK;
- }
-
- CAutoPtr<Packet> p(DNew Packet());
-
- p->TrackNumber = -1;
- p->bDiscontinuity = m_segments.fDiscontinuity;
- p->bSyncPoint = m_segments.fSyncPoint;
- p->rtStart = m_segments.rtStart;
- p->rtStop = m_segments.rtStart + 1;
-
- DWORD len = 0, total = 0;
- POSITION pos = m_segments.GetHeadPosition();
- while(pos)
- {
- segment* s = m_segments.GetNext(pos);
- len = max(len, s->offset + s->data.GetCount());
- total += s->data.GetCount();
- }
- ASSERT(len == total);
- len += 1 + 2 * 4 * (!m_segments.fMerged ? m_segments.GetCount() : 1);
-
- p->SetCount(len);
-
- BYTE* pData = p->GetData();
-
- *pData++ = m_segments.fMerged ? 0 : m_segments.GetCount() - 1;
-
- if(m_segments.fMerged)
- {
- *((DWORD*)pData) = 1;
- pData += 4;
- *((DWORD*)pData) = 0;
- pData += 4;
- }
- else
- {
- pos = m_segments.GetHeadPosition();
- while(pos)
- {
- *((DWORD*)pData) = 1;
- pData += 4;
- *((DWORD*)pData) = m_segments.GetNext(pos)->offset;
- pData += 4;
- }
- }
-
- pos = m_segments.GetHeadPosition();
- while(pos)
- {
- segment* s = m_segments.GetNext(pos);
- memcpy(pData + s->offset, s->data.GetData(), s->data.GetCount());
- }
-
- hr = __super::DeliverPacket(p);
-
- m_segments.Clear();
-
- return hr;
+ HRESULT hr;
+
+ if(m_segments.GetCount() == 0)
+ {
+ m_segments.Clear();
+ return S_OK;
+ }
+
+ CAutoPtr<Packet> p(DNew Packet());
+
+ p->TrackNumber = -1;
+ p->bDiscontinuity = m_segments.fDiscontinuity;
+ p->bSyncPoint = m_segments.fSyncPoint;
+ p->rtStart = m_segments.rtStart;
+ p->rtStop = m_segments.rtStart+1;
+
+ DWORD len = 0, total = 0;
+ POSITION pos = m_segments.GetHeadPosition();
+ while(pos)
+ {
+ segment* s = m_segments.GetNext(pos);
+ len = max(len, s->offset + s->data.GetCount());
+ total += s->data.GetCount();
+ }
+ ASSERT(len == total);
+ len += 1 + 2*4*(!m_segments.fMerged ? m_segments.GetCount() : 1);
+
+ p->SetCount(len);
+
+ BYTE* pData = p->GetData();
+
+ *pData++ = m_segments.fMerged ? 0 : m_segments.GetCount()-1;
+
+ if(m_segments.fMerged)
+ {
+ *((DWORD*)pData) = 1; pData += 4;
+ *((DWORD*)pData) = 0; pData += 4;
+ }
+ else
+ {
+ pos = m_segments.GetHeadPosition();
+ while(pos)
+ {
+ *((DWORD*)pData) = 1; pData += 4;
+ *((DWORD*)pData) = m_segments.GetNext(pos)->offset; pData += 4;
+ }
+ }
+
+ pos = m_segments.GetHeadPosition();
+ while(pos)
+ {
+ segment* s = m_segments.GetNext(pos);
+ memcpy(pData + s->offset, s->data.GetData(), s->data.GetCount());
+ }
+
+ hr = __super::DeliverPacket(p);
+
+ m_segments.Clear();
+
+ return hr;
}
HRESULT CRealMediaSplitterOutputPin::DeliverPacket(CAutoPtr<Packet> p)
{
- HRESULT hr = S_OK;
-
- ASSERT(p->rtStart < p->rtStop);
-
- if(m_mt.subtype == MEDIASUBTYPE_WAVE_DOLBY_AC3)
- {
- WORD* s = (WORD*)p->GetData();
- WORD* e = s + p->GetCount() / 2;
- while(s < e) bswap(*s++);
- }
-
- if(m_mt.subtype == MEDIASUBTYPE_RV10 || m_mt.subtype == MEDIASUBTYPE_RV20
- || m_mt.subtype == MEDIASUBTYPE_RV30 || m_mt.subtype == MEDIASUBTYPE_RV40
- || m_mt.subtype == MEDIASUBTYPE_RV41)
- {
- CAutoLock cAutoLock(&m_csQueue);
-
- int len = p->GetCount();
- BYTE* pIn = p->GetData();
- BYTE* pInOrg = pIn;
-
- if(m_segments.rtStart != p->rtStart)
- {
- if(S_OK != (hr = DeliverSegments()))
- return hr;
- }
-
- if(!m_segments.fDiscontinuity && p->bDiscontinuity)
- m_segments.fDiscontinuity = true;
- m_segments.fSyncPoint = !!p->bSyncPoint;
- m_segments.rtStart = p->rtStart;
-
- while(pIn - pInOrg < len)
- {
- BYTE hdr = *pIn++, subseq = 0, seqnum = 0;
- DWORD packetlen = 0, packetoffset = 0;
-
- if((hdr & 0xc0) == 0x40)
- {
- pIn++;
- packetlen = len - (pIn - pInOrg);
- }
- else
- {
- if((hdr & 0x40) == 0)
- subseq = (*pIn++) & 0x7f;
-
-#define GetWORD(var) \
+ HRESULT hr = S_OK;
+
+ ASSERT(p->rtStart < p->rtStop);
+
+ if(m_mt.subtype == MEDIASUBTYPE_WAVE_DOLBY_AC3)
+ {
+ WORD* s = (WORD*)p->GetData();
+ WORD* e = s + p->GetCount()/2;
+ while(s < e) bswap(*s++);
+ }
+
+ if(m_mt.subtype == MEDIASUBTYPE_RV10 || m_mt.subtype == MEDIASUBTYPE_RV20
+ || m_mt.subtype == MEDIASUBTYPE_RV30 || m_mt.subtype == MEDIASUBTYPE_RV40
+ || m_mt.subtype == MEDIASUBTYPE_RV41)
+ {
+ CAutoLock cAutoLock(&m_csQueue);
+
+ int len = p->GetCount();
+ BYTE* pIn = p->GetData();
+ BYTE* pInOrg = pIn;
+
+ if(m_segments.rtStart != p->rtStart)
+ {
+ if(S_OK != (hr = DeliverSegments()))
+ return hr;
+ }
+
+ if(!m_segments.fDiscontinuity && p->bDiscontinuity)
+ m_segments.fDiscontinuity = true;
+ m_segments.fSyncPoint = !!p->bSyncPoint;
+ m_segments.rtStart = p->rtStart;
+
+ while(pIn - pInOrg < len)
+ {
+ BYTE hdr = *pIn++, subseq = 0, seqnum = 0;
+ DWORD packetlen = 0, packetoffset = 0;
+
+ if((hdr&0xc0) == 0x40)
+ {
+ pIn++;
+ packetlen = len - (pIn - pInOrg);
+ }
+ else
+ {
+ if((hdr&0x40) == 0)
+ subseq = (*pIn++)&0x7f;
+
+ #define GetWORD(var) \
var = (var<<8)|(*pIn++); \
var = (var<<8)|(*pIn++); \
-
- GetWORD(packetlen);
- if(packetlen & 0x8000) m_segments.fMerged = true;
- if((packetlen & 0x4000) == 0)
- {
- GetWORD(packetlen);
- packetlen &= 0x3fffffff;
- }
- else packetlen &= 0x3fff;
-
- GetWORD(packetoffset);
- if((packetoffset & 0x4000) == 0)
- {
- GetWORD(packetoffset);
- packetoffset &= 0x3fffffff;
- }
- else packetoffset &= 0x3fff;
-
-#undef GetWORD
-
- if((hdr & 0xc0) == 0xc0)
- m_segments.rtStart = 10000i64 * packetoffset - m_rtStart, packetoffset = 0;
- else if((hdr & 0xc0) == 0x80)
- packetoffset = packetlen - packetoffset;
-
- seqnum = *pIn++;
- }
- int len2 = min(len - (pIn - pInOrg), packetlen - packetoffset);
+ GetWORD(packetlen);
+ if(packetlen&0x8000) m_segments.fMerged = true;
+ if((packetlen&0x4000) == 0) {GetWORD(packetlen); packetlen &= 0x3fffffff;}
+ else packetlen &= 0x3fff;
- CAutoPtr<segment> s(DNew segment);
- s->offset = packetoffset;
- s->data.SetCount(len2);
- memcpy(s->data.GetData(), pIn, len2);
- m_segments.AddTail(s);
+ GetWORD(packetoffset);
+ if((packetoffset&0x4000) == 0) {GetWORD(packetoffset); packetoffset &= 0x3fffffff;}
+ else packetoffset &= 0x3fff;
- pIn += len2;
+ #undef GetWORD
- if((hdr & 0x80) || packetoffset + len2 >= packetlen)
- {
- if(S_OK != (hr = DeliverSegments()))
- return hr;
- }
- }
- }
- else if(m_mt.subtype == MEDIASUBTYPE_RAAC || m_mt.subtype == MEDIASUBTYPE_RACP
- || m_mt.subtype == MEDIASUBTYPE_AAC)
- {
- BYTE* ptr = p->GetData() + 2;
-
- CAtlList<WORD> sizes;
- int total = 0;
- int remaining = p->GetCount() - 2;
- int expected = *(ptr - 1) >> 4;
-
- while(total < remaining)
- {
- int size = (ptr[0] << 8) | (ptr[1]);
- sizes.AddTail(size);
- total += size;
- ptr += 2;
- remaining -= 2;
- expected--;
- }
-
- ASSERT(total == remaining);
- ASSERT(expected == 0);
-
- WAVEFORMATEX* wfe = (WAVEFORMATEX*)m_mt.pbFormat;
- REFERENCE_TIME rtDur = 10240000000i64 / wfe->nSamplesPerSec * (wfe->cbSize > 2 ? 2 : 1);
- REFERENCE_TIME rtStart = p->rtStart;
- BOOL bDiscontinuity = p->bDiscontinuity;
-
- POSITION pos = sizes.GetHeadPosition();
- while(pos)
- {
- WORD size = sizes.GetNext(pos);
-
- CAutoPtr<Packet> p(DNew Packet);
- p->bDiscontinuity = bDiscontinuity;
- p->bSyncPoint = true;
- p->rtStart = rtStart;
- p->rtStop = rtStart += rtDur;
- p->SetData(ptr, size);
- ptr += size;
- bDiscontinuity = false;
- if(S_OK != (hr = __super::DeliverPacket(p)))
- break;
- }
- }
- else
- {
- hr = __super::DeliverPacket(p);
- }
-
- return hr;
+ if((hdr&0xc0) == 0xc0)
+ m_segments.rtStart = 10000i64*packetoffset - m_rtStart, packetoffset = 0;
+ else if((hdr&0xc0) == 0x80)
+ packetoffset = packetlen - packetoffset;
+
+ seqnum = *pIn++;
+ }
+
+ int len2 = min(len - (pIn - pInOrg), packetlen - packetoffset);
+
+ CAutoPtr<segment> s(DNew segment);
+ s->offset = packetoffset;
+ s->data.SetCount(len2);
+ memcpy(s->data.GetData(), pIn, len2);
+ m_segments.AddTail(s);
+
+ pIn += len2;
+
+ if((hdr&0x80) || packetoffset+len2 >= packetlen)
+ {
+ if(S_OK != (hr = DeliverSegments()))
+ return hr;
+ }
+ }
+ }
+ else if(m_mt.subtype == MEDIASUBTYPE_RAAC || m_mt.subtype == MEDIASUBTYPE_RACP
+ || m_mt.subtype == MEDIASUBTYPE_AAC)
+ {
+ BYTE* ptr = p->GetData()+2;
+
+ CAtlList<WORD> sizes;
+ int total = 0;
+ int remaining = p->GetCount()-2;
+ int expected = *(ptr-1)>>4;
+
+ while(total < remaining)
+ {
+ int size = (ptr[0]<<8)|(ptr[1]);
+ sizes.AddTail(size);
+ total += size;
+ ptr += 2;
+ remaining -= 2;
+ expected--;
+ }
+
+ ASSERT(total == remaining);
+ ASSERT(expected == 0);
+
+ WAVEFORMATEX* wfe = (WAVEFORMATEX*)m_mt.pbFormat;
+ REFERENCE_TIME rtDur = 10240000000i64/wfe->nSamplesPerSec * (wfe->cbSize>2?2:1);
+ REFERENCE_TIME rtStart = p->rtStart;
+ BOOL bDiscontinuity = p->bDiscontinuity;
+
+ POSITION pos = sizes.GetHeadPosition();
+ while(pos)
+ {
+ WORD size = sizes.GetNext(pos);
+
+ CAutoPtr<Packet> p(DNew Packet);
+ p->bDiscontinuity = bDiscontinuity;
+ p->bSyncPoint = true;
+ p->rtStart = rtStart;
+ p->rtStop = rtStart += rtDur;
+ p->SetData(ptr, size);
+ ptr += size;
+ bDiscontinuity = false;
+ if(S_OK != (hr = __super::DeliverPacket(p)))
+ break;
+ }
+ }
+ else
+ {
+ hr = __super::DeliverPacket(p);
+ }
+
+ return hr;
}
//
@@ -1028,10 +969,10 @@ HRESULT CRealMediaSplitterOutputPin::DeliverPacket(CAutoPtr<Packet> p)
//
CRealMediaSourceFilter::CRealMediaSourceFilter(LPUNKNOWN pUnk, HRESULT* phr)
- : CRealMediaSplitterFilter(pUnk, phr)
+ : CRealMediaSplitterFilter(pUnk, phr)
{
- m_clsid = __uuidof(this);
- m_pInput.Free();
+ m_clsid = __uuidof(this);
+ m_pInput.Free();
}
//
@@ -1039,488 +980,468 @@ CRealMediaSourceFilter::CRealMediaSourceFilter(LPUNKNOWN pUnk, HRESULT* phr)
//
CRMFile::CRMFile(IAsyncReader* pAsyncReader, HRESULT& hr)
- : CBaseSplitterFile(pAsyncReader, hr)
+ : CBaseSplitterFile(pAsyncReader, hr)
{
- if(FAILED(hr)) return;
- hr = Init();
+ if(FAILED(hr)) return;
+ hr = Init();
}
-template<typename T>
+template<typename T>
HRESULT CRMFile::Read(T& var)
{
- HRESULT hr = ByteRead((BYTE*)&var, sizeof(var));
- bswap(var);
- return hr;
+ HRESULT hr = ByteRead((BYTE*)&var, sizeof(var));
+ bswap(var);
+ return hr;
}
HRESULT CRMFile::Read(ChunkHdr& hdr)
{
- memset(&hdr, 0, sizeof(hdr));
- HRESULT hr;
- if(S_OK != (hr = Read(hdr.object_id))
- || S_OK != (hr = Read(hdr.size))
- || S_OK != (hr = Read(hdr.object_version)))
- return hr;
- return S_OK;
+ memset(&hdr, 0, sizeof(hdr));
+ HRESULT hr;
+ if(S_OK != (hr = Read(hdr.object_id))
+ || S_OK != (hr = Read(hdr.size))
+ || S_OK != (hr = Read(hdr.object_version)))
+ return hr;
+ return S_OK;
}
HRESULT CRMFile::Read(MediaPacketHeader& mph, bool fFull)
{
- memset(&mph, 0, FIELD_OFFSET(MediaPacketHeader, pData));
- mph.stream = -1;
-
- HRESULT hr;
-
- UINT16 object_version;
- if(S_OK != (hr = Read(object_version))) return hr;
- if(object_version != 0 && object_version != 1) return S_OK;
-
- UINT8 flags;
- if(S_OK != (hr = Read(mph.len))
- || S_OK != (hr = Read(mph.stream))
- || S_OK != (hr = Read(mph.tStart))
- || S_OK != (hr = Read(mph.reserved))
- || S_OK != (hr = Read(flags)))
- return hr;
- mph.flags = (MediaPacketHeader::flag_t)flags;
-
- LONG len = mph.len;
- len -= sizeof(object_version);
- len -= FIELD_OFFSET(MediaPacketHeader, flags);
- len -= sizeof(flags);
- ASSERT(len >= 0);
- len = max(len, 0);
-
- if(fFull)
- {
- mph.pData.SetCount(len);
- if(mph.len > 0 && S_OK != (hr = ByteRead(mph.pData.GetData(), len)))
- return hr;
- }
- else
- {
- Seek(GetPos() + len);
- }
-
- return S_OK;
+ memset(&mph, 0, FIELD_OFFSET(MediaPacketHeader, pData));
+ mph.stream = -1;
+
+ HRESULT hr;
+
+ UINT16 object_version;
+ if(S_OK != (hr = Read(object_version))) return hr;
+ if(object_version != 0 && object_version != 1) return S_OK;
+
+ UINT8 flags;
+ if(S_OK != (hr = Read(mph.len))
+ || S_OK != (hr = Read(mph.stream))
+ || S_OK != (hr = Read(mph.tStart))
+ || S_OK != (hr = Read(mph.reserved))
+ || S_OK != (hr = Read(flags)))
+ return hr;
+ mph.flags = (MediaPacketHeader::flag_t)flags;
+
+ LONG len = mph.len;
+ len -= sizeof(object_version);
+ len -= FIELD_OFFSET(MediaPacketHeader, flags);
+ len -= sizeof(flags);
+ ASSERT(len >= 0);
+ len = max(len, 0);
+
+ if(fFull)
+ {
+ mph.pData.SetCount(len);
+ if(mph.len > 0 && S_OK != (hr = ByteRead(mph.pData.GetData(), len)))
+ return hr;
+ }
+ else
+ {
+ Seek(GetPos() + len);
+ }
+
+ return S_OK;
}
HRESULT CRMFile::Init()
{
- Seek(0);
-
- bool fFirstChunk = true;
-
- HRESULT hr;
-
- ChunkHdr hdr;
- while(GetRemaining() && S_OK == (hr = Read(hdr)))
- {
- __int64 pos = GetPos() - sizeof(hdr);
-
- if(fFirstChunk && hdr.object_id != '.RMF')
- return E_FAIL;
-
- fFirstChunk = false;
-
- if(pos + hdr.size > GetLength() && hdr.object_id != 'DATA') // truncated?
- break;
-
- if(hdr.object_id == 0x2E7261FD) // '.ra+0xFD'
- return E_FAIL;
-
- if(hdr.object_version == 0)
- {
- switch(hdr.object_id)
- {
- case '.RMF':
- if(S_OK != (hr = Read(m_fh.version))) return hr;
- if(hdr.size == 0x10)
- {
- WORD w = 0;
- if(S_OK != (hr = Read(w))) return hr;
- m_fh.nHeaders = w;
- }
- else if(S_OK != (hr = Read(m_fh.nHeaders))) return hr;
- break;
- case 'CONT':
- UINT16 slen;
- if(S_OK != (hr = Read(slen))) return hr;
- if(slen > 0 && S_OK != (hr = ByteRead((BYTE*)m_cd.title.GetBufferSetLength(slen), slen))) return hr;
- if(S_OK != (hr = Read(slen))) return hr;
- if(slen > 0 && S_OK != (hr = ByteRead((BYTE*)m_cd.author.GetBufferSetLength(slen), slen))) return hr;
- if(S_OK != (hr = Read(slen))) return hr;
- if(slen > 0 && S_OK != (hr = ByteRead((BYTE*)m_cd.copyright.GetBufferSetLength(slen), slen))) return hr;
- if(S_OK != (hr = Read(slen))) return hr;
- if(slen > 0 && S_OK != (hr = ByteRead((BYTE*)m_cd.comment.GetBufferSetLength(slen), slen))) return hr;
- break;
- case 'PROP':
- if(S_OK != (hr = Read(m_p.maxBitRate))) return hr;
- if(S_OK != (hr = Read(m_p.avgBitRate))) return hr;
- if(S_OK != (hr = Read(m_p.maxPacketSize))) return hr;
- if(S_OK != (hr = Read(m_p.avgPacketSize))) return hr;
- if(S_OK != (hr = Read(m_p.nPackets))) return hr;
- if(S_OK != (hr = Read(m_p.tDuration))) return hr;
- if(S_OK != (hr = Read(m_p.tPreroll))) return hr;
- if(S_OK != (hr = Read(m_p.ptrIndex))) return hr;
- if(S_OK != (hr = Read(m_p.ptrData))) return hr;
- if(S_OK != (hr = Read(m_p.nStreams))) return hr;
- UINT16 flags;
- if(S_OK != (hr = Read(flags))) return hr;
- m_p.flags = (Properies::flags_t)flags;
- break;
- case 'MDPR':
- {
- CAutoPtr<MediaProperies> mp(DNew MediaProperies);
- if(S_OK != (hr = Read(mp->stream))) return hr;
- if(S_OK != (hr = Read(mp->maxBitRate))) return hr;
- if(S_OK != (hr = Read(mp->avgBitRate))) return hr;
- if(S_OK != (hr = Read(mp->maxPacketSize))) return hr;
- if(S_OK != (hr = Read(mp->avgPacketSize))) return hr;
- if(S_OK != (hr = Read(mp->tStart))) return hr;
- if(S_OK != (hr = Read(mp->tPreroll))) return hr;
- if(S_OK != (hr = Read(mp->tDuration))) return hr;
- UINT8 slen;
- if(S_OK != (hr = Read(slen))) return hr;
- if(slen > 0 && S_OK != (hr = ByteRead((BYTE*)mp->name.GetBufferSetLength(slen), slen))) return hr;
- if(S_OK != (hr = Read(slen))) return hr;
- if(slen > 0 && S_OK != (hr = ByteRead((BYTE*)mp->mime.GetBufferSetLength(slen), slen))) return hr;
- UINT32 tsdlen;
- if(S_OK != (hr = Read(tsdlen))) return hr;
- mp->typeSpecData.SetCount(tsdlen);
- if(tsdlen > 0 && S_OK != (hr = ByteRead(mp->typeSpecData.GetData(), tsdlen))) return hr;
- mp->width = mp->height = 0;
- mp->interlaced = mp->top_field_first = false;
- m_mps.AddTail(mp);
- break;
- }
- case 'DATA':
- {
- CAutoPtr<DataChunk> dc(DNew DataChunk);
- if(S_OK != (hr = Read(dc->nPackets))) return hr;
- if(S_OK != (hr = Read(dc->ptrNext))) return hr;
- dc->pos = GetPos();
- m_dcs.AddTail(dc);
+ Seek(0);
+
+ bool fFirstChunk = true;
+
+ HRESULT hr;
+
+ ChunkHdr hdr;
+ while(GetRemaining() && S_OK == (hr = Read(hdr)))
+ {
+ __int64 pos = GetPos() - sizeof(hdr);
+
+ if(fFirstChunk && hdr.object_id != '.RMF')
+ return E_FAIL;
+
+ fFirstChunk = false;
+
+ if(pos + hdr.size > GetLength() && hdr.object_id != 'DATA') // truncated?
+ break;
+
+ if(hdr.object_id == 0x2E7261FD) // '.ra+0xFD'
+ return E_FAIL;
+
+ if(hdr.object_version == 0)
+ {
+ switch(hdr.object_id)
+ {
+ case '.RMF':
+ if(S_OK != (hr = Read(m_fh.version))) return hr;
+ if(hdr.size == 0x10) {WORD w = 0; if(S_OK != (hr = Read(w))) return hr; m_fh.nHeaders = w;}
+ else if(S_OK != (hr = Read(m_fh.nHeaders))) return hr;
+ break;
+ case 'CONT':
+ UINT16 slen;
+ if(S_OK != (hr = Read(slen))) return hr;
+ if(slen > 0 && S_OK != (hr = ByteRead((BYTE*)m_cd.title.GetBufferSetLength(slen), slen))) return hr;
+ if(S_OK != (hr = Read(slen))) return hr;
+ if(slen > 0 && S_OK != (hr = ByteRead((BYTE*)m_cd.author.GetBufferSetLength(slen), slen))) return hr;
+ if(S_OK != (hr = Read(slen))) return hr;
+ if(slen > 0 && S_OK != (hr = ByteRead((BYTE*)m_cd.copyright.GetBufferSetLength(slen), slen))) return hr;
+ if(S_OK != (hr = Read(slen))) return hr;
+ if(slen > 0 && S_OK != (hr = ByteRead((BYTE*)m_cd.comment.GetBufferSetLength(slen), slen))) return hr;
+ break;
+ case 'PROP':
+ if(S_OK != (hr = Read(m_p.maxBitRate))) return hr;
+ if(S_OK != (hr = Read(m_p.avgBitRate))) return hr;
+ if(S_OK != (hr = Read(m_p.maxPacketSize))) return hr;
+ if(S_OK != (hr = Read(m_p.avgPacketSize))) return hr;
+ if(S_OK != (hr = Read(m_p.nPackets))) return hr;
+ if(S_OK != (hr = Read(m_p.tDuration))) return hr;
+ if(S_OK != (hr = Read(m_p.tPreroll))) return hr;
+ if(S_OK != (hr = Read(m_p.ptrIndex))) return hr;
+ if(S_OK != (hr = Read(m_p.ptrData))) return hr;
+ if(S_OK != (hr = Read(m_p.nStreams))) return hr;
+ UINT16 flags;
+ if(S_OK != (hr = Read(flags))) return hr;
+ m_p.flags = (Properies::flags_t)flags;
+ break;
+ case 'MDPR':
+ {
+ CAutoPtr<MediaProperies> mp(DNew MediaProperies);
+ if(S_OK != (hr = Read(mp->stream))) return hr;
+ if(S_OK != (hr = Read(mp->maxBitRate))) return hr;
+ if(S_OK != (hr = Read(mp->avgBitRate))) return hr;
+ if(S_OK != (hr = Read(mp->maxPacketSize))) return hr;
+ if(S_OK != (hr = Read(mp->avgPacketSize))) return hr;
+ if(S_OK != (hr = Read(mp->tStart))) return hr;
+ if(S_OK != (hr = Read(mp->tPreroll))) return hr;
+ if(S_OK != (hr = Read(mp->tDuration))) return hr;
+ UINT8 slen;
+ if(S_OK != (hr = Read(slen))) return hr;
+ if(slen > 0 && S_OK != (hr = ByteRead((BYTE*)mp->name.GetBufferSetLength(slen), slen))) return hr;
+ if(S_OK != (hr = Read(slen))) return hr;
+ if(slen > 0 && S_OK != (hr = ByteRead((BYTE*)mp->mime.GetBufferSetLength(slen), slen))) return hr;
+ UINT32 tsdlen;
+ if(S_OK != (hr = Read(tsdlen))) return hr;
+ mp->typeSpecData.SetCount(tsdlen);
+ if(tsdlen > 0 && S_OK != (hr = ByteRead(mp->typeSpecData.GetData(), tsdlen))) return hr;
+ mp->width = mp->height = 0;
+ mp->interlaced = mp->top_field_first = false;
+ m_mps.AddTail(mp);
+ break;
+ }
+ case 'DATA':
+ {
+ CAutoPtr<DataChunk> dc(DNew DataChunk);
+ if(S_OK != (hr = Read(dc->nPackets))) return hr;
+ if(S_OK != (hr = Read(dc->ptrNext))) return hr;
+ dc->pos = GetPos();
+ m_dcs.AddTail(dc);
GetDimensions();
- break;
- }
- case 'INDX':
- {
- IndexChunkHeader ich;
- if(S_OK != (hr = Read(ich.nIndices))) return hr;
- if(S_OK != (hr = Read(ich.stream))) return hr;
- if(S_OK != (hr = Read(ich.ptrNext))) return hr;
- int stream = GetMasterStream();
- while(ich.nIndices-- > 0)
- {
- UINT16 object_version;
- if(S_OK != (hr = Read(object_version))) return hr;
- if(object_version == 0)
- {
- CAutoPtr<IndexRecord> ir(DNew IndexRecord);
- if(S_OK != (hr = Read(ir->tStart))) return hr;
- if(S_OK != (hr = Read(ir->ptrFilePos))) return hr;
- if(S_OK != (hr = Read(ir->packet))) return hr;
- if(ich.stream == stream) m_irs.AddTail(ir);
- }
- }
- break;
- }
- case '.SUB':
- if(hdr.size > sizeof(hdr))
- {
- int size = hdr.size - sizeof(hdr);
- CAutoVectorPtr<char> buff;
- if(!buff.Allocate(size)) return E_OUTOFMEMORY;
- char* p = buff;
- if(S_OK != (hr = ByteRead((BYTE*)p, size))) return hr;
- for(char* end = p + size; p < end;)
- {
- subtitle s;
- s.name = p;
- p += s.name.GetLength() + 1;
- CStringA len(p);
- p += len.GetLength() + 1;
- s.data = CStringA(p, strtol(len, NULL, 10));
- p += s.data.GetLength();
- m_subs.AddTail(s);
- }
- }
- break;
- }
- }
-
- if(hdr.object_id == 'CONT' && BitRead(32, true) == 'DATA')
- {
- hdr.size = GetPos() - pos;
- }
-
- ASSERT(hdr.object_id == 'DATA'
- || GetPos() == pos + hdr.size
- || GetPos() == pos + sizeof(hdr));
-
- pos += hdr.size;
- if(pos > GetPos())
- Seek(pos);
- }
-
- return S_OK;
+ break;
+ }
+ case 'INDX':
+ {
+ IndexChunkHeader ich;
+ if(S_OK != (hr = Read(ich.nIndices))) return hr;
+ if(S_OK != (hr = Read(ich.stream))) return hr;
+ if(S_OK != (hr = Read(ich.ptrNext))) return hr;
+ int stream = GetMasterStream();
+ while(ich.nIndices-- > 0)
+ {
+ UINT16 object_version;
+ if(S_OK != (hr = Read(object_version))) return hr;
+ if(object_version == 0)
+ {
+ CAutoPtr<IndexRecord> ir(DNew IndexRecord);
+ if(S_OK != (hr = Read(ir->tStart))) return hr;
+ if(S_OK != (hr = Read(ir->ptrFilePos))) return hr;
+ if(S_OK != (hr = Read(ir->packet))) return hr;
+ if(ich.stream == stream) m_irs.AddTail(ir);
+ }
+ }
+ break;
+ }
+ case '.SUB':
+ if(hdr.size > sizeof(hdr))
+ {
+ int size = hdr.size - sizeof(hdr);
+ CAutoVectorPtr<char> buff;
+ if(!buff.Allocate(size)) return E_OUTOFMEMORY;
+ char* p = buff;
+ if(S_OK != (hr = ByteRead((BYTE*)p, size))) return hr;
+ for(char* end = p + size; p < end; )
+ {
+ subtitle s;
+ s.name = p; p += s.name.GetLength()+1;
+ CStringA len(p); p += len.GetLength()+1;
+ s.data = CStringA(p, strtol(len, NULL, 10)); p += s.data.GetLength();
+ m_subs.AddTail(s);
+ }
+ }
+ break;
+ }
+ }
+
+ if(hdr.object_id == 'CONT' && BitRead(32, true) == 'DATA')
+ {
+ hdr.size = GetPos() - pos;
+ }
+
+ ASSERT(hdr.object_id == 'DATA'
+ || GetPos() == pos + hdr.size
+ || GetPos() == pos + sizeof(hdr));
+
+ pos += hdr.size;
+ if(pos > GetPos())
+ Seek(pos);
+ }
+
+ return S_OK;
}
#define GetBits(n) GetBits2(n, p, bit_offset, bit_buffer)
unsigned int GetBits2(int n, unsigned char*& p, unsigned int& bit_offset, unsigned int& bit_buffer)
{
- unsigned int ret = ((unsigned int)bit_buffer >> (32 - (n)));
-
- bit_offset += n;
- bit_buffer <<= n;
- if(bit_offset > (32 - 16))
- {
- p += bit_offset >> 3;
- bit_offset &= 7;
- bit_buffer = (unsigned int)p[0] << 24;
- bit_buffer |= (unsigned int)p[1] << 16;
- bit_buffer |= (unsigned int)p[2] << 8;
- bit_buffer |= (unsigned int)p[3];
- bit_buffer <<= bit_offset;
- }
-
- return ret;
+ unsigned int ret = ((unsigned int)bit_buffer >> (32-(n)));
+
+ bit_offset += n;
+ bit_buffer <<= n;
+ if(bit_offset > (32-16))
+ {
+ p += bit_offset >> 3;
+ bit_offset &= 7;
+ bit_buffer = (unsigned int)p[0] << 24;
+ bit_buffer |= (unsigned int)p[1] << 16;
+ bit_buffer |= (unsigned int)p[2] << 8;
+ bit_buffer |= (unsigned int)p[3];
+ bit_buffer <<= bit_offset;
+ }
+
+ return ret;
}
void GetDimensions(unsigned char* p, unsigned int* wi, unsigned int* hi)
{
- unsigned int w, h, c;
-
- const unsigned int cw[8] = {160, 176, 240, 320, 352, 640, 704, 0};
- const unsigned int ch1[8] = {120, 132, 144, 240, 288, 480, 0, 0};
- const unsigned int ch2[4] = {180, 360, 576, 0};
-
- unsigned int bit_offset = 0;
- unsigned int bit_buffer = *(unsigned int*)p;
- bswap(bit_buffer);
-
- GetBits(13);
-
- GetBits(13);
-
- w = cw[GetBits(3)];
- if(w == 0)
- {
- do
- {
- c = GetBits(8);
- w += (c << 2);
- }
- while(c == 255);
- }
-
- c = GetBits(3);
-
- h = ch1[c];
- if(h == 0)
- {
- c = ((c << 1) | GetBits(1)) & 3;
-
- h = ch2[c];
- if(h == 0)
- {
- do
- {
- c = GetBits(8);
- h += (c << 2);
- }
- while(c == 255);
- }
- }
-
- *wi = w;
- *hi = h;
+ unsigned int w, h, c;
+
+ const unsigned int cw[8] = {160, 176, 240, 320, 352, 640, 704, 0};
+ const unsigned int ch1[8] = {120, 132, 144, 240, 288, 480, 0, 0};
+ const unsigned int ch2[4] = {180, 360, 576, 0};
+
+ unsigned int bit_offset = 0;
+ unsigned int bit_buffer = *(unsigned int*)p;
+ bswap(bit_buffer);
+
+ GetBits(13);
+
+ GetBits(13);
+
+ w = cw[GetBits(3)];
+ if(w == 0)
+ {
+ do
+ {
+ c = GetBits(8);
+ w += (c << 2);
+ }
+ while(c == 255);
+ }
+
+ c = GetBits(3);
+
+ h = ch1[c];
+ if(h == 0)
+ {
+ c = ((c << 1) | GetBits(1)) & 3;
+
+ h = ch2[c];
+ if(h == 0)
+ {
+ do
+ {
+ c = GetBits(8);
+ h += (c << 2);
+ }
+ while(c == 255);
+ }
+ }
+
+ *wi = w;
+ *hi = h;
}
-void GetDimensions_X10(unsigned char* p, unsigned int* wi, unsigned int* hi,
- bool *interlaced, bool *top_field_first, bool *repeat_field)
-{
- unsigned int w, h, c;
-
- const unsigned int cw[8] = {160, 176, 240, 320, 352, 640, 704, 0};
- const unsigned int ch1[8] = {120, 132, 144, 240, 288, 480, 0, 0};
- const unsigned int ch2[4] = {180, 360, 576, 0};
-
- unsigned int bit_offset = 0;
- unsigned int bit_buffer = *(unsigned int*)p;
- bswap(bit_buffer);
-
- GetBits(9);
-
- *interlaced = false;
- *top_field_first = false;
- *repeat_field = false;
- c = GetBits(1);
- if(c)
- {
- c = GetBits(1);
- if(c)
- *interlaced = true;
- c = GetBits(1);
- if(c)
- *top_field_first = true;
- c = GetBits(1);
- if(c)
- *repeat_field = true;
-
- c = GetBits(1);
- c = GetBits(1);
- if(c)
- GetBits(2);
- }
-
- GetBits(16);
-
- w = cw[GetBits(3)];
- if(w == 0)
- {
- do
- {
- c = GetBits(8);
- w += (c << 2);
- }
- while(c == 255);
- }
-
- c = GetBits(3);
-
- h = ch1[c];
- if(h == 0)
- {
- c = ((c << 1) | GetBits(1)) & 3;
-
- h = ch2[c];
- if(h == 0)
- {
- do
- {
- c = GetBits(8);
- h += (c << 2);
- }
- while(c == 255);
- }
- }
-
- *wi = w;
- *hi = h;
+void GetDimensions_X10(unsigned char* p, unsigned int* wi, unsigned int* hi,
+ bool *interlaced, bool *top_field_first, bool *repeat_field)
+{
+ unsigned int w, h, c;
+
+ const unsigned int cw[8] = {160, 176, 240, 320, 352, 640, 704, 0};
+ const unsigned int ch1[8] = {120, 132, 144, 240, 288, 480, 0, 0};
+ const unsigned int ch2[4] = {180, 360, 576, 0};
+
+ unsigned int bit_offset = 0;
+ unsigned int bit_buffer = *(unsigned int*)p;
+ bswap(bit_buffer);
+
+ GetBits(9);
+
+ *interlaced = false;
+ *top_field_first = false;
+ *repeat_field = false;
+ c = GetBits(1);
+ if (c)
+ {
+ c = GetBits(1);
+ if (c)
+ *interlaced = true;
+ c = GetBits(1);
+ if (c)
+ *top_field_first = true;
+ c = GetBits(1);
+ if (c)
+ *repeat_field = true;
+
+ c = GetBits(1);
+ c = GetBits(1);
+ if (c)
+ GetBits(2);
+ }
+
+ GetBits(16);
+
+ w = cw[GetBits(3)];
+ if(w == 0)
+ {
+ do
+ {
+ c = GetBits(8);
+ w += (c << 2);
+ }
+ while(c == 255);
+ }
+
+ c = GetBits(3);
+
+ h = ch1[c];
+ if(h == 0)
+ {
+ c = ((c << 1) | GetBits(1)) & 3;
+
+ h = ch2[c];
+ if(h == 0)
+ {
+ do
+ {
+ c = GetBits(8);
+ h += (c << 2);
+ }
+ while(c == 255);
+ }
+ }
+
+ *wi = w;
+ *hi = h;
}
void CRMFile::GetDimensions()
{
- POSITION pos = m_mps.GetHeadPosition();
- while(pos)
- {
- UINT64 filepos = GetPos();
-
- MediaProperies* pmp = m_mps.GetNext(pos);
- if(pmp->mime == "video/x-pn-realvideo")
- {
- pmp->width = pmp->height = 0;
-
- rvinfo rvi = *(rvinfo*)pmp->typeSpecData.GetData();
- rvi.bswap();
-
- if(rvi.fcc2 != '04VR' && rvi.fcc2 != '14VR')
- continue;
-
- MediaPacketHeader mph;
- while(S_OK == Read(mph))
- {
- if(mph.stream != pmp->stream || mph.len == 0
- || !(mph.flags & MediaPacketHeader::PN_KEYFRAME_FLAG))
- continue;
-
- BYTE* p = mph.pData.GetData();
- BYTE* p0 = p;
- int len = mph.pData.GetCount();
-
- BYTE hdr = *p++;
- DWORD packetlen = 0, packetoffset = 0;
-
- if((hdr & 0xc0) == 0x40)
- {
- packetlen = len - (++p - p0);
- }
- else
- {
- if((hdr & 0x40) == 0) p++;
-
-#define GetWORD(var) \
+ POSITION pos = m_mps.GetHeadPosition();
+ while(pos)
+ {
+ UINT64 filepos = GetPos();
+
+ MediaProperies* pmp = m_mps.GetNext(pos);
+ if(pmp->mime == "video/x-pn-realvideo")
+ {
+ pmp->width = pmp->height = 0;
+
+ rvinfo rvi = *(rvinfo*)pmp->typeSpecData.GetData();
+ rvi.bswap();
+
+ if(rvi.fcc2 != '04VR' && rvi.fcc2 != '14VR')
+ continue;
+
+ MediaPacketHeader mph;
+ while(S_OK == Read(mph))
+ {
+ if(mph.stream != pmp->stream || mph.len == 0
+ || !(mph.flags&MediaPacketHeader::PN_KEYFRAME_FLAG))
+ continue;
+
+ BYTE* p = mph.pData.GetData();
+ BYTE* p0 = p;
+ int len = mph.pData.GetCount();
+
+ BYTE hdr = *p++;
+ DWORD packetlen = 0, packetoffset = 0;
+
+ if((hdr&0xc0) == 0x40)
+ {
+ packetlen = len - (++p - p0);
+ }
+ else
+ {
+ if((hdr&0x40) == 0) p++;
+
+ #define GetWORD(var) \
var = (var<<8)|(*p++); \
var = (var<<8)|(*p++); \
-
- GetWORD(packetlen);
- if((packetlen & 0x4000) == 0)
- {
- GetWORD(packetlen);
- packetlen &= 0x3fffffff;
- }
- else packetlen &= 0x3fff;
-
- GetWORD(packetoffset);
- if((packetoffset & 0x4000) == 0)
- {
- GetWORD(packetoffset);
- packetoffset &= 0x3fffffff;
- }
- else packetoffset &= 0x3fff;
-
-#undef GetWORD
-
- if((hdr & 0xc0) == 0xc0) packetoffset = 0;
- else if((hdr & 0xc0) == 0x80) packetoffset = packetlen - packetoffset;
-
- p++;
- }
-
- len = min(len - (p - p0), packetlen - packetoffset);
-
- if(len > 0)
- {
- bool repeat_field;
- if(rvi.fcc2 == '14VR') ::GetDimensions_X10(p, &pmp->width, &pmp->height, &pmp->interlaced, &pmp->top_field_first, &repeat_field);
- else ::GetDimensions(p, &pmp->width, &pmp->height);
-
- if(rvi.w == pmp->width && rvi.h == pmp->height)
- pmp->width = pmp->height = 0;
-
- break;
- }
- }
- }
- Seek(filepos);
- }
+ GetWORD(packetlen);
+ if((packetlen&0x4000) == 0) {GetWORD(packetlen); packetlen &= 0x3fffffff;}
+ else packetlen &= 0x3fff;
+
+ GetWORD(packetoffset);
+ if((packetoffset&0x4000) == 0) {GetWORD(packetoffset); packetoffset &= 0x3fffffff;}
+ else packetoffset &= 0x3fff;
+
+ #undef GetWORD
+
+ if((hdr&0xc0) == 0xc0) packetoffset = 0;
+ else if((hdr&0xc0) == 0x80) packetoffset = packetlen - packetoffset;
+
+ p++;
+ }
+
+ len = min(len - (p - p0), packetlen - packetoffset);
+
+ if(len > 0)
+ {
+ bool repeat_field;
+ if(rvi.fcc2 == '14VR') ::GetDimensions_X10(p, &pmp->width, &pmp->height, &pmp->interlaced, &pmp->top_field_first, &repeat_field);
+ else ::GetDimensions(p, &pmp->width, &pmp->height);
+
+ if(rvi.w == pmp->width && rvi.h == pmp->height)
+ pmp->width = pmp->height = 0;
+
+ break;
+ }
+ }
+ }
+
+ Seek(filepos);
+ }
}
int CRMFile::GetMasterStream()
{
- int s1 = -1, s2 = -1;
+ int s1 = -1, s2 = -1;
- POSITION pos = m_mps.GetHeadPosition();
- while(pos)
- {
- MediaProperies* pmp = m_mps.GetNext(pos);
- if(pmp->mime == "video/x-pn-realvideo")
- {
- s1 = pmp->stream;
- break;
- }
- else if(pmp->mime == "audio/x-pn-realaudio" && s2 == -1) s2 = pmp->stream;
- }
+ POSITION pos = m_mps.GetHeadPosition();
+ while(pos)
+ {
+ MediaProperies* pmp = m_mps.GetNext(pos);
+ if(pmp->mime == "video/x-pn-realvideo") {s1 = pmp->stream; break;}
+ else if(pmp->mime == "audio/x-pn-realaudio" && s2 == -1) s2 = pmp->stream;
+ }
- if(s1 == -1)
- s1 = s2;
+ if(s1 == -1)
+ s1 = s2;
- return s1;
+ return s1;
}
@@ -1531,443 +1452,421 @@ int CRMFile::GetMasterStream()
//
CRealVideoDecoder::CRealVideoDecoder(LPUNKNOWN lpunk, HRESULT* phr)
- : CBaseVideoFilter(NAME("CRealVideoDecoder"), lpunk, phr, __uuidof(this))
- , m_hDrvDll(NULL)
- , m_dwCookie(0)
- , m_lastBuffSizeDim(0)
+ : CBaseVideoFilter(NAME("CRealVideoDecoder"), lpunk, phr, __uuidof(this))
+ , m_hDrvDll(NULL)
+ , m_dwCookie(0)
+ , m_lastBuffSizeDim(0)
{
}
CRealVideoDecoder::~CRealVideoDecoder()
{
- if(m_hDrvDll) FreeLibrary(m_hDrvDll);
+ if(m_hDrvDll) FreeLibrary(m_hDrvDll);
}
HRESULT CRealVideoDecoder::InitRV(const CMediaType* pmt)
{
- FreeRV();
-
- HRESULT hr = VFW_E_TYPE_NOT_ACCEPTED;
-
- rvinfo rvi = *(rvinfo*)(pmt->Format() + (pmt->formattype == FORMAT_VideoInfo ? sizeof(VIDEOINFOHEADER) : sizeof(VIDEOINFOHEADER2)));
- rvi.bswap();
-
-#pragma pack(push, 1)
- struct
- {
- WORD unk1, w, h, unk3;
- DWORD unk2, subformat, unk5, format;
- } i =
- {11, rvi.w, rvi.h, 0, 0, rvi.type1, 1, rvi.type2};
-#pragma pack(pop)
-
- if(FAILED(hr = RVInit(&i, &m_dwCookie)))
- return hr;
-
- if(rvi.fcc2 <= '03VR' && rvi.type2 >= 0x20200002)
- {
- int nWidthHeight = (1 + ((rvi.type1 >> 16) & 7));
- UINT32* pWH = DNew UINT32[nWidthHeight*2];
- pWH[0] = rvi.w;
- pWH[1] = rvi.h;
- for(int i = 2; i < nWidthHeight * 2; i++)
- pWH[i] = rvi.morewh[i-2] * 4;
-#pragma pack(push, 1)
- struct
- {
- UINT32 data1;
- UINT32 data2;
- UINT32* dimensions;
- } cmsg_data =
- {0x24, nWidthHeight, pWH};
-#pragma pack(pop)
- hr = RVCustomMessage(&cmsg_data, m_dwCookie);
- delete [] pWH;
- }
-
- return hr;
+ FreeRV();
+
+ HRESULT hr = VFW_E_TYPE_NOT_ACCEPTED;
+
+ rvinfo rvi = *(rvinfo*)(pmt->Format() + (pmt->formattype == FORMAT_VideoInfo ? sizeof(VIDEOINFOHEADER) : sizeof(VIDEOINFOHEADER2)));
+ rvi.bswap();
+
+ #pragma pack(push, 1)
+ struct {WORD unk1, w, h, unk3; DWORD unk2, subformat, unk5, format;} i =
+ {11, rvi.w, rvi.h, 0, 0, rvi.type1, 1, rvi.type2};
+ #pragma pack(pop)
+
+ if(FAILED(hr = RVInit(&i, &m_dwCookie)))
+ return hr;
+
+ if(rvi.fcc2 <= '03VR' && rvi.type2 >= 0x20200002)
+ {
+ int nWidthHeight = (1+((rvi.type1>>16)&7));
+ UINT32* pWH = DNew UINT32[nWidthHeight*2];
+ pWH[0] = rvi.w; pWH[1] = rvi.h;
+ for(int i = 2; i < nWidthHeight*2; i++)
+ pWH[i] = rvi.morewh[i-2]*4;
+ #pragma pack(push, 1)
+ struct {UINT32 data1; UINT32 data2; UINT32* dimensions;} cmsg_data =
+ {0x24, nWidthHeight, pWH};
+ #pragma pack(pop)
+ hr = RVCustomMessage(&cmsg_data, m_dwCookie);
+ delete [] pWH;
+ }
+
+ return hr;
}
void CRealVideoDecoder::FreeRV()
{
- if(m_dwCookie)
- {
- RVFree(m_dwCookie);
- m_dwCookie = 0;
- }
+ if(m_dwCookie)
+ {
+ RVFree(m_dwCookie);
+ m_dwCookie = 0;
+ }
}
HRESULT CRealVideoDecoder::Transform(IMediaSample* pIn)
{
- CAutoLock cAutoLock(&m_csReceive);
-
- HRESULT hr;
-
- BYTE* pDataIn = NULL;
- if(FAILED(hr = pIn->GetPointer(&pDataIn)))
- return hr;
-
- long len = pIn->GetActualDataLength();
- if(len <= 0) return S_OK; // nothing to do
-
- REFERENCE_TIME rtStart, rtStop;
- pIn->GetTime(&rtStart, &rtStop);
-
- rtStart += m_tStart;
-
- int offset = 1 + ((*pDataIn) + 1) * 8;
-
-#pragma pack(push, 1)
- struct
- {
- DWORD len, unk1, chunks;
- DWORD* extra;
- DWORD unk2, timestamp;
- } transform_in =
- {len - offset, 0, *pDataIn, (DWORD*)(pDataIn + 1), 0, (DWORD)(rtStart / 10000)};
- struct
- {
- DWORD unk1, unk2, timestamp, w, h;
- } transform_out =
- {0, 0, 0, 0, 0};
-#pragma pack(pop)
-
- pDataIn += offset;
-
- if(m_fDropFrames && m_timestamp + 1 == transform_in.timestamp)
- {
- m_timestamp = transform_in.timestamp;
- return S_OK;
- }
-
-
- unsigned int tmp1, tmp2;
- bool interlaced = false, tmp3, tmp4;
- ::GetDimensions_X10(pDataIn, &tmp1, &tmp2, &interlaced, &tmp3, &tmp4);
-
- int size = tmp1 * tmp2;
- if(m_lastBuffSizeDim < size)
- {
- m_pI420.Free();
- m_pI420Tmp.Free();
-
- m_lastBuffSizeDim = size;
- ATLTRACE("resize out put buff %d" , size);
- if(m_pI420.Allocate(size * 3 / 2))
- {
- ATLTRACE(" m_pI420.Allocated 1");
- memset(m_pI420, 0, size);
- ATLTRACE(" m_pI420.Allocated 2");
- memset(m_pI420 + size, 0x80, size / 2);
- ATLTRACE(" m_pI420.Allocated 3");
- }
- else
- {
- ATLTRACE(" m_pI420.Allocate fail %d" , size * 3 / 2);
- return S_OK;
- }
- if(m_pI420Tmp.Allocate(size * 3 / 2))
- {
- ATLTRACE(" m_pI420Tmp.Allocated 1");
- memset(m_pI420Tmp, 0, size);
- ATLTRACE(" m_pI420Tmp.Allocated 2");
- memset(m_pI420Tmp + size, 0x80, size / 2);
- ATLTRACE(" m_pI420Tmp.Allocated 3");
- }
- else
- {
- ATLTRACE(" m_pI420Tmp.Allocate fail %d" , size * 3 / 2);
- return S_OK;
- }
- }
-
- hr = RVTransform(pDataIn, (BYTE*)m_pI420, &transform_in, &transform_out, m_dwCookie);
-
- m_timestamp = transform_in.timestamp;
-
- if(FAILED(hr))
- {
- TRACE(_T("RV returned an error code!!!\n"));
- ASSERT(!(transform_out.unk1 & 1)); // error allowed when the "render" flag is not set
+ CAutoLock cAutoLock(&m_csReceive);
+
+ HRESULT hr;
+
+ BYTE* pDataIn = NULL;
+ if(FAILED(hr = pIn->GetPointer(&pDataIn)))
+ return hr;
+
+ long len = pIn->GetActualDataLength();
+ if(len <= 0) return S_OK; // nothing to do
+
+ REFERENCE_TIME rtStart, rtStop;
+ pIn->GetTime(&rtStart, &rtStop);
+
+ rtStart += m_tStart;
+
+ int offset = 1+((*pDataIn)+1)*8;
+
+ #pragma pack(push, 1)
+ struct {DWORD len, unk1, chunks; DWORD* extra; DWORD unk2, timestamp;} transform_in =
+ {len - offset, 0, *pDataIn, (DWORD*)(pDataIn+1), 0, (DWORD)(rtStart/10000)};
+ struct {DWORD unk1, unk2, timestamp, w, h;} transform_out =
+ {0,0,0,0,0};
+ #pragma pack(pop)
+
+ pDataIn += offset;
+
+ if(m_fDropFrames && m_timestamp+1 == transform_in.timestamp)
+ {
+ m_timestamp = transform_in.timestamp;
+ return S_OK;
+ }
+
+
+ unsigned int tmp1, tmp2;
+ bool interlaced = false, tmp3, tmp4;
+ ::GetDimensions_X10(pDataIn, &tmp1, &tmp2, &interlaced, &tmp3, &tmp4);
+
+ int size = tmp1*tmp2;
+ if( m_lastBuffSizeDim < size )
+ {
+ m_pI420.Free();
+ m_pI420Tmp.Free();
+
+ m_lastBuffSizeDim = size;
+ ATLTRACE("resize out put buff %d" ,size);
+ if ( m_pI420.Allocate(size*3/2) )
+ {
+ ATLTRACE(" m_pI420.Allocated 1" );
+ memset(m_pI420, 0, size);
+ ATLTRACE(" m_pI420.Allocated 2" );
+ memset(m_pI420 + size, 0x80, size/2);
+ ATLTRACE(" m_pI420.Allocated 3" );
+ }
+ else
+ {
+ ATLTRACE(" m_pI420.Allocate fail %d" ,size*3/2);
+ return S_OK;
+ }
+ if( m_pI420Tmp.Allocate(size*3/2) )
+ {
+ ATLTRACE(" m_pI420Tmp.Allocated 1" );
+ memset(m_pI420Tmp, 0, size);
+ ATLTRACE(" m_pI420Tmp.Allocated 2" );
+ memset(m_pI420Tmp + size, 0x80, size/2);
+ ATLTRACE(" m_pI420Tmp.Allocated 3" );
+ }
+ else
+ {
+ ATLTRACE(" m_pI420Tmp.Allocate fail %d" ,size*3/2);
+ return S_OK;
+ }
+ }
+
+ hr = RVTransform(pDataIn, (BYTE*)m_pI420, &transform_in, &transform_out, m_dwCookie);
+
+ m_timestamp = transform_in.timestamp;
+
+ if(FAILED(hr))
+ {
+ TRACE(_T("RV returned an error code!!!\n"));
+ ASSERT(!(transform_out.unk1&1)); // error allowed when the "render" flag is not set
// return hr;
- }
+ }
- if(pIn->IsPreroll() == S_OK || rtStart < 0 || !(transform_out.unk1 & 1))
- return S_OK;
+ if(pIn->IsPreroll() == S_OK || rtStart < 0 || !(transform_out.unk1&1))
+ return S_OK;
- CComPtr<IMediaSample> pOut;
- BYTE* pDataOut = NULL;
- if(/*FAILED(hr = GetDeliveryBuffer(transform_out.w, transform_out.h, &pOut)) // TODO
+ CComPtr<IMediaSample> pOut;
+ BYTE* pDataOut = NULL;
+ if(/*FAILED(hr = GetDeliveryBuffer(transform_out.w, transform_out.h, &pOut)) // TODO
&& */ FAILED(hr = GetDeliveryBuffer(m_w, m_h, &pOut))
- || FAILED(hr = pOut->GetPointer(&pDataOut)))
- return hr;
+ || FAILED(hr = pOut->GetPointer(&pDataOut)))
+ return hr;
- BYTE* pI420[3] = {m_pI420, m_pI420Tmp, NULL};
+ BYTE* pI420[3] = {m_pI420, m_pI420Tmp, NULL};
- if(interlaced)
- {
- int size = m_w * m_h;
- DeinterlaceBlend(pI420[1], pI420[0], m_w, m_h, m_w, m_w);
- DeinterlaceBlend(pI420[1] + size, pI420[0] + size, m_w / 2, m_h / 2, m_w / 2, m_w / 2);
- DeinterlaceBlend(pI420[1] + size * 5 / 4, pI420[0] + size * 5 / 4, m_w / 2, m_h / 2, m_w / 2, m_w / 2);
- pI420[2] = pI420[1], pI420[1] = pI420[0], pI420[0] = pI420[2];
- }
+ if(interlaced)
+ {
+ int size = m_w*m_h;
+ DeinterlaceBlend(pI420[1], pI420[0], m_w, m_h, m_w, m_w);
+ DeinterlaceBlend(pI420[1]+size, pI420[0]+size, m_w/2, m_h/2, m_w/2, m_w/2);
+ DeinterlaceBlend(pI420[1]+size*5/4, pI420[0]+size*5/4, m_w/2, m_h/2, m_w/2, m_w/2);
+ pI420[2] = pI420[1], pI420[1] = pI420[0], pI420[0] = pI420[2];
+ }
- if(transform_out.w != m_w || transform_out.h != m_h)
- {
- Resize(pI420[0], transform_out.w, transform_out.h, pI420[1], m_w, m_h);
- // only one of these can be true, and when it happens the result image must be in the tmp buffer
- if(transform_out.w == m_w || transform_out.h == m_h)
- pI420[2] = pI420[1], pI420[1] = pI420[0], pI420[0] = pI420[2];
- }
+ if(transform_out.w != m_w || transform_out.h != m_h)
+ {
+ Resize(pI420[0], transform_out.w, transform_out.h, pI420[1], m_w, m_h);
+ // only one of these can be true, and when it happens the result image must be in the tmp buffer
+ if(transform_out.w == m_w || transform_out.h == m_h)
+ pI420[2] = pI420[1], pI420[1] = pI420[0], pI420[0] = pI420[2];
+ }
- rtStart = 10000i64 * transform_out.timestamp - m_tStart;
- rtStop = rtStart + 1;
- pOut->SetTime(&rtStart, /*NULL*/&rtStop);
+ rtStart = 10000i64*transform_out.timestamp - m_tStart;
+ rtStop = rtStart + 1;
+ pOut->SetTime(&rtStart, /*NULL*/&rtStop);
- pOut->SetDiscontinuity(pIn->IsDiscontinuity() == S_OK);
+ pOut->SetDiscontinuity(pIn->IsDiscontinuity() == S_OK);
- CopyBuffer(pDataOut, pI420[0], m_w, m_h, m_w, MEDIASUBTYPE_I420);
+ CopyBuffer(pDataOut, pI420[0], m_w, m_h, m_w, MEDIASUBTYPE_I420);
- DbgLog((LOG_TRACE, 0, _T("V: rtStart=%I64d, rtStop=%I64d, disc=%d, sync=%d"),
- rtStart, rtStop, pOut->IsDiscontinuity() == S_OK, pOut->IsSyncPoint() == S_OK));
+DbgLog((LOG_TRACE, 0, _T("V: rtStart=%I64d, rtStop=%I64d, disc=%d, sync=%d"),
+ rtStart, rtStop, pOut->IsDiscontinuity() == S_OK, pOut->IsSyncPoint() == S_OK));
- return m_pOutput->Deliver(pOut);
+ return m_pOutput->Deliver(pOut);
}
void CRealVideoDecoder::Resize(BYTE* pIn, DWORD wi, DWORD hi, BYTE* pOut, DWORD wo, DWORD ho)
{
- int si = wi * hi, so = wo * ho;
- ASSERT(((si * so) & 3) == 0);
-
- if(wi < wo)
- {
- ResizeWidth(pIn, wi, hi, pOut, wo, ho);
- ResizeWidth(pIn + si, wi / 2, hi / 2, pOut + so, wo / 2, ho / 2);
- ResizeWidth(pIn + si + si / 4, wi / 2, hi / 2, pOut + so + so / 4, wo / 2, ho / 2);
- if(hi == ho) return;
- ResizeHeight(pOut, wo, hi, pIn, wo, ho);
- ResizeHeight(pOut + so, wo / 2, hi / 2, pIn + so, wo / 2, ho / 2);
- ResizeHeight(pOut + so + so / 4, wo / 2, hi / 2, pIn + so + so / 4, wo / 2, ho / 2);
- }
- else if(hi < ho)
- {
- ResizeHeight(pIn, wi, hi, pOut, wo, ho);
- ResizeHeight(pIn + si, wi / 2, hi / 2, pOut + so, wo / 2, ho / 2);
- ResizeHeight(pIn + si + si / 4, wi / 2, hi / 2, pOut + so + so / 4, wo / 2, ho / 2);
- if(wi == wo) return;
- ASSERT(0); // this is uncreachable code, but anyway... looks nice being so symmetric
- ResizeWidth(pOut, wi, ho, pIn, wo, ho);
- ResizeWidth(pOut + so, wi / 2, ho / 2, pIn + so, wo / 2, ho / 2);
- ResizeWidth(pOut + so + so / 4, wi / 2, ho / 2, pIn + so + so / 4, wo / 2, ho / 2);
- }
+ int si = wi*hi, so = wo*ho;
+ ASSERT(((si*so)&3) == 0);
+
+ if(wi < wo)
+ {
+ ResizeWidth(pIn, wi, hi, pOut, wo, ho);
+ ResizeWidth(pIn + si, wi/2, hi/2, pOut + so, wo/2, ho/2);
+ ResizeWidth(pIn + si + si/4, wi/2, hi/2, pOut + so + so/4, wo/2, ho/2);
+ if(hi == ho) return;
+ ResizeHeight(pOut, wo, hi, pIn, wo, ho);
+ ResizeHeight(pOut + so, wo/2, hi/2, pIn + so, wo/2, ho/2);
+ ResizeHeight(pOut + so + so/4, wo/2, hi/2, pIn + so + so/4, wo/2, ho/2);
+ }
+ else if(hi < ho)
+ {
+ ResizeHeight(pIn, wi, hi, pOut, wo, ho);
+ ResizeHeight(pIn + si, wi/2, hi/2, pOut + so, wo/2, ho/2);
+ ResizeHeight(pIn + si + si/4, wi/2, hi/2, pOut + so + so/4, wo/2, ho/2);
+ if(wi == wo) return;
+ ASSERT(0); // this is uncreachable code, but anyway... looks nice being so symmetric
+ ResizeWidth(pOut, wi, ho, pIn, wo, ho);
+ ResizeWidth(pOut + so, wi/2, ho/2, pIn + so, wo/2, ho/2);
+ ResizeWidth(pOut + so + so/4, wi/2, ho/2, pIn + so + so/4, wo/2, ho/2);
+ }
}
void CRealVideoDecoder::ResizeWidth(BYTE* pIn, DWORD wi, DWORD hi, BYTE* pOut, DWORD wo, DWORD ho)
{
- for(DWORD y = 0; y < hi; y++, pIn += wi, pOut += wo)
- {
- if(wi == wo) memcpy(pOut, pIn, wo);
- else ResizeRow(pIn, wi, 1, pOut, wo, 1);
- }
+ for(DWORD y = 0; y < hi; y++, pIn += wi, pOut += wo)
+ {
+ if(wi == wo) memcpy(pOut, pIn, wo);
+ else ResizeRow(pIn, wi, 1, pOut, wo, 1);
+ }
}
void CRealVideoDecoder::ResizeHeight(BYTE* pIn, DWORD wi, DWORD hi, BYTE* pOut, DWORD wo, DWORD ho)
{
- if(hi == ho)
- {
- memcpy(pOut, pIn, wo * ho);
- }
- else
- {
- for(DWORD x = 0; x < wo; x++, pIn++, pOut++)
- ResizeRow(pIn, hi, wo, pOut, ho, wo);
- }
+ if(hi == ho)
+ {
+ memcpy(pOut, pIn, wo*ho);
+ }
+ else
+ {
+ for(DWORD x = 0; x < wo; x++, pIn++, pOut++)
+ ResizeRow(pIn, hi, wo, pOut, ho, wo);
+ }
}
void CRealVideoDecoder::ResizeRow(BYTE* pIn, DWORD wi, DWORD dpi, BYTE* pOut, DWORD wo, DWORD dpo)
{
- ASSERT(wi < wo);
+ ASSERT(wi < wo);
if(dpo == 1)
- {
- for(DWORD i = 0, j = 0, dj = (wi << 16) / wo; i < wo - 1; i++, pOut++, j += dj)
+ {
+ for(DWORD i = 0, j = 0, dj = (wi<<16)/wo; i < wo-1; i++, pOut++, j += dj)
// pOut[i] = pIn[j>>16];
- {
- BYTE* p = &pIn[j>>16];
- DWORD jf = j & 0xffff;
- *pOut = ((p[0] * (0xffff - jf) + p[1] * jf) + 0x7fff) >> 16;
- }
-
- *pOut = pIn[wi-1];
- }
- else
- {
- for(DWORD i = 0, j = 0, dj = (wi << 16) / wo; i < wo - 1; i++, pOut += dpo, j += dj)
+ {
+ BYTE* p = &pIn[j>>16];
+ DWORD jf = j&0xffff;
+ *pOut = ((p[0]*(0xffff-jf) + p[1]*jf) + 0x7fff) >> 16;
+ }
+
+ *pOut = pIn[wi-1];
+ }
+ else
+ {
+ for(DWORD i = 0, j = 0, dj = (wi<<16)/wo; i < wo-1; i++, pOut += dpo, j += dj)
// *pOut = pIn[dpi*(j>>16)];
- {
- BYTE* p = &pIn[dpi*(j>>16)];
- DWORD jf = j & 0xffff;
- *pOut = ((p[0] * (0xffff - jf) + p[dpi] * jf) + 0x7fff) >> 16;
- }
-
- *pOut = pIn[dpi*(wi-1)];
- }
+ {
+ BYTE* p = &pIn[dpi*(j>>16)];
+ DWORD jf = j&0xffff;
+ *pOut = ((p[0]*(0xffff-jf) + p[dpi]*jf) + 0x7fff) >> 16;
+ }
+
+ *pOut = pIn[dpi*(wi-1)];
+ }
}
HRESULT CRealVideoDecoder::CheckInputType(const CMediaType* mtIn)
{
- if(mtIn->majortype != MEDIATYPE_Video
- || mtIn->subtype != MEDIASUBTYPE_RV20
- && mtIn->subtype != MEDIASUBTYPE_RV30
- && mtIn->subtype != MEDIASUBTYPE_RV40
- && mtIn->subtype != MEDIASUBTYPE_RV41)
- return VFW_E_TYPE_NOT_ACCEPTED;
-
- if(mtIn->formattype == FORMAT_VideoInfo2)
- {
- VIDEOINFOHEADER2* vih2 = (VIDEOINFOHEADER2*)mtIn->Format();
- if(vih2->dwPictAspectRatioX < vih2->bmiHeader.biWidth
- || vih2->dwPictAspectRatioY < vih2->bmiHeader.biHeight)
- return VFW_E_TYPE_NOT_ACCEPTED;
- }
-
- if(!m_pInput->IsConnected())
- {
- if(m_hDrvDll)
- {
- FreeLibrary(m_hDrvDll);
- m_hDrvDll = NULL;
- }
-
- CAtlList<CString> paths;
- CString olddll, newdll, oldpath, newpath;
-
- olddll.Format(_T("drv%c3260.dll"), (TCHAR)((mtIn->subtype.Data1 >> 16) & 0xff));
- newdll =
- mtIn->subtype == FOURCCMap('14VR') ? _T("drvi.dll") :
- mtIn->subtype == FOURCCMap('02VR') ? _T("drv2.dll") :
- _T("drvc.dll");
-
- CRegKey key;
- TCHAR buff[_MAX_PATH];
- ULONG len = sizeof(buff);
- if(ERROR_SUCCESS == key.Open(HKEY_CLASSES_ROOT, _T("Software\\RealNetworks\\Preferences\\DT_Codecs"), KEY_READ)
- && ERROR_SUCCESS == key.QueryStringValue(NULL, buff, &len) && _tcslen(buff) > 0)
- {
- oldpath = buff;
- TCHAR c = oldpath[oldpath.GetLength()-1];
- if(c != '\\' && c != '/') oldpath += '\\';
- key.Close();
- }
- len = sizeof(buff);
- if(ERROR_SUCCESS == key.Open(HKEY_CLASSES_ROOT, _T("Helix\\HelixSDK\\10.0\\Preferences\\DT_Codecs"), KEY_READ)
- && ERROR_SUCCESS == key.QueryStringValue(NULL, buff, &len) && _tcslen(buff) > 0)
- {
- newpath = buff;
- TCHAR c = newpath[newpath.GetLength()-1];
- if(c != '\\' && c != '/') newpath += '\\';
- key.Close();
- }
-
- if(!newpath.IsEmpty()) paths.AddTail(newpath + newdll);
- if(!oldpath.IsEmpty()) paths.AddTail(oldpath + newdll);
- paths.AddTail(newdll); // default dll paths
- if(!newpath.IsEmpty()) paths.AddTail(newpath + olddll);
- if(!oldpath.IsEmpty()) paths.AddTail(oldpath + olddll);
- paths.AddTail(olddll); // default dll paths
-
- POSITION pos = paths.GetHeadPosition();
- while(pos && !(m_hDrvDll = LoadLibrary(paths.GetNext(pos))));
-
- if(m_hDrvDll)
- {
- RVCustomMessage = (PRVCustomMessage)GetProcAddress(m_hDrvDll, "RV20toYUV420CustomMessage");
- RVFree = (PRVFree)GetProcAddress(m_hDrvDll, "RV20toYUV420Free");
- RVHiveMessage = (PRVHiveMessage)GetProcAddress(m_hDrvDll, "RV20toYUV420HiveMessage");
- RVInit = (PRVInit)GetProcAddress(m_hDrvDll, "RV20toYUV420Init");
- RVTransform = (PRVTransform)GetProcAddress(m_hDrvDll, "RV20toYUV420Transform");
-
- if(!RVCustomMessage) RVCustomMessage = (PRVCustomMessage)GetProcAddress(m_hDrvDll, "RV40toYUV420CustomMessage");
- if(!RVFree) RVFree = (PRVFree)GetProcAddress(m_hDrvDll, "RV40toYUV420Free");
- if(!RVHiveMessage) RVHiveMessage = (PRVHiveMessage)GetProcAddress(m_hDrvDll, "RV40toYUV420HiveMessage");
- if(!RVInit) RVInit = (PRVInit)GetProcAddress(m_hDrvDll, "RV40toYUV420Init");
- if(!RVTransform) RVTransform = (PRVTransform)GetProcAddress(m_hDrvDll, "RV40toYUV420Transform");
- }
-
- if(!m_hDrvDll || !RVCustomMessage
- || !RVFree || !RVHiveMessage
- || !RVInit || !RVTransform)
- return VFW_E_TYPE_NOT_ACCEPTED;
-
- if(FAILED(InitRV(mtIn)))
- return VFW_E_TYPE_NOT_ACCEPTED;
- }
-
- return S_OK;
+ if(mtIn->majortype != MEDIATYPE_Video
+ || mtIn->subtype != MEDIASUBTYPE_RV20
+ && mtIn->subtype != MEDIASUBTYPE_RV30
+ && mtIn->subtype != MEDIASUBTYPE_RV40
+ && mtIn->subtype != MEDIASUBTYPE_RV41)
+ return VFW_E_TYPE_NOT_ACCEPTED;
+
+ if(mtIn->formattype == FORMAT_VideoInfo2)
+ {
+ VIDEOINFOHEADER2* vih2 = (VIDEOINFOHEADER2*)mtIn->Format();
+ if(vih2->dwPictAspectRatioX < vih2->bmiHeader.biWidth
+ || vih2->dwPictAspectRatioY < vih2->bmiHeader.biHeight)
+ return VFW_E_TYPE_NOT_ACCEPTED;
+ }
+
+ if(!m_pInput->IsConnected())
+ {
+ if(m_hDrvDll) {FreeLibrary(m_hDrvDll); m_hDrvDll = NULL;}
+
+ CAtlList<CString> paths;
+ CString olddll, newdll, oldpath, newpath;
+
+ olddll.Format(_T("drv%c3260.dll"), (TCHAR)((mtIn->subtype.Data1>>16)&0xff));
+ newdll =
+ mtIn->subtype == FOURCCMap('14VR') ? _T("drvi.dll") :
+ mtIn->subtype == FOURCCMap('02VR') ? _T("drv2.dll") :
+ _T("drvc.dll");
+
+ CRegKey key;
+ TCHAR buff[_MAX_PATH];
+ ULONG len = sizeof(buff);
+ if(ERROR_SUCCESS == key.Open(HKEY_CLASSES_ROOT, _T("Software\\RealNetworks\\Preferences\\DT_Codecs"), KEY_READ)
+ && ERROR_SUCCESS == key.QueryStringValue(NULL, buff, &len) && _tcslen(buff) > 0)
+ {
+ oldpath = buff;
+ TCHAR c = oldpath[oldpath.GetLength()-1];
+ if(c != '\\' && c != '/') oldpath += '\\';
+ key.Close();
+ }
+ len = sizeof(buff);
+ if(ERROR_SUCCESS == key.Open(HKEY_CLASSES_ROOT, _T("Helix\\HelixSDK\\10.0\\Preferences\\DT_Codecs"), KEY_READ)
+ && ERROR_SUCCESS == key.QueryStringValue(NULL, buff, &len) && _tcslen(buff) > 0)
+ {
+ newpath = buff;
+ TCHAR c = newpath[newpath.GetLength()-1];
+ if(c != '\\' && c != '/') newpath += '\\';
+ key.Close();
+ }
+
+ if(!newpath.IsEmpty()) paths.AddTail(newpath + newdll);
+ if(!oldpath.IsEmpty()) paths.AddTail(oldpath + newdll);
+ paths.AddTail(newdll); // default dll paths
+ if(!newpath.IsEmpty()) paths.AddTail(newpath + olddll);
+ if(!oldpath.IsEmpty()) paths.AddTail(oldpath + olddll);
+ paths.AddTail(olddll); // default dll paths
+
+ POSITION pos = paths.GetHeadPosition();
+ while(pos && !(m_hDrvDll = LoadLibrary(paths.GetNext(pos))));
+
+ if(m_hDrvDll)
+ {
+ RVCustomMessage = (PRVCustomMessage)GetProcAddress(m_hDrvDll, "RV20toYUV420CustomMessage");
+ RVFree = (PRVFree)GetProcAddress(m_hDrvDll, "RV20toYUV420Free");
+ RVHiveMessage = (PRVHiveMessage)GetProcAddress(m_hDrvDll, "RV20toYUV420HiveMessage");
+ RVInit = (PRVInit)GetProcAddress(m_hDrvDll, "RV20toYUV420Init");
+ RVTransform = (PRVTransform)GetProcAddress(m_hDrvDll, "RV20toYUV420Transform");
+
+ if(!RVCustomMessage) RVCustomMessage = (PRVCustomMessage)GetProcAddress(m_hDrvDll, "RV40toYUV420CustomMessage");
+ if(!RVFree) RVFree = (PRVFree)GetProcAddress(m_hDrvDll, "RV40toYUV420Free");
+ if(!RVHiveMessage) RVHiveMessage = (PRVHiveMessage)GetProcAddress(m_hDrvDll, "RV40toYUV420HiveMessage");
+ if(!RVInit) RVInit = (PRVInit)GetProcAddress(m_hDrvDll, "RV40toYUV420Init");
+ if(!RVTransform) RVTransform = (PRVTransform)GetProcAddress(m_hDrvDll, "RV40toYUV420Transform");
+ }
+
+ if(!m_hDrvDll || !RVCustomMessage
+ || !RVFree || !RVHiveMessage
+ || !RVInit || !RVTransform)
+ return VFW_E_TYPE_NOT_ACCEPTED;
+
+ if(FAILED(InitRV(mtIn)))
+ return VFW_E_TYPE_NOT_ACCEPTED;
+ }
+
+ return S_OK;
}
HRESULT CRealVideoDecoder::CheckTransform(const CMediaType* mtIn, const CMediaType* mtOut)
{
- if(m_pOutput && m_pOutput->IsConnected())
- {
- BITMAPINFOHEADER bih1, bih2;
- if(ExtractBIH(mtOut, &bih1) && ExtractBIH(&m_pOutput->CurrentMediaType(), &bih2)
- && abs(bih1.biHeight) != abs(bih2.biHeight))
- return VFW_E_TYPE_NOT_ACCEPTED;
- }
+ if(m_pOutput && m_pOutput->IsConnected())
+ {
+ BITMAPINFOHEADER bih1, bih2;
+ if(ExtractBIH(mtOut, &bih1) && ExtractBIH(&m_pOutput->CurrentMediaType(), &bih2)
+ && abs(bih1.biHeight) != abs(bih2.biHeight))
+ return VFW_E_TYPE_NOT_ACCEPTED;
+ }
- return __super::CheckTransform(mtIn, mtOut);
+ return __super::CheckTransform(mtIn, mtOut);
}
HRESULT CRealVideoDecoder::StartStreaming()
{
- const CMediaType& mt = m_pInput->CurrentMediaType();
- if(FAILED(InitRV(&mt)))
- return E_FAIL;
+ const CMediaType& mt = m_pInput->CurrentMediaType();
+ if(FAILED(InitRV(&mt)))
+ return E_FAIL;
- int size = m_w * m_h;
- m_lastBuffSizeDim = size;
- m_pI420.Allocate(size * 3 / 2);
- memset(m_pI420, 0, size);
- memset(m_pI420 + size, 0x80, size / 2);
- m_pI420Tmp.Allocate(size * 3 / 2);
- memset(m_pI420Tmp, 0, size);
- memset(m_pI420Tmp + size, 0x80, size / 2);
+ int size = m_w*m_h;
+ m_lastBuffSizeDim = size;
+ m_pI420.Allocate(size*3/2);
+ memset(m_pI420, 0, size);
+ memset(m_pI420 + size, 0x80, size/2);
+ m_pI420Tmp.Allocate(size*3/2);
+ memset(m_pI420Tmp, 0, size);
+ memset(m_pI420Tmp + size, 0x80, size/2);
- return __super::StartStreaming();
+ return __super::StartStreaming();
}
HRESULT CRealVideoDecoder::StopStreaming()
{
- m_pI420.Free();
- m_pI420Tmp.Free();
+ m_pI420.Free();
+ m_pI420Tmp.Free();
- FreeRV();
+ FreeRV();
- return __super::StopStreaming();
+ return __super::StopStreaming();
}
HRESULT CRealVideoDecoder::NewSegment(REFERENCE_TIME tStart, REFERENCE_TIME tStop, double dRate)
{
- CAutoLock cAutoLock(&m_csReceive);
+ CAutoLock cAutoLock(&m_csReceive);
- m_timestamp = ~0;
- m_fDropFrames = false;
+ m_timestamp = ~0;
+ m_fDropFrames = false;
- DWORD tmp[2] = {20, 0};
- RVHiveMessage(tmp, m_dwCookie);
+ DWORD tmp[2] = {20, 0};
+ RVHiveMessage(tmp, m_dwCookie);
- m_tStart = tStart;
- return __super::NewSegment(tStart, tStop, dRate);
+ m_tStart = tStart;
+ return __super::NewSegment(tStart, tStop, dRate);
}
HRESULT CRealVideoDecoder::AlterQuality(Quality q)
{
- if(q.Late > 500 * 10000i64) m_fDropFrames = true;
- if(q.Late <= 0) m_fDropFrames = false;
+ if(q.Late > 500*10000i64) m_fDropFrames = true;
+ if(q.Late <= 0) m_fDropFrames = false;
// TRACE(_T("CRealVideoDecoder::AlterQuality: Type=%d, Proportion=%d, Late=%I64d, TimeStamp=%I64d\n"), q.Type, q.Proportion, q.Late, q.TimeStamp);
- return E_NOTIMPL;
+ return E_NOTIMPL;
}
/////////////////////////
@@ -1977,543 +1876,518 @@ HRESULT CRealVideoDecoder::AlterQuality(Quality q)
//
CRealAudioDecoder::CRealAudioDecoder(LPUNKNOWN lpunk, HRESULT* phr)
- : CTransformFilter(NAME("CRealAudioDecoder"), lpunk, __uuidof(this))
- , m_hDrvDll(NULL)
- , m_dwCookie(0)
+ : CTransformFilter(NAME("CRealAudioDecoder"), lpunk, __uuidof(this))
+ , m_hDrvDll(NULL)
+ , m_dwCookie(0)
{
- if(phr) *phr = S_OK;
+ if(phr) *phr = S_OK;
}
CRealAudioDecoder::~CRealAudioDecoder()
{
// FreeRA();
- if(m_hDrvDll) FreeLibrary(m_hDrvDll);
+ if(m_hDrvDll) FreeLibrary(m_hDrvDll);
}
HRESULT CRealAudioDecoder::InitRA(const CMediaType* pmt)
{
- FreeRA();
-
- HRESULT hr;
-
- if(RAOpenCodec2 && FAILED(hr = RAOpenCodec2(&m_dwCookie, m_dllpath))
- || RAOpenCodec && FAILED(hr = RAOpenCodec(&m_dwCookie)))
- return VFW_E_TYPE_NOT_ACCEPTED;
-
- WAVEFORMATEX* pwfe = (WAVEFORMATEX*)pmt->Format();
-
- // someone might be doing cbSize = sizeof(WAVEFORMATEX), chances of
- // cbSize being really sizeof(WAVEFORMATEX) is less than this,
- // especially with our rm splitter ;)
- DWORD cbSize = pwfe->cbSize;
- if(cbSize == sizeof(WAVEFORMATEX))
- {
- ASSERT(0);
- cbSize = 0;
- }
-
- WORD wBitsPerSample = pwfe->wBitsPerSample;
- if(!wBitsPerSample) wBitsPerSample = 16;
-
-#pragma pack(push, 1)
- struct
- {
- DWORD freq;
- WORD bpsample, channels, quality;
- DWORD bpframe, packetsize, extralen;
- void* extra;
- } initdata =
- {
- pwfe->nSamplesPerSec, wBitsPerSample, pwfe->nChannels, 100,
- 0, 0, 0, NULL
- };
-#pragma pack(pop)
-
- CAutoVectorPtr<BYTE> pBuff;
-
- if(pmt->subtype == MEDIASUBTYPE_AAC)
- {
- pBuff.Allocate(cbSize + 1);
- pBuff[0] = 0x02;
- memcpy(pBuff + 1, pwfe + 1, cbSize);
- initdata.extralen = cbSize + 1;
- initdata.extra = pBuff;
- }
- else
- {
- if(pmt->FormatLength() <= sizeof(WAVEFORMATEX) + cbSize) // must have type_specific_data appended
- return VFW_E_TYPE_NOT_ACCEPTED;
-
- BYTE* fmt = pmt->Format() + sizeof(WAVEFORMATEX) + cbSize;
-
- for(int i = 0, len = pmt->FormatLength() - (sizeof(WAVEFORMATEX) + cbSize); i < len - 4; i++, fmt++)
- {
- if(fmt[0] == '.' || fmt[1] == 'r' || fmt[2] == 'a')
- break;
- }
-
- m_rai = *(rainfo*)fmt;
- m_rai.bswap();
-
- BYTE* p;
-
- if(m_rai.version2 == 4)
- {
- p = (BYTE*)((rainfo4*)fmt + 1);
- int len = *p++;
- p += len;
- len = *p++;
- p += len;
- ASSERT(len == 4);
- }
- else if(m_rai.version2 == 5)
- {
- p = (BYTE*)((rainfo5*)fmt + 1);
- }
- else
- {
- return VFW_E_TYPE_NOT_ACCEPTED;
- }
-
- p += 3;
- if(m_rai.version2 == 5) p++;
-
- initdata.bpframe = m_rai.sub_packet_size;
- initdata.packetsize = m_rai.coded_frame_size;
- initdata.extralen = min((pmt->Format() + pmt->FormatLength()) - (p + 4), *(DWORD*)p);
- initdata.extra = p + 4;
- }
-
- if(FAILED(hr = RAInitDecoder(m_dwCookie, &initdata)))
- return VFW_E_TYPE_NOT_ACCEPTED;
-
- if(RASetPwd)
- RASetPwd(m_dwCookie, "Ardubancel Quazanga");
-
- if(RASetFlavor && FAILED(hr = RASetFlavor(m_dwCookie, m_rai.flavor)))
- return VFW_E_TYPE_NOT_ACCEPTED;
-
- return S_OK;
+ FreeRA();
+
+ HRESULT hr;
+
+ if(RAOpenCodec2 && FAILED(hr = RAOpenCodec2(&m_dwCookie, m_dllpath))
+ || RAOpenCodec && FAILED(hr = RAOpenCodec(&m_dwCookie)))
+ return VFW_E_TYPE_NOT_ACCEPTED;
+
+ WAVEFORMATEX* pwfe = (WAVEFORMATEX*)pmt->Format();
+
+ // someone might be doing cbSize = sizeof(WAVEFORMATEX), chances of
+ // cbSize being really sizeof(WAVEFORMATEX) is less than this,
+ // especially with our rm splitter ;)
+ DWORD cbSize = pwfe->cbSize;
+ if(cbSize == sizeof(WAVEFORMATEX)) {ASSERT(0); cbSize = 0;}
+
+ WORD wBitsPerSample = pwfe->wBitsPerSample;
+ if(!wBitsPerSample) wBitsPerSample = 16;
+
+ #pragma pack(push, 1)
+ struct {DWORD freq; WORD bpsample, channels, quality; DWORD bpframe, packetsize, extralen; void* extra;} initdata =
+ {pwfe->nSamplesPerSec, wBitsPerSample, pwfe->nChannels, 100,
+ 0, 0, 0, NULL};
+ #pragma pack(pop)
+
+ CAutoVectorPtr<BYTE> pBuff;
+
+ if(pmt->subtype == MEDIASUBTYPE_AAC)
+ {
+ pBuff.Allocate(cbSize+1);
+ pBuff[0] = 0x02;
+ memcpy(pBuff+1, pwfe+1, cbSize);
+ initdata.extralen = cbSize+1;
+ initdata.extra = pBuff;
+ }
+ else
+ {
+ if(pmt->FormatLength() <= sizeof(WAVEFORMATEX) + cbSize) // must have type_specific_data appended
+ return VFW_E_TYPE_NOT_ACCEPTED;
+
+ BYTE* fmt = pmt->Format() + sizeof(WAVEFORMATEX) + cbSize;
+
+ for(int i = 0, len = pmt->FormatLength() - (sizeof(WAVEFORMATEX) + cbSize); i < len-4; i++, fmt++)
+ {
+ if(fmt[0] == '.' || fmt[1] == 'r' || fmt[2] == 'a')
+ break;
+ }
+
+ m_rai = *(rainfo*)fmt;
+ m_rai.bswap();
+
+ BYTE* p;
+
+ if(m_rai.version2 == 4)
+ {
+ p = (BYTE*)((rainfo4*)fmt+1);
+ int len = *p++; p += len; len = *p++; p += len;
+ ASSERT(len == 4);
+ }
+ else if(m_rai.version2 == 5)
+ {
+ p = (BYTE*)((rainfo5*)fmt+1);
+ }
+ else
+ {
+ return VFW_E_TYPE_NOT_ACCEPTED;
+ }
+
+ p += 3;
+ if(m_rai.version2 == 5) p++;
+
+ initdata.bpframe = m_rai.sub_packet_size;
+ initdata.packetsize = m_rai.coded_frame_size;
+ initdata.extralen = min((pmt->Format() + pmt->FormatLength()) - (p + 4), *(DWORD*)p);
+ initdata.extra = p + 4;
+ }
+
+ if(FAILED(hr = RAInitDecoder(m_dwCookie, &initdata)))
+ return VFW_E_TYPE_NOT_ACCEPTED;
+
+ if(RASetPwd)
+ RASetPwd(m_dwCookie, "Ardubancel Quazanga");
+
+ if(RASetFlavor && FAILED(hr = RASetFlavor(m_dwCookie, m_rai.flavor)))
+ return VFW_E_TYPE_NOT_ACCEPTED;
+
+ return S_OK;
}
void CRealAudioDecoder::FreeRA()
{
- if(m_dwCookie)
- {
- RAFreeDecoder(m_dwCookie);
- RACloseCodec(m_dwCookie);
- m_dwCookie = 0;
- }
+ if(m_dwCookie)
+ {
+ RAFreeDecoder(m_dwCookie);
+ RACloseCodec(m_dwCookie);
+ m_dwCookie = 0;
+ }
}
HRESULT CRealAudioDecoder::Receive(IMediaSample* pIn)
{
- CAutoLock cAutoLock(&m_csReceive);
+ CAutoLock cAutoLock(&m_csReceive);
- HRESULT hr;
+ HRESULT hr;
AM_SAMPLE2_PROPERTIES* const pProps = m_pInput->SampleProps();
if(pProps->dwStreamId != AM_STREAM_MEDIA)
- return m_pOutput->Deliver(pIn);
-
- BYTE* pDataIn = NULL;
- if(FAILED(hr = pIn->GetPointer(&pDataIn))) return hr;
- BYTE* pDataInOrg = pDataIn;
-
- long len = pIn->GetActualDataLength();
- if(len <= 0) return S_OK;
-
- REFERENCE_TIME rtStart, rtStop;
- pIn->GetTime(&rtStart, &rtStop);
- /*
- if(pIn->IsPreroll() == S_OK || rtStart < 0)
- return S_OK;
- */
- //
-
- if(S_OK == pIn->IsSyncPoint())
- {
- m_bufflen = 0;
- m_rtBuffStart = rtStart;
- m_fBuffDiscontinuity = pIn->IsDiscontinuity() == S_OK;
- }
-
- BYTE* src = NULL;
- BYTE* dst = NULL;
-
- int w = m_rai.coded_frame_size;
- int h = m_rai.sub_packet_h;
- int sps = m_rai.sub_packet_size;
-
- if(m_pInput->CurrentMediaType().subtype == MEDIASUBTYPE_RAAC
- || m_pInput->CurrentMediaType().subtype == MEDIASUBTYPE_RACP
- || m_pInput->CurrentMediaType().subtype == MEDIASUBTYPE_AAC)
- {
- src = pDataIn;
- dst = pDataIn + len;
- w = len;
- }
- else
- {
- memcpy(&m_buff[m_bufflen], pDataIn, len);
- m_bufflen += len;
-
- len = w * h;
-
- if(m_bufflen >= len)
- {
- ASSERT(m_bufflen == len);
-
- src = m_buff;
- dst = m_buff + len;
-
- if(sps > 0
- && (m_pInput->CurrentMediaType().subtype == MEDIASUBTYPE_COOK
- || m_pInput->CurrentMediaType().subtype == MEDIASUBTYPE_ATRC))
- {
- for(int y = 0; y < h; y++)
- {
- for(int x = 0, w2 = w / sps; x < w2; x++)
- {
- // TRACE(_T("--- %d, %d\n"), (h*x+((h+1)/2)*(y&1)+(y>>1)), sps*(h*x+((h+1)/2)*(y&1)+(y>>1)));
- memcpy(dst + sps*(h * x + ((h + 1) / 2)*(y & 1) + (y >> 1)), src, sps);
- src += sps;
- }
- }
-
- src = m_buff + len;
- dst = m_buff + len * 2;
- }
- else if(m_pInput->CurrentMediaType().subtype == MEDIASUBTYPE_SIPR)
- {
- // http://mplayerhq.hu/pipermail/mplayer-dev-eng/2002-August/010569.html
-
- static BYTE sipr_swaps[38][2] =
- {
- {0, 63}, {1, 22}, {2, 44}, {3, 90}, {5, 81}, {7, 31}, {8, 86}, {9, 58}, {10, 36}, {12, 68},
- {13, 39}, {14, 73}, {15, 53}, {16, 69}, {17, 57}, {19, 88}, {20, 34}, {21, 71}, {24, 46},
- {25, 94}, {26, 54}, {28, 75}, {29, 50}, {32, 70}, {33, 92}, {35, 74}, {38, 85}, {40, 56},
- {42, 87}, {43, 65}, {45, 59}, {48, 79}, {49, 93}, {51, 89}, {55, 95}, {61, 76}, {67, 83},
- {77, 80}
- };
-
- int bs = h * w * 2 / 96; // nibbles per subpacket
- for(int n = 0; n < 38; n++)
- {
- int i = bs * sipr_swaps[n][0];
- int o = bs * sipr_swaps[n][1];
- // swap nibbles of block 'i' with 'o' TODO: optimize
- for(int j = 0; j < bs; j++)
- {
- int x = (i & 1) ? (src[(i>>1)] >> 4) : (src[(i>>1)] & 15);
- int y = (o & 1) ? (src[(o>>1)] >> 4) : (src[(o>>1)] & 15);
- if(o & 1) src[(o>>1)] = (src[(o>>1)] & 0x0F) | (x << 4);
- else src[(o>>1)] = (src[(o>>1)] & 0xF0) | x;
- if(i & 1) src[(i>>1)] = (src[(i>>1)] & 0x0F) | (y << 4);
- else src[(i>>1)] = (src[(i>>1)] & 0xF0) | y;
- ++i;
- ++o;
- }
- }
- }
+ return m_pOutput->Deliver(pIn);
+
+ BYTE* pDataIn = NULL;
+ if(FAILED(hr = pIn->GetPointer(&pDataIn))) return hr;
+ BYTE* pDataInOrg = pDataIn;
+
+ long len = pIn->GetActualDataLength();
+ if(len <= 0) return S_OK;
- m_bufflen = 0;
- }
- }
-
- rtStart = m_rtBuffStart;
-
- for(; src < dst; src += w)
- {
- CComPtr<IMediaSample> pOut;
- BYTE* pDataOut = NULL;
- if(FAILED(hr = m_pOutput->GetDeliveryBuffer(&pOut, NULL, NULL, 0))
- || FAILED(hr = pOut->GetPointer(&pDataOut)))
- return hr;
-
- AM_MEDIA_TYPE* pmt;
- if(SUCCEEDED(pOut->GetMediaType(&pmt)) && pmt)
- {
- CMediaType mt(*pmt);
- m_pOutput->SetMediaType(&mt);
- DeleteMediaType(pmt);
- }
-
- hr = RADecode(m_dwCookie, src, w, pDataOut, &len, -1);
-
- if(FAILED(hr))
- {
- TRACE(_T("RA returned an error code!!!\n"));
- continue;
+ REFERENCE_TIME rtStart, rtStop;
+ pIn->GetTime(&rtStart, &rtStop);
+/*
+ if(pIn->IsPreroll() == S_OK || rtStart < 0)
+ return S_OK;
+*/
+ //
+
+ if(S_OK == pIn->IsSyncPoint())
+ {
+ m_bufflen = 0;
+ m_rtBuffStart = rtStart;
+ m_fBuffDiscontinuity = pIn->IsDiscontinuity() == S_OK;
+ }
+
+ BYTE* src = NULL;
+ BYTE* dst = NULL;
+
+ int w = m_rai.coded_frame_size;
+ int h = m_rai.sub_packet_h;
+ int sps = m_rai.sub_packet_size;
+
+ if(m_pInput->CurrentMediaType().subtype == MEDIASUBTYPE_RAAC
+ || m_pInput->CurrentMediaType().subtype == MEDIASUBTYPE_RACP
+ || m_pInput->CurrentMediaType().subtype == MEDIASUBTYPE_AAC)
+ {
+ src = pDataIn;
+ dst = pDataIn + len;
+ w = len;
+ }
+ else
+ {
+ memcpy(&m_buff[m_bufflen], pDataIn, len);
+ m_bufflen += len;
+
+ len = w*h;
+
+ if(m_bufflen >= len)
+ {
+ ASSERT(m_bufflen == len);
+
+ src = m_buff;
+ dst = m_buff + len;
+
+ if(sps > 0
+ && (m_pInput->CurrentMediaType().subtype == MEDIASUBTYPE_COOK
+ || m_pInput->CurrentMediaType().subtype == MEDIASUBTYPE_ATRC))
+ {
+ for(int y = 0; y < h; y++)
+ {
+ for(int x = 0, w2 = w / sps; x < w2; x++)
+ {
+ // TRACE(_T("--- %d, %d\n"), (h*x+((h+1)/2)*(y&1)+(y>>1)), sps*(h*x+((h+1)/2)*(y&1)+(y>>1)));
+ memcpy(dst + sps*(h*x+((h+1)/2)*(y&1)+(y>>1)), src, sps);
+ src += sps;
+ }
+ }
+
+ src = m_buff + len;
+ dst = m_buff + len*2;
+ }
+ else if(m_pInput->CurrentMediaType().subtype == MEDIASUBTYPE_SIPR)
+ {
+ // http://mplayerhq.hu/pipermail/mplayer-dev-eng/2002-August/010569.html
+
+ static BYTE sipr_swaps[38][2]={
+ {0,63},{1,22},{2,44},{3,90},{5,81},{7,31},{8,86},{9,58},{10,36},{12,68},
+ {13,39},{14,73},{15,53},{16,69},{17,57},{19,88},{20,34},{21,71},{24,46},
+ {25,94},{26,54},{28,75},{29,50},{32,70},{33,92},{35,74},{38,85},{40,56},
+ {42,87},{43,65},{45,59},{48,79},{49,93},{51,89},{55,95},{61,76},{67,83},
+ {77,80} };
+
+ int bs=h*w*2/96; // nibbles per subpacket
+ for(int n=0;n<38;n++){
+ int i=bs*sipr_swaps[n][0];
+ int o=bs*sipr_swaps[n][1];
+ // swap nibbles of block 'i' with 'o' TODO: optimize
+ for(int j=0;j<bs;j++){
+ int x=(i&1) ? (src[(i>>1)]>>4) : (src[(i>>1)]&15);
+ int y=(o&1) ? (src[(o>>1)]>>4) : (src[(o>>1)]&15);
+ if(o&1) src[(o>>1)]=(src[(o>>1)]&0x0F)|(x<<4);
+ else src[(o>>1)]=(src[(o>>1)]&0xF0)|x;
+ if(i&1) src[(i>>1)]=(src[(i>>1)]&0x0F)|(y<<4);
+ else src[(i>>1)]=(src[(i>>1)]&0xF0)|y;
+ ++i;++o;
+ }
+ }
+ }
+
+ m_bufflen = 0;
+ }
+ }
+
+ rtStart = m_rtBuffStart;
+
+ for(; src < dst; src += w)
+ {
+ CComPtr<IMediaSample> pOut;
+ BYTE* pDataOut = NULL;
+ if(FAILED(hr = m_pOutput->GetDeliveryBuffer(&pOut, NULL, NULL, 0))
+ || FAILED(hr = pOut->GetPointer(&pDataOut)))
+ return hr;
+
+ AM_MEDIA_TYPE* pmt;
+ if(SUCCEEDED(pOut->GetMediaType(&pmt)) && pmt)
+ {
+ CMediaType mt(*pmt);
+ m_pOutput->SetMediaType(&mt);
+ DeleteMediaType(pmt);
+ }
+
+ hr = RADecode(m_dwCookie, src, w, pDataOut, &len, -1);
+
+ if(FAILED(hr))
+ {
+ TRACE(_T("RA returned an error code!!!\n"));
+ continue;
// return hr;
- }
+ }
- WAVEFORMATEX* pwfe = (WAVEFORMATEX*)m_pOutput->CurrentMediaType().Format();
+ WAVEFORMATEX* pwfe = (WAVEFORMATEX*)m_pOutput->CurrentMediaType().Format();
- rtStop = rtStart + 1000i64 * len / pwfe->nAvgBytesPerSec * 10000;
- pOut->SetTime(&rtStart, &rtStop);
- pOut->SetMediaTime(NULL, NULL);
+ rtStop = rtStart + 1000i64*len/pwfe->nAvgBytesPerSec*10000;
+ pOut->SetTime(&rtStart, &rtStop);
+ pOut->SetMediaTime(NULL, NULL);
- pOut->SetDiscontinuity(m_fBuffDiscontinuity);
- m_fBuffDiscontinuity = false;
- pOut->SetSyncPoint(TRUE);
+ pOut->SetDiscontinuity(m_fBuffDiscontinuity); m_fBuffDiscontinuity = false;
+ pOut->SetSyncPoint(TRUE);
- pOut->SetActualDataLength(len);
+ pOut->SetActualDataLength(len);
- DbgLog((LOG_TRACE, 0, _T("A: rtStart=%I64d, rtStop=%I64d, disc=%d, sync=%d"),
- rtStart, rtStop, pOut->IsDiscontinuity() == S_OK, pOut->IsSyncPoint() == S_OK));
+DbgLog((LOG_TRACE, 0, _T("A: rtStart=%I64d, rtStop=%I64d, disc=%d, sync=%d"),
+rtStart, rtStop, pOut->IsDiscontinuity() == S_OK, pOut->IsSyncPoint() == S_OK));
- if(rtStart >= 0 && S_OK != (hr = m_pOutput->Deliver(pOut)))
- return hr;
+ if(rtStart >= 0 && S_OK != (hr = m_pOutput->Deliver(pOut)))
+ return hr;
- rtStart = rtStop;
- }
+ rtStart = rtStop;
+ }
- m_rtBuffStart = rtStart;
+ m_rtBuffStart = rtStart;
- return S_OK;
+ return S_OK;
}
HRESULT CRealAudioDecoder::CheckInputType(const CMediaType* mtIn)
{
- if(mtIn->majortype != MEDIATYPE_Audio
- || mtIn->subtype != MEDIASUBTYPE_14_4
- && mtIn->subtype != MEDIASUBTYPE_28_8
- && mtIn->subtype != MEDIASUBTYPE_ATRC
- && mtIn->subtype != MEDIASUBTYPE_COOK
- && mtIn->subtype != MEDIASUBTYPE_DNET
- && mtIn->subtype != MEDIASUBTYPE_SIPR
- && mtIn->subtype != MEDIASUBTYPE_RAAC
- && mtIn->subtype != MEDIASUBTYPE_RACP
- && mtIn->subtype != MEDIASUBTYPE_AAC)
- return VFW_E_TYPE_NOT_ACCEPTED;
-
- if(!m_pInput->IsConnected())
- {
- if(m_hDrvDll)
- {
- FreeLibrary(m_hDrvDll);
- m_hDrvDll = NULL;
- }
-
- CAtlList<CString> paths;
- CString olddll, newdll, oldpath, newpath;
-
- TCHAR fourcc[5] =
- {
- (TCHAR)((mtIn->subtype.Data1 >> 0) & 0xff),
- (TCHAR)((mtIn->subtype.Data1 >> 8) & 0xff),
- (TCHAR)((mtIn->subtype.Data1 >> 16) & 0xff),
- (TCHAR)((mtIn->subtype.Data1 >> 24) & 0xff),
- 0
- };
-
- if(!_tcscmp(_T("RACP"), fourcc) || !_tcscmp(_T("\xff"), fourcc))
- _tcscpy(fourcc, _T("RAAC"));
-
- olddll.Format(_T("%s3260.dll"), fourcc);
- newdll.Format(_T("%s.dll"), fourcc);
-
- CRegKey key;
- TCHAR buff[_MAX_PATH];
- ULONG len = sizeof(buff);
- if(ERROR_SUCCESS == key.Open(HKEY_CLASSES_ROOT, _T("Software\\RealNetworks\\Preferences\\DT_Codecs"), KEY_READ)
- && ERROR_SUCCESS == key.QueryStringValue(NULL, buff, &len) && _tcslen(buff) > 0)
- {
- oldpath = buff;
- TCHAR c = oldpath[oldpath.GetLength()-1];
- if(c != '\\' && c != '/') oldpath += '\\';
- key.Close();
- }
- len = sizeof(buff);
- if(ERROR_SUCCESS == key.Open(HKEY_CLASSES_ROOT, _T("Helix\\HelixSDK\\10.0\\Preferences\\DT_Codecs"), KEY_READ)
- && ERROR_SUCCESS == key.QueryStringValue(NULL, buff, &len) && _tcslen(buff) > 0)
- {
- newpath = buff;
- TCHAR c = newpath[newpath.GetLength()-1];
- if(c != '\\' && c != '/') newpath += '\\';
- key.Close();
- }
-
- if(!newpath.IsEmpty()) paths.AddTail(newpath + newdll);
- if(!oldpath.IsEmpty()) paths.AddTail(oldpath + newdll);
- paths.AddTail(newdll); // default dll paths
- if(!newpath.IsEmpty()) paths.AddTail(newpath + olddll);
- if(!oldpath.IsEmpty()) paths.AddTail(oldpath + olddll);
- paths.AddTail(olddll); // default dll paths
-
- POSITION pos = paths.GetHeadPosition();
- while(pos && !(m_hDrvDll = LoadLibrary(paths.GetNext(pos))));
-
- if(m_hDrvDll)
- {
- RACloseCodec = (PCloseCodec)GetProcAddress(m_hDrvDll, "RACloseCodec");
- RADecode = (PDecode)GetProcAddress(m_hDrvDll, "RADecode");
- RAFlush = (PFlush)GetProcAddress(m_hDrvDll, "RAFlush");
- RAFreeDecoder = (PFreeDecoder)GetProcAddress(m_hDrvDll, "RAFreeDecoder");
- RAGetFlavorProperty = (PGetFlavorProperty)GetProcAddress(m_hDrvDll, "RAGetFlavorProperty");
- RAInitDecoder = (PInitDecoder)GetProcAddress(m_hDrvDll, "RAInitDecoder");
- RAOpenCodec = (POpenCodec)GetProcAddress(m_hDrvDll, "RAOpenCodec");
- RAOpenCodec2 = (POpenCodec2)GetProcAddress(m_hDrvDll, "RAOpenCodec2");
- RASetFlavor = (PSetFlavor)GetProcAddress(m_hDrvDll, "RASetFlavor");
- RASetDLLAccessPath = (PSetDLLAccessPath)GetProcAddress(m_hDrvDll, "RASetDLLAccessPath");
- RASetPwd = (PSetPwd)GetProcAddress(m_hDrvDll, "RASetPwd");
- }
-
- if(!m_hDrvDll || !RACloseCodec || !RADecode /*|| !RAFlush*/
- || !RAFreeDecoder || !RAGetFlavorProperty || !RAInitDecoder
- || !(RAOpenCodec || RAOpenCodec2) /*|| !RASetFlavor*/)
- return VFW_E_TYPE_NOT_ACCEPTED;
-
- if(m_hDrvDll)
- {
- char buff[_MAX_PATH];
- GetModuleFileNameA(m_hDrvDll, buff, MAX_PATH);
- CPathA p(buff);
- p.RemoveFileSpec();
- p.AddBackslash();
- m_dllpath = p.m_strPath;
- if(RASetDLLAccessPath)
- RASetDLLAccessPath("DT_Codecs=" + m_dllpath);
- }
-
- if(FAILED(InitRA(mtIn)))
- return VFW_E_TYPE_NOT_ACCEPTED;
- }
-
- return S_OK;
+ if(mtIn->majortype != MEDIATYPE_Audio
+ || mtIn->subtype != MEDIASUBTYPE_14_4
+ && mtIn->subtype != MEDIASUBTYPE_28_8
+ && mtIn->subtype != MEDIASUBTYPE_ATRC
+ && mtIn->subtype != MEDIASUBTYPE_COOK
+ && mtIn->subtype != MEDIASUBTYPE_DNET
+ && mtIn->subtype != MEDIASUBTYPE_SIPR
+ && mtIn->subtype != MEDIASUBTYPE_RAAC
+ && mtIn->subtype != MEDIASUBTYPE_RACP
+ && mtIn->subtype != MEDIASUBTYPE_AAC)
+ return VFW_E_TYPE_NOT_ACCEPTED;
+
+ if(!m_pInput->IsConnected())
+ {
+ if(m_hDrvDll) {FreeLibrary(m_hDrvDll); m_hDrvDll = NULL;}
+
+ CAtlList<CString> paths;
+ CString olddll, newdll, oldpath, newpath;
+
+ TCHAR fourcc[5] =
+ {
+ (TCHAR)((mtIn->subtype.Data1>>0)&0xff),
+ (TCHAR)((mtIn->subtype.Data1>>8)&0xff),
+ (TCHAR)((mtIn->subtype.Data1>>16)&0xff),
+ (TCHAR)((mtIn->subtype.Data1>>24)&0xff),
+ 0
+ };
+
+ if(!_tcscmp(_T("RACP"), fourcc) || !_tcscmp(_T("\xff"), fourcc))
+ _tcscpy(fourcc, _T("RAAC"));
+
+ olddll.Format(_T("%s3260.dll"), fourcc);
+ newdll.Format(_T("%s.dll"), fourcc);
+
+ CRegKey key;
+ TCHAR buff[_MAX_PATH];
+ ULONG len = sizeof(buff);
+ if(ERROR_SUCCESS == key.Open(HKEY_CLASSES_ROOT, _T("Software\\RealNetworks\\Preferences\\DT_Codecs"), KEY_READ)
+ && ERROR_SUCCESS == key.QueryStringValue(NULL, buff, &len) && _tcslen(buff) > 0)
+ {
+ oldpath = buff;
+ TCHAR c = oldpath[oldpath.GetLength()-1];
+ if(c != '\\' && c != '/') oldpath += '\\';
+ key.Close();
+ }
+ len = sizeof(buff);
+ if(ERROR_SUCCESS == key.Open(HKEY_CLASSES_ROOT, _T("Helix\\HelixSDK\\10.0\\Preferences\\DT_Codecs"), KEY_READ)
+ && ERROR_SUCCESS == key.QueryStringValue(NULL, buff, &len) && _tcslen(buff) > 0)
+ {
+ newpath = buff;
+ TCHAR c = newpath[newpath.GetLength()-1];
+ if(c != '\\' && c != '/') newpath += '\\';
+ key.Close();
+ }
+
+ if(!newpath.IsEmpty()) paths.AddTail(newpath + newdll);
+ if(!oldpath.IsEmpty()) paths.AddTail(oldpath + newdll);
+ paths.AddTail(newdll); // default dll paths
+ if(!newpath.IsEmpty()) paths.AddTail(newpath + olddll);
+ if(!oldpath.IsEmpty()) paths.AddTail(oldpath + olddll);
+ paths.AddTail(olddll); // default dll paths
+
+ POSITION pos = paths.GetHeadPosition();
+ while(pos && !(m_hDrvDll = LoadLibrary(paths.GetNext(pos))));
+
+ if(m_hDrvDll)
+ {
+ RACloseCodec = (PCloseCodec)GetProcAddress(m_hDrvDll, "RACloseCodec");
+ RADecode = (PDecode)GetProcAddress(m_hDrvDll, "RADecode");
+ RAFlush = (PFlush)GetProcAddress(m_hDrvDll, "RAFlush");
+ RAFreeDecoder = (PFreeDecoder)GetProcAddress(m_hDrvDll, "RAFreeDecoder");
+ RAGetFlavorProperty = (PGetFlavorProperty)GetProcAddress(m_hDrvDll, "RAGetFlavorProperty");
+ RAInitDecoder = (PInitDecoder)GetProcAddress(m_hDrvDll, "RAInitDecoder");
+ RAOpenCodec = (POpenCodec)GetProcAddress(m_hDrvDll, "RAOpenCodec");
+ RAOpenCodec2 = (POpenCodec2)GetProcAddress(m_hDrvDll, "RAOpenCodec2");
+ RASetFlavor = (PSetFlavor)GetProcAddress(m_hDrvDll, "RASetFlavor");
+ RASetDLLAccessPath = (PSetDLLAccessPath)GetProcAddress(m_hDrvDll, "RASetDLLAccessPath");
+ RASetPwd = (PSetPwd)GetProcAddress(m_hDrvDll, "RASetPwd");
+ }
+
+ if(!m_hDrvDll || !RACloseCodec || !RADecode /*|| !RAFlush*/
+ || !RAFreeDecoder || !RAGetFlavorProperty || !RAInitDecoder
+ || !(RAOpenCodec || RAOpenCodec2) /*|| !RASetFlavor*/)
+ return VFW_E_TYPE_NOT_ACCEPTED;
+
+ if(m_hDrvDll)
+ {
+ char buff[_MAX_PATH];
+ GetModuleFileNameA(m_hDrvDll, buff, MAX_PATH);
+ CPathA p(buff);
+ p.RemoveFileSpec();
+ p.AddBackslash();
+ m_dllpath = p.m_strPath;
+ if(RASetDLLAccessPath)
+ RASetDLLAccessPath("DT_Codecs=" + m_dllpath);
+ }
+
+ if(FAILED(InitRA(mtIn)))
+ return VFW_E_TYPE_NOT_ACCEPTED;
+ }
+
+ return S_OK;
}
HRESULT CRealAudioDecoder::CheckTransform(const CMediaType* mtIn, const CMediaType* mtOut)
{
- return mtIn->majortype == MEDIATYPE_Audio && (mtIn->subtype == MEDIASUBTYPE_14_4
- || mtIn->subtype == MEDIASUBTYPE_28_8
- || mtIn->subtype == MEDIASUBTYPE_ATRC
- || mtIn->subtype == MEDIASUBTYPE_COOK
- || mtIn->subtype == MEDIASUBTYPE_DNET
- || mtIn->subtype == MEDIASUBTYPE_SIPR
- || mtIn->subtype == MEDIASUBTYPE_RAAC
- || mtIn->subtype == MEDIASUBTYPE_RACP
- || mtIn->subtype == MEDIASUBTYPE_AAC)
- && mtOut->majortype == MEDIATYPE_Audio && mtOut->subtype == MEDIASUBTYPE_PCM
- ? S_OK
- : VFW_E_TYPE_NOT_ACCEPTED;
+ return mtIn->majortype == MEDIATYPE_Audio && (mtIn->subtype == MEDIASUBTYPE_14_4
+ || mtIn->subtype == MEDIASUBTYPE_28_8
+ || mtIn->subtype == MEDIASUBTYPE_ATRC
+ || mtIn->subtype == MEDIASUBTYPE_COOK
+ || mtIn->subtype == MEDIASUBTYPE_DNET
+ || mtIn->subtype == MEDIASUBTYPE_SIPR
+ || mtIn->subtype == MEDIASUBTYPE_RAAC
+ || mtIn->subtype == MEDIASUBTYPE_RACP
+ || mtIn->subtype == MEDIASUBTYPE_AAC)
+ && mtOut->majortype == MEDIATYPE_Audio && mtOut->subtype == MEDIASUBTYPE_PCM
+ ? S_OK
+ : VFW_E_TYPE_NOT_ACCEPTED;
}
HRESULT CRealAudioDecoder::DecideBufferSize(IMemAllocator* pAllocator, ALLOCATOR_PROPERTIES* pProperties)
{
- if(m_pInput->IsConnected() == FALSE) return E_UNEXPECTED;
+ if(m_pInput->IsConnected() == FALSE) return E_UNEXPECTED;
- CComPtr<IMemAllocator> pAllocatorIn;
- m_pInput->GetAllocator(&pAllocatorIn);
- if(!pAllocatorIn) return E_UNEXPECTED;
+ CComPtr<IMemAllocator> pAllocatorIn;
+ m_pInput->GetAllocator(&pAllocatorIn);
+ if(!pAllocatorIn) return E_UNEXPECTED;
- WAVEFORMATEX* pwfe = (WAVEFORMATEX*)m_pOutput->CurrentMediaType().Format();
+ WAVEFORMATEX* pwfe = (WAVEFORMATEX*)m_pOutput->CurrentMediaType().Format();
- WORD wBitsPerSample = pwfe->wBitsPerSample;
- if(!wBitsPerSample) wBitsPerSample = 16;
+ WORD wBitsPerSample = pwfe->wBitsPerSample;
+ if(!wBitsPerSample) wBitsPerSample = 16;
- // ok, maybe this is too much...
- pProperties->cBuffers = 8;
- pProperties->cbBuffer = pwfe->nChannels * pwfe->nSamplesPerSec * wBitsPerSample >> 3; // nAvgBytesPerSec;
- pProperties->cbAlign = 1;
- pProperties->cbPrefix = 0;
+ // ok, maybe this is too much...
+ pProperties->cBuffers = 8;
+ pProperties->cbBuffer = pwfe->nChannels*pwfe->nSamplesPerSec*wBitsPerSample>>3; // nAvgBytesPerSec;
+ pProperties->cbAlign = 1;
+ pProperties->cbPrefix = 0;
- HRESULT hr;
- ALLOCATOR_PROPERTIES Actual;
- if(FAILED(hr = pAllocator->SetProperties(pProperties, &Actual)))
- return hr;
+ HRESULT hr;
+ ALLOCATOR_PROPERTIES Actual;
+ if(FAILED(hr = pAllocator->SetProperties(pProperties, &Actual)))
+ return hr;
return(pProperties->cBuffers > Actual.cBuffers || pProperties->cbBuffer > Actual.cbBuffer
- ? E_FAIL
- : NOERROR);
+ ? E_FAIL
+ : NOERROR);
}
HRESULT CRealAudioDecoder::GetMediaType(int iPosition, CMediaType* pmt)
{
if(m_pInput->IsConnected() == FALSE) return E_UNEXPECTED;
- *pmt = m_pInput->CurrentMediaType();
- pmt->subtype = MEDIASUBTYPE_PCM;
- WAVEFORMATEX* pwfe = (WAVEFORMATEX*)pmt->ReallocFormatBuffer(sizeof(WAVEFORMATEX));
-
- if(iPosition < 0) return E_INVALIDARG;
- if(iPosition > (pwfe->nChannels > 2 && pwfe->nChannels <= 6 ? 1 : 0)) return VFW_S_NO_MORE_ITEMS;
-
- if(!pwfe->wBitsPerSample) pwfe->wBitsPerSample = 16;
-
- pwfe->cbSize = 0;
- pwfe->wFormatTag = WAVE_FORMAT_PCM;
- pwfe->nBlockAlign = pwfe->nChannels * pwfe->wBitsPerSample >> 3;
- pwfe->nAvgBytesPerSec = pwfe->nSamplesPerSec * pwfe->nBlockAlign;
-
- if(iPosition == 0 && pwfe->nChannels > 2 && pwfe->nChannels <= 6)
- {
- static DWORD chmask[] =
- {
- KSAUDIO_SPEAKER_DIRECTOUT,
- KSAUDIO_SPEAKER_MONO,
- KSAUDIO_SPEAKER_STEREO,
- KSAUDIO_SPEAKER_STEREO | SPEAKER_FRONT_CENTER,
- KSAUDIO_SPEAKER_QUAD,
- KSAUDIO_SPEAKER_QUAD | SPEAKER_FRONT_CENTER,
- KSAUDIO_SPEAKER_5POINT1
- };
-
- WAVEFORMATEXTENSIBLE* pwfex = (WAVEFORMATEXTENSIBLE*)pmt->ReallocFormatBuffer(sizeof(WAVEFORMATEXTENSIBLE));
- pwfex->Format.cbSize = sizeof(WAVEFORMATEXTENSIBLE) - sizeof(WAVEFORMATEX);
- pwfex->Format.wFormatTag = WAVE_FORMAT_EXTENSIBLE;
- pwfex->dwChannelMask = chmask[pwfex->Format.nChannels];
- pwfex->Samples.wValidBitsPerSample = pwfex->Format.wBitsPerSample;
- pwfex->SubFormat = KSDATAFORMAT_SUBTYPE_PCM;
- }
-
- return S_OK;
+ *pmt = m_pInput->CurrentMediaType();
+ pmt->subtype = MEDIASUBTYPE_PCM;
+ WAVEFORMATEX* pwfe = (WAVEFORMATEX*)pmt->ReallocFormatBuffer(sizeof(WAVEFORMATEX));
+
+ if(iPosition < 0) return E_INVALIDARG;
+ if(iPosition > (pwfe->nChannels > 2 && pwfe->nChannels <= 6 ? 1 : 0)) return VFW_S_NO_MORE_ITEMS;
+
+ if(!pwfe->wBitsPerSample) pwfe->wBitsPerSample = 16;
+
+ pwfe->cbSize = 0;
+ pwfe->wFormatTag = WAVE_FORMAT_PCM;
+ pwfe->nBlockAlign = pwfe->nChannels*pwfe->wBitsPerSample>>3;
+ pwfe->nAvgBytesPerSec = pwfe->nSamplesPerSec*pwfe->nBlockAlign;
+
+ if(iPosition == 0 && pwfe->nChannels > 2 && pwfe->nChannels <= 6)
+ {
+ static DWORD chmask[] =
+ {
+ KSAUDIO_SPEAKER_DIRECTOUT,
+ KSAUDIO_SPEAKER_MONO,
+ KSAUDIO_SPEAKER_STEREO,
+ KSAUDIO_SPEAKER_STEREO|SPEAKER_FRONT_CENTER,
+ KSAUDIO_SPEAKER_QUAD,
+ KSAUDIO_SPEAKER_QUAD|SPEAKER_FRONT_CENTER,
+ KSAUDIO_SPEAKER_5POINT1
+ };
+
+ WAVEFORMATEXTENSIBLE* pwfex = (WAVEFORMATEXTENSIBLE*)pmt->ReallocFormatBuffer(sizeof(WAVEFORMATEXTENSIBLE));
+ pwfex->Format.cbSize = sizeof(WAVEFORMATEXTENSIBLE) - sizeof(WAVEFORMATEX);
+ pwfex->Format.wFormatTag = WAVE_FORMAT_EXTENSIBLE;
+ pwfex->dwChannelMask = chmask[pwfex->Format.nChannels];
+ pwfex->Samples.wValidBitsPerSample = pwfex->Format.wBitsPerSample;
+ pwfex->SubFormat = KSDATAFORMAT_SUBTYPE_PCM;
+ }
+
+ return S_OK;
}
HRESULT CRealAudioDecoder::StartStreaming()
{
- int w = m_rai.coded_frame_size;
- int h = m_rai.sub_packet_h;
- int sps = m_rai.sub_packet_size;
+ int w = m_rai.coded_frame_size;
+ int h = m_rai.sub_packet_h;
+ int sps = m_rai.sub_packet_size;
- int len = w * h;
+ int len = w*h;
- m_buff.Allocate(len * 2);
- m_bufflen = 0;
- m_rtBuffStart = 0;
+ m_buff.Allocate(len*2);
+ m_bufflen = 0;
+ m_rtBuffStart = 0;
- return __super::StartStreaming();
+ return __super::StartStreaming();
}
HRESULT CRealAudioDecoder::StopStreaming()
{
- m_buff.Free();
- m_bufflen = 0;
+ m_buff.Free();
+ m_bufflen = 0;
- return __super::StopStreaming();
+ return __super::StopStreaming();
}
HRESULT CRealAudioDecoder::EndOfStream()
{
- return __super::EndOfStream();
+ return __super::EndOfStream();
}
HRESULT CRealAudioDecoder::BeginFlush()
{
- return __super::BeginFlush();
+ return __super::BeginFlush();
}
HRESULT CRealAudioDecoder::EndFlush()
{
- return __super::EndFlush();
+ return __super::EndFlush();
}
HRESULT CRealAudioDecoder::NewSegment(REFERENCE_TIME tStart, REFERENCE_TIME tStop, double dRate)
{
- CAutoLock cAutoLock(&m_csReceive);
- m_tStart = tStart;
- m_bufflen = 0;
- m_rtBuffStart = 0;
- return __super::NewSegment(tStart, tStop, dRate);
+ CAutoLock cAutoLock(&m_csReceive);
+ m_tStart = tStart;
+ m_bufflen = 0;
+ m_rtBuffStart = 0;
+ return __super::NewSegment(tStart, tStop, dRate);
}
diff --git a/src/filters/parser/RealMediaSplitter/RealMediaSplitter.h b/src/filters/parser/RealMediaSplitter/RealMediaSplitter.h
index 200c3b5fc..42b28e5da 100644
--- a/src/filters/parser/RealMediaSplitter/RealMediaSplitter.h
+++ b/src/filters/parser/RealMediaSplitter/RealMediaSplitter.h
@@ -1,4 +1,4 @@
-/*
+/*
* Copyright (C) 2003-2006 Gabest
* http://www.gabest.org
*
@@ -6,15 +6,15 @@
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2, or (at your option)
* any later version.
- *
+ *
* This Program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with GNU Make; see the file COPYING. If not, write to
- * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
+ * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
* http://www.gnu.org/copyleft/gpl.html
*
*/
@@ -30,219 +30,185 @@
namespace RMFF
{
-typedef struct
-{
- union
- {
- char id[4];
- UINT32 object_id;
- };
- UINT32 size;
- UINT16 object_version;
-} ChunkHdr;
-typedef struct
-{
- UINT32 version, nHeaders;
-} FileHdr;
-typedef struct
-{
- UINT32 maxBitRate, avgBitRate;
- UINT32 maxPacketSize, avgPacketSize, nPackets;
- UINT32 tDuration, tPreroll;
- UINT32 ptrIndex, ptrData;
- UINT16 nStreams;
- enum flags_t {PN_SAVE_ENABLED = 1, PN_PERFECT_PLAY_ENABLED = 2, PN_LIVE_BROADCAST = 4} flags;
-} Properies;
-typedef struct
-{
- UINT16 stream;
- UINT32 maxBitRate, avgBitRate;
- UINT32 maxPacketSize, avgPacketSize;
- UINT32 tStart, tPreroll, tDuration;
- CStringA name, mime;
- CAtlArray<BYTE> typeSpecData;
- UINT32 width, height;
- bool interlaced, top_field_first;
-} MediaProperies;
-typedef struct
-{
- CStringA title, author, copyright, comment;
-} ContentDesc;
-typedef struct
-{
- UINT64 pos;
- UINT32 nPackets, ptrNext;
-} DataChunk;
-typedef struct
-{
- UINT16 len, stream;
- UINT32 tStart;
- UINT8 reserved;
- enum flag_t {PN_RELIABLE_FLAG = 1, PN_KEYFRAME_FLAG = 2} flags; // UINT8
- CAtlArray<BYTE> pData;
-} MediaPacketHeader;
-typedef struct
-{
- UINT32 nIndices;
- UINT16 stream;
- UINT32 ptrNext;
-} IndexChunkHeader;
-typedef struct
-{
- UINT32 tStart, ptrFilePos, packet;
-} IndexRecord;
+ typedef struct {union {char id[4]; UINT32 object_id;}; UINT32 size; UINT16 object_version;} ChunkHdr;
+ typedef struct {UINT32 version, nHeaders;} FileHdr;
+ typedef struct
+ {
+ UINT32 maxBitRate, avgBitRate;
+ UINT32 maxPacketSize, avgPacketSize, nPackets;
+ UINT32 tDuration, tPreroll;
+ UINT32 ptrIndex, ptrData;
+ UINT16 nStreams;
+ enum flags_t {PN_SAVE_ENABLED=1, PN_PERFECT_PLAY_ENABLED=2, PN_LIVE_BROADCAST=4} flags;
+ } Properies;
+ typedef struct
+ {
+ UINT16 stream;
+ UINT32 maxBitRate, avgBitRate;
+ UINT32 maxPacketSize, avgPacketSize;
+ UINT32 tStart, tPreroll, tDuration;
+ CStringA name, mime;
+ CAtlArray<BYTE> typeSpecData;
+ UINT32 width, height;
+ bool interlaced, top_field_first;
+ } MediaProperies;
+ typedef struct {CStringA title, author, copyright, comment;} ContentDesc;
+ typedef struct {UINT64 pos; UINT32 nPackets, ptrNext;} DataChunk;
+ typedef struct
+ {
+ UINT16 len, stream;
+ UINT32 tStart;
+ UINT8 reserved;
+ enum flag_t {PN_RELIABLE_FLAG=1, PN_KEYFRAME_FLAG=2} flags; // UINT8
+ CAtlArray<BYTE> pData;
+ } MediaPacketHeader;
+ typedef struct {UINT32 nIndices; UINT16 stream; UINT32 ptrNext;} IndexChunkHeader;
+ typedef struct {UINT32 tStart, ptrFilePos, packet;} IndexRecord;
}
struct rvinfo
{
- DWORD dwSize, fcc1, fcc2;
- WORD w, h, bpp;
- DWORD unk1, fps, type1, type2;
- BYTE morewh[14];
- void bswap();
+ DWORD dwSize, fcc1, fcc2;
+ WORD w, h, bpp;
+ DWORD unk1, fps, type1, type2;
+ BYTE morewh[14];
+ void bswap();
};
struct rainfo
{
- DWORD fourcc1; // '.', 'r', 'a', 0xfd
- WORD version1; // 4 or 5
- WORD unknown1; // 00 000
- DWORD fourcc2; // .ra4 or .ra5
- DWORD unknown2; // ???
- WORD version2; // 4 or 5
- DWORD header_size; // == 0x4e
- WORD flavor; // codec flavor id
- DWORD coded_frame_size; // coded frame size
- DWORD unknown3; // big number
- DWORD unknown4; // bigger number
- DWORD unknown5; // yet another number
- WORD sub_packet_h;
- WORD frame_size;
- WORD sub_packet_size;
- WORD unknown6; // 00 00
- void bswap();
+ DWORD fourcc1; // '.', 'r', 'a', 0xfd
+ WORD version1; // 4 or 5
+ WORD unknown1; // 00 000
+ DWORD fourcc2; // .ra4 or .ra5
+ DWORD unknown2; // ???
+ WORD version2; // 4 or 5
+ DWORD header_size; // == 0x4e
+ WORD flavor; // codec flavor id
+ DWORD coded_frame_size; // coded frame size
+ DWORD unknown3; // big number
+ DWORD unknown4; // bigger number
+ DWORD unknown5; // yet another number
+ WORD sub_packet_h;
+ WORD frame_size;
+ WORD sub_packet_size;
+ WORD unknown6; // 00 00
+ void bswap();
};
struct rainfo4 : rainfo
{
- WORD sample_rate;
- WORD unknown8; // 0
- WORD sample_size;
- WORD channels;
- void bswap();
+ WORD sample_rate;
+ WORD unknown8; // 0
+ WORD sample_size;
+ WORD channels;
+ void bswap();
};
struct rainfo5 : rainfo
{
- BYTE unknown7[6]; // 0, srate, 0
- WORD sample_rate;
- WORD unknown8; // 0
- WORD sample_size;
- WORD channels;
- DWORD genr; // "genr"
- DWORD fourcc3; // fourcc
- void bswap();
+ BYTE unknown7[6]; // 0, srate, 0
+ WORD sample_rate;
+ WORD unknown8; // 0
+ WORD sample_size;
+ WORD channels;
+ DWORD genr; // "genr"
+ DWORD fourcc3; // fourcc
+ void bswap();
};
#pragma pack(pop)
class CRMFile : public CBaseSplitterFile
{
- // using CBaseSplitterFile::Read;
+ // using CBaseSplitterFile::Read;
- HRESULT Init();
- void GetDimensions();
+ HRESULT Init();
+ void GetDimensions();
public:
- CRMFile(IAsyncReader* pAsyncReader, HRESULT& hr);
-
- template<typename T> HRESULT Read(T& var);
- HRESULT Read(RMFF::ChunkHdr& hdr);
- HRESULT Read(RMFF::MediaPacketHeader& mph, bool fFull = true);
-
- RMFF::FileHdr m_fh;
- RMFF::ContentDesc m_cd;
- RMFF::Properies m_p;
- CAutoPtrList<RMFF::MediaProperies> m_mps;
- CAutoPtrList<RMFF::DataChunk> m_dcs;
- CAutoPtrList<RMFF::IndexRecord> m_irs;
-
- typedef struct
- {
- CStringA name, data;
- } subtitle;
- CAtlList<subtitle> m_subs;
-
- int GetMasterStream();
+ CRMFile(IAsyncReader* pAsyncReader, HRESULT& hr);
+
+ template<typename T> HRESULT Read(T& var);
+ HRESULT Read(RMFF::ChunkHdr& hdr);
+ HRESULT Read(RMFF::MediaPacketHeader& mph, bool fFull = true);
+
+ RMFF::FileHdr m_fh;
+ RMFF::ContentDesc m_cd;
+ RMFF::Properies m_p;
+ CAutoPtrList<RMFF::MediaProperies> m_mps;
+ CAutoPtrList<RMFF::DataChunk> m_dcs;
+ CAutoPtrList<RMFF::IndexRecord> m_irs;
+
+ typedef struct {CStringA name, data;} subtitle;
+ CAtlList<subtitle> m_subs;
+
+ int GetMasterStream();
};
class CRealMediaSplitterOutputPin : public CBaseSplitterOutputPin
{
private:
- typedef struct
- {
- CAtlArray<BYTE> data;
- DWORD offset;
- } segment;
-
- class CSegments : public CAutoPtrList<segment>, public CCritSec
- {
- public:
- REFERENCE_TIME rtStart;
- bool fDiscontinuity, fSyncPoint, fMerged;
- void Clear()
- {
- CAutoLock cAutoLock(this);
- rtStart = 0;
- fDiscontinuity = fSyncPoint = fMerged = false;
- RemoveAll();
- }
- } m_segments;
-
- CCritSec m_csQueue;
-
- HRESULT DeliverSegments();
+ typedef struct {CAtlArray<BYTE> data; DWORD offset;} segment;
+
+ class CSegments : public CAutoPtrList<segment>, public CCritSec
+ {
+ public:
+ REFERENCE_TIME rtStart;
+ bool fDiscontinuity, fSyncPoint, fMerged;
+ void Clear()
+ {
+ CAutoLock cAutoLock(this);
+ rtStart = 0;
+ fDiscontinuity = fSyncPoint = fMerged = false;
+ RemoveAll();
+ }
+ } m_segments;
+
+ CCritSec m_csQueue;
+
+ HRESULT DeliverSegments();
protected:
- HRESULT DeliverPacket(CAutoPtr<Packet> p);
+ HRESULT DeliverPacket(CAutoPtr<Packet> p);
public:
- CRealMediaSplitterOutputPin(CAtlArray<CMediaType>& mts, LPCWSTR pName, CBaseFilter* pFilter, CCritSec* pLock, HRESULT* phr);
- virtual ~CRealMediaSplitterOutputPin();
+ CRealMediaSplitterOutputPin(CAtlArray<CMediaType>& mts, LPCWSTR pName, CBaseFilter* pFilter, CCritSec* pLock, HRESULT* phr);
+ virtual ~CRealMediaSplitterOutputPin();
- HRESULT DeliverEndFlush();
+ HRESULT DeliverEndFlush();
};
[uuid("E21BE468-5C18-43EB-B0CC-DB93A847D769")]
class CRealMediaSplitterFilter : public CBaseSplitterFilter
{
protected:
- CAutoPtr<CRMFile> m_pFile;
- HRESULT CreateOutputs(IAsyncReader* pAsyncReader);
+ CAutoPtr<CRMFile> m_pFile;
+ HRESULT CreateOutputs(IAsyncReader* pAsyncReader);
- bool DemuxInit();
- void DemuxSeek(REFERENCE_TIME rt);
- bool DemuxLoop();
+ bool DemuxInit();
+ void DemuxSeek(REFERENCE_TIME rt);
+ bool DemuxLoop();
- POSITION m_seekpos;
- UINT32 m_seekpacket;
- UINT64 m_seekfilepos;
+ POSITION m_seekpos;
+ UINT32 m_seekpacket;
+ UINT64 m_seekfilepos;
public:
- CRealMediaSplitterFilter(LPUNKNOWN pUnk, HRESULT* phr);
- virtual ~CRealMediaSplitterFilter();
+ CRealMediaSplitterFilter(LPUNKNOWN pUnk, HRESULT* phr);
+ virtual ~CRealMediaSplitterFilter();
- // IKeyFrameInfo
+ // IKeyFrameInfo
- STDMETHODIMP_(HRESULT) GetKeyFrameCount(UINT& nKFs);
- STDMETHODIMP_(HRESULT) GetKeyFrames(const GUID* pFormat, REFERENCE_TIME* pKFs, UINT& nKFs);
+ STDMETHODIMP_(HRESULT) GetKeyFrameCount(UINT& nKFs);
+ STDMETHODIMP_(HRESULT) GetKeyFrames(const GUID* pFormat, REFERENCE_TIME* pKFs, UINT& nKFs);
};
[uuid("765035B3-5944-4A94-806B-20EE3415F26F")]
class CRealMediaSourceFilter : public CRealMediaSplitterFilter
{
public:
- CRealMediaSourceFilter(LPUNKNOWN pUnk, HRESULT* phr);
+ CRealMediaSourceFilter(LPUNKNOWN pUnk, HRESULT* phr);
};
////////////
@@ -250,106 +216,106 @@ public:
[uuid("238D0F23-5DC9-45A6-9BE2-666160C324DD")]
class CRealVideoDecoder : public CBaseVideoFilter
{
- typedef HRESULT(WINAPI *PRVCustomMessage)(void*, DWORD);
- typedef HRESULT(WINAPI *PRVFree)(DWORD);
- typedef HRESULT(WINAPI *PRVHiveMessage)(void*, DWORD);
- typedef HRESULT(WINAPI *PRVInit)(void*, DWORD* dwCookie);
- typedef HRESULT(WINAPI *PRVTransform)(BYTE*, BYTE*, void*, void*, DWORD);
+ typedef HRESULT (WINAPI *PRVCustomMessage)(void*, DWORD);
+ typedef HRESULT (WINAPI *PRVFree)(DWORD);
+ typedef HRESULT (WINAPI *PRVHiveMessage)(void*, DWORD);
+ typedef HRESULT (WINAPI *PRVInit)(void*, DWORD* dwCookie);
+ typedef HRESULT (WINAPI *PRVTransform)(BYTE*, BYTE*, void*, void*, DWORD);
- PRVCustomMessage RVCustomMessage;
- PRVFree RVFree;
- PRVHiveMessage RVHiveMessage;
- PRVInit RVInit;
- PRVTransform RVTransform;
+ PRVCustomMessage RVCustomMessage;
+ PRVFree RVFree;
+ PRVHiveMessage RVHiveMessage;
+ PRVInit RVInit;
+ PRVTransform RVTransform;
- HMODULE m_hDrvDll;
- DWORD m_dwCookie;
- int m_lastBuffSizeDim;
+ HMODULE m_hDrvDll;
+ DWORD m_dwCookie;
+ int m_lastBuffSizeDim;
- HRESULT InitRV(const CMediaType* pmt);
- void FreeRV();
+ HRESULT InitRV(const CMediaType* pmt);
+ void FreeRV();
- REFERENCE_TIME m_tStart;
+ REFERENCE_TIME m_tStart;
- void Resize(BYTE* pIn, DWORD wi, DWORD hi, BYTE* pOut, DWORD wo, DWORD ho);
- void ResizeWidth(BYTE* pIn, DWORD wi, DWORD hi, BYTE* pOut, DWORD wo, DWORD ho);
- void ResizeHeight(BYTE* pIn, DWORD wi, DWORD hi, BYTE* pOut, DWORD wo, DWORD ho);
- void ResizeRow(BYTE* pIn, DWORD wi, DWORD dpi, BYTE* pOut, DWORD wo, DWORD dpo);
+ void Resize(BYTE* pIn, DWORD wi, DWORD hi, BYTE* pOut, DWORD wo, DWORD ho);
+ void ResizeWidth(BYTE* pIn, DWORD wi, DWORD hi, BYTE* pOut, DWORD wo, DWORD ho);
+ void ResizeHeight(BYTE* pIn, DWORD wi, DWORD hi, BYTE* pOut, DWORD wo, DWORD ho);
+ void ResizeRow(BYTE* pIn, DWORD wi, DWORD dpi, BYTE* pOut, DWORD wo, DWORD dpo);
- CAutoVectorPtr<BYTE> m_pI420, m_pI420Tmp;
+ CAutoVectorPtr<BYTE> m_pI420, m_pI420Tmp;
public:
- CRealVideoDecoder(LPUNKNOWN lpunk, HRESULT* phr);
- virtual ~CRealVideoDecoder();
+ CRealVideoDecoder(LPUNKNOWN lpunk, HRESULT* phr);
+ virtual ~CRealVideoDecoder();
- HRESULT Transform(IMediaSample* pIn);
- HRESULT CheckInputType(const CMediaType* mtIn);
- HRESULT CheckTransform(const CMediaType* mtIn, const CMediaType* mtOut);
+ HRESULT Transform(IMediaSample* pIn);
+ HRESULT CheckInputType(const CMediaType* mtIn);
+ HRESULT CheckTransform(const CMediaType* mtIn, const CMediaType* mtOut);
- HRESULT StartStreaming();
- HRESULT StopStreaming();
+ HRESULT StartStreaming();
+ HRESULT StopStreaming();
- HRESULT NewSegment(REFERENCE_TIME tStart, REFERENCE_TIME tStop, double dRate);
+ HRESULT NewSegment(REFERENCE_TIME tStart, REFERENCE_TIME tStop, double dRate);
- DWORD m_timestamp;
- bool m_fDropFrames;
- HRESULT AlterQuality(Quality q);
+ DWORD m_timestamp;
+ bool m_fDropFrames;
+ HRESULT AlterQuality(Quality q);
};
[uuid("941A4793-A705-4312-8DFC-C11CA05F397E")]
class CRealAudioDecoder : public CTransformFilter
{
- typedef HRESULT(WINAPI *PCloseCodec)(DWORD);
- typedef HRESULT(WINAPI *PDecode)(DWORD, BYTE*, long, BYTE*, long*, long);
- typedef HRESULT(WINAPI *PFlush)(DWORD, DWORD, DWORD);
- typedef HRESULT(WINAPI *PFreeDecoder)(DWORD);
- typedef void*(WINAPI *PGetFlavorProperty)(void*, DWORD, DWORD, int*);
- typedef HRESULT(WINAPI *PInitDecoder)(DWORD, void*);
- typedef HRESULT(WINAPI *POpenCodec)(void*);
- typedef HRESULT(WINAPI *POpenCodec2)(void*, const char*);
- typedef HRESULT(WINAPI *PSetFlavor)(DWORD, WORD);
- typedef void (WINAPI *PSetDLLAccessPath)(const char*);
- typedef void (WINAPI *PSetPwd)(DWORD, const char*);
-
- PCloseCodec RACloseCodec;
- PDecode RADecode;
- PFlush RAFlush;
- PFreeDecoder RAFreeDecoder;
- PGetFlavorProperty RAGetFlavorProperty;
- PInitDecoder RAInitDecoder;
- POpenCodec RAOpenCodec;
- POpenCodec2 RAOpenCodec2;
- PSetFlavor RASetFlavor;
- PSetDLLAccessPath RASetDLLAccessPath;
- PSetPwd RASetPwd;
-
- CStringA m_dllpath;
- HMODULE m_hDrvDll;
- DWORD m_dwCookie;
-
- HRESULT InitRA(const CMediaType* pmt);
- void FreeRA();
-
- REFERENCE_TIME m_tStart;
-
- rainfo m_rai;
- CAutoVectorPtr<BYTE> m_buff;
- int m_bufflen;
- REFERENCE_TIME m_rtBuffStart;
- bool m_fBuffDiscontinuity;
+ typedef HRESULT (WINAPI *PCloseCodec)(DWORD);
+ typedef HRESULT (WINAPI *PDecode)(DWORD,BYTE*,long,BYTE*,long*,long);
+ typedef HRESULT (WINAPI *PFlush)(DWORD,DWORD,DWORD);
+ typedef HRESULT (WINAPI *PFreeDecoder)(DWORD);
+ typedef void* (WINAPI *PGetFlavorProperty)(void*,DWORD,DWORD,int*);
+ typedef HRESULT (WINAPI *PInitDecoder)(DWORD, void*);
+ typedef HRESULT (WINAPI *POpenCodec)(void*);
+ typedef HRESULT (WINAPI *POpenCodec2)(void*, const char*);
+ typedef HRESULT (WINAPI *PSetFlavor)(DWORD, WORD);
+ typedef void (WINAPI *PSetDLLAccessPath)(const char*);
+ typedef void (WINAPI *PSetPwd)(DWORD, const char*);
+
+ PCloseCodec RACloseCodec;
+ PDecode RADecode;
+ PFlush RAFlush;
+ PFreeDecoder RAFreeDecoder;
+ PGetFlavorProperty RAGetFlavorProperty;
+ PInitDecoder RAInitDecoder;
+ POpenCodec RAOpenCodec;
+ POpenCodec2 RAOpenCodec2;
+ PSetFlavor RASetFlavor;
+ PSetDLLAccessPath RASetDLLAccessPath;
+ PSetPwd RASetPwd;
+
+ CStringA m_dllpath;
+ HMODULE m_hDrvDll;
+ DWORD m_dwCookie;
+
+ HRESULT InitRA(const CMediaType* pmt);
+ void FreeRA();
+
+ REFERENCE_TIME m_tStart;
+
+ rainfo m_rai;
+ CAutoVectorPtr<BYTE> m_buff;
+ int m_bufflen;
+ REFERENCE_TIME m_rtBuffStart;
+ bool m_fBuffDiscontinuity;
public:
- CRealAudioDecoder(LPUNKNOWN lpunk, HRESULT* phr);
- virtual ~CRealAudioDecoder();
+ CRealAudioDecoder(LPUNKNOWN lpunk, HRESULT* phr);
+ virtual ~CRealAudioDecoder();
- HRESULT Receive(IMediaSample* pIn);
- HRESULT CheckInputType(const CMediaType* mtIn);
- HRESULT CheckTransform(const CMediaType* mtIn, const CMediaType* mtOut);
- HRESULT DecideBufferSize(IMemAllocator* pAllocator, ALLOCATOR_PROPERTIES* pProperties);
- HRESULT GetMediaType(int iPosition, CMediaType* pMediaType);
+ HRESULT Receive(IMediaSample* pIn);
+ HRESULT CheckInputType(const CMediaType* mtIn);
+ HRESULT CheckTransform(const CMediaType* mtIn, const CMediaType* mtOut);
+ HRESULT DecideBufferSize(IMemAllocator* pAllocator, ALLOCATOR_PROPERTIES* pProperties);
+ HRESULT GetMediaType(int iPosition, CMediaType* pMediaType);
- HRESULT StartStreaming();
- HRESULT StopStreaming();
+ HRESULT StartStreaming();
+ HRESULT StopStreaming();
HRESULT EndOfStream();
HRESULT BeginFlush();
diff --git a/src/filters/parser/RealMediaSplitter/resource.h b/src/filters/parser/RealMediaSplitter/resource.h
index 713badf0e..68f7b566d 100644
--- a/src/filters/parser/RealMediaSplitter/resource.h
+++ b/src/filters/parser/RealMediaSplitter/resource.h
@@ -3,7 +3,7 @@
// Used by RealMediaSplitter.rc
// Next default values for new objects
-//
+//
#ifdef APSTUDIO_INVOKED
#ifndef APSTUDIO_READONLY_SYMBOLS
#define _APS_NEXT_RESOURCE_VALUE 101
diff --git a/src/filters/parser/RealMediaSplitter/stdafx.cpp b/src/filters/parser/RealMediaSplitter/stdafx.cpp
index 54ea1d445..8a7154bc7 100644
--- a/src/filters/parser/RealMediaSplitter/stdafx.cpp
+++ b/src/filters/parser/RealMediaSplitter/stdafx.cpp
@@ -1,4 +1,4 @@
-/*
+/*
* Copyright (C) 2003-2006 Gabest
* http://www.gabest.org
*
@@ -6,15 +6,15 @@
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2, or (at your option)
* any later version.
- *
+ *
* This Program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with GNU Make; see the file COPYING. If not, write to
- * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
+ * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
* http://www.gnu.org/copyleft/gpl.html
*
*/
diff --git a/src/filters/parser/RealMediaSplitter/stdafx.h b/src/filters/parser/RealMediaSplitter/stdafx.h
index 6fe7f24f9..f7ba733d1 100644
--- a/src/filters/parser/RealMediaSplitter/stdafx.h
+++ b/src/filters/parser/RealMediaSplitter/stdafx.h
@@ -1,4 +1,4 @@
-/*
+/*
* Copyright (C) 2003-2006 Gabest
* http://www.gabest.org
*
@@ -6,15 +6,15 @@
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2, or (at your option)
* any later version.
- *
+ *
* This Program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with GNU Make; see the file COPYING. If not, write to
- * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
+ * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
* http://www.gnu.org/copyleft/gpl.html
*
*/
diff --git a/src/filters/parser/RoQSplitter/RoQSplitter.cpp b/src/filters/parser/RoQSplitter/RoQSplitter.cpp
index 2c6fcafca..78545aef3 100644
--- a/src/filters/parser/RoQSplitter/RoQSplitter.cpp
+++ b/src/filters/parser/RoQSplitter/RoQSplitter.cpp
@@ -1,4 +1,4 @@
-/*
+/*
* Copyright (C) 2003-2006 Gabest
* http://www.gabest.org
*
@@ -6,15 +6,15 @@
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2, or (at your option)
* any later version.
- *
+ *
* This Program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with GNU Make; see the file COPYING. If not, write to
- * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
+ * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
* http://www.gnu.org/copyleft/gpl.html
*
*/
@@ -28,8 +28,8 @@
const AMOVIESETUP_MEDIATYPE sudPinTypesIn[] =
{
- {&MEDIATYPE_Stream, &MEDIASUBTYPE_RoQ},
- {&MEDIATYPE_Stream, &MEDIASUBTYPE_NULL},
+ {&MEDIATYPE_Stream, &MEDIASUBTYPE_RoQ},
+ {&MEDIATYPE_Stream, &MEDIASUBTYPE_NULL},
};
const AMOVIESETUP_PIN sudpPins[] =
@@ -40,12 +40,12 @@ const AMOVIESETUP_PIN sudpPins[] =
const AMOVIESETUP_MEDIATYPE sudPinTypesIn2[] =
{
- {&MEDIATYPE_Video, &MEDIASUBTYPE_RoQV},
+ {&MEDIATYPE_Video, &MEDIASUBTYPE_RoQV},
};
const AMOVIESETUP_MEDIATYPE sudPinTypesOut2[] =
{
- {&MEDIATYPE_Video, &MEDIASUBTYPE_NULL},
+ {&MEDIATYPE_Video, &MEDIASUBTYPE_NULL},
};
const AMOVIESETUP_PIN sudpPins2[] =
@@ -56,12 +56,12 @@ const AMOVIESETUP_PIN sudpPins2[] =
const AMOVIESETUP_MEDIATYPE sudPinTypesIn3[] =
{
- {&MEDIATYPE_Audio, &MEDIASUBTYPE_RoQA},
+ {&MEDIATYPE_Audio, &MEDIASUBTYPE_RoQA},
};
const AMOVIESETUP_MEDIATYPE sudPinTypesOut3[] =
{
- {&MEDIATYPE_Audio, &MEDIASUBTYPE_PCM},
+ {&MEDIATYPE_Audio, &MEDIASUBTYPE_PCM},
};
const AMOVIESETUP_PIN sudpPins3[] =
@@ -72,16 +72,16 @@ const AMOVIESETUP_PIN sudpPins3[] =
const AMOVIESETUP_FILTER sudFilter[] =
{
- {&__uuidof(CRoQSplitterFilter), L"MPC - RoQ Splitter", MERIT_NORMAL + 1, countof(sudpPins), sudpPins, CLSID_LegacyAmFilterCategory},
- {&__uuidof(CRoQSourceFilter), L"MPC - RoQ Source", MERIT_NORMAL + 1, 0, NULL, CLSID_LegacyAmFilterCategory},
- {&__uuidof(CRoQVideoDecoder), L"MPC - RoQ Video Decoder", MERIT_NORMAL, countof(sudpPins2), sudpPins2, CLSID_LegacyAmFilterCategory},
- {&__uuidof(CRoQAudioDecoder), L"MPC - RoQ Audio Decoder", MERIT_NORMAL, countof(sudpPins3), sudpPins3, CLSID_LegacyAmFilterCategory},
+ {&__uuidof(CRoQSplitterFilter), L"MPC - RoQ Splitter", MERIT_NORMAL+1, countof(sudpPins), sudpPins, CLSID_LegacyAmFilterCategory},
+ {&__uuidof(CRoQSourceFilter), L"MPC - RoQ Source", MERIT_NORMAL+1, 0, NULL, CLSID_LegacyAmFilterCategory},
+ {&__uuidof(CRoQVideoDecoder), L"MPC - RoQ Video Decoder", MERIT_NORMAL, countof(sudpPins2), sudpPins2, CLSID_LegacyAmFilterCategory},
+ {&__uuidof(CRoQAudioDecoder), L"MPC - RoQ Audio Decoder", MERIT_NORMAL, countof(sudpPins3), sudpPins3, CLSID_LegacyAmFilterCategory},
};
CFactoryTemplate g_Templates[] =
{
- {sudFilter[0].strName, sudFilter[0].clsID, CreateInstance<CRoQSplitterFilter>, NULL, &sudFilter[0]},
- {sudFilter[1].strName, sudFilter[1].clsID, CreateInstance<CRoQSourceFilter>, NULL, &sudFilter[1]},
+ {sudFilter[0].strName, sudFilter[0].clsID, CreateInstance<CRoQSplitterFilter>, NULL, &sudFilter[0]},
+ {sudFilter[1].strName, sudFilter[1].clsID, CreateInstance<CRoQSourceFilter>, NULL, &sudFilter[1]},
{sudFilter[2].strName, sudFilter[2].clsID, CreateInstance<CRoQVideoDecoder>, NULL, &sudFilter[2]},
{sudFilter[3].strName, sudFilter[3].clsID, CreateInstance<CRoQAudioDecoder>, NULL, &sudFilter[3]},
};
@@ -90,16 +90,16 @@ int g_cTemplates = countof(g_Templates);
STDAPI DllRegisterServer()
{
- RegisterSourceFilter(CLSID_AsyncReader, MEDIASUBTYPE_RoQ, _T("0,8,,8410FFFFFFFF1E00"), _T(".roq"), NULL);
+ RegisterSourceFilter(CLSID_AsyncReader, MEDIASUBTYPE_RoQ, _T("0,8,,8410FFFFFFFF1E00"), _T(".roq"), NULL);
- return AMovieDllRegisterServer2(TRUE);
+ return AMovieDllRegisterServer2(TRUE);
}
STDAPI DllUnregisterServer()
{
- UnRegisterSourceFilter(MEDIASUBTYPE_RoQ);
+ UnRegisterSourceFilter(MEDIASUBTYPE_RoQ);
- return AMovieDllRegisterServer2(FALSE);
+ return AMovieDllRegisterServer2(FALSE);
}
#include "../../FilterApp.h"
@@ -113,206 +113,206 @@ CFilterApp theApp;
//
CRoQSplitterFilter::CRoQSplitterFilter(LPUNKNOWN pUnk, HRESULT* phr)
- : CBaseSplitterFilter(NAME("CRoQSplitterFilter"), pUnk, phr, __uuidof(this))
+ : CBaseSplitterFilter(NAME("CRoQSplitterFilter"), pUnk, phr, __uuidof(this))
{
}
HRESULT CRoQSplitterFilter::CreateOutputs(IAsyncReader* pAsyncReader)
{
- CheckPointer(pAsyncReader, E_POINTER);
-
- HRESULT hr = E_FAIL;
-
- m_pAsyncReader = pAsyncReader;
-
- UINT64 hdr = 0, hdrchk = 0x001effffffff1084;
- m_pAsyncReader->SyncRead(0, 8, (BYTE*)&hdr);
- if(hdr != hdrchk) return E_FAIL;
-
- //
-
- m_rtNewStart = m_rtCurrent = 0;
- m_rtNewStop = m_rtStop = m_rtDuration = 0;
-
- // pins
-
- CMediaType mt;
- CAtlArray<CMediaType> mts;
-
- int iHasVideo = 0;
- int iHasAudio = 0;
-
- m_index.RemoveAll();
- __int64 audiosamples = 0;
-
- roq_info ri;
- memset(&ri, 0, sizeof(ri));
-
- roq_chunk rc;
-
- UINT64 pos = 8;
-
- while(S_OK == m_pAsyncReader->SyncRead(pos, sizeof(rc), (BYTE*)&rc))
- {
- pos += sizeof(rc);
-
- if(rc.id == 0x1001)
- {
- if(S_OK != m_pAsyncReader->SyncRead(pos, sizeof(ri), (BYTE*)&ri) || ri.w == 0 || ri.h == 0)
- break;
- }
- else if(rc.id == 0x1002 || rc.id == 0x1011)
- {
- if(!iHasVideo && ri.w > 0 && ri.h > 0)
- {
- mts.RemoveAll();
-
- mt.InitMediaType();
- mt.majortype = MEDIATYPE_Video;
- mt.subtype = MEDIASUBTYPE_RoQV;
- mt.formattype = FORMAT_VideoInfo;
- VIDEOINFOHEADER vih;
- memset(&vih, 0, sizeof(vih));
- vih.AvgTimePerFrame = 10000000i64 / 30;
- vih.bmiHeader.biSize = sizeof(vih.bmiHeader.biSize);
- vih.bmiHeader.biWidth = ri.w;
- vih.bmiHeader.biHeight = ri.h;
- vih.bmiHeader.biCompression = MEDIASUBTYPE_RoQV.Data1;
- mt.SetFormat((BYTE*)&vih, sizeof(vih));
- mt.lSampleSize = 1;
-
- mts.Add(mt);
-
- CAutoPtr<CBaseSplitterOutputPin> pPinOut(DNew CBaseSplitterOutputPin(mts, L"Video", this, this, &hr));
- AddOutputPin(0, pPinOut);
- }
-
- if(rc.id == 0x1002)
- {
- iHasVideo++;
-
- index i;
- i.rtv = 10000000i64 * m_index.GetCount() / 30;
- i.rta = 10000000i64 * audiosamples / 22050;
- i.fp = pos - sizeof(rc);
- m_index.AddTail(i);
- }
- }
- else if(rc.id == 0x1020 || rc.id == 0x1021)
- {
- if(!iHasAudio)
- {
- mts.RemoveAll();
-
- mt.InitMediaType();
- mt.majortype = MEDIATYPE_Audio;
- mt.subtype = MEDIASUBTYPE_RoQA;
- mt.formattype = FORMAT_WaveFormatEx;
- WAVEFORMATEX wfe;
- memset(&wfe, 0, sizeof(wfe));
- wfe.wFormatTag = (WORD)WAVE_FORMAT_RoQA; // cut into half, hehe, like anyone would care
- wfe.nChannels = (rc.id & 1) + 1;
- wfe.nSamplesPerSec = 22050;
- wfe.wBitsPerSample = 16;
- mt.SetFormat((BYTE*)&wfe, sizeof(wfe));
- mt.lSampleSize = 1;
- mts.Add(mt);
-
- CAutoPtr<CBaseSplitterOutputPin> pPinOut(DNew CBaseSplitterOutputPin(mts, L"Audio", this, this, &hr));
- AddOutputPin(1, pPinOut);
- }
-
- iHasAudio++;
-
- audiosamples += rc.size / ((rc.id & 1) + 1);
- }
-
- pos += rc.size;
- }
-
- //
-
- m_rtNewStop = m_rtStop = m_rtDuration = 10000000i64 * iHasVideo / 30;
-
- return m_pOutputs.GetCount() > 0 ? S_OK : E_FAIL;
+ CheckPointer(pAsyncReader, E_POINTER);
+
+ HRESULT hr = E_FAIL;
+
+ m_pAsyncReader = pAsyncReader;
+
+ UINT64 hdr = 0, hdrchk = 0x001effffffff1084;
+ m_pAsyncReader->SyncRead(0, 8, (BYTE*)&hdr);
+ if(hdr != hdrchk) return E_FAIL;
+
+ //
+
+ m_rtNewStart = m_rtCurrent = 0;
+ m_rtNewStop = m_rtStop = m_rtDuration = 0;
+
+ // pins
+
+ CMediaType mt;
+ CAtlArray<CMediaType> mts;
+
+ int iHasVideo = 0;
+ int iHasAudio = 0;
+
+ m_index.RemoveAll();
+ __int64 audiosamples = 0;
+
+ roq_info ri;
+ memset(&ri, 0, sizeof(ri));
+
+ roq_chunk rc;
+
+ UINT64 pos = 8;
+
+ while(S_OK == m_pAsyncReader->SyncRead(pos, sizeof(rc), (BYTE*)&rc))
+ {
+ pos += sizeof(rc);
+
+ if(rc.id == 0x1001)
+ {
+ if(S_OK != m_pAsyncReader->SyncRead(pos, sizeof(ri), (BYTE*)&ri) || ri.w == 0 || ri.h == 0)
+ break;
+ }
+ else if(rc.id == 0x1002 || rc.id == 0x1011)
+ {
+ if(!iHasVideo && ri.w > 0 && ri.h > 0)
+ {
+ mts.RemoveAll();
+
+ mt.InitMediaType();
+ mt.majortype = MEDIATYPE_Video;
+ mt.subtype = MEDIASUBTYPE_RoQV;
+ mt.formattype = FORMAT_VideoInfo;
+ VIDEOINFOHEADER vih;
+ memset(&vih, 0, sizeof(vih));
+ vih.AvgTimePerFrame = 10000000i64/30;
+ vih.bmiHeader.biSize = sizeof(vih.bmiHeader.biSize);
+ vih.bmiHeader.biWidth = ri.w;
+ vih.bmiHeader.biHeight = ri.h;
+ vih.bmiHeader.biCompression = MEDIASUBTYPE_RoQV.Data1;
+ mt.SetFormat((BYTE*)&vih, sizeof(vih));
+ mt.lSampleSize = 1;
+
+ mts.Add(mt);
+
+ CAutoPtr<CBaseSplitterOutputPin> pPinOut(DNew CBaseSplitterOutputPin(mts, L"Video", this, this, &hr));
+ AddOutputPin(0, pPinOut);
+ }
+
+ if(rc.id == 0x1002)
+ {
+ iHasVideo++;
+
+ index i;
+ i.rtv = 10000000i64*m_index.GetCount()/30;
+ i.rta = 10000000i64*audiosamples/22050;
+ i.fp = pos - sizeof(rc);
+ m_index.AddTail(i);
+ }
+ }
+ else if(rc.id == 0x1020 || rc.id == 0x1021)
+ {
+ if(!iHasAudio)
+ {
+ mts.RemoveAll();
+
+ mt.InitMediaType();
+ mt.majortype = MEDIATYPE_Audio;
+ mt.subtype = MEDIASUBTYPE_RoQA;
+ mt.formattype = FORMAT_WaveFormatEx;
+ WAVEFORMATEX wfe;
+ memset(&wfe, 0, sizeof(wfe));
+ wfe.wFormatTag = (WORD)WAVE_FORMAT_RoQA; // cut into half, hehe, like anyone would care
+ wfe.nChannels = (rc.id&1)+1;
+ wfe.nSamplesPerSec = 22050;
+ wfe.wBitsPerSample = 16;
+ mt.SetFormat((BYTE*)&wfe, sizeof(wfe));
+ mt.lSampleSize = 1;
+ mts.Add(mt);
+
+ CAutoPtr<CBaseSplitterOutputPin> pPinOut(DNew CBaseSplitterOutputPin(mts, L"Audio", this, this, &hr));
+ AddOutputPin(1, pPinOut);
+ }
+
+ iHasAudio++;
+
+ audiosamples += rc.size / ((rc.id&1)+1);
+ }
+
+ pos += rc.size;
+ }
+
+ //
+
+ m_rtNewStop = m_rtStop = m_rtDuration = 10000000i64*iHasVideo/30;
+
+ return m_pOutputs.GetCount() > 0 ? S_OK : E_FAIL;
}
bool CRoQSplitterFilter::DemuxInit()
{
- m_indexpos = m_index.GetHeadPosition();
+ m_indexpos = m_index.GetHeadPosition();
- return(true);
+ return(true);
}
void CRoQSplitterFilter::DemuxSeek(REFERENCE_TIME rt)
{
- if(rt <= 0)
- {
- m_indexpos = m_index.GetHeadPosition();
- }
- else
- {
- m_indexpos = m_index.GetTailPosition();
- while(m_indexpos && m_index.GetPrev(m_indexpos).rtv > rt);
- }
+ if(rt <= 0)
+ {
+ m_indexpos = m_index.GetHeadPosition();
+ }
+ else
+ {
+ m_indexpos = m_index.GetTailPosition();
+ while(m_indexpos && m_index.GetPrev(m_indexpos).rtv > rt);
+ }
}
bool CRoQSplitterFilter::DemuxLoop()
{
- if(!m_indexpos) return(true);
-
- index& i = m_index.GetAt(m_indexpos);
-
- REFERENCE_TIME rtVideo = i.rtv, rtAudio = i.rta;
-
- HRESULT hr = S_OK;
-
- UINT64 pos = i.fp;
-
- roq_chunk rc;
- while(S_OK == (hr = m_pAsyncReader->SyncRead(pos, sizeof(rc), (BYTE*)&rc))
- && !CheckRequest(NULL))
- {
- pos += sizeof(rc);
-
- CAutoPtr<Packet> p(DNew Packet());
-
- if(rc.id == 0x1002 || rc.id == 0x1011 || rc.id == 0x1020 || rc.id == 0x1021)
- {
- p->SetCount(sizeof(rc) + rc.size);
- memcpy(p->GetData(), &rc, sizeof(rc));
- if(S_OK != (hr = m_pAsyncReader->SyncRead(pos, rc.size, p->GetData() + sizeof(rc))))
- break;
- }
-
- if(rc.id == 0x1002 || rc.id == 0x1011)
- {
- p->TrackNumber = 0;
- p->bSyncPoint = rtVideo == 0;
- p->rtStart = rtVideo;
- p->rtStop = rtVideo += (rc.id == 0x1011 ? 10000000i64 / 30 : 0);
- TRACE(_T("v: %I64d - %I64d (%d)\n"), p->rtStart / 10000, p->rtStop / 10000, p->GetCount());
- }
- else if(rc.id == 0x1020 || rc.id == 0x1021)
- {
- int nChannels = (rc.id & 1) + 1;
-
- p->TrackNumber = 1;
- p->bSyncPoint = TRUE;
- p->rtStart = rtAudio;
- p->rtStop = rtAudio += 10000000i64 * rc.size / (nChannels * 22050);
- TRACE(_T("a: %I64d - %I64d (%d)\n"), p->rtStart / 10000, p->rtStop / 10000, p->GetCount());
- }
-
- if(rc.id == 0x1002 || rc.id == 0x1011 || rc.id == 0x1020 || rc.id == 0x1021)
- {
- hr = DeliverPacket(p);
- }
-
- pos += rc.size;
- }
-
- return(true);
+ if(!m_indexpos) return(true);
+
+ index& i = m_index.GetAt(m_indexpos);
+
+ REFERENCE_TIME rtVideo = i.rtv, rtAudio = i.rta;
+
+ HRESULT hr = S_OK;
+
+ UINT64 pos = i.fp;
+
+ roq_chunk rc;
+ while(S_OK == (hr = m_pAsyncReader->SyncRead(pos, sizeof(rc), (BYTE*)&rc))
+ && !CheckRequest(NULL))
+ {
+ pos += sizeof(rc);
+
+ CAutoPtr<Packet> p(DNew Packet());
+
+ if(rc.id == 0x1002 || rc.id == 0x1011 || rc.id == 0x1020 || rc.id == 0x1021)
+ {
+ p->SetCount(sizeof(rc) + rc.size);
+ memcpy(p->GetData(), &rc, sizeof(rc));
+ if(S_OK != (hr = m_pAsyncReader->SyncRead(pos, rc.size, p->GetData() + sizeof(rc))))
+ break;
+ }
+
+ if(rc.id == 0x1002 || rc.id == 0x1011)
+ {
+ p->TrackNumber = 0;
+ p->bSyncPoint = rtVideo == 0;
+ p->rtStart = rtVideo;
+ p->rtStop = rtVideo += (rc.id == 0x1011 ? 10000000i64/30 : 0);
+ TRACE(_T("v: %I64d - %I64d (%d)\n"), p->rtStart/10000, p->rtStop/10000, p->GetCount());
+ }
+ else if(rc.id == 0x1020 || rc.id == 0x1021)
+ {
+ int nChannels = (rc.id&1)+1;
+
+ p->TrackNumber = 1;
+ p->bSyncPoint = TRUE;
+ p->rtStart = rtAudio;
+ p->rtStop = rtAudio += 10000000i64*rc.size/(nChannels*22050);
+ TRACE(_T("a: %I64d - %I64d (%d)\n"), p->rtStart/10000, p->rtStop/10000, p->GetCount());
+ }
+
+ if(rc.id == 0x1002 || rc.id == 0x1011 || rc.id == 0x1020 || rc.id == 0x1021)
+ {
+ hr = DeliverPacket(p);
+ }
+
+ pos += rc.size;
+ }
+
+ return(true);
}
//
@@ -320,10 +320,10 @@ bool CRoQSplitterFilter::DemuxLoop()
//
CRoQSourceFilter::CRoQSourceFilter(LPUNKNOWN pUnk, HRESULT* phr)
- : CRoQSplitterFilter(pUnk, phr)
+ : CRoQSplitterFilter(pUnk, phr)
{
- m_clsid = __uuidof(this);
- m_pInput.Free();
+ m_clsid = __uuidof(this);
+ m_pInput.Free();
}
//
@@ -331,9 +331,9 @@ CRoQSourceFilter::CRoQSourceFilter(LPUNKNOWN pUnk, HRESULT* phr)
//
CRoQVideoDecoder::CRoQVideoDecoder(LPUNKNOWN lpunk, HRESULT* phr)
- : CTransformFilter(NAME("CRoQVideoDecoder"), lpunk, __uuidof(this))
+ : CTransformFilter(NAME("CRoQVideoDecoder"), lpunk, __uuidof(this))
{
- if(phr) *phr = S_OK;
+ if(phr) *phr = S_OK;
}
CRoQVideoDecoder::~CRoQVideoDecoder()
@@ -342,532 +342,505 @@ CRoQVideoDecoder::~CRoQVideoDecoder()
void CRoQVideoDecoder::apply_vector_2x2(int x, int y, roq_cell* cell)
{
- unsigned char* yptr;
- yptr = m_y[0] + (y * m_pitch) + x;
- *yptr++ = cell->y0;
- *yptr++ = cell->y1;
- yptr += (m_pitch - 2);
- *yptr++ = cell->y2;
- *yptr++ = cell->y3;
- m_u[0][(y/2) *(m_pitch/2) + x/2] = cell->u;
- m_v[0][(y/2) *(m_pitch/2) + x/2] = cell->v;
+ unsigned char* yptr;
+ yptr = m_y[0] + (y * m_pitch) + x;
+ *yptr++ = cell->y0;
+ *yptr++ = cell->y1;
+ yptr += (m_pitch - 2);
+ *yptr++ = cell->y2;
+ *yptr++ = cell->y3;
+ m_u[0][(y/2) * (m_pitch/2) + x/2] = cell->u;
+ m_v[0][(y/2) * (m_pitch/2) + x/2] = cell->v;
}
void CRoQVideoDecoder::apply_vector_4x4(int x, int y, roq_cell* cell)
{
- unsigned long row_inc, c_row_inc;
- register unsigned char y0, y1, u, v;
- unsigned char *yptr, *uptr, *vptr;
-
- yptr = m_y[0] + (y * m_pitch) + x;
- uptr = m_u[0] + (y / 2) * (m_pitch / 2) + x / 2;
- vptr = m_v[0] + (y / 2) * (m_pitch / 2) + x / 2;
-
- row_inc = m_pitch - 4;
- c_row_inc = (m_pitch / 2) - 2;
- *yptr++ = y0 = cell->y0;
- *uptr++ = u = cell->u;
- *vptr++ = v = cell->v;
- *yptr++ = y0;
- *yptr++ = y1 = cell->y1;
- *uptr++ = u;
- *vptr++ = v;
- *yptr++ = y1;
-
- yptr += row_inc;
-
- *yptr++ = y0;
- *yptr++ = y0;
- *yptr++ = y1;
- *yptr++ = y1;
-
- yptr += row_inc;
- uptr += c_row_inc;
- vptr += c_row_inc;
-
- *yptr++ = y0 = cell->y2;
- *uptr++ = u;
- *vptr++ = v;
- *yptr++ = y0;
- *yptr++ = y1 = cell->y3;
- *uptr++ = u;
- *vptr++ = v;
- *yptr++ = y1;
-
- yptr += row_inc;
-
- *yptr++ = y0;
- *yptr++ = y0;
- *yptr++ = y1;
- *yptr++ = y1;
+ unsigned long row_inc, c_row_inc;
+ register unsigned char y0, y1, u, v;
+ unsigned char *yptr, *uptr, *vptr;
+
+ yptr = m_y[0] + (y * m_pitch) + x;
+ uptr = m_u[0] + (y/2) * (m_pitch/2) + x/2;
+ vptr = m_v[0] + (y/2) * (m_pitch/2) + x/2;
+
+ row_inc = m_pitch - 4;
+ c_row_inc = (m_pitch/2) - 2;
+ *yptr++ = y0 = cell->y0; *uptr++ = u = cell->u; *vptr++ = v = cell->v;
+ *yptr++ = y0;
+ *yptr++ = y1 = cell->y1; *uptr++ = u; *vptr++ = v;
+ *yptr++ = y1;
+
+ yptr += row_inc;
+
+ *yptr++ = y0;
+ *yptr++ = y0;
+ *yptr++ = y1;
+ *yptr++ = y1;
+
+ yptr += row_inc; uptr += c_row_inc; vptr += c_row_inc;
+
+ *yptr++ = y0 = cell->y2; *uptr++ = u; *vptr++ = v;
+ *yptr++ = y0;
+ *yptr++ = y1 = cell->y3; *uptr++ = u; *vptr++ = v;
+ *yptr++ = y1;
+
+ yptr += row_inc;
+
+ *yptr++ = y0;
+ *yptr++ = y0;
+ *yptr++ = y1;
+ *yptr++ = y1;
}
void CRoQVideoDecoder::apply_motion_4x4(int x, int y, unsigned char mv, char mean_x, char mean_y)
{
- int i, mx, my;
- unsigned char *pa, *pb;
-
- mx = x + 8 - (mv >> 4) - mean_x;
- my = y + 8 - (mv & 0xf) - mean_y;
-
- pa = m_y[0] + (y * m_pitch) + x;
- pb = m_y[1] + (my * m_pitch) + mx;
- for(i = 0; i < 4; i++)
- {
- pa[0] = pb[0];
- pa[1] = pb[1];
- pa[2] = pb[2];
- pa[3] = pb[3];
- pa += m_pitch;
- pb += m_pitch;
- }
-
- pa = m_u[0] + (y / 2) * (m_pitch / 2) + x / 2;
- pb = m_u[1] + (my / 2) * (m_pitch / 2) + (mx + 1) / 2;
- for(i = 0; i < 2; i++)
- {
- pa[0] = pb[0];
- pa[1] = pb[1];
- pa += m_pitch / 2;
- pb += m_pitch / 2;
- }
-
- pa = m_v[0] + (y / 2) * (m_pitch / 2) + x / 2;
- pb = m_v[1] + (my / 2) * (m_pitch / 2) + (mx + 1) / 2;
- for(i = 0; i < 2; i++)
- {
- pa[0] = pb[0];
- pa[1] = pb[1];
- pa += m_pitch / 2;
- pb += m_pitch / 2;
- }
+ int i, mx, my;
+ unsigned char *pa, *pb;
+
+ mx = x + 8 - (mv >> 4) - mean_x;
+ my = y + 8 - (mv & 0xf) - mean_y;
+
+ pa = m_y[0] + (y * m_pitch) + x;
+ pb = m_y[1] + (my * m_pitch) + mx;
+ for(i = 0; i < 4; i++)
+ {
+ pa[0] = pb[0];
+ pa[1] = pb[1];
+ pa[2] = pb[2];
+ pa[3] = pb[3];
+ pa += m_pitch;
+ pb += m_pitch;
+ }
+
+ pa = m_u[0] + (y/2) * (m_pitch/2) + x/2;
+ pb = m_u[1] + (my/2) * (m_pitch/2) + (mx + 1)/2;
+ for(i = 0; i < 2; i++)
+ {
+ pa[0] = pb[0];
+ pa[1] = pb[1];
+ pa += m_pitch/2;
+ pb += m_pitch/2;
+ }
+
+ pa = m_v[0] + (y/2) * (m_pitch/2) + x/2;
+ pb = m_v[1] + (my/2) * (m_pitch/2) + (mx + 1)/2;
+ for(i = 0; i < 2; i++)
+ {
+ pa[0] = pb[0];
+ pa[1] = pb[1];
+ pa += m_pitch/2;
+ pb += m_pitch/2;
+ }
}
void CRoQVideoDecoder::apply_motion_8x8(int x, int y, unsigned char mv, char mean_x, char mean_y)
{
- int mx, my, i;
- unsigned char *pa, *pb;
-
- mx = x + 8 - (mv >> 4) - mean_x;
- my = y + 8 - (mv & 0xf) - mean_y;
-
- pa = m_y[0] + (y * m_pitch) + x;
- pb = m_y[1] + (my * m_pitch) + mx;
- for(i = 0; i < 8; i++)
- {
- pa[0] = pb[0];
- pa[1] = pb[1];
- pa[2] = pb[2];
- pa[3] = pb[3];
- pa[4] = pb[4];
- pa[5] = pb[5];
- pa[6] = pb[6];
- pa[7] = pb[7];
- pa += m_pitch;
- pb += m_pitch;
- }
-
- pa = m_u[0] + (y / 2) * (m_pitch / 2) + x / 2;
- pb = m_u[1] + (my / 2) * (m_pitch / 2) + (mx + 1) / 2;
- for(i = 0; i < 4; i++)
- {
- pa[0] = pb[0];
- pa[1] = pb[1];
- pa[2] = pb[2];
- pa[3] = pb[3];
- pa += m_pitch / 2;
- pb += m_pitch / 2;
- }
-
- pa = m_v[0] + (y / 2) * (m_pitch / 2) + x / 2;
- pb = m_v[1] + (my / 2) * (m_pitch / 2) + (mx + 1) / 2;
- for(i = 0; i < 4; i++)
- {
- pa[0] = pb[0];
- pa[1] = pb[1];
- pa[2] = pb[2];
- pa[3] = pb[3];
- pa += m_pitch / 2;
- pb += m_pitch / 2;
- }
+ int mx, my, i;
+ unsigned char *pa, *pb;
+
+ mx = x + 8 - (mv >> 4) - mean_x;
+ my = y + 8 - (mv & 0xf) - mean_y;
+
+ pa = m_y[0] + (y * m_pitch) + x;
+ pb = m_y[1] + (my * m_pitch) + mx;
+ for(i = 0; i < 8; i++)
+ {
+ pa[0] = pb[0];
+ pa[1] = pb[1];
+ pa[2] = pb[2];
+ pa[3] = pb[3];
+ pa[4] = pb[4];
+ pa[5] = pb[5];
+ pa[6] = pb[6];
+ pa[7] = pb[7];
+ pa += m_pitch;
+ pb += m_pitch;
+ }
+
+ pa = m_u[0] + (y/2) * (m_pitch/2) + x/2;
+ pb = m_u[1] + (my/2) * (m_pitch/2) + (mx + 1)/2;
+ for(i = 0; i < 4; i++)
+ {
+ pa[0] = pb[0];
+ pa[1] = pb[1];
+ pa[2] = pb[2];
+ pa[3] = pb[3];
+ pa += m_pitch/2;
+ pb += m_pitch/2;
+ }
+
+ pa = m_v[0] + (y/2) * (m_pitch/2) + x/2;
+ pb = m_v[1] + (my/2) * (m_pitch/2) + (mx + 1)/2;
+ for(i = 0; i < 4; i++)
+ {
+ pa[0] = pb[0];
+ pa[1] = pb[1];
+ pa[2] = pb[2];
+ pa[3] = pb[3];
+ pa += m_pitch/2;
+ pb += m_pitch/2;
+ }
}
HRESULT CRoQVideoDecoder::NewSegment(REFERENCE_TIME tStart, REFERENCE_TIME tStop, double dRate)
{
- CAutoLock cAutoLock(&m_csReceive);
+ CAutoLock cAutoLock(&m_csReceive);
- m_rtStart = tStart;
+ m_rtStart = tStart;
- BITMAPINFOHEADER bih;
- ExtractBIH(&m_pInput->CurrentMediaType(), &bih);
+ BITMAPINFOHEADER bih;
+ ExtractBIH(&m_pInput->CurrentMediaType(), &bih);
- int size = bih.biWidth * bih.biHeight;
+ int size = bih.biWidth*bih.biHeight;
- memset(m_y[0], 0, size);
- memset(m_u[0], 0x80, size / 2);
- memset(m_y[1], 0, size);
- memset(m_u[1], 0x80, size / 2);
+ memset(m_y[0], 0, size);
+ memset(m_u[0], 0x80, size/2);
+ memset(m_y[1], 0, size);
+ memset(m_u[1], 0x80, size/2);
- return __super::NewSegment(tStart, tStop, dRate);
+ return __super::NewSegment(tStart, tStop, dRate);
}
HRESULT CRoQVideoDecoder::Transform(IMediaSample* pIn, IMediaSample* pOut)
{
- CAutoLock cAutoLock(&m_csReceive);
-
- HRESULT hr;
-
- AM_MEDIA_TYPE* pmt;
- if(SUCCEEDED(pOut->GetMediaType(&pmt)) && pmt)
- {
- CMediaType mt(*pmt);
- m_pOutput->SetMediaType(&mt);
- DeleteMediaType(pmt);
- }
-
- BYTE* pDataIn = NULL;
- if(FAILED(hr = pIn->GetPointer(&pDataIn))) return hr;
-
- long len = pIn->GetActualDataLength();
- if(len <= 0) return S_OK; // nothing to do
-
- REFERENCE_TIME rtStart = 0, rtStop = 0;
- pIn->GetTime(&rtStart, &rtStop);
-
- if(pIn->IsPreroll() == S_OK || rtStart < 0)
- return S_OK;
-
- BYTE* pDataOut = NULL;
- if(FAILED(hr = pOut->GetPointer(&pDataOut)))
- return hr;
-
- BITMAPINFOHEADER bih;
- ExtractBIH(&m_pInput->CurrentMediaType(), &bih);
-
- int w = bih.biWidth, h = bih.biHeight;
-
- // TODO: decode picture into m_pI420
-
- roq_chunk* rc = (roq_chunk*)pDataIn;
-
- pDataIn += sizeof(roq_chunk);
-
- if(rc->id == 0x1002)
- {
- DWORD nv1 = rc->arg >> 8;
- if(nv1 == 0) nv1 = 256;
-
- DWORD nv2 = rc->arg & 0xff;
- if(nv2 == 0 && nv1 * 6 < rc->size) nv2 = 256;
-
- memcpy(m_cells, pDataIn, sizeof(m_cells[0])*nv1);
- pDataIn += sizeof(m_cells[0]) * nv1;
-
- for(int i = 0; i < (int)nv2; i++)
- for(int j = 0; j < 4; j++)
- m_qcells[i].idx[j] = &m_cells[*pDataIn++];
-
- return S_FALSE;
- }
- else if(rc->id == 0x1011)
- {
- int bpos = 0, xpos = 0, ypos = 0;
- int vqflg = 0, vqflg_pos = -1, vqid;
- roq_qcell* qcell = NULL;
-
- BYTE* buf = pDataIn;
-
- while(bpos < (int)rc->size && ypos < h)
- {
- for(int yp = ypos; yp < ypos + 16; yp += 8)
- {
- for(int xp = xpos; xp < xpos + 16; xp += 8)
- {
- if(vqflg_pos < 0)
- {
- vqflg = buf[bpos++];
- vqflg |= buf[bpos++] << 8;
- vqflg_pos = 7;
- }
-
- vqid = (vqflg >> (vqflg_pos * 2)) & 3;
- vqflg_pos--;
-
- switch(vqid)
- {
- case 0:
- break;
- case 1:
- apply_motion_8x8(xp, yp, buf[bpos++], rc->arg >> 8, rc->arg & 0xff);
- break;
- case 2:
- qcell = m_qcells + buf[bpos++];
- apply_vector_4x4(xp, yp, qcell->idx[0]);
- apply_vector_4x4(xp + 4, yp, qcell->idx[1]);
- apply_vector_4x4(xp, yp + 4, qcell->idx[2]);
- apply_vector_4x4(xp + 4, yp + 4, qcell->idx[3]);
- break;
- case 3:
- for(int k = 0; k < 4; k++)
- {
- int x = xp, y = yp;
- if(k & 1) x += 4;
- if(k & 2) y += 4;
-
- if(vqflg_pos < 0)
- {
- vqflg = buf[bpos++];
- vqflg |= buf[bpos++] << 8;
- vqflg_pos = 7;
- }
-
- vqid = (vqflg >> (vqflg_pos * 2)) & 3;
- vqflg_pos--;
-
- switch(vqid)
- {
- case 0:
- break;
- case 1:
- apply_motion_4x4(x, y, buf[bpos++], rc->arg >> 8, rc->arg & 0xff);
- break;
- case 2:
- qcell = m_qcells + buf[bpos++];
- apply_vector_2x2(x, y, qcell->idx[0]);
- apply_vector_2x2(x + 2, y, qcell->idx[1]);
- apply_vector_2x2(x, y + 2, qcell->idx[2]);
- apply_vector_2x2(x + 2, y + 2, qcell->idx[3]);
- break;
- case 3:
- apply_vector_2x2(x, y, &m_cells[buf[bpos++]]);
- apply_vector_2x2(x + 2, y, &m_cells[buf[bpos++]]);
- apply_vector_2x2(x, y + 2, &m_cells[buf[bpos++]]);
- apply_vector_2x2(x + 2, y + 2, &m_cells[buf[bpos++]]);
- break;
- }
- }
- break;
- }
- }
- }
-
- xpos += 16;
- if(xpos >= w)
- {
- xpos -= w;
- ypos += 16;
- }
- }
-
- if(m_rtStart + rtStart == 0)
- {
- memcpy(m_y[1], m_y[0], w * h * 3 / 2);
- }
- else
- {
- BYTE* tmp;
- tmp = m_y[0];
- m_y[0] = m_y[1];
- m_y[1] = tmp;
- tmp = m_u[0];
- m_u[0] = m_u[1];
- m_u[1] = tmp;
- tmp = m_v[0];
- m_v[0] = m_v[1];
- m_v[1] = tmp;
- }
- }
- else
- {
- return E_UNEXPECTED;
- }
-
- if(rtStart < 0)
- return S_FALSE;
-
- Copy(pDataOut, m_y[1], w, h);
-
- pOut->SetTime(&rtStart, &rtStop);
-
- return S_OK;
+ CAutoLock cAutoLock(&m_csReceive);
+
+ HRESULT hr;
+
+ AM_MEDIA_TYPE* pmt;
+ if(SUCCEEDED(pOut->GetMediaType(&pmt)) && pmt)
+ {
+ CMediaType mt(*pmt);
+ m_pOutput->SetMediaType(&mt);
+ DeleteMediaType(pmt);
+ }
+
+ BYTE* pDataIn = NULL;
+ if(FAILED(hr = pIn->GetPointer(&pDataIn))) return hr;
+
+ long len = pIn->GetActualDataLength();
+ if(len <= 0) return S_OK; // nothing to do
+
+ REFERENCE_TIME rtStart = 0, rtStop = 0;
+ pIn->GetTime(&rtStart, &rtStop);
+
+ if(pIn->IsPreroll() == S_OK || rtStart < 0)
+ return S_OK;
+
+ BYTE* pDataOut = NULL;
+ if(FAILED(hr = pOut->GetPointer(&pDataOut)))
+ return hr;
+
+ BITMAPINFOHEADER bih;
+ ExtractBIH(&m_pInput->CurrentMediaType(), &bih);
+
+ int w = bih.biWidth, h = bih.biHeight;
+
+ // TODO: decode picture into m_pI420
+
+ roq_chunk* rc = (roq_chunk*)pDataIn;
+
+ pDataIn += sizeof(roq_chunk);
+
+ if(rc->id == 0x1002)
+ {
+ DWORD nv1 = rc->arg>>8;
+ if(nv1 == 0) nv1 = 256;
+
+ DWORD nv2 = rc->arg&0xff;
+ if(nv2 == 0 && nv1 * 6 < rc->size) nv2 = 256;
+
+ memcpy(m_cells, pDataIn, sizeof(m_cells[0])*nv1);
+ pDataIn += sizeof(m_cells[0])*nv1;
+
+ for(int i = 0; i < (int)nv2; i++)
+ for(int j = 0; j < 4; j++)
+ m_qcells[i].idx[j] = &m_cells[*pDataIn++];
+
+ return S_FALSE;
+ }
+ else if(rc->id == 0x1011)
+ {
+ int bpos = 0, xpos = 0, ypos = 0;
+ int vqflg = 0, vqflg_pos = -1, vqid;
+ roq_qcell* qcell = NULL;
+
+ BYTE* buf = pDataIn;
+
+ while(bpos < (int)rc->size && ypos < h)
+ {
+ for(int yp = ypos; yp < ypos + 16; yp += 8)
+ {
+ for(int xp = xpos; xp < xpos + 16; xp += 8)
+ {
+ if(vqflg_pos < 0)
+ {
+ vqflg = buf[bpos++];
+ vqflg |= buf[bpos++]<<8;
+ vqflg_pos = 7;
+ }
+
+ vqid = (vqflg >> (vqflg_pos * 2)) & 3;
+ vqflg_pos--;
+
+ switch(vqid)
+ {
+ case 0:
+ break;
+ case 1:
+ apply_motion_8x8(xp, yp, buf[bpos++], rc->arg >> 8, rc->arg & 0xff);
+ break;
+ case 2:
+ qcell = m_qcells + buf[bpos++];
+ apply_vector_4x4(xp, yp, qcell->idx[0]);
+ apply_vector_4x4(xp+4, yp, qcell->idx[1]);
+ apply_vector_4x4(xp, yp+4, qcell->idx[2]);
+ apply_vector_4x4(xp+4, yp+4, qcell->idx[3]);
+ break;
+ case 3:
+ for(int k = 0; k < 4; k++)
+ {
+ int x = xp, y = yp;
+ if(k&1) x += 4;
+ if(k&2) y += 4;
+
+ if(vqflg_pos < 0)
+ {
+ vqflg = buf[bpos++];
+ vqflg |= buf[bpos++]<<8;
+ vqflg_pos = 7;
+ }
+
+ vqid = (vqflg >> (vqflg_pos * 2)) & 3;
+ vqflg_pos--;
+
+ switch(vqid)
+ {
+ case 0:
+ break;
+ case 1:
+ apply_motion_4x4(x, y, buf[bpos++], rc->arg >> 8, rc->arg & 0xff);
+ break;
+ case 2:
+ qcell = m_qcells + buf[bpos++];
+ apply_vector_2x2(x, y, qcell->idx[0]);
+ apply_vector_2x2(x+2, y, qcell->idx[1]);
+ apply_vector_2x2(x, y+2, qcell->idx[2]);
+ apply_vector_2x2(x+2, y+2, qcell->idx[3]);
+ break;
+ case 3:
+ apply_vector_2x2(x, y, &m_cells[buf[bpos++]]);
+ apply_vector_2x2(x+2, y, &m_cells[buf[bpos++]]);
+ apply_vector_2x2(x, y+2, &m_cells[buf[bpos++]]);
+ apply_vector_2x2(x+2, y+2, &m_cells[buf[bpos++]]);
+ break;
+ }
+ }
+ break;
+ }
+ }
+ }
+
+ xpos += 16;
+ if(xpos >= w) {xpos -= w; ypos += 16;}
+ }
+
+ if(m_rtStart+rtStart == 0)
+ {
+ memcpy(m_y[1], m_y[0], w*h*3/2);
+ }
+ else
+ {
+ BYTE* tmp;
+ tmp = m_y[0]; m_y[0] = m_y[1]; m_y[1] = tmp;
+ tmp = m_u[0]; m_u[0] = m_u[1]; m_u[1] = tmp;
+ tmp = m_v[0]; m_v[0] = m_v[1]; m_v[1] = tmp;
+ }
+ }
+ else
+ {
+ return E_UNEXPECTED;
+ }
+
+ if(rtStart < 0)
+ return S_FALSE;
+
+ Copy(pDataOut, m_y[1], w, h);
+
+ pOut->SetTime(&rtStart, &rtStop);
+
+ return S_OK;
}
void CRoQVideoDecoder::Copy(BYTE* pOut, BYTE* pIn, DWORD w, DWORD h)
{
- BITMAPINFOHEADER bihOut;
- ExtractBIH(&m_pOutput->CurrentMediaType(), &bihOut);
-
- int pitchIn = w;
- int pitchInUV = pitchIn >> 1;
- BYTE* pInU = pIn + pitchIn * h;
- BYTE* pInV = pInU + pitchInUV * h / 2;
-
- if(bihOut.biCompression == '2YUY')
- {
- BitBltFromI420ToYUY2(w, h, pOut, bihOut.biWidth * 2, pIn, pInU, pInV, pitchIn);
- }
- else if(bihOut.biCompression == 'I420' || bihOut.biCompression == 'VUYI')
- {
- BitBltFromI420ToI420(w, h, pOut, pOut + bihOut.biWidth * h, pOut + bihOut.biWidth * h * 5 / 4, bihOut.biWidth, pIn, pInU, pInV, pitchIn);
- }
- else if(bihOut.biCompression == '21VY')
- {
- BitBltFromI420ToI420(w, h, pOut, pOut + bihOut.biWidth * h * 5 / 4, pOut + bihOut.biWidth * h, bihOut.biWidth, pIn, pInU, pInV, pitchIn);
- }
- else if(bihOut.biCompression == BI_RGB || bihOut.biCompression == BI_BITFIELDS)
- {
- int pitchOut = bihOut.biWidth * bihOut.biBitCount >> 3;
-
- if(bihOut.biHeight > 0)
- {
- pOut += pitchOut * (h - 1);
- pitchOut = -pitchOut;
- }
-
- if(!BitBltFromI420ToRGB(w, h, pOut, pitchOut, bihOut.biBitCount, pIn, pInU, pInV, pitchIn))
- {
- for(DWORD y = 0; y < h; y++, pIn += pitchIn, pOut += pitchOut)
- memset(pOut, 0, pitchOut);
- }
- }
+ BITMAPINFOHEADER bihOut;
+ ExtractBIH(&m_pOutput->CurrentMediaType(), &bihOut);
+
+ int pitchIn = w;
+ int pitchInUV = pitchIn>>1;
+ BYTE* pInU = pIn + pitchIn*h;
+ BYTE* pInV = pInU + pitchInUV*h/2;
+
+ if(bihOut.biCompression == '2YUY')
+ {
+ BitBltFromI420ToYUY2(w, h, pOut, bihOut.biWidth*2, pIn, pInU, pInV, pitchIn);
+ }
+ else if(bihOut.biCompression == 'I420' || bihOut.biCompression == 'VUYI')
+ {
+ BitBltFromI420ToI420(w, h, pOut, pOut + bihOut.biWidth*h, pOut + bihOut.biWidth*h*5/4, bihOut.biWidth, pIn, pInU, pInV, pitchIn);
+ }
+ else if(bihOut.biCompression == '21VY')
+ {
+ BitBltFromI420ToI420(w, h, pOut, pOut + bihOut.biWidth*h*5/4, pOut + bihOut.biWidth*h, bihOut.biWidth, pIn, pInU, pInV, pitchIn);
+ }
+ else if(bihOut.biCompression == BI_RGB || bihOut.biCompression == BI_BITFIELDS)
+ {
+ int pitchOut = bihOut.biWidth*bihOut.biBitCount>>3;
+
+ if(bihOut.biHeight > 0)
+ {
+ pOut += pitchOut*(h-1);
+ pitchOut = -pitchOut;
+ }
+
+ if(!BitBltFromI420ToRGB(w, h, pOut, pitchOut, bihOut.biBitCount, pIn, pInU, pInV, pitchIn))
+ {
+ for(DWORD y = 0; y < h; y++, pIn += pitchIn, pOut += pitchOut)
+ memset(pOut, 0, pitchOut);
+ }
+ }
}
HRESULT CRoQVideoDecoder::CheckInputType(const CMediaType* mtIn)
{
- return mtIn->majortype == MEDIATYPE_Video && mtIn->subtype == MEDIASUBTYPE_RoQV
- ? S_OK
- : VFW_E_TYPE_NOT_ACCEPTED;
+ return mtIn->majortype == MEDIATYPE_Video && mtIn->subtype == MEDIASUBTYPE_RoQV
+ ? S_OK
+ : VFW_E_TYPE_NOT_ACCEPTED;
}
HRESULT CRoQVideoDecoder::CheckTransform(const CMediaType* mtIn, const CMediaType* mtOut)
{
- if(m_pOutput && m_pOutput->IsConnected())
- {
- BITMAPINFOHEADER bih1, bih2;
- if(ExtractBIH(mtOut, &bih1) && ExtractBIH(&m_pOutput->CurrentMediaType(), &bih2)
- && abs(bih1.biHeight) != abs(bih2.biHeight))
- return VFW_E_TYPE_NOT_ACCEPTED;
- }
-
- return SUCCEEDED(CheckInputType(mtIn))
- && mtOut->majortype == MEDIATYPE_Video && (mtOut->subtype == MEDIASUBTYPE_YUY2
- || mtOut->subtype == MEDIASUBTYPE_YV12
- || mtOut->subtype == MEDIASUBTYPE_I420
- || mtOut->subtype == MEDIASUBTYPE_IYUV
- || mtOut->subtype == MEDIASUBTYPE_ARGB32
- || mtOut->subtype == MEDIASUBTYPE_RGB32
- || mtOut->subtype == MEDIASUBTYPE_RGB24
- || mtOut->subtype == MEDIASUBTYPE_RGB565
- || mtOut->subtype == MEDIASUBTYPE_RGB555)
- ? S_OK
- : VFW_E_TYPE_NOT_ACCEPTED;
+ if(m_pOutput && m_pOutput->IsConnected())
+ {
+ BITMAPINFOHEADER bih1, bih2;
+ if(ExtractBIH(mtOut, &bih1) && ExtractBIH(&m_pOutput->CurrentMediaType(), &bih2)
+ && abs(bih1.biHeight) != abs(bih2.biHeight))
+ return VFW_E_TYPE_NOT_ACCEPTED;
+ }
+
+ return SUCCEEDED(CheckInputType(mtIn))
+ && mtOut->majortype == MEDIATYPE_Video && (mtOut->subtype == MEDIASUBTYPE_YUY2
+ || mtOut->subtype == MEDIASUBTYPE_YV12
+ || mtOut->subtype == MEDIASUBTYPE_I420
+ || mtOut->subtype == MEDIASUBTYPE_IYUV
+ || mtOut->subtype == MEDIASUBTYPE_ARGB32
+ || mtOut->subtype == MEDIASUBTYPE_RGB32
+ || mtOut->subtype == MEDIASUBTYPE_RGB24
+ || mtOut->subtype == MEDIASUBTYPE_RGB565
+ || mtOut->subtype == MEDIASUBTYPE_RGB555)
+ ? S_OK
+ : VFW_E_TYPE_NOT_ACCEPTED;
}
HRESULT CRoQVideoDecoder::DecideBufferSize(IMemAllocator* pAllocator, ALLOCATOR_PROPERTIES* pProperties)
{
- if(m_pInput->IsConnected() == FALSE) return E_UNEXPECTED;
+ if(m_pInput->IsConnected() == FALSE) return E_UNEXPECTED;
- BITMAPINFOHEADER bih;
- ExtractBIH(&m_pOutput->CurrentMediaType(), &bih);
+ BITMAPINFOHEADER bih;
+ ExtractBIH(&m_pOutput->CurrentMediaType(), &bih);
- pProperties->cBuffers = 1;
- pProperties->cbBuffer = bih.biSizeImage;
- pProperties->cbAlign = 1;
- pProperties->cbPrefix = 0;
+ pProperties->cBuffers = 1;
+ pProperties->cbBuffer = bih.biSizeImage;
+ pProperties->cbAlign = 1;
+ pProperties->cbPrefix = 0;
- HRESULT hr;
- ALLOCATOR_PROPERTIES Actual;
- if(FAILED(hr = pAllocator->SetProperties(pProperties, &Actual)))
- return hr;
+ HRESULT hr;
+ ALLOCATOR_PROPERTIES Actual;
+ if(FAILED(hr = pAllocator->SetProperties(pProperties, &Actual)))
+ return hr;
return(pProperties->cBuffers > Actual.cBuffers || pProperties->cbBuffer > Actual.cbBuffer
- ? E_FAIL
- : NOERROR);
+ ? E_FAIL
+ : NOERROR);
}
HRESULT CRoQVideoDecoder::GetMediaType(int iPosition, CMediaType* pmt)
{
if(m_pInput->IsConnected() == FALSE) return E_UNEXPECTED;
- struct
- {
- const GUID* subtype;
- WORD biPlanes, biBitCount;
- DWORD biCompression;
- } fmts[] =
- {
- {&MEDIASUBTYPE_YV12, 3, 12, '21VY'},
- {&MEDIASUBTYPE_I420, 3, 12, '024I'},
- {&MEDIASUBTYPE_IYUV, 3, 12, 'VUYI'},
- {&MEDIASUBTYPE_YUY2, 1, 16, '2YUY'},
- {&MEDIASUBTYPE_ARGB32, 1, 32, BI_RGB},
- {&MEDIASUBTYPE_RGB32, 1, 32, BI_RGB},
- {&MEDIASUBTYPE_RGB24, 1, 24, BI_RGB},
- {&MEDIASUBTYPE_RGB565, 1, 16, BI_RGB},
- {&MEDIASUBTYPE_RGB555, 1, 16, BI_RGB},
- {&MEDIASUBTYPE_ARGB32, 1, 32, BI_BITFIELDS},
- {&MEDIASUBTYPE_RGB32, 1, 32, BI_BITFIELDS},
- {&MEDIASUBTYPE_RGB24, 1, 24, BI_BITFIELDS},
- {&MEDIASUBTYPE_RGB565, 1, 16, BI_BITFIELDS},
- {&MEDIASUBTYPE_RGB555, 1, 16, BI_BITFIELDS},
- };
-
- if(iPosition < 0) return E_INVALIDARG;
- if(iPosition >= countof(fmts)) return VFW_S_NO_MORE_ITEMS;
-
- BITMAPINFOHEADER bih;
- ExtractBIH(&m_pInput->CurrentMediaType(), &bih);
-
- pmt->majortype = MEDIATYPE_Video;
- pmt->subtype = *fmts[iPosition].subtype;
- pmt->formattype = FORMAT_VideoInfo;
-
- BITMAPINFOHEADER bihOut;
- memset(&bihOut, 0, sizeof(bihOut));
- bihOut.biSize = sizeof(bihOut);
- bihOut.biWidth = bih.biWidth;
- bihOut.biHeight = bih.biHeight;
- bihOut.biPlanes = fmts[iPosition].biPlanes;
- bihOut.biBitCount = fmts[iPosition].biBitCount;
- bihOut.biCompression = fmts[iPosition].biCompression;
- bihOut.biSizeImage = bih.biWidth * bih.biHeight * bihOut.biBitCount >> 3;
-
- VIDEOINFOHEADER* vih = (VIDEOINFOHEADER*)pmt->AllocFormatBuffer(sizeof(VIDEOINFOHEADER));
- memset(vih, 0, sizeof(VIDEOINFOHEADER));
- vih->bmiHeader = bihOut;
-
- CorrectMediaType(pmt);
-
- return S_OK;
+ struct {const GUID* subtype; WORD biPlanes, biBitCount; DWORD biCompression;} fmts[] =
+ {
+ {&MEDIASUBTYPE_YV12, 3, 12, '21VY'},
+ {&MEDIASUBTYPE_I420, 3, 12, '024I'},
+ {&MEDIASUBTYPE_IYUV, 3, 12, 'VUYI'},
+ {&MEDIASUBTYPE_YUY2, 1, 16, '2YUY'},
+ {&MEDIASUBTYPE_ARGB32, 1, 32, BI_RGB},
+ {&MEDIASUBTYPE_RGB32, 1, 32, BI_RGB},
+ {&MEDIASUBTYPE_RGB24, 1, 24, BI_RGB},
+ {&MEDIASUBTYPE_RGB565, 1, 16, BI_RGB},
+ {&MEDIASUBTYPE_RGB555, 1, 16, BI_RGB},
+ {&MEDIASUBTYPE_ARGB32, 1, 32, BI_BITFIELDS},
+ {&MEDIASUBTYPE_RGB32, 1, 32, BI_BITFIELDS},
+ {&MEDIASUBTYPE_RGB24, 1, 24, BI_BITFIELDS},
+ {&MEDIASUBTYPE_RGB565, 1, 16, BI_BITFIELDS},
+ {&MEDIASUBTYPE_RGB555, 1, 16, BI_BITFIELDS},
+ };
+
+ if(iPosition < 0) return E_INVALIDARG;
+ if(iPosition >= countof(fmts)) return VFW_S_NO_MORE_ITEMS;
+
+ BITMAPINFOHEADER bih;
+ ExtractBIH(&m_pInput->CurrentMediaType(), &bih);
+
+ pmt->majortype = MEDIATYPE_Video;
+ pmt->subtype = *fmts[iPosition].subtype;
+ pmt->formattype = FORMAT_VideoInfo;
+
+ BITMAPINFOHEADER bihOut;
+ memset(&bihOut, 0, sizeof(bihOut));
+ bihOut.biSize = sizeof(bihOut);
+ bihOut.biWidth = bih.biWidth;
+ bihOut.biHeight = bih.biHeight;
+ bihOut.biPlanes = fmts[iPosition].biPlanes;
+ bihOut.biBitCount = fmts[iPosition].biBitCount;
+ bihOut.biCompression = fmts[iPosition].biCompression;
+ bihOut.biSizeImage = bih.biWidth*bih.biHeight*bihOut.biBitCount>>3;
+
+ VIDEOINFOHEADER* vih = (VIDEOINFOHEADER*)pmt->AllocFormatBuffer(sizeof(VIDEOINFOHEADER));
+ memset(vih, 0, sizeof(VIDEOINFOHEADER));
+ vih->bmiHeader = bihOut;
+
+ CorrectMediaType(pmt);
+
+ return S_OK;
}
HRESULT CRoQVideoDecoder::StartStreaming()
{
- BITMAPINFOHEADER bih;
- ExtractBIH(&m_pInput->CurrentMediaType(), &bih);
+ BITMAPINFOHEADER bih;
+ ExtractBIH(&m_pInput->CurrentMediaType(), &bih);
- int size = bih.biWidth * bih.biHeight;
+ int size = bih.biWidth*bih.biHeight;
- m_y[0] = DNew BYTE[size*3/2];
- m_u[0] = m_y[0] + size;
- m_v[0] = m_y[0] + size * 5 / 4;
- m_y[1] = DNew BYTE[size*3/2];
- m_u[1] = m_y[1] + size;
- m_v[1] = m_y[1] + size * 5 / 4;
+ m_y[0] = DNew BYTE[size*3/2];
+ m_u[0] = m_y[0] + size;
+ m_v[0] = m_y[0] + size*5/4;
+ m_y[1] = DNew BYTE[size*3/2];
+ m_u[1] = m_y[1] + size;
+ m_v[1] = m_y[1] + size*5/4;
- m_pitch = bih.biWidth;
+ m_pitch = bih.biWidth;
- return __super::StartStreaming();
+ return __super::StartStreaming();
}
HRESULT CRoQVideoDecoder::StopStreaming()
{
- delete [] m_y[0];
- m_y[0] = NULL;
- delete [] m_y[1];
- m_y[1] = NULL;
+ delete [] m_y[0]; m_y[0] = NULL;
+ delete [] m_y[1]; m_y[1] = NULL;
- return __super::StopStreaming();
+ return __super::StopStreaming();
}
//
@@ -875,9 +848,9 @@ HRESULT CRoQVideoDecoder::StopStreaming()
//
CRoQAudioDecoder::CRoQAudioDecoder(LPUNKNOWN lpunk, HRESULT* phr)
- : CTransformFilter(NAME("CRoQAudioDecoder"), lpunk, __uuidof(this))
+ : CTransformFilter(NAME("CRoQAudioDecoder"), lpunk, __uuidof(this))
{
- if(phr) *phr = S_OK;
+ if(phr) *phr = S_OK;
}
CRoQAudioDecoder::~CRoQAudioDecoder()
@@ -886,148 +859,147 @@ CRoQAudioDecoder::~CRoQAudioDecoder()
HRESULT CRoQAudioDecoder::Transform(IMediaSample* pIn, IMediaSample* pOut)
{
- HRESULT hr;
-
- AM_MEDIA_TYPE* pmt;
- if(SUCCEEDED(pOut->GetMediaType(&pmt)) && pmt)
- {
- CMediaType mt(*pmt);
- m_pOutput->SetMediaType(&mt);
- DeleteMediaType(pmt);
- }
-
- WAVEFORMATEX* pwfe = (WAVEFORMATEX*)m_pOutput->CurrentMediaType().Format();
-
- BYTE* pDataIn = NULL;
- if(FAILED(hr = pIn->GetPointer(&pDataIn)))
- return hr;
-
- long len = pIn->GetActualDataLength();
- if(len <= 0) return S_OK;
-
- REFERENCE_TIME rtStart, rtStop;
- pIn->GetTime(&rtStart, &rtStop);
-
- if(pIn->IsPreroll() == S_OK || rtStart < 0)
- return S_OK;
-
- BYTE* pDataOut = NULL;
- if(FAILED(hr = pOut->GetPointer(&pDataOut)))
- return hr;
-
- long size = pOut->GetSize();
- if(size <= 0)
- return E_FAIL;
-
- roq_chunk* rc = (roq_chunk*)pDataIn;
-
- WAVEFORMATEX* wfe = (WAVEFORMATEX*)m_pOutput->CurrentMediaType().Format();
-
- if(wfe->nChannels == 1)
- {
- int mono = (short)rc->arg;
- unsigned char* src = pDataIn + sizeof(roq_chunk);
- short* dst = (short*)pDataOut;
- for(int i = sizeof(roq_chunk); i < len; i++, src++, dst++)
- {
- short diff = (*src & 0x7f) * (*src & 0x7f);
- if(*src & 0x80) diff = -diff;
- mono += diff;
- *dst = (short)mono;
- }
- }
- else if(wfe->nChannels == 2)
- {
- int left = (char)(rc->arg >> 8) << 8;
- int right = (char)(rc->arg) << 8;
- unsigned char* src = pDataIn + sizeof(roq_chunk);
- short* dst = (short*)pDataOut;
- for(int i = sizeof(roq_chunk); i < len; i += 2, src++, dst++)
- {
- short diff = (*src & 0x7f) * (*src & 0x7f);
- if(*src & 0x80) diff = -diff;
- ASSERT((int)left + diff <= SHRT_MAX && (int)left + diff >= SHRT_MIN);
- left += diff;
- *dst = (short)left;
-
- src++;
- dst++;
-
- diff = (*src & 0x7f) * (*src & 0x7f);
- if(*src & 0x80) diff = -diff;
- ASSERT((int)right + diff <= SHRT_MAX && (int)right + diff >= SHRT_MIN);
- right += diff;
- *dst = (short)right;
- }
- }
- else
- {
- return E_UNEXPECTED;
- }
-
- pOut->SetTime(&rtStart, &rtStop);
-
- pOut->SetActualDataLength(2 *(len - sizeof(roq_chunk)));
-
- return S_OK;
+ HRESULT hr;
+
+ AM_MEDIA_TYPE* pmt;
+ if(SUCCEEDED(pOut->GetMediaType(&pmt)) && pmt)
+ {
+ CMediaType mt(*pmt);
+ m_pOutput->SetMediaType(&mt);
+ DeleteMediaType(pmt);
+ }
+
+ WAVEFORMATEX* pwfe = (WAVEFORMATEX*)m_pOutput->CurrentMediaType().Format();
+
+ BYTE* pDataIn = NULL;
+ if(FAILED(hr = pIn->GetPointer(&pDataIn)))
+ return hr;
+
+ long len = pIn->GetActualDataLength();
+ if(len <= 0) return S_OK;
+
+ REFERENCE_TIME rtStart, rtStop;
+ pIn->GetTime(&rtStart, &rtStop);
+
+ if(pIn->IsPreroll() == S_OK || rtStart < 0)
+ return S_OK;
+
+ BYTE* pDataOut = NULL;
+ if(FAILED(hr = pOut->GetPointer(&pDataOut)))
+ return hr;
+
+ long size = pOut->GetSize();
+ if(size <= 0)
+ return E_FAIL;
+
+ roq_chunk* rc = (roq_chunk*)pDataIn;
+
+ WAVEFORMATEX* wfe = (WAVEFORMATEX*)m_pOutput->CurrentMediaType().Format();
+
+ if(wfe->nChannels == 1)
+ {
+ int mono = (short)rc->arg;
+ unsigned char* src = pDataIn + sizeof(roq_chunk);
+ short* dst = (short*)pDataOut;
+ for(int i = sizeof(roq_chunk); i < len; i++, src++, dst++)
+ {
+ short diff = (*src&0x7f)*(*src&0x7f);
+ if(*src&0x80) diff = -diff;
+ mono += diff;
+ *dst = (short)mono;
+ }
+ }
+ else if(wfe->nChannels == 2)
+ {
+ int left = (char)(rc->arg>>8)<<8;
+ int right = (char)(rc->arg)<<8;
+ unsigned char* src = pDataIn + sizeof(roq_chunk);
+ short* dst = (short*)pDataOut;
+ for(int i = sizeof(roq_chunk); i < len; i+=2, src++, dst++)
+ {
+ short diff = (*src&0x7f)*(*src&0x7f);
+ if(*src&0x80) diff = -diff;
+ ASSERT((int)left + diff <= SHRT_MAX && (int)left + diff >= SHRT_MIN);
+ left += diff;
+ *dst = (short)left;
+
+ src++; dst++;
+
+ diff = (*src&0x7f)*(*src&0x7f);
+ if(*src&0x80) diff = -diff;
+ ASSERT((int)right + diff <= SHRT_MAX && (int)right + diff >= SHRT_MIN);
+ right += diff;
+ *dst = (short)right;
+ }
+ }
+ else
+ {
+ return E_UNEXPECTED;
+ }
+
+ pOut->SetTime(&rtStart, &rtStop);
+
+ pOut->SetActualDataLength(2*(len-sizeof(roq_chunk)));
+
+ return S_OK;
}
HRESULT CRoQAudioDecoder::CheckInputType(const CMediaType* mtIn)
{
- return mtIn->majortype == MEDIATYPE_Audio && mtIn->subtype == MEDIASUBTYPE_RoQA
- ? S_OK
- : VFW_E_TYPE_NOT_ACCEPTED;
+ return mtIn->majortype == MEDIATYPE_Audio && mtIn->subtype == MEDIASUBTYPE_RoQA
+ ? S_OK
+ : VFW_E_TYPE_NOT_ACCEPTED;
}
HRESULT CRoQAudioDecoder::CheckTransform(const CMediaType* mtIn, const CMediaType* mtOut)
{
- return SUCCEEDED(CheckInputType(mtIn))
- && mtOut->majortype == MEDIATYPE_Audio && mtOut->subtype == MEDIASUBTYPE_PCM
- ? S_OK
- : VFW_E_TYPE_NOT_ACCEPTED;
+ return SUCCEEDED(CheckInputType(mtIn))
+ && mtOut->majortype == MEDIATYPE_Audio && mtOut->subtype == MEDIASUBTYPE_PCM
+ ? S_OK
+ : VFW_E_TYPE_NOT_ACCEPTED;
}
HRESULT CRoQAudioDecoder::DecideBufferSize(IMemAllocator* pAllocator, ALLOCATOR_PROPERTIES* pProperties)
{
- if(m_pInput->IsConnected() == FALSE) return E_UNEXPECTED;
+ if(m_pInput->IsConnected() == FALSE) return E_UNEXPECTED;
- CComPtr<IMemAllocator> pAllocatorIn;
- m_pInput->GetAllocator(&pAllocatorIn);
- if(!pAllocatorIn) return E_UNEXPECTED;
+ CComPtr<IMemAllocator> pAllocatorIn;
+ m_pInput->GetAllocator(&pAllocatorIn);
+ if(!pAllocatorIn) return E_UNEXPECTED;
- WAVEFORMATEX* wfe = (WAVEFORMATEX*)m_pOutput->CurrentMediaType().Format();
+ WAVEFORMATEX* wfe = (WAVEFORMATEX*)m_pOutput->CurrentMediaType().Format();
- // ok, maybe this is too much...
- pProperties->cBuffers = 8;
- pProperties->cbBuffer = wfe->nChannels * wfe->nSamplesPerSec * wfe->wBitsPerSample >> 3; // nAvgBytesPerSec;
- pProperties->cbAlign = 1;
- pProperties->cbPrefix = 0;
+ // ok, maybe this is too much...
+ pProperties->cBuffers = 8;
+ pProperties->cbBuffer = wfe->nChannels*wfe->nSamplesPerSec*wfe->wBitsPerSample>>3; // nAvgBytesPerSec;
+ pProperties->cbAlign = 1;
+ pProperties->cbPrefix = 0;
- HRESULT hr;
- ALLOCATOR_PROPERTIES Actual;
- if(FAILED(hr = pAllocator->SetProperties(pProperties, &Actual)))
- return hr;
+ HRESULT hr;
+ ALLOCATOR_PROPERTIES Actual;
+ if(FAILED(hr = pAllocator->SetProperties(pProperties, &Actual)))
+ return hr;
return pProperties->cBuffers > Actual.cBuffers || pProperties->cbBuffer > Actual.cbBuffer
- ? E_FAIL
- : NOERROR;
+ ? E_FAIL
+ : NOERROR;
}
HRESULT CRoQAudioDecoder::GetMediaType(int iPosition, CMediaType* pmt)
{
if(m_pInput->IsConnected() == FALSE) return E_UNEXPECTED;
- if(iPosition < 0) return E_INVALIDARG;
- if(iPosition > 0) return VFW_S_NO_MORE_ITEMS;
+ if(iPosition < 0) return E_INVALIDARG;
+ if(iPosition > 0) return VFW_S_NO_MORE_ITEMS;
- *pmt = m_pInput->CurrentMediaType();
- pmt->subtype = MEDIASUBTYPE_PCM;
+ *pmt = m_pInput->CurrentMediaType();
+ pmt->subtype = MEDIASUBTYPE_PCM;
- WAVEFORMATEX* wfe = (WAVEFORMATEX*)pmt->ReallocFormatBuffer(sizeof(WAVEFORMATEX));
- wfe->cbSize = 0;
- wfe->wFormatTag = WAVE_FORMAT_PCM;
- wfe->nBlockAlign = wfe->nChannels * wfe->wBitsPerSample >> 3;
- wfe->nAvgBytesPerSec = wfe->nSamplesPerSec * wfe->nBlockAlign;
+ WAVEFORMATEX* wfe = (WAVEFORMATEX*)pmt->ReallocFormatBuffer(sizeof(WAVEFORMATEX));
+ wfe->cbSize = 0;
+ wfe->wFormatTag = WAVE_FORMAT_PCM;
+ wfe->nBlockAlign = wfe->nChannels*wfe->wBitsPerSample>>3;
+ wfe->nAvgBytesPerSec = wfe->nSamplesPerSec*wfe->nBlockAlign;
- return S_OK;
+ return S_OK;
}
diff --git a/src/filters/parser/RoQSplitter/RoQSplitter.h b/src/filters/parser/RoQSplitter/RoQSplitter.h
index 50e86a4ff..c7fa21108 100644
--- a/src/filters/parser/RoQSplitter/RoQSplitter.h
+++ b/src/filters/parser/RoQSplitter/RoQSplitter.h
@@ -1,4 +1,4 @@
-/*
+/*
* Copyright (C) 2003-2006 Gabest
* http://www.gabest.org
*
@@ -6,15 +6,15 @@
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2, or (at your option)
* any later version.
- *
+ *
* This Program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with GNU Make; see the file COPYING. If not, write to
- * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
+ * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
* http://www.gnu.org/copyleft/gpl.html
*
*/
@@ -24,119 +24,101 @@
#include "../BaseSplitter/BaseSplitter.h"
// {48B93619-A959-45d9-B5FD-E12A67A96CF1}
-DEFINE_GUID(MEDIASUBTYPE_RoQ,
- 0x48b93619, 0xa959, 0x45d9, 0xb5, 0xfd, 0xe1, 0x2a, 0x67, 0xa9, 0x6c, 0xf1);
+DEFINE_GUID(MEDIASUBTYPE_RoQ,
+0x48b93619, 0xa959, 0x45d9, 0xb5, 0xfd, 0xe1, 0x2a, 0x67, 0xa9, 0x6c, 0xf1);
// 56516F52-0000-0010-8000-00AA00389B71 'RoQV' == MEDIASUBTYPE_RoQV
DEFINE_GUID(MEDIASUBTYPE_RoQV,
- 0x56516F52, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71);
+0x56516F52, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71);
#define WAVE_FORMAT_RoQA 0x41516F52
// 41516F52-0000-0010-8000-00AA00389B71 'RoQA' == MEDIASUBTYPE_RoQA
DEFINE_GUID(MEDIASUBTYPE_RoQA,
- WAVE_FORMAT_RoQA, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71);
+WAVE_FORMAT_RoQA, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71);
#pragma pack(push, 1)
-struct roq_chunk
-{
- WORD id;
- DWORD size;
- WORD arg;
-};
-struct roq_info
-{
- WORD w, h, unk1, unk2;
-};
+struct roq_chunk {WORD id; DWORD size; WORD arg;};
+struct roq_info {WORD w, h, unk1, unk2;};
#pragma pack(pop)
[uuid("C73DF7C1-21F2-44C7-A430-D35FB9BB298F")]
class CRoQSplitterFilter : public CBaseSplitterFilter
{
- CComPtr<IAsyncReader> m_pAsyncReader;
+ CComPtr<IAsyncReader> m_pAsyncReader;
- struct index
- {
- REFERENCE_TIME rtv, rta;
- __int64 fp;
- };
- CAtlList<index> m_index;
- POSITION m_indexpos;
+ struct index {REFERENCE_TIME rtv, rta; __int64 fp;};
+ CAtlList<index> m_index;
+ POSITION m_indexpos;
protected:
- HRESULT CreateOutputs(IAsyncReader* pAsyncReader);
+ HRESULT CreateOutputs(IAsyncReader* pAsyncReader);
- bool DemuxInit();
- void DemuxSeek(REFERENCE_TIME rt);
- bool DemuxLoop();
+ bool DemuxInit();
+ void DemuxSeek(REFERENCE_TIME rt);
+ bool DemuxLoop();
public:
- CRoQSplitterFilter(LPUNKNOWN pUnk, HRESULT* phr);
+ CRoQSplitterFilter(LPUNKNOWN pUnk, HRESULT* phr);
};
[uuid("02B8E5C2-4E1F-45D3-9A8E-B8F1EDE6DE09")]
class CRoQSourceFilter : public CRoQSplitterFilter
{
public:
- CRoQSourceFilter(LPUNKNOWN pUnk, HRESULT* phr);
+ CRoQSourceFilter(LPUNKNOWN pUnk, HRESULT* phr);
};
[uuid("FBEFC5EC-ABA0-4E6C-ACA3-D05FDFEFB853")]
class CRoQVideoDecoder : public CTransformFilter
{
- CCritSec m_csReceive;
+ CCritSec m_csReceive;
- REFERENCE_TIME m_rtStart;
+ REFERENCE_TIME m_rtStart;
- BYTE* m_y[2];
- BYTE* m_u[2];
- BYTE* m_v[2];
- int m_pitch;
+ BYTE* m_y[2];
+ BYTE* m_u[2];
+ BYTE* m_v[2];
+ int m_pitch;
- void Copy(BYTE* pOut, BYTE* pIn, DWORD w, DWORD h);
+ void Copy(BYTE* pOut, BYTE* pIn, DWORD w, DWORD h);
-#pragma pack(push, 1)
- struct roq_cell
- {
- BYTE y0, y1, y2, y3, u, v;
- } m_cells[256];
- struct roq_qcell
- {
- roq_cell* idx[4];
- } m_qcells[256];
-#pragma pack(pop)
- void apply_vector_2x2(int x, int y, roq_cell* cell);
- void apply_vector_4x4(int x, int y, roq_cell* cell);
- void apply_motion_4x4(int x, int y, unsigned char mv, char mean_x, char mean_y);
- void apply_motion_8x8(int x, int y, unsigned char mv, char mean_x, char mean_y);
+ #pragma pack(push, 1)
+ struct roq_cell {BYTE y0, y1, y2, y3, u, v;} m_cells[256];
+ struct roq_qcell {roq_cell* idx[4];} m_qcells[256];
+ #pragma pack(pop)
+ void apply_vector_2x2(int x, int y, roq_cell* cell);
+ void apply_vector_4x4(int x, int y, roq_cell* cell);
+ void apply_motion_4x4(int x, int y, unsigned char mv, char mean_x, char mean_y);
+ void apply_motion_8x8(int x, int y, unsigned char mv, char mean_x, char mean_y);
public:
- CRoQVideoDecoder(LPUNKNOWN lpunk, HRESULT* phr);
- virtual ~CRoQVideoDecoder();
+ CRoQVideoDecoder(LPUNKNOWN lpunk, HRESULT* phr);
+ virtual ~CRoQVideoDecoder();
HRESULT NewSegment(REFERENCE_TIME tStart, REFERENCE_TIME tStop, double dRate);
- HRESULT Transform(IMediaSample* pIn, IMediaSample* pOut);
- HRESULT CheckInputType(const CMediaType* mtIn);
- HRESULT CheckTransform(const CMediaType* mtIn, const CMediaType* mtOut);
- HRESULT DecideBufferSize(IMemAllocator* pAllocator, ALLOCATOR_PROPERTIES* pProperties);
- HRESULT GetMediaType(int iPosition, CMediaType* pMediaType);
+ HRESULT Transform(IMediaSample* pIn, IMediaSample* pOut);
+ HRESULT CheckInputType(const CMediaType* mtIn);
+ HRESULT CheckTransform(const CMediaType* mtIn, const CMediaType* mtOut);
+ HRESULT DecideBufferSize(IMemAllocator* pAllocator, ALLOCATOR_PROPERTIES* pProperties);
+ HRESULT GetMediaType(int iPosition, CMediaType* pMediaType);
- HRESULT StartStreaming();
- HRESULT StopStreaming();
+ HRESULT StartStreaming();
+ HRESULT StopStreaming();
};
[uuid("226FAF85-E358-4502-8C98-F4224BE76953")]
class CRoQAudioDecoder : public CTransformFilter
{
public:
- CRoQAudioDecoder(LPUNKNOWN lpunk, HRESULT* phr);
- virtual ~CRoQAudioDecoder();
-
- HRESULT Transform(IMediaSample* pIn, IMediaSample* pOut);
- HRESULT CheckInputType(const CMediaType* mtIn);
- HRESULT CheckTransform(const CMediaType* mtIn, const CMediaType* mtOut);
- HRESULT DecideBufferSize(IMemAllocator* pAllocator, ALLOCATOR_PROPERTIES* pProperties);
- HRESULT GetMediaType(int iPosition, CMediaType* pMediaType);
+ CRoQAudioDecoder(LPUNKNOWN lpunk, HRESULT* phr);
+ virtual ~CRoQAudioDecoder();
+
+ HRESULT Transform(IMediaSample* pIn, IMediaSample* pOut);
+ HRESULT CheckInputType(const CMediaType* mtIn);
+ HRESULT CheckTransform(const CMediaType* mtIn, const CMediaType* mtOut);
+ HRESULT DecideBufferSize(IMemAllocator* pAllocator, ALLOCATOR_PROPERTIES* pProperties);
+ HRESULT GetMediaType(int iPosition, CMediaType* pMediaType);
};
diff --git a/src/filters/parser/RoQSplitter/resource.h b/src/filters/parser/RoQSplitter/resource.h
index ed68ccb09..9bee95d26 100644
--- a/src/filters/parser/RoQSplitter/resource.h
+++ b/src/filters/parser/RoQSplitter/resource.h
@@ -3,7 +3,7 @@
// Used by RoQSplitter.rc
// Next default values for new objects
-//
+//
#ifdef APSTUDIO_INVOKED
#ifndef APSTUDIO_READONLY_SYMBOLS
#define _APS_NEXT_RESOURCE_VALUE 101
diff --git a/src/filters/parser/RoQSplitter/stdafx.cpp b/src/filters/parser/RoQSplitter/stdafx.cpp
index e1ec5adac..4284c08d9 100644
--- a/src/filters/parser/RoQSplitter/stdafx.cpp
+++ b/src/filters/parser/RoQSplitter/stdafx.cpp
@@ -1,4 +1,4 @@
-/*
+/*
* Copyright (C) 2003-2006 Gabest
* http://www.gabest.org
*
@@ -6,15 +6,15 @@
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2, or (at your option)
* any later version.
- *
+ *
* This Program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with GNU Make; see the file COPYING. If not, write to
- * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
+ * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
* http://www.gnu.org/copyleft/gpl.html
*
*/
diff --git a/src/filters/parser/RoQSplitter/stdafx.h b/src/filters/parser/RoQSplitter/stdafx.h
index 0c8bbfda0..e3ebbbb58 100644
--- a/src/filters/parser/RoQSplitter/stdafx.h
+++ b/src/filters/parser/RoQSplitter/stdafx.h
@@ -1,4 +1,4 @@
-/*
+/*
* Copyright (C) 2003-2006 Gabest
* http://www.gabest.org
*
@@ -6,15 +6,15 @@
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2, or (at your option)
* any later version.
- *
+ *
* This Program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with GNU Make; see the file COPYING. If not, write to
- * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
+ * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
* http://www.gnu.org/copyleft/gpl.html
*
*/
diff --git a/src/filters/parser/SSFSplitter/SSFSplitter.cpp b/src/filters/parser/SSFSplitter/SSFSplitter.cpp
index 5858ae13f..d4cafd14e 100644
--- a/src/filters/parser/SSFSplitter/SSFSplitter.cpp
+++ b/src/filters/parser/SSFSplitter/SSFSplitter.cpp
@@ -1,4 +1,4 @@
-/*
+/*
* Copyright (C) 2003-2006 Gabest
* http://www.gabest.org
*
@@ -6,15 +6,15 @@
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2, or (at your option)
* any later version.
- *
+ *
* This Program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with GNU Make; see the file COPYING. If not, write to
- * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
+ * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
* http://www.gnu.org/copyleft/gpl.html
*
*/
@@ -28,8 +28,8 @@
const AMOVIESETUP_MEDIATYPE sudPinTypesIn[] =
{
- {&MEDIATYPE_Stream, &MEDIASUBTYPE_SSF},
- {&MEDIATYPE_Stream, &MEDIASUBTYPE_NULL},
+ {&MEDIATYPE_Stream, &MEDIASUBTYPE_SSF},
+ {&MEDIATYPE_Stream, &MEDIASUBTYPE_NULL},
};
const AMOVIESETUP_PIN sudpPins[] =
@@ -40,30 +40,30 @@ const AMOVIESETUP_PIN sudpPins[] =
const AMOVIESETUP_FILTER sudFilter[] =
{
- {&__uuidof(CSSFSplitterFilter), L"MPC - SSF Splitter", MERIT_NORMAL, countof(sudpPins), sudpPins, CLSID_LegacyAmFilterCategory},
- {&__uuidof(CSSFSourceFilter), L"MPC - SSF Source", MERIT_NORMAL, 0, NULL, CLSID_LegacyAmFilterCategory},
+ {&__uuidof(CSSFSplitterFilter), L"MPC - SSF Splitter", MERIT_NORMAL, countof(sudpPins), sudpPins, CLSID_LegacyAmFilterCategory},
+ {&__uuidof(CSSFSourceFilter), L"MPC - SSF Source", MERIT_NORMAL, 0, NULL, CLSID_LegacyAmFilterCategory},
};
CFactoryTemplate g_Templates[] =
{
- {sudFilter[0].strName, sudFilter[0].clsID, CreateInstance<CSSFSplitterFilter>, NULL, &sudFilter[0]},
- {sudFilter[1].strName, sudFilter[1].clsID, CreateInstance<CSSFSourceFilter>, NULL, &sudFilter[1]},
+ {sudFilter[0].strName, sudFilter[0].clsID, CreateInstance<CSSFSplitterFilter>, NULL, &sudFilter[0]},
+ {sudFilter[1].strName, sudFilter[1].clsID, CreateInstance<CSSFSourceFilter>, NULL, &sudFilter[1]},
};
int g_cTemplates = countof(g_Templates);
STDAPI DllRegisterServer()
{
- SetRegKeyValue(_T("Media Type\\Extensions"), _T(".ssf"), _T("Source Filter"), CStringFromGUID(__uuidof(CSSFSourceFilter)));
+ SetRegKeyValue(_T("Media Type\\Extensions"), _T(".ssf"), _T("Source Filter"), CStringFromGUID(__uuidof(CSSFSourceFilter)));
- return AMovieDllRegisterServer2(TRUE);
+ return AMovieDllRegisterServer2(TRUE);
}
STDAPI DllUnregisterServer()
{
- DeleteRegKey(_T("Media Type\\Extensions"), _T(".ssf"));
+ DeleteRegKey(_T("Media Type\\Extensions"), _T(".ssf"));
- return AMovieDllRegisterServer2(FALSE);
+ return AMovieDllRegisterServer2(FALSE);
}
#include "../../FilterApp.h"
@@ -74,33 +74,33 @@ CFilterApp theApp;
namespace ssf
{
-class InputStreamBSF : public InputStream
-{
- CBaseSplitterFile* m_pFile;
-
-public:
- InputStreamBSF(CBaseSplitterFile* pFile)
- : m_pFile(pFile)
- {
- ASSERT(m_pFile);
- }
-
- int InputStreamBSF::NextByte()
- {
- if(!m_pFile) ThrowError(_T("m_pFile is NULL"));
- if(!m_pFile->GetRemaining()) return EOS;
- return (int)m_pFile->BitRead(8);
- }
-};
+ class InputStreamBSF : public InputStream
+ {
+ CBaseSplitterFile* m_pFile;
+
+ public:
+ InputStreamBSF(CBaseSplitterFile* pFile)
+ : m_pFile(pFile)
+ {
+ ASSERT(m_pFile);
+ }
+
+ int InputStreamBSF::NextByte()
+ {
+ if(!m_pFile) ThrowError(_T("m_pFile is NULL"));
+ if(!m_pFile->GetRemaining()) return EOS;
+ return (int)m_pFile->BitRead(8);
+ }
+ };
}
int CSSFSplitterFilter::SegmentItemEx::Compare(const void* a, const void* b)
{
- const SegmentItemEx* si1 = (const SegmentItemEx*)a;
- const SegmentItemEx* si2 = (const SegmentItemEx*)b;
- if(si1->start < si2->start) return -1;
- if(si2->start < si1->start) return +1;
- return 0;
+ const SegmentItemEx* si1 = (const SegmentItemEx*)a;
+ const SegmentItemEx* si2 = (const SegmentItemEx*)b;
+ if(si1->start < si2->start) return -1;
+ if(si2->start < si1->start) return +1;
+ return 0;
}
//
@@ -108,154 +108,142 @@ int CSSFSplitterFilter::SegmentItemEx::Compare(const void* a, const void* b)
//
CSSFSplitterFilter::CSSFSplitterFilter(LPUNKNOWN pUnk, HRESULT* phr)
- : CBaseSplitterFilter(NAME("CSSFSplitterFilter"), pUnk, phr, __uuidof(this))
+ : CBaseSplitterFilter(NAME("CSSFSplitterFilter"), pUnk, phr, __uuidof(this))
{
}
HRESULT CSSFSplitterFilter::CreateOutputs(IAsyncReader* pAsyncReader)
{
- CheckPointer(pAsyncReader, E_POINTER);
-
- HRESULT hr = E_FAIL;
-
- m_pFile.Free();
- m_pFile.Attach(DNew CBaseSplitterFile(pAsyncReader, hr));
- if(!m_pFile) return E_OUTOFMEMORY;
- if(FAILED(hr))
- {
- m_pFile.Free();
- return hr;
- }
-
- try
- {
- m_ssf.Parse(ssf::InputStreamBSF(m_pFile));
- }
- catch(ssf::Exception&)
- {
- return E_FAIL;
- }
-
- //
-
- m_rtNewStart = m_rtCurrent = 0;
- m_rtNewStop = m_rtStop = m_rtDuration = 0;
-
- if(ssf::Reference* pRootRef = m_ssf.GetRootRef())
- {
- ssf::WCharOutputStream s;
- ssf::StringMapW<float> offset;
-
- POSITION pos = pRootRef->m_nodes.GetHeadPosition();
- while(pos)
- {
- if(ssf::Definition* pDef = dynamic_cast<ssf::Definition*>(pRootRef->m_nodes.GetNext(pos)))
- {
- try
- {
- ssf::Definition::Time time;
-
- if(pDef->m_type == L"subtitle" && pDef->GetAsTime(time, offset) && (*pDef)[L"@"].IsValue())
- {
- SegmentItemEx si;
- si.pDef = pDef;
- si.start = time.start.value;
- si.stop = time.stop.value;
- m_subs.AddTail(si);
-
- // m_ssf.SetTime(pDef, si.start, si.stop);
-
- continue;
- }
- }
- catch(ssf::Exception&)
- {
- }
-
- pDef->Dump(s);
- }
- }
-
- CStringA hdr = UTF16To8(s.GetString());
-
- CAtlArray<CMediaType> mts;
-
- CMediaType mt;
- mt.majortype = MEDIATYPE_Subtitle;
- mt.subtype = MEDIASUBTYPE_SSF;
- mt.formattype = FORMAT_SubtitleInfo;
- SUBTITLEINFO* si = (SUBTITLEINFO*)mt.AllocFormatBuffer(sizeof(SUBTITLEINFO) + hdr.GetLength() + 3);
- memset(si, 0, sizeof(*si));
- si->dwOffset = sizeof(*si);
- BYTE* p = (BYTE*)(si + 1);
- p[0] = 0xef;
- p[1] = 0xbb;
- p[2] = 0xbf;
- memcpy(&p[3], (LPCSTR)hdr, hdr.GetLength());
- mts.Add(mt);
-
- CAutoPtr<CBaseSplitterOutputPin> pPinOut(DNew CBaseSplitterOutputPin(mts, L"Output", this, this, &hr));
- EXECUTE_ASSERT(SUCCEEDED(AddOutputPin(0, pPinOut)));
-
- CAtlArray<SegmentItemEx> subs;
- subs.SetCount(m_subs.GetCount());
- pos = m_subs.GetHeadPosition();
- for(size_t i = 0; pos; i++) subs.SetAt(i, m_subs.GetNext(pos));
- qsort(subs.GetData(), subs.GetCount(), sizeof(SegmentItemEx), SegmentItemEx::Compare);
- m_subs.RemoveAll();
- for(size_t i = 0; i < subs.GetCount(); i++) m_subs.AddTail(subs[i]);
-
- if(!m_ssf.m_segments.IsEmpty())
- {
- m_rtNewStop = m_rtStop = m_rtDuration = 10000000i64 * m_ssf.m_segments.GetTail().m_stop;
- }
- }
-
- return m_pOutputs.GetCount() > 0 ? S_OK : E_FAIL;
+ CheckPointer(pAsyncReader, E_POINTER);
+
+ HRESULT hr = E_FAIL;
+
+ m_pFile.Free();
+ m_pFile.Attach(DNew CBaseSplitterFile(pAsyncReader, hr));
+ if(!m_pFile) return E_OUTOFMEMORY;
+ if(FAILED(hr)) {m_pFile.Free(); return hr;}
+
+ try {m_ssf.Parse(ssf::InputStreamBSF(m_pFile));}
+ catch(ssf::Exception&) {return E_FAIL;}
+
+ //
+
+ m_rtNewStart = m_rtCurrent = 0;
+ m_rtNewStop = m_rtStop = m_rtDuration = 0;
+
+ if(ssf::Reference* pRootRef = m_ssf.GetRootRef())
+ {
+ ssf::WCharOutputStream s;
+ ssf::StringMapW<float> offset;
+
+ POSITION pos = pRootRef->m_nodes.GetHeadPosition();
+ while(pos)
+ {
+ if(ssf::Definition* pDef = dynamic_cast<ssf::Definition*>(pRootRef->m_nodes.GetNext(pos)))
+ {
+ try
+ {
+ ssf::Definition::Time time;
+
+ if(pDef->m_type == L"subtitle" && pDef->GetAsTime(time, offset) && (*pDef)[L"@"].IsValue())
+ {
+ SegmentItemEx si;
+ si.pDef = pDef;
+ si.start = time.start.value;
+ si.stop = time.stop.value;
+ m_subs.AddTail(si);
+
+ // m_ssf.SetTime(pDef, si.start, si.stop);
+
+ continue;
+ }
+ }
+ catch(ssf::Exception&)
+ {
+ }
+
+ pDef->Dump(s);
+ }
+ }
+
+ CStringA hdr = UTF16To8(s.GetString());
+
+ CAtlArray<CMediaType> mts;
+
+ CMediaType mt;
+ mt.majortype = MEDIATYPE_Subtitle;
+ mt.subtype = MEDIASUBTYPE_SSF;
+ mt.formattype = FORMAT_SubtitleInfo;
+ SUBTITLEINFO* si = (SUBTITLEINFO*)mt.AllocFormatBuffer(sizeof(SUBTITLEINFO) + hdr.GetLength() + 3);
+ memset(si, 0, sizeof(*si));
+ si->dwOffset = sizeof(*si);
+ BYTE* p = (BYTE*)(si+1);
+ p[0] = 0xef; p[1] = 0xbb; p[2] = 0xbf;
+ memcpy(&p[3], (LPCSTR)hdr, hdr.GetLength());
+ mts.Add(mt);
+
+ CAutoPtr<CBaseSplitterOutputPin> pPinOut(DNew CBaseSplitterOutputPin(mts, L"Output", this, this, &hr));
+ EXECUTE_ASSERT(SUCCEEDED(AddOutputPin(0, pPinOut)));
+
+ CAtlArray<SegmentItemEx> subs;
+ subs.SetCount(m_subs.GetCount());
+ pos = m_subs.GetHeadPosition();
+ for(size_t i = 0; pos; i++) subs.SetAt(i, m_subs.GetNext(pos));
+ qsort(subs.GetData(), subs.GetCount(), sizeof(SegmentItemEx), SegmentItemEx::Compare);
+ m_subs.RemoveAll();
+ for(size_t i = 0; i < subs.GetCount(); i++) m_subs.AddTail(subs[i]);
+
+ if(!m_ssf.m_segments.IsEmpty())
+ {
+ m_rtNewStop = m_rtStop = m_rtDuration = 10000000i64*m_ssf.m_segments.GetTail().m_stop;
+ }
+ }
+
+ return m_pOutputs.GetCount() > 0 ? S_OK : E_FAIL;
}
bool CSSFSplitterFilter::DemuxInit()
{
- return true;
+ return true;
}
void CSSFSplitterFilter::DemuxSeek(REFERENCE_TIME rt)
{
- if(rt <= 0)
- {
- }
- else
- {
- // TODO
- }
+ if(rt <= 0)
+ {
+ }
+ else
+ {
+ // TODO
+ }
}
bool CSSFSplitterFilter::DemuxLoop()
{
- HRESULT hr = S_OK;
+ HRESULT hr = S_OK;
- POSITION pos = m_subs.GetHeadPosition();
+ POSITION pos = m_subs.GetHeadPosition();
- while(pos && SUCCEEDED(hr) && !CheckRequest(NULL))
- {
- SegmentItemEx& si = m_subs.GetNext(pos);
+ while(pos && SUCCEEDED(hr) && !CheckRequest(NULL))
+ {
+ SegmentItemEx& si = m_subs.GetNext(pos);
- ssf::WCharOutputStream s;
- si.pDef->Dump(s);
- CStringA& str = UTF16To8(s.GetString());
+ ssf::WCharOutputStream s;
+ si.pDef->Dump(s);
+ CStringA& str = UTF16To8(s.GetString());
- CAutoPtr<Packet> p(DNew Packet());
+ CAutoPtr<Packet> p(DNew Packet());
- p->TrackNumber = 0;
- p->bSyncPoint = TRUE; // TODO
- p->rtStart = 10000000i64 * si.start;
- p->rtStop = 10000000i64 * si.stop;
- p->SetData((LPCSTR)str, str.GetLength());
+ p->TrackNumber = 0;
+ p->bSyncPoint = TRUE; // TODO
+ p->rtStart = 10000000i64*si.start;
+ p->rtStop = 10000000i64*si.stop;
+ p->SetData((LPCSTR)str, str.GetLength());
- hr = DeliverPacket(p);
- }
+ hr = DeliverPacket(p);
+ }
- return true;
+ return true;
}
//
@@ -263,8 +251,8 @@ bool CSSFSplitterFilter::DemuxLoop()
//
CSSFSourceFilter::CSSFSourceFilter(LPUNKNOWN pUnk, HRESULT* phr)
- : CSSFSplitterFilter(pUnk, phr)
+ : CSSFSplitterFilter(pUnk, phr)
{
- m_clsid = __uuidof(this);
- m_pInput.Free();
+ m_clsid = __uuidof(this);
+ m_pInput.Free();
}
diff --git a/src/filters/parser/SSFSplitter/SSFSplitter.h b/src/filters/parser/SSFSplitter/SSFSplitter.h
index 26b6ae48a..abd82b5fe 100644
--- a/src/filters/parser/SSFSplitter/SSFSplitter.h
+++ b/src/filters/parser/SSFSplitter/SSFSplitter.h
@@ -1,4 +1,4 @@
-/*
+/*
* Copyright (C) 2003-2006 Gabest
* http://www.gabest.org
*
@@ -6,15 +6,15 @@
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2, or (at your option)
* any later version.
- *
+ *
* This Program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with GNU Make; see the file COPYING. If not, write to
- * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
+ * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
* http://www.gnu.org/copyleft/gpl.html
*
*/
@@ -27,31 +27,31 @@
[uuid("95C3F9F6-1E05-4C34-8122-504476EACB51")]
class CSSFSplitterFilter : public CBaseSplitterFilter
{
- CAutoPtr<CBaseSplitterFile> m_pFile;
+ CAutoPtr<CBaseSplitterFile> m_pFile;
- ssf::SubtitleFile m_ssf;
+ ssf::SubtitleFile m_ssf;
- struct SegmentItemEx : public ssf::SubtitleFile::SegmentItem
- {
- static int Compare(const void* a, const void* b);
- };
+ struct SegmentItemEx : public ssf::SubtitleFile::SegmentItem
+ {
+ static int Compare(const void* a, const void* b);
+ };
- CAtlList<SegmentItemEx> m_subs;
+ CAtlList<SegmentItemEx> m_subs;
protected:
- HRESULT CreateOutputs(IAsyncReader* pAsyncReader);
+ HRESULT CreateOutputs(IAsyncReader* pAsyncReader);
- bool DemuxInit();
- void DemuxSeek(REFERENCE_TIME rt);
- bool DemuxLoop();
+ bool DemuxInit();
+ void DemuxSeek(REFERENCE_TIME rt);
+ bool DemuxLoop();
public:
- CSSFSplitterFilter(LPUNKNOWN pUnk, HRESULT* phr);
+ CSSFSplitterFilter(LPUNKNOWN pUnk, HRESULT* phr);
};
[uuid("57F46A2A-6DC9-4A9F-B5FA-DFDD62B8BAFB")]
class CSSFSourceFilter : public CSSFSplitterFilter
{
public:
- CSSFSourceFilter(LPUNKNOWN pUnk, HRESULT* phr);
+ CSSFSourceFilter(LPUNKNOWN pUnk, HRESULT* phr);
};
diff --git a/src/filters/parser/SSFSplitter/resource.h b/src/filters/parser/SSFSplitter/resource.h
index 67ed4aab3..ac2936f6e 100644
--- a/src/filters/parser/SSFSplitter/resource.h
+++ b/src/filters/parser/SSFSplitter/resource.h
@@ -3,7 +3,7 @@
// Used by SSFSplitter.rc
// Next default values for new objects
-//
+//
#ifdef APSTUDIO_INVOKED
#ifndef APSTUDIO_READONLY_SYMBOLS
#define _APS_NEXT_RESOURCE_VALUE 101
diff --git a/src/filters/parser/SSFSplitter/stdafx.cpp b/src/filters/parser/SSFSplitter/stdafx.cpp
index b52e42b40..924d2f316 100644
--- a/src/filters/parser/SSFSplitter/stdafx.cpp
+++ b/src/filters/parser/SSFSplitter/stdafx.cpp
@@ -1,4 +1,4 @@
-/*
+/*
* Copyright (C) 2003-2006 Gabest
* http://www.gabest.org
*
@@ -6,15 +6,15 @@
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2, or (at your option)
* any later version.
- *
+ *
* This Program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with GNU Make; see the file COPYING. If not, write to
- * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
+ * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
* http://www.gnu.org/copyleft/gpl.html
*
*/
diff --git a/src/filters/parser/SSFSplitter/stdafx.h b/src/filters/parser/SSFSplitter/stdafx.h
index 5eae4881c..043e18b3c 100644
--- a/src/filters/parser/SSFSplitter/stdafx.h
+++ b/src/filters/parser/SSFSplitter/stdafx.h
@@ -1,4 +1,4 @@
-/*
+/*
* Copyright (C) 2003-2006 Gabest
* http://www.gabest.org
*
@@ -6,15 +6,15 @@
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2, or (at your option)
* any later version.
- *
+ *
* This Program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with GNU Make; see the file COPYING. If not, write to
- * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
+ * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
* http://www.gnu.org/copyleft/gpl.html
*
*/
diff --git a/src/filters/parser/StreamDriveThru/StreamDriveThru.cpp b/src/filters/parser/StreamDriveThru/StreamDriveThru.cpp
index 8d80b2720..571bea2ca 100644
--- a/src/filters/parser/StreamDriveThru/StreamDriveThru.cpp
+++ b/src/filters/parser/StreamDriveThru/StreamDriveThru.cpp
@@ -1,4 +1,4 @@
-/*
+/*
* Copyright (C) 2003-2006 Gabest
* http://www.gabest.org
*
@@ -6,15 +6,15 @@
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2, or (at your option)
* any later version.
- *
+ *
* This Program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with GNU Make; see the file COPYING. If not, write to
- * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
+ * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
* http://www.gnu.org/copyleft/gpl.html
*
*/
@@ -27,12 +27,12 @@
const AMOVIESETUP_MEDIATYPE sudPinTypesIn[] =
{
- {&MEDIATYPE_Stream, &MEDIASUBTYPE_NULL},
+ {&MEDIATYPE_Stream, &MEDIASUBTYPE_NULL},
};
const AMOVIESETUP_MEDIATYPE sudPinTypesOut[] =
{
- {&MEDIATYPE_Stream, &MEDIASUBTYPE_NULL},
+ {&MEDIATYPE_Stream, &MEDIASUBTYPE_NULL},
};
const AMOVIESETUP_PIN sudpPins[] =
@@ -43,24 +43,24 @@ const AMOVIESETUP_PIN sudpPins[] =
const AMOVIESETUP_FILTER sudFilter[] =
{
- {&__uuidof(CStreamDriveThruFilter), L"MPC - StreamDriveThru", MERIT_DO_NOT_USE, countof(sudpPins), sudpPins, CLSID_LegacyAmFilterCategory}
+ {&__uuidof(CStreamDriveThruFilter), L"MPC - StreamDriveThru", MERIT_DO_NOT_USE, countof(sudpPins), sudpPins, CLSID_LegacyAmFilterCategory}
};
CFactoryTemplate g_Templates[] =
{
- {sudFilter[0].strName, sudFilter[0].clsID, CreateInstance<CStreamDriveThruFilter>, NULL, &sudFilter[0]}
+ {sudFilter[0].strName, sudFilter[0].clsID, CreateInstance<CStreamDriveThruFilter>, NULL, &sudFilter[0]}
};
int g_cTemplates = countof(g_Templates);
STDAPI DllRegisterServer()
{
- return AMovieDllRegisterServer2(TRUE);
+ return AMovieDllRegisterServer2(TRUE);
}
STDAPI DllUnregisterServer()
{
- return AMovieDllRegisterServer2(FALSE);
+ return AMovieDllRegisterServer2(FALSE);
}
#include "../../FilterApp.h"
@@ -74,290 +74,272 @@ CFilterApp theApp;
//
CStreamDriveThruFilter::CStreamDriveThruFilter(LPUNKNOWN pUnk, HRESULT* phr)
- : CBaseFilter(NAME("CStreamDriveThruFilter"), pUnk, &m_csLock, __uuidof(this))
- , m_position(0)
+ : CBaseFilter(NAME("CStreamDriveThruFilter"), pUnk, &m_csLock, __uuidof(this))
+ , m_position(0)
{
- if(phr) *phr = S_OK;
+ if(phr) *phr = S_OK;
- m_pInput = DNew CStreamDriveThruInputPin(NAME("CStreamDriveThruInputPin"), this, &m_csLock, phr);
- m_pOutput = DNew CStreamDriveThruOutputPin(NAME("CStreamDriveThruOutputPin"), this, &m_csLock, phr);
+ m_pInput = DNew CStreamDriveThruInputPin(NAME("CStreamDriveThruInputPin"), this, &m_csLock, phr);
+ m_pOutput = DNew CStreamDriveThruOutputPin(NAME("CStreamDriveThruOutputPin"), this, &m_csLock, phr);
- CAMThread::Create();
+ CAMThread::Create();
}
CStreamDriveThruFilter::~CStreamDriveThruFilter()
{
- CAutoLock csAutoLock(&m_csLock);
+ CAutoLock csAutoLock(&m_csLock);
- CAMThread::CallWorker(CMD_EXIT);
- CAMThread::Close();
+ CAMThread::CallWorker(CMD_EXIT);
+ CAMThread::Close();
- delete m_pInput;
- delete m_pOutput;
+ delete m_pInput;
+ delete m_pOutput;
}
STDMETHODIMP CStreamDriveThruFilter::NonDelegatingQueryInterface(REFIID riid, void** ppv)
{
- CheckPointer(ppv, E_POINTER);
+ CheckPointer(ppv, E_POINTER);
- return
- QI(IMediaSeeking)
- __super::NonDelegatingQueryInterface(riid, ppv);
+ return
+ QI(IMediaSeeking)
+ __super::NonDelegatingQueryInterface(riid, ppv);
}
#define PACKETSIZE 65536
DWORD CStreamDriveThruFilter::ThreadProc()
{
- while(1)
- {
- DWORD cmd = GetRequest();
-
- switch(cmd)
- {
- default:
- case CMD_EXIT:
- Reply(S_OK);
- return 0;
- case CMD_STOP:
- Reply(S_OK);
- break;
- case CMD_PAUSE:
- Reply(S_OK);
- break;
- case CMD_RUN:
- Reply(S_OK);
-
- do
- {
- CComPtr<IAsyncReader> pAsyncReader;
- CComPtr<IStream> pStream;
-
- if(!m_pInput || !m_pInput->IsConnected() || FAILED(m_pInput->GetAsyncReader(&pAsyncReader))
- || !m_pOutput || !m_pOutput->IsConnected() || FAILED(m_pOutput->GetStream(&pStream)))
- break;
-
- LARGE_INTEGER li = {0};
- ULARGE_INTEGER uli = {0};
-
- if(FAILED(pStream->Seek(li, STREAM_SEEK_SET, NULL))
- || FAILED(pStream->SetSize(uli)))
- break;
-
- if(CComQIPtr<IFileSinkFilter2> pFSF = GetFilterFromPin(m_pOutput->GetConnected()))
- {
- pFSF->SetMode(AM_FILE_OVERWRITE);
-
- LPOLESTR pfn;
- if(SUCCEEDED(pFSF->GetCurFile(&pfn, NULL)))
- {
- pFSF->SetFileName(pfn, NULL);
- CoTaskMemFree(pfn);
- }
- }
-
- m_position = 0;
- BYTE buff[PACKETSIZE];
-
- do
- {
- while(!CheckRequest(&cmd))
- {
- CAutoLock csAutoLock(&m_csLock);
-
- LONGLONG total = 0, available = 0;
- if(FAILED(pAsyncReader->Length(&total, &available)) || m_position >= total)
- {
- cmd = CMD_STOP;
- break;
- }
-
- LONG size = (LONG)min(PACKETSIZE, total - m_position);
- if(FAILED(pAsyncReader->SyncRead(m_position, size, buff)))
- {
- cmd = CMD_STOP;
- break;
- }
-
- ULONG written = 0;
- if(FAILED(pStream->Write(buff, (ULONG)size, &written)) || (ULONG)size != written)
- {
- cmd = CMD_STOP;
- break;
- }
-
- m_position += size;
- }
-
- if(cmd == CMD_PAUSE)
- {
- Reply(S_OK); // reply to CMD_PAUSE
-
- while(!CheckRequest(&cmd))
- Sleep(50);
-
- Reply(S_OK); // reply to something
- }
- }
- while(cmd == CMD_RUN);
-
- uli.QuadPart = m_position;
- pStream->SetSize(uli);
-
- if(CComPtr<IPin> pPin = m_pOutput->GetConnected())
- pPin->EndOfStream();
- }
- while(false);
-
- break;
- }
- }
-
- return 0;
+ while(1)
+ {
+ DWORD cmd = GetRequest();
+
+ switch(cmd)
+ {
+ default:
+ case CMD_EXIT:
+ Reply(S_OK);
+ return 0;
+ case CMD_STOP:
+ Reply(S_OK);
+ break;
+ case CMD_PAUSE:
+ Reply(S_OK);
+ break;
+ case CMD_RUN:
+ Reply(S_OK);
+
+ do
+ {
+ CComPtr<IAsyncReader> pAsyncReader;
+ CComPtr<IStream> pStream;
+
+ if(!m_pInput || !m_pInput->IsConnected() || FAILED(m_pInput->GetAsyncReader(&pAsyncReader))
+ || !m_pOutput || !m_pOutput->IsConnected() || FAILED(m_pOutput->GetStream(&pStream)))
+ break;
+
+ LARGE_INTEGER li = {0};
+ ULARGE_INTEGER uli = {0};
+
+ if(FAILED(pStream->Seek(li, STREAM_SEEK_SET, NULL))
+ || FAILED(pStream->SetSize(uli)))
+ break;
+
+ if(CComQIPtr<IFileSinkFilter2> pFSF = GetFilterFromPin(m_pOutput->GetConnected()))
+ {
+ pFSF->SetMode(AM_FILE_OVERWRITE);
+
+ LPOLESTR pfn;
+ if(SUCCEEDED(pFSF->GetCurFile(&pfn, NULL)))
+ {
+ pFSF->SetFileName(pfn, NULL);
+ CoTaskMemFree(pfn);
+ }
+ }
+
+ m_position = 0;
+ BYTE buff[PACKETSIZE];
+
+ do
+ {
+ while(!CheckRequest(&cmd))
+ {
+ CAutoLock csAutoLock(&m_csLock);
+
+ LONGLONG total = 0, available = 0;
+ if(FAILED(pAsyncReader->Length(&total, &available)) || m_position >= total)
+ {
+ cmd = CMD_STOP;
+ break;
+ }
+
+ LONG size = (LONG)min(PACKETSIZE, total - m_position);
+ if(FAILED(pAsyncReader->SyncRead(m_position, size, buff)))
+ {
+ cmd = CMD_STOP;
+ break;
+ }
+
+ ULONG written = 0;
+ if(FAILED(pStream->Write(buff, (ULONG)size, &written)) || (ULONG)size != written)
+ {
+ cmd = CMD_STOP;
+ break;
+ }
+
+ m_position += size;
+ }
+
+ if(cmd == CMD_PAUSE)
+ {
+ Reply(S_OK); // reply to CMD_PAUSE
+
+ while(!CheckRequest(&cmd))
+ Sleep(50);
+
+ Reply(S_OK); // reply to something
+ }
+ }
+ while(cmd == CMD_RUN);
+
+ uli.QuadPart = m_position;
+ pStream->SetSize(uli);
+
+ if(CComPtr<IPin> pPin = m_pOutput->GetConnected())
+ pPin->EndOfStream();
+ }
+ while(false);
+
+ break;
+ }
+ }
+
+ return 0;
}
int CStreamDriveThruFilter::GetPinCount()
{
- return 2;
+ return 2;
}
CBasePin* CStreamDriveThruFilter::GetPin(int n)
{
CAutoLock csAutoLock(&m_csLock);
- if(n == 0) return m_pInput;
- else if(n == 1) return m_pOutput;
+ if(n == 0) return m_pInput;
+ else if(n == 1) return m_pOutput;
return NULL;
}
STDMETHODIMP CStreamDriveThruFilter::Stop()
{
- HRESULT hr;
+ HRESULT hr;
+
+ if(FAILED(hr = __super::Stop()))
+ return hr;
- if(FAILED(hr = __super::Stop()))
- return hr;
+ CallWorker(CMD_STOP);
- CallWorker(CMD_STOP);
-
- return S_OK;
+ return S_OK;
}
STDMETHODIMP CStreamDriveThruFilter::Pause()
{
- HRESULT hr;
-
- if(FAILED(hr = __super::Pause()))
- return hr;
+ HRESULT hr;
+
+ if(FAILED(hr = __super::Pause()))
+ return hr;
- CallWorker(CMD_PAUSE);
+ CallWorker(CMD_PAUSE);
- return S_OK;
+ return S_OK;
}
STDMETHODIMP CStreamDriveThruFilter::Run(REFERENCE_TIME tStart)
{
- HRESULT hr;
+ HRESULT hr;
+
+ if(FAILED(hr = __super::Run(tStart)))
+ return hr;
- if(FAILED(hr = __super::Run(tStart)))
- return hr;
+ CallWorker(CMD_RUN);
- CallWorker(CMD_RUN);
-
- return S_OK;
+ return S_OK;
}
// IMediaSeeking
STDMETHODIMP CStreamDriveThruFilter::GetCapabilities(DWORD* pCapabilities)
{
- return pCapabilities ? *pCapabilities = AM_SEEKING_CanGetCurrentPos | AM_SEEKING_CanGetStopPos | AM_SEEKING_CanGetDuration, S_OK : E_POINTER;
+ return pCapabilities ? *pCapabilities = AM_SEEKING_CanGetCurrentPos|AM_SEEKING_CanGetStopPos|AM_SEEKING_CanGetDuration, S_OK : E_POINTER;
}
STDMETHODIMP CStreamDriveThruFilter::CheckCapabilities(DWORD* pCapabilities)
{
- CheckPointer(pCapabilities, E_POINTER);
+ CheckPointer(pCapabilities, E_POINTER);
- if(*pCapabilities == 0) return S_OK;
+ if(*pCapabilities == 0) return S_OK;
- DWORD caps;
- GetCapabilities(&caps);
+ DWORD caps;
+ GetCapabilities(&caps);
- DWORD caps2 = caps & *pCapabilities;
+ DWORD caps2 = caps & *pCapabilities;
- return caps2 == 0 ? E_FAIL : caps2 == *pCapabilities ? S_OK : S_FALSE;
+ return caps2 == 0 ? E_FAIL : caps2 == *pCapabilities ? S_OK : S_FALSE;
}
STDMETHODIMP CStreamDriveThruFilter::IsFormatSupported(const GUID* pFormat)
{
- return !pFormat ? E_POINTER : *pFormat == TIME_FORMAT_MEDIA_TIME ? S_OK : S_FALSE;
+ return !pFormat ? E_POINTER : *pFormat == TIME_FORMAT_MEDIA_TIME ? S_OK : S_FALSE;
}
STDMETHODIMP CStreamDriveThruFilter::QueryPreferredFormat(GUID* pFormat)
{
- return GetTimeFormat(pFormat);
+ return GetTimeFormat(pFormat);
}
STDMETHODIMP CStreamDriveThruFilter::GetTimeFormat(GUID* pFormat)
{
- return pFormat ? *pFormat = TIME_FORMAT_MEDIA_TIME, S_OK : E_POINTER;
+ return pFormat ? *pFormat = TIME_FORMAT_MEDIA_TIME, S_OK : E_POINTER;
}
STDMETHODIMP CStreamDriveThruFilter::IsUsingTimeFormat(const GUID* pFormat)
{
- return IsFormatSupported(pFormat);
+ return IsFormatSupported(pFormat);
}
STDMETHODIMP CStreamDriveThruFilter::SetTimeFormat(const GUID* pFormat)
{
- return S_OK == IsFormatSupported(pFormat) ? S_OK : E_INVALIDARG;
+ return S_OK == IsFormatSupported(pFormat) ? S_OK : E_INVALIDARG;
}
STDMETHODIMP CStreamDriveThruFilter::GetDuration(LONGLONG* pDuration)
{
- CheckPointer(pDuration, E_POINTER);
- CheckPointer(m_pInput, VFW_E_NOT_CONNECTED);
+ CheckPointer(pDuration, E_POINTER);
+ CheckPointer(m_pInput, VFW_E_NOT_CONNECTED);
- if(CComQIPtr<IAsyncReader> pAsyncReader = m_pInput->GetConnected())
- {
- LONGLONG total, available;
- if(SUCCEEDED(pAsyncReader->Length(&total, &available)))
- {
- *pDuration = total;
- return S_OK;
- }
- }
+ if(CComQIPtr<IAsyncReader> pAsyncReader = m_pInput->GetConnected())
+ {
+ LONGLONG total, available;
+ if(SUCCEEDED(pAsyncReader->Length(&total, &available)))
+ {
+ *pDuration = total;
+ return S_OK;
+ }
+ }
- return E_NOINTERFACE;
+ return E_NOINTERFACE;
}
STDMETHODIMP CStreamDriveThruFilter::GetStopPosition(LONGLONG* pStop)
{
- return GetDuration(pStop);
+ return GetDuration(pStop);
}
STDMETHODIMP CStreamDriveThruFilter::GetCurrentPosition(LONGLONG* pCurrent)
{
- return pCurrent ? *pCurrent = m_position, S_OK : E_POINTER;
-}
-STDMETHODIMP CStreamDriveThruFilter::ConvertTimeFormat(LONGLONG* pTarget, const GUID* pTargetFormat, LONGLONG Source, const GUID* pSourceFormat)
-{
- return E_NOTIMPL;
-}
-STDMETHODIMP CStreamDriveThruFilter::SetPositions(LONGLONG* pCurrent, DWORD dwCurrentFlags, LONGLONG* pStop, DWORD dwStopFlags)
-{
- return E_NOTIMPL;
-}
-STDMETHODIMP CStreamDriveThruFilter::GetPositions(LONGLONG* pCurrent, LONGLONG* pStop)
-{
- return E_NOTIMPL;
-}
-STDMETHODIMP CStreamDriveThruFilter::GetAvailable(LONGLONG* pEarliest, LONGLONG* pLatest)
-{
- return E_NOTIMPL;
-}
-STDMETHODIMP CStreamDriveThruFilter::SetRate(double dRate)
-{
- return E_NOTIMPL;
-}
-STDMETHODIMP CStreamDriveThruFilter::GetRate(double* pdRate)
-{
- return E_NOTIMPL;
+ return pCurrent ? *pCurrent = m_position, S_OK : E_POINTER;
}
+STDMETHODIMP CStreamDriveThruFilter::ConvertTimeFormat(LONGLONG* pTarget, const GUID* pTargetFormat, LONGLONG Source, const GUID* pSourceFormat) {return E_NOTIMPL;}
+STDMETHODIMP CStreamDriveThruFilter::SetPositions(LONGLONG* pCurrent, DWORD dwCurrentFlags, LONGLONG* pStop, DWORD dwStopFlags) {return E_NOTIMPL;}
+STDMETHODIMP CStreamDriveThruFilter::GetPositions(LONGLONG* pCurrent, LONGLONG* pStop) {return E_NOTIMPL;}
+STDMETHODIMP CStreamDriveThruFilter::GetAvailable(LONGLONG* pEarliest, LONGLONG* pLatest) {return E_NOTIMPL;}
+STDMETHODIMP CStreamDriveThruFilter::SetRate(double dRate) {return E_NOTIMPL;}
+STDMETHODIMP CStreamDriveThruFilter::GetRate(double* pdRate) {return E_NOTIMPL;}
STDMETHODIMP CStreamDriveThruFilter::GetPreroll(LONGLONG* pllPreroll)
{
- return pllPreroll ? *pllPreroll = 0, S_OK : E_POINTER;
+ return pllPreroll ? *pllPreroll = 0, S_OK : E_POINTER;
}
//
@@ -365,7 +347,7 @@ STDMETHODIMP CStreamDriveThruFilter::GetPreroll(LONGLONG* pllPreroll)
//
CStreamDriveThruInputPin::CStreamDriveThruInputPin(TCHAR* pName, CBaseFilter* pFilter, CCritSec* pLock, HRESULT* phr)
- : CBasePin(pName, pFilter, pLock, phr, L"Input", PINDIR_INPUT)
+ : CBasePin(pName, pFilter, pLock, phr, L"Input", PINDIR_INPUT)
{
}
@@ -375,79 +357,79 @@ CStreamDriveThruInputPin::~CStreamDriveThruInputPin()
HRESULT CStreamDriveThruInputPin::GetAsyncReader(IAsyncReader** ppAsyncReader)
{
- CheckPointer(ppAsyncReader, E_POINTER);
+ CheckPointer(ppAsyncReader, E_POINTER);
- *ppAsyncReader = NULL;
+ *ppAsyncReader = NULL;
- CheckPointer(m_pAsyncReader, VFW_E_NOT_CONNECTED);
+ CheckPointer(m_pAsyncReader, VFW_E_NOT_CONNECTED);
- (*ppAsyncReader = m_pAsyncReader)->AddRef();
+ (*ppAsyncReader = m_pAsyncReader)->AddRef();
- return S_OK;
+ return S_OK;
}
STDMETHODIMP CStreamDriveThruInputPin::NonDelegatingQueryInterface(REFIID riid, void** ppv)
{
- CheckPointer(ppv, E_POINTER);
+ CheckPointer(ppv, E_POINTER);
- return
- __super::NonDelegatingQueryInterface(riid, ppv);
+ return
+ __super::NonDelegatingQueryInterface(riid, ppv);
}
HRESULT CStreamDriveThruInputPin::CheckMediaType(const CMediaType* pmt)
{
- return pmt->majortype == MEDIATYPE_Stream
- ? S_OK
- : E_INVALIDARG;
+ return pmt->majortype == MEDIATYPE_Stream
+ ? S_OK
+ : E_INVALIDARG;
}
HRESULT CStreamDriveThruInputPin::CheckConnect(IPin* pPin)
{
- HRESULT hr;
+ HRESULT hr;
- if(FAILED(hr = __super::CheckConnect(pPin)))
- return hr;
+ if(FAILED(hr = __super::CheckConnect(pPin)))
+ return hr;
- if(!CComQIPtr<IAsyncReader>(pPin))
- return E_NOINTERFACE;
+ if(!CComQIPtr<IAsyncReader>(pPin))
+ return E_NOINTERFACE;
- return S_OK;
+ return S_OK;
}
HRESULT CStreamDriveThruInputPin::BreakConnect()
{
- HRESULT hr;
+ HRESULT hr;
- if(FAILED(hr = __super::BreakConnect()))
- return hr;
+ if(FAILED(hr = __super::BreakConnect()))
+ return hr;
- m_pAsyncReader.Release();
+ m_pAsyncReader.Release();
- return S_OK;
+ return S_OK;
}
HRESULT CStreamDriveThruInputPin::CompleteConnect(IPin* pPin)
{
- HRESULT hr;
+ HRESULT hr;
- if(FAILED(hr = __super::CompleteConnect(pPin)))
- return hr;
+ if(FAILED(hr = __super::CompleteConnect(pPin)))
+ return hr;
- CheckPointer(pPin, E_POINTER);
- m_pAsyncReader = pPin;
- CheckPointer(m_pAsyncReader, E_NOINTERFACE);
+ CheckPointer(pPin, E_POINTER);
+ m_pAsyncReader = pPin;
+ CheckPointer(m_pAsyncReader, E_NOINTERFACE);
- return S_OK;
+ return S_OK;
}
STDMETHODIMP CStreamDriveThruInputPin::BeginFlush()
{
- return E_UNEXPECTED;
+ return E_UNEXPECTED;
}
STDMETHODIMP CStreamDriveThruInputPin::EndFlush()
{
- return E_UNEXPECTED;
+ return E_UNEXPECTED;
}
//
@@ -455,7 +437,7 @@ STDMETHODIMP CStreamDriveThruInputPin::EndFlush()
//
CStreamDriveThruOutputPin::CStreamDriveThruOutputPin(TCHAR* pName, CBaseFilter* pFilter, CCritSec* pLock, HRESULT* phr)
- : CBaseOutputPin(pName, pFilter, pLock, phr, L"Output")
+ : CBaseOutputPin(pName, pFilter, pLock, phr, L"Output")
{
}
@@ -465,23 +447,23 @@ CStreamDriveThruOutputPin::~CStreamDriveThruOutputPin()
HRESULT CStreamDriveThruOutputPin::GetStream(IStream** ppStream)
{
- CheckPointer(ppStream, E_POINTER);
+ CheckPointer(ppStream, E_POINTER);
- *ppStream = NULL;
+ *ppStream = NULL;
- CheckPointer(m_pStream, VFW_E_NOT_CONNECTED);
+ CheckPointer(m_pStream, VFW_E_NOT_CONNECTED);
- (*ppStream = m_pStream)->AddRef();
+ (*ppStream = m_pStream)->AddRef();
- return S_OK;
+ return S_OK;
}
STDMETHODIMP CStreamDriveThruOutputPin::NonDelegatingQueryInterface(REFIID riid, void** ppv)
{
- CheckPointer(ppv, E_POINTER);
+ CheckPointer(ppv, E_POINTER);
- return
- __super::NonDelegatingQueryInterface(riid, ppv);
+ return
+ __super::NonDelegatingQueryInterface(riid, ppv);
}
HRESULT CStreamDriveThruOutputPin::DecideBufferSize(IMemAllocator* pAlloc, ALLOCATOR_PROPERTIES* pProperties)
@@ -491,8 +473,8 @@ HRESULT CStreamDriveThruOutputPin::DecideBufferSize(IMemAllocator* pAlloc, ALLOC
HRESULT hr = NOERROR;
- pProperties->cBuffers = 1;
- pProperties->cbBuffer = PACKETSIZE;
+ pProperties->cBuffers = 1;
+ pProperties->cbBuffer = PACKETSIZE;
ALLOCATOR_PROPERTIES Actual;
if(FAILED(hr = pAlloc->SetProperties(pProperties, &Actual))) return hr;
@@ -505,76 +487,76 @@ HRESULT CStreamDriveThruOutputPin::DecideBufferSize(IMemAllocator* pAlloc, ALLOC
HRESULT CStreamDriveThruOutputPin::CheckMediaType(const CMediaType* pmt)
{
- return pmt->majortype == MEDIATYPE_Stream
- ? S_OK
- : E_INVALIDARG;
+ return pmt->majortype == MEDIATYPE_Stream
+ ? S_OK
+ : E_INVALIDARG;
}
HRESULT CStreamDriveThruOutputPin::GetMediaType(int iPosition, CMediaType* pmt)
{
CAutoLock cAutoLock(m_pLock);
- if(iPosition < 0) return E_INVALIDARG;
- if(iPosition > 0) return VFW_S_NO_MORE_ITEMS;
+ if(iPosition < 0) return E_INVALIDARG;
+ if(iPosition > 0) return VFW_S_NO_MORE_ITEMS;
- pmt->majortype = MEDIATYPE_Stream;
- pmt->subtype = GUID_NULL;
- pmt->formattype = GUID_NULL;
- pmt->SetSampleSize(PACKETSIZE);
+ pmt->majortype = MEDIATYPE_Stream;
+ pmt->subtype = GUID_NULL;
+ pmt->formattype = GUID_NULL;
+ pmt->SetSampleSize(PACKETSIZE);
- return S_OK;
+ return S_OK;
}
HRESULT CStreamDriveThruOutputPin::CheckConnect(IPin* pPin)
{
- HRESULT hr;
+ HRESULT hr;
- if(FAILED(hr = __super::CheckConnect(pPin)))
- return hr;
+ if(FAILED(hr = __super::CheckConnect(pPin)))
+ return hr;
- if(!CComQIPtr<IStream>(pPin))
- return E_NOINTERFACE;
+ if(!CComQIPtr<IStream>(pPin))
+ return E_NOINTERFACE;
- return S_OK;
+ return S_OK;
}
HRESULT CStreamDriveThruOutputPin::BreakConnect()
{
- HRESULT hr;
+ HRESULT hr;
- if(FAILED(hr = __super::BreakConnect()))
- return hr;
+ if(FAILED(hr = __super::BreakConnect()))
+ return hr;
- m_pStream.Release();
+ m_pStream.Release();
- return S_OK;
+ return S_OK;
}
HRESULT CStreamDriveThruOutputPin::CompleteConnect(IPin* pPin)
{
- HRESULT hr;
+ HRESULT hr;
- if(FAILED(hr = __super::CompleteConnect(pPin)))
- return hr;
+ if(FAILED(hr = __super::CompleteConnect(pPin)))
+ return hr;
- CheckPointer(pPin, E_POINTER);
- m_pStream = pPin;
- CheckPointer(m_pStream, E_NOINTERFACE);
+ CheckPointer(pPin, E_POINTER);
+ m_pStream = pPin;
+ CheckPointer(m_pStream, E_NOINTERFACE);
- return S_OK;
+ return S_OK;
}
STDMETHODIMP CStreamDriveThruOutputPin::BeginFlush()
{
- return E_UNEXPECTED;
+ return E_UNEXPECTED;
}
STDMETHODIMP CStreamDriveThruOutputPin::EndFlush()
{
- return E_UNEXPECTED;
+ return E_UNEXPECTED;
}
STDMETHODIMP CStreamDriveThruOutputPin::Notify(IBaseFilter* pSender, Quality q)
{
- return E_NOTIMPL;
+ return E_NOTIMPL;
}
diff --git a/src/filters/parser/StreamDriveThru/StreamDriveThru.h b/src/filters/parser/StreamDriveThru/StreamDriveThru.h
index 042b66c53..08a2ebe16 100644
--- a/src/filters/parser/StreamDriveThru/StreamDriveThru.h
+++ b/src/filters/parser/StreamDriveThru/StreamDriveThru.h
@@ -1,4 +1,4 @@
-/*
+/*
* Copyright (C) 2003-2006 Gabest
* http://www.gabest.org
*
@@ -6,15 +6,15 @@
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2, or (at your option)
* any later version.
- *
+ *
* This Program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with GNU Make; see the file COPYING. If not, write to
- * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
+ * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
* http://www.gnu.org/copyleft/gpl.html
*
*/
@@ -27,38 +27,38 @@
class CStreamDriveThruInputPin : public CBasePin
{
- CComQIPtr<IAsyncReader> m_pAsyncReader;
+ CComQIPtr<IAsyncReader> m_pAsyncReader;
public:
- CStreamDriveThruInputPin(TCHAR* pName, CBaseFilter* pFilter, CCritSec* pLock, HRESULT* phr);
- virtual ~CStreamDriveThruInputPin();
+ CStreamDriveThruInputPin(TCHAR* pName, CBaseFilter* pFilter, CCritSec* pLock, HRESULT* phr);
+ virtual ~CStreamDriveThruInputPin();
- HRESULT GetAsyncReader(IAsyncReader** ppAsyncReader);
+ HRESULT GetAsyncReader(IAsyncReader** ppAsyncReader);
- DECLARE_IUNKNOWN;
+ DECLARE_IUNKNOWN;
STDMETHODIMP NonDelegatingQueryInterface(REFIID riid, void** ppv);
HRESULT CheckMediaType(const CMediaType* pmt);
HRESULT CheckConnect(IPin* pPin);
HRESULT BreakConnect();
- HRESULT CompleteConnect(IPin* pPin);
+ HRESULT CompleteConnect(IPin* pPin);
- STDMETHODIMP BeginFlush();
- STDMETHODIMP EndFlush();
+ STDMETHODIMP BeginFlush();
+ STDMETHODIMP EndFlush();
};
class CStreamDriveThruOutputPin : public CBaseOutputPin
{
- CComQIPtr<IStream> m_pStream;
+ CComQIPtr<IStream> m_pStream;
public:
- CStreamDriveThruOutputPin(TCHAR* pName, CBaseFilter* pFilter, CCritSec* pLock, HRESULT* phr);
- virtual ~CStreamDriveThruOutputPin();
+ CStreamDriveThruOutputPin(TCHAR* pName, CBaseFilter* pFilter, CCritSec* pLock, HRESULT* phr);
+ virtual ~CStreamDriveThruOutputPin();
- HRESULT GetStream(IStream** ppStream);
+ HRESULT GetStream(IStream** ppStream);
- DECLARE_IUNKNOWN;
+ DECLARE_IUNKNOWN;
STDMETHODIMP NonDelegatingQueryInterface(REFIID riid, void** ppv);
HRESULT DecideBufferSize(IMemAllocator* pAlloc, ALLOCATOR_PROPERTIES* pProperties);
@@ -70,58 +70,58 @@ public:
HRESULT BreakConnect();
HRESULT CompleteConnect(IPin* pPin);
- STDMETHODIMP BeginFlush();
- STDMETHODIMP EndFlush();
+ STDMETHODIMP BeginFlush();
+ STDMETHODIMP EndFlush();
- STDMETHODIMP Notify(IBaseFilter* pSender, Quality q);
+ STDMETHODIMP Notify(IBaseFilter* pSender, Quality q);
};
[uuid("534FE6FD-F1F0-4aec-9F45-FF397320CE33")]
class CStreamDriveThruFilter : public CBaseFilter, protected CAMThread, public IMediaSeeking
{
- CCritSec m_csLock;
+ CCritSec m_csLock;
- CStreamDriveThruInputPin* m_pInput;
- CStreamDriveThruOutputPin* m_pOutput;
+ CStreamDriveThruInputPin* m_pInput;
+ CStreamDriveThruOutputPin* m_pOutput;
protected:
- enum {CMD_EXIT, CMD_STOP, CMD_PAUSE, CMD_RUN};
+ enum {CMD_EXIT, CMD_STOP, CMD_PAUSE, CMD_RUN};
DWORD ThreadProc();
- LONGLONG m_position;
+ LONGLONG m_position;
public:
- CStreamDriveThruFilter(LPUNKNOWN pUnk, HRESULT* phr);
- virtual ~CStreamDriveThruFilter();
+ CStreamDriveThruFilter(LPUNKNOWN pUnk, HRESULT* phr);
+ virtual ~CStreamDriveThruFilter();
- DECLARE_IUNKNOWN;
+ DECLARE_IUNKNOWN;
STDMETHODIMP NonDelegatingQueryInterface(REFIID riid, void** ppv);
- int GetPinCount();
- CBasePin* GetPin(int n);
-
- STDMETHODIMP Stop();
- STDMETHODIMP Pause();
- STDMETHODIMP Run(REFERENCE_TIME tStart);
-
- // IMediaSeeking
-
- STDMETHODIMP GetCapabilities(DWORD* pCapabilities);
- STDMETHODIMP CheckCapabilities(DWORD* pCapabilities);
- STDMETHODIMP IsFormatSupported(const GUID* pFormat);
- STDMETHODIMP QueryPreferredFormat(GUID* pFormat);
- STDMETHODIMP GetTimeFormat(GUID* pFormat);
- STDMETHODIMP IsUsingTimeFormat(const GUID* pFormat);
- STDMETHODIMP SetTimeFormat(const GUID* pFormat);
- STDMETHODIMP GetDuration(LONGLONG* pDuration);
- STDMETHODIMP GetStopPosition(LONGLONG* pStop);
- STDMETHODIMP GetCurrentPosition(LONGLONG* pCurrent);
- STDMETHODIMP ConvertTimeFormat(LONGLONG* pTarget, const GUID* pTargetFormat, LONGLONG Source, const GUID* pSourceFormat);
- STDMETHODIMP SetPositions(LONGLONG* pCurrent, DWORD dwCurrentFlags, LONGLONG* pStop, DWORD dwStopFlags);
- STDMETHODIMP GetPositions(LONGLONG* pCurrent, LONGLONG* pStop);
- STDMETHODIMP GetAvailable(LONGLONG* pEarliest, LONGLONG* pLatest);
- STDMETHODIMP SetRate(double dRate);
- STDMETHODIMP GetRate(double* pdRate);
- STDMETHODIMP GetPreroll(LONGLONG* pllPreroll);
+ int GetPinCount();
+ CBasePin* GetPin(int n);
+
+ STDMETHODIMP Stop();
+ STDMETHODIMP Pause();
+ STDMETHODIMP Run(REFERENCE_TIME tStart);
+
+ // IMediaSeeking
+
+ STDMETHODIMP GetCapabilities(DWORD* pCapabilities);
+ STDMETHODIMP CheckCapabilities(DWORD* pCapabilities);
+ STDMETHODIMP IsFormatSupported(const GUID* pFormat);
+ STDMETHODIMP QueryPreferredFormat(GUID* pFormat);
+ STDMETHODIMP GetTimeFormat(GUID* pFormat);
+ STDMETHODIMP IsUsingTimeFormat(const GUID* pFormat);
+ STDMETHODIMP SetTimeFormat(const GUID* pFormat);
+ STDMETHODIMP GetDuration(LONGLONG* pDuration);
+ STDMETHODIMP GetStopPosition(LONGLONG* pStop);
+ STDMETHODIMP GetCurrentPosition(LONGLONG* pCurrent);
+ STDMETHODIMP ConvertTimeFormat(LONGLONG* pTarget, const GUID* pTargetFormat, LONGLONG Source, const GUID* pSourceFormat);
+ STDMETHODIMP SetPositions(LONGLONG* pCurrent, DWORD dwCurrentFlags, LONGLONG* pStop, DWORD dwStopFlags);
+ STDMETHODIMP GetPositions(LONGLONG* pCurrent, LONGLONG* pStop);
+ STDMETHODIMP GetAvailable(LONGLONG* pEarliest, LONGLONG* pLatest);
+ STDMETHODIMP SetRate(double dRate);
+ STDMETHODIMP GetRate(double* pdRate);
+ STDMETHODIMP GetPreroll(LONGLONG* pllPreroll);
};
diff --git a/src/filters/parser/StreamDriveThru/resource.h b/src/filters/parser/StreamDriveThru/resource.h
index eb1073cda..16eef629e 100644
--- a/src/filters/parser/StreamDriveThru/resource.h
+++ b/src/filters/parser/StreamDriveThru/resource.h
@@ -3,7 +3,7 @@
// Used by streamdrivethru.rc
// Next default values for new objects
-//
+//
#ifdef APSTUDIO_INVOKED
#ifndef APSTUDIO_READONLY_SYMBOLS
#define _APS_NEXT_RESOURCE_VALUE 101
diff --git a/src/filters/parser/StreamDriveThru/stdafx.cpp b/src/filters/parser/StreamDriveThru/stdafx.cpp
index d774a068d..6915aebce 100644
--- a/src/filters/parser/StreamDriveThru/stdafx.cpp
+++ b/src/filters/parser/StreamDriveThru/stdafx.cpp
@@ -1,4 +1,4 @@
-/*
+/*
* Copyright (C) 2003-2006 Gabest
* http://www.gabest.org
*
@@ -6,15 +6,15 @@
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2, or (at your option)
* any later version.
- *
+ *
* This Program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with GNU Make; see the file COPYING. If not, write to
- * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
+ * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
* http://www.gnu.org/copyleft/gpl.html
*
*/
diff --git a/src/filters/parser/StreamDriveThru/stdafx.h b/src/filters/parser/StreamDriveThru/stdafx.h
index 3e12d9514..e0482b2bb 100644
--- a/src/filters/parser/StreamDriveThru/stdafx.h
+++ b/src/filters/parser/StreamDriveThru/stdafx.h
@@ -1,4 +1,4 @@
-/*
+/*
* Copyright (C) 2003-2006 Gabest
* http://www.gabest.org
*
@@ -6,15 +6,15 @@
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2, or (at your option)
* any later version.
- *
+ *
* This Program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License
* along with GNU Make; see the file COPYING. If not, write to
- * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
+ * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
* http://www.gnu.org/copyleft/gpl.html
*
*/