TMC3.cpp 22.3 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"
37
#include "constants.h"
38
#include "program_options_lite.h"
39
#include "io_tlv.h"
40
#include "version.h"
Khaled Mammou's avatar
TMC3v0  
Khaled Mammou committed
41
42
43
44

using namespace std;
using namespace pcc;

45
46
47
48
49
//============================================================================

struct Parameters {
  bool isDecoder;

50
51
52
  // command line parsing should adjust dist2 values according to PQS
  bool positionQuantizationScaleAdjustsDist2;

53
54
55
  // output mode for ply writing (binary or ascii)
  bool outputBinaryPly;

56
57
58
  // when true, configure the encoder as if no attributes are specified
  bool disableAttributeCoding;

59
60
61
62
  std::string uncompressedDataPath;
  std::string compressedStreamPath;
  std::string reconstructedDataPath;

63
64
65
  // Filename for saving pre inverse scaled point cloud.
  std::string preInvScalePath;

66
67
68
69
70
  pcc::EncoderParams encoder;
  pcc::DecoderParams decoder;

  // todo(df): this should be per-attribute
  ColorTransform colorTransform;
71
72
73

  // todo(df): this should be per-attribute
  int reflectanceScale;
74
75
76
77
};

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

78
79
80
int
main(int argc, char* argv[])
{
81
  cout << "MPEG PCC tmc3 version " << ::pcc::version << endl;
82

Khaled Mammou's avatar
TMC3v0  
Khaled Mammou committed
83
84
85
86
  Parameters params;
  if (!ParseParameters(argc, argv, params)) {
    return -1;
  }
87
88
89
90
91
92
93

  // 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
94
  int ret = 0;
95
  if (params.isDecoder) {
96
    ret = Decompress(params, clock_user);
97
98
  } else {
    ret = Compress(params, clock_user);
Khaled Mammou's avatar
TMC3v0  
Khaled Mammou committed
99
100
  }

101
102
103
104
105
106
107
108
  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
109
110
111
  return ret;
}

112
113
114
//---------------------------------------------------------------------------
// :: Command line / config parsing helpers

115
116
117
118
template<typename T>
static std::istream&
readUInt(std::istream& in, T& val)
{
119
120
121
122
123
124
  unsigned int tmp;
  in >> tmp;
  val = T(tmp);
  return in;
}

125
126
127
static std::istream&
operator>>(std::istream& in, ColorTransform& val)
{
128
129
130
  return readUInt(in, val);
}

131
namespace pcc {
132
static std::istream&
133
operator>>(std::istream& in, AttributeEncoding& val)
134
{
135
  return readUInt(in, val);
136
137
}
}  // namespace pcc
138

139
namespace pcc {
140
141
142
static std::istream&
operator>>(std::istream& in, GeometryCodecType& val)
{
143
  return readUInt(in, val);
144
145
}
}  // namespace pcc
146

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

160
namespace pcc {
161
162
163
static std::ostream&
operator<<(std::ostream& out, const GeometryCodecType& val)
{
164
  switch (val) {
165
166
  case GeometryCodecType::kOctree: out << "1 (Octree)"; break;
  case GeometryCodecType::kTriSoup: out << "2 (TriSoup)"; break;
167
168
  }
  return out;
169
170
}
}  // namespace pcc
171

172
173
174
//---------------------------------------------------------------------------
// :: Command line / config parsing

175
176
177
bool
ParseParameters(int argc, char* argv[], Parameters& params)
{
178
179
  namespace po = df::program_options_lite;

180
181
182
183
184
  struct {
    AttributeDescription desc;
    AttributeParameterSet aps;
  } params_attr;

185
186
187
188
189
190
191
192
193
194
195
196
197
  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"
      //
198
199
200
201
202
203
204
205
206
207
208
209
210
211

      // 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;
212
213
    };

214
  /* clang-format off */
215
216
217
218
219
220
221
222
223
224
225
  // 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")

226
227
  (po::Section("General"))

228
  ("mode", params.isDecoder, false,
229
230
    "The encoding/decoding mode:\n"
    "  0: encode\n"
231
    "  1: decode")
232
233
234

  // i/o parameters
  ("reconstructedDataPath",
235
236
    params.reconstructedDataPath, {},
    "The ouput reconstructed pointcloud file path (decoder only)")
237
238

  ("uncompressedDataPath",
239
240
    params.uncompressedDataPath, {},
    "The input pointcloud file path")
241
242

  ("compressedStreamPath",
243
244
    params.compressedStreamPath, {},
    "The compressed bitstream path (encoder=output, decoder=input)")
245

246
  ("postRecolorPath",
247
    params.encoder.postRecolorPath, {},
248
    "Recolored pointcloud file path (encoder only)")
249
250

  ("preInvScalePath",
251
    params.preInvScalePath, {},
252
    "Pre inverse scaled pointcloud file path (decoder only)")
253

254
255
256
257
  ("outputBinaryPly",
    params.outputBinaryPly, false,
    "Output ply files using binary (or otherwise ascii) format")

258
  // general
259
  // todo(df): this should be per-attribute
260
  ("colorTransform",
261
262
263
264
    params.colorTransform, COLOR_TRANSFORM_RGB_TO_YCBCR,
    "The colour transform to be applied:\n"
    "  0: none\n"
    "  1: RGB to YCbCr (Rec.709)")
265

266
267
268
269
270
271
  // todo(df): this should be per-attribute
  ("hack.reflectanceScale",
    params.reflectanceScale, 1,
    "scale factor to be applied to reflectance "
    "pre encoding / post reconstruction")

272
273
  // NB: if adding decoder options, uncomment the Decoder section marker
  // (po::Section("Decoder"))
274
275
276

  (po::Section("Encoder"))

277
  ("positionQuantizationScale",
278
    params.encoder.sps.seq_source_geom_scale_factor, 1.f,
279
    "Scale factor to be applied to point positions during quantization process")
280

281
282
283
284
  ("positionQuantizationScaleAdjustsDist2",
    params.positionQuantizationScaleAdjustsDist2, false,
    "Scale dist2 values by squared positionQuantizationScale")

285
  ("mergeDuplicatedPoints",
286
    params.encoder.gps.geom_unique_points_flag, true,
287
    "Enables removal of duplicated points")
288

289
290
291
292
  ("disableAttributeCoding",
    params.disableAttributeCoding, false,
    "Ignore attribute coding configuration")

293
  (po::Section("Geometry"))
294

295
  // tools
296
  ("geometryCodec",
297
    params.encoder.gps.geom_codec_type, GeometryCodecType::kOctree,
298
    "Controls the method used to encode geometry:\n"
299
300
    "  1: octree (TMC3)\n"
    "  2: trisoup (TMC1)")
301

302
  ("neighbourContextRestriction",
303
    params.encoder.gps.neighbour_context_restriction_flag, false,
304
    "Limit geometry octree occupancy contextualisation to sibling nodes")
305

306
  ("neighbourAvailBoundaryLog2",
307
    params.encoder.gps.neighbour_avail_boundary_log2, 0,
308
309
310
    "Defines the avaliability volume for neighbour occupancy lookups."
    " 0: unconstrained")

311
  ("inferredDirectCodingMode",
312
    params.encoder.gps.inferred_direct_coding_mode_enabled_flag, true,
313
    "Permits early termination of the geometry octree for isolated points")
314

315
316
  // (trisoup) geometry parameters
  ("triSoupDepth",  // log2(maxBB+1), where maxBB+1 is analogous to image width
317
    params.encoder.gps.trisoup_depth, 10,
318
    "Depth of voxels (reconstructed points) in trisoup geometry")
319
320

  ("triSoupLevel",
321
    params.encoder.gps.trisoup_triangle_level, 7,
322
    "Level of triangles (reconstructed surface) in trisoup geometry")
323
324

  ("triSoupIntToOrigScale",  // reciprocal of positionQuantizationScale
325
326
    params.encoder.sps.donotuse_trisoup_int_to_orig_scale, 1.f,
    "orig_coords = integer_coords * intToOrigScale")
327

328
329
  (po::Section("Attributes"))

330
331
332
  // attribute processing
  //   NB: Attribute options are special in the way they are applied (see above)
  ("attribute",
333
334
335
    attribute_setter,
    "Encode the given attribute (NB, must appear after the"
    "following attribute parameters)")
336

337
338
339
340
  ("bitdepth",
    params_attr.desc.attr_bitdepth, 8,
    "Attribute bitdepth")

341
  ("transformType",
342
    params_attr.aps.attr_encoding, AttributeEncoding::kPredictingTransform,
343
    "Coding method to use for attribute:\n"
344
    "  0: Hierarchical neighbourhood prediction\n"
345
    "  1: Region Adaptive Hierarchical Transform (RAHT)\n"
346
    "  2: Hierarichical neighbourhood prediction as lifting transform")
347

348
  ("rahtLeafDecimationDepth",
349
    params_attr.aps.raht_binary_level_threshold, 3,
350
351
    "Sets coefficients to zero in the bottom n levels of RAHT tree. "
    "Used for chroma-subsampling in attribute=color only.")
352

353
  ("rahtQuantizationStep",
354
    params_attr.aps.quant_step_size_luma, 0,
355
    "deprecated -- use quantizationStepsLuma")
356
357

  ("rahtDepth",
358
    params_attr.aps.raht_depth, 21,
359
360
    "Number of bits for morton representation of an RAHT co-ordinate"
    "component")
361

362
  ("numberOfNearestNeighborsInPrediction",
363
    params_attr.aps.num_pred_nearest_neighbours, 3,
364
    "Attribute's maximum number of nearest neighbors to be used for prediction")
365

366
367
368
369
370
371
  ("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)")

372
  ("levelOfDetailCount",
373
    params_attr.aps.numDetailLevels, 1,
374
    "Attribute's number of levels of detail")
375

376
377
378
  ("quantizationStepLuma",
    params_attr.aps.quant_step_size_luma, 0,
    "Attribute's luma quantization step size")
379

380
381
382
  ("quantizationStepChroma",
    params_attr.aps.quant_step_size_chroma, 0,
    "Attribute's chroma quantization step size")
383

384
385
  ("dist2",
    params_attr.aps.dist2, {},
386
387
    "Attribute's list of squared distances, or initial value for automatic"
    "derivation")
388
  ;
389
  /* clang-format on */
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404

  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;
  }

405
406
407
408
  if (int(params.encoder.gps.geom_codec_type) == 0) {
    err.error() << "Bypassed geometry coding is no longer supported\n";
  }

409
  // For trisoup, ensure that positionQuantizationScale is the exact inverse of intToOrigScale.
410
411
412
  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;
413
414
  }

415
416
417
418
419
420
421
  // support disabling attribute coding (simplifies configuration)
  if (params.disableAttributeCoding) {
    params.encoder.attributeIdxMap.clear();
    params.encoder.sps.attributeSets.clear();
    params.encoder.aps.clear();
  }

422
  // fixup any per-attribute settings
423
  for (const auto& it : params.encoder.attributeIdxMap) {
424
    auto& attr_sps = params.encoder.sps.attributeSets[it.second];
425
426
    auto& attr_aps = params.encoder.aps[it.second];

427
428
429
430
431
    // Avoid wasting bits signalling chroma quant step size for reflectance
    if (it.first == "reflectance") {
      attr_aps.quant_step_size_chroma = 0;
    }

432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
    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;
      }
    }

451
452
453
454
455
456
457
458
459
460
461
    // 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));
    }

462
463
464
465
466
467
468
469
470
471
472
    // 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)
473
474
    if (attr_aps.attr_encoding == AttributeEncoding::kRAHTransform) {
      attr_aps.numDetailLevels = 0;
475
      attr_aps.adaptive_prediction_threshold = 0;
476
477
478

      // todo(df): suggest chroma quant_step_size for raht
      attr_aps.quant_step_size_chroma = 0;
479
480
481
    }
  }

482
  // sanity checks
483
484
485
486
487
488
489
490
  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;

491
492
493
494
495
496
497
498
499
500
501
    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";
    }

502
503
    if (isLifting) {
      int lod = attr_aps.numDetailLevels;
504

505
      if (lod > 255 || lod < 1) {
506
        err.error() << it.first
507
                    << ".levelOfDetailCount must be in the range [1,255]\n";
508
      }
509
510
      if (attr_aps.dist2.size() != lod) {
        err.error() << it.first << ".dist2 does not have " << lod
511
                    << " entries\n";
512
      }
513

514
515
516
517
518
      if (attr_aps.adaptive_prediction_threshold < 0) {
        err.error() << it.first
                    << ".adaptivePredictionThreshold must be positive\n";
      }

519
      if (
520
        attr_aps.num_pred_nearest_neighbours
521
        > kAttributePredictionMaxNeighbourCount) {
522
523
        err.error() << it.first
                    << ".numberOfNearestNeighborsInPrediction must be <= "
524
                    << kAttributePredictionMaxNeighbourCount << "\n";
525
      }
526
    }
Khaled Mammou's avatar
TMC3v0  
Khaled Mammou committed
527
528
  }

529
530
  // check required arguments are specified

531
  if (!params.isDecoder && params.uncompressedDataPath.empty())
532
533
    err.error() << "uncompressedDataPath not set\n";

534
  if (params.isDecoder && params.reconstructedDataPath.empty())
535
536
537
538
539
540
541
542
543
544
    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;

545
546
  // Dump the complete derived configuration
  cout << "+ Effective configuration parameters\n";
547

548
  po::dumpCfg(cout, opts, "General", 4);
549
  if (params.isDecoder) {
550
    po::dumpCfg(cout, opts, "Decoder", 4);
551
  } else {
552
553
554
    po::dumpCfg(cout, opts, "Encoder", 4);
    po::dumpCfg(cout, opts, "Geometry", 4);

555
    for (const auto& it : params.encoder.attributeIdxMap) {
556
      // NB: when dumping the config, opts references params_attr
557
558
      params_attr.desc = params.encoder.sps.attributeSets[it.second];
      params_attr.aps = params.encoder.aps[it.second];
559
560
561
      cout << "    " << it.first << "\n";
      po::dumpCfg(cout, opts, "Attributes", 8);
    }
Khaled Mammou's avatar
TMC3v0  
Khaled Mammou committed
562
563
  }

564
565
  cout << endl;

Khaled Mammou's avatar
TMC3v0  
Khaled Mammou committed
566
567
  return true;
}
568

569
int
570
Compress(Parameters& params, Stopwatch& clock)
571
{
Khaled Mammou's avatar
TMC3v0  
Khaled Mammou committed
572
  PCCPointSet3 pointCloud;
573
574
575
  if (
    !pointCloud.read(params.uncompressedDataPath)
    || pointCloud.getPointCount() == 0) {
Khaled Mammou's avatar
TMC3v0  
Khaled Mammou committed
576
577
578
579
    cout << "Error: can't open input file!" << endl;
    return -1;
  }

580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
  // 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;
  }

597
598
  clock.start();

Khaled Mammou's avatar
TMC3v0  
Khaled Mammou committed
599
600
601
  if (params.colorTransform == COLOR_TRANSFORM_RGB_TO_YCBCR) {
    pointCloud.convertRGBToYUV();
  }
602
603
604
605
606
607
608
609
610

  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
611
612
  PCCTMC3Encoder3 encoder;

613
614
  // The reconstructed point cloud
  std::unique_ptr<PCCPointSet3> reconPointCloud;
Khaled Mammou's avatar
TMC3v0  
Khaled Mammou committed
615
  if (!params.reconstructedDataPath.empty()) {
616
    reconPointCloud.reset(new PCCPointSet3);
Khaled Mammou's avatar
TMC3v0  
Khaled Mammou committed
617
618
  }

619
  int ret = encoder.compress(
620
621
    pointCloud, &params.encoder,
    [&](const PayloadBuffer& buf) { writeTlv(buf, fout); },
622
    reconPointCloud.get());
623
  if (ret) {
Khaled Mammou's avatar
TMC3v0  
Khaled Mammou committed
624
625
626
    cout << "Error: can't compress point cloud!" << endl;
    return -1;
  }
627

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

631
632
  clock.stop();

Khaled Mammou's avatar
TMC3v0  
Khaled Mammou committed
633
634
  if (!params.reconstructedDataPath.empty()) {
    if (params.colorTransform == COLOR_TRANSFORM_RGB_TO_YCBCR) {
635
636
637
638
639
640
641
642
643
      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
644
    }
645

646
647
    reconPointCloud->write(
      params.reconstructedDataPath, !params.outputBinaryPly);
Khaled Mammou's avatar
TMC3v0  
Khaled Mammou committed
648
649
650
651
  }

  return 0;
}
652
int
653
Decompress(Parameters& params, Stopwatch& clock)
654
{
Khaled Mammou's avatar
TMC3v0  
Khaled Mammou committed
655
656
657
658
659
  ifstream fin(params.compressedStreamPath, ios::binary);
  if (!fin.is_open()) {
    return -1;
  }

660
661
  clock.start();

662
  PayloadBuffer buf;
Khaled Mammou's avatar
TMC3v0  
Khaled Mammou committed
663
  PCCTMC3Decoder3 decoder;
664

665
666
667
  while (true) {
    PayloadBuffer* buf_ptr = &buf;
    readTlv(fin, &buf);
Khaled Mammou's avatar
TMC3v0  
Khaled Mammou committed
668

669
670
671
    // at end of file (or other error), flush decoder
    if (!fin)
      buf_ptr = nullptr;
Khaled Mammou's avatar
TMC3v0  
Khaled Mammou committed
672

673
674
675
    int ret = decoder.decompress(
      params.decoder, buf_ptr, [&](const PCCPointSet3& decodedPointCloud) {
        PCCPointSet3 pointCloud(decodedPointCloud);
676

677
678
679
680
        if (params.colorTransform == COLOR_TRANSFORM_RGB_TO_YCBCR) {
          pointCloud.convertYUVToRGB();
        }

681
682
683
684
685
686
687
688
        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);
          }
        }

689
690
        // Dump the decoded colour using the pre inverse scaled geometry
        if (!params.preInvScalePath.empty()) {
691
          pointCloud.write(params.preInvScalePath, !params.outputBinaryPly);
692
693
        }

694
        decoder.inverseQuantization(pointCloud);
695
696
697

        clock.stop();

698
699
        if (!pointCloud.write(
              params.reconstructedDataPath, !params.outputBinaryPly)) {
700
701
702
703
704
705
706
707
708
709
710
711
712
          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
713
  }
714

715
716
717
718
719
720
  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
721
722
  return 0;
}