| 1 | // Copyright (c) 2007-2017 Fredrik Mellbin |
| 2 | // |
| 3 | // Permission is hereby granted, free of charge, to any person obtaining a copy |
| 4 | // of this software and associated documentation files (the "Software"), to deal |
| 5 | // in the Software without restriction, including without limitation the rights |
| 6 | // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell |
| 7 | // copies of the Software, and to permit persons to whom the Software is |
| 8 | // furnished to do so, subject to the following conditions: |
| 9 | // |
| 10 | // The above copyright notice and this permission notice shall be included in |
| 11 | // all copies or substantial portions of the Software. |
| 12 | // |
| 13 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR |
| 14 | // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, |
| 15 | // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE |
| 16 | // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER |
| 17 | // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, |
| 18 | // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN |
| 19 | // THE SOFTWARE. |
| 20 | |
| 21 | #include "indexing.h" |
| 22 | |
| 23 | #include "track.h" |
| 24 | #include "videoutils.h" |
| 25 | #include "zipfile.h" |
| 26 | |
| 27 | #include <algorithm> |
| 28 | #include <limits> |
| 29 | #include <numeric> |
| 30 | #include <sstream> |
| 31 | |
| 32 | extern "C" { |
| 33 | #include <libavutil/avutil.h> |
| 34 | #include <libavutil/sha.h> |
| 35 | } |
| 36 | |
| 37 | #define INDEXID 0x53920873 |
| 38 | #define INDEX_VERSION 8 |
| 39 | |
| 40 | SharedAVContext::~SharedAVContext() { |
| 41 | avcodec_free_context(&CodecContext); |
| 42 | if (Parser) |
| 43 | av_parser_close(Parser); |
| 44 | } |
| 45 | |
| 46 | void FFMS_Index::CalculateFileSignature(const char *Filename, int64_t *Filesize, uint8_t Digest[20]) { |
| 47 | FileHandle file(Filename, "rb", FFMS_ERROR_INDEX, FFMS_ERROR_FILE_READ); |
| 48 | |
| 49 | std::unique_ptr<AVSHA, decltype(&av_free)> ctx{ av_sha_alloc(), av_free }; |
| 50 | av_sha_init(ctx.get(), 160); |
| 51 | |
| 52 | try { |
| 53 | *Filesize = file.Size(); |
| 54 | std::vector<char> FileBuffer(static_cast<size_t>(std::min<int64_t>(1024 * 1024, *Filesize))); |
| 55 | size_t BytesRead = file.Read(FileBuffer.data(), FileBuffer.size()); |
| 56 | av_sha_update(ctx.get(), reinterpret_cast<const uint8_t*>(FileBuffer.data()), BytesRead); |
| 57 | |
| 58 | if (*Filesize > static_cast<int64_t>(FileBuffer.size())) { |
| 59 | file.Seek(*Filesize - static_cast<int64_t>(FileBuffer.size()), SEEK_SET); |
| 60 | BytesRead = file.Read(FileBuffer.data(), FileBuffer.size()); |
| 61 | av_sha_update(ctx.get(), reinterpret_cast<const uint8_t*>(FileBuffer.data()), BytesRead); |
| 62 | } |
| 63 | } catch (...) { |
| 64 | av_sha_final(ctx.get(), Digest); |
| 65 | throw; |
| 66 | } |
| 67 | av_sha_final(ctx.get(), Digest); |
| 68 | } |
| 69 | |
| 70 | void FFMS_Index::Finalize(std::vector<SharedAVContext> const& video_contexts, const char *Format) { |
| 71 | for (size_t i = 0, end = size(); i != end; ++i) { |
| 72 | FFMS_Track& track = (*this)[i]; |
| 73 | |
| 74 | if (!strcmp(Format, "mpeg") || !strcmp(Format, "mpegts") || !strcmp(Format, "mpegtsraw")) |
| 75 | if (std::any_of(track.begin(), track.end(), [](FrameInfo F) { return F.PTS == AV_NOPTS_VALUE; })) |
| 76 | track.RevertToDTS(); |
| 77 | |
| 78 | // Some audio tracks are simply insane junk (seen with als) and will have a single(?) super long packet and |
| 79 | // apart from that look legit and be chosen instead of usable audio. This hopefully rejects some of it. |
| 80 | // Caused by sample in https://github.com/FFMS/ffms2/issues/351 |
| 81 | if (track.TT == FFMS_TYPE_AUDIO) { |
| 82 | if (track.size() <= 10 && track.size() > 0 && track[0].SampleCount > 1000000) |
| 83 | track.clear(); |
| 84 | } |
| 85 | |
| 86 | // H.264 PAFF needs to have some frames hidden |
| 87 | // |
| 88 | // Don't send any WMV/ASF files, since they (as far as we know) cannot contain PAFF, |
| 89 | // but may also have valid, split packets, with pos equal to the previous pos. |
| 90 | if (video_contexts[i].CodecContext && video_contexts[i].CodecContext->codec_id == AV_CODEC_ID_H264 && !!strcmp(Format, "asf")) |
| 91 | track.MaybeHideFrames(); |
| 92 | |
| 93 | track.FinalizeTrack(); |
| 94 | |
| 95 | if (track.TT != FFMS_TYPE_VIDEO) continue; |
| 96 | |
| 97 | if (video_contexts[i].CodecContext && video_contexts[i].CodecContext->has_b_frames) { |
| 98 | track.MaxBFrames = video_contexts[i].CodecContext->has_b_frames; |
| 99 | continue; |
| 100 | } |
| 101 | |
| 102 | // Whether or not has_b_frames gets set during indexing seems |
| 103 | // to vary based on version of FFmpeg/Libav, so do an extra |
| 104 | // check for b-frames if it's 0. |
| 105 | for (size_t f = 0; f < track.size(); ++f) { |
| 106 | if (track[f].FrameType == AV_PICTURE_TYPE_B) { |
| 107 | track.MaxBFrames = 1; |
| 108 | break; |
| 109 | } |
| 110 | } |
| 111 | } |
| 112 | } |
| 113 | |
| 114 | bool FFMS_Index::CompareFileSignature(const char *Filename) { |
| 115 | int64_t CFilesize; |
| 116 | uint8_t CDigest[20]; |
| 117 | CalculateFileSignature(Filename, &CFilesize, CDigest); |
| 118 | return (CFilesize == Filesize && !memcmp(CDigest, Digest, sizeof(Digest))); |
| 119 | } |
| 120 | |
| 121 | void FFMS_Index::WriteIndex(ZipFile &zf) { |
| 122 | // Write the index file header |
| 123 | zf.Write<uint32_t>(INDEXID); |
| 124 | zf.Write<uint32_t>(FFMS_VERSION); |
| 125 | zf.Write<uint16_t>(INDEX_VERSION); |
| 126 | zf.Write<uint32_t>(size()); |
| 127 | zf.Write<uint32_t>(ErrorHandling); |
| 128 | zf.Write<uint32_t>(avutil_version()); |
| 129 | zf.Write<uint32_t>(avformat_version()); |
| 130 | zf.Write<uint32_t>(avcodec_version()); |
| 131 | zf.Write<uint32_t>(swscale_version()); |
| 132 | zf.Write<int64_t>(Filesize); |
| 133 | zf.Write(Digest); |
| 134 | |
| 135 | zf.Write<uint32_t>(LAVFOpts.size()); |
| 136 | for (const auto &iter : LAVFOpts) { |
| 137 | zf.Write<uint32_t>(iter.first.length()); |
| 138 | zf.Write(iter.first.data(), iter.first.length()); |
| 139 | zf.Write<uint32_t>(iter.second.length()); |
| 140 | zf.Write(iter.second.data(), iter.second.length()); |
| 141 | } |
| 142 | |
| 143 | for (size_t i = 0; i < size(); ++i) |
| 144 | at(i).Write(zf); |
| 145 | |
| 146 | zf.Finish(); |
| 147 | } |
| 148 | |
| 149 | void FFMS_Index::WriteIndexFile(const char *IndexFile) { |
| 150 | ZipFile zf(IndexFile, "wb"); |
| 151 | |
| 152 | WriteIndex(zf); |
| 153 | } |
| 154 | |
| 155 | uint8_t *FFMS_Index::WriteIndexBuffer(size_t *Size) { |
| 156 | ZipFile zf; |
| 157 | |
| 158 | WriteIndex(zf); |
| 159 | |
| 160 | return zf.GetBuffer(Size); |
| 161 | } |
| 162 | |
| 163 | void FFMS_Index::ReadIndex(ZipFile &zf, const char *IndexFile) { |
| 164 | // Read the index file header |
| 165 | if (zf.Read<uint32_t>() != INDEXID) |
| 166 | throw FFMS_Exception(FFMS_ERROR_PARSER, FFMS_ERROR_FILE_READ, |
| 167 | std::string("'") + IndexFile + "' is not a valid index file"); |
| 168 | |
| 169 | if (zf.Read<uint32_t>() != FFMS_VERSION) |
| 170 | throw FFMS_Exception(FFMS_ERROR_PARSER, FFMS_ERROR_FILE_READ, |
| 171 | std::string("'") + IndexFile + "' was not created with the expected FFMS2 version"); |
| 172 | |
| 173 | if (zf.Read<uint16_t>() != INDEX_VERSION) |
| 174 | throw FFMS_Exception(FFMS_ERROR_PARSER, FFMS_ERROR_FILE_READ, |
| 175 | std::string("'") + IndexFile + "' is not the expected index version"); |
| 176 | |
| 177 | uint32_t Tracks = zf.Read<uint32_t>(); |
| 178 | ErrorHandling = zf.Read<uint32_t>(); |
| 179 | |
| 180 | if (zf.Read<uint32_t>() != avutil_version() || |
| 181 | zf.Read<uint32_t>() != avformat_version() || |
| 182 | zf.Read<uint32_t>() != avcodec_version() || |
| 183 | zf.Read<uint32_t>() != swscale_version()) |
| 184 | throw FFMS_Exception(FFMS_ERROR_PARSER, FFMS_ERROR_FILE_READ, |
| 185 | std::string("A different FFmpeg build was used to create '") + IndexFile + "'"); |
| 186 | |
| 187 | Filesize = zf.Read<int64_t>(); |
| 188 | zf.Read(Digest, sizeof(Digest)); |
| 189 | |
| 190 | uint32_t NumOptions = zf.Read<uint32_t>(); |
| 191 | std::vector<char> KeyBuffer; |
| 192 | std::vector<char> ValueBuffer; |
| 193 | for (uint32_t i = 0; i < NumOptions; i++) { |
| 194 | uint32_t KeyLength = zf.Read<uint32_t>(); |
| 195 | KeyBuffer.resize(KeyLength); |
| 196 | zf.Read(KeyBuffer.data(), KeyLength); |
| 197 | |
| 198 | uint32_t ValueLength = zf.Read<uint32_t>(); |
| 199 | ValueBuffer.resize(ValueLength); |
| 200 | zf.Read(ValueBuffer.data(), ValueLength); |
| 201 | |
| 202 | LAVFOpts[std::string(KeyBuffer.data(), KeyLength)] = std::string(ValueBuffer.data(), ValueLength); |
| 203 | } |
| 204 | |
| 205 | reserve(Tracks); |
| 206 | try { |
| 207 | for (size_t i = 0; i < Tracks; ++i) |
| 208 | emplace_back(zf); |
| 209 | } catch (FFMS_Exception const&) { |
| 210 | throw; |
| 211 | } catch (...) { |
| 212 | throw FFMS_Exception(FFMS_ERROR_PARSER, FFMS_ERROR_FILE_READ, |
| 213 | std::string("Unknown error while reading index information in '") + IndexFile + "'"); |
| 214 | } |
| 215 | } |
| 216 | |
| 217 | FFMS_Index::FFMS_Index(const char *IndexFile) { |
| 218 | ZipFile zf(IndexFile, "rb"); |
| 219 | |
| 220 | ReadIndex(zf, IndexFile); |
| 221 | } |
| 222 | |
| 223 | FFMS_Index::FFMS_Index(const uint8_t *Buffer, size_t Size) { |
| 224 | ZipFile zf(Buffer, Size); |
| 225 | |
| 226 | ReadIndex(zf, "User supplied buffer"); |
| 227 | } |
| 228 | |
| 229 | FFMS_Index::FFMS_Index(int64_t Filesize, uint8_t Digest[20], int ErrorHandling, const std::map<std::string, std::string> &LAVFOpts) |
| 230 | : ErrorHandling(ErrorHandling) |
| 231 | , Filesize(Filesize), LAVFOpts(LAVFOpts) { |
| 232 | memcpy(this->Digest, Digest, sizeof(this->Digest)); |
| 233 | } |
| 234 | |
| 235 | void FFMS_Indexer::SetIndexTrack(int Track, bool Index) { |
| 236 | if (Track < 0 || Track >= GetNumberOfTracks()) |
| 237 | return; |
| 238 | if (Index) |
| 239 | IndexMask.insert(Track); |
| 240 | else |
| 241 | IndexMask.erase(Track); |
| 242 | }; |
| 243 | |
| 244 | void FFMS_Indexer::SetIndexTrackType(int TrackType, bool Index) { |
| 245 | for (int i = 0; i < GetNumberOfTracks(); i++) { |
| 246 | if (GetTrackType(i) == TrackType) { |
| 247 | if (Index) |
| 248 | IndexMask.insert(i); |
| 249 | else |
| 250 | IndexMask.erase(i); |
| 251 | } |
| 252 | } |
| 253 | } |
| 254 | |
| 255 | void FFMS_Indexer::SetErrorHandling(int ErrorHandling_) { |
| 256 | if (ErrorHandling_ != FFMS_IEH_ABORT && ErrorHandling_ != FFMS_IEH_CLEAR_TRACK && |
| 257 | ErrorHandling_ != FFMS_IEH_STOP_TRACK && ErrorHandling_ != FFMS_IEH_IGNORE) |
| 258 | throw FFMS_Exception(FFMS_ERROR_INDEXING, FFMS_ERROR_INVALID_ARGUMENT, |
| 259 | "Invalid error handling mode specified"); |
| 260 | ErrorHandling = ErrorHandling_; |
| 261 | } |
| 262 | |
| 263 | void FFMS_Indexer::SetProgressCallback(TIndexCallback IC_, void *ICPrivate_) { |
| 264 | IC = IC_; |
| 265 | ICPrivate = ICPrivate_; |
| 266 | } |
| 267 | |
| 268 | FFMS_Indexer::FFMS_Indexer(const char *Filename, const FFMS_KeyValuePair *DemuxerOptions, int NumOptions) |
| 269 | : SourceFile(Filename) { |
| 270 | try { |
| 271 | AVDictionary *Dict = nullptr; |
| 272 | for (int i = 0; i < NumOptions; i++) { |
| 273 | if (!DemuxerOptions[i].Key && !DemuxerOptions[i].Value) |
| 274 | throw FFMS_Exception(FFMS_ERROR_INDEX, FFMS_ERROR_INVALID_ARGUMENT, |
| 275 | "Demuxer key-value pairs can't have NULL strings"); |
| 276 | LAVFOpts[DemuxerOptions[i].Key] = DemuxerOptions[i].Value; |
| 277 | av_dict_set(&Dict, DemuxerOptions[i].Key, DemuxerOptions[i].Value, 0); |
| 278 | } |
| 279 | |
| 280 | if (avformat_open_input(&FormatContext, Filename, nullptr, &Dict) != 0) |
| 281 | throw FFMS_Exception(FFMS_ERROR_PARSER, FFMS_ERROR_FILE_READ, |
| 282 | std::string("Can't open '") + Filename + "'"); |
| 283 | |
| 284 | av_dict_free(&Dict); |
| 285 | |
| 286 | FFMS_Index::CalculateFileSignature(Filename, &Filesize, Digest); |
| 287 | |
| 288 | if (avformat_find_stream_info(FormatContext, nullptr) < 0) { |
| 289 | avformat_close_input(&FormatContext); |
| 290 | throw FFMS_Exception(FFMS_ERROR_PARSER, FFMS_ERROR_FILE_READ, |
| 291 | "Couldn't find stream information"); |
| 292 | } |
| 293 | |
| 294 | for (unsigned int i = 0; i < FormatContext->nb_streams; i++) |
| 295 | if (FormatContext->streams[i]->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) |
| 296 | IndexMask.insert(i); |
| 297 | |
| 298 | DecodeFrame = av_frame_alloc(); |
| 299 | if (!DecodeFrame) |
| 300 | throw FFMS_Exception(FFMS_ERROR_DECODING, FFMS_ERROR_ALLOCATION_FAILED, |
| 301 | "Couldn't allocate frame"); |
| 302 | } catch (...) { |
| 303 | Free(); |
| 304 | throw; |
| 305 | } |
| 306 | } |
| 307 | |
| 308 | uint32_t FFMS_Indexer::IndexAudioPacket(int Track, AVPacket *Packet, SharedAVContext &Context, FFMS_Index &TrackIndices) { |
| 309 | AVCodecContext *CodecContext = Context.CodecContext; |
| 310 | int64_t StartSample = Context.CurrentSample; |
| 311 | int Ret = avcodec_send_packet(CodecContext, Packet); |
| 312 | if (Ret != 0) { |
| 313 | if (ErrorHandling == FFMS_IEH_ABORT) { |
| 314 | throw FFMS_Exception(FFMS_ERROR_CODEC, FFMS_ERROR_DECODING, "Audio decoding error"); |
| 315 | } else if (ErrorHandling == FFMS_IEH_CLEAR_TRACK) { |
| 316 | TrackIndices[Track].clear(); |
| 317 | IndexMask.erase(Track); |
| 318 | } else if (ErrorHandling == FFMS_IEH_STOP_TRACK) { |
| 319 | IndexMask.erase(Track); |
| 320 | } |
| 321 | } |
| 322 | |
| 323 | while (true) { |
| 324 | av_frame_unref(DecodeFrame); |
| 325 | Ret = avcodec_receive_frame(CodecContext, DecodeFrame); |
| 326 | if (Ret == 0) { |
| 327 | CheckAudioProperties(Track, CodecContext); |
| 328 | Context.CurrentSample += DecodeFrame->nb_samples; |
| 329 | } else if (Ret == AVERROR_EOF || Ret == AVERROR(EAGAIN)) { |
| 330 | break; |
| 331 | } else { |
| 332 | if (ErrorHandling == FFMS_IEH_ABORT) { |
| 333 | throw FFMS_Exception(FFMS_ERROR_CODEC, FFMS_ERROR_DECODING, "Audio decoding error"); |
| 334 | } else if (ErrorHandling == FFMS_IEH_CLEAR_TRACK) { |
| 335 | TrackIndices[Track].clear(); |
| 336 | IndexMask.erase(Track); |
| 337 | } else if (ErrorHandling == FFMS_IEH_STOP_TRACK) { |
| 338 | IndexMask.erase(Track); |
| 339 | } |
| 340 | } |
| 341 | } |
| 342 | |
| 343 | return static_cast<uint32_t>(Context.CurrentSample - StartSample); |
| 344 | } |
| 345 | |
| 346 | void FFMS_Indexer::CheckAudioProperties(int Track, AVCodecContext *Context) { |
| 347 | auto it = LastAudioProperties.find(Track); |
| 348 | if (it == LastAudioProperties.end()) { |
| 349 | FFMS_AudioProperties &AP = LastAudioProperties[Track]; |
| 350 | AP.SampleRate = Context->sample_rate; |
| 351 | AP.SampleFormat = Context->sample_fmt; |
| 352 | AP.Channels = Context->ch_layout.nb_channels; |
| 353 | } else if (it->second.SampleRate != Context->sample_rate || |
| 354 | it->second.SampleFormat != Context->sample_fmt || |
| 355 | it->second.Channels != Context->ch_layout.nb_channels) { |
| 356 | std::ostringstream buf; // fixme, dodgy comparison and maybe wrong since it skips layout comp |
| 357 | buf << |
| 358 | "Audio format change detected. This is currently unsupported." |
| 359 | << " Channels: " << it->second.Channels << " -> " << Context->ch_layout.nb_channels << ";" |
| 360 | << " Sample rate: " << it->second.SampleRate << " -> " << Context->sample_rate << ";" |
| 361 | << " Sample format: " << av_get_sample_fmt_name((AVSampleFormat)it->second.SampleFormat) << " -> " |
| 362 | << av_get_sample_fmt_name(Context->sample_fmt); |
| 363 | throw FFMS_Exception(FFMS_ERROR_UNSUPPORTED, FFMS_ERROR_DECODING, buf.str()); |
| 364 | } |
| 365 | } |
| 366 | |
| 367 | void FFMS_Indexer::ParseVideoPacket(SharedAVContext &VideoContext, AVPacket *pkt, int *RepeatPict, |
| 368 | int *FrameType, bool *Invisible, bool *SecondField, enum AVPictureStructure *LastPicStruct) { |
| 369 | if (VideoContext.Parser) { |
| 370 | uint8_t *OB; |
| 371 | int OBSize; |
| 372 | |
| 373 | av_parser_parse2(VideoContext.Parser, |
| 374 | VideoContext.CodecContext, |
| 375 | &OB, &OBSize, |
| 376 | pkt->data, pkt->size, |
| 377 | pkt->pts, pkt->dts, pkt->pos); |
| 378 | |
| 379 | // H.264 (PAFF) and HEVC may have one field per packet, so we need to track |
| 380 | // when we have a full or half frame available, and mark one of them as |
| 381 | // hidden, so we do not get duplicate frames. |
| 382 | if (VideoContext.CodecContext->codec_id == AV_CODEC_ID_H264 || |
| 383 | VideoContext.CodecContext->codec_id == AV_CODEC_ID_HEVC) { |
| 384 | if ((VideoContext.Parser->picture_structure == AV_PICTURE_STRUCTURE_TOP_FIELD && |
| 385 | *LastPicStruct == AV_PICTURE_STRUCTURE_BOTTOM_FIELD) || |
| 386 | (VideoContext.Parser->picture_structure == AV_PICTURE_STRUCTURE_BOTTOM_FIELD && |
| 387 | *LastPicStruct == AV_PICTURE_STRUCTURE_TOP_FIELD)) { |
| 388 | *SecondField = true; |
| 389 | *LastPicStruct = AV_PICTURE_STRUCTURE_UNKNOWN; |
| 390 | } else { |
| 391 | *LastPicStruct = VideoContext.Parser->picture_structure; |
| 392 | } |
| 393 | } |
| 394 | |
| 395 | *RepeatPict = VideoContext.Parser->repeat_pict; |
| 396 | *FrameType = VideoContext.Parser->pict_type; |
| 397 | *Invisible = (VideoContext.Parser->repeat_pict < 0 || (pkt->flags & AV_PKT_FLAG_DISCARD)); |
| 398 | } else { |
| 399 | *Invisible = !!(pkt->flags & AV_PKT_FLAG_DISCARD); |
| 400 | } |
| 401 | |
| 402 | if (VideoContext.CodecContext->codec_id == AV_CODEC_ID_VP8) |
| 403 | ParseVP8(pkt->data[0], Invisible, FrameType); |
| 404 | else if (VideoContext.CodecContext->codec_id == AV_CODEC_ID_VP9) |
| 405 | ParseVP9(pkt->data[0], FrameType); |
| 406 | } |
| 407 | |
| 408 | void FFMS_Indexer::Free() { |
| 409 | av_frame_free(&DecodeFrame); |
| 410 | avformat_close_input(&FormatContext); |
| 411 | } |
| 412 | |
| 413 | FFMS_Indexer::~FFMS_Indexer() { |
| 414 | Free(); |
| 415 | } |
| 416 | |
| 417 | int FFMS_Indexer::GetNumberOfTracks() { |
| 418 | return FormatContext->nb_streams; |
| 419 | } |
| 420 | |
| 421 | const char *FFMS_Indexer::GetFormatName() { |
| 422 | return FormatContext->iformat->name; |
| 423 | } |
| 424 | |
| 425 | FFMS_TrackType FFMS_Indexer::GetTrackType(int Track) { |
| 426 | return static_cast<FFMS_TrackType>(FormatContext->streams[Track]->codecpar->codec_type); |
| 427 | } |
| 428 | |
| 429 | const char *FFMS_Indexer::GetTrackCodec(int Track) { |
| 430 | auto *codec = avcodec_find_decoder(FormatContext->streams[Track]->codecpar->codec_id); |
| 431 | return codec ? codec->name : nullptr; |
| 432 | } |
| 433 | |
| 434 | FFMS_Index *FFMS_Indexer::DoIndexing() { |
| 435 | std::vector<SharedAVContext> AVContexts(FormatContext->nb_streams); |
| 436 | |
| 437 | auto TrackIndices = std::unique_ptr<FFMS_Index>(new FFMS_Index(Filesize, Digest, ErrorHandling, LAVFOpts)); |
| 438 | bool UseDTS = !strcmp(FormatContext->iformat->name, "nuv"); |
| 439 | bool IsMpegLike = !strcmp(FormatContext->iformat->name, "mpeg") || !strcmp(FormatContext->iformat->name, "mpegts") || !strcmp(FormatContext->iformat->name, "mpegtsraw"); |
| 440 | |
| 441 | for (unsigned int i = 0; i < FormatContext->nb_streams; i++) { |
| 442 | TrackIndices->emplace_back((int64_t)FormatContext->streams[i]->time_base.num * 1000, |
| 443 | FormatContext->streams[i]->time_base.den, |
| 444 | static_cast<FFMS_TrackType>(FormatContext->streams[i]->codecpar->codec_type), |
| 445 | !!(FormatContext->iformat->flags & AVFMT_TS_DISCONT), |
| 446 | UseDTS); |
| 447 | |
| 448 | if (IndexMask.count(i) && FormatContext->streams[i]->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) { |
| 449 | auto *VideoCodec = avcodec_find_decoder(FormatContext->streams[i]->codecpar->codec_id); |
| 450 | if (!VideoCodec) { |
| 451 | FormatContext->streams[i]->discard = AVDISCARD_ALL; |
| 452 | IndexMask.erase(i); |
| 453 | continue; |
| 454 | } |
| 455 | |
| 456 | AVContexts[i].CodecContext = avcodec_alloc_context3(VideoCodec); |
| 457 | if (AVContexts[i].CodecContext == nullptr) |
| 458 | throw FFMS_Exception(FFMS_ERROR_CODEC, FFMS_ERROR_ALLOCATION_FAILED, |
| 459 | "Could not allocate video codec context"); |
| 460 | |
| 461 | if (avcodec_parameters_to_context(AVContexts[i].CodecContext, FormatContext->streams[i]->codecpar) < 0) |
| 462 | throw FFMS_Exception(FFMS_ERROR_CODEC, FFMS_ERROR_DECODING, |
| 463 | "Could not copy video codec parameters"); |
| 464 | |
| 465 | if (avcodec_open2(AVContexts[i].CodecContext, VideoCodec, nullptr) < 0) |
| 466 | throw FFMS_Exception(FFMS_ERROR_CODEC, FFMS_ERROR_DECODING, |
| 467 | "Could not open video codec"); |
| 468 | |
| 469 | AVContexts[i].Parser = av_parser_init(FormatContext->streams[i]->codecpar->codec_id); |
| 470 | if (AVContexts[i].Parser) |
| 471 | AVContexts[i].Parser->flags = PARSER_FLAG_COMPLETE_FRAMES; |
| 472 | |
| 473 | if (FormatContext->streams[i]->disposition & AV_DISPOSITION_ATTACHED_PIC) { |
| 474 | FormatContext->streams[i]->discard = AVDISCARD_ALL; |
| 475 | IndexMask.erase(i); |
| 476 | } else { |
| 477 | IndexMask.insert(i); |
| 478 | } |
| 479 | } else if (IndexMask.count(i) && FormatContext->streams[i]->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) { |
| 480 | auto *AudioCodec = avcodec_find_decoder(FormatContext->streams[i]->codecpar->codec_id); |
| 481 | if (AudioCodec == nullptr) |
| 482 | throw FFMS_Exception(FFMS_ERROR_CODEC, FFMS_ERROR_UNSUPPORTED, |
| 483 | "Audio codec not found"); |
| 484 | |
| 485 | AVContexts[i].CodecContext = avcodec_alloc_context3(AudioCodec); |
| 486 | if (AVContexts[i].CodecContext == nullptr) |
| 487 | throw FFMS_Exception(FFMS_ERROR_CODEC, FFMS_ERROR_ALLOCATION_FAILED, |
| 488 | "Could not allocate audio codec context"); |
| 489 | |
| 490 | if (avcodec_parameters_to_context(AVContexts[i].CodecContext, FormatContext->streams[i]->codecpar) < 0) |
| 491 | throw FFMS_Exception(FFMS_ERROR_CODEC, FFMS_ERROR_DECODING, |
| 492 | "Could not copy audio codec parameters"); |
| 493 | |
| 494 | if (avcodec_open2(AVContexts[i].CodecContext, AudioCodec, nullptr) < 0) |
| 495 | throw FFMS_Exception(FFMS_ERROR_CODEC, FFMS_ERROR_DECODING, |
| 496 | "Could not open audio codec"); |
| 497 | |
| 498 | (*TrackIndices)[i].HasTS = false; |
| 499 | } else { |
| 500 | FormatContext->streams[i]->discard = AVDISCARD_ALL; |
| 501 | IndexMask.erase(i); |
| 502 | } |
| 503 | } |
| 504 | |
| 505 | AVPacket *Packet = av_packet_alloc(); |
| 506 | if (!Packet) |
| 507 | throw FFMS_Exception(FFMS_ERROR_CODEC, FFMS_ERROR_ALLOCATION_FAILED, |
| 508 | "Could not allocate packet."); |
| 509 | std::vector<int64_t> LastValidTS(FormatContext->nb_streams, AV_NOPTS_VALUE); |
| 510 | |
| 511 | int64_t filesize = avio_size(FormatContext->pb); |
| 512 | enum AVPictureStructure LastPicStruct = AV_PICTURE_STRUCTURE_UNKNOWN; |
| 513 | int ret; |
| 514 | while ((ret = av_read_frame(FormatContext, Packet)) >= 0) { |
| 515 | // Update progress |
| 516 | // FormatContext->pb can apparently be NULL when opening images. |
| 517 | if (IC && FormatContext->pb) { |
| 518 | if ((*IC)(FormatContext->pb->pos, filesize, ICPrivate)) { |
| 519 | av_packet_free(&Packet); |
| 520 | throw FFMS_Exception(FFMS_ERROR_CANCELLED, FFMS_ERROR_USER, |
| 521 | "Cancelled by user"); |
| 522 | } |
| 523 | } |
| 524 | if (!IndexMask.count(Packet->stream_index)) { |
| 525 | av_packet_unref(Packet); |
| 526 | continue; |
| 527 | } |
| 528 | |
| 529 | int Track = Packet->stream_index; |
| 530 | FFMS_Track &TrackInfo = (*TrackIndices)[Track]; |
| 531 | bool KeyFrame = !!(Packet->flags & AV_PKT_FLAG_KEY); |
| 532 | ReadTS(Packet, LastValidTS[Track], (*TrackIndices)[Track].UseDTS); |
| 533 | |
| 534 | if (FormatContext->streams[Track]->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) { |
| 535 | int64_t PTS = TrackInfo.UseDTS ? Packet->dts : Packet->pts; |
| 536 | if (PTS == AV_NOPTS_VALUE && !IsMpegLike) { |
| 537 | // VPx alt-refs are output as packets which lack timestmps or durations, since |
| 538 | // they are invisible. Currently, the timestamp mangling code in libavformat |
| 539 | // will sometimes add a bogus timestamp and duration, if the webm in question |
| 540 | // has the block duration set (which is a hack, and not really a frame duration |
| 541 | // at all). In the future, libav* will only output packets without timestamps |
| 542 | // or duration, so we need to handle it here, regardless. This does not handle |
| 543 | // NVOPs. We set the duration based on the last PTS, for these packets, because |
| 544 | // FFMS2 currently sorts packets by PTS, which will break decoding, otherwise. |
| 545 | bool HasAltRefs = (FormatContext->streams[Track]->codecpar->codec_id == AV_CODEC_ID_VP8 || |
| 546 | FormatContext->streams[Track]->codecpar->codec_id == AV_CODEC_ID_VP9); |
| 547 | if (Packet->duration == 0 && !HasAltRefs) { |
| 548 | av_packet_free(&Packet); |
| 549 | throw FFMS_Exception(FFMS_ERROR_INDEXING, FFMS_ERROR_PARSER, |
| 550 | "Invalid packet pts, dts, and duration"); |
| 551 | } |
| 552 | |
| 553 | if (TrackInfo.empty()) |
| 554 | PTS = 0; |
| 555 | else |
| 556 | PTS = TrackInfo.back().PTS + TrackInfo.LastDuration; |
| 557 | |
| 558 | TrackInfo.HasTS = false; |
| 559 | } |
| 560 | |
| 561 | int RepeatPict = -1; |
| 562 | int FrameType = 0; |
| 563 | bool Invisible = false; |
| 564 | bool SecondField = false; |
| 565 | ParseVideoPacket(AVContexts[Track], Packet, &RepeatPict, &FrameType, &Invisible, &SecondField, &LastPicStruct); |
| 566 | |
| 567 | TrackInfo.AddVideoFrame(PTS, Packet->dts, RepeatPict, KeyFrame, |
| 568 | FrameType, Packet->pos, Invisible, SecondField); |
| 569 | } else if (FormatContext->streams[Track]->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) { |
| 570 | // For video seeking timestamps are used only if all packets have |
| 571 | // timestamps, while for audio they're used if any have timestamps, |
| 572 | // as it's pretty common for only some packets to have timestamps |
| 573 | if (LastValidTS[Track] != AV_NOPTS_VALUE) |
| 574 | TrackInfo.HasTS = true; |
| 575 | |
| 576 | int64_t StartSample = AVContexts[Track].CurrentSample; |
| 577 | uint32_t SampleCount = IndexAudioPacket(Track, Packet, AVContexts[Track], *TrackIndices); |
| 578 | TrackInfo.SampleRate = AVContexts[Track].CodecContext->sample_rate; |
| 579 | |
| 580 | TrackInfo.AddAudioFrame(LastValidTS[Track], Packet->dts, |
| 581 | StartSample, SampleCount, KeyFrame, Packet->pos, Packet->flags & AV_PKT_FLAG_DISCARD); |
| 582 | } |
| 583 | |
| 584 | if (!(Packet->flags & AV_PKT_FLAG_DISCARD)) |
| 585 | TrackInfo.LastDuration = Packet->duration; |
| 586 | |
| 587 | av_packet_unref(Packet); |
| 588 | } |
| 589 | av_packet_free(&Packet); |
| 590 | if (IsIOError(ret)) |
| 591 | throw FFMS_Exception(FFMS_ERROR_INDEXING, FFMS_ERROR_FILE_READ, |
| 592 | "Indexing failed: " + AVErrorToString(ret)); |
| 593 | |
| 594 | TrackIndices->Finalize(AVContexts, FormatContext->iformat->name); |
| 595 | return TrackIndices.release(); |
| 596 | } |
| 597 | |
| 598 | void FFMS_Indexer::ReadTS(const AVPacket *Packet, int64_t &TS, bool &UseDTS) { |
| 599 | if (!UseDTS && Packet->pts != AV_NOPTS_VALUE) |
| 600 | TS = Packet->pts; |
| 601 | if (TS == AV_NOPTS_VALUE) |
| 602 | UseDTS = true; |
| 603 | if (UseDTS && Packet->dts != AV_NOPTS_VALUE) |
| 604 | TS = Packet->dts; |
| 605 | } |