Coverage Report

Created: 2026-07-25 07:52

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/ffmpeg/libavformat/imfdec.c
Line
Count
Source
1
/*
2
 * This file is part of FFmpeg.
3
 *
4
 * FFmpeg is free software; you can redistribute it and/or
5
 * modify it under the terms of the GNU Lesser General Public
6
 * License as published by the Free Software Foundation; either
7
 * version 2.1 of the License, or (at your option) any later version.
8
 *
9
 * FFmpeg is distributed in the hope that it will be useful,
10
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12
 * Lesser General Public License for more details.
13
 *
14
 * You should have received a copy of the GNU Lesser General Public
15
 * License along with FFmpeg; if not, write to the Free Software
16
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
17
 */
18
19
/*
20
 *
21
 * Copyright (c) Sandflow Consulting LLC
22
 *
23
 * Redistribution and use in source and binary forms, with or without
24
 * modification, are permitted provided that the following conditions are met:
25
 *
26
 * * Redistributions of source code must retain the above copyright notice, this
27
 *   list of conditions and the following disclaimer.
28
 * * Redistributions in binary form must reproduce the above copyright notice,
29
 *   this list of conditions and the following disclaimer in the documentation
30
 *   and/or other materials provided with the distribution.
31
 *
32
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
33
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
34
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
35
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
36
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
37
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
38
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
39
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
40
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
41
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
42
 * POSSIBILITY OF SUCH DAMAGE.
43
 */
44
45
/**
46
 * Demuxes an IMF Composition
47
 *
48
 * References
49
 * OV 2067-0:2018 - SMPTE Overview Document - Interoperable Master Format
50
 * ST 2067-2:2020 - SMPTE Standard - Interoperable Master Format — Core Constraints
51
 * ST 2067-3:2020 - SMPTE Standard - Interoperable Master Format — Composition Playlist
52
 * ST 2067-5:2020 - SMPTE Standard - Interoperable Master Format — Essence Component
53
 * ST 2067-20:2016 - SMPTE Standard - Interoperable Master Format — Application #2
54
 * ST 2067-21:2020 - SMPTE Standard - Interoperable Master Format — Application #2 Extended
55
 * ST 2067-102:2017 - SMPTE Standard - Interoperable Master Format — Common Image Pixel Color Schemes
56
 * ST 429-9:2007 - SMPTE Standard - D-Cinema Packaging — Asset Mapping and File Segmentation
57
 *
58
 * @author Marc-Antoine Arnaud
59
 * @author Valentin Noel
60
 * @author Nicholas Vanderzwet
61
 * @file
62
 * @ingroup lavu_imf
63
 */
64
65
#include "avio_internal.h"
66
#include "demux.h"
67
#include "imf.h"
68
#include "internal.h"
69
#include "libavcodec/packet.h"
70
#include "libavutil/avstring.h"
71
#include "libavutil/bprint.h"
72
#include "libavutil/intreadwrite.h"
73
#include "libavutil/mem.h"
74
#include "libavutil/opt.h"
75
#include <inttypes.h>
76
#include <libxml/parser.h>
77
78
0
#define AVRATIONAL_FORMAT "%d/%d"
79
0
#define AVRATIONAL_ARG(rational) rational.num, rational.den
80
81
/**
82
 * IMF Asset locator
83
 */
84
typedef struct IMFAssetLocator {
85
    AVUUID uuid;
86
    char *absolute_uri;
87
} IMFAssetLocator;
88
89
/**
90
 * IMF Asset locator map
91
 * Results from the parsing of one or more ASSETMAP XML files
92
 */
93
typedef struct IMFAssetLocatorMap {
94
    uint32_t asset_count;
95
    IMFAssetLocator *assets;
96
} IMFAssetLocatorMap;
97
98
typedef struct IMFVirtualTrackResourcePlaybackCtx {
99
    IMFAssetLocator *locator;          /**< Location of the resource */
100
    FFIMFTrackFileResource *resource;  /**< Underlying IMF CPL resource */
101
    AVFormatContext *ctx;              /**< Context associated with the resource */
102
    AVRational start_time;             /**< inclusive start time of the resource on the CPL timeline (s) */
103
    AVRational end_time;               /**< exclusive end time of the resource on the CPL timeline (s) */
104
    AVRational ts_offset;              /**< start_time minus the entry point into the resource (s) */
105
} IMFVirtualTrackResourcePlaybackCtx;
106
107
typedef struct IMFVirtualTrackPlaybackCtx {
108
    int32_t index;                                 /**< Track index in playlist */
109
    AVRational current_timestamp;                  /**< Current temporal position */
110
    AVRational duration;                           /**< Overall duration */
111
    uint32_t resource_count;                       /**< Number of resources (<= INT32_MAX) */
112
    unsigned int resources_alloc_sz;               /**< Size of the buffer holding the resource */
113
    IMFVirtualTrackResourcePlaybackCtx *resources; /**< Buffer holding the resources */
114
    int32_t current_resource_index;                /**< Index of the current resource in resources,
115
                                                        or < 0 if a current resource has yet to be selected */
116
} IMFVirtualTrackPlaybackCtx;
117
118
typedef struct IMFContext {
119
    const AVClass *class;
120
    const char *base_url;
121
    char *asset_map_paths;
122
    AVIOInterruptCB *interrupt_callback;
123
    AVDictionary *avio_opts;
124
    FFIMFCPL *cpl;
125
    IMFAssetLocatorMap asset_locator_map;
126
    uint32_t track_count;
127
    IMFVirtualTrackPlaybackCtx **tracks;
128
} IMFContext;
129
130
static int imf_uri_is_url(const char *string)
131
0
{
132
0
    return strstr(string, "://") != NULL;
133
0
}
134
135
static int imf_uri_is_unix_abs_path(const char *string)
136
0
{
137
0
    return string[0] == '/';
138
0
}
139
140
static int imf_uri_is_dos_abs_path(const char *string)
141
0
{
142
    /* Absolute path case: `C:\path\to\somewhere` */
143
0
    if (string[1] == ':' && string[2] == '\\')
144
0
        return 1;
145
146
    /* Absolute path case: `C:/path/to/somewhere` */
147
0
    if (string[1] == ':' && string[2] == '/')
148
0
        return 1;
149
150
    /* Network path case: `\\path\to\somewhere` */
151
0
    if (string[0] == '\\' && string[1] == '\\')
152
0
        return 1;
153
154
0
    return 0;
155
0
}
156
157
static int imf_time_to_ts(int64_t *ts, AVRational t, AVRational time_base)
158
0
{
159
0
    int dst_num;
160
0
    int dst_den;
161
0
    AVRational r;
162
163
0
    r = av_div_q(t, time_base);
164
165
0
    if ((av_reduce(&dst_num, &dst_den, r.num, r.den, INT64_MAX) != 1))
166
0
        return 1;
167
168
0
    if (dst_den != 1)
169
0
        return 1;
170
171
0
    *ts = dst_num;
172
173
0
    return 0;
174
0
}
175
176
/**
177
 * Parse a ASSETMAP XML file to extract the UUID-URI mapping of assets.
178
 * @param s the current format context, if any (can be NULL).
179
 * @param doc the XML document to be parsed.
180
 * @param asset_map pointer on the IMFAssetLocatorMap to fill.
181
 * @param base_url the url of the asset map XML file, if any (can be NULL).
182
 * @return a negative value in case of error, 0 otherwise.
183
 */
184
static int parse_imf_asset_map_from_xml_dom(AVFormatContext *s,
185
                                            xmlDocPtr doc,
186
                                            IMFAssetLocatorMap *asset_map,
187
                                            const char *base_url)
188
0
{
189
0
    xmlNodePtr asset_map_element = NULL;
190
0
    xmlNodePtr node = NULL;
191
0
    xmlNodePtr asset_element = NULL;
192
0
    unsigned long elem_count;
193
0
    char *uri;
194
0
    int ret = 0;
195
0
    IMFAssetLocator *asset = NULL;
196
0
    void *tmp;
197
198
0
    asset_map_element = xmlDocGetRootElement(doc);
199
200
0
    if (!asset_map_element) {
201
0
        av_log(s, AV_LOG_ERROR, "Unable to parse asset map XML - missing root node\n");
202
0
        return AVERROR_INVALIDDATA;
203
0
    }
204
205
0
    if (asset_map_element->type != XML_ELEMENT_NODE || av_strcasecmp(asset_map_element->name, "AssetMap")) {
206
0
        av_log(s, AV_LOG_ERROR, "Unable to parse asset map XML - wrong root node name[%s] type[%d]\n",
207
0
               asset_map_element->name, (int)asset_map_element->type);
208
0
        return AVERROR_INVALIDDATA;
209
0
    }
210
211
    /* parse asset locators */
212
0
    if (!(node = ff_imf_xml_get_child_element_by_name(asset_map_element, "AssetList"))) {
213
0
        av_log(s, AV_LOG_ERROR, "Unable to parse asset map XML - missing AssetList node\n");
214
0
        return AVERROR_INVALIDDATA;
215
0
    }
216
0
    elem_count = xmlChildElementCount(node);
217
0
    if (elem_count > UINT32_MAX
218
0
        || asset_map->asset_count > UINT32_MAX - elem_count)
219
0
        return AVERROR(ENOMEM);
220
0
    tmp = av_realloc_array(asset_map->assets,
221
0
                           elem_count + asset_map->asset_count,
222
0
                           sizeof(IMFAssetLocator));
223
0
    if (!tmp) {
224
0
        av_log(s, AV_LOG_ERROR, "Cannot allocate IMF asset locators\n");
225
0
        return AVERROR(ENOMEM);
226
0
    }
227
0
    asset_map->assets = tmp;
228
229
0
    asset_element = xmlFirstElementChild(node);
230
0
    while (asset_element) {
231
0
        if (av_strcasecmp(asset_element->name, "Asset") != 0)
232
0
            continue;
233
234
0
        asset = &(asset_map->assets[asset_map->asset_count]);
235
236
0
        if (!(node = ff_imf_xml_get_child_element_by_name(asset_element, "Id"))) {
237
0
            av_log(s, AV_LOG_ERROR, "Unable to parse asset map XML - missing Id node\n");
238
0
            return AVERROR_INVALIDDATA;
239
0
        }
240
241
0
        if (ff_imf_xml_read_uuid(node, asset->uuid)) {
242
0
            av_log(s, AV_LOG_ERROR, "Could not parse UUID from asset in asset map.\n");
243
0
            return AVERROR_INVALIDDATA;
244
0
        }
245
246
0
        av_log(s, AV_LOG_DEBUG, "Found asset id: " AV_PRI_URN_UUID "\n", AV_UUID_ARG(asset->uuid));
247
248
0
        if (!(node = ff_imf_xml_get_child_element_by_name(asset_element, "ChunkList"))) {
249
0
            av_log(s, AV_LOG_ERROR, "Unable to parse asset map XML - missing ChunkList node\n");
250
0
            return AVERROR_INVALIDDATA;
251
0
        }
252
253
0
        if (!(node = ff_imf_xml_get_child_element_by_name(node, "Chunk"))) {
254
0
            av_log(s, AV_LOG_ERROR, "Unable to parse asset map XML - missing Chunk node\n");
255
0
            return AVERROR_INVALIDDATA;
256
0
        }
257
258
0
        xmlNodePtr path_node = ff_imf_xml_get_child_element_by_name(node, "Path");
259
0
        if (!path_node) {
260
0
            av_log(s, AV_LOG_ERROR, "Unable to parse asset map XML - missing Path element in Chunk\n");
261
0
            ret = AVERROR_INVALIDDATA;
262
0
            break;
263
0
        }
264
0
        uri = xmlNodeGetContent(path_node);
265
0
        if (!uri || !uri[0]) {
266
0
            av_log(s, AV_LOG_ERROR, "Unable to parse asset map XML - empty Path element in Chunk\n");
267
0
            xmlFree(uri);
268
0
            ret = AVERROR_INVALIDDATA;
269
0
            break;
270
0
        }
271
272
0
        if (!imf_uri_is_url(uri) && !imf_uri_is_unix_abs_path(uri) && !imf_uri_is_dos_abs_path(uri))
273
0
            asset->absolute_uri = av_append_path_component(base_url, uri);
274
0
        else
275
0
            asset->absolute_uri = av_strdup(uri);
276
0
        xmlFree(uri);
277
0
        if (!asset->absolute_uri)
278
0
            return AVERROR(ENOMEM);
279
280
0
        av_log(s, AV_LOG_DEBUG, "Found asset absolute URI: %s\n", asset->absolute_uri);
281
282
0
        asset_map->asset_count++;
283
0
        asset_element = xmlNextElementSibling(asset_element);
284
0
    }
285
286
0
    return ret;
287
0
}
288
289
/**
290
 * Initializes an IMFAssetLocatorMap structure.
291
 */
292
static void imf_asset_locator_map_init(IMFAssetLocatorMap *asset_map)
293
9
{
294
9
    asset_map->assets = NULL;
295
9
    asset_map->asset_count = 0;
296
9
}
297
298
/**
299
 * Free a IMFAssetLocatorMap pointer.
300
 */
301
static void imf_asset_locator_map_deinit(IMFAssetLocatorMap *asset_map)
302
20.1k
{
303
20.1k
    for (uint32_t i = 0; i < asset_map->asset_count; i++)
304
0
        av_freep(&asset_map->assets[i].absolute_uri);
305
306
20.1k
    av_freep(&asset_map->assets);
307
20.1k
}
308
309
static int parse_assetmap(AVFormatContext *s, const char *url)
310
9
{
311
9
    IMFContext *c = s->priv_data;
312
9
    AVIOContext *in = NULL;
313
9
    struct AVBPrint buf;
314
9
    AVDictionary *opts = NULL;
315
9
    xmlDoc *doc = NULL;
316
9
    const char *base_url;
317
9
    char *tmp_str = NULL;
318
9
    int ret;
319
320
9
    av_log(s, AV_LOG_DEBUG, "Asset Map URL: %s\n", url);
321
322
9
    av_dict_copy(&opts, c->avio_opts, 0);
323
9
    ret = s->io_open(s, &in, url, AVIO_FLAG_READ, &opts);
324
9
    av_dict_free(&opts);
325
9
    if (ret < 0)
326
9
        return ret;
327
328
0
    av_bprint_init(&buf, 0, INT_MAX); // xmlReadMemory uses integer length
329
330
0
    ret = avio_read_to_bprint(in, &buf, SIZE_MAX);
331
0
    if (ret < 0 || !avio_feof(in)) {
332
0
        av_log(s, AV_LOG_ERROR, "Unable to read to asset map '%s'\n", url);
333
0
        if (ret == 0)
334
0
            ret = AVERROR_INVALIDDATA;
335
0
        goto clean_up;
336
0
    }
337
338
0
    LIBXML_TEST_VERSION
339
340
0
    tmp_str = av_strdup(url);
341
0
    if (!tmp_str) {
342
0
        ret = AVERROR(ENOMEM);
343
0
        goto clean_up;
344
0
    }
345
0
    base_url = av_dirname(tmp_str);
346
347
0
    doc = xmlReadMemory(buf.str, buf.len, url, NULL, 0);
348
349
0
    ret = parse_imf_asset_map_from_xml_dom(s, doc, &c->asset_locator_map, base_url);
350
0
    if (!ret)
351
0
        av_log(s, AV_LOG_DEBUG, "Found %d assets from %s\n",
352
0
               c->asset_locator_map.asset_count, url);
353
354
0
    xmlFreeDoc(doc);
355
356
0
clean_up:
357
0
    if (tmp_str)
358
0
        av_freep(&tmp_str);
359
0
    ff_format_io_close(s, &in);
360
0
    av_bprint_finalize(&buf, NULL);
361
0
    return ret;
362
0
}
363
364
static IMFAssetLocator *find_asset_map_locator(IMFAssetLocatorMap *asset_map, AVUUID uuid)
365
0
{
366
0
    for (uint32_t i = 0; i < asset_map->asset_count; i++) {
367
0
        if (memcmp(asset_map->assets[i].uuid, uuid, 16) == 0)
368
0
            return &(asset_map->assets[i]);
369
0
    }
370
0
    return NULL;
371
0
}
372
373
static int open_track_resource_context(AVFormatContext *s,
374
                                       IMFVirtualTrackPlaybackCtx *track,
375
                                       int32_t resource_index)
376
0
{
377
0
    IMFContext *c = s->priv_data;
378
0
    int ret = 0;
379
0
    int64_t seek_offset = 0;
380
0
    AVDictionary *opts = NULL;
381
0
    AVStream *st;
382
0
    IMFVirtualTrackResourcePlaybackCtx *track_resource = track->resources + resource_index;
383
384
0
    if (track_resource->ctx) {
385
0
        av_log(s, AV_LOG_DEBUG, "Input context already opened for %s.\n",
386
0
               track_resource->locator->absolute_uri);
387
0
        return 0;
388
0
    }
389
390
0
    track_resource->ctx = avformat_alloc_context();
391
0
    if (!track_resource->ctx)
392
0
        return AVERROR(ENOMEM);
393
394
0
    track_resource->ctx->io_open = s->io_open;
395
0
    track_resource->ctx->io_close2 = s->io_close2;
396
0
    track_resource->ctx->opaque = s->opaque;
397
0
    track_resource->ctx->flags |= s->flags & ~AVFMT_FLAG_CUSTOM_IO;
398
399
0
    if ((ret = ff_copy_whiteblacklists(track_resource->ctx, s)) < 0)
400
0
        goto cleanup;
401
402
0
    if ((ret = av_opt_set(track_resource->ctx, "format_whitelist", "mxf", 0)))
403
0
        goto cleanup;
404
405
0
    if ((ret = av_dict_copy(&opts, c->avio_opts, 0)) < 0)
406
0
        goto cleanup;
407
408
0
    ret = avformat_open_input(&track_resource->ctx,
409
0
                              track_resource->locator->absolute_uri,
410
0
                              NULL,
411
0
                              &opts);
412
0
    if (ret < 0) {
413
0
        av_log(s, AV_LOG_ERROR, "Could not open %s input context: %s\n",
414
0
               track_resource->locator->absolute_uri, av_err2str(ret));
415
0
        goto cleanup;
416
0
    }
417
0
    av_dict_free(&opts);
418
419
    /* make sure there is only one stream in the file */
420
421
0
    if (track_resource->ctx->nb_streams != 1) {
422
0
        ret = AVERROR_INVALIDDATA;
423
0
        goto cleanup;
424
0
    }
425
426
0
    st = track_resource->ctx->streams[0];
427
428
    /* Determine the seek offset into the Track File, taking into account:
429
     * - the current timestamp within the virtual track
430
     * - the entry point of the resource
431
     */
432
0
    if (imf_time_to_ts(&seek_offset,
433
0
                       av_sub_q(track->current_timestamp, track_resource->ts_offset),
434
0
                       st->time_base))
435
0
        av_log(s, AV_LOG_WARNING, "Incoherent stream timebase " AVRATIONAL_FORMAT
436
0
               "and composition timeline position: " AVRATIONAL_FORMAT "\n",
437
0
               AVRATIONAL_ARG(st->time_base), AVRATIONAL_ARG(track->current_timestamp));
438
439
0
    if (seek_offset) {
440
0
        av_log(s, AV_LOG_DEBUG, "Seek at resource %s entry point: %" PRIi64 "\n",
441
0
               track_resource->locator->absolute_uri, seek_offset);
442
0
        ret = avformat_seek_file(track_resource->ctx, 0, seek_offset, seek_offset, seek_offset, 0);
443
0
        if (ret < 0) {
444
0
            av_log(s,
445
0
                   AV_LOG_ERROR,
446
0
                   "Could not seek at %" PRId64 "on %s: %s\n",
447
0
                   seek_offset,
448
0
                   track_resource->locator->absolute_uri,
449
0
                   av_err2str(ret));
450
0
            avformat_close_input(&track_resource->ctx);
451
0
            return ret;
452
0
        }
453
0
    }
454
455
0
    return 0;
456
457
0
cleanup:
458
0
    av_dict_free(&opts);
459
0
    avformat_free_context(track_resource->ctx);
460
0
    track_resource->ctx = NULL;
461
0
    return ret;
462
0
}
463
464
static int open_track_file_resource(AVFormatContext *s,
465
                                    FFIMFTrackFileResource *track_file_resource,
466
                                    IMFVirtualTrackPlaybackCtx *track)
467
0
{
468
0
    IMFContext *c = s->priv_data;
469
0
    IMFAssetLocator *asset_locator;
470
0
    void *tmp;
471
472
0
    asset_locator = find_asset_map_locator(&c->asset_locator_map, track_file_resource->track_file_uuid);
473
0
    if (!asset_locator) {
474
0
        av_log(s, AV_LOG_ERROR, "Could not find asset locator for UUID: " AV_PRI_URN_UUID "\n",
475
0
               AV_UUID_ARG(track_file_resource->track_file_uuid));
476
0
        return AVERROR_INVALIDDATA;
477
0
    }
478
479
0
    av_log(s,
480
0
           AV_LOG_DEBUG,
481
0
           "Found locator for " AV_PRI_URN_UUID ": %s\n",
482
0
           AV_UUID_ARG(asset_locator->uuid),
483
0
           asset_locator->absolute_uri);
484
485
0
    if (track->resource_count > INT32_MAX - track_file_resource->base.repeat_count
486
0
        || (track->resource_count + track_file_resource->base.repeat_count)
487
0
            > INT_MAX / sizeof(IMFVirtualTrackResourcePlaybackCtx))
488
0
        return AVERROR(ENOMEM);
489
0
    tmp = av_fast_realloc(track->resources,
490
0
                          &track->resources_alloc_sz,
491
0
                          (track->resource_count + track_file_resource->base.repeat_count)
492
0
                              * sizeof(IMFVirtualTrackResourcePlaybackCtx));
493
0
    if (!tmp)
494
0
        return AVERROR(ENOMEM);
495
0
    track->resources = tmp;
496
497
0
    for (uint32_t i = 0; i < track_file_resource->base.repeat_count; i++) {
498
0
        IMFVirtualTrackResourcePlaybackCtx vt_ctx;
499
500
0
        vt_ctx.locator = asset_locator;
501
0
        vt_ctx.resource = track_file_resource;
502
0
        vt_ctx.ctx = NULL;
503
0
        vt_ctx.start_time = track->duration;
504
0
        vt_ctx.ts_offset = av_sub_q(vt_ctx.start_time,
505
0
                                    av_div_q(av_make_q((int)track_file_resource->base.entry_point, 1),
506
0
                                             track_file_resource->base.edit_rate));
507
0
        vt_ctx.end_time = av_add_q(track->duration,
508
0
                                   av_make_q((int)track_file_resource->base.duration
509
0
                                                 * track_file_resource->base.edit_rate.den,
510
0
                                             track_file_resource->base.edit_rate.num));
511
0
        track->resources[track->resource_count++] = vt_ctx;
512
0
        track->duration = vt_ctx.end_time;
513
0
    }
514
515
0
    return 0;
516
0
}
517
518
static void imf_virtual_track_playback_context_deinit(IMFVirtualTrackPlaybackCtx *track)
519
0
{
520
0
    for (uint32_t i = 0; i < track->resource_count; i++)
521
0
        avformat_close_input(&track->resources[i].ctx);
522
523
0
    av_freep(&track->resources);
524
0
}
525
526
static int open_virtual_track(AVFormatContext *s,
527
                              FFIMFTrackFileVirtualTrack *virtual_track,
528
                              int32_t track_index)
529
0
{
530
0
    IMFContext *c = s->priv_data;
531
0
    IMFVirtualTrackPlaybackCtx *track = NULL;
532
0
    void *tmp;
533
0
    int ret = 0;
534
535
0
    if (!(track = av_mallocz(sizeof(IMFVirtualTrackPlaybackCtx))))
536
0
        return AVERROR(ENOMEM);
537
0
    track->current_resource_index = -1;
538
0
    track->index = track_index;
539
0
    track->duration = av_make_q(0, 1);
540
541
0
    if (!virtual_track->resource_count) {
542
0
        av_log(s, AV_LOG_ERROR, "Virtual track has no resources\n");
543
0
        ret = AVERROR_INVALIDDATA;
544
0
        goto clean_up;
545
0
    }
546
547
0
    for (uint32_t i = 0; i < virtual_track->resource_count; i++) {
548
0
        av_log(s,
549
0
               AV_LOG_DEBUG,
550
0
               "Open stream from file " AV_PRI_URN_UUID ", stream %d\n",
551
0
               AV_UUID_ARG(virtual_track->resources[i].track_file_uuid),
552
0
               i);
553
0
        if ((ret = open_track_file_resource(s, &virtual_track->resources[i], track)) != 0) {
554
0
            av_log(s,
555
0
                   AV_LOG_ERROR,
556
0
                   "Could not open image track resource " AV_PRI_URN_UUID "\n",
557
0
                   AV_UUID_ARG(virtual_track->resources[i].track_file_uuid));
558
0
            goto clean_up;
559
0
        }
560
0
    }
561
562
0
    track->current_timestamp = av_make_q(0, track->duration.den);
563
564
0
    if (c->track_count == UINT32_MAX) {
565
0
        ret = AVERROR(ENOMEM);
566
0
        goto clean_up;
567
0
    }
568
0
    tmp = av_realloc_array(c->tracks, c->track_count + 1, sizeof(IMFVirtualTrackPlaybackCtx *));
569
0
    if (!tmp) {
570
0
        ret = AVERROR(ENOMEM);
571
0
        goto clean_up;
572
0
    }
573
0
    c->tracks = tmp;
574
0
    c->tracks[c->track_count++] = track;
575
576
0
    return 0;
577
578
0
clean_up:
579
0
    imf_virtual_track_playback_context_deinit(track);
580
0
    av_free(track);
581
0
    return ret;
582
0
}
583
584
static int set_context_streams_from_tracks(AVFormatContext *s)
585
0
{
586
0
    IMFContext *c = s->priv_data;
587
0
    int ret = 0;
588
589
0
    for (uint32_t i = 0; i < c->track_count; i++) {
590
0
        AVStream *asset_stream;
591
0
        AVStream *first_resource_stream;
592
593
        /* Open the first resource of the track to get stream information */
594
0
        ret = open_track_resource_context(s, c->tracks[i], 0);
595
0
        if (ret)
596
0
            return ret;
597
0
        first_resource_stream = c->tracks[i]->resources[0].ctx->streams[0];
598
0
        av_log(s, AV_LOG_DEBUG, "Open the first resource of track %d\n", c->tracks[i]->index);
599
600
0
        asset_stream = ff_stream_clone(s, first_resource_stream);
601
0
        if (!asset_stream) {
602
0
            av_log(s, AV_LOG_ERROR, "Could not clone stream\n");
603
0
            return AVERROR(ENOMEM);
604
0
        }
605
606
0
        asset_stream->id = i;
607
0
        asset_stream->nb_frames = 0;
608
0
        avpriv_set_pts_info(asset_stream,
609
0
                            first_resource_stream->pts_wrap_bits,
610
0
                            first_resource_stream->time_base.num,
611
0
                            first_resource_stream->time_base.den);
612
0
        asset_stream->duration = (int64_t)av_q2d(av_mul_q(c->tracks[i]->duration,
613
0
                                                          av_inv_q(asset_stream->time_base)));
614
0
    }
615
616
0
    return 0;
617
0
}
618
619
static int open_cpl_tracks(AVFormatContext *s)
620
0
{
621
0
    IMFContext *c = s->priv_data;
622
0
    int32_t track_index = 0;
623
0
    int ret;
624
625
0
    if (c->cpl->main_image_2d_track) {
626
0
        if ((ret = open_virtual_track(s, c->cpl->main_image_2d_track, track_index++)) != 0) {
627
0
            av_log(s, AV_LOG_ERROR, "Could not open image track " AV_PRI_URN_UUID "\n",
628
0
                   AV_UUID_ARG(c->cpl->main_image_2d_track->base.id_uuid));
629
0
            return ret;
630
0
        }
631
0
    }
632
633
0
    for (uint32_t i = 0; i < c->cpl->main_audio_track_count; i++) {
634
0
        if ((ret = open_virtual_track(s, &c->cpl->main_audio_tracks[i], track_index++)) != 0) {
635
0
            av_log(s, AV_LOG_ERROR, "Could not open audio track " AV_PRI_URN_UUID "\n",
636
0
                   AV_UUID_ARG(c->cpl->main_audio_tracks[i].base.id_uuid));
637
0
            return ret;
638
0
        }
639
0
    }
640
641
0
    return set_context_streams_from_tracks(s);
642
0
}
643
644
static int imf_read_header(AVFormatContext *s)
645
20.1k
{
646
20.1k
    IMFContext *c = s->priv_data;
647
20.1k
    char *asset_map_path;
648
20.1k
    char *tmp_str;
649
20.1k
    AVDictionaryEntry* tcr;
650
20.1k
    char tc_buf[AV_TIMECODE_STR_SIZE];
651
20.1k
    int ret = 0;
652
653
20.1k
    c->interrupt_callback = &s->interrupt_callback;
654
20.1k
    tmp_str = av_strdup(s->url);
655
20.1k
    if (!tmp_str)
656
0
        return AVERROR(ENOMEM);
657
20.1k
    c->base_url = av_strdup(av_dirname(tmp_str));
658
20.1k
    av_freep(&tmp_str);
659
20.1k
    if (!c->base_url)
660
0
        return AVERROR(ENOMEM);
661
662
20.1k
    if ((ret = ffio_copy_url_options(s->pb, &c->avio_opts)) < 0)
663
0
        return ret;
664
665
20.1k
    av_log(s, AV_LOG_DEBUG, "start parsing IMF CPL: %s\n", s->url);
666
667
20.1k
    if ((ret = ff_imf_parse_cpl(s, s->pb, &c->cpl)) < 0)
668
20.1k
        return ret;
669
670
9
    tcr = av_dict_get(s->metadata, "timecode", NULL, 0);
671
9
    if (!tcr && c->cpl->tc) {
672
0
        ret = av_dict_set(&s->metadata, "timecode",
673
0
                          av_timecode_make_string(c->cpl->tc, tc_buf, 0), 0);
674
0
        if (ret)
675
0
            return ret;
676
0
        av_log(s, AV_LOG_INFO, "Setting timecode to IMF CPL timecode %s\n", tc_buf);
677
0
    }
678
679
9
    av_log(s,
680
9
           AV_LOG_DEBUG,
681
9
           "parsed IMF CPL: " AV_PRI_URN_UUID "\n",
682
9
           AV_UUID_ARG(c->cpl->id_uuid));
683
684
9
    if (!c->asset_map_paths) {
685
9
        c->asset_map_paths = av_append_path_component(c->base_url, "ASSETMAP.xml");
686
9
        if (!c->asset_map_paths) {
687
0
            ret = AVERROR(ENOMEM);
688
0
            return ret;
689
0
        }
690
9
        av_log(s, AV_LOG_DEBUG, "No asset maps provided, using the default ASSETMAP.xml\n");
691
9
    }
692
693
    /* Parse each asset map XML file */
694
9
    imf_asset_locator_map_init(&c->asset_locator_map);
695
9
    asset_map_path = av_strtok(c->asset_map_paths, ",", &tmp_str);
696
9
    while (asset_map_path != NULL) {
697
9
        av_log(s, AV_LOG_DEBUG, "start parsing IMF Asset Map: %s\n", asset_map_path);
698
699
9
        if ((ret = parse_assetmap(s, asset_map_path)))
700
9
            return ret;
701
702
0
        asset_map_path = av_strtok(NULL, ",", &tmp_str);
703
0
    }
704
705
0
    av_log(s, AV_LOG_DEBUG, "parsed IMF Asset Maps\n");
706
707
0
    if ((ret = open_cpl_tracks(s)))
708
0
        return ret;
709
710
0
    av_log(s, AV_LOG_DEBUG, "parsed IMF package\n");
711
712
0
    return 0;
713
0
}
714
715
static IMFVirtualTrackPlaybackCtx *get_next_track_with_minimum_timestamp(AVFormatContext *s)
716
0
{
717
0
    IMFContext *c = s->priv_data;
718
0
    IMFVirtualTrackPlaybackCtx *track = NULL;
719
0
    AVRational minimum_timestamp = av_make_q(INT32_MAX, 1);
720
721
0
    for (uint32_t i = c->track_count; i > 0; i--) {
722
0
        av_log(s, AV_LOG_TRACE, "Compare track %d timestamp " AVRATIONAL_FORMAT
723
0
               " to minimum " AVRATIONAL_FORMAT
724
0
               " (over duration: " AVRATIONAL_FORMAT ")\n", i,
725
0
               AVRATIONAL_ARG(c->tracks[i - 1]->current_timestamp),
726
0
               AVRATIONAL_ARG(minimum_timestamp),
727
0
               AVRATIONAL_ARG(c->tracks[i - 1]->duration));
728
729
0
        if (av_cmp_q(c->tracks[i - 1]->current_timestamp, minimum_timestamp) <= 0) {
730
0
            track = c->tracks[i - 1];
731
0
            minimum_timestamp = track->current_timestamp;
732
0
        }
733
0
    }
734
735
0
    return track;
736
0
}
737
738
static int get_resource_context_for_timestamp(AVFormatContext *s, IMFVirtualTrackPlaybackCtx *track, IMFVirtualTrackResourcePlaybackCtx **resource)
739
0
{
740
0
    *resource = NULL;
741
742
0
    if (av_cmp_q(track->current_timestamp, track->duration) >= 0) {
743
0
        av_log(s, AV_LOG_DEBUG, "Reached the end of the virtual track\n");
744
0
        return AVERROR_EOF;
745
0
    }
746
747
0
    av_log(s,
748
0
           AV_LOG_TRACE,
749
0
           "Looking for track %d resource for timestamp = %lf / %lf\n",
750
0
           track->index,
751
0
           av_q2d(track->current_timestamp),
752
0
           av_q2d(track->duration));
753
0
    for (uint32_t i = 0; i < track->resource_count; i++) {
754
755
0
        if (av_cmp_q(track->resources[i].end_time, track->current_timestamp) > 0) {
756
0
            av_log(s, AV_LOG_DEBUG, "Found resource %d in track %d to read at timestamp %lf: "
757
0
                   "entry=%" PRIu32 ", duration=%" PRIu32 ", editrate=" AVRATIONAL_FORMAT "\n",
758
0
                   i, track->index, av_q2d(track->current_timestamp),
759
0
                   track->resources[i].resource->base.entry_point,
760
0
                   track->resources[i].resource->base.duration,
761
0
                   AVRATIONAL_ARG(track->resources[i].resource->base.edit_rate));
762
763
0
            if (track->current_resource_index != i) {
764
0
                int ret;
765
766
0
                av_log(s, AV_LOG_TRACE, "Switch resource on track %d: re-open context\n",
767
0
                       track->index);
768
769
0
                ret = open_track_resource_context(s, track, i);
770
0
                if (ret != 0)
771
0
                    return ret;
772
0
                if (track->current_resource_index > 0)
773
0
                    avformat_close_input(&track->resources[track->current_resource_index].ctx);
774
0
                track->current_resource_index = i;
775
0
            }
776
777
0
            *resource = track->resources + track->current_resource_index;
778
0
            return 0;
779
0
        }
780
0
    }
781
782
0
    av_log(s, AV_LOG_ERROR, "Could not find IMF track resource to read\n");
783
0
    return AVERROR_STREAM_NOT_FOUND;
784
0
}
785
786
static int imf_read_packet(AVFormatContext *s, AVPacket *pkt)
787
0
{
788
0
    IMFVirtualTrackResourcePlaybackCtx *resource = NULL;
789
0
    int ret = 0;
790
0
    IMFVirtualTrackPlaybackCtx *track;
791
0
    int64_t delta_ts;
792
0
    AVStream *st;
793
0
    AVRational next_timestamp;
794
795
0
    track = get_next_track_with_minimum_timestamp(s);
796
797
0
    if (!track) {
798
0
        av_log(s, AV_LOG_ERROR, "No track found for playback\n");
799
0
        return AVERROR_INVALIDDATA;
800
0
    }
801
802
0
    av_log(s, AV_LOG_DEBUG, "Found track %d to read at timestamp %lf\n",
803
0
           track->index, av_q2d(track->current_timestamp));
804
805
0
    ret = get_resource_context_for_timestamp(s, track, &resource);
806
0
    if (ret)
807
0
        return ret;
808
809
0
    ret = av_read_frame(resource->ctx, pkt);
810
0
    if (ret)
811
0
        return ret;
812
813
0
    av_log(s, AV_LOG_DEBUG, "Got packet: pts=%" PRId64 ", dts=%" PRId64
814
0
            ", duration=%" PRId64 ", stream_index=%d, pos=%" PRId64
815
0
            ", time_base=" AVRATIONAL_FORMAT "\n", pkt->pts, pkt->dts, pkt->duration,
816
0
            pkt->stream_index, pkt->pos, AVRATIONAL_ARG(pkt->time_base));
817
818
    /* IMF resources contain only one stream */
819
820
0
    if (pkt->stream_index != 0)
821
0
        return AVERROR_INVALIDDATA;
822
0
    st = resource->ctx->streams[0];
823
824
0
    pkt->stream_index = track->index;
825
826
    /* adjust the packet PTS and DTS based on the temporal position of the resource within the timeline */
827
828
0
    ret = imf_time_to_ts(&delta_ts, resource->ts_offset, st->time_base);
829
830
0
    if (!ret) {
831
0
        if (pkt->pts != AV_NOPTS_VALUE)
832
0
            pkt->pts += delta_ts;
833
0
        if (pkt->dts != AV_NOPTS_VALUE)
834
0
            pkt->dts += delta_ts;
835
0
    } else {
836
0
        av_log(s, AV_LOG_WARNING, "Incoherent time stamp " AVRATIONAL_FORMAT
837
0
               " for time base " AVRATIONAL_FORMAT,
838
0
               AVRATIONAL_ARG(resource->ts_offset),
839
0
               AVRATIONAL_ARG(pkt->time_base));
840
0
    }
841
842
    /* advance the track timestamp by the packet duration */
843
844
0
    next_timestamp = av_add_q(track->current_timestamp,
845
0
                              av_mul_q(av_make_q((int)pkt->duration, 1), st->time_base));
846
847
    /* if necessary, clamp the next timestamp to the end of the current resource */
848
849
0
    if (av_cmp_q(next_timestamp, resource->end_time) > 0) {
850
851
0
        int64_t new_pkt_dur;
852
853
        /* shrink the packet duration */
854
855
0
        ret = imf_time_to_ts(&new_pkt_dur,
856
0
                             av_sub_q(resource->end_time, track->current_timestamp),
857
0
                             st->time_base);
858
859
0
        if (!ret)
860
0
            pkt->duration = new_pkt_dur;
861
0
        else
862
0
            av_log(s, AV_LOG_WARNING, "Incoherent time base in packet duration calculation\n");
863
864
        /* shrink the packet itself for audio essence */
865
866
0
        if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) {
867
868
0
            if (st->codecpar->codec_id == AV_CODEC_ID_PCM_S24LE) {
869
                /* AV_CODEC_ID_PCM_S24LE is the only PCM format supported in IMF */
870
                /* in this case, explicitly shrink the packet */
871
872
0
                int bytes_per_sample = av_get_exact_bits_per_sample(st->codecpar->codec_id) >> 3;
873
0
                int64_t nbsamples = av_rescale_q(pkt->duration,
874
0
                                                 st->time_base,
875
0
                                                 av_make_q(1, st->codecpar->sample_rate));
876
0
                av_shrink_packet(pkt, nbsamples * st->codecpar->ch_layout.nb_channels * bytes_per_sample);
877
878
0
            } else {
879
                /* in all other cases, use side data to skip samples */
880
0
                int64_t skip_samples;
881
882
0
                ret = imf_time_to_ts(&skip_samples,
883
0
                                     av_sub_q(next_timestamp, resource->end_time),
884
0
                                     av_make_q(1, st->codecpar->sample_rate));
885
886
0
                if (ret || skip_samples < 0 || skip_samples > UINT32_MAX) {
887
0
                    av_log(s, AV_LOG_WARNING, "Cannot skip audio samples\n");
888
0
                } else {
889
0
                    uint8_t *side_data = av_packet_new_side_data(pkt, AV_PKT_DATA_SKIP_SAMPLES, 10);
890
0
                    if (!side_data)
891
0
                        return AVERROR(ENOMEM);
892
893
0
                    AV_WL32(side_data + 4, skip_samples); /* skip from end of this packet */
894
0
                    side_data[6] = 1;                     /* reason for end is convergence */
895
0
                }
896
0
            }
897
898
0
            next_timestamp = resource->end_time;
899
900
0
        } else {
901
0
            av_log(s, AV_LOG_WARNING, "Non-audio packet duration reduced\n");
902
0
        }
903
0
    }
904
905
0
    track->current_timestamp = next_timestamp;
906
907
0
    return 0;
908
0
}
909
910
static int imf_close(AVFormatContext *s)
911
20.1k
{
912
20.1k
    IMFContext *c = s->priv_data;
913
914
20.1k
    av_log(s, AV_LOG_DEBUG, "Close IMF package\n");
915
20.1k
    av_dict_free(&c->avio_opts);
916
20.1k
    av_freep(&c->base_url);
917
20.1k
    imf_asset_locator_map_deinit(&c->asset_locator_map);
918
20.1k
    ff_imf_cpl_free(c->cpl);
919
920
20.1k
    for (uint32_t i = 0; i < c->track_count; i++) {
921
0
        imf_virtual_track_playback_context_deinit(c->tracks[i]);
922
0
        av_freep(&c->tracks[i]);
923
0
    }
924
925
20.1k
    av_freep(&c->tracks);
926
927
20.1k
    return 0;
928
20.1k
}
929
930
static int imf_probe(const AVProbeData *p)
931
967k
{
932
967k
    if (!strstr(p->buf, "<CompositionPlaylist"))
933
961k
        return 0;
934
935
    /* check for a ContentTitle element without including ContentTitleText,
936
     * which is used by the D-Cinema CPL.
937
     */
938
5.77k
    if (!strstr(p->buf, "ContentTitle>"))
939
1.41k
        return 0;
940
941
4.35k
    return AVPROBE_SCORE_MAX;
942
5.77k
}
943
944
static int coherent_ts(int64_t ts, AVRational in_tb, AVRational out_tb)
945
0
{
946
0
    int dst_num;
947
0
    int dst_den;
948
0
    int ret;
949
950
0
    ret = av_reduce(&dst_num, &dst_den, ts * in_tb.num * out_tb.den,
951
0
                    in_tb.den * out_tb.num, INT64_MAX);
952
0
    if (!ret || dst_den != 1)
953
0
        return 0;
954
955
0
    return 1;
956
0
}
957
958
static int imf_seek(AVFormatContext *s, int stream_index, int64_t min_ts,
959
                    int64_t ts, int64_t max_ts, int flags)
960
0
{
961
0
    IMFContext *c = s->priv_data;
962
0
    uint32_t i;
963
964
0
    if (flags & (AVSEEK_FLAG_BYTE | AVSEEK_FLAG_FRAME))
965
0
        return AVERROR(ENOSYS);
966
967
    /* rescale timestamps to Composition edit units */
968
0
    if (stream_index < 0)
969
0
        ff_rescale_interval(AV_TIME_BASE_Q,
970
0
                            av_make_q(c->cpl->edit_rate.den, c->cpl->edit_rate.num),
971
0
                            &min_ts, &ts, &max_ts);
972
0
    else
973
0
        ff_rescale_interval(s->streams[stream_index]->time_base,
974
0
                            av_make_q(c->cpl->edit_rate.den, c->cpl->edit_rate.num),
975
0
                            &min_ts, &ts, &max_ts);
976
977
    /* requested timestamp bounds are too close */
978
0
    if (max_ts < min_ts)
979
0
        return -1;
980
981
    /* clamp requested timestamp to provided bounds */
982
0
    ts = FFMAX(FFMIN(ts, max_ts), min_ts);
983
984
0
    av_log(s, AV_LOG_DEBUG, "Seeking to Composition Playlist edit unit %" PRIi64 "\n", ts);
985
986
    /* set the dts of each stream and temporal offset of each track */
987
0
    for (i = 0; i < c->track_count; i++) {
988
0
        AVStream *st = s->streams[i];
989
0
        IMFVirtualTrackPlaybackCtx *t = c->tracks[i];
990
0
        int64_t dts;
991
992
0
        if (!coherent_ts(ts, av_make_q(c->cpl->edit_rate.den, c->cpl->edit_rate.num),
993
0
                         st->time_base))
994
0
            av_log(s, AV_LOG_WARNING, "Seek position is not coherent across tracks\n");
995
996
0
        dts = av_rescale(ts,
997
0
                         st->time_base.den * c->cpl->edit_rate.den,
998
0
                         st->time_base.num * c->cpl->edit_rate.num);
999
1000
0
        av_log(s, AV_LOG_DEBUG, "Seeking to dts=%" PRId64 " on stream_index=%d\n",
1001
0
               dts, i);
1002
1003
0
        t->current_timestamp = av_mul_q(av_make_q(dts, 1), st->time_base);
1004
0
        if (t->current_resource_index >= 0) {
1005
0
            avformat_close_input(&t->resources[t->current_resource_index].ctx);
1006
0
            t->current_resource_index = -1;
1007
0
        }
1008
0
    }
1009
1010
0
    return 0;
1011
0
}
1012
1013
static const AVOption imf_options[] = {
1014
    {
1015
        .name        = "assetmaps",
1016
        .help        = "Comma-separated paths to ASSETMAP files."
1017
                       "If not specified, the `ASSETMAP.xml` file in the same "
1018
                       "directory as the CPL is used.",
1019
        .offset      = offsetof(IMFContext, asset_map_paths),
1020
        .type        = AV_OPT_TYPE_STRING,
1021
        .default_val = {.str = NULL},
1022
        .flags       = AV_OPT_FLAG_DECODING_PARAM,
1023
    },
1024
    {NULL},
1025
};
1026
1027
static const AVClass imf_class = {
1028
    .class_name = "imf",
1029
    .item_name  = av_default_item_name,
1030
    .option     = imf_options,
1031
    .version    = LIBAVUTIL_VERSION_INT,
1032
};
1033
1034
const FFInputFormat ff_imf_demuxer = {
1035
    .p.name         = "imf",
1036
    .p.long_name    = NULL_IF_CONFIG_SMALL("IMF (Interoperable Master Format)"),
1037
    .p.flags        = AVFMT_NO_BYTE_SEEK,
1038
    .p.priv_class   = &imf_class,
1039
    .flags_internal = FF_INFMT_FLAG_INIT_CLEANUP,
1040
    .priv_data_size = sizeof(IMFContext),
1041
    .read_probe     = imf_probe,
1042
    .read_header    = imf_read_header,
1043
    .read_packet    = imf_read_packet,
1044
    .read_close     = imf_close,
1045
    .read_seek2     = imf_seek,
1046
};