Coverage Report

Created: 2026-12-01 06:50

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/libheif/libheif/sequences/track.cc
Line
Count
Source
1
/*
2
 * HEIF image base codec.
3
 * Copyright (c) 2024 Dirk Farin <dirk.farin@gmail.com>
4
 *
5
 * This file is part of libheif.
6
 *
7
 * libheif is free software: you can redistribute it and/or modify
8
 * it under the terms of the GNU Lesser General Public License as
9
 * published by the Free Software Foundation, either version 3 of
10
 * the License, or (at your option) any later version.
11
 *
12
 * libheif is distributed in the hope that it will be useful,
13
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15
 * GNU Lesser General Public License for more details.
16
 *
17
 * You should have received a copy of the GNU Lesser General Public License
18
 * along with libheif.  If not, see <http://www.gnu.org/licenses/>.
19
 */
20
21
#include <cstring>
22
#include "track.h"
23
#include "context.h"
24
#include "sequences/seq_boxes.h"
25
#include "sequences/chunk.h"
26
#include "sequences/track_visual.h"
27
#include "sequences/track_metadata.h"
28
#include "api_structs.h"
29
#include <algorithm>
30
#include <limits>
31
#include <memory>
32
#include <utility>
33
34
35
TrackOptions& TrackOptions::operator=(const TrackOptions& src)
36
0
{
37
0
  if (&src == this) {
38
0
    return *this;
39
0
  }
40
41
0
  this->track_timescale = src.track_timescale;
42
0
  this->write_sample_aux_infos_interleaved = src.write_sample_aux_infos_interleaved;
43
0
  this->with_sample_tai_timestamps = src.with_sample_tai_timestamps;
44
45
0
  if (src.tai_clock_info) {
46
0
    this->tai_clock_info = heif_tai_clock_info_alloc();
47
0
    heif_tai_clock_info_copy(this->tai_clock_info, src.tai_clock_info);
48
0
  }
49
0
  else {
50
0
    this->tai_clock_info = nullptr;
51
0
  }
52
53
0
  this->with_sample_content_ids = src.with_sample_content_ids;
54
0
  this->gimi_track_content_id = src.gimi_track_content_id;
55
56
0
  return *this;
57
0
}
58
59
60
SampleAuxInfoHelper::SampleAuxInfoHelper(bool interleaved)
61
0
  : m_interleaved(interleaved)
62
0
{
63
0
  m_saiz = std::make_shared<Box_saiz>();
64
0
  m_saio = std::make_shared<Box_saio>();
65
0
}
66
67
68
void SampleAuxInfoHelper::set_aux_info_type(uint32_t aux_info_type, uint32_t aux_info_type_parameter)
69
0
{
70
0
  m_saiz->set_aux_info_type(aux_info_type, aux_info_type_parameter);
71
0
  m_saio->set_aux_info_type(aux_info_type, aux_info_type_parameter);
72
0
}
73
74
Error SampleAuxInfoHelper::add_sample_info(const std::vector<uint8_t>& data)
75
0
{
76
0
  if (data.size() > 0xFF) {
77
0
    return {
78
0
      heif_error_Encoding_error,
79
0
      heif_suberror_Unspecified,
80
0
      "Encoded sample auxiliary information exceeds maximum size"
81
0
    };
82
0
  }
83
84
0
  m_saiz->add_sample_size(static_cast<uint8_t>(data.size()));
85
86
0
  m_data.insert(m_data.end(), data.begin(), data.end());
87
88
0
  return Error::Ok;
89
0
}
90
91
void SampleAuxInfoHelper::add_nonpresent_sample()
92
0
{
93
0
  m_saiz->add_nonpresent_sample();
94
0
}
95
96
97
void SampleAuxInfoHelper::write_interleaved(const std::shared_ptr<HeifFile>& file)
98
0
{
99
0
  if (m_interleaved && !m_data.empty()) {
100
    // TODO: I think this does not work because the image data does not know that there is SAI in-between
101
0
    uint64_t pos = file->append_mdat_data(m_data);
102
0
    m_saio->add_chunk_offset(pos);
103
104
0
    m_data.clear();
105
0
  }
106
0
}
107
108
void SampleAuxInfoHelper::write_all(const std::shared_ptr<Box>& parent, const std::shared_ptr<HeifFile>& file)
109
0
{
110
0
  parent->append_child_box(m_saiz);
111
0
  parent->append_child_box(m_saio);
112
113
0
  if (!m_data.empty()) {
114
0
    uint64_t pos = file->append_mdat_data(m_data);
115
0
    m_saio->add_chunk_offset(pos);
116
0
  }
117
0
}
118
119
120
SampleAuxInfoReader::SampleAuxInfoReader(const std::shared_ptr<Box_saiz>& saiz,
121
                                         const std::shared_ptr<Box_saio>& saio,
122
                                         const std::vector<std::shared_ptr<Chunk>>& chunks)
123
0
{
124
0
  m_saiz = saiz;
125
0
  m_saio = saio;
126
127
0
  bool oneChunk = (saio->get_num_chunks() == 1);
128
129
0
  uint32_t current_chunk = 0;
130
0
  uint64_t offset = saio->get_chunk_offset(0);
131
0
  uint32_t nSamples = saiz->get_num_samples();
132
133
0
  m_contiguous_and_constant_size = (oneChunk && m_saiz->have_samples_constant_size());
134
135
0
  if (m_contiguous_and_constant_size) {
136
0
    m_singleChunk_offset = offset;
137
0
  }
138
0
  else {
139
0
    m_sample_offsets.resize(nSamples);
140
141
0
    for (uint32_t i = 0; i < nSamples; i++) {
142
0
      if (!oneChunk && i > chunks[current_chunk]->last_sample_number()) {
143
0
        current_chunk++;
144
0
        if (current_chunk >= chunks.size()) {
145
0
          break;
146
0
        }
147
0
        offset = saio->get_chunk_offset(current_chunk);
148
0
      }
149
150
0
      m_sample_offsets[i] = offset;
151
0
      offset += saiz->get_sample_size(i);
152
0
    }
153
0
  }
154
0
}
155
156
157
heif_sample_aux_info_type SampleAuxInfoReader::get_type() const
158
0
{
159
0
  heif_sample_aux_info_type type;
160
0
  type.type = m_saiz->get_aux_info_type();
161
0
  type.parameter = m_saiz->get_aux_info_type_parameter();
162
0
  return type;
163
0
}
164
165
166
Result<std::vector<uint8_t> > SampleAuxInfoReader::get_sample_info(const HeifFile* file, uint32_t sample_idx)
167
0
{
168
0
  uint64_t offset;
169
0
  uint8_t size;
170
171
0
  if (m_contiguous_and_constant_size) {
172
0
    if (sample_idx >= m_saiz->get_num_samples()) {
173
      // The 'saiz' describes aux info for fewer samples than the track contains;
174
      // samples beyond its range carry none. The variable-size branch below already
175
      // handles this via get_sample_size(); without the same bound here the offset
176
      // runs past the aux-info chunk into an unrelated file region.
177
0
      return {};
178
0
    }
179
0
    size = m_saiz->get_sample_size(0);
180
0
    offset = m_singleChunk_offset + uint64_t{sample_idx} * size;
181
0
  }
182
0
  else {
183
0
    size = m_saiz->get_sample_size(sample_idx);
184
0
    if (size > 0) {
185
0
      if (sample_idx >= m_sample_offsets.size()) {
186
0
        return {};
187
0
      }
188
189
0
      offset = m_sample_offsets[sample_idx];
190
0
    }
191
0
  }
192
193
0
  std::vector<uint8_t> data;
194
195
0
  if (size > 0) {
196
0
    Error err = file->append_data_from_file_range(data, offset, size);
197
0
    if (err) {
198
0
      return err;
199
0
    }
200
0
  }
201
202
0
  return data;
203
0
}
204
205
206
std::shared_ptr<HeifFile> Track::get_file() const
207
0
{
208
0
  return m_heif_context->get_heif_file();
209
0
}
210
211
212
Track::Track(HeifContext* ctx)
213
2
{
214
2
  m_heif_context = ctx;
215
2
}
216
217
218
Error Track::load(const std::shared_ptr<Box_trak>& trak_box)
219
2
{
220
2
  m_trak = trak_box;
221
222
2
  auto tkhd = trak_box->get_child_box<Box_tkhd>();
223
2
  if (!tkhd) {
224
2
    return {
225
2
      heif_error_Invalid_input,
226
2
      heif_suberror_Unspecified,
227
2
      "Track has no 'tkhd' box."
228
2
    };
229
2
  }
230
231
0
  m_tkhd = tkhd;
232
233
0
  m_id = tkhd->get_track_id();
234
235
0
  auto edts = trak_box->get_child_box<Box_edts>();
236
0
  if (edts) {
237
0
    m_elst = edts->get_child_box<Box_elst>();
238
0
  }
239
240
0
  auto mdia = trak_box->get_child_box<Box_mdia>();
241
0
  if (!mdia) {
242
0
    return {
243
0
      heif_error_Invalid_input,
244
0
      heif_suberror_Unspecified,
245
0
      "Track has no 'mdia' box."
246
0
    };
247
0
  }
248
249
0
  m_tref = trak_box->get_child_box<Box_tref>();
250
251
0
  auto hdlr = mdia->get_child_box<Box_hdlr>();
252
0
  if (!hdlr) {
253
0
    return {
254
0
      heif_error_Invalid_input,
255
0
      heif_suberror_Unspecified,
256
0
      "Track has no 'hdlr' box."
257
0
    };
258
0
  }
259
260
0
  m_handler_type = hdlr->get_handler_type();
261
262
0
  m_minf = mdia->get_child_box<Box_minf>();
263
0
  if (!m_minf) {
264
0
    return {
265
0
      heif_error_Invalid_input,
266
0
      heif_suberror_Unspecified,
267
0
      "Track has no 'minf' box."
268
0
    };
269
0
  }
270
271
0
  m_mdhd = mdia->get_child_box<Box_mdhd>();
272
0
  if (!m_mdhd) {
273
0
    return {
274
0
      heif_error_Invalid_input,
275
0
      heif_suberror_Unspecified,
276
0
      "Track has no 'mdhd' box."
277
0
    };
278
0
  }
279
280
0
  auto stbl = m_minf->get_child_box<Box_stbl>();
281
0
  if (!stbl) {
282
0
    return {
283
0
      heif_error_Invalid_input,
284
0
      heif_suberror_Unspecified,
285
0
      "Track has no 'stbl' box."
286
0
    };
287
0
  }
288
289
0
  m_stsd = stbl->get_child_box<Box_stsd>();
290
0
  if (!m_stsd) {
291
0
    return {
292
0
      heif_error_Invalid_input,
293
0
      heif_suberror_Unspecified,
294
0
      "Track has no 'stsd' box."
295
0
    };
296
0
  }
297
298
0
  m_stsc = stbl->get_child_box<Box_stsc>();
299
0
  if (!m_stsc) {
300
0
    return {
301
0
      heif_error_Invalid_input,
302
0
      heif_suberror_Unspecified,
303
0
      "Track has no 'stsc' box."
304
0
    };
305
0
  }
306
307
0
  m_stco = stbl->get_child_box<Box_stco>();
308
0
  if (!m_stco) {
309
0
    return {
310
0
      heif_error_Invalid_input,
311
0
      heif_suberror_Unspecified,
312
0
      "Track has no 'stco' box."
313
0
    };
314
0
  }
315
316
0
  m_stsz = stbl->get_child_box<Box_stsz>();
317
0
  if (!m_stsz) {
318
0
    return {
319
0
      heif_error_Invalid_input,
320
0
      heif_suberror_Unspecified,
321
0
      "Track has no 'stsz' box."
322
0
    };
323
0
  }
324
325
  // Enforce the sequence-frame limit before allocating any per-chunk state below.
326
  // Box_stsz::parse already applies this when parsing from a file, but check again
327
  // here so the invariant holds even if m_stsz was built another way.
328
0
  const auto* limits = m_heif_context->get_security_limits();
329
0
  if (limits->max_sequence_frames > 0 &&
330
0
      m_stsz->num_samples() > limits->max_sequence_frames) {
331
0
    return {
332
0
      heif_error_Memory_allocation_error,
333
0
      heif_suberror_Security_limit_exceeded,
334
0
      "Security limit for maximum number of sequence frames exceeded"
335
0
    };
336
0
  }
337
338
0
  m_stts = stbl->get_child_box<Box_stts>();
339
0
  if (!m_stts) {
340
0
    return {
341
0
      heif_error_Invalid_input,
342
0
      heif_suberror_Unspecified,
343
0
      "Track has no 'stts' box."
344
0
    };
345
0
  }
346
347
0
  m_ctts = stbl->get_child_box<Box_ctts>();
348
349
  // --- check that number of samples in various boxes are consistent
350
351
0
  if (m_stts->get_number_of_samples() != m_stsz->num_samples()) {
352
0
    return {
353
0
      heif_error_Invalid_input,
354
0
      heif_suberror_Unspecified,
355
0
      "Number of samples in 'stts' and 'stsz' is inconsistent."
356
0
    };
357
0
  }
358
359
0
  if (m_ctts && m_ctts->get_number_of_samples() != m_stsz->num_samples()) {
360
0
    return {
361
0
      heif_error_Invalid_input,
362
0
      heif_suberror_Unspecified,
363
0
      "Number of samples in 'ctts' and 'stsz' is inconsistent."
364
0
    };
365
0
  }
366
367
0
  const std::vector<uint32_t>& chunk_offsets = m_stco->get_offsets();
368
0
  assert(chunk_offsets.size() <= (size_t) std::numeric_limits<uint32_t>::max()); // There cannot be more than uint32_t chunks.
369
370
  // Account the per-chunk sample-range tables (Chunk::m_sample_ranges) against
371
  // max_total_memory before building any chunk. Their combined size across all
372
  // chunks is num_samples * sizeof(SampleFileRange); a small track can declare
373
  // millions of samples in one chunk, so without this the tables are untracked
374
  // and multiple tracks can exhaust memory undetected (GHSA-xw34-mjcp-jqh8, V2/V3).
375
0
  if (auto err = m_chunk_sample_ranges_memory.alloc(m_stsz->num_samples(),
376
0
                                                    Chunk::sample_range_entry_size(),
377
0
                                                    limits, "the sequence chunk sample-range tables")) {
378
0
    return err;
379
0
  }
380
381
0
  uint32_t current_sample_idx = 0;
382
0
  int32_t previous_sample_description_index = -1;
383
384
0
  for (size_t chunk_idx = 0; chunk_idx < chunk_offsets.size(); chunk_idx++) {
385
0
    auto* s2c = m_stsc->get_chunk(static_cast<uint32_t>(chunk_idx + 1));
386
0
    if (!s2c) {
387
0
      return {
388
0
        heif_error_Invalid_input,
389
0
        heif_suberror_Unspecified,
390
0
        "'stco' box references a non-existing chunk."
391
0
      };
392
0
    }
393
394
0
    Box_stsc::SampleToChunk sampleToChunk = *s2c;
395
396
0
    auto sample_description = m_stsd->get_sample_entry(sampleToChunk.sample_description_index - 1);
397
0
    if (!sample_description) {
398
0
      return {
399
0
        heif_error_Invalid_input,
400
0
        heif_suberror_Unspecified,
401
0
        "Track references a non-existing sample description."
402
0
      };
403
0
    }
404
405
0
    if (auto auxi = sample_description->get_child_box<Box_auxi>()) {
406
0
      m_auxiliary_info_type = auxi->get_aux_track_type_urn();
407
0
    }
408
409
0
    if (m_first_taic == nullptr) {
410
0
      auto taic = sample_description->get_child_box<Box_taic>();
411
0
      if (taic) {
412
0
        m_first_taic = taic;
413
0
      }
414
0
    }
415
416
0
    if (static_cast<uint64_t>(current_sample_idx) + sampleToChunk.samples_per_chunk > m_stsz->num_samples()) {
417
0
      return {
418
0
        heif_error_Invalid_input,
419
0
        heif_suberror_Unspecified,
420
0
        "Number of samples in 'stsc' box exceeds sample sizes in 'stsz' box."
421
0
      };
422
0
    }
423
424
0
    auto chunk = Chunk::create(m_heif_context, m_id,
425
0
                               current_sample_idx, sampleToChunk.samples_per_chunk,
426
0
                               m_stco->get_offsets()[chunk_idx],
427
0
                               m_stsz);
428
429
0
    if (!chunk) {
430
0
      return {
431
0
        heif_error_Invalid_input,
432
0
        heif_suberror_Unspecified,
433
0
        "Chunk file offset overflows 64-bit range."
434
0
      };
435
0
    }
436
437
0
    chunk->set_sample_description_index(sampleToChunk.sample_description_index);
438
439
0
    if (auto visualSampleDescription = std::dynamic_pointer_cast<const Box_VisualSampleEntry>(sample_description)) {
440
0
      if (chunk_idx > 0 && (int32_t) sampleToChunk.sample_description_index == previous_sample_description_index) {
441
        // reuse decoder from previous chunk if it uses the sample sample_description_index
442
0
        chunk->set_decoder(m_chunks[chunk_idx - 1]->get_decoder());
443
0
      }
444
0
      else {
445
        // use a new decoder
446
0
        auto decoder = Decoder::alloc_for_sequence_sample_description_box(visualSampleDescription);
447
0
        if (!decoder) {
448
0
          return {
449
0
            heif_error_Invalid_input,
450
0
            heif_suberror_Unspecified,
451
0
            "Sample description has unsupported codec or is missing the codec configuration box."
452
0
          };
453
0
        }
454
0
        chunk->set_decoder(decoder);
455
0
      }
456
0
    }
457
458
0
    m_chunks.push_back(chunk);
459
460
0
    current_sample_idx += sampleToChunk.samples_per_chunk;
461
0
    previous_sample_description_index = sampleToChunk.sample_description_index;
462
0
  }
463
464
0
  if (current_sample_idx != m_stsz->num_samples()) {
465
0
    return {
466
0
      heif_error_Invalid_input,
467
0
      heif_suberror_Unspecified,
468
0
      "Number of samples covered by 'stsc' does not match 'stsz'/'stts'."
469
0
    };
470
0
  }
471
472
  // --- read sample auxiliary information boxes
473
474
0
  std::vector<std::shared_ptr<Box_saiz> > saiz_boxes = stbl->get_child_boxes<Box_saiz>();
475
0
  std::vector<std::shared_ptr<Box_saio> > saio_boxes = stbl->get_child_boxes<Box_saio>();
476
477
0
  if (saio_boxes.size() != saiz_boxes.size()) {
478
0
    return Error{
479
0
      heif_error_Invalid_input,
480
0
      heif_suberror_Unspecified,
481
0
      "Boxes 'saiz' and `saio` must come in pairs."
482
0
    };
483
0
  }
484
485
0
  for (const auto& saiz : saiz_boxes) {
486
0
    uint32_t aux_info_type = saiz->get_aux_info_type();
487
0
    uint32_t aux_info_type_parameter = saiz->get_aux_info_type_parameter();
488
489
    // find the corresponding saio box
490
491
0
    std::shared_ptr<Box_saio> saio;
492
0
    for (const auto& candidate : saio_boxes) {
493
0
      if (candidate->get_aux_info_type() == aux_info_type &&
494
0
          candidate->get_aux_info_type_parameter() == aux_info_type_parameter) {
495
0
        saio = candidate;
496
0
        break;
497
0
      }
498
0
    }
499
500
0
    if (saio) {
501
0
      if (saio->get_num_chunks() != 1 &&
502
0
          saio->get_num_chunks() != m_stco->get_number_of_chunks()) {
503
0
        return Error{
504
0
          heif_error_Invalid_input,
505
0
          heif_suberror_Unspecified,
506
0
          "Invalid number of chunks in 'saio' box."
507
0
        };
508
0
      }
509
510
0
      if (saio->get_num_chunks() != 1 && m_chunks.empty() && saiz->get_num_samples() > 0) {
511
0
        return Error{
512
0
          heif_error_Invalid_input,
513
0
          heif_suberror_Unspecified,
514
0
          "'saiz' box references samples but no chunks exist."
515
0
        };
516
0
      }
517
518
0
      if (saiz->get_num_samples() > m_stsz->num_samples()) {
519
0
        return Error{
520
0
          heif_error_Invalid_input,
521
0
          heif_suberror_Unspecified,
522
0
          "Number of samples in 'saiz' box exceeds actual number of samples."
523
0
        };
524
0
      }
525
526
0
      if (aux_info_type == fourcc("suid")) {
527
0
        m_aux_reader_content_ids = std::make_unique<SampleAuxInfoReader>(saiz, saio, m_chunks);
528
0
      }
529
530
0
      if (aux_info_type == fourcc("stai")) {
531
0
        m_aux_reader_tai_timestamps = std::make_unique<SampleAuxInfoReader>(saiz, saio, m_chunks);
532
0
      }
533
0
    }
534
0
    else {
535
0
      return Error{
536
0
        heif_error_Invalid_input,
537
0
        heif_suberror_Unspecified,
538
0
        "'saiz' box without matching 'saio' box."
539
0
      };
540
0
    }
541
0
  }
542
543
  // --- read track properties
544
545
0
  if (auto meta = trak_box->get_child_box<Box_meta>()) {
546
0
    auto iloc = meta->get_child_box<Box_iloc>();
547
0
    auto idat = meta->get_child_box<Box_idat>();
548
549
0
    auto iinf = meta->get_child_box<Box_iinf>();
550
0
    if (iinf) {
551
0
      auto infe_boxes = iinf->get_child_boxes<Box_infe>();
552
0
      for (const auto& box : infe_boxes) {
553
0
        if (box->get_item_type_4cc() == fourcc("uri ") &&
554
0
            box->get_item_uri_type() == "urn:uuid:15beb8e4-944d-5fc6-a3dd-cb5a7e655c73") {
555
0
          heif_item_id id = box->get_item_ID();
556
557
0
          if (!iloc) {
558
0
            return {
559
0
              heif_error_Invalid_input,
560
0
              heif_suberror_Unspecified,
561
0
              "Track meta references item content-id but file has no 'iloc' box."
562
0
            };
563
0
          }
564
565
0
          std::vector<uint8_t> data;
566
0
          Error err = iloc->read_data(id, m_heif_context->get_heif_file()->get_reader(), idat, &data, m_heif_context->get_security_limits());
567
0
          if (err) {
568
0
            return err;
569
0
          }
570
571
0
          Result<std::string> contentIdResult = vector_to_string(data);
572
0
          if (!contentIdResult) {
573
0
            return contentIdResult.error();
574
0
          }
575
576
0
          m_track_info.gimi_track_content_id = *contentIdResult;
577
0
        }
578
0
      }
579
0
    }
580
0
  }
581
582
583
  // --- initialize track tables
584
585
0
  Error err = init_sample_timing_table();
586
0
  if (err) {
587
0
    return err;
588
0
  }
589
590
0
  return {};
591
0
}
592
593
594
Track::Track(HeifContext* ctx, uint32_t track_id, const TrackOptions* options, uint32_t handler_type)
595
0
{
596
0
  m_heif_context = ctx;
597
598
0
  m_moov = ctx->get_heif_file()->get_moov_box();
599
0
  assert(m_moov);
600
601
  // --- find next free track ID
602
603
0
  if (track_id == 0) {
604
0
    auto idResult = ctx->get_id_creator().get_new_id(IDCreator::Namespace::track);
605
    // Track constructor cannot return errors; assert on overflow (extremely unlikely).
606
0
    assert(idResult);
607
0
    track_id = *idResult;
608
609
0
    auto mvhd = m_moov->get_child_box<Box_mvhd>();
610
0
    mvhd->set_next_track_id(track_id + 1);
611
612
0
    m_id = track_id;
613
0
  }
614
615
0
  m_trak = std::make_shared<Box_trak>();
616
0
  m_moov->append_child_box(m_trak);
617
618
0
  m_tkhd = std::make_shared<Box_tkhd>();
619
0
  m_trak->append_child_box(m_tkhd);
620
0
  m_tkhd->set_track_id(track_id);
621
622
0
  auto mdia = std::make_shared<Box_mdia>();
623
0
  m_trak->append_child_box(mdia);
624
625
0
  m_mdhd = std::make_shared<Box_mdhd>();
626
0
  m_mdhd->set_timescale(options ? options->track_timescale : 90000);
627
0
  mdia->append_child_box(m_mdhd);
628
629
0
  m_hdlr = std::make_shared<Box_hdlr>();
630
0
  mdia->append_child_box(m_hdlr);
631
0
  m_hdlr->set_handler_type(handler_type);
632
633
0
  m_minf = std::make_shared<Box_minf>();
634
0
  mdia->append_child_box(m_minf);
635
636
  // add (unused) 'dinf'
637
638
0
  auto dinf = std::make_shared<Box_dinf>();
639
0
  auto dref = std::make_shared<Box_dref>();
640
0
  auto url = std::make_shared<Box_url>();
641
0
  m_minf->append_child_box(dinf);
642
0
  dinf->append_child_box(dref);
643
0
  dref->append_child_box(url);
644
645
  // vmhd is added in Track_Visual
646
647
0
  m_stbl = std::make_shared<Box_stbl>();
648
0
  m_minf->append_child_box(m_stbl);
649
650
0
  m_stsd = std::make_shared<Box_stsd>();
651
0
  m_stbl->append_child_box(m_stsd);
652
653
0
  m_stts = std::make_shared<Box_stts>();
654
0
  m_stbl->append_child_box(m_stts);
655
656
0
  m_ctts = std::make_shared<Box_ctts>();
657
  // The ctts box will be added in finalize_track(), but only there is frame-reordering.
658
659
0
  m_stsc = std::make_shared<Box_stsc>();
660
0
  m_stbl->append_child_box(m_stsc);
661
662
0
  m_stsz = std::make_shared<Box_stsz>();
663
0
  m_stbl->append_child_box(m_stsz);
664
665
0
  m_stco = std::make_shared<Box_stco>();
666
0
  m_stbl->append_child_box(m_stco);
667
668
0
  m_stss = std::make_shared<Box_stss>();
669
0
  m_stbl->append_child_box(m_stss);
670
671
0
  if (options) {
672
0
    m_track_info = *options;
673
674
0
    if (m_track_info.with_sample_tai_timestamps != heif_sample_aux_info_presence_none) {
675
0
      m_aux_helper_tai_timestamps = std::make_unique<SampleAuxInfoHelper>(m_track_info.write_sample_aux_infos_interleaved);
676
0
      m_aux_helper_tai_timestamps->set_aux_info_type(fourcc("stai"));
677
0
    }
678
679
0
    if (m_track_info.with_sample_content_ids != heif_sample_aux_info_presence_none) {
680
0
      m_aux_helper_content_ids = std::make_unique<SampleAuxInfoHelper>(m_track_info.write_sample_aux_infos_interleaved);
681
0
      m_aux_helper_content_ids->set_aux_info_type(fourcc("suid"));
682
0
    }
683
684
0
    if (!options->gimi_track_content_id.empty()) {
685
0
      auto hdlr_box = std::make_shared<Box_hdlr>();
686
0
      hdlr_box->set_handler_type(fourcc("meta"));
687
688
0
      auto uuid_box = std::make_shared<Box_infe>();
689
0
      uuid_box->set_item_type_4cc(fourcc("uri "));
690
0
      uuid_box->set_item_uri_type("urn:uuid:15beb8e4-944d-5fc6-a3dd-cb5a7e655c73");
691
0
      uuid_box->set_item_ID(1);
692
693
0
      auto iinf_box = std::make_shared<Box_iinf>();
694
0
      iinf_box->append_child_box(uuid_box);
695
696
0
      std::vector<uint8_t> track_uuid_vector;
697
0
      track_uuid_vector.insert(track_uuid_vector.begin(),
698
0
                               options->gimi_track_content_id.c_str(),
699
0
                               options->gimi_track_content_id.c_str() + options->gimi_track_content_id.length() + 1);
700
701
0
      auto iloc_box = std::make_shared<Box_iloc>();
702
0
      iloc_box->append_data(1, track_uuid_vector, 1);
703
704
0
      auto meta_box = std::make_shared<Box_meta>();
705
0
      meta_box->append_child_box(hdlr_box);
706
0
      meta_box->append_child_box(iinf_box);
707
0
      meta_box->append_child_box(iloc_box);
708
709
0
      m_trak->append_child_box(meta_box);
710
0
    }
711
0
  }
712
0
}
713
714
715
Result<std::shared_ptr<Track> > Track::alloc_track(HeifContext* ctx, const std::shared_ptr<Box_trak>& trak)
716
30
{
717
30
  auto mdia = trak->get_child_box<Box_mdia>();
718
30
  if (!mdia) {
719
12
    return Error{
720
12
      heif_error_Invalid_input,
721
12
      heif_suberror_Unspecified,
722
12
      "Track has no 'mdia' box."
723
12
    };
724
12
  }
725
726
18
  auto hdlr = mdia->get_child_box<Box_hdlr>();
727
18
  if (!hdlr) {
728
7
    return Error{
729
7
      heif_error_Invalid_input,
730
7
      heif_suberror_Unspecified,
731
7
      "Track has no 'hdlr' box."
732
7
    };
733
7
  }
734
735
11
  std::shared_ptr<Track> track;
736
737
11
  switch (hdlr->get_handler_type()) {
738
2
    case fourcc("pict"):
739
2
    case fourcc("vide"):
740
2
    case fourcc("auxv"):
741
2
      track = std::make_shared<Track_Visual>(ctx);
742
2
      break;
743
0
    case fourcc("meta"):
744
0
      track = std::make_shared<Track_Metadata>(ctx);
745
0
      break;
746
9
    default: {
747
9
      std::stringstream sstr;
748
9
      sstr << "Track with unsupported handler type '" << fourcc_to_string(hdlr->get_handler_type()) << "'.";
749
9
      return Error{
750
9
        heif_error_Unsupported_feature,
751
9
        heif_suberror_Unsupported_track_type,
752
9
        sstr.str()
753
9
      };
754
2
    }
755
11
  }
756
757
11
  assert(track);
758
2
  Error loadError = track->load(trak);
759
2
  if (loadError) {
760
2
    return loadError;
761
2
  }
762
763
0
  return {track};
764
2
}
765
766
767
bool Track::is_visual_track() const
768
0
{
769
0
  return (m_handler_type == fourcc("pict") ||
770
0
          m_handler_type == fourcc("vide"));
771
0
}
772
773
774
static const char* cAuxType_alpha_miaf = "urn:mpeg:mpegB:cicp:systems:auxiliary:alpha";
775
static const char* cAuxType_alpha_hevc = "urn:mpeg:hevc:2015:auxid:1";
776
static const char* cAuxType_alpha_avc = "urn:mpeg:avc:2015:auxid:1";
777
778
heif_auxiliary_track_info_type Track::get_auxiliary_info_type() const
779
0
{
780
0
  if (m_auxiliary_info_type == cAuxType_alpha_miaf ||
781
0
      m_auxiliary_info_type == cAuxType_alpha_hevc ||
782
0
      m_auxiliary_info_type == cAuxType_alpha_avc) {
783
0
    return heif_auxiliary_track_info_type_alpha;
784
0
  }
785
0
  else {
786
0
    return heif_auxiliary_track_info_type_unknown;
787
0
  }
788
0
}
789
790
const char* get_track_auxiliary_info_type(heif_compression_format format)
791
0
{
792
0
  switch (format) {
793
0
    case heif_compression_HEVC:
794
0
      return cAuxType_alpha_hevc;
795
0
    case heif_compression_AVC:
796
0
      return cAuxType_alpha_avc;
797
0
    case heif_compression_AV1:
798
0
      return cAuxType_alpha_miaf;
799
0
    default:
800
0
      return cAuxType_alpha_miaf; // TODO: is this correct for all remaining compression types ?
801
0
  }
802
0
}
803
804
// TODO: is this correct or should we set the aux_info_type depending on the compression format?
805
void Track::set_auxiliary_info_type(heif_auxiliary_track_info_type type)
806
0
{
807
0
  switch (type) {
808
0
    case heif_auxiliary_track_info_type_alpha:
809
0
      m_auxiliary_info_type = cAuxType_alpha_miaf;
810
0
      break;
811
0
    default:
812
0
      m_auxiliary_info_type.clear();
813
0
      break;
814
0
  }
815
0
}
816
817
818
uint32_t Track::get_first_cluster_sample_entry_type() const
819
0
{
820
0
  if (m_stsd->get_num_sample_entries() == 0) {
821
0
    return 0; // TODO: error ? Or can we assume at this point that there is at least one sample entry?
822
0
  }
823
824
0
  return m_stsd->get_sample_entry(0)->get_short_type();
825
0
}
826
827
828
Result<std::string> Track::get_first_cluster_urim_uri() const
829
0
{
830
0
  if (m_stsd->get_num_sample_entries() == 0) {
831
0
    return Error{
832
0
      heif_error_Invalid_input,
833
0
      heif_suberror_Unspecified,
834
0
      "This track has no sample entries."
835
0
    };
836
0
  }
837
838
0
  std::shared_ptr<const Box> sampleEntry = m_stsd->get_sample_entry(0);
839
0
  auto urim = std::dynamic_pointer_cast<const Box_URIMetaSampleEntry>(sampleEntry);
840
0
  if (!urim) {
841
0
    return Error{
842
0
      heif_error_Usage_error,
843
0
      heif_suberror_Unspecified,
844
0
      "This cluster is no 'urim' sample entry."
845
0
    };
846
0
  }
847
848
0
  std::shared_ptr<const Box_uri> uri = urim->get_child_box<const Box_uri>();
849
0
  if (!uri) {
850
0
    return Error{
851
0
      heif_error_Invalid_input,
852
0
      heif_suberror_Unspecified,
853
0
      "The 'urim' box has no 'uri' child box."
854
0
    };
855
0
  }
856
857
0
  return uri->get_uri();
858
0
}
859
860
861
bool Track::end_of_sequence_reached() const
862
0
{
863
  //return (m_next_sample_to_be_processed > m_chunks.back()->last_sample_number());
864
0
  return m_next_sample_to_be_output >= m_num_output_samples;
865
0
}
866
867
868
Error Track::finalize_track()
869
0
{
870
  // --- write active chunk data
871
872
0
  size_t data_start = m_heif_context->get_heif_file()->append_mdat_data(m_chunk_data);
873
0
  m_chunk_data.clear();
874
875
  // first sample in chunk? -> write chunk offset
876
877
0
  if (true) {
878
    // m_stsc->last_chunk_empty()) {
879
    // TODO: we will have to call this at the end of a chunk to dump the current SAI queue
880
881
    // if auxiliary data is interleaved, write it between the chunks
882
0
    if (m_aux_helper_tai_timestamps) m_aux_helper_tai_timestamps->write_interleaved(get_file());
883
0
    if (m_aux_helper_content_ids) m_aux_helper_content_ids->write_interleaved(get_file());
884
885
    // TODO
886
0
    assert(data_start < 0xFF000000); // add some headroom for header data
887
0
    m_stco->add_chunk_offset(static_cast<uint32_t>(data_start));
888
0
  }
889
890
891
  // --- write rest of data
892
893
0
  if (m_aux_helper_tai_timestamps) m_aux_helper_tai_timestamps->write_all(m_stbl, get_file());
894
0
  if (m_aux_helper_content_ids) m_aux_helper_content_ids->write_all(m_stbl, get_file());
895
896
0
  uint64_t duration = m_stts->get_total_duration(true);
897
0
  m_mdhd->set_duration(duration);
898
899
0
  m_stss->set_total_number_of_samples(m_stsz->num_samples());
900
901
  // only add ctts box if we use frame-reordering
902
0
  if (!m_ctts->is_constant_offset()) {
903
0
    m_stbl->append_child_box(m_ctts);
904
0
  }
905
906
0
  return {};
907
0
}
908
909
910
uint64_t Track::get_duration_in_media_units() const
911
0
{
912
0
  return m_mdhd->get_duration();
913
0
}
914
915
916
uint32_t Track::get_timescale() const
917
0
{
918
0
  return m_mdhd->get_timescale();
919
0
}
920
921
922
void Track::set_track_duration_in_movie_units(uint64_t total_duration, uint64_t segment_duration)
923
0
{
924
0
  m_tkhd->set_duration(total_duration);
925
926
0
  if (m_elst) {
927
0
    Box_elst::Entry entry;
928
0
    entry.segment_duration = segment_duration;
929
930
0
    m_elst->add_entry(entry);
931
0
  }
932
0
}
933
934
935
void Track::enable_edit_list_repeat_mode(bool enable)
936
0
{
937
0
  if (!m_elst) {
938
0
    if (!enable) {
939
0
      return;
940
0
    }
941
942
0
    auto edts = std::make_shared<Box_edts>();
943
0
    m_trak->append_child_box(edts);
944
945
0
    m_elst = std::make_shared<Box_elst>();
946
0
    edts->append_child_box(m_elst);
947
948
0
    m_elst->enable_repeat_mode(enable);
949
0
  }
950
0
}
951
952
953
void Track::add_chunk(heif_compression_format format)
954
0
{
955
0
  auto chunk = std::make_shared<Chunk>(m_heif_context, m_id, format);
956
0
  m_chunks.push_back(chunk);
957
958
0
  int chunkIdx = (uint32_t) m_chunks.size();
959
0
  m_stsc->add_chunk(chunkIdx);
960
0
}
961
962
void Track::set_sample_description_box(const std::shared_ptr<Box>& sample_description_box)
963
0
{
964
  // --- add 'taic' when we store timestamps as sample auxiliary information
965
966
0
  if (m_track_info.with_sample_tai_timestamps != heif_sample_aux_info_presence_none) {
967
0
    auto taic = std::make_shared<Box_taic>();
968
0
    taic->set_from_tai_clock_info(m_track_info.tai_clock_info);
969
0
    sample_description_box->append_child_box(taic);
970
0
  }
971
972
0
  m_stsd->add_sample_entry(sample_description_box);
973
0
}
974
975
976
Error Track::write_sample_data(const std::vector<uint8_t>& raw_data, uint32_t sample_duration,
977
                               int32_t composition_time_offset,
978
                               bool is_sync_sample,
979
                               const heif_tai_timestamp_packet* tai, const std::optional<std::string>& gimi_contentID)
980
0
{
981
0
  m_chunk_data.insert(m_chunk_data.end(), raw_data.begin(), raw_data.end());
982
983
0
  m_stsc->increase_samples_in_chunk(1);
984
985
0
  m_stsz->append_sample_size((uint32_t) raw_data.size());
986
987
0
  if (is_sync_sample) {
988
0
    m_stss->add_sync_sample(m_next_sample_to_be_output + 1);
989
0
  }
990
991
0
  if (sample_duration == 0) {
992
0
    return {
993
0
      heif_error_Usage_error,
994
0
      heif_suberror_Unspecified,
995
0
      "Sample duration may not be 0"
996
0
    };
997
0
  }
998
999
0
  m_stts->append_sample_duration(sample_duration);
1000
0
  m_ctts->append_sample_offset(composition_time_offset);
1001
1002
1003
  // --- sample timestamp
1004
1005
0
  if (m_track_info.with_sample_tai_timestamps != heif_sample_aux_info_presence_none) {
1006
0
    if (tai) {
1007
0
      std::vector<uint8_t> tai_data = Box_itai::encode_tai_to_bitstream(tai);
1008
0
      auto err = m_aux_helper_tai_timestamps->add_sample_info(tai_data);
1009
0
      if (err) {
1010
0
        return err;
1011
0
      }
1012
0
    }
1013
0
    else if (m_track_info.with_sample_tai_timestamps == heif_sample_aux_info_presence_optional) {
1014
0
      m_aux_helper_tai_timestamps->add_nonpresent_sample();
1015
0
    }
1016
0
    else {
1017
0
      return {
1018
0
        heif_error_Encoding_error,
1019
0
        heif_suberror_Unspecified,
1020
0
        "Mandatory TAI timestamp missing"
1021
0
      };
1022
0
    }
1023
0
  }
1024
1025
  // --- sample content id
1026
1027
0
  if (m_track_info.with_sample_content_ids != heif_sample_aux_info_presence_none) {
1028
0
    if (gimi_contentID) {
1029
0
      const auto& id = *gimi_contentID;
1030
0
      const char* id_str = id.c_str();
1031
0
      std::vector<uint8_t> id_vector;
1032
0
      id_vector.insert(id_vector.begin(), id_str, id_str + id.length() + 1);
1033
0
      auto err = m_aux_helper_content_ids->add_sample_info(id_vector);
1034
0
      if (err) {
1035
0
        return err;
1036
0
      }
1037
0
    }
1038
0
    else if (m_track_info.with_sample_content_ids == heif_sample_aux_info_presence_optional) {
1039
0
      m_aux_helper_content_ids->add_nonpresent_sample();
1040
0
    }
1041
0
    else {
1042
0
      return {
1043
0
        heif_error_Encoding_error,
1044
0
        heif_suberror_Unspecified,
1045
0
        "Mandatory ContentID missing"
1046
0
      };
1047
0
    }
1048
0
  }
1049
1050
0
  m_next_sample_to_be_output++;
1051
1052
0
  return Error::Ok;
1053
0
}
1054
1055
1056
void Track::add_reference_to_track(uint32_t referenceType, uint32_t to_track_id)
1057
0
{
1058
0
  if (!m_tref) {
1059
0
    m_tref = std::make_shared<Box_tref>();
1060
0
    m_trak->append_child_box(m_tref);
1061
0
  }
1062
1063
0
  m_tref->add_references(to_track_id, referenceType);
1064
0
}
1065
1066
1067
Error Track::init_sample_timing_table()
1068
0
{
1069
0
  m_num_samples = m_stsz->num_samples();
1070
1071
0
  const auto* limits = m_heif_context->get_security_limits();
1072
1073
  // Account the presentation timeline against max_total_memory before allocating
1074
  // it. m_num_samples is bounded by max_sequence_frames, but a single small track
1075
  // can still declare millions of samples, so this ~48-bytes/sample vector must be
1076
  // tracked to bound multi-track accumulation (GHSA-xw34-mjcp-jqh8, V2/V3). The
1077
  // media timeline built below is moved into m_presentation_timeline (not copied),
1078
  // so only one such buffer ever exists and this single reservation covers it.
1079
0
  if (auto err = m_presentation_timeline_memory.alloc(m_num_samples, sizeof(SampleTiming),
1080
0
                                                      limits, "the sequence presentation timeline")) {
1081
0
    return err;
1082
0
  }
1083
1084
  // --- build media timeline
1085
1086
0
  std::vector<SampleTiming> media_timeline;
1087
0
  media_timeline.reserve(m_num_samples);
1088
1089
0
  uint64_t current_decoding_time = 0;
1090
0
  uint32_t current_chunk = 0;
1091
0
  uint32_t current_sample_in_chunk_idx = 0;
1092
1093
0
  for (uint32_t i = 0; i < m_num_samples; i++) {
1094
0
    SampleTiming timing;
1095
0
    timing.sampleIdx = i;
1096
0
    timing.sampleInChunkIdx = current_sample_in_chunk_idx;
1097
0
    timing.media_decoding_time = current_decoding_time;
1098
    // O(log entries) per lookup (Box_stts uses a prefix-sum binary search), so
1099
    // building the whole table is O(samples * log entries) rather than the former
1100
    // O(samples * entries) file-open CPU-DoS (GHSA-xw34-mjcp-jqh8, variant V1).
1101
0
    timing.sample_duration_media_time = m_stts->get_sample_duration(i);
1102
0
    current_decoding_time += timing.sample_duration_media_time;
1103
0
    current_sample_in_chunk_idx++;
1104
1105
0
    while (current_chunk < m_chunks.size() &&
1106
0
           i > m_chunks[current_chunk]->last_sample_number()) {
1107
0
      current_chunk++;
1108
0
      current_sample_in_chunk_idx = 0;
1109
0
    }
1110
1111
0
    if (current_chunk >= m_chunks.size()) {
1112
0
      return {
1113
0
        heif_error_Invalid_input,
1114
0
        heif_suberror_Unspecified,
1115
0
        "Sample not covered by any chunk."
1116
0
      };
1117
0
    }
1118
1119
0
    timing.chunkIdx = current_chunk;
1120
1121
0
    media_timeline.push_back(timing);
1122
0
  }
1123
1124
  // --- build presentation timeline from editlist
1125
1126
0
  bool fallback = false;
1127
1128
0
  if (m_heif_context->get_sequence_timescale() != get_timescale()) {
1129
0
    fallback = true;
1130
0
  }
1131
0
  else if (m_elst &&
1132
0
           m_elst->num_entries() == 1 &&
1133
0
           m_elst->get_entry(0).media_time == 0 &&
1134
0
           m_elst->get_entry(0).segment_duration == m_mdhd->get_duration() &&
1135
0
           m_elst->is_repeat_mode()) {
1136
1137
0
    uint64_t duration_media_units = get_duration_in_media_units();
1138
0
    if (duration_media_units == 0) {
1139
0
      return {
1140
0
        heif_error_Invalid_input,
1141
0
        heif_suberror_Unspecified,
1142
0
        "Track duration is zero."
1143
0
      };
1144
0
    }
1145
1146
0
    uint64_t multiplier = m_heif_context->get_sequence_duration() / duration_media_units;
1147
1148
    // Logical number of output samples = physical samples x repeat multiplier.
1149
    // Compute this saturating instead of wrapping: with the indefinite-duration
1150
    // sentinel (mvhd.duration = UINT64_MAX) the multiplier is enormous, and a plain
1151
    // multiply could overflow uint64_t and wrap to a small, misleading value.
1152
0
    uint64_t timeline_size = media_timeline.size();
1153
0
    uint64_t total_output_samples;
1154
0
    if (timeline_size != 0 && multiplier > std::numeric_limits<uint64_t>::max() / timeline_size) {
1155
0
      total_output_samples = std::numeric_limits<uint64_t>::max();
1156
0
    }
1157
0
    else {
1158
0
      total_output_samples = multiplier * timeline_size;
1159
0
    }
1160
1161
    // The decode loop (Track_Visual::decode_next_image_sample), the raw-data path
1162
    // (get_next_sample_raw_data) and end_of_sequence_reached() all count emitted
1163
    // samples with a uint32_t (m_next_sample_to_be_output). If m_num_output_samples
1164
    // exceeds UINT32_MAX, that counter can never reach it and decoding never
1165
    // terminates (GHSA-xw34-mjcp-jqh8, variants V4/V5). The physical-sample limit
1166
    // (max_sequence_frames) is also never applied to this repeat-amplified logical
1167
    // count (variant V6). Bound the number of samples the loop will emit by the
1168
    // sequence-frame limit (or UINT32_MAX when the limit is disabled), so a
1169
    // repeat/indefinite edit list cannot inflate a single physical sample into an
1170
    // effectively infinite decode. The reported repetition count below still signals
1171
    // "infinite", so a caller wanting true unbounded playback can loop the media
1172
    // itself via heif_decoding_options::ignore_sequence_editlist.
1173
0
    uint64_t output_sample_cap = (limits->max_sequence_frames > 0)
1174
0
                                 ? limits->max_sequence_frames
1175
0
                                 : std::numeric_limits<uint32_t>::max();
1176
1177
0
    m_num_output_samples = std::min(total_output_samples, output_sample_cap);
1178
1179
0
    if (m_heif_context->is_sequence_duration_indefinite()) {
1180
      // mvhd carries the all-1s sentinel -> editlist repeats forever.
1181
0
      m_num_repetitions = std::numeric_limits<uint32_t>::max();
1182
0
    }
1183
0
    else if (multiplier >= std::numeric_limits<uint32_t>::max()) {
1184
      // Doesn't fit in the API's uint32_t; treat as effectively infinite.
1185
0
      m_num_repetitions = std::numeric_limits<uint32_t>::max();
1186
0
    }
1187
0
    else {
1188
0
      m_num_repetitions = static_cast<uint32_t>(multiplier);
1189
0
    }
1190
0
  }
1191
0
  else {
1192
0
    fallback = true;
1193
0
  }
1194
1195
  // Fallback: just play the media timeline
1196
0
  if (fallback) {
1197
0
    m_num_output_samples = media_timeline.size();
1198
    // No editlist box at all: the media plays exactly once.
1199
    // Editlist box present but its pattern isn't one libheif interprets: report
1200
    // 0 so callers know they should not rely on a repetition count.
1201
0
    m_num_repetitions = m_elst ? 0 : 1;
1202
0
  }
1203
1204
  // Both branches above use media_timeline unchanged as the presentation timeline.
1205
  // Move (do not copy) it in so only one such buffer is ever allocated, matching
1206
  // the single reservation made at the top of this function.
1207
0
  m_presentation_timeline = std::move(media_timeline);
1208
1209
0
  return {};
1210
0
}
1211
1212
1213
Result<heif_raw_sequence_sample*> Track::get_next_sample_raw_data(const heif_decoding_options* options)
1214
0
{
1215
0
  uint64_t num_output_samples = m_num_output_samples;
1216
0
  if (options && options->ignore_sequence_editlist) {
1217
0
    num_output_samples = m_num_samples;
1218
0
  }
1219
1220
0
  if (m_next_sample_to_be_output >= num_output_samples) {
1221
0
    return Error{
1222
0
      heif_error_End_of_sequence,
1223
0
      heif_suberror_Unspecified,
1224
0
      "End of sequence"
1225
0
    };
1226
0
  }
1227
1228
0
  const auto& sampleTiming = m_presentation_timeline[m_next_sample_to_be_output % m_presentation_timeline.size()];
1229
0
  uint32_t sample_idx = sampleTiming.sampleIdx;
1230
0
  uint32_t chunk_idx = sampleTiming.chunkIdx;
1231
1232
0
  const std::shared_ptr<Chunk>& chunk = m_chunks[chunk_idx];
1233
1234
0
  DataExtent extent = chunk->get_data_extent_for_sample(sample_idx);
1235
0
  auto readResult = extent.read_data();
1236
0
  if (!readResult) {
1237
0
    return readResult.error();
1238
0
  }
1239
1240
  // Keep the sample in a unique_ptr until the single success exit below. Several
1241
  // error returns follow (sample auxiliary info driven by file bytes), and the
1242
  // Result<T*> error variant cannot carry the pointer back to the caller, so a raw
1243
  // 'new' here leaked the sample together with its full payload copy on every one
1244
  // of them (GHSA-4rv4-953r-p24q).
1245
0
  auto sample = std::make_unique<heif_raw_sequence_sample>();
1246
1247
  // Move the payload out of the function-local extent instead of copying it. The
1248
  // extent is destroyed when this function returns anyway, and moving halves the
1249
  // peak memory needed per sample.
1250
0
  sample->data = std::move(**readResult);
1251
1252
  // read sample duration
1253
1254
0
  if (m_stts) {
1255
0
    sample->duration = m_stts->get_sample_duration(sample_idx);
1256
0
  }
1257
1258
  // --- read sample auxiliary data
1259
1260
0
  if (m_aux_reader_content_ids) {
1261
0
    auto readResult = m_aux_reader_content_ids->get_sample_info(get_file().get(), sample_idx);
1262
0
    if (!readResult) {
1263
0
      return readResult.error();
1264
0
    }
1265
1266
0
    if (!readResult->empty()) {
1267
0
      Result<std::string> convResult = vector_to_string(*readResult);
1268
0
      if (!convResult) {
1269
0
        return convResult.error();
1270
0
      }
1271
1272
0
      sample->gimi_sample_content_id = *convResult;
1273
0
    }
1274
0
  }
1275
1276
0
  if (m_aux_reader_tai_timestamps) {
1277
0
    auto readResult = m_aux_reader_tai_timestamps->get_sample_info(get_file().get(), sample_idx);
1278
0
    if (!readResult) {
1279
0
      return readResult.error();
1280
0
    }
1281
1282
0
    if (!readResult->empty()) {
1283
0
      auto resultTai = Box_itai::decode_tai_from_vector(*readResult);
1284
0
      if (!resultTai) {
1285
0
        return resultTai.error();
1286
0
      }
1287
1288
0
      sample->timestamp = heif_tai_timestamp_packet_alloc();
1289
0
      heif_tai_timestamp_packet_copy(sample->timestamp, &*resultTai);
1290
0
    }
1291
0
  }
1292
1293
0
  m_next_sample_to_be_output++;
1294
1295
0
  return sample.release();
1296
0
}
1297
1298
1299
std::vector<heif_sample_aux_info_type> Track::get_sample_aux_info_types() const
1300
0
{
1301
0
  std::vector<heif_sample_aux_info_type> types;
1302
1303
0
  if (m_aux_reader_tai_timestamps) types.emplace_back(m_aux_reader_tai_timestamps->get_type());
1304
0
  if (m_aux_reader_content_ids) types.emplace_back(m_aux_reader_content_ids->get_type());
1305
1306
0
  return types;
1307
0
}