PageRenderTime 136ms CodeModel.GetById 23ms app.highlight 101ms RepoModel.GetById 2ms app.codeStats 0ms

/libavformat/nutdec.c

http://github.com/FFmpeg/FFmpeg
C | 1307 lines | 1130 code | 140 blank | 37 comment | 325 complexity | 06b035b026cbccdd6a4266e649699c95 MD5 | raw file
   1/*
   2 * "NUT" Container Format demuxer
   3 * Copyright (c) 2004-2006 Michael Niedermayer
   4 * Copyright (c) 2003 Alex Beregszaszi
   5 *
   6 * This file is part of FFmpeg.
   7 *
   8 * FFmpeg is free software; you can redistribute it and/or
   9 * modify it under the terms of the GNU Lesser General Public
  10 * License as published by the Free Software Foundation; either
  11 * version 2.1 of the License, or (at your option) any later version.
  12 *
  13 * FFmpeg is distributed in the hope that it will be useful,
  14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
  15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  16 * Lesser General Public License for more details.
  17 *
  18 * You should have received a copy of the GNU Lesser General Public
  19 * License along with FFmpeg; if not, write to the Free Software
  20 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  21 */
  22
  23#include "libavutil/avstring.h"
  24#include "libavutil/avassert.h"
  25#include "libavutil/bswap.h"
  26#include "libavutil/dict.h"
  27#include "libavutil/intreadwrite.h"
  28#include "libavutil/mathematics.h"
  29#include "libavutil/tree.h"
  30#include "libavcodec/bytestream.h"
  31#include "avio_internal.h"
  32#include "isom.h"
  33#include "nut.h"
  34#include "riff.h"
  35
  36#define NUT_MAX_STREAMS 256    /* arbitrary sanity check value */
  37
  38static int64_t nut_read_timestamp(AVFormatContext *s, int stream_index,
  39                                  int64_t *pos_arg, int64_t pos_limit);
  40
  41static int get_str(AVIOContext *bc, char *string, unsigned int maxlen)
  42{
  43    unsigned int len = ffio_read_varlen(bc);
  44
  45    if (len && maxlen)
  46        avio_read(bc, string, FFMIN(len, maxlen));
  47    while (len > maxlen) {
  48        avio_r8(bc);
  49        len--;
  50        if (bc->eof_reached)
  51            len = maxlen;
  52    }
  53
  54    if (maxlen)
  55        string[FFMIN(len, maxlen - 1)] = 0;
  56
  57    if (bc->eof_reached)
  58        return AVERROR_EOF;
  59    if (maxlen == len)
  60        return -1;
  61    else
  62        return 0;
  63}
  64
  65static int64_t get_s(AVIOContext *bc)
  66{
  67    int64_t v = ffio_read_varlen(bc) + 1;
  68
  69    if (v & 1)
  70        return -(v >> 1);
  71    else
  72        return  (v >> 1);
  73}
  74
  75static uint64_t get_fourcc(AVIOContext *bc)
  76{
  77    unsigned int len = ffio_read_varlen(bc);
  78
  79    if (len == 2)
  80        return avio_rl16(bc);
  81    else if (len == 4)
  82        return avio_rl32(bc);
  83    else {
  84        av_log(NULL, AV_LOG_ERROR, "Unsupported fourcc length %d\n", len);
  85        return -1;
  86    }
  87}
  88
  89static int get_packetheader(NUTContext *nut, AVIOContext *bc,
  90                            int calculate_checksum, uint64_t startcode)
  91{
  92    int64_t size;
  93
  94    startcode = av_be2ne64(startcode);
  95    startcode = ff_crc04C11DB7_update(0, (uint8_t*) &startcode, 8);
  96
  97    ffio_init_checksum(bc, ff_crc04C11DB7_update, startcode);
  98    size = ffio_read_varlen(bc);
  99    if (size > 4096)
 100        avio_rb32(bc);
 101    if (ffio_get_checksum(bc) && size > 4096)
 102        return -1;
 103
 104    ffio_init_checksum(bc, calculate_checksum ? ff_crc04C11DB7_update : NULL, 0);
 105
 106    return size;
 107}
 108
 109static uint64_t find_any_startcode(AVIOContext *bc, int64_t pos)
 110{
 111    uint64_t state = 0;
 112
 113    if (pos >= 0)
 114        /* Note, this may fail if the stream is not seekable, but that should
 115         * not matter, as in this case we simply start where we currently are */
 116        avio_seek(bc, pos, SEEK_SET);
 117    while (!avio_feof(bc)) {
 118        state = (state << 8) | avio_r8(bc);
 119        if ((state >> 56) != 'N')
 120            continue;
 121        switch (state) {
 122        case MAIN_STARTCODE:
 123        case STREAM_STARTCODE:
 124        case SYNCPOINT_STARTCODE:
 125        case INFO_STARTCODE:
 126        case INDEX_STARTCODE:
 127            return state;
 128        }
 129    }
 130
 131    return 0;
 132}
 133
 134/**
 135 * Find the given startcode.
 136 * @param code the startcode
 137 * @param pos the start position of the search, or -1 if the current position
 138 * @return the position of the startcode or -1 if not found
 139 */
 140static int64_t find_startcode(AVIOContext *bc, uint64_t code, int64_t pos)
 141{
 142    for (;;) {
 143        uint64_t startcode = find_any_startcode(bc, pos);
 144        if (startcode == code)
 145            return avio_tell(bc) - 8;
 146        else if (startcode == 0)
 147            return -1;
 148        pos = -1;
 149    }
 150}
 151
 152static int nut_probe(const AVProbeData *p)
 153{
 154    int i;
 155
 156    for (i = 0; i < p->buf_size-8; i++) {
 157        if (AV_RB32(p->buf+i) != MAIN_STARTCODE>>32)
 158            continue;
 159        if (AV_RB32(p->buf+i+4) == (MAIN_STARTCODE & 0xFFFFFFFF))
 160            return AVPROBE_SCORE_MAX;
 161    }
 162    return 0;
 163}
 164
 165#define GET_V(dst, check)                                                     \
 166    do {                                                                      \
 167        tmp = ffio_read_varlen(bc);                                           \
 168        if (!(check)) {                                                       \
 169            av_log(s, AV_LOG_ERROR, "Error " #dst " is (%"PRId64")\n", tmp);  \
 170            ret = AVERROR_INVALIDDATA;                                        \
 171            goto fail;                                                        \
 172        }                                                                     \
 173        dst = tmp;                                                            \
 174    } while (0)
 175
 176static int skip_reserved(AVIOContext *bc, int64_t pos)
 177{
 178    pos -= avio_tell(bc);
 179    if (pos < 0) {
 180        avio_seek(bc, pos, SEEK_CUR);
 181        return AVERROR_INVALIDDATA;
 182    } else {
 183        while (pos--) {
 184            if (bc->eof_reached)
 185                return AVERROR_INVALIDDATA;
 186            avio_r8(bc);
 187        }
 188        return 0;
 189    }
 190}
 191
 192static int decode_main_header(NUTContext *nut)
 193{
 194    AVFormatContext *s = nut->avf;
 195    AVIOContext *bc    = s->pb;
 196    uint64_t tmp, end;
 197    unsigned int stream_count;
 198    int i, j, count, ret;
 199    int tmp_stream, tmp_mul, tmp_pts, tmp_size, tmp_res, tmp_head_idx;
 200
 201    end  = get_packetheader(nut, bc, 1, MAIN_STARTCODE);
 202    end += avio_tell(bc);
 203
 204    nut->version = ffio_read_varlen(bc);
 205    if (nut->version < NUT_MIN_VERSION ||
 206        nut->version > NUT_MAX_VERSION) {
 207        av_log(s, AV_LOG_ERROR, "Version %d not supported.\n",
 208               nut->version);
 209        return AVERROR(ENOSYS);
 210    }
 211    if (nut->version > 3)
 212        nut->minor_version = ffio_read_varlen(bc);
 213
 214    GET_V(stream_count, tmp > 0 && tmp <= NUT_MAX_STREAMS);
 215
 216    nut->max_distance = ffio_read_varlen(bc);
 217    if (nut->max_distance > 65536) {
 218        av_log(s, AV_LOG_DEBUG, "max_distance %d\n", nut->max_distance);
 219        nut->max_distance = 65536;
 220    }
 221
 222    GET_V(nut->time_base_count, tmp > 0 && tmp < INT_MAX / sizeof(AVRational));
 223    nut->time_base = av_malloc_array(nut->time_base_count, sizeof(AVRational));
 224    if (!nut->time_base)
 225        return AVERROR(ENOMEM);
 226
 227    for (i = 0; i < nut->time_base_count; i++) {
 228        GET_V(nut->time_base[i].num, tmp > 0 && tmp < (1ULL << 31));
 229        GET_V(nut->time_base[i].den, tmp > 0 && tmp < (1ULL << 31));
 230        if (av_gcd(nut->time_base[i].num, nut->time_base[i].den) != 1) {
 231            av_log(s, AV_LOG_ERROR, "invalid time base %d/%d\n",
 232                   nut->time_base[i].num,
 233                   nut->time_base[i].den);
 234            ret = AVERROR_INVALIDDATA;
 235            goto fail;
 236        }
 237    }
 238    tmp_pts      = 0;
 239    tmp_mul      = 1;
 240    tmp_stream   = 0;
 241    tmp_head_idx = 0;
 242    for (i = 0; i < 256;) {
 243        int tmp_flags  = ffio_read_varlen(bc);
 244        int tmp_fields = ffio_read_varlen(bc);
 245
 246        if (tmp_fields > 0)
 247            tmp_pts = get_s(bc);
 248        if (tmp_fields > 1)
 249            tmp_mul = ffio_read_varlen(bc);
 250        if (tmp_fields > 2)
 251            tmp_stream = ffio_read_varlen(bc);
 252        if (tmp_fields > 3)
 253            tmp_size = ffio_read_varlen(bc);
 254        else
 255            tmp_size = 0;
 256        if (tmp_fields > 4)
 257            tmp_res = ffio_read_varlen(bc);
 258        else
 259            tmp_res = 0;
 260        if (tmp_fields > 5)
 261            count = ffio_read_varlen(bc);
 262        else
 263            count = tmp_mul - tmp_size;
 264        if (tmp_fields > 6)
 265            get_s(bc);
 266        if (tmp_fields > 7)
 267            tmp_head_idx = ffio_read_varlen(bc);
 268
 269        while (tmp_fields-- > 8) {
 270            if (bc->eof_reached) {
 271                av_log(s, AV_LOG_ERROR, "reached EOF while decoding main header\n");
 272                ret = AVERROR_INVALIDDATA;
 273                goto fail;
 274            }
 275            ffio_read_varlen(bc);
 276        }
 277
 278        if (count <= 0 || count > 256 - (i <= 'N') - i) {
 279            av_log(s, AV_LOG_ERROR, "illegal count %d at %d\n", count, i);
 280            ret = AVERROR_INVALIDDATA;
 281            goto fail;
 282        }
 283        if (tmp_stream >= stream_count) {
 284            av_log(s, AV_LOG_ERROR, "illegal stream number %d >= %d\n",
 285                   tmp_stream, stream_count);
 286            ret = AVERROR_INVALIDDATA;
 287            goto fail;
 288        }
 289
 290        for (j = 0; j < count; j++, i++) {
 291            if (i == 'N') {
 292                nut->frame_code[i].flags = FLAG_INVALID;
 293                j--;
 294                continue;
 295            }
 296            nut->frame_code[i].flags          = tmp_flags;
 297            nut->frame_code[i].pts_delta      = tmp_pts;
 298            nut->frame_code[i].stream_id      = tmp_stream;
 299            nut->frame_code[i].size_mul       = tmp_mul;
 300            nut->frame_code[i].size_lsb       = tmp_size + j;
 301            nut->frame_code[i].reserved_count = tmp_res;
 302            nut->frame_code[i].header_idx     = tmp_head_idx;
 303        }
 304    }
 305    av_assert0(nut->frame_code['N'].flags == FLAG_INVALID);
 306
 307    if (end > avio_tell(bc) + 4) {
 308        int rem = 1024;
 309        GET_V(nut->header_count, tmp < 128U);
 310        nut->header_count++;
 311        for (i = 1; i < nut->header_count; i++) {
 312            uint8_t *hdr;
 313            GET_V(nut->header_len[i], tmp > 0 && tmp < 256);
 314            if (rem < nut->header_len[i]) {
 315                av_log(s, AV_LOG_ERROR,
 316                       "invalid elision header %d : %d > %d\n",
 317                       i, nut->header_len[i], rem);
 318                ret = AVERROR_INVALIDDATA;
 319                goto fail;
 320            }
 321            rem -= nut->header_len[i];
 322            hdr = av_malloc(nut->header_len[i]);
 323            if (!hdr) {
 324                ret = AVERROR(ENOMEM);
 325                goto fail;
 326            }
 327            avio_read(bc, hdr, nut->header_len[i]);
 328            nut->header[i] = hdr;
 329        }
 330        av_assert0(nut->header_len[0] == 0);
 331    }
 332
 333    // flags had been effectively introduced in version 4
 334    if (nut->version > 3 && end > avio_tell(bc) + 4) {
 335        nut->flags = ffio_read_varlen(bc);
 336    }
 337
 338    if (skip_reserved(bc, end) || ffio_get_checksum(bc)) {
 339        av_log(s, AV_LOG_ERROR, "main header checksum mismatch\n");
 340        ret = AVERROR_INVALIDDATA;
 341        goto fail;
 342    }
 343
 344    nut->stream = av_calloc(stream_count, sizeof(StreamContext));
 345    if (!nut->stream) {
 346        ret = AVERROR(ENOMEM);
 347        goto fail;
 348    }
 349    for (i = 0; i < stream_count; i++)
 350        avformat_new_stream(s, NULL);
 351
 352    return 0;
 353fail:
 354    av_freep(&nut->time_base);
 355    for (i = 1; i < nut->header_count; i++) {
 356        av_freep(&nut->header[i]);
 357    }
 358    nut->header_count = 0;
 359    return ret;
 360}
 361
 362static int decode_stream_header(NUTContext *nut)
 363{
 364    AVFormatContext *s = nut->avf;
 365    AVIOContext *bc    = s->pb;
 366    StreamContext *stc;
 367    int class, stream_id, ret;
 368    uint64_t tmp, end;
 369    AVStream *st = NULL;
 370
 371    end  = get_packetheader(nut, bc, 1, STREAM_STARTCODE);
 372    end += avio_tell(bc);
 373
 374    GET_V(stream_id, tmp < s->nb_streams && !nut->stream[tmp].time_base);
 375    stc = &nut->stream[stream_id];
 376    st  = s->streams[stream_id];
 377    if (!st)
 378        return AVERROR(ENOMEM);
 379
 380    class                = ffio_read_varlen(bc);
 381    tmp                  = get_fourcc(bc);
 382    st->codecpar->codec_tag = tmp;
 383    switch (class) {
 384    case 0:
 385        st->codecpar->codec_type = AVMEDIA_TYPE_VIDEO;
 386        st->codecpar->codec_id   = av_codec_get_id((const AVCodecTag * const []) {
 387                                                    ff_nut_video_tags,
 388                                                    ff_codec_bmp_tags,
 389                                                    ff_codec_movvideo_tags,
 390                                                    0
 391                                                },
 392                                                tmp);
 393        break;
 394    case 1:
 395        st->codecpar->codec_type = AVMEDIA_TYPE_AUDIO;
 396        st->codecpar->codec_id   = av_codec_get_id((const AVCodecTag * const []) {
 397                                                    ff_nut_audio_tags,
 398                                                    ff_codec_wav_tags,
 399                                                    ff_nut_audio_extra_tags,
 400                                                    0
 401                                                },
 402                                                tmp);
 403        break;
 404    case 2:
 405        st->codecpar->codec_type = AVMEDIA_TYPE_SUBTITLE;
 406        st->codecpar->codec_id   = ff_codec_get_id(ff_nut_subtitle_tags, tmp);
 407        break;
 408    case 3:
 409        st->codecpar->codec_type = AVMEDIA_TYPE_DATA;
 410        st->codecpar->codec_id   = ff_codec_get_id(ff_nut_data_tags, tmp);
 411        break;
 412    default:
 413        av_log(s, AV_LOG_ERROR, "unknown stream class (%d)\n", class);
 414        return AVERROR(ENOSYS);
 415    }
 416    if (class < 3 && st->codecpar->codec_id == AV_CODEC_ID_NONE)
 417        av_log(s, AV_LOG_ERROR,
 418               "Unknown codec tag '0x%04x' for stream number %d\n",
 419               (unsigned int) tmp, stream_id);
 420
 421    GET_V(stc->time_base_id, tmp < nut->time_base_count);
 422    GET_V(stc->msb_pts_shift, tmp < 16);
 423    stc->max_pts_distance = ffio_read_varlen(bc);
 424    GET_V(stc->decode_delay, tmp < 1000); // sanity limit, raise this if Moore's law is true
 425    st->codecpar->video_delay = stc->decode_delay;
 426    ffio_read_varlen(bc); // stream flags
 427
 428    GET_V(st->codecpar->extradata_size, tmp < (1 << 30));
 429    if (st->codecpar->extradata_size) {
 430        ret = ff_get_extradata(s, st->codecpar, bc,
 431                               st->codecpar->extradata_size);
 432        if (ret < 0)
 433            return ret;
 434    }
 435
 436    if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
 437        GET_V(st->codecpar->width,  tmp > 0);
 438        GET_V(st->codecpar->height, tmp > 0);
 439        st->sample_aspect_ratio.num = ffio_read_varlen(bc);
 440        st->sample_aspect_ratio.den = ffio_read_varlen(bc);
 441        if ((!st->sample_aspect_ratio.num) != (!st->sample_aspect_ratio.den)) {
 442            av_log(s, AV_LOG_ERROR, "invalid aspect ratio %d/%d\n",
 443                   st->sample_aspect_ratio.num, st->sample_aspect_ratio.den);
 444            ret = AVERROR_INVALIDDATA;
 445            goto fail;
 446        }
 447        ffio_read_varlen(bc); /* csp type */
 448    } else if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) {
 449        GET_V(st->codecpar->sample_rate, tmp > 0);
 450        ffio_read_varlen(bc); // samplerate_den
 451        GET_V(st->codecpar->channels, tmp > 0);
 452    }
 453    if (skip_reserved(bc, end) || ffio_get_checksum(bc)) {
 454        av_log(s, AV_LOG_ERROR,
 455               "stream header %d checksum mismatch\n", stream_id);
 456        ret = AVERROR_INVALIDDATA;
 457        goto fail;
 458    }
 459    stc->time_base = &nut->time_base[stc->time_base_id];
 460    avpriv_set_pts_info(s->streams[stream_id], 63, stc->time_base->num,
 461                        stc->time_base->den);
 462    return 0;
 463fail:
 464    if (st && st->codecpar) {
 465        av_freep(&st->codecpar->extradata);
 466        st->codecpar->extradata_size = 0;
 467    }
 468    return ret;
 469}
 470
 471static void set_disposition_bits(AVFormatContext *avf, char *value,
 472                                 int stream_id)
 473{
 474    int flag = 0, i;
 475
 476    for (i = 0; ff_nut_dispositions[i].flag; ++i)
 477        if (!strcmp(ff_nut_dispositions[i].str, value))
 478            flag = ff_nut_dispositions[i].flag;
 479    if (!flag)
 480        av_log(avf, AV_LOG_INFO, "unknown disposition type '%s'\n", value);
 481    for (i = 0; i < avf->nb_streams; ++i)
 482        if (stream_id == i || stream_id == -1)
 483            avf->streams[i]->disposition |= flag;
 484}
 485
 486static int decode_info_header(NUTContext *nut)
 487{
 488    AVFormatContext *s = nut->avf;
 489    AVIOContext *bc    = s->pb;
 490    uint64_t tmp, chapter_start, chapter_len;
 491    unsigned int stream_id_plus1, count;
 492    int chapter_id, i, ret = 0;
 493    int64_t value, end;
 494    char name[256], str_value[1024], type_str[256];
 495    const char *type;
 496    int *event_flags        = NULL;
 497    AVChapter *chapter      = NULL;
 498    AVStream *st            = NULL;
 499    AVDictionary **metadata = NULL;
 500    int metadata_flag       = 0;
 501
 502    end  = get_packetheader(nut, bc, 1, INFO_STARTCODE);
 503    end += avio_tell(bc);
 504
 505    GET_V(stream_id_plus1, tmp <= s->nb_streams);
 506    chapter_id    = get_s(bc);
 507    chapter_start = ffio_read_varlen(bc);
 508    chapter_len   = ffio_read_varlen(bc);
 509    count         = ffio_read_varlen(bc);
 510
 511    if (chapter_id && !stream_id_plus1) {
 512        int64_t start = chapter_start / nut->time_base_count;
 513        chapter = avpriv_new_chapter(s, chapter_id,
 514                                     nut->time_base[chapter_start %
 515                                                    nut->time_base_count],
 516                                     start, start + chapter_len, NULL);
 517        if (!chapter) {
 518            av_log(s, AV_LOG_ERROR, "Could not create chapter.\n");
 519            return AVERROR(ENOMEM);
 520        }
 521        metadata = &chapter->metadata;
 522    } else if (stream_id_plus1) {
 523        st       = s->streams[stream_id_plus1 - 1];
 524        metadata = &st->metadata;
 525        event_flags = &st->event_flags;
 526        metadata_flag = AVSTREAM_EVENT_FLAG_METADATA_UPDATED;
 527    } else {
 528        metadata = &s->metadata;
 529        event_flags = &s->event_flags;
 530        metadata_flag = AVFMT_EVENT_FLAG_METADATA_UPDATED;
 531    }
 532
 533    for (i = 0; i < count; i++) {
 534        ret = get_str(bc, name, sizeof(name));
 535        if (ret < 0) {
 536            av_log(s, AV_LOG_ERROR, "get_str failed while decoding info header\n");
 537            return ret;
 538        }
 539        value = get_s(bc);
 540        str_value[0] = 0;
 541
 542        if (value == -1) {
 543            type = "UTF-8";
 544            ret = get_str(bc, str_value, sizeof(str_value));
 545        } else if (value == -2) {
 546            ret = get_str(bc, type_str, sizeof(type_str));
 547            if (ret < 0) {
 548                av_log(s, AV_LOG_ERROR, "get_str failed while decoding info header\n");
 549                return ret;
 550            }
 551            type = type_str;
 552            ret = get_str(bc, str_value, sizeof(str_value));
 553        } else if (value == -3) {
 554            type  = "s";
 555            value = get_s(bc);
 556        } else if (value == -4) {
 557            type  = "t";
 558            value = ffio_read_varlen(bc);
 559        } else if (value < -4) {
 560            type = "r";
 561            get_s(bc);
 562        } else {
 563            type = "v";
 564        }
 565
 566        if (ret < 0) {
 567            av_log(s, AV_LOG_ERROR, "get_str failed while decoding info header\n");
 568            return ret;
 569        }
 570
 571        if (stream_id_plus1 > s->nb_streams) {
 572            av_log(s, AV_LOG_WARNING,
 573                   "invalid stream id %d for info packet\n",
 574                   stream_id_plus1);
 575            continue;
 576        }
 577
 578        if (!strcmp(type, "UTF-8")) {
 579            if (chapter_id == 0 && !strcmp(name, "Disposition")) {
 580                set_disposition_bits(s, str_value, stream_id_plus1 - 1);
 581                continue;
 582            }
 583
 584            if (stream_id_plus1 && !strcmp(name, "r_frame_rate")) {
 585                sscanf(str_value, "%d/%d", &st->r_frame_rate.num, &st->r_frame_rate.den);
 586                if (st->r_frame_rate.num >= 1000LL*st->r_frame_rate.den ||
 587                    st->r_frame_rate.num < 0 || st->r_frame_rate.den < 0)
 588                    st->r_frame_rate.num = st->r_frame_rate.den = 0;
 589                continue;
 590            }
 591
 592            if (metadata && av_strcasecmp(name, "Uses") &&
 593                av_strcasecmp(name, "Depends") && av_strcasecmp(name, "Replaces")) {
 594                if (event_flags)
 595                    *event_flags |= metadata_flag;
 596                av_dict_set(metadata, name, str_value, 0);
 597            }
 598        }
 599    }
 600
 601    if (skip_reserved(bc, end) || ffio_get_checksum(bc)) {
 602        av_log(s, AV_LOG_ERROR, "info header checksum mismatch\n");
 603        return AVERROR_INVALIDDATA;
 604    }
 605fail:
 606    return FFMIN(ret, 0);
 607}
 608
 609static int decode_syncpoint(NUTContext *nut, int64_t *ts, int64_t *back_ptr)
 610{
 611    AVFormatContext *s = nut->avf;
 612    AVIOContext *bc    = s->pb;
 613    int64_t end;
 614    uint64_t tmp;
 615    int ret;
 616
 617    nut->last_syncpoint_pos = avio_tell(bc) - 8;
 618
 619    end  = get_packetheader(nut, bc, 1, SYNCPOINT_STARTCODE);
 620    end += avio_tell(bc);
 621
 622    tmp       = ffio_read_varlen(bc);
 623    *back_ptr = nut->last_syncpoint_pos - 16 * ffio_read_varlen(bc);
 624    if (*back_ptr < 0)
 625        return AVERROR_INVALIDDATA;
 626
 627    ff_nut_reset_ts(nut, nut->time_base[tmp % nut->time_base_count],
 628                    tmp / nut->time_base_count);
 629
 630    if (nut->flags & NUT_BROADCAST) {
 631        tmp = ffio_read_varlen(bc);
 632        av_log(s, AV_LOG_VERBOSE, "Syncpoint wallclock %"PRId64"\n",
 633               av_rescale_q(tmp / nut->time_base_count,
 634                            nut->time_base[tmp % nut->time_base_count],
 635                            AV_TIME_BASE_Q));
 636    }
 637
 638    if (skip_reserved(bc, end) || ffio_get_checksum(bc)) {
 639        av_log(s, AV_LOG_ERROR, "sync point checksum mismatch\n");
 640        return AVERROR_INVALIDDATA;
 641    }
 642
 643    *ts = tmp / nut->time_base_count *
 644          av_q2d(nut->time_base[tmp % nut->time_base_count]) * AV_TIME_BASE;
 645
 646    if ((ret = ff_nut_add_sp(nut, nut->last_syncpoint_pos, *back_ptr, *ts)) < 0)
 647        return ret;
 648
 649    return 0;
 650}
 651
 652//FIXME calculate exactly, this is just a good approximation.
 653static int64_t find_duration(NUTContext *nut, int64_t filesize)
 654{
 655    AVFormatContext *s = nut->avf;
 656    int64_t duration = 0;
 657
 658    ff_find_last_ts(s, -1, &duration, NULL, nut_read_timestamp);
 659
 660    if(duration > 0)
 661        s->duration_estimation_method = AVFMT_DURATION_FROM_PTS;
 662    return duration;
 663}
 664
 665static int find_and_decode_index(NUTContext *nut)
 666{
 667    AVFormatContext *s = nut->avf;
 668    AVIOContext *bc    = s->pb;
 669    uint64_t tmp, end;
 670    int i, j, syncpoint_count;
 671    int64_t filesize = avio_size(bc);
 672    int64_t *syncpoints = NULL;
 673    uint64_t max_pts;
 674    int8_t *has_keyframe = NULL;
 675    int ret = AVERROR_INVALIDDATA;
 676
 677    if(filesize <= 0)
 678        return -1;
 679
 680    avio_seek(bc, filesize - 12, SEEK_SET);
 681    avio_seek(bc, filesize - avio_rb64(bc), SEEK_SET);
 682    if (avio_rb64(bc) != INDEX_STARTCODE) {
 683        av_log(s, AV_LOG_WARNING, "no index at the end\n");
 684
 685        if(s->duration<=0)
 686            s->duration = find_duration(nut, filesize);
 687        return ret;
 688    }
 689
 690    end  = get_packetheader(nut, bc, 1, INDEX_STARTCODE);
 691    end += avio_tell(bc);
 692
 693    max_pts = ffio_read_varlen(bc);
 694    s->duration = av_rescale_q(max_pts / nut->time_base_count,
 695                               nut->time_base[max_pts % nut->time_base_count],
 696                               AV_TIME_BASE_Q);
 697    s->duration_estimation_method = AVFMT_DURATION_FROM_PTS;
 698
 699    GET_V(syncpoint_count, tmp < INT_MAX / 8 && tmp > 0);
 700    syncpoints   = av_malloc_array(syncpoint_count, sizeof(int64_t));
 701    has_keyframe = av_malloc_array(syncpoint_count + 1, sizeof(int8_t));
 702    if (!syncpoints || !has_keyframe) {
 703        ret = AVERROR(ENOMEM);
 704        goto fail;
 705    }
 706    for (i = 0; i < syncpoint_count; i++) {
 707        syncpoints[i] = ffio_read_varlen(bc);
 708        if (syncpoints[i] <= 0)
 709            goto fail;
 710        if (i)
 711            syncpoints[i] += syncpoints[i - 1];
 712    }
 713
 714    for (i = 0; i < s->nb_streams; i++) {
 715        int64_t last_pts = -1;
 716        for (j = 0; j < syncpoint_count;) {
 717            uint64_t x = ffio_read_varlen(bc);
 718            int type   = x & 1;
 719            int n      = j;
 720            x >>= 1;
 721            if (type) {
 722                int flag = x & 1;
 723                x >>= 1;
 724                if (n + x >= syncpoint_count + 1) {
 725                    av_log(s, AV_LOG_ERROR, "index overflow A %d + %"PRIu64" >= %d\n", n, x, syncpoint_count + 1);
 726                    goto fail;
 727                }
 728                while (x--)
 729                    has_keyframe[n++] = flag;
 730                has_keyframe[n++] = !flag;
 731            } else {
 732                if (x <= 1) {
 733                    av_log(s, AV_LOG_ERROR, "index: x %"PRIu64" is invalid\n", x);
 734                    goto fail;
 735                }
 736                while (x != 1) {
 737                    if (n >= syncpoint_count + 1) {
 738                        av_log(s, AV_LOG_ERROR, "index overflow B\n");
 739                        goto fail;
 740                    }
 741                    has_keyframe[n++] = x & 1;
 742                    x >>= 1;
 743                }
 744            }
 745            if (has_keyframe[0]) {
 746                av_log(s, AV_LOG_ERROR, "keyframe before first syncpoint in index\n");
 747                goto fail;
 748            }
 749            av_assert0(n <= syncpoint_count + 1);
 750            for (; j < n && j < syncpoint_count; j++) {
 751                if (has_keyframe[j]) {
 752                    uint64_t B, A = ffio_read_varlen(bc);
 753                    if (!A) {
 754                        A = ffio_read_varlen(bc);
 755                        B = ffio_read_varlen(bc);
 756                        // eor_pts[j][i] = last_pts + A + B
 757                    } else
 758                        B = 0;
 759                    av_add_index_entry(s->streams[i], 16 * syncpoints[j - 1],
 760                                       last_pts + A, 0, 0, AVINDEX_KEYFRAME);
 761                    last_pts += A + B;
 762                }
 763            }
 764        }
 765    }
 766
 767    if (skip_reserved(bc, end) || ffio_get_checksum(bc)) {
 768        av_log(s, AV_LOG_ERROR, "index checksum mismatch\n");
 769        goto fail;
 770    }
 771    ret = 0;
 772
 773fail:
 774    av_free(syncpoints);
 775    av_free(has_keyframe);
 776    return ret;
 777}
 778
 779static int nut_read_close(AVFormatContext *s)
 780{
 781    NUTContext *nut = s->priv_data;
 782    int i;
 783
 784    av_freep(&nut->time_base);
 785    av_freep(&nut->stream);
 786    ff_nut_free_sp(nut);
 787    for (i = 1; i < nut->header_count; i++)
 788        av_freep(&nut->header[i]);
 789
 790    return 0;
 791}
 792
 793static int nut_read_header(AVFormatContext *s)
 794{
 795    NUTContext *nut = s->priv_data;
 796    AVIOContext *bc = s->pb;
 797    int64_t pos;
 798    int initialized_stream_count;
 799
 800    nut->avf = s;
 801
 802    /* main header */
 803    pos = 0;
 804    do {
 805        pos = find_startcode(bc, MAIN_STARTCODE, pos) + 1;
 806        if (pos < 0 + 1) {
 807            av_log(s, AV_LOG_ERROR, "No main startcode found.\n");
 808            goto fail;
 809        }
 810    } while (decode_main_header(nut) < 0);
 811
 812    /* stream headers */
 813    pos = 0;
 814    for (initialized_stream_count = 0; initialized_stream_count < s->nb_streams;) {
 815        pos = find_startcode(bc, STREAM_STARTCODE, pos) + 1;
 816        if (pos < 0 + 1) {
 817            av_log(s, AV_LOG_ERROR, "Not all stream headers found.\n");
 818            goto fail;
 819        }
 820        if (decode_stream_header(nut) >= 0)
 821            initialized_stream_count++;
 822    }
 823
 824    /* info headers */
 825    pos = 0;
 826    for (;;) {
 827        uint64_t startcode = find_any_startcode(bc, pos);
 828        pos = avio_tell(bc);
 829
 830        if (startcode == 0) {
 831            av_log(s, AV_LOG_ERROR, "EOF before video frames\n");
 832            goto fail;
 833        } else if (startcode == SYNCPOINT_STARTCODE) {
 834            nut->next_startcode = startcode;
 835            break;
 836        } else if (startcode != INFO_STARTCODE) {
 837            continue;
 838        }
 839
 840        decode_info_header(nut);
 841    }
 842
 843    s->internal->data_offset = pos - 8;
 844
 845    if (bc->seekable & AVIO_SEEKABLE_NORMAL) {
 846        int64_t orig_pos = avio_tell(bc);
 847        find_and_decode_index(nut);
 848        avio_seek(bc, orig_pos, SEEK_SET);
 849    }
 850    av_assert0(nut->next_startcode == SYNCPOINT_STARTCODE);
 851
 852    ff_metadata_conv_ctx(s, NULL, ff_nut_metadata_conv);
 853
 854    return 0;
 855
 856fail:
 857    nut_read_close(s);
 858
 859    return AVERROR_INVALIDDATA;
 860}
 861
 862static int read_sm_data(AVFormatContext *s, AVIOContext *bc, AVPacket *pkt, int is_meta, int64_t maxpos)
 863{
 864    int count = ffio_read_varlen(bc);
 865    int skip_start = 0;
 866    int skip_end = 0;
 867    int channels = 0;
 868    int64_t channel_layout = 0;
 869    int sample_rate = 0;
 870    int width = 0;
 871    int height = 0;
 872    int i, ret;
 873
 874    for (i=0; i<count; i++) {
 875        uint8_t name[256], str_value[256], type_str[256];
 876        int value;
 877        if (avio_tell(bc) >= maxpos)
 878            return AVERROR_INVALIDDATA;
 879        ret = get_str(bc, name, sizeof(name));
 880        if (ret < 0) {
 881            av_log(s, AV_LOG_ERROR, "get_str failed while reading sm data\n");
 882            return ret;
 883        }
 884        value = get_s(bc);
 885
 886        if (value == -1) {
 887            ret = get_str(bc, str_value, sizeof(str_value));
 888            if (ret < 0) {
 889                av_log(s, AV_LOG_ERROR, "get_str failed while reading sm data\n");
 890                return ret;
 891            }
 892            av_log(s, AV_LOG_WARNING, "Unknown string %s / %s\n", name, str_value);
 893        } else if (value == -2) {
 894            uint8_t *dst = NULL;
 895            int64_t v64, value_len;
 896
 897            ret = get_str(bc, type_str, sizeof(type_str));
 898            if (ret < 0) {
 899                av_log(s, AV_LOG_ERROR, "get_str failed while reading sm data\n");
 900                return ret;
 901            }
 902            value_len = ffio_read_varlen(bc);
 903            if (value_len < 0 || value_len >= maxpos - avio_tell(bc))
 904                return AVERROR_INVALIDDATA;
 905            if (!strcmp(name, "Palette")) {
 906                dst = av_packet_new_side_data(pkt, AV_PKT_DATA_PALETTE, value_len);
 907            } else if (!strcmp(name, "Extradata")) {
 908                dst = av_packet_new_side_data(pkt, AV_PKT_DATA_NEW_EXTRADATA, value_len);
 909            } else if (sscanf(name, "CodecSpecificSide%"SCNd64"", &v64) == 1) {
 910                dst = av_packet_new_side_data(pkt, AV_PKT_DATA_MATROSKA_BLOCKADDITIONAL, value_len + 8);
 911                if(!dst)
 912                    return AVERROR(ENOMEM);
 913                AV_WB64(dst, v64);
 914                dst += 8;
 915            } else if (!strcmp(name, "ChannelLayout") && value_len == 8) {
 916                channel_layout = avio_rl64(bc);
 917                continue;
 918            } else {
 919                av_log(s, AV_LOG_WARNING, "Unknown data %s / %s\n", name, type_str);
 920                avio_skip(bc, value_len);
 921                continue;
 922            }
 923            if(!dst)
 924                return AVERROR(ENOMEM);
 925            avio_read(bc, dst, value_len);
 926        } else if (value == -3) {
 927            value = get_s(bc);
 928        } else if (value == -4) {
 929            value = ffio_read_varlen(bc);
 930        } else if (value < -4) {
 931            get_s(bc);
 932        } else {
 933            if (!strcmp(name, "SkipStart")) {
 934                skip_start = value;
 935            } else if (!strcmp(name, "SkipEnd")) {
 936                skip_end = value;
 937            } else if (!strcmp(name, "Channels")) {
 938                channels = value;
 939            } else if (!strcmp(name, "SampleRate")) {
 940                sample_rate = value;
 941            } else if (!strcmp(name, "Width")) {
 942                width = value;
 943            } else if (!strcmp(name, "Height")) {
 944                height = value;
 945            } else {
 946                av_log(s, AV_LOG_WARNING, "Unknown integer %s\n", name);
 947            }
 948        }
 949    }
 950
 951    if (channels || channel_layout || sample_rate || width || height) {
 952        uint8_t *dst = av_packet_new_side_data(pkt, AV_PKT_DATA_PARAM_CHANGE, 28);
 953        if (!dst)
 954            return AVERROR(ENOMEM);
 955        bytestream_put_le32(&dst,
 956                            AV_SIDE_DATA_PARAM_CHANGE_CHANNEL_COUNT*(!!channels) +
 957                            AV_SIDE_DATA_PARAM_CHANGE_CHANNEL_LAYOUT*(!!channel_layout) +
 958                            AV_SIDE_DATA_PARAM_CHANGE_SAMPLE_RATE*(!!sample_rate) +
 959                            AV_SIDE_DATA_PARAM_CHANGE_DIMENSIONS*(!!(width|height))
 960                           );
 961        if (channels)
 962            bytestream_put_le32(&dst, channels);
 963        if (channel_layout)
 964            bytestream_put_le64(&dst, channel_layout);
 965        if (sample_rate)
 966            bytestream_put_le32(&dst, sample_rate);
 967        if (width || height){
 968            bytestream_put_le32(&dst, width);
 969            bytestream_put_le32(&dst, height);
 970        }
 971    }
 972
 973    if (skip_start || skip_end) {
 974        uint8_t *dst = av_packet_new_side_data(pkt, AV_PKT_DATA_SKIP_SAMPLES, 10);
 975        if (!dst)
 976            return AVERROR(ENOMEM);
 977        AV_WL32(dst, skip_start);
 978        AV_WL32(dst+4, skip_end);
 979    }
 980
 981    if (avio_tell(bc) >= maxpos)
 982        return AVERROR_INVALIDDATA;
 983
 984    return 0;
 985}
 986
 987static int decode_frame_header(NUTContext *nut, int64_t *pts, int *stream_id,
 988                               uint8_t *header_idx, int frame_code)
 989{
 990    AVFormatContext *s = nut->avf;
 991    AVIOContext *bc    = s->pb;
 992    StreamContext *stc;
 993    int size, flags, size_mul, pts_delta, i, reserved_count, ret;
 994    uint64_t tmp;
 995
 996    if (!(nut->flags & NUT_PIPE) &&
 997        avio_tell(bc) > nut->last_syncpoint_pos + nut->max_distance) {
 998        av_log(s, AV_LOG_ERROR,
 999               "Last frame must have been damaged %"PRId64" > %"PRId64" + %d\n",
1000               avio_tell(bc), nut->last_syncpoint_pos, nut->max_distance);
1001        return AVERROR_INVALIDDATA;
1002    }
1003
1004    flags          = nut->frame_code[frame_code].flags;
1005    size_mul       = nut->frame_code[frame_code].size_mul;
1006    size           = nut->frame_code[frame_code].size_lsb;
1007    *stream_id     = nut->frame_code[frame_code].stream_id;
1008    pts_delta      = nut->frame_code[frame_code].pts_delta;
1009    reserved_count = nut->frame_code[frame_code].reserved_count;
1010    *header_idx    = nut->frame_code[frame_code].header_idx;
1011
1012    if (flags & FLAG_INVALID)
1013        return AVERROR_INVALIDDATA;
1014    if (flags & FLAG_CODED)
1015        flags ^= ffio_read_varlen(bc);
1016    if (flags & FLAG_STREAM_ID) {
1017        GET_V(*stream_id, tmp < s->nb_streams);
1018    }
1019    stc = &nut->stream[*stream_id];
1020    if (flags & FLAG_CODED_PTS) {
1021        int64_t coded_pts = ffio_read_varlen(bc);
1022        // FIXME check last_pts validity?
1023        if (coded_pts < (1LL << stc->msb_pts_shift)) {
1024            *pts = ff_lsb2full(stc, coded_pts);
1025        } else
1026            *pts = coded_pts - (1LL << stc->msb_pts_shift);
1027    } else
1028        *pts = stc->last_pts + pts_delta;
1029    if (flags & FLAG_SIZE_MSB)
1030        size += size_mul * ffio_read_varlen(bc);
1031    if (flags & FLAG_MATCH_TIME)
1032        get_s(bc);
1033    if (flags & FLAG_HEADER_IDX)
1034        *header_idx = ffio_read_varlen(bc);
1035    if (flags & FLAG_RESERVED)
1036        reserved_count = ffio_read_varlen(bc);
1037    for (i = 0; i < reserved_count; i++) {
1038        if (bc->eof_reached) {
1039            av_log(s, AV_LOG_ERROR, "reached EOF while decoding frame header\n");
1040            return AVERROR_INVALIDDATA;
1041        }
1042        ffio_read_varlen(bc);
1043    }
1044
1045    if (*header_idx >= (unsigned)nut->header_count) {
1046        av_log(s, AV_LOG_ERROR, "header_idx invalid\n");
1047        return AVERROR_INVALIDDATA;
1048    }
1049    if (size > 4096)
1050        *header_idx = 0;
1051    size -= nut->header_len[*header_idx];
1052
1053    if (flags & FLAG_CHECKSUM) {
1054        avio_rb32(bc); // FIXME check this
1055    } else if (!(nut->flags & NUT_PIPE) &&
1056               size > 2 * nut->max_distance ||
1057               FFABS(stc->last_pts - *pts) > stc->max_pts_distance) {
1058        av_log(s, AV_LOG_ERROR, "frame size > 2max_distance and no checksum\n");
1059        return AVERROR_INVALIDDATA;
1060    }
1061
1062    stc->last_pts   = *pts;
1063    stc->last_flags = flags;
1064
1065    return size;
1066fail:
1067    return ret;
1068}
1069
1070static int decode_frame(NUTContext *nut, AVPacket *pkt, int frame_code)
1071{
1072    AVFormatContext *s = nut->avf;
1073    AVIOContext *bc    = s->pb;
1074    int size, stream_id, discard, ret;
1075    int64_t pts, last_IP_pts;
1076    StreamContext *stc;
1077    uint8_t header_idx;
1078
1079    size = decode_frame_header(nut, &pts, &stream_id, &header_idx, frame_code);
1080    if (size < 0)
1081        return size;
1082
1083    stc = &nut->stream[stream_id];
1084
1085    if (stc->last_flags & FLAG_KEY)
1086        stc->skip_until_key_frame = 0;
1087
1088    discard     = s->streams[stream_id]->discard;
1089    last_IP_pts = s->streams[stream_id]->last_IP_pts;
1090    if ((discard >= AVDISCARD_NONKEY && !(stc->last_flags & FLAG_KEY)) ||
1091        (discard >= AVDISCARD_BIDIR  && last_IP_pts != AV_NOPTS_VALUE &&
1092         last_IP_pts > pts) ||
1093        discard >= AVDISCARD_ALL ||
1094        stc->skip_until_key_frame) {
1095        avio_skip(bc, size);
1096        return 1;
1097    }
1098
1099    ret = av_new_packet(pkt, size + nut->header_len[header_idx]);
1100    if (ret < 0)
1101        return ret;
1102    if (nut->header[header_idx])
1103        memcpy(pkt->data, nut->header[header_idx], nut->header_len[header_idx]);
1104    pkt->pos = avio_tell(bc); // FIXME
1105    if (stc->last_flags & FLAG_SM_DATA) {
1106        int sm_size;
1107        if (read_sm_data(s, bc, pkt, 0, pkt->pos + size) < 0) {
1108            ret = AVERROR_INVALIDDATA;
1109            goto fail;
1110        }
1111        if (read_sm_data(s, bc, pkt, 1, pkt->pos + size) < 0) {
1112            ret = AVERROR_INVALIDDATA;
1113            goto fail;
1114        }
1115        sm_size = avio_tell(bc) - pkt->pos;
1116        size      -= sm_size;
1117        pkt->size -= sm_size;
1118    }
1119
1120    ret = avio_read(bc, pkt->data + nut->header_len[header_idx], size);
1121    if (ret != size) {
1122        if (ret < 0)
1123            goto fail;
1124    }
1125    av_shrink_packet(pkt, nut->header_len[header_idx] + ret);
1126
1127    pkt->stream_index = stream_id;
1128    if (stc->last_flags & FLAG_KEY)
1129        pkt->flags |= AV_PKT_FLAG_KEY;
1130    pkt->pts = pts;
1131
1132    return 0;
1133fail:
1134    av_packet_unref(pkt);
1135    return ret;
1136}
1137
1138static int nut_read_packet(AVFormatContext *s, AVPacket *pkt)
1139{
1140    NUTContext *nut = s->priv_data;
1141    AVIOContext *bc = s->pb;
1142    int i, frame_code = 0, ret, skip;
1143    int64_t ts, back_ptr;
1144
1145    for (;;) {
1146        int64_t pos  = avio_tell(bc);
1147        uint64_t tmp = nut->next_startcode;
1148        nut->next_startcode = 0;
1149
1150        if (tmp) {
1151            pos -= 8;
1152        } else {
1153            frame_code = avio_r8(bc);
1154            if (avio_feof(bc))
1155                return AVERROR_EOF;
1156            if (frame_code == 'N') {
1157                tmp = frame_code;
1158                for (i = 1; i < 8; i++)
1159                    tmp = (tmp << 8) + avio_r8(bc);
1160            }
1161        }
1162        switch (tmp) {
1163        case MAIN_STARTCODE:
1164        case STREAM_STARTCODE:
1165        case INDEX_STARTCODE:
1166            skip = get_packetheader(nut, bc, 0, tmp);
1167            avio_skip(bc, skip);
1168            break;
1169        case INFO_STARTCODE:
1170            if (decode_info_header(nut) < 0)
1171                goto resync;
1172            break;
1173        case SYNCPOINT_STARTCODE:
1174            if (decode_syncpoint(nut, &ts, &back_ptr) < 0)
1175                goto resync;
1176            frame_code = avio_r8(bc);
1177        case 0:
1178            ret = decode_frame(nut, pkt, frame_code);
1179            if (ret == 0)
1180                return 0;
1181            else if (ret == 1) // OK but discard packet
1182                break;
1183        default:
1184resync:
1185            av_log(s, AV_LOG_DEBUG, "syncing from %"PRId64"\n", pos);
1186            tmp = find_any_startcode(bc, FFMAX(nut->last_syncpoint_pos, nut->last_resync_pos) + 1);
1187            nut->last_resync_pos = avio_tell(bc);
1188            if (tmp == 0)
1189                return AVERROR_INVALIDDATA;
1190            av_log(s, AV_LOG_DEBUG, "sync\n");
1191            nut->next_startcode = tmp;
1192        }
1193    }
1194}
1195
1196static int64_t nut_read_timestamp(AVFormatContext *s, int stream_index,
1197                                  int64_t *pos_arg, int64_t pos_limit)
1198{
1199    NUTContext *nut = s->priv_data;
1200    AVIOContext *bc = s->pb;
1201    int64_t pos, pts, back_ptr;
1202    av_log(s, AV_LOG_DEBUG, "read_timestamp(X,%d,%"PRId64",%"PRId64")\n",
1203           stream_index, *pos_arg, pos_limit);
1204
1205    pos = *pos_arg;
1206    do {
1207        pos = find_startcode(bc, SYNCPOINT_STARTCODE, pos) + 1;
1208        if (pos < 1) {
1209            av_log(s, AV_LOG_ERROR, "read_timestamp failed.\n");
1210            return AV_NOPTS_VALUE;
1211        }
1212    } while (decode_syncpoint(nut, &pts, &back_ptr) < 0);
1213    *pos_arg = pos - 1;
1214    av_assert0(nut->last_syncpoint_pos == *pos_arg);
1215
1216    av_log(s, AV_LOG_DEBUG, "return %"PRId64" %"PRId64"\n", pts, back_ptr);
1217    if (stream_index == -2)
1218        return back_ptr;
1219    av_assert0(stream_index == -1);
1220    return pts;
1221}
1222
1223static int read_seek(AVFormatContext *s, int stream_index,
1224                     int64_t pts, int flags)
1225{
1226    NUTContext *nut    = s->priv_data;
1227    AVStream *st       = s->streams[stream_index];
1228    Syncpoint dummy    = { .ts = pts * av_q2d(st->time_base) * AV_TIME_BASE };
1229    Syncpoint nopts_sp = { .ts = AV_NOPTS_VALUE, .back_ptr = AV_NOPTS_VALUE };
1230    Syncpoint *sp, *next_node[2] = { &nopts_sp, &nopts_sp };
1231    int64_t pos, pos2, ts;
1232    int i;
1233
1234    if (nut->flags & NUT_PIPE) {
1235        return AVERROR(ENOSYS);
1236    }
1237
1238    if (st->index_entries) {
1239        int index = av_index_search_timestamp(st, pts, flags);
1240        if (index < 0)
1241            index = av_index_search_timestamp(st, pts, flags ^ AVSEEK_FLAG_BACKWARD);
1242        if (index < 0)
1243            return -1;
1244
1245        pos2 = st->index_entries[index].pos;
1246        ts   = st->index_entries[index].timestamp;
1247    } else {
1248        av_tree_find(nut->syncpoints, &dummy, ff_nut_sp_pts_cmp,
1249                     (void **) next_node);
1250        av_log(s, AV_LOG_DEBUG, "%"PRIu64"-%"PRIu64" %"PRId64"-%"PRId64"\n",
1251               next_node[0]->pos, next_node[1]->pos, next_node[0]->ts,
1252               next_node[1]->ts);
1253        pos = ff_gen_search(s, -1, dummy.ts, next_node[0]->pos,
1254                            next_node[1]->pos, next_node[1]->pos,
1255                            next_node[0]->ts, next_node[1]->ts,
1256                            AVSEEK_FLAG_BACKWARD, &ts, nut_read_timestamp);
1257        if (pos < 0)
1258            return pos;
1259
1260        if (!(flags & AVSEEK_FLAG_BACKWARD)) {
1261            dummy.pos    = pos + 16;
1262            next_node[1] = &nopts_sp;
1263            av_tree_find(nut->syncpoints, &dummy, ff_nut_sp_pos_cmp,
1264                         (void **) next_node);
1265            pos2 = ff_gen_search(s, -2, dummy.pos, next_node[0]->pos,
1266                                 next_node[1]->pos, next_node[1]->pos,
1267                                 next_node[0]->back_ptr, next_node[1]->back_ptr,
1268                                 flags, &ts, nut_read_timestamp);
1269            if (pos2 >= 0)
1270                pos = pos2;
1271            // FIXME dir but I think it does not matter
1272        }
1273        dummy.pos = pos;
1274        sp = av_tree_find(nut->syncpoints, &dummy, ff_nut_sp_pos_cmp,
1275                          NULL);
1276
1277        av_assert0(sp);
1278        pos2 = sp->back_ptr - 15;
1279    }
1280    av_log(s, AV_LOG_DEBUG, "SEEKTO: %"PRId64"\n", pos2);
1281    pos = find_startcode(s->pb, SYNCPOINT_STARTCODE, pos2);
1282    avio_seek(s->pb, pos, SEEK_SET);
1283    nut->last_syncpoint_pos = pos;
1284    av_log(s, AV_LOG_DEBUG, "SP: %"PRId64"\n", pos);
1285    if (pos2 > pos || pos2 + 15 < pos)
1286        av_log(s, AV_LOG_ERROR, "no syncpoint at backptr pos\n");
1287    for (i = 0; i < s->nb_streams; i++)
1288        nut->stream[i].skip_until_key_frame = 1;
1289
1290    nut->last_resync_pos = 0;
1291
1292    return 0;
1293}
1294
1295AVInputFormat ff_nut_demuxer = {
1296    .name           = "nut",
1297    .long_name      = NULL_IF_CONFIG_SMALL("NUT"),
1298    .flags          = AVFMT_SEEK_TO_PTS,
1299    .priv_data_size = sizeof(NUTContext),
1300    .read_probe     = nut_probe,
1301    .read_header    = nut_read_header,
1302    .read_packet    = nut_read_packet,
1303    .read_close     = nut_read_close,
1304    .read_seek      = read_seek,
1305    .extensions     = "nut",
1306    .codec_tag      = ff_nut_codec_tags,
1307};