TMC3.cpp 24.4 KB
Newer Older
Khaled Mammou's avatar
TMC3v0  
Khaled Mammou committed
1
/* The copyright in this software is being made available under the BSD
David Flynn's avatar
David Flynn committed
2
3
4
 * Licence, included below.  This software may be subject to other third
 * party and contributor rights, including patent rights, and no such
 * rights are granted under this licence.
Khaled Mammou's avatar
TMC3v0  
Khaled Mammou committed
5
 *
David Flynn's avatar
David Flynn committed
6
 * Copyright (c) 2017-2018, ISO/IEC
Khaled Mammou's avatar
TMC3v0  
Khaled Mammou committed
7
8
9
10
11
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
David Flynn's avatar
David Flynn committed
12
13
14
15
16
17
18
19
20
21
 * * Redistributions of source code must retain the above copyright
 *   notice, this list of conditions and the following disclaimer.
 *
 * * Redistributions in binary form must reproduce the above copyright
 *   notice, this list of conditions and the following disclaimer in the
 *   documentation and/or other materials provided with the distribution.
 *
 * * Neither the name of the ISO/IEC nor the names of its contributors
 *   may be used to endorse or promote products derived from this
 *   software without specific prior written permission.
Khaled Mammou's avatar
TMC3v0  
Khaled Mammou committed
22
23
24
25
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
David Flynn's avatar
David Flynn committed
26
27
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
Khaled Mammou's avatar
TMC3v0  
Khaled Mammou committed
28
29
30
31
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
David Flynn's avatar
David Flynn committed
32
33
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
Khaled Mammou's avatar
TMC3v0  
Khaled Mammou committed
34
35
36
 */

#include "TMC3.h"
David Flynn's avatar
David Flynn committed
37
38
39
40
41

#include <memory>

#include "PCCTMC3Encoder.h"
#include "PCCTMC3Decoder.h"
42
#include "constants.h"
43
#include "program_options_lite.h"
44
#include "io_tlv.h"
45
#include "version.h"
Khaled Mammou's avatar
TMC3v0  
Khaled Mammou committed
46
47
48
49

using namespace std;
using namespace pcc;

50
51
52
53
54
//============================================================================

struct Parameters {
  bool isDecoder;

55
56
57
  // command line parsing should adjust dist2 values according to PQS
  bool positionQuantizationScaleAdjustsDist2;

58
59
60
  // output mode for ply writing (binary or ascii)
  bool outputBinaryPly;

61
62
63
  // when true, configure the encoder as if no attributes are specified
  bool disableAttributeCoding;

64
65
66
67
  std::string uncompressedDataPath;
  std::string compressedStreamPath;
  std::string reconstructedDataPath;

68
69
70
  // Filename for saving pre inverse scaled point cloud.
  std::string preInvScalePath;

71
72
73
74
75
  pcc::EncoderParams encoder;
  pcc::DecoderParams decoder;

  // todo(df): this should be per-attribute
  ColorTransform colorTransform;
76
77
78

  // todo(df): this should be per-attribute
  int reflectanceScale;
79
80
81
82
};

//============================================================================

83
84
85
int
main(int argc, char* argv[])
{
86
  cout << "MPEG PCC tmc3 version " << ::pcc::version << endl;
87

Khaled Mammou's avatar
TMC3v0  
Khaled Mammou committed
88
89
90
91
  Parameters params;
  if (!ParseParameters(argc, argv, params)) {
    return -1;
  }
92
93
94
95
96
97
98

  // Timers to count elapsed wall/user time
  pcc::chrono::Stopwatch<std::chrono::steady_clock> clock_wall;
  pcc::chrono::Stopwatch<pcc::chrono::utime_inc_children_clock> clock_user;

  clock_wall.start();

Khaled Mammou's avatar
TMC3v0  
Khaled Mammou committed
99
  int ret = 0;
100
  if (params.isDecoder) {
101
    ret = Decompress(params, clock_user);
102
103
  } else {
    ret = Compress(params, clock_user);
Khaled Mammou's avatar
TMC3v0  
Khaled Mammou committed
104
105
  }

106
107
108
109
110
111
112
113
  clock_wall.stop();

  using namespace std::chrono;
  auto total_wall = duration_cast<milliseconds>(clock_wall.count()).count();
  auto total_user = duration_cast<milliseconds>(clock_user.count()).count();
  std::cout << "Processing time (wall): " << total_wall / 1000.0 << " s\n";
  std::cout << "Processing time (user): " << total_user / 1000.0 << " s\n";

Khaled Mammou's avatar
TMC3v0  
Khaled Mammou committed
114
115
116
  return ret;
}

117
118
119
//---------------------------------------------------------------------------
// :: Command line / config parsing helpers

120
121
122
123
template<typename T>
static std::istream&
readUInt(std::istream& in, T& val)
{
124
125
126
127
128
129
  unsigned int tmp;
  in >> tmp;
  val = T(tmp);
  return in;
}

130
131
132
static std::istream&
operator>>(std::istream& in, ColorTransform& val)
{
133
134
135
  return readUInt(in, val);
}

136
namespace pcc {
137
static std::istream&
138
operator>>(std::istream& in, AttributeEncoding& val)
139
{
140
  return readUInt(in, val);
141
142
}
}  // namespace pcc
143

144
namespace pcc {
145
146
147
static std::istream&
operator>>(std::istream& in, GeometryCodecType& val)
{
148
  return readUInt(in, val);
149
150
}
}  // namespace pcc
151

152
namespace pcc {
153
static std::ostream&
154
operator<<(std::ostream& out, const AttributeEncoding& val)
155
{
156
  switch (val) {
157
158
159
  case AttributeEncoding::kPredictingTransform: out << "0 (Pred)"; break;
  case AttributeEncoding::kRAHTransform: out << "1 (RAHT)"; break;
  case AttributeEncoding::kLiftingTransform: out << "2 (Lift)"; break;
160
161
  }
  return out;
162
163
}
}  // namespace pcc
164

165
namespace pcc {
166
167
168
static std::ostream&
operator<<(std::ostream& out, const GeometryCodecType& val)
{
169
  switch (val) {
170
171
  case GeometryCodecType::kOctree: out << "1 (Octree)"; break;
  case GeometryCodecType::kTriSoup: out << "2 (TriSoup)"; break;
172
173
  }
  return out;
174
175
}
}  // namespace pcc
176

177
178
179
//---------------------------------------------------------------------------
// :: Command line / config parsing

180
181
182
bool
ParseParameters(int argc, char* argv[], Parameters& params)
{
183
184
  namespace po = df::program_options_lite;

185
186
187
188
189
  struct {
    AttributeDescription desc;
    AttributeParameterSet aps;
  } params_attr;

190
191
192
193
194
195
196
197
198
199
200
201
202
  bool print_help = false;

  // a helper to set the attribute
  std::function<po::OptionFunc::Func> attribute_setter =
    [&](po::Options&, const std::string& name, po::ErrorReporter) {
      // copy the current state of parsed attribute parameters
      //
      // NB: this does not cause the default values of attr to be restored
      // for the next attribute block.  A side-effect of this is that the
      // following is allowed leading to attribute foo having both X=1 and
      // Y=2:
      //   "--attr.X=1 --attribute foo --attr.Y=2 --attribute foo"
      //
203
204
205
206
207
208
209
210
211
212
213
214
215
216

      // NB: insert returns any existing element
      const auto& it = params.encoder.attributeIdxMap.insert(
        {name, int(params.encoder.attributeIdxMap.size())});

      if (it.second) {
        params.encoder.sps.attributeSets.push_back(params_attr.desc);
        params.encoder.aps.push_back(params_attr.aps);
        return;
      }

      // update existing entry
      params.encoder.sps.attributeSets[it.first->second] = params_attr.desc;
      params.encoder.aps[it.first->second] = params_attr.aps;
217
218
    };

219
  /* clang-format off */
220
221
222
223
224
225
226
227
228
229
230
  // The definition of the program/config options, along with default values.
  //
  // NB: when updating the following tables:
  //      (a) please keep to 80-columns for easier reading at a glance,
  //      (b) do not vertically align values -- it breaks quickly
  //
  po::Options opts;
  opts.addOptions()
  ("help", print_help, false, "this help text")
  ("config,c", po::parseConfigFile, "configuration file name")

231
232
  (po::Section("General"))

233
  ("mode", params.isDecoder, false,
234
235
    "The encoding/decoding mode:\n"
    "  0: encode\n"
236
    "  1: decode")
237
238
239

  // i/o parameters
  ("reconstructedDataPath",
240
241
    params.reconstructedDataPath, {},
    "The ouput reconstructed pointcloud file path (decoder only)")
242
243

  ("uncompressedDataPath",
244
245
    params.uncompressedDataPath, {},
    "The input pointcloud file path")
246
247

  ("compressedStreamPath",
248
249
    params.compressedStreamPath, {},
    "The compressed bitstream path (encoder=output, decoder=input)")
250

251
  ("postRecolorPath",
252
    params.encoder.postRecolorPath, {},
253
    "Recolored pointcloud file path (encoder only)")
254
255

  ("preInvScalePath",
256
    params.preInvScalePath, {},
257
    "Pre inverse scaled pointcloud file path (decoder only)")
258

259
260
261
262
  ("outputBinaryPly",
    params.outputBinaryPly, false,
    "Output ply files using binary (or otherwise ascii) format")

263
  // general
264
  // todo(df): this should be per-attribute
265
  ("colorTransform",
266
267
268
269
    params.colorTransform, COLOR_TRANSFORM_RGB_TO_YCBCR,
    "The colour transform to be applied:\n"
    "  0: none\n"
    "  1: RGB to YCbCr (Rec.709)")
270

271
272
273
274
275
276
  // todo(df): this should be per-attribute
  ("hack.reflectanceScale",
    params.reflectanceScale, 1,
    "scale factor to be applied to reflectance "
    "pre encoding / post reconstruction")

277
278
  // NB: if adding decoder options, uncomment the Decoder section marker
  // (po::Section("Decoder"))
279
280
281

  (po::Section("Encoder"))

282
  ("positionQuantizationScale",
283
    params.encoder.sps.seq_source_geom_scale_factor, 1.f,
284
    "Scale factor to be applied to point positions during quantization process")
285

286
287
288
289
  ("positionQuantizationScaleAdjustsDist2",
    params.positionQuantizationScaleAdjustsDist2, false,
    "Scale dist2 values by squared positionQuantizationScale")

290
  ("mergeDuplicatedPoints",
291
    params.encoder.gps.geom_unique_points_flag, true,
292
    "Enables removal of duplicated points")
293

294
295
296
297
  ("disableAttributeCoding",
    params.disableAttributeCoding, false,
    "Ignore attribute coding configuration")

298
  (po::Section("Geometry"))
299

300
  // tools
301
  ("geometryCodec",
302
    params.encoder.gps.geom_codec_type, GeometryCodecType::kOctree,
303
    "Controls the method used to encode geometry:\n"
304
305
    "  1: octree (TMC3)\n"
    "  2: trisoup (TMC1)")
306

307
308
309
310
311
312
  ("bitwiseOccupancyCoding",
    params.encoder.gps.bitwise_occupancy_coding_flag, true,
    "Selects between bitwise and bytewise occupancy coding:\n"
    "  0: bytewise\n"
    "  1: bitwise")

313
  ("neighbourContextRestriction",
314
    params.encoder.gps.neighbour_context_restriction_flag, false,
315
    "Limit geometry octree occupancy contextualisation to sibling nodes")
316

317
  ("neighbourAvailBoundaryLog2",
318
    params.encoder.gps.neighbour_avail_boundary_log2, 0,
319
320
321
    "Defines the avaliability volume for neighbour occupancy lookups."
    " 0: unconstrained")

322
  ("inferredDirectCodingMode",
323
    params.encoder.gps.inferred_direct_coding_mode_enabled_flag, true,
324
    "Permits early termination of the geometry octree for isolated points")
325

326
327
328
329
  ("intra_pred_max_node_size_log2",
    params.encoder.gps.intra_pred_max_node_size_log2, 0,
    "octree nodesizes eligible for occupancy intra prediction")

330
331
332
333
  ("ctxOccupancyReductionFactor",
     params.encoder.gps.geom_occupancy_ctx_reduction_factor, 3,
     "Adjusts the number of contexts used in occupancy coding")

334
335
  // (trisoup) geometry parameters
  ("triSoupDepth",  // log2(maxBB+1), where maxBB+1 is analogous to image width
336
    params.encoder.gps.trisoup_depth, 10,
337
    "Depth of voxels (reconstructed points) in trisoup geometry")
338
339

  ("triSoupLevel",
340
    params.encoder.gps.trisoup_triangle_level, 7,
341
    "Level of triangles (reconstructed surface) in trisoup geometry")
342
343

  ("triSoupIntToOrigScale",  // reciprocal of positionQuantizationScale
344
345
    params.encoder.sps.donotuse_trisoup_int_to_orig_scale, 1.f,
    "orig_coords = integer_coords * intToOrigScale")
346

347
348
  (po::Section("Attributes"))

349
350
351
  // attribute processing
  //   NB: Attribute options are special in the way they are applied (see above)
  ("attribute",
352
353
354
    attribute_setter,
    "Encode the given attribute (NB, must appear after the"
    "following attribute parameters)")
355

356
357
358
359
  ("bitdepth",
    params_attr.desc.attr_bitdepth, 8,
    "Attribute bitdepth")

360
  ("transformType",
361
    params_attr.aps.attr_encoding, AttributeEncoding::kPredictingTransform,
362
    "Coding method to use for attribute:\n"
363
    "  0: Hierarchical neighbourhood prediction\n"
364
    "  1: Region Adaptive Hierarchical Transform (RAHT)\n"
365
    "  2: Hierarichical neighbourhood prediction as lifting transform")
366

367
  ("rahtLeafDecimationDepth",
368
    params_attr.aps.raht_binary_level_threshold, 3,
369
370
    "Sets coefficients to zero in the bottom n levels of RAHT tree. "
    "Used for chroma-subsampling in attribute=color only.")
371

372
  ("rahtQuantizationStep",
373
    params_attr.aps.quant_step_size_luma, 0,
374
    "deprecated -- use quantizationStepsLuma")
375
376

  ("rahtDepth",
377
    params_attr.aps.raht_depth, 21,
378
379
    "Number of bits for morton representation of an RAHT co-ordinate"
    "component")
380

381
  ("numberOfNearestNeighborsInPrediction",
382
    params_attr.aps.num_pred_nearest_neighbours, 3,
383
    "Attribute's maximum number of nearest neighbors to be used for prediction")
384

385
386
387
388
389
390
  ("adaptivePredictionThreshold",
    params_attr.aps.adaptive_prediction_threshold, -1,
    "Neighbouring attribute value difference that enables choice of "
    "single|multi predictors. Applies to transformType=2 only.\n"
    "  -1: auto = 2**(bitdepth-2)")

391
392
393
394
395
  ("max_num_direct_predictors",
    params_attr.aps.max_num_direct_predictors, 3,
    "Maximum number of nearest neighbour candidates used in direct"
    "attribute prediction")

396
  ("levelOfDetailCount",
397
    params_attr.aps.numDetailLevels, 1,
398
    "Attribute's number of levels of detail")
399

400
401
402
  ("quantizationStepLuma",
    params_attr.aps.quant_step_size_luma, 0,
    "Attribute's luma quantization step size")
403

404
405
406
  ("quantizationStepChroma",
    params_attr.aps.quant_step_size_chroma, 0,
    "Attribute's chroma quantization step size")
407

408
409
  ("dist2",
    params_attr.aps.dist2, {},
410
411
    "Attribute's list of squared distances, or initial value for automatic"
    "derivation")
412
  ;
413
  /* clang-format on */
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428

  po::setDefaults(opts);
  po::ErrorReporter err;
  const list<const char*>& argv_unhandled =
    po::scanArgv(opts, argc, (const char**)argv, err);

  for (const auto arg : argv_unhandled) {
    err.warn() << "Unhandled argument ignored: " << arg << "\n";
  }

  if (argc == 1 || print_help) {
    po::doHelp(std::cout, opts, 78);
    return false;
  }

429
430
431
432
  if (int(params.encoder.gps.geom_codec_type) == 0) {
    err.error() << "Bypassed geometry coding is no longer supported\n";
  }

433
  // For trisoup, ensure that positionQuantizationScale is the exact inverse of intToOrigScale.
434
435
436
  if (params.encoder.gps.geom_codec_type == GeometryCodecType::kTriSoup) {
    params.encoder.sps.seq_source_geom_scale_factor =
      1.0f / params.encoder.sps.donotuse_trisoup_int_to_orig_scale;
437
438
  }

439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
  // TriSoup geometry is only enabled when trisoup depth > triangle_level.
  // NB: this happens after the scale factor fudge above, since the user
  //     believes they are configuring trisoup
  if (params.encoder.gps.geom_codec_type == GeometryCodecType::kTriSoup) {
    const auto& gps = params.encoder.gps;
    int trisoupNodeSizeLog2 = gps.trisoup_depth - gps.trisoup_triangle_level;
    if (trisoupNodeSizeLog2 <= 0) {
      err.warn() << "TriSoup disabled when depth <= triangle level\n";
      params.encoder.gps.geom_codec_type = GeometryCodecType::kOctree;
    }
  }

  // Certain coding modes are not available when trisoup is enabled.
  // Disable them, and warn if set (they may be set as defaults).
  if (params.encoder.gps.geom_codec_type == GeometryCodecType::kTriSoup) {
    if (!params.encoder.gps.geom_unique_points_flag)
      err.warn() << "TriSoup geometry does not preserve duplicated points\n";

    if (params.encoder.gps.inferred_direct_coding_mode_enabled_flag)
      err.warn() << "TriSoup geometry is incompatable with IDCM\n";

    params.encoder.gps.geom_unique_points_flag = true;
    params.encoder.gps.inferred_direct_coding_mode_enabled_flag = false;
  }

464
465
466
467
468
469
470
  // support disabling attribute coding (simplifies configuration)
  if (params.disableAttributeCoding) {
    params.encoder.attributeIdxMap.clear();
    params.encoder.sps.attributeSets.clear();
    params.encoder.aps.clear();
  }

471
  // fixup any per-attribute settings
472
  for (const auto& it : params.encoder.attributeIdxMap) {
473
    auto& attr_sps = params.encoder.sps.attributeSets[it.second];
474
475
    auto& attr_aps = params.encoder.aps[it.second];

476
477
478
479
480
    // Avoid wasting bits signalling chroma quant step size for reflectance
    if (it.first == "reflectance") {
      attr_aps.quant_step_size_chroma = 0;
    }

481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
    bool isLifting =
      attr_aps.attr_encoding == AttributeEncoding::kPredictingTransform
      || attr_aps.attr_encoding == AttributeEncoding::kLiftingTransform;

    // derive the dist2 values based on an initial value
    if (isLifting && !attr_aps.dist2.empty()) {
      if (attr_aps.dist2.size() < attr_aps.numDetailLevels) {
        attr_aps.dist2.resize(attr_aps.numDetailLevels);
        const double distRatio = 4.0;
        uint64_t d2 = attr_aps.dist2[0];

        for (int i = 1; i < attr_aps.numDetailLevels; ++i) {
          attr_aps.dist2[attr_aps.numDetailLevels - 1 - i] = d2;
          d2 = uint64_t(std::round(distRatio * d2));
        }
        attr_aps.dist2[attr_aps.numDetailLevels - 1] = 0;
      }
    }

500
501
502
503
504
505
506
507
508
509
510
    // In order to simplify specification of dist2 values, which are
    // depending on the scale of the coded point cloud, the following
    // adjust the dist2 values according to PQS.  The user need only
    // specify the unquantised PQS value.
    if (params.positionQuantizationScaleAdjustsDist2) {
      double pqs = params.encoder.sps.seq_source_geom_scale_factor;
      double pqs2 = pqs * pqs;
      for (auto& dist2 : attr_aps.dist2)
        dist2 = int64_t(std::round(pqs2 * dist2));
    }

511
512
513
514
515
516
517
518
519
520
521
    // Set default threshold based on bitdepth
    if (attr_aps.adaptive_prediction_threshold == -1) {
      attr_aps.adaptive_prediction_threshold = 1
        << (attr_sps.attr_bitdepth - 2);
    }

    if (attr_aps.attr_encoding == AttributeEncoding::kLiftingTransform) {
      attr_aps.adaptive_prediction_threshold = 0;
    }

    // For RAHT, ensure that the unused lod count = 0 (prevents mishaps)
522
523
    if (attr_aps.attr_encoding == AttributeEncoding::kRAHTransform) {
      attr_aps.numDetailLevels = 0;
524
      attr_aps.adaptive_prediction_threshold = 0;
525
526
527

      // todo(df): suggest chroma quant_step_size for raht
      attr_aps.quant_step_size_chroma = 0;
528
529
530
    }
  }

531
  // sanity checks
532
533
534
535
536
537

  if (params.encoder.gps.intra_pred_max_node_size_log2)
    if (!params.encoder.gps.neighbour_avail_boundary_log2)
      err.error() << "Geometry intra prediction requires finite"
                     "neighbour_avail_boundary_log2\n";

538
539
540
541
542
543
544
545
  for (const auto& it : params.encoder.attributeIdxMap) {
    const auto& attr_sps = params.encoder.sps.attributeSets[it.second];
    const auto& attr_aps = params.encoder.aps[it.second];

    bool isLifting =
      attr_aps.attr_encoding == AttributeEncoding::kPredictingTransform
      || attr_aps.attr_encoding == AttributeEncoding::kLiftingTransform;

546
547
548
549
550
551
552
553
554
555
556
    if (it.first == "color") {
      // todo(??): permit relaxing of the following constraint
      if (attr_sps.attr_bitdepth > 8)
        err.error() << it.first << ".bitdepth must be less than 9\n";
    }

    if (it.first == "reflectance") {
      if (attr_sps.attr_bitdepth > 16)
        err.error() << it.first << ".bitdepth must be less than 17\n";
    }

557
558
    if (isLifting) {
      int lod = attr_aps.numDetailLevels;
559

560
      if (lod > 255 || lod < 1) {
561
        err.error() << it.first
562
                    << ".levelOfDetailCount must be in the range [1,255]\n";
563
      }
564
565
      if (attr_aps.dist2.size() != lod) {
        err.error() << it.first << ".dist2 does not have " << lod
566
                    << " entries\n";
567
      }
568

569
570
571
572
573
      if (attr_aps.adaptive_prediction_threshold < 0) {
        err.error() << it.first
                    << ".adaptivePredictionThreshold must be positive\n";
      }

574
      if (
575
        attr_aps.num_pred_nearest_neighbours
576
        > kAttributePredictionMaxNeighbourCount) {
577
578
        err.error() << it.first
                    << ".numberOfNearestNeighborsInPrediction must be <= "
579
                    << kAttributePredictionMaxNeighbourCount << "\n";
580
      }
581
    }
Khaled Mammou's avatar
TMC3v0  
Khaled Mammou committed
582
583
  }

584
585
  // check required arguments are specified

586
  if (!params.isDecoder && params.uncompressedDataPath.empty())
587
588
    err.error() << "uncompressedDataPath not set\n";

589
  if (params.isDecoder && params.reconstructedDataPath.empty())
590
591
592
593
594
595
596
597
598
599
    err.error() << "reconstructedDataPath not set\n";

  if (params.compressedStreamPath.empty())
    err.error() << "compressedStreamPath not set\n";

  // report the current configuration (only in the absence of errors so
  // that errors/warnings are more obvious and in the same place).
  if (err.is_errored)
    return false;

600
601
  // Dump the complete derived configuration
  cout << "+ Effective configuration parameters\n";
602

603
  po::dumpCfg(cout, opts, "General", 4);
604
  if (params.isDecoder) {
605
    po::dumpCfg(cout, opts, "Decoder", 4);
606
  } else {
607
608
609
    po::dumpCfg(cout, opts, "Encoder", 4);
    po::dumpCfg(cout, opts, "Geometry", 4);

610
    for (const auto& it : params.encoder.attributeIdxMap) {
611
      // NB: when dumping the config, opts references params_attr
612
613
      params_attr.desc = params.encoder.sps.attributeSets[it.second];
      params_attr.aps = params.encoder.aps[it.second];
614
615
616
      cout << "    " << it.first << "\n";
      po::dumpCfg(cout, opts, "Attributes", 8);
    }
Khaled Mammou's avatar
TMC3v0  
Khaled Mammou committed
617
618
  }

619
620
  cout << endl;

Khaled Mammou's avatar
TMC3v0  
Khaled Mammou committed
621
622
  return true;
}
623

624
int
625
Compress(Parameters& params, Stopwatch& clock)
626
{
Khaled Mammou's avatar
TMC3v0  
Khaled Mammou committed
627
  PCCPointSet3 pointCloud;
628
629
630
  if (
    !pointCloud.read(params.uncompressedDataPath)
    || pointCloud.getPointCount() == 0) {
Khaled Mammou's avatar
TMC3v0  
Khaled Mammou committed
631
632
633
634
    cout << "Error: can't open input file!" << endl;
    return -1;
  }

635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
  // Sanitise the input point cloud
  // todo(df): remove the following with generic handling of properties
  bool codeColour = params.encoder.attributeIdxMap.count("color");
  if (!codeColour)
    pointCloud.removeColors();
  assert(codeColour == pointCloud.hasColors());

  bool codeReflectance = params.encoder.attributeIdxMap.count("reflectance");
  if (!codeReflectance)
    pointCloud.removeReflectances();
  assert(codeReflectance == pointCloud.hasReflectances());

  ofstream fout(params.compressedStreamPath, ios::binary);
  if (!fout.is_open()) {
    return -1;
  }

652
653
  clock.start();

Khaled Mammou's avatar
TMC3v0  
Khaled Mammou committed
654
655
656
  if (params.colorTransform == COLOR_TRANSFORM_RGB_TO_YCBCR) {
    pointCloud.convertRGBToYUV();
  }
657
658
659
660
661
662
663
664
665

  if (params.reflectanceScale > 1 && pointCloud.hasReflectances()) {
    const auto pointCount = pointCloud.getPointCount();
    for (size_t i = 0; i < pointCount; ++i) {
      int val = pointCloud.getReflectance(i) / params.reflectanceScale;
      pointCloud.setReflectance(i, val);
    }
  }

Khaled Mammou's avatar
TMC3v0  
Khaled Mammou committed
666
667
  PCCTMC3Encoder3 encoder;

668
669
  // The reconstructed point cloud
  std::unique_ptr<PCCPointSet3> reconPointCloud;
Khaled Mammou's avatar
TMC3v0  
Khaled Mammou committed
670
  if (!params.reconstructedDataPath.empty()) {
671
    reconPointCloud.reset(new PCCPointSet3);
Khaled Mammou's avatar
TMC3v0  
Khaled Mammou committed
672
673
  }

674
  int ret = encoder.compress(
675
676
    pointCloud, &params.encoder,
    [&](const PayloadBuffer& buf) { writeTlv(buf, fout); },
677
    reconPointCloud.get());
678
  if (ret) {
Khaled Mammou's avatar
TMC3v0  
Khaled Mammou committed
679
680
681
    cout << "Error: can't compress point cloud!" << endl;
    return -1;
  }
682

683
  std::cout << "Total bitstream size " << fout.tellp() << " B" << std::endl;
Khaled Mammou's avatar
TMC3v0  
Khaled Mammou committed
684
685
  fout.close();

686
687
  clock.stop();

Khaled Mammou's avatar
TMC3v0  
Khaled Mammou committed
688
689
  if (!params.reconstructedDataPath.empty()) {
    if (params.colorTransform == COLOR_TRANSFORM_RGB_TO_YCBCR) {
690
691
692
693
694
695
696
697
698
      reconPointCloud->convertYUVToRGB();
    }

    if (params.reflectanceScale > 1 && reconPointCloud->hasReflectances()) {
      const auto pointCount = reconPointCloud->getPointCount();
      for (size_t i = 0; i < pointCount; ++i) {
        int val = reconPointCloud->getReflectance(i) * params.reflectanceScale;
        reconPointCloud->setReflectance(i, val);
      }
Khaled Mammou's avatar
TMC3v0  
Khaled Mammou committed
699
    }
700

701
702
    reconPointCloud->write(
      params.reconstructedDataPath, !params.outputBinaryPly);
Khaled Mammou's avatar
TMC3v0  
Khaled Mammou committed
703
704
705
706
  }

  return 0;
}
707
int
708
Decompress(Parameters& params, Stopwatch& clock)
709
{
Khaled Mammou's avatar
TMC3v0  
Khaled Mammou committed
710
711
712
713
714
  ifstream fin(params.compressedStreamPath, ios::binary);
  if (!fin.is_open()) {
    return -1;
  }

715
716
  clock.start();

717
  PayloadBuffer buf;
Khaled Mammou's avatar
TMC3v0  
Khaled Mammou committed
718
  PCCTMC3Decoder3 decoder;
719

720
721
722
  while (true) {
    PayloadBuffer* buf_ptr = &buf;
    readTlv(fin, &buf);
Khaled Mammou's avatar
TMC3v0  
Khaled Mammou committed
723

724
725
726
    // at end of file (or other error), flush decoder
    if (!fin)
      buf_ptr = nullptr;
Khaled Mammou's avatar
TMC3v0  
Khaled Mammou committed
727

728
729
730
    int ret = decoder.decompress(
      params.decoder, buf_ptr, [&](const PCCPointSet3& decodedPointCloud) {
        PCCPointSet3 pointCloud(decodedPointCloud);
731

732
733
734
735
        if (params.colorTransform == COLOR_TRANSFORM_RGB_TO_YCBCR) {
          pointCloud.convertYUVToRGB();
        }

736
737
738
739
740
741
742
743
        if (params.reflectanceScale > 1 && pointCloud.hasReflectances()) {
          const auto pointCount = pointCloud.getPointCount();
          for (size_t i = 0; i < pointCount; ++i) {
            int val = pointCloud.getReflectance(i) * params.reflectanceScale;
            pointCloud.setReflectance(i, val);
          }
        }

744
745
        // Dump the decoded colour using the pre inverse scaled geometry
        if (!params.preInvScalePath.empty()) {
746
          pointCloud.write(params.preInvScalePath, !params.outputBinaryPly);
747
748
        }

749
        decoder.inverseQuantization(pointCloud);
750
751
752

        clock.stop();

753
754
        if (!pointCloud.write(
              params.reconstructedDataPath, !params.outputBinaryPly)) {
755
756
757
758
759
760
761
762
763
764
765
766
767
          cout << "Error: can't open output file!" << endl;
        }

        clock.start();
      });

    if (ret) {
      cout << "Error: can't decompress point cloud!" << endl;
      return -1;
    }

    if (!buf_ptr)
      break;
Khaled Mammou's avatar
TMC3v0  
Khaled Mammou committed
768
  }
769

770
771
772
773
774
775
  fin.clear();
  fin.seekg(0, ios_base::end);
  std::cout << "Total bitstream size " << fin.tellg() << " B" << std::endl;

  clock.stop();

Khaled Mammou's avatar
TMC3v0  
Khaled Mammou committed
776
777
  return 0;
}