├── .gitattributes ├── .github └── workflows │ ├── ci.yml │ └── ci_linux.yml ├── .gitignore ├── CMakeLists.txt ├── LICENSE ├── README.md ├── app ├── CMakeLists.txt ├── main.cpp ├── mainwindow.cpp ├── mainwindow.h ├── model.cpp ├── model.h ├── objectmodel.cpp ├── objectmodel.h ├── panel.cpp ├── panel.h ├── res │ ├── AppImage.desktop │ ├── icon.ico │ ├── icon.svg │ ├── icon1024x1024.png │ ├── icon128x128.png │ ├── icon16x16.png │ ├── icon256x256.png │ ├── icon32x32.png │ ├── icon48x48.png │ ├── icon512x512.png │ ├── icon64x64.png │ └── res.rc ├── siview │ ├── chunkmodel.cpp │ ├── chunkmodel.h │ ├── infopanel.cpp │ ├── infopanel.h │ ├── siview.cpp │ └── siview.h ├── vector3edit.cpp ├── vector3edit.h └── viewer │ ├── mediapanel.cpp │ └── mediapanel.h ├── cmake └── FindFFMPEG.cmake ├── lib ├── CMakeLists.txt ├── core.cpp ├── core.h ├── file.cpp ├── file.h ├── info.h ├── interleaf.cpp ├── interleaf.h ├── object.cpp ├── object.h ├── othertypes.h ├── sitypes.cpp ├── sitypes.h ├── types.h └── util.h └── packaging └── screenshot.png /.gitattributes: -------------------------------------------------------------------------------- 1 | * text=auto eol=lf 2 | 3 | *.sln text eol=crlf 4 | -------------------------------------------------------------------------------- /.github/workflows/ci.yml: -------------------------------------------------------------------------------- 1 | name: CI 2 | 3 | on: 4 | push: 5 | branches: 6 | - master 7 | paths-ignore: 8 | - 'README.md' 9 | pull_request: 10 | branches: 11 | - master 12 | paths-ignore: 13 | - 'README.md' 14 | 15 | jobs: 16 | build: 17 | runs-on: windows-latest 18 | 19 | env: 20 | FFMPEG_DIR: ffmpeg-n5.1.6-16-g6e63e49496-win64-gpl-shared-5.1 21 | 22 | steps: 23 | - name: Checkout 24 | uses: actions/checkout@v2 25 | with: 26 | fetch-depth: 0 27 | 28 | - name: Install Developer Command Prompt for Microsoft Visual C++ 29 | uses: ilammy/msvc-dev-cmd@v1 30 | 31 | - name: Install Qt 32 | uses: jurplel/install-qt-action@v4 33 | with: 34 | version: '6.9' 35 | arch: 'win64_msvc2022_64' 36 | modules: 'qtmultimedia' 37 | 38 | - name: Install FFmpeg 39 | shell: bash 40 | run: | 41 | curl -fLOSs https://github.com/BtbN/FFmpeg-Builds/releases/download/autobuild-2025-01-31-12-58/$FFMPEG_DIR.zip 42 | 7z x $FFMPEG_DIR.zip 43 | 44 | - name: Build 45 | shell: bash 46 | run: | 47 | cmake . -G Ninja -DCMAKE_BUILD_TYPE=Release -DFFMPEG_ROOT=$FFMPEG_DIR 48 | ninja 49 | 50 | - name: Deploy 51 | shell: bash 52 | run: | 53 | mkdir deploy 54 | cp app/*.exe deploy 55 | cp lib/*.dll deploy 56 | cp $FFMPEG_DIR/bin/*.dll deploy 57 | cd deploy 58 | windeployqt si-edit.exe libweaver.dll 59 | 60 | - name: Upload Build Artifact 61 | uses: actions/upload-artifact@v4 62 | with: 63 | path: 64 | deploy 65 | 66 | - name: Upload to Releases 67 | shell: bash 68 | if: github.event_name == 'push' 69 | env: 70 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} 71 | TRAVIS_REPO_SLUG: isledecomp/siedit 72 | TRAVIS_COMMIT: ${{ github.sha }} 73 | run: | 74 | cd deploy 75 | 7z a si-edit.zip * 76 | curl -fLOSs --retry 2 --retry-delay 60 https://github.com/probonopd/uploadtool/raw/master/upload.sh 77 | ./upload.sh si-edit.zip 78 | -------------------------------------------------------------------------------- /.github/workflows/ci_linux.yml: -------------------------------------------------------------------------------- 1 | name: CI-Linux 2 | 3 | on: 4 | push: 5 | branches: 6 | - master 7 | paths-ignore: 8 | - 'README.md' 9 | pull_request: 10 | branches: 11 | - master 12 | paths-ignore: 13 | - 'README.md' 14 | 15 | jobs: 16 | build: 17 | runs-on: ubuntu-latest 18 | 19 | steps: 20 | - name: Checkout 21 | uses: actions/checkout@v4 22 | with: 23 | fetch-depth: 0 24 | 25 | - name: Install Qt 26 | uses: jurplel/install-qt-action@v4 27 | with: 28 | version: '6.9' 29 | arch: 'linux_gcc_64' 30 | modules: 'qtmultimedia' 31 | 32 | - name: Install build dependencies 33 | env: 34 | FFMPEG_DEPS: > 35 | libavutil-dev 36 | libavcodec-dev 37 | libavformat-dev 38 | libavfilter-dev 39 | libswscale-dev 40 | libswresample-dev 41 | libfuse2 42 | APPIMAGE_DEPS: > 43 | libfuse2 44 | libxcb-cursor0 45 | run: sudo apt install -y $FFMPEG_DEPS $APPIMAGE_DEPS 46 | 47 | - name: Build 48 | run: | 49 | cmake -B ${{github.workspace}}/build -DCMAKE_BUILD_TYPE=Release 50 | cmake --build ${{github.workspace}}/build 51 | 52 | - name: Install linuxdeploy 53 | run: | 54 | wget https://github.com/linuxdeploy/linuxdeploy/releases/download/continuous/linuxdeploy-x86_64.AppImage 55 | wget https://github.com/linuxdeploy/linuxdeploy-plugin-qt/releases/download/continuous/linuxdeploy-plugin-qt-x86_64.AppImage 56 | chmod +x linuxdeploy-x86_64.AppImage 57 | chmod +x linuxdeploy-plugin-qt-x86_64.AppImage 58 | 59 | - name: Build AppImage 60 | # Qt6_DIR is set by the install-qt-action 61 | run: > 62 | QMAKE=$Qt6_DIR/bin/qmake 63 | PATH=$Qt6_DIR/libexec:$PATH 64 | ./linuxdeploy-x86_64.AppImage 65 | --appdir AppDir 66 | -e ${{github.workspace}}/build/app/si-edit 67 | -i ${{github.workspace}}/app/res/icon.svg 68 | -d ${{github.workspace}}/app/res/AppImage.desktop 69 | --plugin qt 70 | --output appimage 71 | 72 | - name: 'Upload Artifact: libweaver' 73 | uses: actions/upload-artifact@v4 74 | with: 75 | name: libweaver-Linux 76 | path: ${{github.workspace}}/build/lib/libweaver.so 77 | if-no-files-found: error 78 | 79 | - name: 'Upload Artifact: AppImage' 80 | uses: actions/upload-artifact@v4 81 | with: 82 | name: SI-Edit-Linux.AppImage 83 | path: ${{github.workspace}}/SI_Edit*.AppImage 84 | if-no-files-found: error 85 | 86 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | *.user 2 | build/ 3 | -------------------------------------------------------------------------------- /CMakeLists.txt: -------------------------------------------------------------------------------- 1 | cmake_minimum_required(VERSION 3.14) 2 | 3 | project(libweaver VERSION 1.0 LANGUAGES CXX) 4 | 5 | set(CMAKE_INCLUDE_CURRENT_DIR ON) 6 | 7 | list(APPEND CMAKE_MODULE_PATH "${CMAKE_SOURCE_DIR}/cmake") 8 | 9 | add_subdirectory(lib) 10 | add_subdirectory(app) 11 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # SIEdit 2 | 3 | SIEdit is a fully graphical viewer and editor of the SI streaming asset pack format used by LEGO Island. It can view, extract, and replace data in all of the game's SI files, allowing textures, sounds, animations, path information, FMVs, and even some game logic/metadata to be modified. It is currently still under development, but should work with all files. 4 | 5 | ![SIEdit Screenshot](https://raw.githubusercontent.com/itsmattkc/SIEdit/master/packaging/screenshot.png) 6 | 7 | ## libweaver 8 | 9 | All of the SI-specific code is contained in a separate C++ library called **libweaver**, enabling other projects to re-use the discoveries here and work with SI files too. Currently there is no documentation or stable API, however it should be fairly straightforward, and I plan to add those things in the future. 10 | 11 | ## Building 12 | 13 | SIEdit and libweaver use the fairly standard CMake build system. 14 | 15 | **SIEdit** requires Qt 6+ and FFmpeg for the UI and media playback respectively. 16 | 17 | **libweaver** uses only standard libraries from C++98, and shouldn't require anything special. 18 | 19 | ## Future 20 | 21 | Here's a non-exhaustive list of things I'd like to add in the future: 22 | 23 | - Auto-conversion/conforming when replacing files. Right now, when you replace files, you have to manually convert them into the right format before doing so (e.g. 256-color bitmap with specific paletting, Smacker 2, FLIC, WAV, et al.) It would be nice if SIEdit did this automatically. 24 | - Stable API for libweaver. The library is fairly usable as-is, but it isn't the cleanest thing in the world right now, and I'd like for other people to be able to use it with as little headache as possible. This is my first time providing a library for use in other projects so I also may have made some mistakes. 25 | - Ability to create SI files from scratch. Currently any changes made must use an existing SI as a base. It would be interesting to be able to load completely custom SIs into the game. This may require some more reverse engineering, though I think we have most of the work down. 26 | - As a corollary from this, also the ability to add/delete objects, as opposed to just replacing what already exists. 27 | - More packaging options. Currently we only provide a Windows build, which is ironic since I'm not even a Windows user. We may add a build for macOS and an AppImage for Linux, and I might try setting up a package on the AUR since I use Arch (btw) 28 | -------------------------------------------------------------------------------- /app/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | find_package(Qt6) 2 | 3 | find_package(QT NAMES Qt6 REQUIRED COMPONENTS Widgets Multimedia) 4 | find_package(Qt${QT_VERSION_MAJOR} REQUIRED COMPONENTS Widgets Multimedia) 5 | 6 | find_package(FFMPEG 3.0 REQUIRED 7 | COMPONENTS 8 | avutil 9 | avcodec 10 | avformat 11 | avfilter 12 | swscale 13 | swresample 14 | ) 15 | 16 | set(PROJECT_SOURCES 17 | siview/chunkmodel.cpp 18 | siview/chunkmodel.h 19 | siview/infopanel.cpp 20 | siview/infopanel.h 21 | siview/siview.cpp 22 | siview/siview.h 23 | 24 | viewer/mediapanel.cpp 25 | viewer/mediapanel.h 26 | 27 | main.cpp 28 | mainwindow.cpp 29 | mainwindow.h 30 | model.cpp 31 | model.h 32 | objectmodel.cpp 33 | objectmodel.h 34 | panel.cpp 35 | panel.h 36 | vector3edit.cpp 37 | vector3edit.h 38 | 39 | res/res.rc 40 | ) 41 | 42 | if(${QT_VERSION_MAJOR} GREATER_EQUAL 6) 43 | qt_add_executable(si-edit 44 | MANUAL_FINALIZATION 45 | ${PROJECT_SOURCES} 46 | ) 47 | else() 48 | add_executable(si-edit 49 | ${PROJECT_SOURCES} 50 | ) 51 | endif() 52 | 53 | target_link_libraries(si-edit PRIVATE 54 | Qt${QT_VERSION_MAJOR}::Widgets 55 | Qt${QT_VERSION_MAJOR}::Multimedia 56 | FFMPEG::avutil 57 | FFMPEG::avcodec 58 | FFMPEG::avformat 59 | FFMPEG::avfilter 60 | FFMPEG::swscale 61 | FFMPEG::swresample 62 | libweaver) 63 | target_include_directories(si-edit PRIVATE "${CMAKE_SOURCE_DIR}/lib" ${FFMPEG_INCLUDE_DIRS}) 64 | if (NOT MSVC) 65 | target_compile_options(si-edit PRIVATE -Werror) 66 | endif() 67 | 68 | set_target_properties(si-edit PROPERTIES 69 | MACOSX_BUNDLE_GUI_IDENTIFIER com.mattkc.SIEdit 70 | MACOSX_BUNDLE_BUNDLE_VERSION ${PROJECT_VERSION} 71 | MACOSX_BUNDLE_SHORT_VERSION_STRING ${PROJECT_VERSION_MAJOR}.${PROJECT_VERSION_MINOR} 72 | MACOSX_BUNDLE TRUE 73 | WIN32_EXECUTABLE TRUE 74 | CXX_STANDARD 17 75 | CXX_STANDARD_REQUIRED ON 76 | AUTOUIC ON 77 | AUTOMOC ON 78 | AUTORCC ON 79 | ) 80 | 81 | if(QT_VERSION_MAJOR EQUAL 6) 82 | qt_finalize_executable(si-edit) 83 | endif() 84 | -------------------------------------------------------------------------------- /app/main.cpp: -------------------------------------------------------------------------------- 1 | #include "mainwindow.h" 2 | 3 | #include 4 | #include 5 | 6 | void DebugHandler(QtMsgType type, const QMessageLogContext &context, const QString &msg) 7 | { 8 | QByteArray localMsg = msg.toLocal8Bit(); 9 | 10 | const char* msg_type = "UNKNOWN"; 11 | switch (type) { 12 | case QtDebugMsg: 13 | msg_type = "DEBUG"; 14 | break; 15 | case QtInfoMsg: 16 | msg_type = "INFO"; 17 | break; 18 | case QtWarningMsg: 19 | msg_type = "WARNING"; 20 | break; 21 | case QtCriticalMsg: 22 | msg_type = "ERROR"; 23 | break; 24 | case QtFatalMsg: 25 | msg_type = "FATAL"; 26 | break; 27 | } 28 | 29 | fprintf(stderr, "[%s] %s (%s:%u)\n", msg_type, localMsg.constData(), context.function, context.line); 30 | 31 | #ifdef Q_OS_WINDOWS 32 | // Windows still seems to buffer stderr and we want to see debug messages immediately, so here we make sure each line 33 | // is flushed 34 | fflush(stderr); 35 | #endif 36 | } 37 | 38 | int main(int argc, char *argv[]) 39 | { 40 | qInstallMessageHandler(DebugHandler); 41 | 42 | QApplication a(argc, argv); 43 | 44 | MainWindow w; 45 | 46 | QCommandLineParser parser; 47 | parser.addPositionalArgument(QCoreApplication::translate("main", "file"), 48 | QCoreApplication::translate("main", "The file to open on startup.")); 49 | 50 | parser.process(a); 51 | 52 | if (!parser.positionalArguments().empty()) { 53 | w.OpenFilename(parser.positionalArguments().first()); 54 | } 55 | 56 | w.show(); 57 | return a.exec(); 58 | } 59 | -------------------------------------------------------------------------------- /app/mainwindow.cpp: -------------------------------------------------------------------------------- 1 | #include "mainwindow.h" 2 | 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | 9 | #include "siview/siview.h" 10 | 11 | using namespace si; 12 | 13 | const QString MainWindow::kFileFilter = tr("Interleaf Files (*.si)"); 14 | 15 | MainWindow::MainWindow(QWidget *parent) : 16 | QMainWindow{parent}, 17 | last_set_data_(nullptr) 18 | { 19 | auto splitter = new QSplitter(); 20 | splitter->setChildrenCollapsible(false); 21 | this->setCentralWidget(splitter); 22 | 23 | tree_ = new QTreeView(); 24 | tree_->setModel(&model_); 25 | tree_->setContextMenuPolicy(Qt::CustomContextMenu); 26 | connect(tree_->selectionModel(), &QItemSelectionModel::currentRowChanged, this, &MainWindow::SelectionChanged); 27 | connect(tree_, &QTreeView::customContextMenuRequested, this, &MainWindow::ShowContextMenu); 28 | splitter->addWidget(tree_); 29 | 30 | auto config_area = new QWidget(); 31 | splitter->addWidget(config_area); 32 | 33 | auto config_layout = new QVBoxLayout(config_area); 34 | 35 | action_grp_ = new QGroupBox(); 36 | config_layout->addWidget(action_grp_); 37 | 38 | auto action_layout = new QHBoxLayout(action_grp_); 39 | 40 | action_layout->addStretch(); 41 | 42 | auto extract_btn = new QPushButton(tr("Extract")); 43 | action_layout->addWidget(extract_btn); 44 | connect(extract_btn, &QPushButton::clicked, this, &MainWindow::ExtractClicked); 45 | 46 | auto replace_btn = new QPushButton(tr("Replace")); 47 | action_layout->addWidget(replace_btn); 48 | connect(replace_btn, &QPushButton::clicked, this, &MainWindow::ReplaceClicked); 49 | 50 | action_layout->addStretch(); 51 | 52 | config_stack_ = new QStackedWidget(); 53 | config_layout->addWidget(config_stack_, 1); 54 | 55 | panel_blank_ = new Panel(); 56 | config_stack_->addWidget(panel_blank_); 57 | 58 | panel_media_ = new MediaPanel(); 59 | config_stack_->addWidget(panel_media_); 60 | 61 | properties_group_ = new QGroupBox(); 62 | config_layout->addWidget(properties_group_); 63 | 64 | auto properties_layout = new QGridLayout(properties_group_); 65 | 66 | { 67 | int prow = 0; 68 | 69 | properties_layout->addWidget(new QLabel(tr("Extra")), prow, 0); 70 | 71 | m_extraEdit = new QPlainTextEdit(this); 72 | m_extraEdit->setFixedHeight(m_extraEdit->fontMetrics().height() * 3); 73 | connect(m_extraEdit, &QPlainTextEdit::textChanged, this, &MainWindow::ExtraChanged); 74 | properties_layout->addWidget(m_extraEdit, prow, 1); 75 | 76 | prow++; 77 | 78 | properties_layout->addWidget(new QLabel(tr("Location")), prow, 0); 79 | 80 | m_LocationEdit = new Vector3Edit(); 81 | connect(m_LocationEdit, &Vector3Edit::changed, this, &MainWindow::LocationChanged); 82 | properties_layout->addWidget(m_LocationEdit, prow, 1); 83 | 84 | prow++; 85 | 86 | properties_layout->addWidget(new QLabel(tr("Up")), prow, 0); 87 | 88 | m_UpEdit = new Vector3Edit(); 89 | connect(m_UpEdit, &Vector3Edit::changed, this, &MainWindow::UpChanged); 90 | properties_layout->addWidget(m_UpEdit, prow, 1); 91 | 92 | prow++; 93 | 94 | properties_layout->addWidget(new QLabel(tr("Start Time")), prow, 0); 95 | 96 | start_time_edit_ = new QSpinBox(); 97 | start_time_edit_->setMinimum(0); 98 | start_time_edit_->setMaximum(INT_MAX); 99 | connect(start_time_edit_, static_cast(&QSpinBox::valueChanged), this, &MainWindow::StartTimeChanged); 100 | properties_layout->addWidget(start_time_edit_, prow, 1); 101 | } 102 | 103 | InitializeMenuBar(); 104 | 105 | splitter->setSizes({99999, 99999}); 106 | 107 | setWindowTitle(tr("SI Editor")); 108 | 109 | SetPanel(panel_blank_, nullptr); 110 | } 111 | 112 | void MainWindow::OpenFilename(const QString &s) 113 | { 114 | tree_->clearSelection(); 115 | SetPanel(panel_blank_, nullptr); 116 | model_.SetCore(nullptr); 117 | 118 | if (OpenInterleafFileInternal(this, &interleaf_, s)) { 119 | //tree_->blockSignals(true); 120 | model_.SetCore(&interleaf_); 121 | // tree_->blockSignals(false); 122 | } 123 | } 124 | 125 | void MainWindow::InitializeMenuBar() 126 | { 127 | auto menubar = new QMenuBar(); 128 | 129 | auto file_menu = menubar->addMenu(tr("&File")); 130 | 131 | file_menu->addAction(tr("&New"), tr("Ctrl+N"), this, &MainWindow::NewFile); 132 | 133 | file_menu->addAction(tr("&Open"), tr("Ctrl+O"), this, &MainWindow::OpenFile); 134 | 135 | file_menu->addAction(tr("&Save"), tr("Ctrl+S"), this, &MainWindow::SaveFile); 136 | 137 | file_menu->addAction(tr("Save &As"), tr("Ctrl+Shift+S"), this, &MainWindow::SaveFileAs); 138 | 139 | file_menu->addSeparator(); 140 | 141 | file_menu->addAction(tr("&View SI File"), tr("Ctrl+I"), this, &MainWindow::ViewSIFile); 142 | 143 | file_menu->addAction(tr("E&xtract All"), this, &MainWindow::ExtractAll); 144 | 145 | file_menu->addSeparator(); 146 | 147 | file_menu->addAction(tr("E&xit"), this, &MainWindow::close); 148 | 149 | setMenuBar(menubar); 150 | } 151 | 152 | void MainWindow::SetPanel(Panel *panel, si::Object *chunk) 153 | { 154 | auto current = static_cast(config_stack_->currentWidget()); 155 | current->SetData(nullptr); 156 | 157 | if (chunk && chunk->type() == MxOb::Null) { 158 | chunk = nullptr; 159 | } 160 | 161 | config_stack_->setCurrentWidget(panel); 162 | panel->SetData(chunk); 163 | last_set_data_ = chunk; 164 | 165 | action_grp_->setEnabled(chunk); 166 | properties_group_->setEnabled(chunk); 167 | 168 | if (chunk) { 169 | m_extraEdit->setPlainText(QString::fromUtf8(chunk->extra_.data())); 170 | m_LocationEdit->SetValue(chunk->location_); 171 | m_UpEdit->SetValue(chunk->up_); 172 | start_time_edit_->setValue(chunk->time_offset_); 173 | } else { 174 | m_extraEdit->setPlainText(QString()); 175 | m_LocationEdit->SetValue(si::Vector3(0, 0, 0)); 176 | m_UpEdit->SetValue(si::Vector3(0, 0, 0)); 177 | start_time_edit_->setValue(0); 178 | } 179 | } 180 | 181 | void MainWindow::ExtractObject(si::Object *obj) 182 | { 183 | QString filename = QString::fromStdString(obj->filename()); 184 | if (filename.isEmpty()) { 185 | filename = QString::fromStdString(obj->name()); 186 | filename.append(QStringLiteral(".bin")); 187 | } else { 188 | // Strip off directory 189 | int index = filename.lastIndexOf('\\'); 190 | if (index != -1) { 191 | filename = filename.mid(index+1); 192 | } 193 | } 194 | 195 | QString s = QFileDialog::getSaveFileName(this, tr("Export Object"), filename); 196 | if (!s.isEmpty()) { 197 | if (!obj->ExtractToFile( 198 | #ifdef Q_OS_WINDOWS 199 | s.toStdWString().c_str() 200 | #else 201 | s.toUtf8() 202 | #endif 203 | )) { 204 | QMessageBox::critical(this, QString(), tr("Failed to write to file \"%1\".").arg(s)); 205 | } 206 | } 207 | } 208 | 209 | void MainWindow::ReplaceObject(si::Object *obj) 210 | { 211 | QString s = QFileDialog::getOpenFileName(this, tr("Replace Object")); 212 | if (!s.isEmpty()) { 213 | if (obj->ReplaceWithFile( 214 | #ifdef Q_OS_WINDOWS 215 | s.toStdWString().c_str() 216 | #else 217 | s.toUtf8() 218 | #endif 219 | )) { 220 | static_cast(config_stack_->currentWidget())->ResetData(); 221 | } else { 222 | QMessageBox::critical(this, QString(), tr("Failed to open to file \"%1\".").arg(s)); 223 | } 224 | } 225 | } 226 | 227 | bool MainWindow::OpenInterleafFileInternal(QWidget *parent, si::Interleaf *interleaf, const QString &s) 228 | { 229 | Interleaf::Error r = interleaf->Read( 230 | #ifdef Q_OS_WINDOWS 231 | s.toStdWString().c_str() 232 | #else 233 | s.toUtf8() 234 | #endif 235 | ); 236 | 237 | if (r == Interleaf::ERROR_SUCCESS) { 238 | return true; 239 | } else { 240 | QMessageBox::critical(parent, QString(), tr("Failed to load Interleaf file: %1").arg(r)); 241 | return false; 242 | } 243 | } 244 | 245 | QString MainWindow::GetOpenFileName() 246 | { 247 | return QFileDialog::getOpenFileName(this, QString(), QString(), kFileFilter); 248 | } 249 | 250 | bool MainWindow::ExtractAllRecursiveInternal(const QDir &dir, const si::Core *obj) 251 | { 252 | if (!dir.mkpath(QStringLiteral("."))) { 253 | QMessageBox::critical(this, tr("Extract All Failed"), tr("Failed to create directory \"%1\". Try extracting somewhere else.").arg(dir.absolutePath())); 254 | return false; 255 | } 256 | 257 | for (const Core *child : obj->GetChildren()) { 258 | if (const Object *obj = dynamic_cast(child)) { 259 | if (!obj->data().empty()) { 260 | QString realFilename = QString::fromStdString(obj->filename()); 261 | realFilename = realFilename.mid(realFilename.lastIndexOf('\\')+1); 262 | 263 | QString output = dir.filePath(realFilename); 264 | 265 | if (!obj->ExtractToFile(output.toUtf8())) { 266 | QMessageBox::critical(this, tr("Extract All Failed"), tr("Failed to create file \"%1\". Try extracting somewhere else.").arg(output)); 267 | return false; 268 | } 269 | } 270 | 271 | if (obj->HasChildren()) { 272 | // Extract its children too 273 | if (!ExtractAllRecursiveInternal(QDir(dir.filePath(QString::fromStdString(obj->name()))), obj)) { 274 | return false; 275 | } 276 | } 277 | } 278 | } 279 | 280 | return true; 281 | } 282 | 283 | void MainWindow::NewFile() 284 | { 285 | model_.SetCore(nullptr); 286 | interleaf_.Clear(); 287 | model_.SetCore(&interleaf_); 288 | } 289 | 290 | void MainWindow::OpenFile() 291 | { 292 | QString s = GetOpenFileName(); 293 | if (!s.isEmpty()) { 294 | OpenFilename(s); 295 | } 296 | } 297 | 298 | bool MainWindow::SaveFile() 299 | { 300 | if (current_filename_.isEmpty()) { 301 | return SaveFileAs(); 302 | } else { 303 | Interleaf::Error r = interleaf_.Write( 304 | #ifdef Q_OS_WINDOWS 305 | current_filename_.toStdWString().c_str() 306 | #else 307 | current_filename_.toUtf8() 308 | #endif 309 | ); 310 | 311 | if (r == Interleaf::ERROR_SUCCESS) { 312 | return true; 313 | } else { 314 | QMessageBox::critical(this, QString(), tr("Failed to write SI file: %1").arg(r)); 315 | return false; 316 | } 317 | } 318 | } 319 | 320 | bool MainWindow::SaveFileAs() 321 | { 322 | current_filename_ = QFileDialog::getSaveFileName(this, QString(), QString(), kFileFilter); 323 | if (!current_filename_.isEmpty()) { 324 | return SaveFile(); 325 | } 326 | 327 | return false; 328 | } 329 | 330 | void MainWindow::SelectionChanged(const QModelIndex &index) 331 | { 332 | Panel *p = panel_blank_; 333 | Object *c = dynamic_cast(static_cast(index.internalPointer())); 334 | 335 | if (c) { 336 | p = panel_media_; 337 | } 338 | 339 | if (p != config_stack_->currentWidget() || c != last_set_data_) { 340 | SetPanel(p, c); 341 | } 342 | } 343 | 344 | void MainWindow::ShowContextMenu(const QPoint &p) 345 | { 346 | QMenu menu(this); 347 | 348 | QAction *extract_action = menu.addAction(tr("E&xtract")); 349 | connect(extract_action, &QAction::triggered, this, &MainWindow::ExtractSelectedItems); 350 | 351 | menu.exec(static_cast(sender())->mapToGlobal(p)); 352 | } 353 | 354 | void MainWindow::ExtractSelectedItems() 355 | { 356 | auto selected = tree_->selectionModel()->selectedRows(); 357 | if (selected.empty()) { 358 | return; 359 | } 360 | 361 | for (const QModelIndex &i : selected) { 362 | if (Object *obj = dynamic_cast(static_cast(i.internalPointer()))) { 363 | ExtractObject(obj); 364 | } 365 | } 366 | } 367 | 368 | void MainWindow::ExtractClicked() 369 | { 370 | ExtractObject(last_set_data_); 371 | } 372 | 373 | void MainWindow::ReplaceClicked() 374 | { 375 | ReplaceObject(last_set_data_); 376 | } 377 | 378 | void MainWindow::ViewSIFile() 379 | { 380 | QString s = GetOpenFileName(); 381 | if (!s.isEmpty()) { 382 | std::unique_ptr temp = std::make_unique(); 383 | if (OpenInterleafFileInternal(this, temp.get(), s)) { 384 | SIViewDialog *v = new SIViewDialog(temp->GetInformation(), this); 385 | v->SetSubtitle(QFileInfo(s).fileName()); 386 | v->temp = std::move(temp); 387 | v->setAttribute(Qt::WA_DeleteOnClose); 388 | v->show(); 389 | } 390 | } 391 | } 392 | 393 | void MainWindow::ExtractAll() 394 | { 395 | QString s = QFileDialog::getExistingDirectory(this, tr("Extract All To...")); 396 | if (s.isEmpty()) { 397 | return; 398 | } 399 | 400 | QDir dir(s); 401 | if (!dir.exists()) { 402 | QMessageBox::critical(this, tr("Extract All Failed"), tr("Directory \"%1\" is not valid. Try extracting somewhere else.").arg(s)); 403 | return; 404 | } 405 | 406 | ExtractAllRecursiveInternal(dir, &interleaf_); 407 | } 408 | 409 | void MainWindow::ExtraChanged() 410 | { 411 | if (last_set_data_) { 412 | auto edit = static_cast(sender()); 413 | QString v = edit->toPlainText(); 414 | last_set_data_->extra_ = bytearray(v.toUtf8(), v.size() + 1); 415 | last_set_data_->extra_[v.size()] = 0; 416 | } 417 | } 418 | 419 | void MainWindow::LocationChanged(const Vector3 &v) 420 | { 421 | if (last_set_data_) { 422 | last_set_data_->location_ = v; 423 | } 424 | } 425 | 426 | void MainWindow::UpChanged(const si::Vector3 &v) 427 | { 428 | if (last_set_data_) { 429 | last_set_data_->up_ = v; 430 | } 431 | } 432 | 433 | void MainWindow::StartTimeChanged(int t) 434 | { 435 | if (last_set_data_) { 436 | last_set_data_->time_offset_ = t; 437 | } 438 | } 439 | -------------------------------------------------------------------------------- /app/mainwindow.h: -------------------------------------------------------------------------------- 1 | #ifndef MAINWINDOW_H 2 | #define MAINWINDOW_H 3 | 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | #include 11 | #include 12 | 13 | #include "objectmodel.h" 14 | #include "panel.h" 15 | #include "vector3edit.h" 16 | #include "viewer/mediapanel.h" 17 | 18 | class MainWindow : public QMainWindow 19 | { 20 | Q_OBJECT 21 | public: 22 | explicit MainWindow(QWidget *parent = nullptr); 23 | 24 | void OpenFilename(const QString &s); 25 | 26 | signals: 27 | 28 | private: 29 | void InitializeMenuBar(); 30 | 31 | void SetPanel(Panel *panel, si::Object *chunk); 32 | 33 | void ExtractObject(si::Object *obj); 34 | void ReplaceObject(si::Object *obj); 35 | 36 | static bool OpenInterleafFileInternal(QWidget *parent, si::Interleaf *interleaf, const QString &s); 37 | 38 | QString GetOpenFileName(); 39 | 40 | bool ExtractAllRecursiveInternal(const QDir &dir, const si::Core *obj); 41 | 42 | static const QString kFileFilter; 43 | 44 | QStackedWidget *config_stack_; 45 | 46 | QTreeView *tree_; 47 | 48 | QGroupBox *action_grp_; 49 | 50 | Panel *panel_blank_; 51 | MediaPanel *panel_media_; 52 | 53 | ObjectModel model_; 54 | si::Interleaf interleaf_; 55 | 56 | si::Object *last_set_data_; 57 | 58 | QString current_filename_; 59 | 60 | QGroupBox *properties_group_; 61 | 62 | QPlainTextEdit *m_extraEdit; 63 | Vector3Edit *m_LocationEdit; 64 | Vector3Edit *m_UpEdit; 65 | 66 | QSpinBox *start_time_edit_; 67 | 68 | private slots: 69 | void NewFile(); 70 | void OpenFile(); 71 | bool SaveFile(); 72 | bool SaveFileAs(); 73 | 74 | void SelectionChanged(const QModelIndex &index); 75 | 76 | void ShowContextMenu(const QPoint &p); 77 | 78 | void ExtractSelectedItems(); 79 | void ExtractClicked(); 80 | 81 | void ReplaceClicked(); 82 | 83 | void ViewSIFile(); 84 | void ExtractAll(); 85 | 86 | void ExtraChanged(); 87 | void LocationChanged(const si::Vector3 &v); 88 | void UpChanged(const si::Vector3 &v); 89 | void StartTimeChanged(int t); 90 | 91 | }; 92 | 93 | #endif // MAINWINDOW_H 94 | -------------------------------------------------------------------------------- /app/model.cpp: -------------------------------------------------------------------------------- 1 | #include "model.h" 2 | 3 | #define super QAbstractItemModel 4 | 5 | Model::Model(QObject *parent) : 6 | super(parent), 7 | core_(nullptr) 8 | { 9 | 10 | } 11 | 12 | void Model::SetCore(si::Core *c) 13 | { 14 | beginResetModel(); 15 | core_ = c; 16 | endResetModel(); 17 | } 18 | 19 | si::Core *Model::GetCoreFromIndex(const QModelIndex &index) const 20 | { 21 | if (!index.isValid()) { 22 | return core_; 23 | } else { 24 | return static_cast(index.internalPointer()); 25 | } 26 | } 27 | 28 | QModelIndex Model::index(int row, int column, const QModelIndex &parent) const 29 | { 30 | si::Core *c = GetCoreFromIndex(parent); 31 | if (!c) { 32 | return QModelIndex(); 33 | } 34 | 35 | return createIndex(row, column, c->GetChildAt(row)); 36 | } 37 | 38 | QModelIndex Model::parent(const QModelIndex &index) const 39 | { 40 | si::Core *child = GetCoreFromIndex(index); 41 | if (!child) { 42 | return QModelIndex(); 43 | } 44 | 45 | si::Core *parent = child->GetParent(); 46 | if (!parent) { 47 | return QModelIndex(); 48 | } 49 | 50 | si::Core *grandparent = parent->GetParent(); 51 | if (!grandparent) { 52 | return QModelIndex(); 53 | } 54 | 55 | size_t row = grandparent->IndexOfChild(parent); 56 | return createIndex(int(row), 0, parent); 57 | } 58 | 59 | int Model::rowCount(const QModelIndex &parent) const 60 | { 61 | si::Core *c = GetCoreFromIndex(parent); 62 | if (!c) { 63 | return 0; 64 | } 65 | 66 | return int(c->GetChildCount()); 67 | } 68 | -------------------------------------------------------------------------------- /app/model.h: -------------------------------------------------------------------------------- 1 | #ifndef MODEL_H 2 | #define MODEL_H 3 | 4 | #include 5 | #include 6 | 7 | class Model : public QAbstractItemModel 8 | { 9 | public: 10 | explicit Model(QObject *parent = nullptr); 11 | 12 | si::Core *GetCore() const { return core_; } 13 | void SetCore(si::Core *c); 14 | 15 | virtual QModelIndex index(int row, int column, const QModelIndex &parent = QModelIndex()) const override; 16 | virtual QModelIndex parent(const QModelIndex &index) const override; 17 | virtual int rowCount(const QModelIndex &parent = QModelIndex()) const override; 18 | 19 | protected: 20 | si::Core *GetCoreFromIndex(const QModelIndex &index) const; 21 | 22 | private: 23 | si::Core *core_; 24 | 25 | }; 26 | 27 | #endif // MODEL_H 28 | -------------------------------------------------------------------------------- /app/objectmodel.cpp: -------------------------------------------------------------------------------- 1 | #include "objectmodel.h" 2 | 3 | #include 4 | 5 | #define super Model 6 | 7 | using namespace si; 8 | 9 | ObjectModel::ObjectModel(QObject *parent) : 10 | super{parent} 11 | { 12 | } 13 | 14 | int ObjectModel::columnCount(const QModelIndex &parent) const 15 | { 16 | return kColCount; 17 | } 18 | 19 | QVariant ObjectModel::data(const QModelIndex &index, int role) const 20 | { 21 | Core *c = GetCoreFromIndex(index); 22 | 23 | switch (role) { 24 | case Qt::DisplayRole: 25 | 26 | switch (index.column()) { 27 | case kColIndex: 28 | if (Object *o = dynamic_cast(c)) { 29 | if (!index.parent().isValid()) { 30 | return tr("%1:%2").arg(QString::number(index.row()), QString::number(o->id())); 31 | } else { 32 | return QString::number(o->id()); 33 | } 34 | } 35 | break; 36 | case kColName: 37 | if (Object *o = dynamic_cast(c)) { 38 | return QString::fromStdString(o->name()); 39 | } 40 | break; 41 | } 42 | 43 | break; 44 | } 45 | 46 | return QVariant(); 47 | } 48 | 49 | QVariant ObjectModel::headerData(int section, Qt::Orientation orientation, int role) const 50 | { 51 | if (orientation == Qt::Horizontal && role == Qt::DisplayRole) { 52 | switch (section) { 53 | case kColIndex: 54 | return tr("Index"); 55 | case kColName: 56 | return tr("Name"); 57 | } 58 | } 59 | 60 | return super::headerData(section, orientation, role); 61 | } 62 | -------------------------------------------------------------------------------- /app/objectmodel.h: -------------------------------------------------------------------------------- 1 | #ifndef OBJECTMODEL_H 2 | #define OBJECTMODEL_H 3 | 4 | #include 5 | 6 | #include "model.h" 7 | 8 | class ObjectModel : public Model 9 | { 10 | Q_OBJECT 11 | public: 12 | enum Columns { 13 | kColIndex, 14 | kColName, 15 | 16 | kColCount 17 | }; 18 | 19 | explicit ObjectModel(QObject *parent = nullptr); 20 | 21 | virtual int columnCount(const QModelIndex &parent = QModelIndex()) const override; 22 | virtual QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const override; 23 | virtual QVariant headerData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const override; 24 | 25 | }; 26 | 27 | #endif // OBJECTMODEL_H 28 | -------------------------------------------------------------------------------- /app/panel.cpp: -------------------------------------------------------------------------------- 1 | #include "panel.h" 2 | 3 | Panel::Panel(QWidget *parent) : 4 | QWidget{parent}, 5 | data_(nullptr) 6 | { 7 | outer_layout_ = new QVBoxLayout(this); 8 | outer_layout_->setContentsMargins(0, 0, 0, 0); 9 | 10 | layout_ = new QGridLayout(); 11 | outer_layout_->addLayout(layout_); 12 | } 13 | 14 | void Panel::SetData(void *data) 15 | { 16 | if (data_) { 17 | OnClosingData(data_); 18 | } 19 | 20 | data_ = data; 21 | 22 | if (data_) { 23 | OnOpeningData(data_); 24 | } 25 | } 26 | 27 | void Panel::ResetData() 28 | { 29 | SetData(data_); 30 | } 31 | 32 | void Panel::FinishLayout() 33 | { 34 | outer_layout_->addStretch(); 35 | } 36 | -------------------------------------------------------------------------------- /app/panel.h: -------------------------------------------------------------------------------- 1 | #ifndef PANEL_H 2 | #define PANEL_H 3 | 4 | #include 5 | #include 6 | 7 | class Panel : public QWidget 8 | { 9 | Q_OBJECT 10 | public: 11 | explicit Panel(QWidget *parent = nullptr); 12 | 13 | void *GetData() const { return data_; } 14 | void SetData(void *data); 15 | 16 | void ResetData(); 17 | 18 | signals: 19 | 20 | protected: 21 | virtual void OnOpeningData(void *data){} 22 | virtual void OnClosingData(void *data){} 23 | 24 | QGridLayout *layout() const { return layout_; } 25 | 26 | void FinishLayout(); 27 | 28 | private: 29 | void *data_; 30 | 31 | QVBoxLayout *outer_layout_; 32 | QGridLayout *layout_; 33 | 34 | }; 35 | 36 | #endif // PANEL_H 37 | -------------------------------------------------------------------------------- /app/res/AppImage.desktop: -------------------------------------------------------------------------------- 1 | [Desktop Entry] 2 | Name=SI Edit 3 | Comment=Tool for working with SI files 4 | Exec=si-edit 5 | Terminal=false 6 | Type=Application 7 | Icon=icon 8 | Categories=Development;Graphics;AudioVideo; 9 | 10 | -------------------------------------------------------------------------------- /app/res/icon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/isledecomp/SIEdit/8889908214f00b71ff724d73b3c787720a8482fb/app/res/icon.ico -------------------------------------------------------------------------------- /app/res/icon.svg: -------------------------------------------------------------------------------- 1 | 2 | 15 | 34 | 39 | 42 | 46 | 50 | 55 | 56 | 64 | 70 | 72 | 80 | 84 | 90 | 93 | 96 | 100 | 104 | 109 | 115 | 116 | 123 | 126 | 130 | 134 | 135 | 142 | 145 | 149 | 153 | 157 | 161 | 162 | 169 | 172 | 176 | 177 | 178 | 179 | -------------------------------------------------------------------------------- /app/res/icon1024x1024.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/isledecomp/SIEdit/8889908214f00b71ff724d73b3c787720a8482fb/app/res/icon1024x1024.png -------------------------------------------------------------------------------- /app/res/icon128x128.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/isledecomp/SIEdit/8889908214f00b71ff724d73b3c787720a8482fb/app/res/icon128x128.png -------------------------------------------------------------------------------- /app/res/icon16x16.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/isledecomp/SIEdit/8889908214f00b71ff724d73b3c787720a8482fb/app/res/icon16x16.png -------------------------------------------------------------------------------- /app/res/icon256x256.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/isledecomp/SIEdit/8889908214f00b71ff724d73b3c787720a8482fb/app/res/icon256x256.png -------------------------------------------------------------------------------- /app/res/icon32x32.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/isledecomp/SIEdit/8889908214f00b71ff724d73b3c787720a8482fb/app/res/icon32x32.png -------------------------------------------------------------------------------- /app/res/icon48x48.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/isledecomp/SIEdit/8889908214f00b71ff724d73b3c787720a8482fb/app/res/icon48x48.png -------------------------------------------------------------------------------- /app/res/icon512x512.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/isledecomp/SIEdit/8889908214f00b71ff724d73b3c787720a8482fb/app/res/icon512x512.png -------------------------------------------------------------------------------- /app/res/icon64x64.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/isledecomp/SIEdit/8889908214f00b71ff724d73b3c787720a8482fb/app/res/icon64x64.png -------------------------------------------------------------------------------- /app/res/res.rc: -------------------------------------------------------------------------------- 1 | IDI_ICON1 ICON "icon.ico" 2 | -------------------------------------------------------------------------------- /app/siview/chunkmodel.cpp: -------------------------------------------------------------------------------- 1 | #include "chunkmodel.h" 2 | 3 | #include 4 | #include 5 | 6 | #define super Model 7 | 8 | using namespace si; 9 | 10 | ChunkModel::ChunkModel(QObject *parent) : 11 | super{parent} 12 | { 13 | } 14 | 15 | int ChunkModel::columnCount(const QModelIndex &parent) const 16 | { 17 | return kColCount; 18 | } 19 | 20 | QVariant ChunkModel::data(const QModelIndex &index, int role) const 21 | { 22 | Info *c = static_cast(GetCoreFromIndex(index)); 23 | if (!c) { 24 | return QVariant(); 25 | } 26 | 27 | switch (role) { 28 | case Qt::DisplayRole: 29 | 30 | switch (index.column()) { 31 | case kColType: 32 | // Convert 4-byte ID to QString 33 | return QString::fromLatin1(reinterpret_cast(&c->GetType()), sizeof(uint32_t)); 34 | case kColOffset: 35 | return QStringLiteral("0x%1").arg(QString::number(c->GetOffset(), 16).toUpper()); 36 | case kColSize: 37 | return QStringLiteral("0x%1").arg(QString::number(c->GetSize(), 16).toUpper()); 38 | case kColDesc: 39 | return QString::fromUtf8(RIFF::GetTypeDescription(static_cast(c->GetType()))); 40 | case kColObjectID: 41 | uint32_t i = c->GetObjectID(); 42 | if (i != Info::NULL_OBJECT_ID) { 43 | return QString::number(i); 44 | } 45 | break; 46 | } 47 | 48 | break; 49 | } 50 | 51 | return QVariant(); 52 | } 53 | 54 | QVariant ChunkModel::headerData(int section, Qt::Orientation orientation, int role) const 55 | { 56 | if (orientation == Qt::Horizontal && role == Qt::DisplayRole) { 57 | switch (section) { 58 | case kColType: 59 | return tr("Type"); 60 | case kColOffset: 61 | return tr("Offset"); 62 | case kColSize: 63 | return tr("Size"); 64 | case kColDesc: 65 | return tr("Description"); 66 | case kColObjectID: 67 | return tr("Object ID"); 68 | } 69 | } 70 | 71 | return super::headerData(section, orientation, role); 72 | } 73 | -------------------------------------------------------------------------------- /app/siview/chunkmodel.h: -------------------------------------------------------------------------------- 1 | #ifndef CHUNKMODEL_H 2 | #define CHUNKMODEL_H 3 | 4 | #include 5 | 6 | #include "model.h" 7 | 8 | class ChunkModel : public Model 9 | { 10 | Q_OBJECT 11 | public: 12 | enum Columns 13 | { 14 | kColType, 15 | kColOffset, 16 | kColSize, 17 | kColDesc, 18 | kColObjectID, 19 | 20 | kColCount 21 | }; 22 | 23 | explicit ChunkModel(QObject *parent = nullptr); 24 | 25 | virtual int columnCount(const QModelIndex &parent = QModelIndex()) const override; 26 | virtual QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const override; 27 | virtual QVariant headerData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const override; 28 | 29 | }; 30 | 31 | #endif // CHUNKMODEL_H 32 | -------------------------------------------------------------------------------- /app/siview/infopanel.cpp: -------------------------------------------------------------------------------- 1 | #include "infopanel.h" 2 | 3 | #include 4 | #include 5 | #include 6 | 7 | InfoPanel::InfoPanel(QWidget *parent) : 8 | Panel(parent) 9 | { 10 | int row = 0; 11 | 12 | QScrollArea *scrollArea = new QScrollArea(this); 13 | scrollArea->setWidgetResizable(true); 14 | layout()->addWidget(scrollArea, row, 0); 15 | 16 | m_Lbl = new QLabel(scrollArea); 17 | m_Lbl->setAlignment(Qt::AlignTop | Qt::AlignLeft); 18 | scrollArea->setWidget(m_Lbl); 19 | 20 | row++; 21 | 22 | m_ShowDataBtn = new QPushButton(tr("Show Data")); 23 | connect(m_ShowDataBtn, &QPushButton::clicked, this, &InfoPanel::ShowData); 24 | layout()->addWidget(m_ShowDataBtn, row, 0); 25 | m_ShowDataBtn->hide(); 26 | 27 | row++; 28 | 29 | m_DataView = new QPlainTextEdit(); 30 | m_DataView->setFont(QFontDatabase::systemFont(QFontDatabase::FixedFont)); 31 | layout()->addWidget(m_DataView, row, 0); 32 | m_DataView->hide(); 33 | 34 | //FinishLayout(); 35 | } 36 | 37 | void InfoPanel::OnOpeningData(void *data) 38 | { 39 | auto info = static_cast(data); 40 | m_Lbl->setText(QString::fromStdString(info->GetDescription())); 41 | 42 | if (!info->GetData().empty()) { 43 | m_ShowDataBtn->show(); 44 | } 45 | } 46 | 47 | void InfoPanel::OnClosingData(void *data) 48 | { 49 | m_Lbl->setText(QString()); 50 | m_DataView->hide(); 51 | m_DataView->clear(); 52 | m_ShowDataBtn->hide(); 53 | } 54 | 55 | void InfoPanel::ShowData() 56 | { 57 | const si::bytearray &s = static_cast(this->GetData())->GetData(); 58 | 59 | m_ShowDataBtn->hide(); 60 | m_DataView->setPlainText(QByteArray(s.data(), s.size()).toHex()); 61 | m_DataView->show(); 62 | } 63 | -------------------------------------------------------------------------------- /app/siview/infopanel.h: -------------------------------------------------------------------------------- 1 | #ifndef INFOPANEL_H 2 | #define INFOPANEL_H 3 | 4 | #include 5 | #include 6 | #include 7 | 8 | #include "panel.h" 9 | 10 | class InfoPanel : public Panel 11 | { 12 | Q_OBJECT 13 | public: 14 | InfoPanel(QWidget *parent = nullptr); 15 | 16 | protected: 17 | virtual void OnOpeningData(void *data) override; 18 | virtual void OnClosingData(void *data) override; 19 | 20 | private: 21 | QLabel *m_Lbl; 22 | 23 | QPushButton *m_ShowDataBtn; 24 | 25 | QPlainTextEdit *m_DataView; 26 | 27 | private slots: 28 | void ShowData(); 29 | 30 | }; 31 | 32 | #endif // INFOPANEL_H 33 | -------------------------------------------------------------------------------- /app/siview/siview.cpp: -------------------------------------------------------------------------------- 1 | #include "siview.h" 2 | 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | 9 | using namespace si; 10 | 11 | SIViewDialog::SIViewDialog(Info *riff, QWidget *parent) : 12 | QWidget(parent, Qt::Window), 13 | root_(riff), 14 | last_set_data_(nullptr) 15 | { 16 | auto layout = new QVBoxLayout(this); 17 | 18 | auto splitter = new QSplitter(); 19 | splitter->setChildrenCollapsible(false); 20 | layout->addWidget(splitter); 21 | 22 | auto tree = new QTreeView(); 23 | chunk_model_.SetCore(riff); 24 | tree->setModel(&chunk_model_); 25 | tree->setContextMenuPolicy(Qt::CustomContextMenu); 26 | connect(tree->selectionModel(), &QItemSelectionModel::currentRowChanged, this, &SIViewDialog::SelectionChanged); 27 | splitter->addWidget(tree); 28 | 29 | /*config_stack_ = new QStackedWidget(); 30 | config_stack_->setContentsMargins(0,0,0,0); 31 | splitter->addWidget(config_stack_); 32 | 33 | panel_ = new InfoPanel(); 34 | config_stack_->addWidget(panel_);*/ 35 | 36 | panel_ = new InfoPanel(); 37 | splitter->addWidget(panel_); 38 | 39 | splitter->setSizes({99999, 99999}); 40 | 41 | SetSubtitle(QString()); 42 | } 43 | 44 | void SIViewDialog::SetSubtitle(const QString &s) 45 | { 46 | QString t; 47 | if (s.isEmpty()) { 48 | t = tr("View SI File"); 49 | } else { 50 | t = tr("View SI File: %1").arg(s); 51 | } 52 | setWindowTitle(t); 53 | } 54 | 55 | void SIViewDialog::SelectionChanged(const QModelIndex &index) 56 | { 57 | panel_->SetData(static_cast(index.internalPointer())); 58 | } 59 | -------------------------------------------------------------------------------- /app/siview/siview.h: -------------------------------------------------------------------------------- 1 | #ifndef SIVIEW_H 2 | #define SIVIEW_H 3 | 4 | #include 5 | #include 6 | #include 7 | 8 | #include "chunkmodel.h" 9 | #include "infopanel.h" 10 | 11 | class SIViewDialog : public QWidget 12 | { 13 | Q_OBJECT 14 | public: 15 | SIViewDialog(si::Info *info, QWidget *parent = nullptr); 16 | 17 | void SetSubtitle(const QString &s); 18 | 19 | std::unique_ptr temp; 20 | 21 | private: 22 | QStackedWidget *config_stack_; 23 | 24 | ChunkModel chunk_model_; 25 | 26 | InfoPanel *panel_; 27 | 28 | const si::Info *last_set_data_; 29 | const si::Info *root_; 30 | 31 | std::unique_ptr temp_interleaf_; 32 | 33 | private slots: 34 | void SelectionChanged(const QModelIndex &index); 35 | 36 | }; 37 | 38 | #endif // SIVIEW_H 39 | -------------------------------------------------------------------------------- /app/vector3edit.cpp: -------------------------------------------------------------------------------- 1 | #include "vector3edit.h" 2 | 3 | #include 4 | #include 5 | 6 | Vector3Edit::Vector3Edit(QWidget *parent) : 7 | QWidget{parent} 8 | { 9 | auto layout = new QHBoxLayout(this); 10 | 11 | layout->addWidget(new QLabel(tr("X"))); 12 | 13 | x_edit_ = new QDoubleSpinBox(); 14 | x_edit_->setMinimum(std::numeric_limits::lowest()); 15 | x_edit_->setMaximum(std::numeric_limits::max()); 16 | layout->addWidget(x_edit_); 17 | connect(x_edit_, static_cast(&QDoubleSpinBox::valueChanged), this, &Vector3Edit::internalChanged); 18 | 19 | layout->addStretch(); 20 | 21 | layout->addWidget(new QLabel(tr("Y"))); 22 | 23 | y_edit_ = new QDoubleSpinBox(); 24 | y_edit_->setMinimum(std::numeric_limits::lowest()); 25 | y_edit_->setMaximum(std::numeric_limits::max()); 26 | layout->addWidget(y_edit_); 27 | connect(y_edit_, static_cast(&QDoubleSpinBox::valueChanged), this, &Vector3Edit::internalChanged); 28 | 29 | layout->addStretch(); 30 | 31 | layout->addWidget(new QLabel(tr("Z"))); 32 | 33 | z_edit_ = new QDoubleSpinBox(); 34 | z_edit_->setMinimum(std::numeric_limits::lowest()); 35 | z_edit_->setMaximum(std::numeric_limits::max()); 36 | layout->addWidget(z_edit_); 37 | connect(z_edit_, static_cast(&QDoubleSpinBox::valueChanged), this, &Vector3Edit::internalChanged); 38 | } 39 | 40 | si::Vector3 Vector3Edit::GetValue() const 41 | { 42 | return si::Vector3(x_edit_->value(), y_edit_->value(), z_edit_->value()); 43 | } 44 | 45 | void Vector3Edit::SetValue(const si::Vector3 &xyz) 46 | { 47 | x_edit_->blockSignals(true); 48 | y_edit_->blockSignals(true); 49 | z_edit_->blockSignals(true); 50 | 51 | x_edit_->setValue(xyz.x); 52 | y_edit_->setValue(xyz.y); 53 | z_edit_->setValue(xyz.z); 54 | 55 | x_edit_->blockSignals(false); 56 | y_edit_->blockSignals(false); 57 | z_edit_->blockSignals(false); 58 | } 59 | 60 | void Vector3Edit::internalChanged() 61 | { 62 | emit changed(si::Vector3(x_edit_->value(), y_edit_->value(), z_edit_->value())); 63 | } 64 | -------------------------------------------------------------------------------- /app/vector3edit.h: -------------------------------------------------------------------------------- 1 | #ifndef VECTOR3EDIT_H 2 | #define VECTOR3EDIT_H 3 | 4 | #include 5 | #include 6 | 7 | #include 8 | 9 | class Vector3Edit : public QWidget 10 | { 11 | Q_OBJECT 12 | public: 13 | explicit Vector3Edit(QWidget *parent = nullptr); 14 | 15 | si::Vector3 GetValue() const; 16 | void SetValue(const si::Vector3 &xyz); 17 | 18 | signals: 19 | void changed(const si::Vector3 &v); 20 | 21 | private: 22 | QDoubleSpinBox *x_edit_; 23 | QDoubleSpinBox *y_edit_; 24 | QDoubleSpinBox *z_edit_; 25 | 26 | private slots: 27 | void internalChanged(); 28 | 29 | }; 30 | 31 | #endif // VECTOR3EDIT_H 32 | -------------------------------------------------------------------------------- /app/viewer/mediapanel.cpp: -------------------------------------------------------------------------------- 1 | #include "mediapanel.h" 2 | 3 | #include 4 | 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | #include 11 | #include 12 | #include 13 | 14 | MediaPanel::MediaPanel(QWidget *parent) : 15 | Panel(parent) 16 | { 17 | int row = 0; 18 | 19 | auto wav_group = new QGroupBox(tr("Playback")); 20 | layout()->addWidget(wav_group, row, 0, 1, 2); 21 | 22 | auto preview_layout = new QVBoxLayout(wav_group); 23 | 24 | auto viewer_scroll = new QScrollArea(); 25 | viewer_scroll->setWidgetResizable(true); 26 | 27 | auto viewer_inner = new QWidget(); 28 | viewer_scroll->setWidget(viewer_inner); 29 | 30 | preview_layout->addWidget(viewer_scroll, 1); 31 | 32 | m_viewerLayout = new QVBoxLayout(viewer_inner); 33 | m_viewerLayout->setContentsMargins(0, 0, 0, 0); 34 | 35 | auto ctrl_layout = new QHBoxLayout(); 36 | preview_layout->addLayout(ctrl_layout); 37 | 38 | m_PlayheadSlider = new ClickableSlider(Qt::Horizontal); 39 | m_PlayheadSlider->setMinimum(0); 40 | connect(m_PlayheadSlider, &QSlider::sliderPressed, this, &MediaPanel::SliderPressed); 41 | connect(m_PlayheadSlider, &QSlider::sliderMoved, this, &MediaPanel::SliderMoved); 42 | connect(m_PlayheadSlider, &QSlider::sliderReleased, this, &MediaPanel::SliderReleased); 43 | ctrl_layout->addWidget(m_PlayheadSlider); 44 | 45 | m_PlayBtn = new QPushButton(tr("Play")); 46 | m_PlayBtn->setCheckable(true); 47 | m_PlayShortcut = new QShortcut(QKeySequence(Qt::Key_Space), this); 48 | connect(m_PlayBtn, &QPushButton::clicked, this, &MediaPanel::Play); 49 | connect(m_PlayShortcut, &QShortcut::activated, this, [this]() { Play(!IsPlaying()); }); 50 | ctrl_layout->addWidget(m_PlayBtn); 51 | 52 | //FinishLayout(); 53 | 54 | m_PlaybackTimer = new QTimer(this); 55 | m_PlaybackTimer->setInterval(10); 56 | connect(m_PlaybackTimer, &QTimer::timeout, this, &MediaPanel::TimerUpdate); 57 | 58 | m_audioSink = nullptr; 59 | 60 | m_audioDevice = new MediaAudioMixer(this); 61 | m_audioDevice->SetMediaInstances(&m_mediaInstances); 62 | } 63 | 64 | MediaPanel::~MediaPanel() 65 | { 66 | Close(); 67 | } 68 | 69 | qint64 MediaInstance::ReadAudio(char *data, qint64 maxlen) 70 | { 71 | if (m_AudioFlushed) { 72 | return 0; 73 | } 74 | 75 | qint64 dest_start = 0; 76 | 77 | if (m_virtualPosition < 0) { 78 | int64_t silent_bytes = SecondsToBytes(-m_virtualPosition); 79 | if (silent_bytes >= maxlen) { 80 | memset(data, 0, maxlen); 81 | m_virtualPosition += BytesToSeconds(maxlen); 82 | return maxlen; 83 | } else { 84 | memset(data, 0, silent_bytes); 85 | dest_start += silent_bytes; 86 | m_virtualPosition = 0; 87 | } 88 | } 89 | 90 | while (!m_AudioFlushed && m_AudioBuffer.size() < maxlen) { 91 | int ret = GetNextFrame(m_Frame); 92 | if (ret >= 0 || ret == AVERROR_EOF) { 93 | const uint8_t **in_data; 94 | int in_nb_samples; 95 | if (ret == AVERROR_EOF) { 96 | in_data = nullptr; 97 | in_nb_samples = 0; 98 | m_AudioFlushed = true; 99 | } else { 100 | in_data = const_cast(m_Frame->data); 101 | in_nb_samples = m_Frame->nb_samples; 102 | } 103 | 104 | int dst_nb_samples = av_rescale_rnd(swr_get_delay(m_SwrCtx, m_Stream->codecpar->sample_rate) + in_nb_samples, 105 | m_playbackFormat.sampleRate(), m_Stream->codecpar->sample_rate, AV_ROUND_UP); 106 | int data_size = dst_nb_samples * av_get_bytes_per_sample(m_AudioOutputSampleFmt) * m_playbackFormat.channelCount(); 107 | 108 | int old_sz = m_AudioBuffer.size(); 109 | m_AudioBuffer.resize(old_sz + data_size); 110 | 111 | uint8_t *out = reinterpret_cast(m_AudioBuffer.data() + old_sz); 112 | int converted = swr_convert(m_SwrCtx, &out, dst_nb_samples, in_data, in_nb_samples); 113 | 114 | data_size = converted * av_get_bytes_per_sample(m_AudioOutputSampleFmt) * m_playbackFormat.channelCount(); 115 | 116 | if (m_AudioBuffer.size() != old_sz + data_size) { 117 | m_AudioBuffer.resize(old_sz + data_size); 118 | } 119 | } else { 120 | break; 121 | } 122 | } 123 | 124 | if (!m_AudioBuffer.isEmpty()) { 125 | qint64 copy_len = std::min(maxlen - dest_start, qint64(m_AudioBuffer.size())); 126 | memcpy(data + dest_start, m_AudioBuffer.data(), copy_len); 127 | m_AudioBuffer = m_AudioBuffer.mid(copy_len); 128 | 129 | qint64 total = copy_len + dest_start; 130 | m_virtualPosition += BytesToSeconds(total); 131 | return total; 132 | } 133 | 134 | return 0; 135 | } 136 | 137 | int ReadData(void *opaque, uint8_t *buf, int buf_sz) 138 | { 139 | si::MemoryBuffer *m = static_cast(opaque); 140 | 141 | int s = m->ReadData(reinterpret_cast(buf), buf_sz); 142 | if (s == 0) { 143 | if (m->pos() == m->size()) { 144 | s = AVERROR_EOF; 145 | } 146 | } 147 | 148 | return s; 149 | } 150 | 151 | int64_t SeekData(void *opaque, int64_t offset, int whence) 152 | { 153 | si::MemoryBuffer *m = static_cast(opaque); 154 | 155 | if (whence == AVSEEK_SIZE) { 156 | return m->size(); 157 | } 158 | 159 | m->seek(offset); 160 | 161 | return m->pos(); 162 | } 163 | 164 | void MediaPanel::OnOpeningData(void *data) 165 | { 166 | OpenMediaInstance(static_cast(data)); 167 | 168 | float total_duration = 0.0f; 169 | for (auto it=m_mediaInstances.cbegin(); it!=m_mediaInstances.cend(); it++) { 170 | auto m = *it; 171 | total_duration = std::max(total_duration, m->GetDuration() + m->GetStartOffset()); 172 | } 173 | m_PlayheadSlider->setMaximum(GetSliderValueForSeconds(total_duration)); 174 | } 175 | 176 | void MediaPanel::OnClosingData(void *data) 177 | { 178 | Close(); 179 | } 180 | 181 | void MediaPanel::Close() 182 | { 183 | Play(false); 184 | 185 | qDeleteAll(m_mediaInstances); 186 | m_mediaInstances.clear(); 187 | 188 | m_PlayheadSlider->setValue(0); 189 | 190 | qDeleteAll(m_imgViewers); 191 | m_imgViewers.clear(); 192 | } 193 | 194 | QImage MediaInstance::GetVideoFrame(float t) 195 | { 196 | // Convert percent to duration seconds 197 | t -= m_startOffset; 198 | if (t < 0) { 199 | t = 0; 200 | } 201 | 202 | int64_t ts = SecondsToTimestamp(t); 203 | //int64_t second = std::ceil(flipped); 204 | 205 | AVFrame *using_frame = nullptr; 206 | for (auto it=m_FrameQueue.begin(); it!=m_FrameQueue.end(); it++) { 207 | auto next = it; 208 | next++; 209 | 210 | if ((*it)->pts == ts 211 | || (next != m_FrameQueue.end() && (*next)->pts > ts)) { 212 | using_frame = *it; 213 | break; 214 | } 215 | } 216 | 217 | if (!using_frame) { 218 | // Determine if the queue will eventually get this frame 219 | if (m_FrameQueue.empty() 220 | //|| ts > m_FrameQueue.back()->pts + second 221 | || ts < m_FrameQueue.front()->pts) { 222 | ClearQueue(); 223 | av_seek_frame(m_FmtCtx, m_Stream->index, ts, AVSEEK_FLAG_BACKWARD); 224 | } 225 | 226 | while (m_FrameQueue.empty() || m_FrameQueue.back()->pts < ts) { 227 | AVFrame *f = av_frame_alloc(); 228 | int ret = GetNextFrame(f); 229 | if (ret < 0) { 230 | av_frame_free(&f); 231 | break; 232 | } else { 233 | AVFrame *previous = nullptr; 234 | if (!m_FrameQueue.empty()) { 235 | previous = m_FrameQueue.back(); 236 | } 237 | 238 | m_FrameQueue.push_back(f); 239 | 240 | if (previous && f->pts > ts) { 241 | using_frame = previous; 242 | break; 243 | } else if (f->pts == ts) { 244 | using_frame = f; 245 | break; 246 | } 247 | } 248 | 249 | } 250 | } 251 | 252 | if (using_frame) { 253 | if (using_frame->pts != m_Frame->pts) { 254 | m_Frame->pts = using_frame->pts; 255 | 256 | sws_scale(m_SwsCtx, using_frame->data, using_frame->linesize, 0, using_frame->height, 257 | m_Frame->data, m_Frame->linesize); 258 | 259 | return QImage(m_Frame->data[0], m_Frame->width, m_Frame->height, m_Frame->linesize[0], QImage::Format_RGBA8888); 260 | } 261 | } 262 | 263 | return QImage(); 264 | } 265 | 266 | int MediaInstance::GetNextFrame(AVFrame *frame) 267 | { 268 | m_eof = false; 269 | int ret; 270 | av_frame_unref(frame); 271 | while ((ret = avcodec_receive_frame(m_CodecCtx, frame)) == AVERROR(EAGAIN)) { 272 | av_packet_unref(m_Packet); 273 | ret = av_read_frame(m_FmtCtx, m_Packet); 274 | if (ret < 0) { 275 | break; 276 | } 277 | 278 | if (m_Packet->stream_index == m_Stream->index) { 279 | ret = avcodec_send_packet(m_CodecCtx, m_Packet); 280 | if (ret < 0) { 281 | break; 282 | } 283 | } 284 | } 285 | 286 | if (ret == AVERROR_EOF) { 287 | m_eof = true; 288 | emit EndOfFile(); 289 | } 290 | 291 | return ret; 292 | } 293 | 294 | void MediaPanel::VideoUpdate(float t) 295 | { 296 | for (size_t i=0; icodec_type() == AVMEDIA_TYPE_VIDEO) { 300 | QImage img = m->GetVideoFrame(t); 301 | if (!img.isNull()) { 302 | auto v = m_imgViewers.at(i); 303 | 304 | if (v->property("vflip").toBool()) { 305 | img = img.flipped(Qt::Vertical); 306 | } 307 | 308 | v->setPixmap(QPixmap::fromImage(img)); 309 | } 310 | } 311 | } 312 | } 313 | 314 | float MediaPanel::GetSecondsFromSlider() const 315 | { 316 | return float(m_PlayheadSlider->value()) / SECONDS_INTERVAL; 317 | } 318 | 319 | void MediaPanel::SetSecondsOnSlider(float s) 320 | { 321 | m_PlayheadSlider->setValue(GetSliderValueForSeconds(s)); 322 | } 323 | 324 | int MediaPanel::GetSliderValueForSeconds(float s) 325 | { 326 | return s * SECONDS_INTERVAL; 327 | } 328 | 329 | void MediaPanel::OpenMediaInstance(si::Object *o) 330 | { 331 | switch (o->type()) { 332 | case si::MxOb::Presenter: 333 | for (auto it=o->GetChildren().cbegin(); it!=o->GetChildren().cend(); it++) { 334 | OpenMediaInstance(static_cast(*it)); 335 | } 336 | break; 337 | case si::MxOb::Video: 338 | case si::MxOb::Sound: 339 | case si::MxOb::Bitmap: 340 | { 341 | auto m = new MediaInstance(this); 342 | 343 | m->Open(o->ExtractToMemory()); 344 | m->SetStartOffset(float(o->time_offset_) * 0.001f); 345 | m->SetVolume(float(o->volume_) / si::MxOb::MAXIMUM_VOLUME); 346 | m->SetVirtualTime(0); 347 | 348 | m_mediaInstances.push_back(m); 349 | 350 | if (m->codec_type() == AVMEDIA_TYPE_VIDEO) { 351 | // Heuristic to flip phoneme flics vertically 352 | if (m_imgViewers.size() < m_mediaInstances.size()) { 353 | m_imgViewers.resize(m_mediaInstances.size()); 354 | } 355 | 356 | auto v = new QLabel(); 357 | v->setAlignment(Qt::AlignCenter); 358 | v->setContextMenuPolicy(Qt::CustomContextMenu); 359 | v->setProperty("vflip", (o->name().find("_Pho_") != std::string::npos)); 360 | connect(v, &QWidget::customContextMenuRequested, this, &MediaPanel::LabelContextMenuTriggered); 361 | m_viewerLayout->addWidget(v); 362 | m_imgViewers[m_mediaInstances.size()-1] = v; 363 | 364 | VideoUpdate(0); 365 | } 366 | break; 367 | } 368 | case si::MxOb::Null: 369 | case si::MxOb::World: 370 | case si::MxOb::Event: 371 | case si::MxOb::Animation: 372 | case si::MxOb::Object: 373 | case si::MxOb::TYPE_COUNT: 374 | // Do nothing 375 | break; 376 | } 377 | } 378 | 379 | void MediaPanel::Play(bool e) 380 | { 381 | if (e) { 382 | bool has_video = false; 383 | bool has_audio = false; 384 | 385 | if (m_PlayheadSlider->value() == m_PlayheadSlider->maximum()) { 386 | m_PlayheadSlider->setValue(0); 387 | SliderMoved(0); 388 | } 389 | 390 | m_PlaybackOffset = GetSecondsFromSlider(); 391 | 392 | auto output_dev = QAudioDevice(QMediaDevices::defaultAudioOutput()); 393 | auto fmt = output_dev.preferredFormat(); 394 | 395 | // Require float output (makes our lives easier) 396 | fmt.setSampleFormat(QAudioFormat::Float); 397 | 398 | for (size_t i = 0; i < m_mediaInstances.size(); i++) { 399 | auto m = m_mediaInstances[i]; 400 | 401 | m->ResetEOF(); 402 | 403 | if (m->codec_type() == AVMEDIA_TYPE_VIDEO) { 404 | has_video = true; 405 | } else if (m->codec_type() == AVMEDIA_TYPE_AUDIO) { 406 | if (m_PlaybackOffset < (m->GetDuration() + m->GetStartOffset())) { 407 | if (m->SetUpResampleContext(fmt)) { 408 | // auto out = new QAudioSink(output_dev, fmt, this); 409 | // out->setVolume(m->GetVolume()); 410 | // out->start(m); 411 | // m_audioSinks.push_back(out); 412 | has_audio = true; 413 | } 414 | } else { 415 | m->ResetEOF(true); 416 | } 417 | } 418 | } 419 | 420 | if (has_audio) { 421 | m_audioDevice->SetAudioFormat(fmt); 422 | m_audioDevice->open(QIODevice::ReadOnly); 423 | m_audioDevice->SeekInSeconds(GetSecondsFromSlider()); 424 | 425 | m_audioSink = new QAudioSink(output_dev, fmt, this); 426 | m_audioSink->start(m_audioDevice); 427 | } 428 | 429 | m_PlaybackStart = QDateTime::currentMSecsSinceEpoch(); 430 | m_PlaybackTimer->start(); 431 | m_PlayBtn->setText("Pause"); 432 | } else { 433 | m_PlayBtn->setText("Play"); 434 | m_PlaybackTimer->stop(); 435 | 436 | if (m_audioSink) { 437 | m_audioDevice->close(); 438 | m_audioSink->stop(); 439 | m_audioSink->deleteLater(); 440 | m_audioSink = nullptr; 441 | } 442 | } 443 | m_PlayBtn->setChecked(e); 444 | } 445 | 446 | void MediaPanel::TimerUpdate() 447 | { 448 | bool all_eof = true; 449 | 450 | // Don't set slider if slider pressed 451 | float now = float(QDateTime::currentMSecsSinceEpoch() - m_PlaybackStart) * 0.001f; 452 | now += m_PlaybackOffset; 453 | SetSecondsOnSlider(now); 454 | 455 | for (size_t i=0; iIsEndOfFile()) { 459 | all_eof = false; 460 | } 461 | 462 | if (m->codec_type() == AVMEDIA_TYPE_VIDEO) { 463 | VideoUpdate(now); 464 | } else if (m->codec_type() == AVMEDIA_TYPE_AUDIO) { 465 | // Do nothing yet 466 | } 467 | } 468 | 469 | if (all_eof) { 470 | Play(false); 471 | m_PlayheadSlider->setValue(m_PlayheadSlider->maximum()); 472 | } 473 | } 474 | 475 | void MediaPanel::UpdateVideo() 476 | { 477 | SliderMoved(m_PlayheadSlider->value()); 478 | } 479 | 480 | void MediaPanel::SliderPressed() 481 | { 482 | if (IsPlaying()) { 483 | Play(false); 484 | } 485 | } 486 | 487 | void MediaPanel::SliderMoved(int i) 488 | { 489 | float f = GetSecondsFromSlider(); 490 | m_PlaybackOffset = f; 491 | m_PlaybackStart = QDateTime::currentMSecsSinceEpoch(); 492 | 493 | for (auto it=m_mediaInstances.cbegin(); it!=m_mediaInstances.cend(); it++) { 494 | auto m = *it; 495 | if (m->codec_type() == AVMEDIA_TYPE_VIDEO) { 496 | VideoUpdate(f); 497 | } else if (m->codec_type() == AVMEDIA_TYPE_AUDIO) { 498 | m->Seek(f); 499 | } 500 | } 501 | } 502 | 503 | void MediaPanel::SliderReleased() 504 | { 505 | } 506 | 507 | void MediaPanel::LabelContextMenuTriggered(const QPoint &pos) 508 | { 509 | QMenu m(this); 510 | 511 | QObject *s = sender(); 512 | 513 | auto vert_flip = m.addAction(tr("Flip Vertically")); 514 | vert_flip->setCheckable(true); 515 | vert_flip->setChecked(s->property("vflip").toBool()); 516 | connect(vert_flip, &QAction::triggered, this, [this, s](bool e){ 517 | s->setProperty("vflip", e); 518 | UpdateVideo(); 519 | }); 520 | 521 | m.exec(static_cast(sender())->mapToGlobal(pos)); 522 | } 523 | 524 | ClickableSlider::ClickableSlider(Qt::Orientation orientation, QWidget *parent) : 525 | QSlider(orientation, parent) 526 | { 527 | } 528 | 529 | ClickableSlider::ClickableSlider(QWidget *parent) : 530 | QSlider(parent) 531 | { 532 | } 533 | 534 | void ClickableSlider::mousePressEvent(QMouseEvent *e) 535 | { 536 | int v = double(e->pos().x()) / double(width()) * this->maximum(); 537 | setValue(v); 538 | emit sliderMoved(v); 539 | 540 | QSlider::mousePressEvent(e); 541 | } 542 | 543 | MediaInstance::MediaInstance(QObject *parent) : 544 | QObject(parent), 545 | m_FmtCtx(nullptr), 546 | m_Packet(nullptr), 547 | m_CodecCtx(nullptr), 548 | m_Stream(nullptr), 549 | m_Frame(nullptr), 550 | m_SwsCtx(nullptr), 551 | m_SwrCtx(nullptr), 552 | m_IoCtx(nullptr), 553 | m_startOffset(0.0f) 554 | { 555 | } 556 | 557 | void MediaInstance::Open(const si::bytearray &buf) 558 | { 559 | static const size_t buf_sz = 4096; 560 | 561 | m_Data = buf; 562 | 563 | m_IoCtx = avio_alloc_context( 564 | (unsigned char *) av_malloc(buf_sz), 565 | buf_sz, 566 | 0, 567 | &m_Data, 568 | ReadData, 569 | nullptr, 570 | SeekData 571 | ); 572 | 573 | m_FmtCtx = avformat_alloc_context(); 574 | m_FmtCtx->pb = m_IoCtx; 575 | m_FmtCtx->flags |= AVFMT_FLAG_CUSTOM_IO; 576 | 577 | if (avformat_open_input(&m_FmtCtx, "", nullptr, nullptr) < 0) { 578 | qCritical() << "Failed to open format context"; 579 | Close(); 580 | return; 581 | } 582 | 583 | if (avformat_find_stream_info(m_FmtCtx, nullptr) < 0) { 584 | qCritical() << "Failed to find stream info"; 585 | Close(); 586 | return; 587 | } 588 | 589 | if (m_FmtCtx->nb_streams == 0) { 590 | qWarning() << "No streams in file"; 591 | Close(); 592 | return; 593 | } 594 | 595 | m_Stream = m_FmtCtx->streams[0]; 596 | 597 | m_duration = m_Stream->duration; 598 | if (m_Stream->codecpar->codec_id == AV_CODEC_ID_FLIC) { 599 | // FFmpeg can't retrieve the FLIC duration, but we can 600 | si::FLIC *flic = (si::FLIC *) buf.data(); 601 | m_duration = flic->frames; 602 | } 603 | 604 | const AVCodec *decoder = avcodec_find_decoder(m_Stream->codecpar->codec_id); 605 | if (!decoder) { 606 | qWarning() << "Failed to find decoder for type" << avcodec_get_name(m_Stream->codecpar->codec_id); 607 | Close(); 608 | return; 609 | } 610 | 611 | m_CodecCtx = avcodec_alloc_context3(decoder); 612 | avcodec_parameters_to_context(m_CodecCtx, m_Stream->codecpar); 613 | avcodec_open2(m_CodecCtx, decoder, nullptr); 614 | 615 | m_Packet = av_packet_alloc(); 616 | m_Frame = av_frame_alloc(); 617 | 618 | if (m_Stream->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) { 619 | const AVPixelFormat dest = AV_PIX_FMT_RGBA; 620 | m_SwsCtx = sws_getContext(m_Stream->codecpar->width, 621 | m_Stream->codecpar->height, 622 | static_cast(m_Stream->codecpar->format), 623 | m_Stream->codecpar->width, 624 | m_Stream->codecpar->height, 625 | dest, 626 | 0, 627 | nullptr, 628 | nullptr, 629 | nullptr); 630 | 631 | m_Frame->width = m_Stream->codecpar->width; 632 | m_Frame->height = m_Stream->codecpar->height; 633 | m_Frame->format = dest; 634 | av_frame_get_buffer(m_Frame, 0); 635 | } 636 | } 637 | 638 | void MediaInstance::Close() 639 | { 640 | if (m_CodecCtx) { 641 | avcodec_free_context(&m_CodecCtx); 642 | } 643 | 644 | if (m_SwsCtx) { 645 | sws_freeContext(m_SwsCtx); 646 | m_SwsCtx = nullptr; 647 | } 648 | 649 | if (m_SwrCtx) { 650 | swr_free(&m_SwrCtx); 651 | } 652 | 653 | if (m_Packet) { 654 | av_packet_free(&m_Packet); 655 | } 656 | 657 | if (m_Frame) { 658 | av_frame_free(&m_Frame); 659 | } 660 | 661 | ClearQueue(); 662 | 663 | if (m_FmtCtx) { 664 | avformat_free_context(m_FmtCtx); 665 | m_FmtCtx = nullptr; 666 | } 667 | 668 | if (m_IoCtx) { 669 | avio_context_free(&m_IoCtx); 670 | m_IoCtx = nullptr; 671 | } 672 | 673 | m_Stream = nullptr; 674 | 675 | m_Data.Close(); 676 | } 677 | 678 | bool MediaInstance::SetUpResampleContext(const QAudioFormat &fmt) 679 | { 680 | if (m_SwrCtx) { 681 | swr_free(&m_SwrCtx); 682 | m_SwrCtx = nullptr; 683 | } 684 | 685 | AVSampleFormat smp_fmt = AV_SAMPLE_FMT_S16; 686 | switch (fmt.sampleFormat()) { 687 | default: 688 | case QAudioFormat::Unknown: 689 | break; 690 | case QAudioFormat::Int16: 691 | smp_fmt = AV_SAMPLE_FMT_S16; 692 | break; 693 | case QAudioFormat::Int32: 694 | smp_fmt = AV_SAMPLE_FMT_S32; 695 | break; 696 | case QAudioFormat::UInt8: 697 | smp_fmt = AV_SAMPLE_FMT_U8; 698 | break; 699 | case QAudioFormat::Float: 700 | smp_fmt = AV_SAMPLE_FMT_FLT; 701 | break; 702 | } 703 | 704 | m_playbackFormat = fmt; 705 | m_AudioOutputSampleFmt = smp_fmt; 706 | 707 | #if LIBSWRESAMPLE_VERSION_INT >= AV_VERSION_INT(4, 7, 0) 708 | AVChannelLayout out; 709 | av_channel_layout_default(&out, fmt.channelCount()); 710 | 711 | int r = swr_alloc_set_opts2(&m_SwrCtx, 712 | &out, 713 | smp_fmt, 714 | fmt.sampleRate(), 715 | &m_Stream->codecpar->ch_layout, 716 | static_cast(m_Stream->codecpar->format), 717 | m_Stream->codecpar->sample_rate, 718 | 0, nullptr); 719 | if (r < 0) { 720 | qCritical() << "Failed to alloc swr ctx:" << r; 721 | return false; 722 | } 723 | #else 724 | m_SwrCtx = swr_alloc_set_opts(nullptr, 725 | av_get_default_channel_layout(fmt.channelCount()), 726 | smp_fmt, 727 | fmt.sampleRate(), 728 | av_get_default_channel_layout(m_Stream->codecpar->channels), 729 | static_cast(m_Stream->codecpar->format), 730 | m_Stream->codecpar->sample_rate, 731 | 0, nullptr); 732 | if (!m_SwrCtx) { 733 | qCritical() << "Failed to alloc swr ctx"; 734 | return false; 735 | } 736 | #endif 737 | 738 | if (swr_init(m_SwrCtx) < 0) { 739 | qCritical() << "Failed to init swr ctx"; 740 | return false; 741 | } 742 | 743 | m_AudioFlushed = false; 744 | m_AudioBuffer.clear(); 745 | 746 | return true; 747 | } 748 | 749 | void MediaInstance::Seek(float seconds) 750 | { 751 | SetVirtualTime(seconds); 752 | av_seek_frame(m_FmtCtx, m_Stream->index, SecondsToTimestamp(std::max(0.0f, m_virtualPosition)), AVSEEK_FLAG_BACKWARD); 753 | } 754 | 755 | void MediaInstance::ClearQueue() 756 | { 757 | while (!m_FrameQueue.empty()) { 758 | av_frame_free(&m_FrameQueue.front()); 759 | m_FrameQueue.pop_front(); 760 | } 761 | } 762 | 763 | int64_t MediaInstance::SecondsToTimestamp(float t) const 764 | { 765 | return t / (float(m_Stream->time_base.num) / float(m_Stream->time_base.den)); 766 | } 767 | 768 | float MediaInstance::TimestampToSeconds(int64_t t) const 769 | { 770 | return t * (float(m_Stream->time_base.num) / float(m_Stream->time_base.den)); 771 | } 772 | 773 | int64_t MediaInstance::SecondsToBytes(float t) const 774 | { 775 | return std::floor(t * m_playbackFormat.sampleRate()) * m_playbackFormat.bytesPerFrame(); 776 | } 777 | 778 | float MediaInstance::BytesToSeconds(int64_t t) 779 | { 780 | return float(t / m_playbackFormat.bytesPerFrame()) / m_playbackFormat.sampleRate(); 781 | } 782 | 783 | void MediaInstance::SetVirtualTime(float f) 784 | { 785 | m_virtualPosition = f - m_startOffset; 786 | } 787 | 788 | MediaAudioMixer::MediaAudioMixer(QObject *parent) : 789 | QIODevice(parent) 790 | { 791 | m_mediaInstances = nullptr; 792 | } 793 | 794 | void MediaAudioMixer::SeekInSeconds(float f) 795 | { 796 | seek(m_audioFormat.bytesForDuration(f * 1000000)); 797 | } 798 | 799 | qint64 MediaAudioMixer::readData(char *data, qint64 maxSize) 800 | { 801 | if (!m_mediaInstances) { 802 | return 0; 803 | } 804 | 805 | // Media instances should be set to same sample rate and channel count as output, but we may need to convert format 806 | float *output = reinterpret_cast(data); 807 | 808 | qint64 maxSamples = maxSize / m_audioFormat.bytesPerSample(); 809 | 810 | float *tmp = new float[maxSamples]; 811 | 812 | qint64 touchedBytes = 0; 813 | 814 | for (auto it = m_mediaInstances->cbegin(); it != m_mediaInstances->cend(); it++) { 815 | auto m = *it; 816 | 817 | if (m->codec_type() == AVMEDIA_TYPE_AUDIO) { 818 | qint64 thisRead = m->ReadAudio(reinterpret_cast(tmp), maxSize); 819 | if (thisRead > touchedBytes) { 820 | memset(data + touchedBytes, 0, thisRead - touchedBytes); 821 | touchedBytes = thisRead; 822 | } 823 | 824 | // TODO: Optimize with SSE and NEON 825 | qint64 thisSamples = thisRead / m_audioFormat.bytesPerSample(); 826 | for (qint64 j = 0; j < thisSamples; j++) { 827 | output[j] += tmp[j] * m->GetVolume(); 828 | } 829 | } 830 | } 831 | 832 | delete [] tmp; 833 | 834 | return touchedBytes; 835 | } 836 | 837 | qint64 MediaAudioMixer::writeData(const char *data, qint64 maxSize) 838 | { 839 | return -1; 840 | } 841 | 842 | qint64 MediaAudioMixer::size() const 843 | { 844 | if (!m_mediaInstances) { 845 | return 0; 846 | } 847 | 848 | // Calculate maximum duration in seconds 849 | float maxLength = 0; 850 | for (auto it = m_mediaInstances->cbegin(); it != m_mediaInstances->cend(); it++) { 851 | auto m = *it; 852 | maxLength = qMax(maxLength, m->GetDuration() + m->GetStartOffset()); 853 | } 854 | 855 | // Convert seconds to bytes in the output format 856 | return m_audioFormat.bytesForDuration(maxLength * 1000000); 857 | } 858 | -------------------------------------------------------------------------------- /app/viewer/mediapanel.h: -------------------------------------------------------------------------------- 1 | #ifndef MEDIAPANEL_H 2 | #define MEDIAPANEL_H 3 | 4 | extern "C" { 5 | #include 6 | #include 7 | #include 8 | #include 9 | } 10 | 11 | #include 12 | #include 13 | 14 | #include 15 | #include 16 | #include 17 | #include 18 | #include 19 | #include 20 | #include 21 | #include 22 | #include 23 | #include "panel.h" 24 | 25 | class MediaInstance : public QObject 26 | { 27 | Q_OBJECT 28 | public: 29 | MediaInstance(QObject *parent = nullptr); 30 | 31 | void Open(const si::bytearray &buf); 32 | 33 | void Close(); 34 | 35 | AVMediaType codec_type() const 36 | { 37 | return m_Stream ? m_Stream->codecpar->codec_type : AVMEDIA_TYPE_UNKNOWN; 38 | } 39 | 40 | bool SetUpResampleContext(const QAudioFormat &fmt); 41 | 42 | void Seek(float seconds); 43 | 44 | int GetNextFrame(AVFrame *frame); 45 | 46 | qint64 ReadAudio(char *data, qint64 maxlen); 47 | 48 | QImage GetVideoFrame(float f); 49 | 50 | float GetTime() const 51 | { 52 | return float(m_Frame->pts) / m_duration; 53 | } 54 | 55 | float GetDuration() const 56 | { 57 | return TimestampToSeconds(m_duration); 58 | } 59 | 60 | int64_t SecondsToTimestamp(float t) const; 61 | float TimestampToSeconds(int64_t t) const; 62 | int64_t SecondsToBytes(float t) const; 63 | float BytesToSeconds(int64_t t); 64 | 65 | bool IsEndOfFile() 66 | { 67 | return m_eof; 68 | } 69 | 70 | void ResetEOF(bool val = false) 71 | { 72 | m_eof = val; 73 | } 74 | 75 | float GetStartOffset() const { return m_startOffset; } 76 | void SetStartOffset(const float &m) { m_startOffset = m; } 77 | 78 | void SetVirtualTime(float f); 79 | 80 | float GetVolume() const { return m_volume; } 81 | void SetVolume(float v) { m_volume = v; } 82 | 83 | signals: 84 | void EndOfFile(); 85 | 86 | private: 87 | void ClearQueue(); 88 | 89 | AVFormatContext *m_FmtCtx; 90 | AVStream *m_Stream; 91 | std::list m_FrameQueue; 92 | 93 | AVPacket *m_Packet; 94 | AVFrame *m_Frame; 95 | 96 | AVCodecContext *m_CodecCtx; 97 | 98 | SwsContext *m_SwsCtx; 99 | SwrContext *m_SwrCtx; 100 | 101 | bool m_AudioFlushed; 102 | QByteArray m_AudioBuffer; 103 | 104 | AVIOContext *m_IoCtx; 105 | 106 | si::MemoryBuffer m_Data; 107 | 108 | QAudioFormat m_playbackFormat; 109 | AVSampleFormat m_AudioOutputSampleFmt; 110 | 111 | float m_startOffset; 112 | 113 | bool m_eof; 114 | 115 | int64_t m_duration; 116 | 117 | float m_virtualPosition; 118 | 119 | float m_volume; 120 | 121 | }; 122 | 123 | class MediaAudioMixer : public QIODevice 124 | { 125 | Q_OBJECT 126 | public: 127 | MediaAudioMixer(QObject *parent = nullptr); 128 | 129 | void SetMediaInstances(std::vector *mi) 130 | { 131 | m_mediaInstances = mi; 132 | } 133 | 134 | void SetAudioFormat(const QAudioFormat &fmt) 135 | { 136 | m_audioFormat = fmt; 137 | } 138 | 139 | void SeekInSeconds(float f); 140 | 141 | protected: 142 | virtual qint64 readData(char *data, qint64 maxSize) override; 143 | virtual qint64 writeData(const char *data, qint64 maxSize) override; 144 | virtual qint64 size() const override; 145 | 146 | private: 147 | std::vector *m_mediaInstances; 148 | QAudioFormat m_audioFormat; 149 | }; 150 | 151 | class MediaPanel : public Panel 152 | { 153 | Q_OBJECT 154 | public: 155 | MediaPanel(QWidget *parent = nullptr); 156 | virtual ~MediaPanel() override; 157 | 158 | bool IsPlaying() const 159 | { 160 | return m_PlaybackTimer->isActive(); 161 | } 162 | 163 | const std::vector &GetMediaInstances() const 164 | { 165 | return m_mediaInstances; 166 | } 167 | 168 | protected: 169 | virtual void OnOpeningData(void *data) override; 170 | virtual void OnClosingData(void *data) override; 171 | 172 | private: 173 | void Close(); 174 | 175 | void VideoUpdate(float t); 176 | 177 | static const int SECONDS_INTERVAL = 10; 178 | float GetSecondsFromSlider() const; 179 | void SetSecondsOnSlider(float s); 180 | static int GetSliderValueForSeconds(float s); 181 | 182 | void OpenMediaInstance(si::Object *o); 183 | 184 | std::vector m_imgViewers; 185 | std::vector m_mediaInstances; 186 | 187 | QAudioSink *m_audioSink; 188 | MediaAudioMixer *m_audioDevice; 189 | 190 | QSlider *m_PlayheadSlider; 191 | QPushButton *m_PlayBtn; 192 | QShortcut *m_PlayShortcut; 193 | QTimer *m_PlaybackTimer; 194 | qint64 m_PlaybackStart; 195 | float m_PlaybackOffset; 196 | QVBoxLayout *m_viewerLayout; 197 | 198 | private slots: 199 | void Play(bool e); 200 | 201 | void TimerUpdate(); 202 | 203 | void UpdateVideo(); 204 | 205 | void SliderPressed(); 206 | void SliderMoved(int i); 207 | void SliderReleased(); 208 | 209 | void LabelContextMenuTriggered(const QPoint &pos); 210 | 211 | }; 212 | 213 | class ClickableSlider : public QSlider 214 | { 215 | Q_OBJECT 216 | public: 217 | ClickableSlider(Qt::Orientation orientation, QWidget *parent = nullptr); 218 | ClickableSlider(QWidget *parent = nullptr); 219 | 220 | protected: 221 | virtual void mousePressEvent(QMouseEvent *e) override; 222 | 223 | }; 224 | 225 | #endif // MEDIAPANEL_H 226 | -------------------------------------------------------------------------------- /cmake/FindFFMPEG.cmake: -------------------------------------------------------------------------------- 1 | #[==[ 2 | Provides the following variables: 3 | 4 | * `FFMPEG_INCLUDE_DIRS`: Include directories necessary to use FFMPEG. 5 | * `FFMPEG_LIBRARIES`: Libraries necessary to use FFMPEG. Note that this only 6 | includes libraries for the components requested. 7 | * `FFMPEG_VERSION`: The version of FFMPEG found. 8 | 9 | The following components are supported: 10 | 11 | * `avcodec` 12 | * `avdevice` 13 | * `avfilter` 14 | * `avformat` 15 | * `avresample` 16 | * `avutil` 17 | * `swresample` 18 | * `swscale` 19 | 20 | For each component, the following are provided: 21 | 22 | * `FFMPEG__FOUND`: Libraries for the component. 23 | * `FFMPEG__INCLUDE_DIRS`: Include directories for 24 | the component. 25 | * `FFMPEG__LIBRARIES`: Libraries for the component. 26 | * `FFMPEG::`: A target to use with `target_link_libraries`. 27 | 28 | Note that only components requested with `COMPONENTS` or `OPTIONAL_COMPONENTS` 29 | are guaranteed to set these variables or provide targets. 30 | #]==] 31 | 32 | function (_ffmpeg_find component headername) 33 | find_path("FFMPEG_${component}_INCLUDE_DIR" 34 | NAMES 35 | "lib${component}/${headername}" 36 | PATHS 37 | "${FFMPEG_ROOT}/include" 38 | ~/Library/Frameworks 39 | /Library/Frameworks 40 | /usr/local/include 41 | /usr/include 42 | /sw/include # Fink 43 | /opt/local/include # DarwinPorts 44 | /opt/csw/include # Blastwave 45 | /opt/include 46 | /usr/freeware/include 47 | PATH_SUFFIXES 48 | ffmpeg 49 | DOC "FFMPEG's ${component} include directory") 50 | mark_as_advanced("FFMPEG_${component}_INCLUDE_DIR") 51 | 52 | # On Windows, static FFMPEG is sometimes built as `lib.a`. 53 | if (WIN32) 54 | list(APPEND CMAKE_FIND_LIBRARY_SUFFIXES ".a" ".lib") 55 | list(APPEND CMAKE_FIND_LIBRARY_PREFIXES "" "lib") 56 | endif () 57 | 58 | find_library("FFMPEG_${component}_LIBRARY" 59 | NAMES 60 | "${component}" 61 | PATHS 62 | "${FFMPEG_ROOT}/lib" 63 | ~/Library/Frameworks 64 | /Library/Frameworks 65 | /usr/local/lib 66 | /usr/local/lib64 67 | /usr/lib 68 | /usr/lib64 69 | /sw/lib 70 | /opt/local/lib 71 | /opt/csw/lib 72 | /opt/lib 73 | /usr/freeware/lib64 74 | "${FFMPEG_ROOT}/bin" 75 | DOC "FFMPEG's ${component} library") 76 | mark_as_advanced("FFMPEG_${component}_LIBRARY") 77 | 78 | if (FFMPEG_${component}_LIBRARY AND FFMPEG_${component}_INCLUDE_DIR) 79 | set(_deps_found TRUE) 80 | set(_deps_link) 81 | foreach (_ffmpeg_dep IN LISTS ARGN) 82 | if (TARGET "FFMPEG::${_ffmpeg_dep}") 83 | list(APPEND _deps_link "FFMPEG::${_ffmpeg_dep}") 84 | else () 85 | set(_deps_found FALSE) 86 | endif () 87 | endforeach () 88 | if (_deps_found) 89 | add_library("FFMPEG::${component}" UNKNOWN IMPORTED) 90 | set_target_properties("FFMPEG::${component}" PROPERTIES 91 | IMPORTED_LOCATION "${FFMPEG_${component}_LIBRARY}" 92 | INTERFACE_INCLUDE_DIRECTORIES "${FFMPEG_${component}_INCLUDE_DIR}" 93 | IMPORTED_LINK_INTERFACE_LIBRARIES "${_deps_link}") 94 | set("FFMPEG_${component}_FOUND" 1 95 | PARENT_SCOPE) 96 | 97 | set(version_header_path "${FFMPEG_${component}_INCLUDE_DIR}/lib${component}/version.h") 98 | if (EXISTS "${version_header_path}") 99 | string(TOUPPER "${component}" component_upper) 100 | file(STRINGS "${version_header_path}" version 101 | REGEX "#define *LIB${component_upper}_VERSION_(MAJOR|MINOR|MICRO) ") 102 | string(REGEX REPLACE ".*_MAJOR *\([0-9]*\).*" "\\1" major "${version}") 103 | string(REGEX REPLACE ".*_MINOR *\([0-9]*\).*" "\\1" minor "${version}") 104 | string(REGEX REPLACE ".*_MICRO *\([0-9]*\).*" "\\1" micro "${version}") 105 | if (NOT major STREQUAL "" AND 106 | NOT minor STREQUAL "" AND 107 | NOT micro STREQUAL "") 108 | set("FFMPEG_${component}_VERSION" "${major}.${minor}.${micro}" 109 | PARENT_SCOPE) 110 | endif () 111 | endif () 112 | else () 113 | set("FFMPEG_${component}_FOUND" 0 114 | PARENT_SCOPE) 115 | set(what) 116 | if (NOT FFMPEG_${component}_LIBRARY) 117 | set(what "library") 118 | endif () 119 | if (NOT FFMPEG_${component}_INCLUDE_DIR) 120 | if (what) 121 | string(APPEND what " or headers") 122 | else () 123 | set(what "headers") 124 | endif () 125 | endif () 126 | set("FFMPEG_${component}_NOT_FOUND_MESSAGE" 127 | "Could not find the ${what} for ${component}." 128 | PARENT_SCOPE) 129 | endif () 130 | endif () 131 | endfunction () 132 | 133 | _ffmpeg_find(avutil avutil.h) 134 | _ffmpeg_find(avresample avresample.h 135 | avutil) 136 | _ffmpeg_find(swresample swresample.h 137 | avutil) 138 | _ffmpeg_find(swscale swscale.h 139 | avutil) 140 | _ffmpeg_find(avcodec avcodec.h 141 | avutil) 142 | _ffmpeg_find(avformat avformat.h 143 | avcodec avutil) 144 | _ffmpeg_find(avfilter avfilter.h 145 | avutil) 146 | _ffmpeg_find(avdevice avdevice.h 147 | avformat avutil) 148 | 149 | if (TARGET FFMPEG::avutil) 150 | set(_ffmpeg_version_header_path "${FFMPEG_avutil_INCLUDE_DIR}/libavutil/ffversion.h") 151 | if (EXISTS "${_ffmpeg_version_header_path}") 152 | file(STRINGS "${_ffmpeg_version_header_path}" _ffmpeg_version 153 | REGEX "FFMPEG_VERSION") 154 | string(REGEX REPLACE ".*\"n?\(.*\)\"" "\\1" FFMPEG_VERSION "${_ffmpeg_version}") 155 | unset(_ffmpeg_version) 156 | else () 157 | set(FFMPEG_VERSION FFMPEG_VERSION-NOTFOUND) 158 | endif () 159 | unset(_ffmpeg_version_header_path) 160 | endif () 161 | 162 | set(FFMPEG_INCLUDE_DIRS) 163 | set(FFMPEG_LIBRARIES) 164 | set(_ffmpeg_required_vars) 165 | foreach (_ffmpeg_component IN LISTS FFMPEG_FIND_COMPONENTS) 166 | if (TARGET "FFMPEG::${_ffmpeg_component}") 167 | set(FFMPEG_${_ffmpeg_component}_INCLUDE_DIRS 168 | "${FFMPEG_${_ffmpeg_component}_INCLUDE_DIR}") 169 | set(FFMPEG_${_ffmpeg_component}_LIBRARIES 170 | "${FFMPEG_${_ffmpeg_component}_LIBRARY}") 171 | list(APPEND FFMPEG_INCLUDE_DIRS 172 | "${FFMPEG_${_ffmpeg_component}_INCLUDE_DIRS}") 173 | list(APPEND FFMPEG_LIBRARIES 174 | "${FFMPEG_${_ffmpeg_component}_LIBRARIES}") 175 | if (FFMEG_FIND_REQUIRED_${_ffmpeg_component}) 176 | list(APPEND _ffmpeg_required_vars 177 | "FFMPEG_${_ffmpeg_required_vars}_INCLUDE_DIRS" 178 | "FFMPEG_${_ffmpeg_required_vars}_LIBRARIES") 179 | endif () 180 | endif () 181 | endforeach () 182 | unset(_ffmpeg_component) 183 | 184 | if (FFMPEG_INCLUDE_DIRS) 185 | list(REMOVE_DUPLICATES FFMPEG_INCLUDE_DIRS) 186 | endif () 187 | 188 | include(FindPackageHandleStandardArgs) 189 | find_package_handle_standard_args(FFMPEG 190 | REQUIRED_VARS FFMPEG_INCLUDE_DIRS FFMPEG_LIBRARIES ${_ffmpeg_required_vars} 191 | VERSION_VAR FFMPEG_VERSION 192 | HANDLE_COMPONENTS) 193 | unset(_ffmpeg_required_vars) 194 | -------------------------------------------------------------------------------- /lib/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | option(LIBWEAVER_BUILD_DOXYGEN "Build Doxygen documentation" OFF) 2 | 3 | set(LIBWEAVER_SOURCES 4 | core.cpp 5 | core.h 6 | file.cpp 7 | file.h 8 | info.h 9 | interleaf.cpp 10 | interleaf.h 11 | object.cpp 12 | object.h 13 | sitypes.cpp 14 | sitypes.h 15 | types.h 16 | util.h 17 | ) 18 | 19 | add_library(libweaver SHARED 20 | ${LIBWEAVER_SOURCES} 21 | ) 22 | 23 | target_compile_definitions(libweaver PRIVATE LIBWEAVER_LIBRARY) 24 | if (NOT MSVC) 25 | target_compile_options(libweaver PRIVATE -Werror -Wall -Wextra -Wno-unused-parameter) 26 | endif() 27 | set_target_properties(libweaver PROPERTIES 28 | CXX_STANDARD 98 29 | CXX_STANDARD_REQUIRED ON 30 | PREFIX "" 31 | ) 32 | 33 | if(LIBWEAVER_BUILD_DOXYGEN) 34 | find_package(Doxygen) 35 | set(DOXYGEN_PROJECT_NAME "libweaver") 36 | set(DOXYGEN_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/docs") 37 | set(DOXYGEN_EXTRACT_ALL "YES") 38 | set(DOXYGEN_EXTRACT_PRIVATE "YES") 39 | doxygen_add_docs(docs ALL ${LIBWEAVER_SOURCES}) 40 | endif() 41 | -------------------------------------------------------------------------------- /lib/core.cpp: -------------------------------------------------------------------------------- 1 | #include "core.h" 2 | 3 | #include 4 | 5 | namespace si { 6 | 7 | Core::Core() 8 | { 9 | parent_ = NULL; 10 | } 11 | 12 | Core::~Core() 13 | { 14 | // Remove from parent if applicable 15 | if (parent_) { 16 | parent_->RemoveChild(this); 17 | } 18 | 19 | DeleteChildren(); 20 | } 21 | 22 | bool Core::FindParent(Core *p) const 23 | { 24 | Core *parent = this->parent_; 25 | while (parent != NULL) { 26 | if (parent == p) { 27 | return true; 28 | } else { 29 | parent = parent->parent_; 30 | } 31 | } 32 | 33 | return false; 34 | } 35 | 36 | void Core::AppendChild(Core *chunk) 37 | { 38 | InsertChild(children_.size(), chunk); 39 | } 40 | 41 | bool Core::RemoveChild(Core *chunk) 42 | { 43 | // If this chunk's parent is not this, return 44 | if (chunk->parent_ != this) { 45 | return false; 46 | } 47 | 48 | // Find chunk in children, if doesn't exist, return false 49 | Children::iterator it = std::find(children_.begin(), children_.end(), chunk); 50 | if (it == children_.end()) { 51 | return false; 52 | } 53 | 54 | chunk->parent_ = NULL; 55 | children_.erase(it); 56 | return true; 57 | } 58 | 59 | void Core::DeleteChildren() 60 | { 61 | // Delete children 62 | Children copy = children_; 63 | for (Children::iterator it = copy.begin(); it != copy.end(); it++) { 64 | delete (*it); 65 | } 66 | } 67 | 68 | size_t Core::IndexOfChild(Core *chunk) const 69 | { 70 | return std::find(children_.begin(), children_.end(), chunk) - children_.begin(); 71 | } 72 | 73 | void Core::InsertChild(size_t index, Core *chunk) 74 | { 75 | if (chunk == this || FindParent(chunk)) { 76 | return; 77 | } 78 | 79 | // If this chunk has another parent, remove it from that parent 80 | if (chunk->parent_) { 81 | chunk->parent_->RemoveChild(chunk); 82 | } 83 | 84 | // Insert at position 85 | chunk->parent_ = this; 86 | children_.insert(children_.begin() + index, chunk); 87 | } 88 | 89 | } 90 | -------------------------------------------------------------------------------- /lib/core.h: -------------------------------------------------------------------------------- 1 | #ifndef CORE_H 2 | #define CORE_H 3 | 4 | #include 5 | #include 6 | 7 | #include "types.h" 8 | 9 | namespace si { 10 | 11 | class Core 12 | { 13 | public: 14 | Core(); 15 | LIBWEAVER_EXPORT virtual ~Core(); 16 | 17 | typedef std::vector Children; 18 | 19 | LIBWEAVER_EXPORT Core *GetParent() const { return parent_; } 20 | LIBWEAVER_EXPORT const Children &GetChildren() const { return children_; } 21 | 22 | bool FindParent(Core *p) const; 23 | 24 | void AppendChild(Core *Core); 25 | bool RemoveChild(Core *Core); 26 | void InsertChild(size_t index, Core *Core); 27 | Core *RemoveChild(size_t index); 28 | 29 | LIBWEAVER_EXPORT size_t IndexOfChild(Core *Core) const; 30 | LIBWEAVER_EXPORT Core *GetChildAt(size_t index) const { return children_.at(index); } 31 | LIBWEAVER_EXPORT size_t GetChildCount() const { return children_.size(); } 32 | LIBWEAVER_EXPORT bool HasChildren() const { return !children_.empty(); } 33 | LIBWEAVER_EXPORT bool ContainsChild(Core *child) const { return std::find(children_.begin(), children_.end(), child) != children_.end(); } 34 | 35 | protected: 36 | void DeleteChildren(); 37 | 38 | private: 39 | // Disable copy 40 | Core(const Core& other); 41 | Core& operator=(const Core& other); 42 | 43 | Core *parent_; 44 | Children children_; 45 | 46 | }; 47 | 48 | } 49 | 50 | #endif // CORE_H 51 | -------------------------------------------------------------------------------- /lib/file.cpp: -------------------------------------------------------------------------------- 1 | #include "file.h" 2 | 3 | #ifdef _WIN32 4 | #define NOMINMAX 5 | #include 6 | #else 7 | #include 8 | #define FSTR(x) static_cast(x) 9 | #endif 10 | 11 | namespace si { 12 | 13 | File::File() 14 | { 15 | m_Handle = NULL; 16 | } 17 | 18 | bool File::Open(const char *c, Mode mode) 19 | { 20 | #ifdef _WIN32 21 | m_Handle = CreateFileA(c, 22 | mode == Read ? GENERIC_READ : GENERIC_WRITE, 23 | FILE_SHARE_READ, 24 | NULL, 25 | mode == Read ? OPEN_EXISTING : CREATE_NEW, 26 | FILE_ATTRIBUTE_NORMAL, 27 | NULL); 28 | m_Mode = mode; 29 | return m_Handle != INVALID_HANDLE_VALUE; 30 | #else 31 | std::ios::openmode m = std::ios::binary; 32 | 33 | if (mode == Read) { 34 | m |= std::ios::in; 35 | } else { 36 | m |= std::ios::out; 37 | } 38 | 39 | m_Handle = new std::fstream(); 40 | FSTR(m_Handle)->open(c, m); 41 | if (FSTR(m_Handle)->good() && FSTR(m_Handle)->is_open()) { 42 | m_Mode = mode; 43 | return true; 44 | } 45 | 46 | return false; 47 | #endif 48 | } 49 | 50 | #ifdef _WIN32 51 | bool File::Open(const wchar_t *c, Mode mode) 52 | { 53 | m_Handle = CreateFileW(c, 54 | mode == Read ? GENERIC_READ : GENERIC_WRITE, 55 | FILE_SHARE_READ, 56 | NULL, 57 | mode == Read ? OPEN_EXISTING : CREATE_NEW, 58 | FILE_ATTRIBUTE_NORMAL, 59 | NULL); 60 | return m_Handle != INVALID_HANDLE_VALUE; 61 | } 62 | #endif 63 | 64 | File::pos_t File::pos() 65 | { 66 | #ifdef _WIN32 67 | LONG high = 0; 68 | DWORD low = SetFilePointer(m_Handle, 0, &high, FILE_CURRENT); 69 | return pos_t(high) << 32 | low; 70 | #else 71 | if (m_Mode == Read) { 72 | return FSTR(m_Handle)->tellg(); 73 | } else { 74 | return FSTR(m_Handle)->tellp(); 75 | } 76 | #endif 77 | } 78 | 79 | File::pos_t File::size() 80 | { 81 | #ifdef _WIN32 82 | DWORD high; 83 | DWORD low = GetFileSize(m_Handle, &high); 84 | return pos_t(high) << 32 | low; 85 | #else 86 | pos_t before = pos(); 87 | seek(0, SeekEnd); 88 | pos_t sz = pos(); 89 | seek(before, SeekStart); 90 | return sz; 91 | #endif 92 | } 93 | 94 | void File::seek(File::pos_t p, SeekMode s) 95 | { 96 | #ifdef _WIN32 97 | LONG high = p >> 32; 98 | DWORD low = (DWORD) p; 99 | 100 | DWORD m; 101 | switch (s) { 102 | case SeekStart: 103 | m = FILE_BEGIN; 104 | break; 105 | case SeekCurrent: 106 | m = FILE_CURRENT; 107 | break; 108 | case SeekEnd: 109 | m = FILE_END; 110 | break; 111 | } 112 | 113 | SetFilePointer(m_Handle, low, &high, m); 114 | #else 115 | std::ios::seekdir d = std::ios::beg; 116 | 117 | switch (s) { 118 | case SeekStart: 119 | d = std::ios::beg; 120 | break; 121 | case SeekCurrent: 122 | d = std::ios::cur; 123 | break; 124 | case SeekEnd: 125 | d = std::ios::end; 126 | break; 127 | } 128 | 129 | if (m_Mode == Read) { 130 | FSTR(m_Handle)->seekg(p, d); 131 | } else { 132 | FSTR(m_Handle)->seekp(p, d); 133 | } 134 | #endif 135 | } 136 | 137 | void File::Close() 138 | { 139 | #ifdef _WIN32 140 | CloseHandle(m_Handle); 141 | #else 142 | FSTR(m_Handle)->close(); 143 | delete FSTR(m_Handle); 144 | m_Handle = NULL; 145 | #endif 146 | } 147 | 148 | File::pos_t File::ReadData(void *data, File::pos_t size) 149 | { 150 | #ifdef _WIN32 151 | DWORD r; 152 | ReadFile(m_Handle, data, (DWORD) size, &r, NULL); 153 | return r; 154 | #else 155 | pos_t before = this->pos(); 156 | FSTR(m_Handle)->read((char *) data, size); 157 | return this->pos() - before; 158 | #endif 159 | } 160 | 161 | File::pos_t File::WriteData(const void *data, File::pos_t size) 162 | { 163 | #ifdef _WIN32 164 | DWORD w; 165 | WriteFile(m_Handle, data, (DWORD) size, &w, NULL); 166 | return w; 167 | #else 168 | pos_t before = this->pos(); 169 | FSTR(m_Handle)->write((const char *) data, size); 170 | return this->pos() - before; 171 | #endif 172 | } 173 | 174 | uint8_t FileBase::ReadU8() 175 | { 176 | uint8_t u; 177 | ReadData(&u, sizeof(u)); 178 | return u; 179 | } 180 | 181 | void FileBase::WriteU8(uint8_t u) 182 | { 183 | WriteData(&u, sizeof(u)); 184 | } 185 | 186 | uint16_t FileBase::ReadU16() 187 | { 188 | uint16_t u; 189 | ReadData(&u, sizeof(u)); 190 | return u; 191 | } 192 | 193 | void FileBase::WriteU16(uint16_t u) 194 | { 195 | WriteData(&u, sizeof(u)); 196 | } 197 | 198 | uint32_t FileBase::ReadU32() 199 | { 200 | uint32_t u; 201 | ReadData(&u, sizeof(u)); 202 | return u; 203 | } 204 | 205 | void FileBase::WriteU32(uint32_t u) 206 | { 207 | WriteData(&u, sizeof(u)); 208 | } 209 | 210 | Vector3 FileBase::ReadVector3() 211 | { 212 | Vector3 u; 213 | ReadData(&u, sizeof(u)); 214 | return u; 215 | } 216 | 217 | void FileBase::WriteVector3(const Vector3 &v) 218 | { 219 | WriteData(&v, sizeof(v)); 220 | } 221 | 222 | std::string FileBase::ReadString() 223 | { 224 | std::string d; 225 | 226 | while (true) { 227 | char c; 228 | ReadData(&c, 1); 229 | if (c == 0) { 230 | break; 231 | } 232 | d.push_back(c); 233 | } 234 | 235 | return d; 236 | } 237 | 238 | void FileBase::WriteString(const std::string &d) 239 | { 240 | WriteData(d.c_str(), d.size()); 241 | 242 | // Ensure null terminator 243 | WriteU8(0); 244 | } 245 | 246 | bytearray FileBase::ReadBytes(File::pos_t size) 247 | { 248 | bytearray d; 249 | 250 | d.resize(size); 251 | ReadData(d.data(), size); 252 | 253 | return d; 254 | } 255 | 256 | void FileBase::WriteBytes(const bytearray &ba) 257 | { 258 | WriteData(ba.data(), ba.size()); 259 | } 260 | 261 | MemoryBuffer::MemoryBuffer() 262 | { 263 | m_Position = 0; 264 | } 265 | 266 | MemoryBuffer::MemoryBuffer(const bytearray &data) 267 | { 268 | m_Internal = data; 269 | m_Position = 0; 270 | } 271 | 272 | File::pos_t MemoryBuffer::pos() 273 | { 274 | return m_Position; 275 | } 276 | 277 | File::pos_t MemoryBuffer::size() 278 | { 279 | return m_Internal.size(); 280 | } 281 | 282 | void MemoryBuffer::seek(File::pos_t p, SeekMode s) 283 | { 284 | switch (s) { 285 | case SeekStart: 286 | m_Position = std::min(p, size()); 287 | break; 288 | case SeekCurrent: 289 | m_Position = std::min(m_Position + p, size()); 290 | break; 291 | case SeekEnd: 292 | if (p > size()) { 293 | m_Position = 0; 294 | } else { 295 | m_Position = size() - p; 296 | } 297 | break; 298 | } 299 | } 300 | 301 | File::pos_t MemoryBuffer::ReadData(void *data, File::pos_t size) 302 | { 303 | pos_t remaining = m_Internal.size() - m_Position; 304 | size = std::min(size, remaining); 305 | memcpy(data, m_Internal.data() + m_Position, size); 306 | m_Position += size; 307 | return size; 308 | } 309 | 310 | File::pos_t MemoryBuffer::WriteData(const void *data, File::pos_t size) 311 | { 312 | pos_t end = m_Position + size; 313 | if (end > m_Internal.size()) { 314 | m_Internal.resize(end); 315 | } 316 | memcpy(m_Internal.data() + m_Position, data, size); 317 | m_Position += size; 318 | return size; 319 | } 320 | 321 | } 322 | -------------------------------------------------------------------------------- /lib/file.h: -------------------------------------------------------------------------------- 1 | #ifndef FILE_H 2 | #define FILE_H 3 | 4 | #include "types.h" 5 | 6 | namespace si { 7 | 8 | class FileBase 9 | { 10 | public: 11 | FileBase() 12 | { 13 | } 14 | 15 | virtual ~FileBase() 16 | { 17 | } 18 | 19 | enum Mode { 20 | Read, 21 | Write 22 | }; 23 | 24 | typedef uint64_t pos_t; 25 | 26 | uint8_t ReadU8(); 27 | uint16_t ReadU16(); 28 | uint32_t ReadU32(); 29 | std::string ReadString(); 30 | bytearray ReadBytes(pos_t size); 31 | Vector3 ReadVector3(); 32 | virtual pos_t ReadData(void *data, pos_t size) = 0; 33 | 34 | void WriteU8(uint8_t u); 35 | void WriteU16(uint16_t u); 36 | void WriteU32(uint32_t u); 37 | void WriteString(const std::string &s); 38 | void WriteBytes(const bytearray &b); 39 | void WriteVector3(const Vector3 &b); 40 | virtual pos_t WriteData(const void *data, pos_t size) = 0; 41 | 42 | virtual void Close() {} 43 | 44 | enum SeekMode 45 | { 46 | SeekStart, 47 | SeekCurrent, 48 | SeekEnd 49 | }; 50 | 51 | virtual pos_t pos() = 0; 52 | virtual pos_t size() = 0; 53 | virtual void seek(pos_t p, SeekMode s = SeekStart) = 0; 54 | LIBWEAVER_EXPORT bool atEnd() { return pos() == size(); } 55 | 56 | }; 57 | 58 | class File : public FileBase 59 | { 60 | public: 61 | File(); 62 | 63 | virtual ~File() 64 | { 65 | Close(); 66 | } 67 | 68 | bool Open(const char *c, Mode mode); 69 | 70 | #ifdef _WIN32 71 | bool Open(const wchar_t *c, Mode mode); 72 | #endif 73 | 74 | virtual pos_t pos(); 75 | virtual pos_t size(); 76 | virtual void seek(pos_t p, SeekMode s = SeekStart); 77 | 78 | virtual void Close(); 79 | virtual pos_t ReadData(void *data, pos_t size); 80 | virtual pos_t WriteData(const void *data, pos_t size); 81 | 82 | private: 83 | void *m_Handle; 84 | Mode m_Mode; 85 | 86 | }; 87 | 88 | class MemoryBuffer : public FileBase 89 | { 90 | public: 91 | LIBWEAVER_EXPORT MemoryBuffer(); 92 | LIBWEAVER_EXPORT MemoryBuffer(const bytearray &data); 93 | 94 | LIBWEAVER_EXPORT virtual pos_t pos(); 95 | LIBWEAVER_EXPORT virtual pos_t size(); 96 | LIBWEAVER_EXPORT virtual void seek(pos_t p, SeekMode s = SeekStart); 97 | 98 | const bytearray &data() const { return m_Internal; } 99 | 100 | LIBWEAVER_EXPORT virtual pos_t ReadData(void *data, pos_t size); 101 | LIBWEAVER_EXPORT virtual pos_t WriteData(const void *data, pos_t size); 102 | 103 | private: 104 | bytearray m_Internal; 105 | pos_t m_Position; 106 | 107 | }; 108 | 109 | } 110 | 111 | #endif // FILE_H 112 | -------------------------------------------------------------------------------- /lib/info.h: -------------------------------------------------------------------------------- 1 | #ifndef INFO_H 2 | #define INFO_H 3 | 4 | #include "core.h" 5 | 6 | namespace si { 7 | 8 | class Info : public Core 9 | { 10 | public: 11 | static const uint32_t NULL_OBJECT_ID = 0xFFFFFFFF; 12 | 13 | Info() 14 | { 15 | m_ObjectID = NULL_OBJECT_ID; 16 | } 17 | 18 | void clear() 19 | { 20 | m_Desc.clear(); 21 | DeleteChildren(); 22 | } 23 | 24 | const uint32_t &GetType() const { return m_Type; } 25 | void SetType(const uint32_t &t) { m_Type = t; } 26 | 27 | const uint32_t &GetOffset() const { return m_Offset; } 28 | void SetOffset(const uint32_t &t) { m_Offset = t; } 29 | 30 | const uint32_t &GetObjectID() const { return m_ObjectID; } 31 | void SetObjectID(const uint32_t &t) { m_ObjectID = t; } 32 | 33 | const uint32_t &GetSize() const { return m_Size; } 34 | void SetSize(const uint32_t &t) { m_Size = t; } 35 | 36 | const std::string &GetDescription() const { return m_Desc; } 37 | void SetDescription(const std::string &d) { m_Desc = d; } 38 | 39 | const bytearray &GetData() const { return m_Data; } 40 | void SetData(const bytearray &d) { m_Data = d; } 41 | 42 | private: 43 | uint32_t m_Type; 44 | uint32_t m_Offset; 45 | uint32_t m_Size; 46 | uint32_t m_ObjectID; 47 | std::string m_Desc; 48 | bytearray m_Data; 49 | 50 | }; 51 | 52 | } 53 | 54 | #endif // INFO_H 55 | -------------------------------------------------------------------------------- /lib/interleaf.cpp: -------------------------------------------------------------------------------- 1 | #include "interleaf.h" 2 | 3 | #include 4 | #include 5 | #include 6 | 7 | #include "object.h" 8 | #include "othertypes.h" 9 | #include "sitypes.h" 10 | #include "util.h" 11 | 12 | namespace si { 13 | 14 | static const uint32_t kMinimumChunkSize = 8; 15 | 16 | Interleaf::Interleaf() 17 | { 18 | } 19 | 20 | void Interleaf::Clear() 21 | { 22 | m_Info.clear(); 23 | m_BufferSize = 0; 24 | m_JoiningProgress = 0; 25 | m_JoiningSize = 0; 26 | m_ObjectIDTable.clear(); 27 | m_ObjectList.clear(); 28 | DeleteChildren(); 29 | } 30 | 31 | Interleaf::Error Interleaf::Read(const char *f) 32 | { 33 | File is; 34 | if (!is.Open(f, File::Read)) { 35 | return ERROR_IO; 36 | } 37 | return Read(&is); 38 | } 39 | 40 | Interleaf::Error Interleaf::Write(const char *f) const 41 | { 42 | File os; 43 | if (!os.Open(f, File::Write)) { 44 | return ERROR_IO; 45 | } 46 | return Write(&os); 47 | } 48 | 49 | #ifdef _WIN32 50 | Interleaf::Error Interleaf::Read(const wchar_t *f) 51 | { 52 | File is; 53 | if (!is.Open(f, File::Read)) { 54 | return ERROR_IO; 55 | } 56 | return Read(&is); 57 | } 58 | 59 | Interleaf::Error Interleaf::Write(const wchar_t *f) const 60 | { 61 | File os; 62 | if (!os.Open(f, File::Write)) { 63 | return ERROR_IO; 64 | } 65 | return Write(&os); 66 | } 67 | #endif 68 | 69 | Interleaf::Error Interleaf::ReadChunk(Core *parent, FileBase *f, Info *info) 70 | { 71 | uint32_t offset = f->pos(); 72 | uint32_t id = f->ReadU32(); 73 | uint32_t size = f->ReadU32(); 74 | uint32_t end = uint32_t(f->pos()) + size; 75 | 76 | info->SetType(id); 77 | info->SetOffset(offset); 78 | info->SetSize(size); 79 | 80 | std::stringstream desc; 81 | 82 | switch (static_cast(id)) { 83 | case RIFF::RIFF_: 84 | { 85 | // Require RIFF type to be OMNI 86 | uint32_t riff_type = f->ReadU32(); 87 | if (riff_type != RIFF::OMNI) { 88 | return ERROR_INVALID_INPUT; 89 | } 90 | 91 | desc << "Type: " << RIFF::PrintU32AsString(riff_type); 92 | break; 93 | } 94 | case RIFF::MxHd: 95 | { 96 | m_Version = f->ReadU32(); 97 | desc << "Version: 0x" << std::hex << m_Version << std::endl; 98 | 99 | m_BufferSize = f->ReadU32(); 100 | desc << "Buffer Size: 0x" << std::hex << m_BufferSize; 101 | 102 | m_BufferCount = f->ReadU32(); 103 | desc << std::endl << "Buffer Count: " << std::dec << m_BufferCount << std::endl; 104 | break; 105 | } 106 | case RIFF::pad_: 107 | f->seek(size, File::SeekCurrent); 108 | break; 109 | case RIFF::MxOf: 110 | { 111 | uint32_t offset_count = f->ReadU32(); 112 | 113 | desc << "Count: " << offset_count; 114 | 115 | uint32_t real_count = (size - sizeof(uint32_t)) / sizeof(uint32_t); 116 | m_ObjectList.resize(real_count); 117 | for (uint32_t i = 0; i < real_count; i++) { 118 | Object *o = new Object(); 119 | parent->AppendChild(o); 120 | 121 | uint32_t choffset = f->ReadU32(); 122 | m_ObjectList[i] = choffset; 123 | desc << std::endl << i << ": 0x" << std::hex << choffset; 124 | } 125 | break; 126 | } 127 | case RIFF::LIST: 128 | { 129 | uint32_t list_type = f->ReadU32(); 130 | desc << "Type: " << RIFF::PrintU32AsString(list_type) << std::endl; 131 | uint32_t list_count = 0; 132 | if (list_type == RIFF::MxCh) { 133 | if (m_Version == Version2_1) { 134 | uint32_t unknown_list_entry = f->ReadU32(); 135 | desc << "Unknown v2.1 list entry: " << unknown_list_entry << std::endl; 136 | } 137 | 138 | list_count = f->ReadU32(); 139 | if (list_count == LIST::Act_ || list_count == LIST::RAND) { 140 | desc << "Extension: "; 141 | if (list_count == LIST::RAND) { 142 | uint32_t rand_upper = f->ReadU32(); 143 | uint64_t rand_val = uint64_t(rand_upper) << 32 | list_count; 144 | f->seek(1, File::SeekCurrent); 145 | desc << ((const char *) &rand_val); 146 | } else if (list_count == LIST::Act_) { 147 | desc << ((const char *) &list_count); 148 | } 149 | desc << std::endl; 150 | 151 | // Re-read list count 152 | list_count = f->ReadU32(); 153 | for (uint32_t i=0; iReadU16(); 156 | desc << " " << ((const char *) &val) << std::endl; 157 | } 158 | } 159 | desc << "Count: " << list_count << std::endl; 160 | } 161 | break; 162 | } 163 | case RIFF::MxSt: 164 | case RIFF::MxDa: 165 | case RIFF::WAVE: 166 | case RIFF::fmt_: 167 | case RIFF::data: 168 | case RIFF::OMNI: 169 | // Types with no data 170 | break; 171 | case RIFF::MxOb: 172 | { 173 | Object *o = NULL; 174 | 175 | for (size_t i=0; i(GetChildAt(i)); 178 | break; 179 | } 180 | } 181 | 182 | if (!o) { 183 | o = new Object(); 184 | parent->AppendChild(o); 185 | } 186 | 187 | ReadObject(f, o, desc); 188 | 189 | info->SetObjectID(o->id()); 190 | 191 | m_ObjectIDTable[o->id()] = o; 192 | 193 | parent = o; 194 | break; 195 | } 196 | case RIFF::MxCh: 197 | { 198 | uint16_t flags = f->ReadU16(); 199 | desc << "Flags: 0x" << std::hex << flags << std::endl; 200 | 201 | uint32_t object = f->ReadU32(); 202 | desc << "Object: " << std::dec << object << std::endl; 203 | 204 | uint32_t time = f->ReadU32(); 205 | desc << "Time: " << time << std::endl; 206 | 207 | uint32_t data_sz = f->ReadU32(); 208 | desc << "Size: " << data_sz << std::endl; 209 | 210 | bytearray data = f->ReadBytes(size - MxCh::HEADER_SIZE); 211 | 212 | info->SetObjectID(object); 213 | info->SetData(data); 214 | 215 | if (!(flags & MxCh::FLAG_END)) { 216 | std::map::iterator it = m_ObjectIDTable.find(object); 217 | if (it == m_ObjectIDTable.end()) { 218 | LogError() << "Failed to find object " << object << " for chunk at " << std::hex << offset << std::dec << std::endl; 219 | //return ERROR_INVALID_INPUT; 220 | } else { 221 | Object *o = it->second; 222 | 223 | if (flags & MxCh::FLAG_SPLIT && m_JoiningSize > 0) { 224 | o->data_.back().append(data); 225 | 226 | m_JoiningProgress += data.size(); 227 | if (m_JoiningProgress == m_JoiningSize) { 228 | m_JoiningProgress = 0; 229 | m_JoiningSize = 0; 230 | } 231 | } else { 232 | o->data_.push_back(data); 233 | 234 | if (o->data_.size() == 2) { 235 | o->time_offset_ = time; 236 | } 237 | 238 | if (flags & MxCh::FLAG_SPLIT) { 239 | m_JoiningProgress = data.size(); 240 | m_JoiningSize = data_sz; 241 | } 242 | } 243 | } 244 | break; 245 | } 246 | } 247 | } 248 | 249 | // Assume any remaining data is this chunk's children 250 | while (!f->atEnd() && (f->pos() + kMinimumChunkSize) < end) { 251 | // Check alignment, if there's not enough room to for another segment, skip ahead 252 | if (m_BufferSize > 0) { 253 | uint32_t offset_in_buffer = f->pos()%m_BufferSize; 254 | if (offset_in_buffer + kMinimumChunkSize > m_BufferSize) { 255 | f->seek(m_BufferSize-offset_in_buffer, File::SeekCurrent); 256 | } 257 | } 258 | 259 | // Read next child 260 | Info *subinfo = new Info(); 261 | info->AppendChild(subinfo); 262 | Error e = ReadChunk(parent, f, subinfo); 263 | if (e != ERROR_SUCCESS) { 264 | return e; 265 | } 266 | } 267 | 268 | info->SetDescription(desc.str()); 269 | 270 | if (f->pos() < end) { 271 | f->seek(end, File::SeekStart); 272 | } 273 | 274 | if (size%2 == 1) { 275 | f->seek(1, File::SeekCurrent); 276 | } 277 | 278 | return ERROR_SUCCESS; 279 | } 280 | 281 | Object *Interleaf::ReadObject(FileBase *f, Object *o, std::stringstream &desc) 282 | { 283 | o->type_ = static_cast(f->ReadU16()); 284 | desc << "Type: " << o->type_ << std::endl; 285 | o->presenter_ = f->ReadString(); 286 | desc << "Presenter: " << o->presenter_ << std::endl; 287 | o->unknown1_ = f->ReadU32(); 288 | desc << "Unknown1: " << o->unknown1_ << std::endl; 289 | o->name_ = f->ReadString(); 290 | desc << "Name: " << o->name_ << std::endl; 291 | o->id_ = f->ReadU32(); 292 | desc << "ID: " << o->id_ << std::endl; 293 | o->flags_ = f->ReadU32(); 294 | desc << "Flags: 0x" << std::hex << o->flags_ << std::dec << std::endl; 295 | o->unknown4_ = f->ReadU32(); 296 | desc << "Unknown4: " << o->unknown4_ << std::endl; 297 | o->duration_ = f->ReadU32(); 298 | desc << "Duration: " << o->duration_ << std::endl; 299 | o->loops_ = f->ReadU32(); 300 | desc << "Loops: " << o->loops_ << std::endl; 301 | o->location_ = f->ReadVector3(); 302 | desc << "Location: " << o->location_.x << " " << o->location_.y << " " << o->location_.z << std::endl; 303 | o->direction_ = f->ReadVector3(); 304 | desc << "Direction: " << o->direction_.x << " " << o->direction_.y << " " << o->direction_.z << std::endl; 305 | o->up_ = f->ReadVector3(); 306 | desc << "Up: " << o->up_.x << " " << o->up_.y << " " << o->up_.z << std::endl; 307 | 308 | uint16_t extra_sz = f->ReadU16(); 309 | desc << "Extra Size: " << extra_sz << std::endl; 310 | o->extra_ = f->ReadBytes(extra_sz); 311 | 312 | desc << "Extra Data: "; 313 | if (o->extra_.size() > 0) { 314 | desc << o->extra_.data() << std::endl; 315 | } 316 | desc << std::endl; 317 | 318 | if (o->type_ != MxOb::Presenter && o->type_ != MxOb::World && o->type_ != MxOb::Animation) { 319 | o->filename_ = f->ReadString(); 320 | desc << "Filename: " << o->filename_ << std::endl; 321 | o->unknown26_ = f->ReadU32(); 322 | desc << "Unknown26: " << o->unknown26_ << std::endl; 323 | o->unknown27_ = f->ReadU32(); 324 | desc << "Unknown27: " << o->unknown27_ << std::endl; 325 | o->unknown28_ = f->ReadU32(); 326 | desc << "Unknown28: " << o->unknown28_ << std::endl; 327 | o->filetype_ = static_cast(f->ReadU32()); 328 | desc << "File Type: " << RIFF::PrintU32AsString(o->filetype_) << std::endl; 329 | o->unknown29_ = f->ReadU32(); 330 | desc << "Unknown29: " << o->unknown29_ << std::endl; 331 | o->unknown30_ = f->ReadU32(); 332 | desc << "Unknown30: " << o->unknown30_ << std::endl; 333 | 334 | if (o->filetype_ == MxOb::WAV) { 335 | o->volume_ = f->ReadU32(); 336 | desc << "Unknown31: " << o->volume_ << std::endl; 337 | } 338 | } 339 | 340 | return o; 341 | } 342 | 343 | Interleaf::Error Interleaf::Read(FileBase *f) 344 | { 345 | Clear(); 346 | return ReadChunk(this, f, &m_Info); 347 | } 348 | 349 | void RecursivelyAddObjectToList(std::vector *list, Object *o) 350 | { 351 | list->push_back(o); 352 | for (size_t j=0; jGetChildCount(); j++) { 353 | RecursivelyAddObjectToList(list, static_cast(o->GetChildAt(j))); 354 | } 355 | } 356 | 357 | Interleaf::Error Interleaf::Write(FileBase *f) const 358 | { 359 | if (m_BufferSize == 0) { 360 | LogError() << "Buffer size must be set to write" << std::endl; 361 | return ERROR_INVALID_BUFFER_SIZE; 362 | } 363 | 364 | RIFF::Chk riff = RIFF::BeginChunk(f, RIFF::RIFF_); 365 | f->WriteU32(RIFF::OMNI); 366 | 367 | size_t offset_table_pos; 368 | 369 | { 370 | // MxHd 371 | RIFF::Chk mxhd = RIFF::BeginChunk(f, RIFF::MxHd); 372 | 373 | f->WriteU32(m_Version); 374 | f->WriteU32(m_BufferSize); 375 | f->WriteU32(m_BufferCount); 376 | 377 | RIFF::EndChunk(f, mxhd); 378 | } 379 | 380 | { 381 | // MxOf 382 | RIFF::Chk mxof = RIFF::BeginChunk(f, RIFF::MxOf); 383 | 384 | f->WriteU32(GetChildCount()); 385 | 386 | offset_table_pos = f->pos(); 387 | 388 | for (size_t i = 0; i < GetChildCount(); i++) { 389 | f->WriteU32(0); 390 | } 391 | 392 | RIFF::EndChunk(f, mxof); 393 | } 394 | 395 | { 396 | // LIST 397 | RIFF::Chk list_mxst = RIFF::BeginChunk(f, RIFF::LIST); 398 | 399 | f->WriteU32(RIFF::MxSt); 400 | 401 | for (size_t i = 0; i < GetChildCount(); i++) { 402 | Object *child = static_cast(GetChildAt(i)); 403 | if (child->type() == MxOb::Null) { 404 | continue; 405 | } 406 | 407 | size_t maxSz = child->CalculateMaximumDiskSize() + kMinimumChunkSize; 408 | WritePaddingIfNecessary(f, maxSz); 409 | 410 | uint32_t mxst_offset = f->pos(); 411 | 412 | f->seek(size_t(offset_table_pos) + i * sizeof(uint32_t)); 413 | f->WriteU32(mxst_offset); 414 | f->seek(mxst_offset); 415 | 416 | // MxSt 417 | RIFF::Chk mxst = RIFF::BeginChunk(f, RIFF::MxSt); 418 | 419 | { 420 | // MxOb 421 | WriteObject(f, child); 422 | } 423 | 424 | { 425 | // LIST 426 | RIFF::Chk list_mxda = RIFF::BeginChunk(f, RIFF::LIST); 427 | 428 | f->WriteU32(RIFF::MxDa); 429 | 430 | // First, interleave headers 431 | std::vector objects; 432 | objects.reserve(child->GetChildCount() + 1); 433 | RecursivelyAddObjectToList(&objects, child); 434 | 435 | InterleaveObjects(f, objects); 436 | 437 | RIFF::EndChunk(f, list_mxda); 438 | } 439 | 440 | RIFF::EndChunk(f, mxst); 441 | } 442 | 443 | // Fill remainder with padding 444 | if (f->pos()%m_BufferSize != 0) { 445 | uint32_t current_buf = f->pos() / m_BufferSize; 446 | uint32_t target_sz = (current_buf + 1) * m_BufferSize; 447 | 448 | WritePadding(f, target_sz - f->pos()); 449 | } 450 | 451 | RIFF::EndChunk(f, list_mxst); 452 | } 453 | 454 | RIFF::EndChunk(f, riff); 455 | 456 | return ERROR_SUCCESS; 457 | } 458 | 459 | void Interleaf::WriteObject(FileBase *f, const Object *o) const 460 | { 461 | WritePaddingIfNecessary(f, o->CalculateMaximumDiskSize()); 462 | 463 | RIFF::Chk mxob = RIFF::BeginChunk(f, RIFF::MxOb); 464 | 465 | f->WriteU16(o->type_); 466 | f->WriteString(o->presenter_); 467 | f->WriteU32(o->unknown1_); 468 | f->WriteString(o->name_); 469 | f->WriteU32(o->id_); 470 | f->WriteU32(o->flags_); 471 | f->WriteU32(o->unknown4_); 472 | f->WriteU32(o->duration_); 473 | f->WriteU32(o->loops_); 474 | f->WriteVector3(o->location_); 475 | f->WriteVector3(o->direction_); 476 | f->WriteVector3(o->up_); 477 | 478 | f->WriteU16(o->extra_.size()); 479 | f->WriteBytes(o->extra_); 480 | 481 | if (o->type_ != MxOb::Presenter && o->type_ != MxOb::World && o->type_ != MxOb::Animation) { 482 | f->WriteString(o->filename_); 483 | f->WriteU32(o->unknown26_); 484 | f->WriteU32(o->unknown27_); 485 | f->WriteU32(o->unknown28_); 486 | f->WriteU32(o->filetype_); 487 | f->WriteU32(o->unknown29_); 488 | f->WriteU32(o->unknown30_); 489 | 490 | if (o->filetype_ == MxOb::WAV) { 491 | f->WriteU32(o->volume_); 492 | } 493 | } 494 | 495 | if (o->HasChildren()) { 496 | // Child list 497 | RIFF::Chk list_mxch = RIFF::BeginChunk(f, RIFF::LIST); 498 | 499 | f->WriteU32(RIFF::MxCh); 500 | f->WriteU32(o->GetChildCount()); 501 | 502 | for (size_t i = 0; i < o->GetChildCount(); i++) { 503 | WriteObject(f, static_cast(o->GetChildAt(i))); 504 | } 505 | 506 | RIFF::EndChunk(f, list_mxch); 507 | } 508 | 509 | RIFF::EndChunk(f, mxob); 510 | } 511 | 512 | struct ChunkStatus 513 | { 514 | Object *object; 515 | size_t index; 516 | uint32_t time; 517 | }; 518 | 519 | bool HasChildrenThatNeedPriority(Object *parent, uint32_t parent_time, const std::vector &other_jobs) 520 | { 521 | for (size_t i=0; iContainsChild(other_obj) && other_jobs.at(i).time <= parent_time) { 525 | return true; 526 | } 527 | } 528 | return false; 529 | } 530 | 531 | void Interleaf::InterleaveObjects(FileBase *f, const std::vector &objects) const 532 | { 533 | std::vector status(objects.size()); 534 | 535 | // Set up status vector 536 | for (size_t i=0; itime_offset_; 540 | } 541 | 542 | // First, interleave headers 543 | for (std::vector::iterator it = status.begin(); it != status.end(); ) { 544 | ChunkStatus &s = *it; 545 | Object *o = s.object; 546 | 547 | bool proceed = true; 548 | 549 | if (!o->data().empty()) { 550 | WriteSubChunk(f, 0, o->id(), 0xFFFFFFFF, o->data().front()); 551 | s.index++; 552 | 553 | // If we've already reached the end, write the end chunk now 554 | if (o->data().size() == s.index) { 555 | WriteSubChunk(f, MxCh::FLAG_END, o->id(), 0xFFFFFFFF); 556 | it = status.erase(it); 557 | proceed = false; 558 | } 559 | } 560 | 561 | if (proceed) { 562 | it++; 563 | } 564 | } 565 | 566 | // Next, interleave the rest based on time 567 | while (true) { 568 | // Update parent time too 569 | bool done = false; 570 | while (!done) { 571 | done = true; 572 | for (size_t j=0; jContainsChild(obj)) { 580 | if (p.time < s.time) { 581 | p.time = s.time; 582 | done = false; 583 | } 584 | } 585 | } 586 | } 587 | } 588 | } 589 | 590 | // Find next chunk 591 | std::vector::iterator s = status.begin(); 592 | if (s == status.end()) { 593 | break; 594 | } 595 | 596 | while (HasChildrenThatNeedPriority(s->object, s->time, status)) { 597 | s++; 598 | } 599 | 600 | if (s == status.end()) { 601 | break; 602 | } 603 | 604 | std::vector::iterator it = s; 605 | it++; 606 | for (; it!=status.end(); it++) { 607 | // Find earliest chunk to write 608 | if (it->time < s->time && !HasChildrenThatNeedPriority(it->object, it->time, status)) { 609 | s = it; 610 | } 611 | } 612 | 613 | if (s->index == s->object->data_.size()) { 614 | WriteSubChunk(f, MxCh::FLAG_END, s->object->id(), s->time); 615 | status.erase(s); 616 | continue; 617 | } 618 | 619 | Object *obj = s->object; 620 | const bytearray &data = obj->data().at(s->index); 621 | 622 | WriteSubChunk(f, 0, obj->id(), s->time, data); 623 | 624 | s->index++; 625 | 626 | // Increment time 627 | switch (obj->filetype()) { 628 | case MxOb::WAV: 629 | { 630 | const WAVFmt *fmt = obj->GetFileHeader().cast(); 631 | s->time += round(double(data.size() * 1000) / (fmt->BitsPerSample/8) / fmt->Channels / fmt->SampleRate); 632 | break; 633 | } 634 | case MxOb::SMK: 635 | { 636 | int32_t frame_rate = obj->GetFileHeader().cast()->FrameRate; 637 | int32_t fps; 638 | if (frame_rate > 0) { 639 | fps = 1000/frame_rate; 640 | } else if (frame_rate < 0) { 641 | fps = 100000/-frame_rate; 642 | } else { 643 | fps = 10; 644 | } 645 | s->time += 1000/fps; 646 | break; 647 | } 648 | case MxOb::FLC: 649 | s->time += obj->GetFileHeader().cast()->speed; 650 | break; 651 | case MxOb::STL: 652 | case MxOb::OBJ: 653 | // Unaffected by time 654 | break; 655 | } 656 | } 657 | } 658 | 659 | void Interleaf::WriteSubChunk(FileBase *f, uint16_t flags, uint32_t object, uint32_t time, const bytearray &data) const 660 | { 661 | static const uint32_t total_hdr = MxCh::HEADER_SIZE + kMinimumChunkSize; 662 | 663 | uint32_t data_offset = 0; 664 | 665 | while (data_offset < data.size() || data.size() == 0) { 666 | uint32_t data_sz = data.size() - data_offset; 667 | 668 | // Calculate whether this chunk will overrun the buffer 669 | uint32_t start_buffer = f->pos() / m_BufferSize; 670 | uint32_t stop_buffer = (uint32_t(f->pos()) - 1 + data_sz + total_hdr) / m_BufferSize; 671 | 672 | size_t max_chunk = data_sz; 673 | 674 | if (start_buffer != stop_buffer) { 675 | size_t remaining = ((start_buffer + 1) * m_BufferSize) - f->pos(); 676 | 677 | if (remaining < total_hdr) { 678 | if (remaining < kMinimumChunkSize) { 679 | // There isn't enough space for another chunk, just jump ahead 680 | f->seek(remaining, File::SeekCurrent); 681 | } else { 682 | // This chunk won't fit in our buffer alignment. We must make a decision to either insert 683 | // padding or split the clip. 684 | WritePadding(f, remaining); 685 | } 686 | continue; 687 | } 688 | 689 | max_chunk = remaining - total_hdr; 690 | 691 | if (!(flags & MxCh::FLAG_SPLIT)) { 692 | 693 | // FIXME: Not sure exactly what this value is yet, likely to be smaller than this 694 | static const uint32_t MAX_PADDING = 9882; 695 | 696 | if (remaining < MAX_PADDING) { 697 | // This chunk won't fit in our buffer alignment. We must make a decision to either insert 698 | // padding or split the clip. 699 | WritePadding(f, remaining); 700 | 701 | // Do loop over again 702 | continue; 703 | } else { 704 | flags |= MxCh::FLAG_SPLIT; 705 | } 706 | } 707 | } 708 | 709 | bytearray chunk = data.mid(data_offset, max_chunk); 710 | WriteSubChunkInternal(f, flags, object, time, data_sz, chunk); 711 | data_offset += chunk.size(); 712 | 713 | if (data.size() == 0) { 714 | break; 715 | } 716 | } 717 | } 718 | 719 | void Interleaf::WriteSubChunkInternal(FileBase *f, uint16_t flags, uint32_t object, uint32_t time, uint32_t data_sz, const bytearray &data) const 720 | { 721 | RIFF::Chk mxch = RIFF::BeginChunk(f, RIFF::MxCh); 722 | 723 | f->WriteU16(flags); 724 | f->WriteU32(object); 725 | f->WriteU32(time); 726 | f->WriteU32(data_sz); 727 | f->WriteBytes(data); 728 | 729 | RIFF::EndChunk(f, mxch); 730 | } 731 | 732 | void Interleaf::WritePadding(FileBase *f, uint32_t size) const 733 | { 734 | if (size < kMinimumChunkSize) { 735 | return; 736 | } 737 | 738 | size -= kMinimumChunkSize; 739 | 740 | f->WriteU32(RIFF::pad_); 741 | f->WriteU32(size); 742 | 743 | bytearray b(size); 744 | b.fill(0xCD); 745 | f->WriteBytes(b); 746 | } 747 | 748 | void Interleaf::WritePaddingIfNecessary(FileBase *f, size_t projectedWrite) const 749 | { 750 | size_t projected_end = f->pos() + projectedWrite; 751 | size_t this_buf = f->pos()/m_BufferSize; 752 | size_t end_buf = projected_end/m_BufferSize; 753 | if (this_buf != end_buf) { 754 | WritePadding(f, (end_buf * m_BufferSize) - f->pos()); 755 | } 756 | } 757 | 758 | } 759 | -------------------------------------------------------------------------------- /lib/interleaf.h: -------------------------------------------------------------------------------- 1 | #ifndef INTERLEAF_H 2 | #define INTERLEAF_H 3 | 4 | #include 5 | 6 | #include "core.h" 7 | #include "file.h" 8 | #include "info.h" 9 | #include "object.h" 10 | 11 | namespace si { 12 | 13 | class Interleaf : public Core 14 | { 15 | public: 16 | enum Error 17 | { 18 | ERROR_SUCCESS, 19 | ERROR_IO, 20 | ERROR_INVALID_INPUT, 21 | ERROR_INVALID_BUFFER_SIZE 22 | }; 23 | 24 | enum Version 25 | { 26 | Version2_1 = 0x00010002, 27 | Version2_2 = 0x00020002 28 | }; 29 | 30 | LIBWEAVER_EXPORT Interleaf(); 31 | 32 | LIBWEAVER_EXPORT void Clear(); 33 | 34 | LIBWEAVER_EXPORT Error Read(const char *f); 35 | LIBWEAVER_EXPORT Error Write(const char *f) const; 36 | 37 | #ifdef _WIN32 38 | LIBWEAVER_EXPORT Error Read(const wchar_t *f); 39 | LIBWEAVER_EXPORT Error Write(const wchar_t *f) const; 40 | #endif 41 | 42 | Error Read(FileBase *is); 43 | Error Write(FileBase *os) const; 44 | 45 | Info *GetInformation() { return &m_Info; } 46 | 47 | private: 48 | Error ReadChunk(Core *parent, FileBase *f, Info *info); 49 | 50 | Object *ReadObject(FileBase *f, Object *o, std::stringstream &desc); 51 | void WriteObject(FileBase *f, const Object *o) const; 52 | 53 | void InterleaveObjects(FileBase *f, const std::vector &objects) const; 54 | 55 | void WriteSubChunk(FileBase *f, uint16_t flags, uint32_t object, uint32_t time, const bytearray &data = bytearray()) const; 56 | void WriteSubChunkInternal(FileBase *f, uint16_t flags, uint32_t object, uint32_t time, uint32_t data_sz, const bytearray &data) const; 57 | 58 | void WritePadding(FileBase *f, uint32_t size) const; 59 | void WritePaddingIfNecessary(FileBase *f, size_t projectedWrite) const; 60 | 61 | Info m_Info; 62 | 63 | uint32_t m_Version; 64 | uint32_t m_BufferSize; 65 | uint32_t m_BufferCount; 66 | 67 | std::vector m_ObjectList; 68 | std::map m_ObjectIDTable; 69 | 70 | uint32_t m_JoiningProgress; 71 | uint32_t m_JoiningSize; 72 | 73 | }; 74 | 75 | } 76 | 77 | #endif // INTERLEAF_H 78 | -------------------------------------------------------------------------------- /lib/object.cpp: -------------------------------------------------------------------------------- 1 | #include "object.h" 2 | 3 | #include 4 | 5 | #include "othertypes.h" 6 | #include "util.h" 7 | 8 | namespace si { 9 | 10 | Object::Object() 11 | { 12 | type_ = MxOb::Null; 13 | id_ = 0; 14 | time_offset_ = 0; 15 | } 16 | 17 | #ifdef _WIN32 18 | bool Object::ReplaceWithFile(const wchar_t *f) 19 | { 20 | File is; 21 | if (!is.Open(f, File::Read)) { 22 | return false; 23 | } 24 | return ReplaceWithFile(&is); 25 | } 26 | 27 | bool Object::ExtractToFile(const wchar_t *f) const 28 | { 29 | File os; 30 | if (!os.Open(f, File::Write)) { 31 | return false; 32 | } 33 | return ExtractToFile(&os); 34 | } 35 | #endif 36 | 37 | bool Object::ReplaceWithFile(const char *f) 38 | { 39 | File is; 40 | if (!is.Open(f, File::Read)) { 41 | return false; 42 | } 43 | return ReplaceWithFile(&is); 44 | } 45 | 46 | bool Object::ExtractToFile(const char *f) const 47 | { 48 | File os; 49 | if (!os.Open(f, File::Write)) { 50 | return false; 51 | } 52 | return ExtractToFile(&os); 53 | } 54 | 55 | bool Object::ReplaceWithFile(FileBase *f) 56 | { 57 | data_.clear(); 58 | 59 | switch (this->filetype()) { 60 | case MxOb::WAV: 61 | { 62 | if (f->ReadU32() != RIFF::RIFF_) { 63 | return false; 64 | } 65 | 66 | // Skip total size 67 | f->ReadU32(); 68 | 69 | if (f->ReadU32() != RIFF::WAVE) { 70 | return false; 71 | } 72 | 73 | bytearray fmt; 74 | bytearray data; 75 | 76 | while (!f->atEnd()) { 77 | uint32_t id = f->ReadU32(); 78 | uint32_t sz = f->ReadU32(); 79 | if (id == RIFF::fmt_) { 80 | fmt = f->ReadBytes(sz); 81 | } else if (id == RIFF::data) { 82 | data = f->ReadBytes(sz); 83 | } else { 84 | f->seek(sz, File::SeekCurrent); 85 | } 86 | } 87 | 88 | if (fmt.empty() || data.empty()) { 89 | return false; 90 | } 91 | 92 | data_.push_back(fmt); 93 | WAVFmt *fmt_info = fmt.cast(); 94 | size_t second_in_bytes = fmt_info->Channels * fmt_info->SampleRate * (fmt_info->BitsPerSample/8); 95 | size_t max; 96 | for (size_t i=0; iReadBytes(sizeof(SMK2)); 107 | 108 | // Read frame sizes 109 | SMK2 smk = *hdr.cast(); 110 | bytearray frame_sizes = f->ReadBytes(smk.Frames * sizeof(uint32_t)); 111 | hdr.append(frame_sizes); 112 | 113 | // Read frame types 114 | hdr.append(f->ReadBytes(smk.Frames)); 115 | 116 | // Read Huffman trees 117 | hdr.append(f->ReadBytes(smk.TreesSize)); 118 | 119 | // Place header into data vector 120 | data_.resize(smk.Frames + 1); 121 | data_[0] = hdr; 122 | 123 | uint32_t *real_sizes = frame_sizes.cast(); 124 | for (uint32_t i=0; i 0) { 127 | data_[i+1] = f->ReadBytes(sz); 128 | } 129 | } 130 | return true; 131 | } 132 | case MxOb::STL: 133 | { 134 | BMP bmp; 135 | f->ReadData(&bmp, sizeof(bmp)); 136 | 137 | bytearray info_header = f->ReadBytes(bmp.DataOffset - f->pos()); 138 | data_.push_back(info_header); 139 | 140 | bytearray pixels = f->ReadBytes(bmp.FileSize - f->pos()); 141 | data_.push_back(pixels); 142 | 143 | return true; 144 | } 145 | case MxOb::OBJ: 146 | { 147 | data_.push_back(f->ReadBytes(f->size())); 148 | return true; 149 | } 150 | default: 151 | LogWarning() << "Don't yet know how to chunk type " << RIFF::PrintU32AsString(this->filetype()) << std::endl; 152 | break; 153 | } 154 | 155 | return false; 156 | } 157 | 158 | bool Object::ExtractToFile(FileBase *f) const 159 | { 160 | if (data_.empty()) { 161 | return false; 162 | } 163 | 164 | switch (this->filetype()) { 165 | case MxOb::WAV: 166 | { 167 | // Write RIFF header 168 | RIFF::Chk riff = RIFF::BeginChunk(f, RIFF::RIFF_); 169 | 170 | f->WriteU32(RIFF::WAVE); 171 | 172 | { 173 | RIFF::Chk fmt = RIFF::BeginChunk(f, RIFF::fmt_); 174 | 175 | f->WriteBytes(data_.at(0)); 176 | 177 | RIFF::EndChunk(f, fmt); 178 | } 179 | 180 | { 181 | RIFF::Chk data = RIFF::BeginChunk(f, RIFF::data); 182 | // Merge all chunks after the first one 183 | for (size_t i=1; iWriteBytes(data_.at(i)); 185 | } 186 | RIFF::EndChunk(f, data); 187 | } 188 | 189 | RIFF::EndChunk(f, riff); 190 | break; 191 | } 192 | case MxOb::STL: 193 | { 194 | uint32_t size = sizeof(BMP); 195 | for (size_t i=0; iWriteData(&bmp, sizeof(bmp)); 207 | 208 | for (size_t i=0; iWriteBytes(data_.at(i)); 210 | } 211 | break; 212 | } 213 | case MxOb::FLC: 214 | { 215 | // First chunk is a complete FLIC header, so add it as-is 216 | f->WriteBytes(data_.at(0)); 217 | 218 | // Subsequent chunks are FLIC frames with an additional 20 byte header that needs to be stripped 219 | const int CUSTOM_HEADER_SZ = 20; 220 | for (size_t i=1; iWriteData(empty_hdr, 16); 224 | } else { 225 | f->WriteData(data_.at(i).data() + CUSTOM_HEADER_SZ, data_.at(i).size() - CUSTOM_HEADER_SZ); 226 | } 227 | } 228 | break; 229 | } 230 | default: 231 | LogWarning() << "Didn't know how to extract type '" << RIFF::PrintU32AsString(filetype()) << "', merging..." << std::endl; 232 | /* fall-through */ 233 | case MxOb::SMK: 234 | case MxOb::OBJ: 235 | // Simply merge 236 | for (size_t i=0; iWriteBytes(data_.at(i)); 238 | } 239 | break; 240 | } 241 | 242 | return true; 243 | } 244 | 245 | bytearray Object::ExtractToMemory() const 246 | { 247 | MemoryBuffer buf; 248 | 249 | ExtractToFile(&buf); 250 | 251 | return buf.data(); 252 | } 253 | 254 | const bytearray &Object::GetFileHeader() const 255 | { 256 | return data_.at(0); 257 | } 258 | 259 | bytearray Object::GetFileBody() const 260 | { 261 | bytearray b; 262 | 263 | for (size_t i=1; iHasChildren()) { 300 | s += 16; 301 | 302 | for (size_t i = 0; i < this->GetChildCount(); i++) { 303 | s += static_cast(this->GetChildAt(i))->CalculateMaximumDiskSize(); 304 | } 305 | } 306 | 307 | return s; 308 | } 309 | 310 | Object *Object::FindSubObjectWithID(uint32_t id) 311 | { 312 | if (this->id() == id) { 313 | return this; 314 | } 315 | 316 | for (Children::const_iterator it=GetChildren().begin(); it!=GetChildren().end(); it++) { 317 | if (Object *o = static_cast(*it)->FindSubObjectWithID(id)) { 318 | return o; 319 | } 320 | } 321 | 322 | return NULL; 323 | } 324 | 325 | } 326 | -------------------------------------------------------------------------------- /lib/object.h: -------------------------------------------------------------------------------- 1 | #ifndef OBJECT_H 2 | #define OBJECT_H 3 | 4 | #include "core.h" 5 | #include "sitypes.h" 6 | #include "types.h" 7 | 8 | namespace si { 9 | 10 | class Object : public Core 11 | { 12 | public: 13 | typedef std::vector ChunkedData; 14 | 15 | Object(); 16 | 17 | #if defined(_WIN32) 18 | LIBWEAVER_EXPORT bool ReplaceWithFile(const wchar_t *f); 19 | LIBWEAVER_EXPORT bool ExtractToFile(const wchar_t *f) const; 20 | #endif 21 | 22 | LIBWEAVER_EXPORT bool ReplaceWithFile(const char *f); 23 | LIBWEAVER_EXPORT bool ExtractToFile(const char *f) const; 24 | 25 | LIBWEAVER_EXPORT bool ReplaceWithFile(FileBase *f); 26 | LIBWEAVER_EXPORT bool ExtractToFile(FileBase *f) const; 27 | 28 | LIBWEAVER_EXPORT bytearray ExtractToMemory() const; 29 | 30 | LIBWEAVER_EXPORT const bytearray &GetFileHeader() const; 31 | LIBWEAVER_EXPORT bytearray GetFileBody() const; 32 | LIBWEAVER_EXPORT size_t GetFileBodySize() const; 33 | 34 | const MxOb::Type &type() const { return type_; } 35 | const MxOb::FileType &filetype() const { return filetype_; } 36 | const uint32_t &id() const { return id_; } 37 | const std::string &name() const { return name_; } 38 | const std::string &filename() const { return filename_; } 39 | const ChunkedData &data() const { return data_; } 40 | 41 | size_t CalculateMaximumDiskSize() const; 42 | 43 | Object *FindSubObjectWithID(uint32_t id); 44 | 45 | MxOb::Type type_; 46 | std::string presenter_; 47 | uint32_t unknown1_; 48 | std::string name_; 49 | uint32_t id_; 50 | uint32_t flags_; 51 | uint32_t unknown4_; 52 | uint32_t duration_; 53 | uint32_t loops_; 54 | Vector3 location_; 55 | Vector3 direction_; 56 | Vector3 up_; 57 | bytearray extra_; 58 | std::string filename_; 59 | uint32_t unknown26_; 60 | uint32_t unknown27_; 61 | uint32_t unknown28_; 62 | MxOb::FileType filetype_; 63 | uint32_t unknown29_; 64 | uint32_t unknown30_; 65 | uint32_t volume_; 66 | 67 | uint32_t time_offset_; 68 | 69 | ChunkedData data_; 70 | 71 | private: 72 | 73 | }; 74 | 75 | } 76 | 77 | #endif // OBJECT_H 78 | -------------------------------------------------------------------------------- /lib/othertypes.h: -------------------------------------------------------------------------------- 1 | #ifndef OTHERTYPES_H 2 | #define OTHERTYPES_H 3 | 4 | #include "types.h" 5 | 6 | namespace si { 7 | 8 | class WAVFmt 9 | { 10 | public: 11 | // Standard WAV header 12 | uint16_t Format; 13 | uint16_t Channels; 14 | uint32_t SampleRate; 15 | uint32_t ByteRate; 16 | uint16_t BlockAlign; 17 | uint16_t BitsPerSample; 18 | 19 | // Mindscape extensions (not confirmed yet) 20 | uint32_t DataSize; 21 | uint32_t Flags; 22 | }; 23 | 24 | // Copied from https://www.compuphase.com/flic.htm#FLICHEADER 25 | class FLIC 26 | { 27 | public: 28 | uint32_t size; // Size of FLIC including this headerdesc << " 29 | uint16_t type; // File type 0xAF11, 0xAF12, 0xAF30, 0xAF44, ...desc << " 30 | uint16_t frames; // Number of frames in first segmentdesc << " 31 | uint16_t width; // FLIC width in pixelsdesc << " 32 | uint16_t height; // FLIC height in pixelsdesc << " 33 | uint16_t depth; // Bits per pixel (usually 8)desc << " 34 | uint16_t flags; // Set to zero or to threedesc << " 35 | uint32_t speed; // Delay between framesdesc << " 36 | uint16_t reserved1; // Set to zerodesc << " 37 | uint32_t created; // Date of FLIC creation (FLC only)desc << " 38 | uint32_t creator; // Serial number or compiler id (FLC only)desc << " 39 | uint32_t updated; // Date of FLIC update (FLC only)desc << " 40 | uint32_t updater; // Serial number (FLC only), see creatordesc << " 41 | uint16_t aspect_dx; // Width of square rectangle (FLC only)desc << " 42 | uint16_t aspect_dy; // Height of square rectangle (FLC only)desc << " 43 | uint16_t ext_flags; // EGI: flags for specific EGI extensionsdesc << " 44 | uint16_t keyframes; // EGI: key-image frequencydesc << " 45 | uint16_t totalframes; // EGI: total number of frames (segments)desc << " 46 | uint32_t req_memory; // EGI: maximum chunk size (uncompressed)desc << " 47 | uint16_t max_regions; // EGI: max. number of regions in a CHK_REGION chunkdesc << " 48 | uint16_t transp_num; // EGI: number of transparent levelsdesc << " 49 | uint8_t reserved2[24]; // Set to zerodesc << " 50 | uint32_t oframe1; // Offset to frame 1 (FLC only)desc << " 51 | uint32_t oframe2; // Offset to frame 2 (FLC only)desc << " 52 | uint8_t reserved3[40]; // Set to zerodesc << " 53 | }; 54 | 55 | class FLICFrame 56 | { 57 | public: 58 | uint32_t size; // Size of the chunk, including subchunks 59 | uint16_t type; // Chunk type: 0xF1FA 60 | uint16_t chunks; // Number of subchunks 61 | uint16_t delay; // Delay in milliseconds 62 | int16_t reserved; // Always zero 63 | uint16_t width; // Frame width override (if non-zero) 64 | uint16_t height; // Frame height override (if non-zero) 65 | }; 66 | 67 | // Copied from https://wiki.multimedia.cx/index.php/Smacker#Header 68 | class SMK2 69 | { 70 | public: 71 | uint32_t Signature; 72 | uint32_t Width; 73 | uint32_t Height; 74 | uint32_t Frames; 75 | uint32_t FrameRate; 76 | uint32_t Flags; 77 | uint32_t AudioSize[7]; 78 | uint32_t TreesSize; 79 | uint32_t MMap_Size; 80 | uint32_t MClr_Size; 81 | uint32_t Full_Size; 82 | uint32_t Type_Size; 83 | uint32_t AudioRate[7]; 84 | uint32_t Dummy; 85 | }; 86 | 87 | // Analogous to BITMAPFILEHEADER, copied from http://www.ece.ualberta.ca/~elliott/ee552/studentAppNotes/2003_w/misc/bmp_file_format/bmp_file_format.htm 88 | LIBWEAVER_PACK(class BMP 89 | { 90 | public: 91 | uint16_t Signature; // Should always be BM 92 | uint32_t FileSize; // Size of total file including header and 'BM' 93 | uint32_t Reserved; // Unused (always 0) 94 | uint32_t DataOffset; // Offset of actual data after BITMAPINFOHEADER 95 | }); 96 | 97 | } 98 | 99 | #endif // OTHERTYPES_H 100 | -------------------------------------------------------------------------------- /lib/sitypes.cpp: -------------------------------------------------------------------------------- 1 | #include "sitypes.h" 2 | 3 | #include "util.h" 4 | 5 | namespace si { 6 | 7 | const char *MxOb::GetTypeName(Type type) 8 | { 9 | switch (type) { 10 | case Video: 11 | return "SMK"; 12 | case Sound: 13 | return "WAV"; 14 | case Presenter: 15 | return "MxPresenter"; 16 | case Bitmap: 17 | return "BMP"; 18 | case Object: 19 | return "3D Object"; 20 | case World: 21 | return "World"; 22 | case Event: 23 | return "Event"; 24 | case Animation: 25 | return "Animation"; 26 | case Null: 27 | case TYPE_COUNT: 28 | break; 29 | } 30 | 31 | return "Unknown"; 32 | } 33 | 34 | std::vector MxOb::GetFlagsName(Flags flags) 35 | { 36 | std::vector names; 37 | 38 | if (flags == FLAGS_COUNT) { 39 | return names; 40 | } 41 | 42 | if (flags & Transparent) { 43 | names.push_back("Transparent"); 44 | } 45 | if (flags & NoLoop) { 46 | names.push_back("NoLoop"); 47 | } 48 | if (flags & LoopCache) { 49 | names.push_back("LoopCache"); 50 | } 51 | if (flags & LoopStream) { 52 | names.push_back("LoopStream"); 53 | } 54 | if (flags & Unknown) { 55 | names.push_back("Unknown"); 56 | } 57 | 58 | return names; 59 | } 60 | 61 | const char *RIFF::GetTypeDescription(Type t) 62 | { 63 | switch (t) { 64 | case RIFF_: 65 | return "Resource Interchange File Format"; 66 | case LIST: 67 | return "List of sub-elements"; 68 | case MxSt: 69 | return "Stream"; 70 | case MxHd: 71 | return "Interleaf Header"; 72 | case MxCh: 73 | return "Data Chunk"; 74 | case MxOf: 75 | return "Offset Table"; 76 | case pad_: 77 | return "Padding"; 78 | case MxOb: 79 | return "Streamable Object"; 80 | case MxDa: 81 | return "Data"; 82 | case WAVE: 83 | return "WAVE"; 84 | case fmt_: 85 | return "WAVE Format"; 86 | case OMNI: 87 | return "OMNI"; 88 | case data: 89 | return "WAVE Data"; 90 | } 91 | 92 | return "Unknown"; 93 | } 94 | 95 | RIFF::Chk RIFF::BeginChunk(FileBase *f, uint32_t type) 96 | { 97 | Chk stat; 98 | 99 | f->WriteU32(type); 100 | stat.size_position = f->pos(); 101 | f->WriteU32(0); 102 | stat.data_start = f->pos(); 103 | 104 | return stat; 105 | } 106 | 107 | void RIFF::EndChunk(FileBase *f, const Chk &stat) 108 | { 109 | size_t now = f->pos(); 110 | 111 | uint32_t sz = now - stat.data_start; 112 | 113 | f->seek(stat.size_position); 114 | f->WriteU32(sz); 115 | 116 | f->seek(now); 117 | 118 | if (sz%2 == 1) { 119 | f->WriteU8(0); 120 | } 121 | } 122 | 123 | } 124 | -------------------------------------------------------------------------------- /lib/sitypes.h: -------------------------------------------------------------------------------- 1 | #ifndef SI_H 2 | #define SI_H 3 | 4 | #include 5 | 6 | #include "file.h" 7 | #include "types.h" 8 | 9 | namespace si { 10 | 11 | /** 12 | * @brief RIFF chunk type 13 | * 14 | * Name | Size | Type | Description 15 | * -------- | -------- | -------- | ----------- 16 | * Format | 4 | u32 | 4-byte ASCII identifier for what type of RIFF this is (usually 'OMNI' in the case of LEGO Island) 17 | */ 18 | class RIFF 19 | { 20 | public: 21 | enum Type { 22 | RIFF_ = 0x46464952, 23 | LIST = 0x5453494c, 24 | MxSt = 0x7453784d, 25 | MxHd = 0x6448784d, 26 | MxCh = 0x6843784d, 27 | MxOf = 0x664f784d, 28 | MxOb = 0x624f784d, 29 | MxDa = 0x6144784d, 30 | pad_ = 0x20646170, 31 | OMNI = 0x494e4d4f, 32 | WAVE = 0x45564157, 33 | fmt_ = 0x20746D66, 34 | data = 0x61746164 35 | }; 36 | 37 | struct Chk 38 | { 39 | size_t size_position; 40 | size_t data_start; 41 | }; 42 | 43 | static Chk BeginChunk(FileBase *f, uint32_t type); 44 | static void EndChunk(FileBase *f, const Chk &stat); 45 | 46 | static inline std::string PrintU32AsString(uint32_t u) 47 | { 48 | return std::string((const char *) &u, sizeof(u)); 49 | } 50 | 51 | LIBWEAVER_EXPORT static const char *GetTypeDescription(Type t); 52 | 53 | }; 54 | 55 | /** 56 | * @brief LIST chunk type 57 | * 58 | * Name | Size | Type | Description 59 | * -------- | -------- | -------- | ----------- 60 | * Format | 4 | u32 | 4-byte ASCII identifier for what type of LIST this is. 61 | * Count | 4 | u32 | (Optional) for 'MxCh' type LISTs, the number of elements in this list. 62 | */ 63 | class LIST : public RIFF 64 | { 65 | public: 66 | enum Variation { 67 | Act_ = 0x00746341, 68 | RAND = 0x444e4152 69 | }; 70 | }; 71 | 72 | /** 73 | * @brief MxHd chunk type 74 | * 75 | * Name | Size | Type | Description 76 | * ----------- | -------- | -------- | ----------- 77 | * Version | 4 | u32 | Version of this SI file stored as two packed 16-bit words, the high word being the major version and the low word being the minor version. 78 | * BufferSize | 4 | u32 | The amount of data to read from disk at a time. 79 | * BufferCount | 4 | u32 | FIXME: Currently not understood what this field does. 80 | */ 81 | class MxHd : public RIFF 82 | { 83 | public: 84 | }; 85 | 86 | /** 87 | * @brief MxSt chunk type 88 | * 89 | * MxSt is a container type only, it has none of its own members. 90 | */ 91 | class MxSt : public RIFF 92 | { 93 | public: 94 | }; 95 | 96 | /** 97 | * @brief MxCh chunk type 98 | * 99 | * Name | Size | Type | Description 100 | * ---------- | -------- | --------- | ----------- 101 | * Flags | 2 | u16 | Flags determining the behavior of this chunk. 102 | * Object | 4 | u32 | ID of the MxOb that this chunk belongs to. 103 | * Time | 4 | u32 | Time in milliseconds that this chunk's data should be presented at. 104 | * DataSize | 4 | u32 | Size of the data in this chunk. 105 | * Data | DataSize | bytearray | Actual data in chunk. 106 | */ 107 | class MxCh : public RIFF 108 | { 109 | public: 110 | enum Flag { 111 | FLAG_SPLIT = 0x10, 112 | FLAG_END = 0x2 113 | }; 114 | 115 | static const uint32_t HEADER_SIZE = 14; 116 | }; 117 | 118 | /** 119 | * @brief MxOf chunk type 120 | * 121 | * Name | Size | Type | Description 122 | * ---------- | -------- | ---------------- | ----------- 123 | * Count | 4 | u32 | Number of objects in this list. Not necessarily the number of offsets, as one offset may point to an object with multiple sub-objects. 124 | * Offsets | Variable | bytearray/u32[] | List of 4-byte file offsets where objects begin. 125 | */ 126 | class MxOf : public RIFF 127 | { 128 | public: 129 | }; 130 | 131 | /** 132 | * @brief pad_ chunk type 133 | * 134 | * Denotes padding to optimize disc reads. Contains no useful information, 135 | * customarily filled with the byte 0xCD. 136 | */ 137 | class pad_ : public RIFF 138 | { 139 | public: 140 | }; 141 | 142 | /** 143 | * @brief MxOb chunk type 144 | * 145 | * Name | Size | Type | Description 146 | * ----------- | -------- | ---------------- | ----------- 147 | * Type | 2 | u16 | Type of object (member of MxOb::Type enum) 148 | * Presenter | Variable | string | Null-terminated string identifying the presenter to use (if type is set to `Presenter`) 149 | * Unknown1 | 4 | u32 | 150 | * Name | Variable | string | Null-terminated string identifying object's name 151 | * ID | 4 | u32 | Unique object identifier within file (used to differentiate interleaved MxChs) 152 | * Flags | 4 | u32 | Flags of object (member of MxOb::Flags enum) 153 | * Unknown4 | 4 | u32 | Similar to Duration, but only used for Lego3DWavePresenter 154 | * Duration | 4 | u32 | Duration in milliseconds * Loops 155 | * Loops | 4 | u32 | 156 | * Position | 24 | Vector3 | Position 157 | * Direction | 24 | Vector3 | Direction to look towards 158 | * Up | 24 | Vector3 | Up vector 159 | * ExtraLength | 2 | u16 | 160 | * ExtraData | ExtraLength | bytearray | 161 | * FileName | Variable | string | Original filename of the file represented by this object. 162 | * Unknown26 | 4 | u32 | 163 | * Unknown27 | 4 | u32 | 164 | * Unknown28 | 4 | u32 | 165 | * FileType | 4 | u32 | 4-byte ASCII ID for the file type 166 | * Unknown29 | 4 | u32 | 167 | * Unknown30 | 4 | u32 | 168 | * Volume | 4 | u32 | Only populated for WAV files. Audio volume from 0 - 79. 169 | */ 170 | class MxOb : public RIFF 171 | { 172 | public: 173 | enum Type 174 | { 175 | /// Not an MxOb type, this is our identifier for an object that is in the TOC but doesn't 176 | /// actually exist 177 | Null = -1, 178 | 179 | /// Video 180 | Video = 0x03, 181 | 182 | /// Audio 183 | Sound = 0x04, 184 | 185 | /// World object for LegoWorldPresenter 186 | World = 0x06, 187 | 188 | /// Custom MxPresenter 189 | Presenter = 0x07, 190 | 191 | /// Event 192 | Event = 0x08, 193 | 194 | /// Animation 195 | Animation = 0x09, 196 | 197 | /// Bitmap image 198 | Bitmap = 0x0A, 199 | 200 | /// 3D Object 201 | Object = 0x0B, 202 | 203 | /// Total number of types (not a real type) 204 | TYPE_COUNT 205 | }; 206 | 207 | enum Flags 208 | { 209 | /// Object loops via cache (i.e. hard disk) 210 | LoopCache = 0x01, 211 | 212 | /// Object does not loop 213 | NoLoop = 0x02, 214 | 215 | /// Object loops via stream (i.e. CD-ROM) 216 | LoopStream = 0x04, 217 | 218 | /// Object is transparent 219 | Transparent = 0x08, 220 | 221 | /// Unknown flag, but set by every object thus far 222 | Unknown = 0x20, 223 | 224 | /// Total number of flags (not a real type) 225 | FLAGS_COUNT, 226 | }; 227 | 228 | enum FileType 229 | { 230 | /// WAVE audio 231 | WAV = 0x56415720, 232 | 233 | /// Bitmap image 234 | STL = 0x4C545320, 235 | 236 | /// FLIC animation 237 | FLC = 0x434c4620, 238 | 239 | /// SMK video 240 | SMK = 0x4b4d5320, 241 | 242 | /// 3D Object 243 | OBJ = 0x4a424f20, 244 | }; 245 | 246 | // FIXME: sitypes.h probably won't be part of the public API, so this should 247 | // probably be moved 248 | LIBWEAVER_EXPORT static const char *GetTypeName(Type type); 249 | LIBWEAVER_EXPORT static std::vector GetFlagsName(Flags flags); 250 | 251 | static const int MAXIMUM_VOLUME = 79; 252 | 253 | }; 254 | 255 | } 256 | 257 | #endif // SI_H 258 | -------------------------------------------------------------------------------- /lib/types.h: -------------------------------------------------------------------------------- 1 | #ifndef TYPES_H 2 | #define TYPES_H 3 | 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | #include 11 | #include 12 | 13 | #if defined(__GNUC__) 14 | #define LIBWEAVER_PACK( __Declaration__ ) __Declaration__ __attribute__((__packed__)) 15 | #elif defined(_MSC_VER) 16 | #define LIBWEAVER_PACK( __Declaration__ ) __pragma( pack(push, 1) ) __Declaration__ __pragma( pack(pop)) 17 | #endif 18 | 19 | #ifdef _MSC_VER 20 | #define LIBWEAVER_EXPORT __declspec(dllexport) 21 | #else 22 | #define LIBWEAVER_EXPORT 23 | #endif 24 | 25 | #if defined(_WIN32) 26 | #define LIBWEAVER_OS_WINDOWS 27 | #elif defined(__APPLE__) 28 | #define LIBWEAVER_OS_MACOS 29 | #elif defined(__linux__) 30 | #define LIBWEAVER_OS_LINUX 31 | #endif 32 | 33 | #if defined(_MSC_VER) && (_MSC_VER < 1600) 34 | // Declare types for MSVC versions less than 2010 (1600) which lacked a stdint.h 35 | typedef unsigned char uint8_t; 36 | typedef char int8_t; 37 | typedef unsigned short uint16_t; 38 | typedef short int16_t; 39 | typedef unsigned int uint32_t; 40 | typedef int int32_t; 41 | typedef unsigned __int64 uint64_t; 42 | typedef __int64 int64_t; 43 | #else 44 | #include 45 | #endif 46 | 47 | namespace si { 48 | 49 | class bytearray : public std::vector 50 | { 51 | public: 52 | bytearray(){} 53 | bytearray(size_t size) 54 | { 55 | resize(size); 56 | } 57 | bytearray(const char *data, size_t size) 58 | { 59 | resize(size); 60 | memcpy(this->data(), data, size); 61 | } 62 | 63 | template 64 | T *cast() { return reinterpret_cast(data()); } 65 | 66 | template 67 | const T *cast() const { return reinterpret_cast(data()); } 68 | 69 | void append(const char *data, size_t size) 70 | { 71 | size_t current = this->size(); 72 | this->resize(current + size); 73 | memcpy(this->data() + current, data, size); 74 | } 75 | 76 | void append(const bytearray &other) 77 | { 78 | size_t current = this->size(); 79 | this->resize(current + other.size()); 80 | memcpy(this->data() + current, other.data(), other.size()); 81 | } 82 | 83 | void fill(char c) 84 | { 85 | memset(this->data(), c, this->size()); 86 | } 87 | 88 | bytearray left(size_t sz) const 89 | { 90 | bytearray b(std::min(sz, this->size())); 91 | memcpy(b.data(), this->data(), b.size()); 92 | return b; 93 | } 94 | 95 | bytearray mid(size_t i, size_t size = 0) const 96 | { 97 | if (i >= this->size()) { 98 | return bytearray(); 99 | } 100 | 101 | size_t target = this->size() - i; 102 | if (size != 0) { 103 | target = std::min(target, size); 104 | } 105 | 106 | bytearray b(target); 107 | memcpy(b.data(), this->data() + i, b.size()); 108 | return b; 109 | } 110 | 111 | bytearray right(size_t i) const 112 | { 113 | if (i >= size()) { 114 | return *this; 115 | } 116 | 117 | bytearray b(i); 118 | memcpy(b.data(), this->data() + this->size() - i, b.size()); 119 | return b; 120 | } 121 | 122 | }; 123 | 124 | class Vector3 125 | { 126 | public: 127 | Vector3(){} 128 | Vector3(double ix, double iy, double iz) 129 | { 130 | x = ix; 131 | y = iy; 132 | z = iz; 133 | } 134 | 135 | double x; 136 | double y; 137 | double z; 138 | }; 139 | 140 | class Data 141 | { 142 | public: 143 | inline Data() 144 | { 145 | data_.resize(sizeof(uint32_t)); 146 | memset(data_.data(), 0, data_.size()); 147 | } 148 | 149 | inline Data(const uint32_t &u) { set(u); } 150 | inline Data(const Vector3 &u) { set(u); } 151 | inline Data(const bytearray &u) { set(u); } 152 | inline Data(const std::string &u) 153 | { 154 | data_.resize(u.size()); 155 | memcpy(data_.data(), u.data(), u.size()); 156 | } 157 | 158 | inline operator uint32_t() const { return toU32(); } 159 | inline operator const char *() const { return data(); } 160 | inline operator Vector3() const { return toVector3(); } 161 | inline operator bytearray() const { return data_; } 162 | inline operator std::string() const { return toString(); } 163 | 164 | inline uint16_t toU16() const { return *data_.cast(); } 165 | inline int16_t toS16() const { return *data_.cast(); } 166 | inline uint32_t toU32() const { return *data_.cast(); } 167 | inline int32_t toS32() const { return *data_.cast(); } 168 | inline Vector3 toVector3() const { return *data_.cast(); } 169 | inline const char *data() const { return data_.data(); }; 170 | inline char *data() { return data_.data(); }; 171 | inline const char *c_str() const { return this->data(); }; 172 | inline size_t size() const { return data_.size(); } 173 | inline const std::string toString() const 174 | { 175 | if (data_.empty()) { 176 | return std::string(); 177 | } else { 178 | // Subtract 1 from size, assuming the last character is a null terminator 179 | return std::string(data_.data(), std::max(size_t(0), data_.size()-1)); 180 | } 181 | } 182 | 183 | inline bool operator==(int u) const 184 | { 185 | return get() == u; 186 | } 187 | 188 | inline bool operator==(uint32_t u) const 189 | { 190 | return get() == u; 191 | } 192 | 193 | template 194 | inline const T &get() const 195 | { 196 | return *data_.cast(); 197 | } 198 | 199 | template 200 | inline void set(const T &value) 201 | { 202 | data_.resize(sizeof(T)); 203 | memcpy(data_.data(), &value, sizeof(T)); 204 | } 205 | 206 | inline void set(const bytearray &value) { data_ = value; } 207 | 208 | private: 209 | bytearray data_; 210 | 211 | }; 212 | 213 | } 214 | 215 | #endif // TYPES_H 216 | -------------------------------------------------------------------------------- /lib/util.h: -------------------------------------------------------------------------------- 1 | #ifndef UTIL_H 2 | #define UTIL_H 3 | 4 | #include 5 | #include 6 | 7 | #include "types.h" 8 | 9 | namespace si { 10 | 11 | inline std::ostream &LogDebug() 12 | { 13 | return std::cout << "[DEBUG] "; 14 | } 15 | 16 | inline std::ostream &LogWarning() 17 | { 18 | return std::cerr << "[WARNING] "; 19 | } 20 | 21 | inline std::ostream &LogError() 22 | { 23 | return std::cerr << "[ERROR] "; 24 | } 25 | 26 | } 27 | 28 | #endif // UTIL_H 29 | -------------------------------------------------------------------------------- /packaging/screenshot.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/isledecomp/SIEdit/8889908214f00b71ff724d73b3c787720a8482fb/packaging/screenshot.png --------------------------------------------------------------------------------