Coverage Report

Created: 2026-12-01 06:47

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/libheif/libheif/sequences/track_visual.cc
Line
Count
Source
1
/*
2
 * HEIF image base codec.
3
 * Copyright (c) 2025 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 "track_visual.h"
22
23
#include <memory>
24
#include <utility>
25
#include "codecs/decoder.h"
26
#include "codecs/encoder.h"
27
#include "chunk.h"
28
#include "image/pixelimage.h"
29
#include "context.h"
30
#include "api_structs.h"
31
#include "codecs/hevc_boxes.h"
32
#include "codecs/uncompressed/unc_boxes.h"
33
34
35
namespace {
36
37
// One outstanding sample is enough for codecs without frame reordering: after
38
// submitting a complete sample, the next poll must return an image or an error.
39
// Video codecs may buffer pictures. This is a work budget, not a codec latency
40
// claim: each returned frame also pays for one non-displayed sample.
41
uint16_t max_sequence_decode_work_debt(heif_compression_format format)
42
95.4k
{
43
95.4k
  switch (format) {
44
524
    case heif_compression_JPEG:
45
592
    case heif_compression_JPEG2000:
46
592
    case heif_compression_HTJ2K:
47
4.96k
    case heif_compression_uncompressed:
48
4.96k
    case heif_compression_mask:
49
4.96k
      return 1;
50
0
    case heif_compression_VVC:
51
      // vvdec parses up to 8 pictures ahead, on top of the frame reordering of the stream.
52
0
      return 64;
53
90.4k
    default:
54
90.4k
      return 32;
55
95.4k
  }
56
95.4k
}
57
58
Error sequence_decode_work_limit_error()
59
176
{
60
176
  return {heif_error_Invalid_input, heif_suberror_Security_limit_exceeded,
61
176
          "Sequence decoding exceeded the limit for samples without enough output frames."};
62
176
}
63
64
} // namespace
65
66
67
Track_Visual::Track_Visual(HeifContext* ctx)
68
12.5k
  : Track(ctx)
69
12.5k
{
70
12.5k
}
71
72
73
Track_Visual::~Track_Visual()
74
12.5k
{
75
12.5k
  for (auto& user_data : m_frame_user_data) {
76
0
    user_data.second.release();
77
0
  }
78
12.5k
}
79
80
81
Error Track_Visual::load(const std::shared_ptr<Box_trak>& trak)
82
12.5k
{
83
12.5k
  Error parentLoadError = Track::load(trak);
84
12.5k
  if (parentLoadError) {
85
174
    return parentLoadError;
86
174
  }
87
88
  // Every chunk of a visual track must have a decoder attached. Track::load()
89
  // attaches one only when the chunk's sample description is a VisualSampleEntry.
90
  // A 'pict'/'vide'/'auxv' track whose 'stsd' also carries a non-visual entry (for
91
  // example an 'mp4a' audio entry) and maps a chunk to it via 'stsc' produces a
92
  // decoder-less chunk. The decode loop (decode_next_image_sample) guarded that
93
  // pointer only with assert(), so on an NDEBUG build it was a NULL-pointer
94
  // dereference through a virtual call (GHSA-8p2c-9wv4-rx4p). Reject the file here,
95
  // before any decoding. This is scoped to the visual track and does not affect
96
  // metadata tracks, which legitimately have non-visual sample entries.
97
533k
  for (const auto& chunk : m_chunks) {
98
533k
    if (!chunk->get_decoder()) {
99
12
      return {
100
12
        heif_error_Invalid_input,
101
12
        heif_suberror_Unspecified,
102
12
        "Image sequence track has a chunk that references a non-visual sample description."
103
12
      };
104
12
    }
105
533k
  }
106
107
  // Collect the colour profiles and HDR metadata of each sample entry, so that we can attach them to the decoded frames.
108
  // As for image item properties, a later 'colr' box replaces an earlier one of the same kind.
109
110
24.7k
  for (size_t i = 0; i < m_stsd->get_num_sample_entries(); i++) {
111
12.3k
    auto sample_entry = m_stsd->get_sample_entry(i);
112
12.3k
    ImageDescription& metadata = m_sample_description_metadata.emplace_back();
113
114
12.3k
    for (const auto& colr : sample_entry->get_child_boxes<Box_colr>()) {
115
772
      metadata.set_color_profile(colr->get_color_profile());
116
772
    }
117
118
12.3k
    if (auto clli = sample_entry->get_child_box<Box_clli>()) {
119
14
      metadata.set_clli(clli->clli);
120
14
    }
121
122
12.3k
    if (auto mdcv = sample_entry->get_child_box<Box_mdcv>()) {
123
2
      metadata.set_mdcv(mdcv->mdcv);
124
2
    }
125
126
12.3k
    if (auto amve = sample_entry->get_child_box<Box_amve>()) {
127
2
      metadata.set_amve(amve->amve);
128
2
    }
129
130
12.3k
    if (auto ndwt = sample_entry->get_child_box<Box_ndwt>()) {
131
4
      metadata.set_nominal_diffuse_white_luminance(ndwt->get_diffuse_white_luminance());
132
4
    }
133
134
12.3k
    if (auto pasp = sample_entry->get_child_box<Box_pasp>()) {
135
8
      metadata.set_pixel_ratio(pasp->hSpacing, pasp->vSpacing);
136
8
    }
137
12.3k
  }
138
139
12.3k
  const std::vector<uint32_t>& chunk_offsets = m_stco->get_offsets();
140
141
  // Find sequence resolution
142
143
12.3k
  if (!chunk_offsets.empty()) {
144
12.3k
    auto* s2c = m_stsc->get_chunk(1);
145
12.3k
    if (!s2c) {
146
0
      return {
147
0
        heif_error_Invalid_input,
148
0
        heif_suberror_Unspecified,
149
0
        "Visual track has no chunk 1"
150
0
      };
151
0
    }
152
153
12.3k
    Box_stsc::SampleToChunk sampleToChunk = *s2c;
154
155
12.3k
    auto sample_description = m_stsd->get_sample_entry(sampleToChunk.sample_description_index - 1);
156
12.3k
    if (!sample_description) {
157
0
      return {
158
0
        heif_error_Invalid_input,
159
0
        heif_suberror_Unspecified,
160
0
        "Visual track has sample description"
161
0
      };
162
0
    }
163
164
12.3k
    auto visual_sample_description = std::dynamic_pointer_cast<const Box_VisualSampleEntry>(sample_description);
165
12.3k
    if (!visual_sample_description) {
166
0
      return {
167
0
        heif_error_Invalid_input,
168
0
        heif_suberror_Unspecified,
169
0
        "Visual track sample description does not match visual track."
170
0
      };
171
0
    }
172
173
12.3k
    m_width = visual_sample_description->get_VisualSampleEntry_const().width;
174
12.3k
    m_height = visual_sample_description->get_VisualSampleEntry_const().height;
175
12.3k
  }
176
177
12.3k
  return {};
178
12.3k
}
179
180
181
Error Track_Visual::initialize_after_parsing(HeifContext* ctx, const std::vector<std::shared_ptr<Track> >& all_tracks)
182
12.0k
{
183
  // --- check whether there is an auxiliary alpha track assigned to this track
184
185
  // Only assign to image-sequence tracks (TODO: are there also alpha tracks allowed for video tracks 'heif_track_type_video'?)
186
187
12.0k
  if (get_handler() == heif_track_type_image_sequence) {
188
12.4k
    for (const auto& track : all_tracks) {
189
      // skip ourselves
190
12.4k
      if (track->get_id() != get_id()) {
191
        // Is this an aux alpha track?
192
973
        auto h = fourcc_to_string(track->get_handler());
193
973
        if (track->get_handler() == heif_track_type_auxiliary &&
194
39
            track->get_auxiliary_info_type() == heif_auxiliary_track_info_type_alpha) {
195
          // Is it assigned to the current track
196
0
          auto tref = track->get_tref_box();
197
0
          if (!tref) {
198
0
            return {
199
0
              heif_error_Invalid_input,
200
0
              heif_suberror_Unspecified,
201
0
              "Auxiliary track without 'tref'"
202
0
            };
203
0
          }
204
205
0
          auto references = tref->get_references(fourcc("auxl"));
206
0
          if (std::any_of(references.begin(), references.end(), [this](uint32_t id) { return id == get_id(); })) {
207
            // Assign it
208
209
0
            m_aux_alpha_track = std::dynamic_pointer_cast<Track_Visual>(track);
210
0
          }
211
0
        }
212
973
      }
213
12.4k
    }
214
11.5k
  }
215
216
12.0k
  return {};
217
12.0k
}
218
219
220
Track_Visual::Track_Visual(HeifContext* ctx, uint32_t track_id, uint16_t width, uint16_t height,
221
                           const TrackOptions* options, uint32_t handler_type)
222
0
  : Track(ctx, track_id, options, handler_type)
223
0
{
224
0
  m_tkhd->set_resolution(width, height);
225
  //m_hdlr->set_handler_type(handler_type);  already done in Track()
226
227
0
  auto vmhd = std::make_shared<Box_vmhd>();
228
0
  m_minf->append_child_box(vmhd);
229
0
}
230
231
232
bool Track_Visual::has_alpha_channel() const
233
0
{
234
0
  if (m_aux_alpha_track != nullptr) {
235
0
    return true;
236
0
  }
237
238
  // --- special case: 'uncv' with alpha component
239
0
#if WITH_UNCOMPRESSED_CODEC
240
0
  if (m_stsd) {
241
0
    auto sampleEntry = m_stsd->get_sample_entry(0);
242
0
    if (sampleEntry) {
243
0
      if (auto box_uncv = std::dynamic_pointer_cast<const Box_uncv>(sampleEntry)) {
244
0
        if (auto cmpd = box_uncv->get_child_box<const Box_cmpd>()) {
245
0
          if (cmpd->has_component(heif_cmpd_component_type_alpha)) {
246
0
            return true;
247
0
          }
248
0
        }
249
0
      }
250
0
    }
251
0
  }
252
0
#endif
253
254
0
  return false;
255
0
}
256
257
258
Result<std::shared_ptr<HeifPixelImage> > Track_Visual::decode_next_image_sample(const heif_decoding_options& options)
259
45.4k
{
260
45.4k
  if (m_decode_work_limit_exceeded) {
261
0
    return sequence_decode_work_limit_error();
262
0
  }
263
264
  // --- If we ignore the editlist, we stop when we reached the end of the original samples.
265
266
45.4k
  uint64_t num_output_samples = m_num_output_samples;
267
45.4k
  if (options.ignore_sequence_editlist) {
268
0
    num_output_samples = m_num_samples;
269
0
  }
270
271
  // --- Did we reach the end of the sequence?
272
273
45.4k
  if (m_next_sample_to_be_output >= num_output_samples) {
274
0
    return Error{
275
0
      heif_error_End_of_sequence,
276
0
      heif_suberror_Unspecified,
277
0
      "End of sequence"
278
0
    };
279
0
  }
280
281
282
45.4k
  std::shared_ptr<HeifPixelImage> image;
283
284
45.4k
  uint32_t sample_idx_in_chunk;
285
45.4k
  uintptr_t decoded_sample_idx = 0; // TODO: map this to sample idx + chunk
286
287
142k
  for (;;) {
288
142k
    const SampleTiming& sampleTiming = m_presentation_timeline[m_next_sample_to_be_decoded % m_presentation_timeline.size()];
289
142k
    sample_idx_in_chunk = sampleTiming.sampleIdx;
290
142k
    uint32_t chunk_idx = sampleTiming.chunkIdx;
291
292
142k
    const std::shared_ptr<Chunk>& chunk = m_chunks[chunk_idx];
293
294
142k
    auto decoder = chunk->get_decoder();
295
142k
    if (!decoder) {
296
      // Should not happen: Track_Visual::load() rejects any visual track that has a
297
      // decoder-less chunk. Guard anyway so that a future regression surfaces as a
298
      // clean error instead of a NULL-pointer dereference through the virtual call
299
      // below (GHSA-8p2c-9wv4-rx4p).
300
0
      return Error{
301
0
        heif_error_Invalid_input,
302
0
        heif_suberror_Unspecified,
303
0
        "Sequence chunk has no decoder."
304
0
      };
305
0
    }
306
307
142k
    const heif_compression_format format = decoder->get_compression_format();
308
142k
    uint16_t& decode_work_debt = m_decode_work_debt[format];
309
310
142k
    if (m_active_decoder) {
311
      // Drain the decoder that received the samples before switching descriptions
312
      // or finishing input. The next sample may belong to another decoder.
313
130k
      const bool end_of_input = m_next_sample_to_be_decoded >= num_output_samples;
314
130k
      const bool switching_decoder = decoder != m_active_decoder;
315
130k
      Result<std::shared_ptr<HeifPixelImage> > getFrameResult = m_active_decoder->get_decoded_frame(options,
316
130k
                                                                                                    &decoded_sample_idx,
317
130k
                                                                                                    m_heif_context->get_security_limits());
318
130k
      if (getFrameResult.error()) {
319
2.62k
        return getFrameResult.error();
320
2.62k
      }
321
322
323
      // We received a decoded frame. Exit "push data" / "decode" loop.
324
325
127k
      if (*getFrameResult != nullptr) {
326
37.6k
        image = *getFrameResult;
327
328
        // Credit the returned frame and one potentially non-displayed sample.
329
        // Do this at the decoder boundary, even if later image postprocessing fails.
330
        // The frame comes from the active decoder, which can have a different format
331
        // than the decoder of the next input sample when the sample description changes.
332
37.6k
        uint16_t& output_work_debt = m_decode_work_debt[m_active_decoder->get_compression_format()];
333
37.6k
        output_work_debt = (output_work_debt > 2) ? output_work_debt - 2 : 0;
334
335
37.6k
        break;
336
37.6k
      }
337
338
90.1k
      if ((end_of_input || switching_decoder) && !m_decoder_is_flushed) {
339
6.00k
        if (Error err = m_active_decoder->flush_decoder()) {
340
0
          return err;
341
0
        }
342
6.00k
        m_decoder_is_flushed = true;
343
6.00k
        continue;
344
6.00k
      }
345
346
      // A drained decoder can be replaced at a chunk boundary. At end-of-input,
347
      // a missing output frame is an error.
348
84.1k
      if (m_decoder_is_flushed) {
349
504
        if (end_of_input) {
350
504
          return Error(heif_error_Decoder_plugin_error,
351
504
                       heif_suberror_Unspecified,
352
504
                       "Did not decode all frames");
353
504
        }
354
0
        m_active_decoder->release_decoder();
355
0
        m_active_decoder.reset();
356
0
        m_decoder_is_flushed = false;
357
0
      }
358
84.1k
    }
359
360
361
    // --- Push more data into the decoder (or send end-of-sequence).
362
363
95.4k
    if (m_next_sample_to_be_decoded < num_output_samples) {
364
365
95.4k
      if (decode_work_debt >= max_sequence_decode_work_debt(format)) {
366
176
        m_decode_work_limit_exceeded = true;
367
176
        return sequence_decode_work_limit_error();
368
176
      }
369
370
      // --- Find the data extent that stores the compressed frame data.
371
372
95.2k
      DataExtent extent = chunk->get_data_extent_for_sample(sample_idx_in_chunk);
373
95.2k
      decoder->set_data_extent(std::move(extent));
374
375
      // std::cout << "PUSH chunk " << chunk_idx << " sample " << sample_idx << " (" << extent.m_size << " bytes)\n";
376
377
      // advance decoding index to next in segment
378
95.2k
      m_next_sample_to_be_decoded++;
379
380
      // Send the decoder configuration when we send the first sample of the chunk.
381
      // The configuration NALs might change for each chunk. A decoder that is shared by
382
      // consecutive chunks with the same sample description receives them again, which is
383
      // harmless (repeated parameter sets / sequence headers), and a decoder that was released
384
      // after draining needs them to start again.
385
95.2k
      const bool is_first_sample = (sample_idx_in_chunk == chunk->first_sample_number());
386
387
      // --- Push data into the decoder.
388
95.2k
      Error decodingError = decoder->decode_sequence_frame_from_compressed_data(is_first_sample,
389
95.2k
                                                                                options,
390
95.2k
                                                                                sample_idx_in_chunk, // user data
391
95.2k
                                                                                m_heif_context->get_security_limits());
392
95.2k
      if (decodingError) {
393
4.51k
        return decodingError;
394
4.51k
      }
395
396
90.7k
      decode_work_debt++;
397
90.7k
      m_active_decoder = decoder;
398
90.7k
    }
399
0
    else {
400
      // Not reached: at end of input, there is always an active decoder (we pushed at least one sample)
401
      // and the draining above either returns a frame or reports an error. Guard against endless looping anyway.
402
0
      return Error(heif_error_Decoder_plugin_error,
403
0
                   heif_suberror_Unspecified,
404
0
                   "Did not decode all frames");
405
0
    }
406
95.4k
  }
407
408
409
  // --- We have received a new decoded image.
410
  //     Postprocess decoded image, attach metadata.
411
412
37.6k
  const SampleTiming& outputTiming = m_presentation_timeline[m_next_sample_to_be_output % m_presentation_timeline.size()];
413
37.6k
  const auto& chunk = m_chunks[outputTiming.chunkIdx];
414
  // Track::load() verified that the sample description index exists.
415
37.6k
  const ImageDescription& metadata = m_sample_description_metadata[chunk->get_sample_description_index() - 1];
416
417
  // Sample-entry colour information takes precedence over bitstream metadata.
418
37.6k
  const nclx_profile sample_entry_nclx = metadata.get_color_profile_nclx();
419
37.6k
  if (sample_entry_nclx.is_defined()) {
420
7.06k
    std::vector<Error> warnings;
421
7.06k
    image->set_color_profile_nclx(consolidate_colr_and_bitstream_nclx(sample_entry_nclx, image->get_color_profile_nclx(),
422
7.06k
                                                                      options, warnings));
423
7.06k
    image->add_warnings(warnings);
424
7.06k
  }
425
426
37.6k
  if (metadata.has_icc_color_profile()) {
427
77
    image->set_color_profile_icc(metadata.get_color_profile_icc());
428
77
  }
429
430
37.6k
  if (metadata.has_clli()) {
431
12
    image->set_clli(metadata.get_clli());
432
12
  }
433
434
37.6k
  if (metadata.has_mdcv()) {
435
1
    image->set_mdcv(metadata.get_mdcv());
436
1
  }
437
438
37.6k
  if (metadata.has_amve()) {
439
1
    image->set_amve(metadata.get_amve());
440
1
  }
441
442
37.6k
  if (metadata.has_nominal_diffuse_white()) {
443
3
    image->set_nominal_diffuse_white_luminance(metadata.get_nominal_diffuse_white_luminance());
444
3
  }
445
446
37.6k
  if (metadata.has_nonsquare_pixel_ratio()) {
447
48
    uint32_t h, v;
448
48
    metadata.get_pixel_ratio(&h, &v);
449
48
    image->set_pixel_ratio(h, v);
450
48
  }
451
452
37.6k
  if (m_stts) {
453
    // 'sample_idx_in_chunk' follows m_next_sample_to_be_decoded, which runs ahead of the output
454
    // by the decoder latency. Look the duration up by the output position instead, like
455
    // Track::get_next_sample_raw_data() does.
456
37.6k
    image->set_sample_duration(m_stts->get_sample_duration(outputTiming.sampleIdx));
457
37.6k
  }
458
459
  // --- assign alpha if we have an assigned alpha track
460
461
37.6k
  if (m_aux_alpha_track) {
462
0
    auto alphaResult = m_aux_alpha_track->decode_next_image_sample(options);
463
0
    if (!alphaResult) {
464
0
      return alphaResult.error();
465
0
    }
466
467
0
    auto alphaImage = *alphaResult;
468
469
    // The alpha auxiliary track may have a different size than the main track. Nothing in the
470
    // standard forbids this. We scale it to the main image size so that downstream consumers can
471
    // rely on the alpha plane matching the color planes. This mirrors what the still-image decoder
472
    // does in ImageItem (see image_item.cc). As noted there, we may later add a decoding option to
473
    // turn this automatic scaling off, but that requires that libheif no longer assumes everywhere
474
    // that the alpha channel has the same resolution as the color channels.
475
0
    if (alphaImage->get_width() != image->get_width() ||
476
0
        alphaImage->get_height() != image->get_height()) {
477
0
      std::shared_ptr<HeifPixelImage> scaled_alpha;
478
0
      Error err = alphaImage->scale_nearest_neighbor(scaled_alpha, image->get_width(), image->get_height(),
479
0
                                                     m_heif_context->get_security_limits());
480
0
      if (err) {
481
0
        return err;
482
0
      }
483
0
      alphaImage = std::move(scaled_alpha);
484
0
    }
485
486
0
    if (Error err = image->transfer_channel_from_image_as(alphaImage, heif_channel_Y, heif_channel_Alpha)) {
487
0
      return err;
488
0
    }
489
0
  }
490
491
492
  // --- read sample auxiliary data
493
494
37.6k
  if (m_aux_reader_content_ids) {
495
0
    auto readResult = m_aux_reader_content_ids->get_sample_info(get_file().get(), (uint32_t)decoded_sample_idx);
496
0
    if (!readResult) {
497
0
      return readResult.error();
498
0
    }
499
500
0
    Result<std::string> convResult = vector_to_string(*readResult);
501
0
    if (!convResult) {
502
0
      return convResult.error();
503
0
    }
504
505
0
    image->set_gimi_sample_content_id(*convResult);
506
0
  }
507
508
37.6k
  if (m_aux_reader_tai_timestamps) {
509
0
    auto readResult = m_aux_reader_tai_timestamps->get_sample_info(get_file().get(), (uint32_t)decoded_sample_idx);
510
0
    if (!readResult) {
511
0
      return readResult.error();
512
0
    }
513
514
0
    std::vector<uint8_t>& tai_data = *readResult;
515
0
    if (!tai_data.empty()) {
516
0
      auto resultTai = Box_itai::decode_tai_from_vector(tai_data);
517
0
      if (!resultTai) {
518
0
        return resultTai.error();
519
0
      }
520
521
0
      image->set_tai_timestamp(&*resultTai);
522
0
    }
523
0
  }
524
525
37.6k
  m_next_sample_to_be_output++;
526
527
37.6k
  return image;
528
37.6k
}
529
530
531
Error Track_Visual::encode_end_of_sequence(heif_encoder* h_encoder)
532
0
{
533
0
  auto encoder = m_chunks.back()->get_encoder();
534
535
0
  for (;;) {
536
0
    Error err = encoder->encode_sequence_flush(h_encoder);
537
0
    if (err) {
538
0
      return err;
539
0
    }
540
541
0
    Result<bool> processingResult = process_encoded_data(h_encoder);
542
0
    if (processingResult.is_error()) {
543
0
      return processingResult.error();
544
0
    }
545
546
0
    if (!*processingResult) {
547
0
      break;
548
0
    }
549
0
  }
550
551
552
  // --- also end alpha track
553
554
0
  if (m_aux_alpha_track) {
555
0
    auto err = m_aux_alpha_track->encode_end_of_sequence(m_alpha_track_encoder.get());
556
0
    if (err) {
557
0
      return err;
558
0
    }
559
0
  }
560
561
0
  return {};
562
0
}
563
564
565
Error Track_Visual::encode_image(const std::shared_ptr<HeifPixelImage>& image,
566
                                 heif_encoder* h_encoder,
567
                                 const heif_sequence_encoding_options* in_options,
568
                                 heif_image_input_class input_class)
569
0
{
570
0
  if (image->get_width() > 0xFFFF ||
571
0
      image->get_height() > 0xFFFF) {
572
0
    return {
573
0
      heif_error_Invalid_input,
574
0
      heif_suberror_Unspecified,
575
0
      "Input image resolution too high"
576
0
    };
577
0
  }
578
579
0
  m_image_class = input_class;
580
581
582
  // --- resolve the encoding options
583
584
  // Build an effective options struct so that the rest of this function never
585
  // has to look at the caller's pointer. 'in_options' may be NULL, which the API
586
  // documents as "use the default options", so every field has to come from a
587
  // fully populated struct instead. This also lets libheif resolve "auto" fields
588
  // (e.g. content_kind) to concrete values before passing them to the encoder
589
  // plugin. heif_sequence_encoding_options_copy is version-aware and ignores a
590
  // NULL source, so callers built against older headers won't be read past their
591
  // actual allocation and a NULL source simply leaves the defaults in place.
592
593
0
  std::unique_ptr<heif_sequence_encoding_options, void(*)(heif_sequence_encoding_options*)>
594
0
      effective_options(heif_sequence_encoding_options_alloc(),
595
0
                        heif_sequence_encoding_options_release);
596
0
  heif_sequence_encoding_options_copy(effective_options.get(), in_options);
597
598
  // Resolve content_kind=auto based on this track's handler type. For auxiliary
599
  // tracks (e.g. alpha) the parent track resolves the value before recursing in,
600
  // so we never reach this branch with handler=auxv.
601
  // TODO: in the future, "auto" could also factor in input frame rate or
602
  // frame-to-frame similarity.
603
0
  if (effective_options->content_kind == heif_sequence_content_kind_auto) {
604
0
    switch (get_handler()) {
605
0
      case heif_track_type_video:
606
0
        effective_options->content_kind = heif_sequence_content_kind_video;
607
0
        break;
608
0
      case heif_track_type_image_sequence:
609
0
      default:
610
0
        effective_options->content_kind = heif_sequence_content_kind_image_sequence;
611
0
        break;
612
0
    }
613
0
  }
614
615
616
  // --- If input has an alpha channel, add an alpha auxiliary track.
617
618
0
  if (effective_options->save_alpha_channel && image->has_alpha() && !m_aux_alpha_track &&
619
0
      h_encoder->plugin->compression_format != heif_compression_uncompressed) { // TODO: ask plugin
620
0
    if (m_active_encoder) {
621
0
      return {
622
0
        heif_error_Usage_error,
623
0
        heif_suberror_Unspecified,
624
0
        "Input images must all either have an alpha channel or none of them."
625
0
      };
626
0
    }
627
0
    else {
628
      // alpha track uses default options, same timescale as color track
629
630
0
      TrackOptions alphaOptions;
631
0
      alphaOptions.track_timescale = m_track_info.track_timescale;
632
633
0
      auto newAlphaTrackResult = m_heif_context->add_visual_sequence_track(&alphaOptions,
634
0
                                                                           heif_track_type_auxiliary,
635
0
                                                                           static_cast<uint16_t>(image->get_width()),
636
0
                                                                           static_cast<uint16_t>(image->get_height()));
637
638
0
      if (auto err = newAlphaTrackResult.error()) {
639
0
        return err;
640
0
      }
641
642
      // add a reference to the color track
643
644
0
      m_aux_alpha_track = *newAlphaTrackResult;
645
0
      m_aux_alpha_track->add_reference_to_track(fourcc("auxl"), m_id);
646
647
      // make a copy of the encoder from the color track for encoding the alpha track
648
649
0
      m_alpha_track_encoder = std::make_unique<heif_encoder>(h_encoder->plugin);
650
0
      heif_error err = m_alpha_track_encoder->alloc();
651
0
      if (err.code) {
652
0
        return {err.code, err.subcode, err.message};
653
0
      }
654
0
      m_alpha_track_encoder->copy_parameters_from(*h_encoder);
655
0
    }
656
0
  }
657
658
659
0
  if (!m_active_encoder) {
660
0
    m_active_encoder = h_encoder;
661
0
  }
662
0
  else if (m_active_encoder != h_encoder) {
663
0
    return {
664
0
      heif_error_Usage_error,
665
0
      heif_suberror_Unspecified,
666
0
      "You may not switch the heif_encoder while encoding a sequence."
667
0
    };
668
0
  }
669
670
0
  if (h_encoder->plugin->plugin_api_version < 4) {
671
0
    return Error{
672
0
      heif_error_Plugin_loading_error, heif_suberror_No_matching_decoder_installed,
673
0
      "Encoder plugin needs to be at least version 4."
674
0
    };
675
0
  }
676
677
  // === generate compressed image bitstream
678
679
  // generate new chunk for first image or when compression formats don't match
680
681
0
  if (m_chunks.empty() || m_chunks.back()->get_compression_format() != h_encoder->plugin->compression_format) {
682
0
    add_chunk(h_encoder->plugin->compression_format);
683
0
  }
684
685
  // --- check whether we have to convert the image color space
686
687
  // The reason for doing the color conversion here is that the input might be an RGBA image and the color conversion
688
  // will extract the alpha plane anyway. We can reuse that plane below instead of having to do a new conversion.
689
690
0
  auto encoder = m_chunks.back()->get_encoder();
691
692
0
  const heif_color_profile_nclx* output_nclx;
693
0
  heif_color_profile_nclx nclx;
694
695
0
  if (const auto* image_nclx = encoder->get_forced_output_nclx()) {
696
0
    output_nclx = const_cast<heif_color_profile_nclx*>(image_nclx);
697
0
  }
698
0
  else if (in_options) {
699
0
    output_nclx = in_options->output_nclx_profile;
700
0
  }
701
0
  else {
702
    // Note: this is the one place that still distinguishes "caller passed no
703
    // options" from "caller passed options with a NULL output_nclx_profile",
704
    // so it reads in_options rather than effective_options. Both cases mean
705
    // "keep the input image's parameters", but they express it differently: a
706
    // NULL profile lets compute_target_nclx_profile() derive them, while the
707
    // branch below builds the profile here. The two differ only for an image
708
    // that carries no NCLX at all, where the explicit undefined profile built
709
    // below makes nclx_profile_matches_spec() request a conversion that a NULL
710
    // profile would skip. Unifying them would change that behaviour, so it is
711
    // left alone here.
712
0
    if (image->has_nclx_color_profile()) {
713
0
      nclx_profile input_nclx = image->get_color_profile_nclx();
714
715
0
      nclx.version = 1;
716
0
      nclx.color_primaries = (enum heif_color_primaries) input_nclx.get_colour_primaries();
717
0
      nclx.transfer_characteristics = (enum heif_transfer_characteristics) input_nclx.get_transfer_characteristics();
718
0
      nclx.matrix_coefficients = (enum heif_matrix_coefficients) input_nclx.get_matrix_coefficients();
719
0
      nclx.full_range_flag = input_nclx.get_full_range_flag();
720
721
0
      output_nclx = &nclx;
722
0
    }
723
0
    else {
724
0
      nclx_profile undefined_nclx;
725
0
      undefined_nclx.copy_to_heif_color_profile_nclx(&nclx);
726
727
0
      output_nclx = &nclx;
728
0
    }
729
0
  }
730
731
0
  Result<std::shared_ptr<HeifPixelImage> > srcImageResult = encoder->convert_colorspace_for_encoding(image,
732
0
                                                                                                     h_encoder,
733
0
                                                                                                     output_nclx,
734
0
                                                                                                     &effective_options->color_conversion_options,
735
0
                                                                                                     m_heif_context->get_security_limits());
736
0
  if (!srcImageResult) {
737
0
    return srcImageResult.error();
738
0
  }
739
740
0
  std::shared_ptr<HeifPixelImage> colorConvertedImage = *srcImageResult;
741
742
  // integer range is checked at beginning of function.
743
0
  assert(colorConvertedImage->get_width() == image->get_width());
744
0
  assert(colorConvertedImage->get_height() == image->get_height());
745
0
  m_width = static_cast<uint16_t>(colorConvertedImage->get_width());
746
0
  m_height = static_cast<uint16_t>(colorConvertedImage->get_height());
747
748
  // --- encode image
749
750
0
  Error encodeError = encoder->encode_sequence_frame(colorConvertedImage, h_encoder,
751
0
                                                     *effective_options,
752
0
                                                     input_class,
753
0
                                                     colorConvertedImage->get_sample_duration(), get_timescale(),
754
0
                                                     m_current_frame_nr);
755
756
0
  if (encodeError) {
757
0
    return encodeError;
758
0
  }
759
760
0
  m_sample_duration = colorConvertedImage->get_sample_duration();
761
  // TODO heif_tai_timestamp_packet* tai = image->get_tai_timestamp();
762
  // TODO image->has_gimi_sample_content_id() ? image->get_gimi_sample_content_id() : std::string{});
763
764
765
  // store frame user data
766
767
0
  FrameUserData userData;
768
0
  userData.sample_duration = colorConvertedImage->get_sample_duration();
769
0
  if (image->has_gimi_sample_content_id()) {
770
0
    userData.gimi_content_id = image->get_gimi_sample_content_id();
771
0
  }
772
773
0
  if (const auto* tai = image->get_tai_timestamp()) {
774
0
    userData.tai_timestamp = heif_tai_timestamp_packet_alloc();
775
0
    heif_tai_timestamp_packet_copy(userData.tai_timestamp, tai);
776
0
  }
777
778
0
  m_frame_user_data[m_current_frame_nr] = userData;
779
780
0
  m_current_frame_nr++;
781
782
  // --- get compressed data from encoder
783
784
0
  Result<bool> processingResult = process_encoded_data(h_encoder);
785
0
  if (auto err = processingResult.error()) {
786
0
    return err;
787
0
  }
788
789
790
  // --- encode alpha channel into auxiliary track
791
792
0
  if (m_aux_alpha_track) {
793
0
    auto alphaImageResult = create_alpha_image_from_image_alpha_channel(colorConvertedImage,
794
0
                                                                        m_heif_context->get_security_limits());
795
0
    if (auto err = alphaImageResult.error()) {
796
0
      return err;
797
0
    }
798
799
0
    (*alphaImageResult)->set_sample_duration(colorConvertedImage->get_sample_duration());
800
801
    // Pass the resolved options (not the caller's in_options) so the alpha aux
802
    // track inherits the color track's content_kind instead of re-resolving
803
    // from its own 'auxv' handler.
804
0
    auto err = m_aux_alpha_track->encode_image(*alphaImageResult,
805
0
                                               m_alpha_track_encoder.get(),
806
0
                                               effective_options.get(),
807
0
                                               heif_image_input_class_alpha);
808
0
    if (err) {
809
0
      return err;
810
0
    }
811
0
  }
812
813
0
  return {};
814
0
}
815
816
817
Result<bool> Track_Visual::process_encoded_data(heif_encoder* h_encoder)
818
0
{
819
0
  auto encoder = m_chunks.back()->get_encoder();
820
821
0
  std::optional<Encoder::CodedImageData> encodingResult = encoder->encode_sequence_extract_data();
822
0
  if (!encodingResult) {
823
    // nothing pending in the encoder
824
0
    return {false};
825
0
  }
826
827
0
  const Encoder::CodedImageData& data = *encodingResult;
828
829
830
0
  if (data.bitstream.empty() &&
831
0
      data.properties.empty()) {
832
0
    return {false};
833
0
  }
834
835
  // --- generate SampleDescriptionBox
836
837
0
  if (!m_generated_sample_description_box) {
838
0
    auto sample_description_box = encoder->get_sample_description_box(data);
839
0
    if (sample_description_box) {
840
0
      VisualSampleEntry& visualSampleEntry = sample_description_box->get_VisualSampleEntry();
841
0
      visualSampleEntry.width = m_width;
842
0
      visualSampleEntry.height = m_height;
843
844
      // add Coding-Constraints box (ccst) only if we are generating an image sequence
845
846
      // TODO: does the alpha track also need a ccst box?
847
      //       ComplianceWarden says so (and it makes sense), but HEIF says that 'ccst' shall be present
848
      //       if the handler is 'pict'. However, the alpha track is 'auxv'.
849
0
      if (true) { // m_hdlr->get_handler_type() == heif_track_type_image_sequence) {
850
0
        auto ccst = std::make_shared<Box_ccst>();
851
0
        ccst->set_coding_constraints(data.codingConstraints);
852
0
        sample_description_box->append_child_box(ccst);
853
0
      }
854
855
0
      if (m_image_class == heif_image_input_class_alpha) {
856
0
        auto auxi_box = std::make_shared<Box_auxi>();
857
0
        auxi_box->set_aux_track_type_urn(get_track_auxiliary_info_type(h_encoder->plugin->compression_format));
858
0
        sample_description_box->append_child_box(auxi_box);
859
0
      }
860
861
0
      set_sample_description_box(sample_description_box);
862
0
      m_generated_sample_description_box = true;
863
0
    }
864
0
  }
865
866
0
  if (!data.bitstream.empty()) {
867
0
    uintptr_t frame_number = data.frame_nr;
868
869
0
    auto& user_data = m_frame_user_data[frame_number];
870
871
0
    int32_t decoding_time = static_cast<int32_t>(m_stsz->num_samples()) * m_sample_duration;
872
0
    int32_t composition_time = static_cast<int32_t>(frame_number) * m_sample_duration;
873
874
0
    Error err = write_sample_data(data.bitstream,
875
0
                                  user_data.sample_duration,
876
0
                                  composition_time - decoding_time,
877
0
                                  data.is_sync_frame,
878
0
                                  user_data.tai_timestamp,
879
0
                                  user_data.gimi_content_id);
880
881
0
    user_data.release();
882
0
    m_frame_user_data.erase(frame_number);
883
884
0
    if (err) {
885
0
      return err;
886
0
    }
887
0
  }
888
889
0
  return {true};
890
0
}
891
892
893
Error Track_Visual::finalize_track()
894
0
{
895
0
  if (m_active_encoder) {
896
0
    Error err = encode_end_of_sequence(m_active_encoder);
897
0
    if (err) {
898
0
      return err;
899
0
    }
900
0
  }
901
902
0
  return Track::finalize_track();
903
0
}
904
905
906
heif_brand2 Track_Visual::get_compatible_brand() const
907
0
{
908
0
  if (m_stsd->get_num_sample_entries() == 0) {
909
0
    return 0; // TODO: error ? Or can we assume at this point that there is at least one sample entry?
910
0
  }
911
912
0
  auto sampleEntry = m_stsd->get_sample_entry(0);
913
914
0
  uint32_t sample_entry_type = sampleEntry->get_short_type();
915
0
  switch (sample_entry_type) {
916
0
    case fourcc("hvc1"): {
917
0
      auto hvcC = sampleEntry->get_child_box<Box_hvcC>();
918
0
      if (!hvcC) { return 0; }
919
920
0
      const auto& config = hvcC->get_configuration();
921
0
      if (config.is_profile_compatible(HEVCDecoderConfigurationRecord::Profile_Main) ||
922
0
          config.is_profile_compatible(HEVCDecoderConfigurationRecord::Profile_MainStillPicture)) {
923
0
        return heif_brand2_hevc;
924
0
      }
925
926
0
      if (config.is_profile_compatible(HEVCDecoderConfigurationRecord::Profile_Main10) ||
927
0
          config.is_profile_compatible(HEVCDecoderConfigurationRecord::Profile_RExt)) {
928
0
        return heif_brand2_hevx;
929
0
      }
930
931
      // There is no brand for the other profiles of HEVC (ISO/IEC 23008-12, B.4.2.2).
932
0
      return 0;
933
0
    }
934
935
0
    case fourcc("avc1"):
936
0
      return heif_brand2_avcs;
937
938
0
    case fourcc("av01"):
939
0
      return heif_brand2_avis;
940
941
0
    case fourcc("j2ki"):
942
0
      return heif_brand2_j2is;
943
944
0
    case fourcc("mjpg"):
945
0
      return heif_brand2_jpgs;
946
947
0
    case fourcc("vvc1"):
948
0
      return heif_brand2_vvis;
949
950
0
    default:
951
0
      return 0;
952
0
  }
953
0
}