• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

ossia / score / 41391215711

02 Nov 2026 04:56AM UTC coverage: 51.66% (-0.6%) from 52.268%
41391215711

push

github

jcelerier
Port probes: what goes through a port or a cable, on hover

Resting the cursor on a port or a cable opens a probe: levels and a trace
for audio, the latest decoded messages for MIDI, the latest values with a
trail for numbers, colour, position, orientation, gain and angle views for
values with a unit, a thumbnail for textures. On a cable it shows what the
source produces, near its end what the process there receives.

The data comes from Execution::PortTap: while a probe is open, a node of
the execution graph gets the port's edges and copies what arrives into a
monitor, without allocation or lock for audio; TapTicker gives taps the
token the graph needs to run them. Probes only tap with execution updates
enabled, refresh at the UI event rate, and open only when previews are
enabled. Nothing touches the document.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01KdPgufUMRpkKzaYvUs9iHW

96 of 644 new or added lines in 9 files covered. (14.91%)

3455 existing lines in 31 files now uncovered.

187161 of 362292 relevant lines covered (51.66%)

305640.16 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

64.05
/src/plugins/score-plugin-media/Video/VideoDecoder.cpp
1
#include "VideoDecoder.hpp"
2

3
#include <Media/Libav.hpp>
4
#include <Video/FrameAccess.hpp>
5
#include <Video/GpuFormats.hpp>
6
#include <Video/PlaybackTime.hpp>
7

8
#include <score/tools/Debug.hpp>
9

10
#include <ossia/detail/flicks.hpp>
11
#include <ossia/detail/libav.hpp>
12
#include <ossia/detail/thread.hpp>
13

14
#include <QApplication>
15
#include <QDebug>
16
#include <QElapsedTimer>
17
#include <QTimer>
18

19
#include <algorithm>
20
#include <cstdlib>
21
#include <functional>
22
#include <iostream>
23
#include <string_view>
24
#include <thread>
25

26
#if defined(__linux__)
27
#include <unistd.h>
28
#endif
29

30
#if SCORE_HAS_LIBAV
31

32
extern "C" {
33
#include <libavcodec/avcodec.h>
34
#include <libavformat/avformat.h>
35
#include <libavutil/pixdesc.h>
36
#include <libswscale/swscale.h>
37
#include <libavcodec/packet.h>
38
#if LIBAVCODEC_VERSION_INT >= AV_VERSION_INT(61, 3, 100)
39
#if __has_include(<libavutil/mastering_display_metadata.h>)
40
#include <libavutil/mastering_display_metadata.h>
41
#endif
42
#endif
43
}
44

45
#if __APPLE__ && __has_include(<libavcodec/videotoolbox.h>)
46
#include "VideoDecoder.vtb.cpp"
47
#endif
48

49
namespace Video
50
{
51
#if LIBAVUTIL_VERSION_MAJOR >= 57
52
static auto get_format_for_codeccontext(AVCodecContext* ctx, const AVPixelFormat* p)
×
53
{
54
  //qDebug() << "device: " << av_pix_fmt_desc_get(ctx->pix_fmt)->name;
55

56
  if(auto self = (LibAVDecoder*)ctx->opaque)
×
57
  {
58
    while(*p != AV_PIX_FMT_NONE)
×
59
    {
60
      //qDebug() << av_pix_fmt_desc_get(*p)->name;
61
      // Check if the format matches the one we want from the expected HWDec
62
      if(*p == self->m_conf.hardwareAcceleration)
×
63
      {
64
        // Check if the format is indeed available
65
        auto fmt = ffmpegHardwareDecodingFormats(*p).format;
×
66
        if(fmt != AV_PIX_FMT_NONE)
×
67
        {
68
          return fmt;
×
69
        }
70
      }
×
71
      ++p;
×
72
    }
73
  }
×
74

75
  return ctx->pix_fmt;
×
76
}
×
77
#endif
78

79
void LibAVDecoder::init_scaler(VideoInterface& self) noexcept
6 ✔
80
{
81
  if(!Video::formatNeedsDecoding(self.pixel_format))
6 ✔
82
    return;
6 ✔
83

84
  m_rescale.open(self);
×
85

86
  // Only claim RGBA once the rescaler that produces it actually opened:
87
  // sws_getContext refuses some source descriptions (a stream whose
88
  // codecpar->format is AV_PIX_FMT_NONE, for one), and the renderer copies
89
  // color_space out of this metadata and applies it to frames that are still
90
  // in their native YUV.
91
  if(!m_rescale)
×
92
    return;
×
93

94
  self.pixel_format = AV_PIX_FMT_RGBA;
×
95
  self.color_space = AVCOL_SPC_RGB;
×
96
}
6 ✔
97

98
int LibAVDecoder::init_codec_context(
10 ✔
99
    const AVCodec* codec, AVBufferRef* hw_dev_ctx, const AVStream* stream,
100
    std::function<void(AVCodecContext&)> setup)
101
{
102
  m_codecContext = avcodec_alloc_context3(codec);
10 ✔
103

104
  avcodec_parameters_to_context(m_codecContext, stream->codecpar);
10 ✔
105

106
  // m_codecContext->flags |= AV_CODEC_FLAG_LOW_DELAY;
107
  // m_codecContext->flags2 |= AV_CODEC_FLAG2_FAST;
108
  const auto threading = chooseDecoderThreading(
10 ✔
109
      *codec, stream->codecpar, m_conf.useCase, m_conf.threads, hw_dev_ctx != nullptr);
10 ✔
110
#if LIBAVUTIL_VERSION_MAJOR >= 57
111
  if(hw_dev_ctx)
10 ✔
112
  {
113
    m_codecContext->hw_device_ctx = hw_dev_ctx;
×
114
    m_codecContext->opaque = (void*)this;
×
115
    m_codecContext->get_format = get_format_for_codeccontext;
×
116
  }
×
117
#endif
118
  applyDecoderThreading(*m_codecContext, threading);
10 ✔
119

120
  SCORE_ASSERT(setup);
10 ✔
121
  setup(*m_codecContext);
10 ✔
122

123
  int err = avcodec_open2(m_codecContext, codec, nullptr);
10 ✔
124
  if(err < 0)
10 ✔
125
  {
126
    qDebug() << "avcodec_open2: " << av_to_string(err);
×
127
    avcodec_free_context(&m_codecContext);
×
128
  }
×
129
  else
130
  {
131
    qDebug().noquote() << "Video decoder:"
20 ✔
132
                       << describeDecoderThreading(*m_codecContext, threading).c_str();
10 ✔
133
  }
134
  return err;
10 ✔
135
}
×
136

137
bool LibAVDecoder::open_codec_context(
6 ✔
138
    VideoInterface& self, const AVStream* stream,
139
    std::function<void(AVCodecContext&)> setup)
140
{
141
  if(auto [hw_dev_ctx, hw_codec] = open_hwdec(*m_codec); hw_codec)
6 ✔
142
  {
143
    int err = init_codec_context(hw_codec, hw_dev_ctx, stream, setup);
×
144
    if(err == 0)
×
145
    {
146
      init_scaler(self);
×
147
      return true;
×
148
    }
149
  }
×
150

151
  // Maybe opening an HW accel failed, we retry in software mode
152
  int err = init_codec_context(m_codec, nullptr, stream, setup);
6 ✔
153
  if(err == 0)
6 ✔
154
  {
155
    init_scaler(self);
6 ✔
156
    return true;
6 ✔
157
  }
158
  return false;
×
159
}
6 ✔
160

161
/*
162
 *
163
    using codec_map_type = ossia::flat_map<AVCodecID, const char*>;
164
    static const codec_map_type codecs{
165
        {AV_CODEC_ID_AV1, "av1_cuvid"},          {AV_CODEC_ID_H264, "h264_cuvid"},
166
        {AV_CODEC_ID_HEVC, "hevc_cuvid"},        {AV_CODEC_ID_MJPEG, "mjpeg_cuvid"},
167
        {AV_CODEC_ID_MPEG1VIDEO, "mpeg1_cuvid"}, {AV_CODEC_ID_MPEG2VIDEO, "mpeg2_cuvid"},
168
        {AV_CODEC_ID_MPEG4, "mpeg4_cuvid"},      {AV_CODEC_ID_VC1, "vc1_cuvid"},
169
        {AV_CODEC_ID_VP8, "vp8_cuvid"},          {AV_CODEC_ID_VP9, "vp9_cuvid"},
170
    };
171
    */
172
std::pair<AVBufferRef*, const AVCodec*>
173
LibAVDecoder::open_hwdec(const AVCodec& detected_codec) noexcept
6 ✔
174
{
175
#if LIBAVUTIL_VERSION_MAJOR >= 57
176
  auto hwAccel = m_conf.hardwareAcceleration;
6 ✔
177
  if(hwAccel == AV_PIX_FMT_NONE)
6 ✔
178
    return {};
6 ✔
179

180
  if(hwAccel == AV_PIX_FMT_NONE
×
181
     || !codecSupportsHWPixelFormat(detected_codec.id, hwAccel))
×
182
  {
183
    auto autoFmt = selectHardwareAcceleration(
×
184
        m_conf.graphicsApi, detected_codec.id, m_conf.gpuVendorId);
×
185
    if(autoFmt != AV_PIX_FMT_NONE)
×
186
      hwAccel = autoFmt;
×
187
    else
188
      return {};
×
189
  }
×
190

191
  const auto device = ffmpegHardwareDecodingFormats(hwAccel).device;
×
192
  if(device == AV_HWDEVICE_TYPE_NONE)
×
193
    return {};
×
194

195
  auto mapped = Video::hwCodecName(detected_codec.name, device);
×
196
  if(mapped.empty())
×
197
    return {};
×
198

199
  auto codec = mapped == detected_codec.name
×
200
                   ? &detected_codec // VideoToolbox case
×
201
                   : avcodec_find_decoder_by_name(mapped.c_str());
×
202
  if(!codec)
×
203
    return {};
×
204

205
  if(hwAccel == AV_PIX_FMT_DRM_PRIME)
×
206
  {
207
    // V4L2M2M: just want to map h264 to h264_v4l2m2m,
208
    // this isn't a true "hwdevice" accel
209
    return {nullptr, codec};
×
210
  }
211

212
  AVBufferRef* hw_device_ctx{};
×
213
  int ret = Video::createHardwareDevice(&hw_device_ctx, device);
×
214
  if(ret != 0)
×
215
    return {};
×
216

217
  if(hwAccel == AV_PIX_FMT_QSV)
×
218
    return {hw_device_ctx, codec};
×
219
  else
220
    return {hw_device_ctx, &detected_codec};
×
221
#else
222
  return {};
223
#endif
224
}
6 ✔
225

226
ReadFrame LibAVDecoder::enqueue_frame(const AVPacket* pkt) noexcept
606 ✔
227
{
228
  auto receive = [this]() -> ReadFrame
1,801 ✔
229
  {
230
    auto frame = m_frames.newFrame();
1,195 ✔
231
    auto read
232
        = receiveVideoFrame(
1,195 ✔
233
            m_codecContext, frame.get(), this->m_conf.ignorePTS, &m_missingTimestamps);
1,195 ✔
234
    if(read.error == AVERROR_EOF)
1,195 ✔
235
      m_finished = true;
11 ✔
236

237
    if(!read.frame)
1,195 ✔
238
    {
239
      m_frames.enqueue_decoding_error(frame.release());
606 ✔
240
      return read;
606 ✔
241
    }
242

243
    if(m_skipBefore != AV_NOPTS_VALUE && read.frame->pts != AV_NOPTS_VALUE)
589 ✔
244
    {
245
#if(LIBAVUTIL_VERSION_MAJOR < 58)
246
      const int64_t duration = read.frame->pkt_duration;
247
#else
248
      const int64_t duration = read.frame->duration;
164 ✔
249
#endif
250
      const int64_t span = duration > 0 ? duration : m_missingTimestamps.step;
164 ✔
251
      if(read.frame->pts + span <= m_skipBefore)
164 ✔
252
      {
253
        // Decoded, so that the frames after it can reference it, and dropped
254
        // like a frame with a negative timestamp.
255
        m_frames.enqueue_decoding_error(frame.release());
161 ✔
256
        return {nullptr, 0};
161 ✔
257
      }
258
      m_skipBefore = AV_NOPTS_VALUE;
3 ✔
259
    }
3 ✔
260

261
    if(m_rescale)
428 ✔
262
    {
UNCOV
263
      m_rescale.rescale(m_frames, frame, read);
×
UNCOV
264
    }
×
265
    else if(read.frame == frame.get())
428 ✔
266
    {
267
      frame.release();
428 ✔
268
    }
428 ✔
269

270
    return read;
428 ✔
271
  };
1,195 ✔
272

273
  ReadFrame last{nullptr, AVERROR(EAGAIN)};
606 ✔
274
  auto keepInOrder = [this, &last](ReadFrame read) {
1,034 ✔
275
    if(last.frame)
428 ✔
276
      m_frames.enqueue(last.frame);
43 ✔
277
    last = read;
428 ✔
278
  };
428 ✔
279

280
  // A decoder may refuse a new packet until every pending frame has been
281
  // received. Drain those frames and retry the exact same packet.
282
  for(;;)
606 ✔
283
  {
284
    const int ret = avcodec_send_packet(m_codecContext, pkt);
610 ✔
285
    if(ret == 0)
610 ✔
286
      break;
604 ✔
287
    if(ret != AVERROR(EAGAIN))
6 ✔
288
    {
289
      if(ret == AVERROR_EOF)
2 ✔
290
        m_finished = true;
2 ✔
291
      else
UNCOV
292
        qDebug() << "avcodec_send_packet: " << av_to_string(ret) << ret;
×
293
      return last.frame ? last : ReadFrame{nullptr, ret};
2 ✔
294
    }
295

296
    auto read = receive();
4 ✔
297
    if(read.frame)
4 ✔
298
    {
299
      keepInOrder(read);
2 ✔
300
      continue;
2 ✔
301
    }
302

303
    // error == 0 with no frame: a frame was decoded but discarded (negative
304
    // pts). The codec still made room, so the packet must be retried, not
305
    // dropped.
306
    if(read.error == 0)
2 ✔
307
      continue;
2 ✔
308

309
    // EAGAIN from send_packet guarantees receive_frame yields a frame; if it
310
    // does not, no progress is possible: bail out instead of spinning.
311
    return last.frame ? last : read;
×
312
  }
313

314
  // One packet can make more than one frame available. Receive all of them
315
  // before reading the next packet so inter-frame reference chains stay intact.
316
  for(;;)
604 ✔
317
  {
318
    auto read = receive();
1,191 ✔
319
    if(read.frame)
1,191 ✔
320
    {
321
      keepInOrder(read);
426 ✔
322
      continue;
426 ✔
323
    }
324
    // A decoded-but-discarded frame (negative pts) is not the end of the
325
    // available frames: keep draining.
326
    if(read.error == 0)
765 ✔
327
      continue;
161 ✔
328
    if(read.error != AVERROR(EAGAIN) && read.error != AVERROR_EOF)
604 ✔
UNCOV
329
      return last.frame ? last : read;
×
330
    break;
604 ✔
331
  }
332

333
  if(last.frame)
604 ✔
334
    last.error = 0;
385 ✔
335
  return last;
604 ✔
336
}
606 ✔
337

338
#if 0
339
static void listHardwareDecodeTextureFormats(AVFrame* frame)
340
{
341
#if LIBAVUTIL_VERSION_MAJOR >= 57
342
  AVPixelFormat* arr = {};
343
  av_hwframe_transfer_get_formats(
344
      frame->hw_frames_ctx,
345
      AVHWFrameTransferDirection::AV_HWFRAME_TRANSFER_DIRECTION_FROM, &arr, 0);
346
  for(auto p = arr; *p != AV_PIX_FMT_NONE; ++p)
347
  {
348
    auto desc = av_pix_fmt_desc_get(*p);
349
    if(desc)
350
      qDebug() << "supported format : " << desc->name;
351
  }
352
  av_free(arr);
353
#endif
354
}
355
#endif
356

357
// Mainly used for HAP which we do not want to decode through ffmpeg
UNCOV
358
void LibAVDecoder::load_packet_in_frame(const AVPacket& packet, AVFrame& frame)
×
359
{
UNCOV
360
  auto cp = m_avstream->codecpar;
×
361
  // TODO this is a hack, we store the FOURCC in the format...
362

UNCOV
363
  memcpy(&frame.format, &cp->codec_tag, 4);
×
364

UNCOV
365
  frame.buf[0] = av_buffer_ref(packet.buf);
×
UNCOV
366
  frame.width = cp->width;
×
UNCOV
367
  frame.height = cp->height;
×
UNCOV
368
  frame.format = (cp->codec_tag);
×
UNCOV
369
  frame.best_effort_timestamp = packet.pts;
×
UNCOV
370
  frame.data[0] = packet.data;
×
UNCOV
371
  frame.linesize[0] = packet.size;
×
UNCOV
372
  frame.pts = packet.pts;
×
UNCOV
373
  frame.pkt_dts = packet.dts;
×
374
#if(LIBAVUTIL_VERSION_MAJOR < 58)
375
  frame.pkt_duration = packet.duration;
376
#else
UNCOV
377
  frame.duration = packet.duration;
×
378
#endif
UNCOV
379
}
×
380

381
ReadFrame receiveVideoFrame(
1,195 ✔
382
    AVCodecContext* codecContext, AVFrame* frame, bool ignorePts,
383
    MissingTimestamps* missing)
384
{
385
  if(codecContext && frame)
1,195 ✔
386
  {
387
    int ret = avcodec_receive_frame(codecContext, frame);
1,195 ✔
388

389
    if(ret < 0)
1,195 ✔
390
    {
391
      return {nullptr, ret};
604 ✔
392
    }
393
    else
394
    {
395
      if(missing)
591 ✔
396
      {
397
        if(frame->pts == AV_NOPTS_VALUE)
591 ✔
398
          frame->pts = frame->best_effort_timestamp;
30 ✔
399
        // Without timestamps the demuxer's durations are unreliable too (raw
400
        // H.264 gives 1 tick after a byte seek): number by the frame rate.
401
        int64_t duration = missing->step;
591 ✔
402
        if(frame->pts == AV_NOPTS_VALUE)
591 ✔
403
        {
404
          frame->pts = missing->next;
30 ✔
405
#if(LIBAVUTIL_VERSION_MAJOR < 58)
406
          frame->pkt_duration = duration;
407
#else
408
          frame->duration = duration;
30 ✔
409
#endif
410
        }
30 ✔
411
        else
412
#if(LIBAVUTIL_VERSION_MAJOR < 58)
413
          duration = frame->pkt_duration > 0 ? frame->pkt_duration : missing->step;
414
#else
415
          duration = frame->duration > 0 ? frame->duration : missing->step;
561 ✔
416
#endif
417
        missing->next = frame->pts + duration;
591 ✔
418
      }
591 ✔
419

420
      if(ignorePts || frame->pts >= 0)
591 ✔
421
      {
422
#if LIBAVUTIL_VERSION_MAJOR >= 57
423
        // Transfer HW frame to CPU
424
        if(formatIsHardwareDecoded(AVPixelFormat(frame->format)))
589 ✔
425
        {
UNCOV
426
          AVFrame* sw_frame = av_frame_alloc();
×
UNCOV
427
          sw_frame->format = AV_PIX_FMT_NONE;
×
428

UNCOV
429
          int hw_ret = av_hwframe_transfer_data(sw_frame, frame, 0);
×
UNCOV
430
          if(hw_ret >= 0)
×
431
          {
432
            sw_frame->pts = frame->pts;
×
UNCOV
433
            av_frame_unref(frame);
×
UNCOV
434
            av_frame_move_ref(frame, sw_frame);
×
UNCOV
435
          }
×
UNCOV
436
          av_frame_free(&sw_frame);
×
UNCOV
437
          if(hw_ret < 0)
×
UNCOV
438
            return {nullptr, hw_ret};
×
UNCOV
439
        }
×
440
#endif
441
        return {frame, ret};
589 ✔
442
      }
443
      else
444
      {
445
        return {nullptr, ret};
2 ✔
446
      }
447
    }
448
  }
449

UNCOV
450
  return {nullptr, AVERROR_UNKNOWN};
×
451
}
1,195 ✔
452

453
VideoInterface::~VideoInterface() { }
299 ✔
454

455
VideoDecoder::VideoDecoder(DecoderConfiguration conf) noexcept
44 ✔
456
{
22 ✔
457
  m_conf = std::move(conf);
22 ✔
458
}
459

460
VideoDecoder::~VideoDecoder() noexcept
22 ✔
UNCOV
461
{
×
462
  close_file();
22 ✔
463
}
22 ✔
464

465
bool VideoDecoder::open(const std::string& inputFile) noexcept
22 ✔
466
{
467
  close_file();
22 ✔
468

469
  m_inputFile = inputFile;
22 ✔
470
  this->filePath = inputFile;
22 ✔
471

472
  if(avformat_open_input(&m_formatContext, inputFile.c_str(), nullptr, nullptr) != 0)
22 ✔
473
  {
474
    close_file();
16 ✔
475
    return false;
16 ✔
476
  }
477

478
  if(avformat_find_stream_info(m_formatContext, nullptr) < 0)
6 ✔
479
  {
UNCOV
480
    close_file();
×
UNCOV
481
    return false;
×
482
  }
483

484
  if(!open_stream())
6 ✔
485
  {
UNCOV
486
    close_file();
×
UNCOV
487
    return false;
×
488
  }
489

490
  // Elementary streams and truncated files have no known duration:
491
  // formatContext->duration stays AV_NOPTS_VALUE (INT64_MIN), and scaling
492
  // that to flicks is a signed overflow. Report 0, like "unknown".
493
  if(m_formatContext->duration == AV_NOPTS_VALUE || m_formatContext->duration < 0)
6 ✔
494
  {
495
    m_duration = 0;
1 ✔
496
  }
1 ✔
497
  else
498
  {
499
    int64_t secs = m_formatContext->duration / AV_TIME_BASE;
5 ✔
500
    int64_t us = m_formatContext->duration % AV_TIME_BASE;
5 ✔
501

502
    m_duration = secs * ossia::flicks_per_second<int64_t>;
5 ✔
503
    m_duration += us * ossia::flicks_per_millisecond<int64_t> / 1000;
5 ✔
504
  }
505

506
  return true;
6 ✔
507
}
22 ✔
508

509
bool VideoDecoder::load(const std::string& inputFile) noexcept
7 ✔
510
{
511
  if(!open(inputFile))
7 ✔
512
    return false;
2 ✔
513

514
  m_running.store(true, std::memory_order_release);
5 ✔
515
  // TODO use a thread pool
516
  m_thread = std::thread{[this] {
10 ✔
517
    ossia::set_thread_name("ossia video");
5 ✔
518
    this->buffer_thread();
5 ✔
519
  }};
5 ✔
520

521
  return true;
5 ✔
522
}
7 ✔
523

UNCOV
524
int64_t VideoDecoder::duration() const noexcept
×
525
{
UNCOV
526
  return m_duration;
×
527
}
528

529
void VideoDecoder::seek(int64_t flicks)
3 ✔
530
{
531
  m_seekTo = flicks;
3 ✔
532
  m_condVar.notify_one();
3 ✔
533
}
3 ✔
534

535
AVFrame* VideoDecoder::dequeue_frame() noexcept
2,214 ✔
536
{
537
  auto f = m_frames.discard_and_dequeue_one();
2,214 ✔
538
  if(f)
2,214 ✔
539
  {
540
    m_last_dequeued_pts = f->pts;
321 ✔
541
  }
321 ✔
542
  m_condVar.notify_one();
2,214 ✔
543
  return f;
2,214 ✔
544
}
545

546
void VideoDecoder::release_frame(AVFrame* frame) noexcept
321 ✔
547
{
548
  m_frames.release(frame);
321 ✔
549
}
321 ✔
550

551
void VideoDecoder::buffer_thread() noexcept
5 ✔
552
{
553
  while(m_running.load(std::memory_order_acquire))
291 ✔
554
  {
555
    if(int64_t seek = m_seekTo.exchange(-1); seek >= 0)
290 ✔
556
    {
557
      seek_impl(seek);
1 ✔
558
    }
1 ✔
559
    else
560
    {
561
      std::unique_lock lck{m_condMut};
289 ✔
562
      m_condVar.wait(lck, [&] {
1,365 ✔
563
        return (m_frames.size() < frames_to_buffer / 2 && !m_finished)
2,152 ✔
564
               || !m_running.load(std::memory_order_acquire) || (m_seekTo != -1);
1,076 ✔
565
      });
566
      if(!m_running.load(std::memory_order_acquire))
289 ✔
567
        return;
4 ✔
568

569
      if(int64_t seek = m_seekTo.exchange(-1); seek >= 0)
285 ✔
570
      {
571
        seek_impl(seek);
2 ✔
572
      }
2 ✔
573

574
      if(m_frames.size() < (frames_to_buffer / 2) && !m_finished)
285 ✔
575
      {
576
        if(auto f = read_frame_impl())
285 ✔
577
        {
578
          m_frames.enqueue(f);
279 ✔
579
        }
279 ✔
580
        std::this_thread::sleep_for(std::chrono::milliseconds(4));
285 ✔
581
      }
285 ✔
582
    }
289 ✔
583
  }
584
}
5 ✔
585

586
void VideoDecoder::close_file() noexcept
60 ✔
587
{
588
  // Stop the running status
589
  m_running.store(false, std::memory_order_release);
60 ✔
590
  m_condVar.notify_one();
60 ✔
591

592
  if(m_thread.joinable())
60 ✔
593
    m_thread.join();
5 ✔
594

595
  // Remove frames that were in flight
596
  m_frames.drain();
60 ✔
597

598
  // Clear the stream
599
  close_video();
60 ✔
600

601
  // Clear the fmt context
602
  if(m_formatContext)
60 ✔
603
  {
604
    // avformat_close_input() already frees the context and sets it to nullptr;
605
    // do NOT also call avformat_free_context() on it (double free).
606
    avformat_close_input(&m_formatContext);
6 ✔
607
    m_formatContext = nullptr;
6 ✔
608
  }
6 ✔
609
}
60 ✔
610

UNCOV
611
ReadFrame LibAVDecoder::read_one_frame_raw(AVPacket& packet)
×
612
{
UNCOV
613
  int res{};
×
614

UNCOV
615
  while((res = av_read_frame(m_formatContext, &packet)) >= 0)
×
616
  {
UNCOV
617
    if(packet.stream_index == m_avstream->index)
×
618
    {
UNCOV
619
      auto frame = m_frames.newFrame();
×
UNCOV
620
      if(frame->buf[0])
×
621
        av_buffer_unref(&frame->buf[0]);
×
622
      // Mainly for HAP: we feed the raw undecoded codec data directly to the GPU, see HAPDecoder
623
      load_packet_in_frame(packet, *frame);
×
624

625
      av_packet_unref(&packet);
×
626
      return {frame.release(), 0};
×
627
    }
×
628
    else
629
    {
UNCOV
630
      av_packet_unref(&packet);
×
631
    }
632
  }
633

634
  // A file that ends in garbage (truncation, an interrupted transcode) makes
635
  // av_read_frame return AVERROR_INVALIDDATA & co forever instead of EOF.
636
  // Either way no more packets will ever come: finish, like ffplay does —
637
  // otherwise buffer_thread retries this error at full tilt for the rest of
638
  // the process's life.
UNCOV
639
  if(res < 0 && res != AVERROR(EAGAIN))
×
640
  {
UNCOV
641
    m_finished = true;
×
UNCOV
642
  }
×
UNCOV
643
  av_packet_unref(&packet);
×
UNCOV
644
  return {nullptr, res};
×
UNCOV
645
}
×
646

647
ReadFrame LibAVDecoder::read_one_frame_avcodec(AVPacket& packet)
288 ✔
648
{
649
  ReadFrame ret_frame;
288 ✔
650
  int res{};
288 ✔
651

652
  int z = 0;
288 ✔
653
do_read_frame:
654
  av_packet_unref(&packet);
497 ✔
655
  while((res = av_read_frame(m_formatContext, &packet)) >= 0)
497 ✔
656
  {
657
    if(packet.stream_index == m_avstream->index)
490 ✔
658
    {
659
      SCORE_ASSERT(m_codecContext);
490 ✔
660
      if(packet.pts != AV_NOPTS_VALUE && packet.dts != AV_NOPTS_VALUE)
490 ✔
661
        m_ptsLead = std::max(m_ptsLead, packet.pts - packet.dts);
460 ✔
662

663
      //av_packet_rescale_ts(
664
      //     &packet, this->m_avstream->time_base, this->m_codecContext->pkt_timebase);
665

666
      ret_frame = enqueue_frame(&packet);
490 ✔
667
      if(ret_frame.error == AVERROR(EAGAIN))
490 ✔
668
      {
669
        if(z++ < 100)
209 ✔
670
          goto do_read_frame;
209 ✔
UNCOV
671
      }
×
672
      av_packet_unref(&packet);
281 ✔
673
      return ret_frame;
281 ✔
674
    }
675
    else
676
    {
UNCOV
677
      av_packet_unref(&packet);
×
678
    }
679
  }
680

681
  // AVERROR_EOF, or a persistent demux error: a truncated or corrupt tail
682
  // makes av_read_frame return AVERROR_INVALIDDATA & co forever, never EOF.
683
  // Either way no more packets will ever come, so both are the end of the
684
  // stream, like ffplay treats them — otherwise buffer_thread retries the
685
  // error at full tilt forever and the frames still buffered inside the
686
  // decoder are never shown.
687
  if(res < 0 && res != AVERROR(EAGAIN))
7 ✔
688
  {
689
    // Flush codec to get remaining frames from the reorder buffer (B-frames)
690
    if(m_codecContext)
7 ✔
691
    {
692
      // enqueue_frame routes every drained frame through the rescaler, like
693
      // every other decode path: these are the last frames of the clip, and a
694
      // decoder whose pixel_format was relabelled RGBA by init_scaler must
695
      // not suddenly emit its native format for them.
696
      auto flushed = enqueue_frame(nullptr);
7 ✔
697
      if(flushed.frame)
7 ✔
698
        m_frames.enqueue(flushed.frame);
6 ✔
699
    }
7 ✔
700
    m_finished = true;
7 ✔
701
  }
7 ✔
702
  av_packet_unref(&packet);
7 ✔
703
  return {nullptr, res};
7 ✔
704
}
288 ✔
705

706
ReadFrame LibAVDecoder::read_one_frame(AVPacket& packet)
288 ✔
707
{
708
  if(m_conf.useAVCodec)
288 ✔
709
    return read_one_frame_avcodec(packet);
288 ✔
710
  else
UNCOV
711
    return read_one_frame_raw(packet);
×
712
}
288 ✔
713
/*
714
// https://stackoverflow.com/a/44468529/1495627
715
static
716
int seek_to_frame(AVFormatContext* format, AVStream* stream, int frameIndex)
717
{
718
  using namespace std;
719
  // Seek is done on packet dts
720
  int64_t target_dts_usecs = std::round(frameIndex * (double)stream->r_frame_rate.den / stream->r_frame_rate.num * AV_TIME_BASE);
721
  // Remove first dts: when non zero seek should be more accurate
722
  auto first_dts_usecs = std::round(stream->first_dts * (double)stream->time_base.num / stream->time_base.den * AV_TIME_BASE);
723
  target_dts_usecs += first_dts_usecs;
724
  return av_seek_frame(format, -1, target_dts_usecs, AVSEEK_FLAG_BACKWARD);
725
}
726
*/
727

728
bool VideoDecoder::seek_impl(int64_t flicks) noexcept
3 ✔
729
{
730
  if(m_avstream->index >= int(m_formatContext->nb_streams))
3 ✔
UNCOV
731
    return false;
×
732

733
  // `flicks` is playback time; the stream's timestamps start at start_pts.
734
  const AVRational stream_tb = m_avstream->time_base;
3 ✔
735

736
  // A time past the end shows the last frame.
737
  if(m_duration > 0 && flicks >= m_duration)
3 ✔
738
    flicks = std::max<int64_t>(
1 ✔
739
        0, m_duration - av_rescale_q(m_missingTimestamps.step, stream_tb, flicks_time_base));
1 ✔
740

741
  const int64_t target = flicksToPts(flicks, stream_tb, start_pts);
3 ✔
742
  const int64_t absolute_flicks
3 ✔
743
      = flicks + av_rescale_q(start_pts, stream_tb, flicks_time_base);
3 ✔
744

745
  constexpr auto av_tb = AVRational{1, AV_TIME_BASE};
3 ✔
746

747
  // No seek for a target less than 0.2 s ahead of the last frame taken: the
748
  // frames already queued reach it. Behind it they never would.
749
  const int64_t last = m_last_dequeued_pts;
3 ✔
750
  if(last != AV_NOPTS_VALUE && flicks != 0 && target >= last
3 ✔
751
     && av_rescale_q(target - last, stream_tb, av_tb) <= (av_tb.den / 5) / av_tb.num)
2 ✔
UNCOV
752
    return false;
×
753

754
  // A stream without timestamps cannot be sought by time: it is restarted by
755
  // bytes, numbered from its beginning, and the frames before the target are
756
  // skipped below.
757
  const bool no_timestamps = m_formatContext->iformat->flags & AVFMT_NOTIMESTAMPS;
3 ✔
758
  auto seek_to = [&](int64_t abs_flicks) {
6 ✔
759
    if(no_timestamps
3 ✔
760
       || !ossia::seek_to_flick(m_formatContext, m_codecContext, m_avstream, abs_flicks))
3 ✔
761
    {
762
      if(av_seek_frame(m_formatContext, m_avstream->index, 0, AVSEEK_FLAG_BYTE) < 0)
×
UNCOV
763
        return false;
×
UNCOV
764
      if(m_codecContext)
×
UNCOV
765
        avcodec_flush_buffers(m_codecContext);
×
UNCOV
766
      m_missingTimestamps.next = start_pts;
×
767
    }
×
768
    return true;
3 ✔
769
  };
3 ✔
770

771
  auto read_first = [&] {
6 ✔
772
    ReadFrame r;
3 ✔
773
    do
3 ✔
774
    {
775
      if(r.frame)
3 ✔
776
      {
UNCOV
777
        SCORE_LIBAV_FRAME_DEALLOC_CHECK(r.frame);
×
UNCOV
778
        av_frame_free(&r.frame);
×
UNCOV
779
      }
×
780

781
      auto pkt = av_packet_alloc();
3 ✔
782
      r = read_one_frame(*pkt);
3 ✔
783
      av_packet_unref(pkt);
3 ✔
784
      av_packet_free(&pkt);
3 ✔
785
      // A newer seek makes reaching this target pointless.
786
    } while(r.error == AVERROR(EAGAIN) && m_seekTo.load(std::memory_order_relaxed) < 0);
3 ✔
787
    return r;
3 ✔
788
  };
789

790
  // The frames between the keyframe the demuxer lands on and the target are
791
  // decoded and dropped here rather than queued: queued, the reader would
792
  // show them, late, one after the other, until it reached the target.
793
  m_skipBefore = target;
3 ✔
794
  struct reset_skip
795
  {
796
    int64_t& skip;
797
    ~reset_skip() { skip = AV_NOPTS_VALUE; }
3 ✔
798
  } reset_skip_on_exit{m_skipBefore};
3 ✔
799

800
  // Every frame enqueued from here on is after the seek; the reader drops
801
  // the ones before, held back or still queued.
802
  const int generation = m_frames.start_generation();
3 ✔
803
  const int64_t lead_flicks = av_rescale_q(m_ptsLead, stream_tb, flicks_time_base);
3 ✔
804
  if(!seek_to(absolute_flicks - lead_flicks))
3 ✔
805
  {
UNCOV
806
    qDebug() << "Failed to seek for time ";
×
UNCOV
807
    seek_generation.store(generation, std::memory_order_release);
×
UNCOV
808
    return false;
×
809
  }
810

811
  // A demuxer seeking on dts (MPEG-TS, MPEG-PS) can land on a frame shown
812
  // after the target while m_ptsLead is not yet known: back off until the
813
  // first frame is not later. A video starting after its container
814
  // legitimately shows its first frame after an earlier target. Frames queued
815
  // by a retry are discarded by the consumer up to the frame marked below.
816
  const int64_t landing = m_avstream->start_time != AV_NOPTS_VALUE
6 ✔
817
                              ? std::max(target, m_avstream->start_time)
3 ✔
UNCOV
818
                              : target;
×
819
  ReadFrame r = read_first();
3 ✔
820
  int64_t back = 0;
3 ✔
821
  for(int attempt = 0; attempt < 6 && r.frame && r.frame->pts != AV_NOPTS_VALUE
5 ✔
822
                       && r.frame->pts > landing && absolute_flicks - back > 0;
2 ✔
UNCOV
823
      attempt++)
×
824
  {
825
    SCORE_LIBAV_FRAME_DEALLOC_CHECK(r.frame);
×
UNCOV
826
    av_frame_free(&r.frame);
×
827
    back = back ? back * 2
×
828
                : 2 * av_rescale_q(m_missingTimestamps.step, stream_tb, flicks_time_base);
×
UNCOV
829
    if(!seek_to(std::max<int64_t>(0, absolute_flicks - lead_flicks - back)))
×
UNCOV
830
      break;
×
UNCOV
831
    m_skipBefore = target;
×
UNCOV
832
    r = read_first();
×
UNCOV
833
  }
×
834
  // The end came before the target, the container's duration being longer
835
  // than the stream: from the keyframe, everything up to the end is shown.
836
  if(m_skipBefore != AV_NOPTS_VALUE && r.error == AVERROR_EOF)
3 ✔
837
  {
UNCOV
838
    m_skipBefore = AV_NOPTS_VALUE;
×
UNCOV
839
    if(seek_to(absolute_flicks - lead_flicks))
×
UNCOV
840
      r = read_first();
×
UNCOV
841
  }
×
842
  while(no_timestamps && r.frame && r.frame->pts + m_missingTimestamps.step <= target)
3 ✔
843
  {
UNCOV
844
    SCORE_LIBAV_FRAME_DEALLOC_CHECK(r.frame);
×
UNCOV
845
    av_frame_free(&r.frame);
×
UNCOV
846
    r = read_first();
×
847
  }
848

849
  if(r.frame)
3 ✔
850
  {
851
    // Enqueue BEFORE publishing the discard marker. Otherwise the GFX thread's
852
    // discard_and_dequeue* can observe the marker for a frame not yet in
853
    // `available`, drain the queue and return r.frame as current while the
854
    // decoder still owns it and is about to enqueue it → double ownership /
855
    // UAF of the pixels a live zero-copy GPU upload references. With this
856
    // order the marker is only ever visible once its frame is already in the
857
    // queue, and the consumer falls through to a normal dequeue when the
858
    // marker frame isn't found.
859
    m_frames.enqueue(r.frame);
2 ✔
860
    m_frames.set_discard_frame(r.frame);
2 ✔
861
  }
2 ✔
862
  else
863
  {
864
    SCORE_LIBAV_FRAME_DEALLOC_CHECK(r.frame);
1 ✔
865
    av_frame_free(&r.frame);
1 ✔
866
  }
867

868
  m_finished = false;
3 ✔
869
  seek_generation.store(generation, std::memory_order_release);
3 ✔
870

871
  return true;
3 ✔
872
}
3 ✔
873

874
AVFrame* VideoDecoder::read_frame_impl() noexcept
285 ✔
875
{
876
  ReadFrame res;
285 ✔
877

878
  if(m_avstream)
285 ✔
879
  {
880
    auto packet = av_packet_alloc();
285 ✔
881

882
    do
285 ✔
883
    {
884
      av_packet_unref(packet);
285 ✔
885
      res = read_one_frame(*packet);
285 ✔
886

887
      if(res.error == AVERROR_EOF)
285 ✔
888
      {
889
        m_finished = true;
6 ✔
890
        av_packet_unref(packet);
6 ✔
891
        av_packet_free(&packet);
6 ✔
892
        return res.frame;
6 ✔
893
      }
894
    } while(res.error == AVERROR(EAGAIN));
279 ✔
895

896
    av_packet_unref(packet);
279 ✔
897
    av_packet_free(&packet);
279 ✔
898
  }
279 ✔
899
  return res.frame;
279 ✔
900
}
285 ✔
901

902
bool VideoDecoder::open_stream() noexcept
6 ✔
903
{
904
  bool res = false;
6 ✔
905

906
  if(!m_formatContext)
6 ✔
UNCOV
907
    return res;
×
908

909
  int stream = -1;
6 ✔
910

911
  for(unsigned int i = 0; i < m_formatContext->nb_streams; i++)
12 ✔
912
  {
913
    if(m_formatContext->streams[i]->codecpar->codec_type == AVMEDIA_TYPE_VIDEO)
6 ✔
914
    {
915
      if(stream == -1)
6 ✔
916
      {
917
        stream = i;
6 ✔
918
        continue;
6 ✔
919
      }
UNCOV
920
    }
×
UNCOV
921
    m_formatContext->streams[i]->discard = AVDISCARD_ALL;
×
UNCOV
922
  }
×
923

924
  if(stream != -1)
6 ✔
925
  {
926
    m_avstream = m_formatContext->streams[stream];
6 ✔
927
    const AVRational tb = m_avstream->time_base;
6 ✔
928
    {
929
      const AVRational rate = m_avstream->avg_frame_rate.num > 0
6 ✔
930
                                  ? m_avstream->avg_frame_rate
6 ✔
931
                                  : m_avstream->r_frame_rate;
×
932
      start_pts = playbackStartPts(*m_formatContext, *m_avstream);
6 ✔
933
      time_base = tb;
6 ✔
934
      m_missingTimestamps = {};
6 ✔
935
      m_missingTimestamps.next = start_pts;
936
      if(rate.num > 0 && rate.den > 0)
6 ✔
937
        m_missingTimestamps.step
12 ✔
938
            = std::max<int64_t>(1, av_rescale_q(1, av_inv_q(rate), tb));
6 ✔
939
    }
940
    dts_per_flicks = (tb.den / (tb.num * ossia::flicks_per_second<double>));
6 ✔
941
    flicks_per_dts = (tb.num * ossia::flicks_per_second<double>) / tb.den;
6 ✔
942

943
    auto codecPar = m_avstream->codecpar;
6 ✔
944
    if((m_codec = avcodec_find_decoder(codecPar->codec_id)))
6 ✔
945
    {
946
      if(codecPar->width <= 0 || codecPar->height <= 0)
6 ✔
947
      {
UNCOV
948
        qDebug() << "VideoDecoder: invalid video: width or height is 0";
×
UNCOV
949
        res = false;
×
UNCOV
950
      }
×
951
      else
952
      {
953
        color_range = codecPar->color_range;
6 ✔
954
        color_primaries = codecPar->color_primaries;
6 ✔
955
        color_trc = codecPar->color_trc;
6 ✔
956
        color_space = codecPar->color_space;
6 ✔
957
        chroma_location = codecPar->chroma_location;
6 ✔
958

959
        // Detect wide-gamut / HDR evidence from primaries and transfer function.
960
        // This is used to infer color_space when it is unspecified.
961
        const bool has_bt2020_evidence =
6 ✔
962
            color_primaries == AVCOL_PRI_BT2020
6 ✔
963
            || color_trc == AVCOL_TRC_SMPTE2084      // PQ (HDR10 / BT.2100)
6 ✔
964
            || color_trc == AVCOL_TRC_ARIB_STD_B67;   // HLG (BT.2100)
6 ✔
965

966
        // Display P3 content may use BT.709 matrix coefficients
967
        // but with wider primaries. Don't force it to BT.2020.
968
        const bool has_p3_evidence =
6 ✔
969
            color_primaries == AVCOL_PRI_SMPTE432     // Display P3 (D65)
6 ✔
970
            || color_primaries == AVCOL_PRI_SMPTE431; // DCI-P3
6 ✔
971

972
        if(color_space == AVCOL_SPC_UNSPECIFIED)
6 ✔
973
        {
974
          if(has_bt2020_evidence)
4 ✔
UNCOV
975
            color_space = AVCOL_SPC_BT2020_NCL;
×
976
          else if(has_p3_evidence)
4 ✔
977
            // P3 content typically uses BT.709 matrix coefficients.
978
            // colorMatrix() will detect the P3 primaries and route
979
            // through the Display P3 pipeline.
UNCOV
980
            color_space = AVCOL_SPC_BT709;
×
981
          else if(codecPar->height < 625)
4 ✔
982
            color_space = AVCOL_SPC_SMPTE170M;
4 ✔
983
          else if(codecPar->height < 720)
×
984
            color_space = AVCOL_SPC_BT470BG;
×
985
          else
UNCOV
986
            color_space = AVCOL_SPC_BT709;
×
987
        }
4 ✔
988
        if(color_range == AVCOL_RANGE_UNSPECIFIED)
6 ✔
989
          color_range = AVCOL_RANGE_MPEG;
4 ✔
990

991
        // HDR handling
992
#if LIBAVCODEC_VERSION_INT >= AV_VERSION_INT(61, 3, 100)
993
        {
994
          const auto data = codecPar->coded_side_data;
995
          const auto n = codecPar->nb_coded_side_data;
996
          // Light data
997
          if(auto sd = av_packet_side_data_get(data, n, AV_PKT_DATA_CONTENT_LIGHT_LEVEL))
998
            if(sd->data)
999
              this->content_light = *reinterpret_cast<const AVContentLightMetadata*>(sd->data);
1000

1001
          // Mastering side data
1002
          if (auto sd = av_packet_side_data_get(data, n, AV_PKT_DATA_MASTERING_DISPLAY_METADATA))
1003
            if(sd->data)
1004
              this->mastering_display = *(AVMasteringDisplayMetadata *)sd->data;
1005
        }
1006
#endif
1007

1008
        codec_id = codecPar->codec_id;
6 ✔
1009

1010
        // Check if this is a GPU-direct codec (HAP or DXV DXT1/DXT5)
1011
        bool use_gpu_direct = false;
6 ✔
1012
        if(m_avstream->codecpar->codec_id == AV_CODEC_ID_HAP)
6 ✔
1013
        {
1014
          // HAP: store the FOURCC in the format for GPU decoder matching
UNCOV
1015
          memcpy(&pixel_format, &m_avstream->codecpar->codec_tag, 4);
×
1016
          use_gpu_direct = true;
×
UNCOV
1017
        }
×
1018
        else if(m_avstream->codecpar->codec_id == AV_CODEC_ID_DXV)
6 ✔
1019
        {
1020
          // DXV: peek first packet to determine sub-format (DXT1/DXT5)
1021
          // Store synthetic fourcc in pixel_format for GPU decoder matching
UNCOV
1022
          auto packet = av_packet_alloc();
×
1023
          if(av_read_frame(m_formatContext, packet) >= 0 && packet->size >= 4)
×
1024
          {
UNCOV
1025
            uint32_t tag = packet->data[0] | (packet->data[1] << 8)
×
UNCOV
1026
                           | (packet->data[2] << 16)
×
UNCOV
1027
                           | ((uint32_t)packet->data[3] << 24);
×
1028
            switch(tag)
×
1029
            {
1030
              case 0x44585431: // MKBETAG('D','X','T','1')
UNCOV
1031
                memcpy(&pixel_format, "Dxv1", 4);
×
1032
                use_gpu_direct = true;
×
1033
                break;
×
1034
              case 0x44585435: // MKBETAG('D','X','T','5')
1035
                memcpy(&pixel_format, "Dxv5", 4);
×
1036
                use_gpu_direct = true;
×
UNCOV
1037
                break;
×
1038
              case 0x59434736: // MKBETAG('Y','C','G','6')
UNCOV
1039
                memcpy(&pixel_format, "DxvY", 4);
×
UNCOV
1040
                use_gpu_direct = true;
×
UNCOV
1041
                break;
×
1042
              case 0x59473130: // MKBETAG('Y','G','1','0')
UNCOV
1043
                memcpy(&pixel_format, "DxvA", 4);
×
UNCOV
1044
                use_gpu_direct = true;
×
UNCOV
1045
                break;
×
1046
              default: {
1047
                // Old format: check type flags in high byte
UNCOV
1048
                uint8_t old_type = tag >> 24;
×
UNCOV
1049
                if(old_type & 0x40)
×
1050
                {
UNCOV
1051
                  memcpy(&pixel_format, "Dxv5", 4);
×
UNCOV
1052
                  use_gpu_direct = true;
×
UNCOV
1053
                }
×
UNCOV
1054
                else if(old_type & 0x20)
×
1055
                {
UNCOV
1056
                  memcpy(&pixel_format, "Dxv1", 4);
×
UNCOV
1057
                  use_gpu_direct = true;
×
UNCOV
1058
                }
×
1059
                // Unknown old format falls through to avcodec
UNCOV
1060
                break;
×
1061
              }
1062
            }
UNCOV
1063
            av_packet_unref(packet);
×
UNCOV
1064
          }
×
UNCOV
1065
          av_packet_free(&packet);
×
1066
          // Seek back to beginning regardless
UNCOV
1067
          av_seek_frame(m_formatContext, m_avstream->index, 0, AVSEEK_FLAG_BACKWARD);
×
UNCOV
1068
        }
×
1069

1070
        if(use_gpu_direct)
6 ✔
1071
        {
1072
          width = codecPar->width;
×
1073
          height = codecPar->height;
×
UNCOV
1074
          fps = av_q2d(m_avstream->avg_frame_rate);
×
1075

UNCOV
1076
          m_conf.useAVCodec = false;
×
UNCOV
1077
          m_codecContext = nullptr;
×
UNCOV
1078
          m_codec = nullptr;
×
UNCOV
1079
          res = true;
×
UNCOV
1080
        }
×
1081
        else
1082
        {
1083
          pixel_format = (AVPixelFormat)codecPar->format;
6 ✔
1084
          width = codecPar->width;
6 ✔
1085
          height = codecPar->height;
6 ✔
1086
          fps = av_q2d(m_avstream->avg_frame_rate);
6 ✔
1087

1088
          res = open_codec_context(*this, m_avstream, [this](AVCodecContext& ctx) {
12 ✔
1089
            ctx.framerate
6 ✔
1090
                = av_guess_frame_rate(m_formatContext, (AVStream*)m_avstream, NULL);
12 ✔
1091
            m_codecContext->pkt_timebase = m_avstream->time_base;
6 ✔
1092
            // m_codecContext->codec_id = m_codec->id;
1093
          });
6 ✔
1094

1095
          if(m_codecContext)
6 ✔
1096
          {
1097
            auto tb = m_codecContext->pkt_timebase;
6 ✔
1098
            dts_per_flicks = (tb.den / (tb.num * ossia::flicks_per_second<double>));
6 ✔
1099
            flicks_per_dts = (tb.num * ossia::flicks_per_second<double>) / tb.den;
6 ✔
1100
          }
6 ✔
1101
        }
1102
      }
1103
    }
6 ✔
1104
  }
6 ✔
1105

1106
  if(res && m_avstream)
6 ✔
1107
  {
1108
    const auto probe
1109
        = classifyFrameAccess(*m_formatContext, *m_avstream, m_inputFile.c_str());
6 ✔
1110
    frame_access = probe.access;
6 ✔
1111
    max_keyframe_gap = probe.max_gap;
6 ✔
1112
  }
6 ✔
1113
  else
1114
  {
UNCOV
1115
    frame_access = FrameAccess::Unknown;
×
UNCOV
1116
    max_keyframe_gap = -1;
×
UNCOV
1117
    close_video();
×
1118
  }
1119
  return res;
6 ✔
1120
}
6 ✔
1121

1122
void VideoDecoder::close_video() noexcept
60 ✔
1123
{
1124
  if(m_codecContext)
60 ✔
1125
  {
1126
    avcodec_flush_buffers(m_codecContext);
6 ✔
1127
#if defined(__APPLE__)
1128
#if FF_API_VT_HWACCEL_CONTEXT
1129
    if(m_codecContext->hwaccel_context)
1130
      av_videotoolbox_default_free(m_codecContext);
1131
#endif
1132
#endif
1133
    avcodec_free_context(&m_codecContext);
6 ✔
1134

1135
    m_codecContext = nullptr;
6 ✔
1136
    m_codec = nullptr;
6 ✔
1137
  }
6 ✔
1138

1139
  m_rescale.close();
60 ✔
1140

1141
  m_avstream = nullptr;
60 ✔
1142
}
60 ✔
1143
}
1144
#endif
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE TRIAL · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc