| 1 | // Copyright (c) 2008-2009 Karl Blomster |
| 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 "ffms.h" |
| 22 | |
| 23 | #ifdef _WIN32 |
| 24 | #include "vsutf16.h" |
| 25 | #endif |
| 26 | |
| 27 | #include <cinttypes> |
| 28 | #include <cstdint> |
| 29 | #include <cstdlib> |
| 30 | #include <cstring> |
| 31 | #include <fstream> |
| 32 | #include <iostream> |
| 33 | #include <string> |
| 34 | #include <vector> |
| 35 | #include <string> |
| 36 | #include <stdexcept> |
| 37 | #include <chrono> |
| 38 | |
| 39 | extern "C" { |
| 40 | #include <libavutil/dict.h> |
| 41 | } |
| 42 | |
| 43 | namespace { |
| 44 | |
| 45 | long long IndexMask = 0; |
| 46 | int Verbose = 0; |
| 47 | int IgnoreErrors = 0; |
| 48 | bool Overwrite = false; |
| 49 | bool PrintProgress = true; |
| 50 | bool WriteTC = false; |
| 51 | bool WriteKF = false; |
| 52 | int64_t ProgressInterval = 1000000; // One second |
| 53 | std::vector<FFMS_KeyValuePair> LAVFOpts; |
| 54 | std::string InputFile; |
| 55 | std::string CacheFile; |
| 56 | |
| 57 | struct Error { |
| 58 | std::string msg; |
| 59 | Error(const char *msg) : msg(msg) {} |
| 60 | Error(const char *msg, FFMS_ErrorInfo const& e) : msg(msg) { |
| 61 | this->msg.append(e.Buffer); |
| 62 | } |
| 63 | }; |
| 64 | |
| 65 | struct Progress { |
| 66 | int Percent; |
| 67 | int64_t Time; |
| 68 | }; |
| 69 | |
| 70 | void PrintUsage() { |
| 71 | std::cout << |
| 72 | "FFmpegSource2 indexing app\n" |
| 73 | "Usage: ffmsindex [options] inputfile [outputfile]\n" |
| 74 | "If no output filename is specified, inputfile.ffindex will be used.\n" |
| 75 | "\n" |
| 76 | "Options:\n" |
| 77 | "-f Force overwriting of existing index file, if any (default: no)\n" |
| 78 | "-v Set FFmpeg verbosity level. Can be repeated for more verbosity. (default: no messages printed)\n" |
| 79 | "-p Disable progress reporting. (default: progress reporting on)\n" |
| 80 | "-c Write timecodes for all video tracks to outputfile_track00.tc.txt (default: no)\n" |
| 81 | "-k Write keyframes for all video tracks to outputfile_track00.kf.txt (default: no)\n" |
| 82 | "-t N Set the audio indexing mask to N (-1 means index all tracks, 0 means index none, default: 0)\n" |
| 83 | "-s N Set audio decoding error handling. See the documentation for details. (default: 0)\n" |
| 84 | "-u N Set the progress update frequency in seconds. Set to 0 for every percent. (default: 1)\n" |
| 85 | "-o string Set demuxer options to be used in the form of 'key=val:key=val'. (default: none)\n" |
| 86 | "\n" |
| 87 | "FFmpeg Demuxer Options:\n" |
| 88 | "--enable_drefs\n" |
| 89 | "--use_absolute_path\n" |
| 90 | << std::endl; |
| 91 | } |
| 92 | |
| 93 | int64_t getTimeInMicroSeconds() { |
| 94 | static std::chrono::time_point<std::chrono::steady_clock> StartTime = std::chrono::steady_clock::now(); |
| 95 | std::chrono::time_point<std::chrono::steady_clock> Now = std::chrono::steady_clock::now(); |
| 96 | return std::chrono::duration_cast<std::chrono::microseconds>(Now - StartTime).count(); |
| 97 | } |
| 98 | |
| 99 | int64_t parseSecondsToMicroseconds(const char *str) { |
| 100 | double val = std::strtod(str, nullptr); |
| 101 | int64_t ret = (int64_t) (val * 1000000.0); |
| 102 | return ret; |
| 103 | } |
| 104 | |
| 105 | void freeDemuxerOpts() { |
| 106 | for (FFMS_KeyValuePair pair : LAVFOpts) { |
| 107 | free(const_cast<char *>(pair.Key)); |
| 108 | free(const_cast<char *>(pair.Value)); |
| 109 | } |
| 110 | LAVFOpts.clear(); |
| 111 | } |
| 112 | |
| 113 | std::vector<FFMS_KeyValuePair> parseDemuxerOpts(const char *str) { |
| 114 | AVDictionary *dict = nullptr; |
| 115 | int ret = av_dict_parse_string(&dict, str, "=", ":", 0); |
| 116 | if (ret < 0) |
| 117 | throw Error("Cannot parse demuxer options."); |
| 118 | |
| 119 | AVDictionaryEntry *en = nullptr; |
| 120 | while ((en = av_dict_get(dict, "", en, AV_DICT_IGNORE_SUFFIX)) != NULL) { |
| 121 | FFMS_KeyValuePair pair; |
| 122 | pair.Key = strdup(en->key); |
| 123 | if (!pair.Key) |
| 124 | goto fail; |
| 125 | pair.Value = strdup(en->value); |
| 126 | if (!pair.Value) { |
| 127 | free(const_cast<char *>(pair.Key)); |
| 128 | goto fail; |
| 129 | } |
| 130 | LAVFOpts.push_back(pair); |
| 131 | } |
| 132 | return LAVFOpts; |
| 133 | fail: |
| 134 | freeDemuxerOpts(); |
| 135 | throw Error("Could not allocate key/value pair."); |
| 136 | } |
| 137 | |
| 138 | void ParseCMDLine(int argc, const char *argv[]) { |
| 139 | for (int i = 1; i < argc; ++i) { |
| 140 | const char *Option = argv[i]; |
| 141 | #define OPTION_ARG(dst, flag, parse) try { dst = parse(i + 1 < argc ? argv[i+1] : throw Error("Error: missing argument for -" flag)); i++; } catch (std::logic_error &) { throw Error("Error: invalid argument specified for -" flag); } |
| 142 | |
| 143 | if (!strcmp(Option, "-f")) { |
| 144 | Overwrite = true; |
| 145 | } else if (!strcmp(Option, "-v")) { |
| 146 | Verbose++; |
| 147 | } else if (!strcmp(Option, "-p")) { |
| 148 | PrintProgress = false; |
| 149 | } else if (!strcmp(Option, "-c")) { |
| 150 | WriteTC = true; |
| 151 | } else if (!strcmp(Option, "-k")) { |
| 152 | WriteKF = true; |
| 153 | } else if (!strcmp(Option, "-t")) { |
| 154 | OPTION_ARG(IndexMask, "t", std::stoll); |
| 155 | } else if (!strcmp(Option, "-s")) { |
| 156 | OPTION_ARG(IgnoreErrors, "s", std::stoi); |
| 157 | } else if (!strcmp(Option, "-u")) { |
| 158 | OPTION_ARG(ProgressInterval, "u", parseSecondsToMicroseconds); |
| 159 | } else if (!strcmp(Option, "-o")) { |
| 160 | OPTION_ARG(LAVFOpts, "o", parseDemuxerOpts); |
| 161 | } else if (!strcmp(Option, "--enable_drefs")) { |
| 162 | parseDemuxerOpts("enable_drefs=1"); |
| 163 | } else if (!strcmp(Option, "--use_absolute_path")) { |
| 164 | parseDemuxerOpts("use_absolute_path=1"); |
| 165 | } else if (InputFile.empty()) { |
| 166 | InputFile = Option; |
| 167 | } else if (CacheFile.empty()) { |
| 168 | CacheFile = Option; |
| 169 | } else { |
| 170 | std::cout << "Warning: ignoring unknown option " << Option << std::endl; |
| 171 | } |
| 172 | } |
| 173 | |
| 174 | if (IgnoreErrors < 0 || IgnoreErrors > 3) |
| 175 | throw Error("Error: invalid error handling mode"); |
| 176 | if (InputFile.empty()) |
| 177 | throw Error("Error: no input file specified"); |
| 178 | |
| 179 | if (CacheFile.empty()) { |
| 180 | CacheFile = InputFile; |
| 181 | CacheFile.append(".ffindex"); |
| 182 | } |
| 183 | } |
| 184 | |
| 185 | int FFMS_CC UpdateProgress(int64_t Current, int64_t Total, void *Private) { |
| 186 | if (!PrintProgress) |
| 187 | return 0; |
| 188 | |
| 189 | int Percentage = int((double(Current) / double(Total)) * 100); |
| 190 | |
| 191 | if (Private) { |
| 192 | Progress *LastProgress = (Progress *)Private; |
| 193 | int64_t CurTime = getTimeInMicroSeconds(); |
| 194 | if (Percentage <= LastProgress->Percent || (LastProgress->Time != 0 && (CurTime - LastProgress->Time) <= ProgressInterval)) |
| 195 | return 0; |
| 196 | LastProgress->Percent = Percentage; |
| 197 | LastProgress->Time = CurTime; |
| 198 | } |
| 199 | |
| 200 | std::cout << "Indexing, please wait... " << Percentage << "% \r" << std::flush; |
| 201 | |
| 202 | return 0; |
| 203 | } |
| 204 | |
| 205 | std::string DumpFilename(FFMS_Track *Track, int TrackNum, const char *Suffix) { |
| 206 | if (FFMS_GetTrackType(Track) != FFMS_TYPE_VIDEO || !FFMS_GetNumFrames(Track)) |
| 207 | return ""; |
| 208 | |
| 209 | char tn[11]; |
| 210 | snprintf(tn, 11, "%02" PRIu32"", (uint32_t) TrackNum); |
| 211 | return CacheFile + "_track" + tn + Suffix; |
| 212 | } |
| 213 | |
| 214 | void DoIndexing() { |
| 215 | char ErrorMsg[1024]; |
| 216 | FFMS_ErrorInfo E; |
| 217 | E.Buffer = ErrorMsg; |
| 218 | E.BufferSize = sizeof(ErrorMsg); |
| 219 | |
| 220 | Progress ProgressTracker = { 0, getTimeInMicroSeconds() }; |
| 221 | |
| 222 | FFMS_Index *Index = FFMS_ReadIndex(CacheFile.c_str(), &E); |
| 223 | if (Index) { |
| 224 | FFMS_DestroyIndex(Index); |
| 225 | if (!Overwrite) |
| 226 | throw Error("Error: index file already exists, use -f if you are sure you want to overwrite it."); |
| 227 | } |
| 228 | |
| 229 | UpdateProgress(0, 100, nullptr); |
| 230 | |
| 231 | FFMS_Indexer *Indexer = FFMS_CreateIndexer2(InputFile.c_str(), LAVFOpts.data(), LAVFOpts.size(), &E); |
| 232 | if (Indexer == nullptr) |
| 233 | throw Error("\nFailed to initialize indexing: ", E); |
| 234 | |
| 235 | FFMS_SetProgressCallback(Indexer, UpdateProgress, &ProgressTracker); |
| 236 | |
| 237 | // Treat -1 as meaning track numbers above sizeof(long long) * 8 too, dumping implies indexing |
| 238 | if (IndexMask == -1) |
| 239 | FFMS_TrackTypeIndexSettings(Indexer, FFMS_TYPE_AUDIO, 1, 0); |
| 240 | |
| 241 | // Apply attributes to remaining tracks (will set the attributes again on some tracks) |
| 242 | for (int i = 0; i < static_cast<int>(sizeof(IndexMask) * 8); i++) { |
| 243 | if ((IndexMask >> i) & 1) |
| 244 | FFMS_TrackIndexSettings(Indexer, i, 1, 0); |
| 245 | } |
| 246 | |
| 247 | Index = FFMS_DoIndexing2(Indexer, IgnoreErrors, &E); |
| 248 | |
| 249 | // The indexer is always freed |
| 250 | Indexer = nullptr; |
| 251 | |
| 252 | freeDemuxerOpts(); |
| 253 | |
| 254 | if (Index == nullptr) |
| 255 | throw Error("\nIndexing error: ", E); |
| 256 | |
| 257 | UpdateProgress(100, 100, nullptr); |
| 258 | |
| 259 | std::cout << std::endl; |
| 260 | |
| 261 | if (WriteTC) { |
| 262 | if (PrintProgress) |
| 263 | std::cout << "Writing timecodes... "; |
| 264 | int NumTracks = FFMS_GetNumTracks(Index); |
| 265 | for (int t = 0; t < NumTracks; t++) { |
| 266 | FFMS_Track *Track = FFMS_GetTrackFromIndex(Index, t); |
| 267 | std::string Filename = DumpFilename(Track, t, ".tc.txt"); |
| 268 | if (!Filename.empty()) { |
| 269 | if (FFMS_WriteTimecodes(Track, Filename.c_str(), &E)) |
| 270 | std::cout << std::endl << "Failed to write timecodes file " |
| 271 | << Filename << ": " << E.Buffer << std::endl; |
| 272 | } |
| 273 | } |
| 274 | if (PrintProgress) |
| 275 | std::cout << "done." << std::endl; |
| 276 | } |
| 277 | |
| 278 | if (WriteKF) { |
| 279 | if (PrintProgress) |
| 280 | std::cout << "Writing keyframes... "; |
| 281 | int NumTracks = FFMS_GetNumTracks(Index); |
| 282 | for (int t = 0; t < NumTracks; t++) { |
| 283 | FFMS_Track *Track = FFMS_GetTrackFromIndex(Index, t); |
| 284 | std::string Filename = DumpFilename(Track, t, ".kf.txt"); |
| 285 | if (!Filename.empty()) { |
| 286 | std::ofstream kf(Filename.c_str()); |
| 287 | kf << "# keyframe format v1\n" |
| 288 | "fps 0\n"; |
| 289 | |
| 290 | int FrameCount = FFMS_GetNumFrames(Track); |
| 291 | for (int CurFrameNum = 0; CurFrameNum < FrameCount; CurFrameNum++) { |
| 292 | if (FFMS_GetFrameInfo(Track, CurFrameNum)->KeyFrame) |
| 293 | kf << CurFrameNum << "\n"; |
| 294 | } |
| 295 | } |
| 296 | } |
| 297 | if (PrintProgress) |
| 298 | std::cout << "done. " << std::endl; |
| 299 | } |
| 300 | |
| 301 | if (PrintProgress) |
| 302 | std::cout << "Writing index... "; |
| 303 | |
| 304 | int error = FFMS_WriteIndex(CacheFile.c_str(), Index, &E); |
| 305 | FFMS_DestroyIndex(Index); |
| 306 | if (error) |
| 307 | throw Error("Error writing index: ", E); |
| 308 | |
| 309 | if (PrintProgress) |
| 310 | std::cout << "done." << std::endl; |
| 311 | } |
| 312 | |
| 313 | } // namespace { |
| 314 | |
| 315 | #ifdef _WIN32 |
| 316 | int wmain(int argc, const wchar_t *_argv[]) { |
| 317 | std::vector<const char *> StringPtrs(argc); |
| 318 | std::vector<std::string> StringStorage(argc); |
| 319 | |
| 320 | for (int i = 0; i < argc; i++) { |
| 321 | StringStorage[i] = utf16_to_utf8(_argv[i]); |
| 322 | StringPtrs[i] = StringStorage[i].c_str(); |
| 323 | } |
| 324 | |
| 325 | const char **argv = StringPtrs.data(); |
| 326 | #else |
| 327 | int main(int argc, const char *argv[]) { |
| 328 | #endif |
| 329 | try { |
| 330 | if (argc <= 1) { |
| 331 | PrintUsage(); |
| 332 | return 0; |
| 333 | } |
| 334 | |
| 335 | ParseCMDLine(argc, argv); |
| 336 | } catch (Error const& e) { |
| 337 | std::cout << e.msg << std::endl << std::flush; |
| 338 | return 1; |
| 339 | } |
| 340 | |
| 341 | FFMS_Init(0, 0); |
| 342 | |
| 343 | switch (Verbose) { |
| 344 | case 0: FFMS_SetLogLevel(FFMS_LOG_QUIET); break; |
| 345 | case 1: FFMS_SetLogLevel(FFMS_LOG_WARNING); break; |
| 346 | case 2: FFMS_SetLogLevel(FFMS_LOG_INFO); break; |
| 347 | case 3: FFMS_SetLogLevel(FFMS_LOG_VERBOSE); break; |
| 348 | default: FFMS_SetLogLevel(FFMS_LOG_DEBUG); // if user used -v 4 or more times, he deserves the spam |
| 349 | } |
| 350 | |
| 351 | try { |
| 352 | DoIndexing(); |
| 353 | } catch (Error const& e) { |
| 354 | std::cout << e.msg << std::endl << std::flush; |
| 355 | return 1; |
| 356 | } |
| 357 | |
| 358 | return 0; |
| 359 | } |