├── .github └── workflows │ └── tests.yml ├── AMIA 2016 Presentation_ QCT-Parse.pdf ├── LICENSE ├── README.md ├── docs ├── Makefile ├── conf.py ├── development.md ├── index.rst ├── make.bat └── readme.rst ├── pyproject.toml ├── qct_parse ├── __init__.py ├── makeqctoolsreport.py ├── overcatch.py ├── qct-parse_10bit_config.txt ├── qct-parse_8bit_config.txt └── qct_parse.py ├── requirements.txt └── tests └── test_qct_parse.py /.github/workflows/tests.yml: -------------------------------------------------------------------------------- 1 | on: [push, pull_request] 2 | name: Supported Python Compatibility Test 3 | jobs: 4 | build: 5 | runs-on: ${{ matrix.os }} 6 | strategy: 7 | matrix: 8 | os: [ubuntu-latest, macos-latest, windows-2019] 9 | python-version: ['3.9', '3.10', '3.11', '3.12', '3.13'] 10 | include: 11 | - os: macos-latest 12 | - os: ubuntu-latest 13 | - os: windows-2019 14 | fail-fast: false 15 | name: Python ${{ matrix.python-version }} ${{ matrix.os }} build 16 | steps: 17 | - uses: actions/checkout@v4 18 | - uses: actions/setup-python@v5 19 | with: 20 | python-version: ${{ matrix.python-version }} 21 | cache: 'pip' # caching pip dependencies 22 | - name: Install requirements 23 | run: | 24 | pip install tox 25 | - uses: actions/github-script@v7 26 | id: tox-env 27 | with: 28 | result-encoding: string 29 | script: | 30 | const frontend = "${{matrix.frontend}}" 31 | const toxEnv = "py${{matrix.python-version}}".replace('.','') 32 | if(frontend === ""){ 33 | return toxEnv 34 | } 35 | return "py${{matrix.python-version}}".replace('.','') + "-${{matrix.frontend}}" 36 | - name: Run tox 37 | run: tox -e ${{ steps.tox-env.outputs.result }} 38 | -------------------------------------------------------------------------------- /AMIA 2016 Presentation_ QCT-Parse.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/amiaopensource/qct-parse/4753dc8d56c7fc226fb088ccc8d25ea6e7570951/AMIA 2016 Presentation_ QCT-Parse.pdf -------------------------------------------------------------------------------- /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 | {one line to give the program's name and a brief idea of what it does.} 635 | Copyright (C) {year} {name of author} 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 | {project} Copyright (C) {year} {fullname} 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 | 2 | # QCTools Automation Scripts 3 | 4 | This repository contains scripts for automating analysis of QCTools reports. 5 | 6 | ## Overview 7 | 8 | ### Install from source: 9 | 10 | * Create a new Python Virtual Environment for qct_parse 11 | * Unix based (Mac or Linux): 12 | `python3 -m venv name_of_env` 13 | * Windows: 14 | `py -m venv name_of_env` 15 | (where 'name_of_env' is replaced with the name of your virtual environment) 16 | * Activate virtual env 17 | * Unix based (Mac or Linux): 18 | `source ./name_of_env/bin/activate` 19 | * Windows: 20 | `name_of_env\scripts\activate` 21 | * Install Package 22 | * Navigate to the repo root directory `path/to/qct-parse/` 23 | * Run the command: 24 | `python -m pip install .` 25 | 26 | ### Test Code 27 | 28 | If you intend to develop the code for your proposes or contribute to the open source project, a test directory is provided in the repo. 29 | * Activate virtual env (see Install from source) 30 | * Install pytest 31 | `pip install pytest` 32 | * Run tests 33 | `python -m pytest` 34 | 35 | ### Building the documentation 36 | * Activate virtual env (see Install from source) 37 | * Install sphinx and myst-parser 38 | `pip install sphinx myst-parser` 39 | * Run sphinx-build command 40 | `sphinx-build ./docs ./dist/docs` 41 | 42 | 43 | ### Commands: 44 | 45 | - **`qct-parse -i/--input [path to QCTools report] [optional arguments]`** 46 | Finds frames that exceed thresholds for QCTool tag(s). Full list of command line arguments below. 47 | 48 | --- 49 | 50 | # `qct-parse` 51 | 52 | Run a single tag against a supplied value or multiple tags using a profile. 53 | 54 | ## Arguments 55 | 56 | | Argument | Description | 57 | |-----------------------------|-------------------------------------------------------------------------------------------------------| 58 | | `-h`, `--help` | Show this help message and exit | 59 | | `-i`, `--input` | Path to the input `qctools.xml.gz` or `qctools.mkv` file | 60 | | `-t`, `--tagname` | The tag name you want to test (e.g., `SATMAX`); see table of tag names below for list | 61 | | `-o`, `--over` | Threshold overage number | 62 | | `-u`, `--under` | Threshold under number | 63 | | `-p`, `--profile` | Compare frame data against tag values from `config.txt`. Use `-p default` for QCTools default values | 64 | | `-buff`, `--buffSize` | Circular buffer size. If even, defaults to the next odd number (default: 11) | 65 | | `-te`, `--thumbExport` | Enable/disable thumbnail export (default: off) | 66 | | `-ted`, `--thumbExportDelay`| Minimum frames between exported thumbnails (default: 9000) | 67 | | `-tep`, `--thumbExportPath` | Path to thumbnail export. Uses input base-path if omitted | 68 | | `-ds`, `--durationStart` | Start analysis from this time (seconds, equivalent to ffmpeg `-ss`) | 69 | | `-de`, `--durationEnd` | End analysis after this time (seconds, equivalent to ffmpeg `-t`) | 70 | | `-bd`, `--barsDetection` | Enable/disable bar detection (default: off) | 71 | | `-be`, `--barsEvaluation` | Use peak values from color bars as 'profile' if bars are detected | 72 | | `-pr`, `--print` | Print over/under frame data to console (default: off) | 73 | | `-csv`, `--csvreport` | Print summary results to a csv sidecar file | 74 | | `-q`, `--quiet` | Suppress ffmpeg output in console (default: off) | 75 | 76 | ## Tags 77 | 78 | | Tag category | Tag names | 79 | |-----------------------------|-------------------------------------------------------------------------------------------------------| 80 | | [YUV values](https://bavc.github.io/qctools/filter_descriptions.html#yuv) | `YMIN,YLOW,YAVG,YHIGH,YMAX`
`UMIN,ULOW,UAVG,UHIGH,UMAX`
`VMIN,VLOW,VAVG,VHIGH,VMAX` | 81 | | [YUV values (difference)](https://bavc.github.io/qctools/filter_descriptions.html#diff) | `YDIF,UDIF,VDIF` | 82 | | [Saturation values](https://bavc.github.io/qctools/filter_descriptions.html#saturation) | `SATMIN,SATLOW,SATAVG,SATHIGH,SATMAX` | 83 | | [Hue values](https://bavc.github.io/qctools/filter_descriptions.html#hue) | `HUEMED,HUEAVG` | 84 | | [Temporal outliers](https://bavc.github.io/qctools/filter_descriptions.html#tout) | `TOUT` | 85 | | [Vertical line repetitions](https://bavc.github.io/qctools/filter_descriptions.html#vrep) | `VREP` | 86 | | [Broadcast range](https://bavc.github.io/qctools/filter_descriptions.html#brng) | `BRNG` | 87 | | [Mean square error fields](https://bavc.github.io/qctools/filter_descriptions.html#msef) | `mse_y,mse_u,mse_v,mse_avg` | 88 | | [Peak signal to noise ratio fields](https://bavc.github.io/qctools/filter_descriptions.html#psnrf) | `psnr_y,psnr_u,psnr_v,psnr_avg` | 89 | 90 | ## Examples 91 | 92 | ### Run single tag tests 93 | ```bash 94 | qct-parse -t SATMAX -o 235 -t YMIN -u 16 -i /path/to/report.mkv.qctools.xml.gz 95 | ``` 96 | 97 | ### Run bars detection using default QCTools profile 98 | ```bash 99 | qct-parse -bd -p default -i /path/to/report.mkv.qctools.mkv 100 | ``` 101 | 102 | ### Export thumbnails of frames beyond threshold 103 | ```bash 104 | qct-parse -p default -te -tep /path/to/export/folder -i /path/to/report.mkv.qctools.xml.gz 105 | ``` 106 | 107 | ### Use peak values from detected color bars as thresholds 108 | ```bash 109 | qct-parse -bd -be -i /path/to/report.mkv.qctools.xml.gz 110 | ``` 111 | 112 | ## Input files 113 | 114 | qct-parse.py will work with the following QCTools report formats: 115 | ``` 116 | qctools.xml.gz 117 | qctools.mkv 118 | ``` 119 | 120 | If the qctools.xml.gz report is in an MKV attachment, the qctools.xml.gz report file will be extracted and saved as a separate file. 121 | 122 | Both 8-bit and 10-bit values are supported. The bit depth will be detected automatically, and does not need to be specified. 123 | 124 | ## Config Files 125 | 126 | The provided profiles are: 127 | * default 128 | * highTolerance 129 | * midTolerance 130 | * lowTolerance 131 | 132 | Each of these profiles contain the following tags with a corresponding threshold: 133 | `YLOW, YMAX, UMIN, UMAX, VMIN, VMAX, SATMAX, TOUT, VREP` 134 | 135 | The profiles are stored in the config.txt files. Please note that there is a separate config.txt for 8-bit and 10-bit values. 136 | 137 | The process for providing user supplied profiles is in development. 138 | Currently, if you wish to create your own profile, you will need to create your own config directory and `config.txt` file. 139 | There is a environmental variable at the top of qct-parse.py which can be used to reset the config directory: 140 | ```bash 141 | CONFIG_ENVIRONMENT_VARIABLE_NAME = 'QCT_PARSE_CONFIG_DIRECTORY' 142 | ``` 143 | Simply place the full path to the user created config *directory* in place of 'QCT_PARSE_CONFIG_DIRECTORY' 144 | 145 | ## Thumbnails 146 | 147 | Thumbnails of failed frames will be exported if the `-te` flag is invoked. 148 | 149 | In order to export thumbnails, the QCTools report must be in the same directory as the video file it is describing, and must have the same file name as the report (excluding the `qctools.xml.gz`). 150 | 151 | If you would like to provide a path for exporting thumbnails, you can do so using the `-tep` flag. 152 | Otherwise, thumbnails will automatically be created in the same directory as the video file and QCTools report, in a new directory. 153 | 154 | When running qct-parse with a profile, the thumbnails will be placed in a directory named `ThumbExports`. 155 | When run against single tags the directory will be named [TAG NAME].[THRESHOLD] 156 | 157 | ## Logging 158 | 159 | A log file is created with the same name as the input file but with a '.log' extension. 160 | For example: `some_video_file.mkv.qctools.xml.gz.log` 161 | 162 | Log files contain every instance of values over the specified threshold. For example: 163 | `2024-10-03 17:02:35,737 SATMAX is over 181.02 with a value of 698.0 at duration 00:00:16.4500` 164 | 165 | --- 166 | 167 | ### Legacy Commands: 168 | 169 | Not in active development. Please file an issue if you are interested in using these. 170 | 171 | #### `makeqctoolsreport` 172 | 173 | A Python port of Morgan’s [makeqctoolsreport.as](https://github.com/iamdamosuzuki/QCToolsReport), this script generates QCTools `.xml.gz` reports from input video files. 174 | 175 | Example Usage: 176 | ```bash 177 | makeqctoolsreport /path/to/input.mxf 178 | ``` 179 | 180 | #### `overcatch` 181 | 182 | A script from the original qct-parse development for running a report against multiple profiles. 183 | 184 | Example Usage: 185 | ```bash 186 | overcatch /path/to/input.mxf 187 | ``` 188 | 189 | --- 190 | 191 | ## Dependencies 192 | 193 | Ensure Python 3.x.x is installed. 194 | 195 | Requires FFmpeg. 196 | 197 | This tool uses the `lxml` python module which is automatically installed with the qct-parse package. 198 | 199 | For more information on `lxml` usage, check out the [lxml documentation](http://lxml.de/). 200 | 201 | --- 202 | 203 | ## Contributors 204 | 205 | - [@eddycolloton](https://github.com/eddycolloton) 206 | - [@CoatesBrendan](https://github.com/CoatesBrendan) 207 | - [@av_morgan](https://github.com/av_morgan) 208 | 209 | ## Maintainer 210 | 211 | - [@av_morgan](https://github.com/av_morgan) 212 | - [@eddycolloton](https://github.com/eddycolloton) 213 | -------------------------------------------------------------------------------- /docs/Makefile: -------------------------------------------------------------------------------- 1 | # Minimal makefile for Sphinx documentation 2 | # 3 | 4 | # You can set these variables from the command line, and also 5 | # from the environment for the first two. 6 | SPHINXOPTS ?= 7 | SPHINXBUILD ?= sphinx-build 8 | SOURCEDIR = . 9 | BUILDDIR = _build 10 | 11 | # Put it first so that "make" without argument is like "make help". 12 | help: 13 | @$(SPHINXBUILD) -M help "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O) 14 | 15 | .PHONY: help Makefile 16 | 17 | # Catch-all target: route all unknown targets to Sphinx using the new 18 | # "make mode" option. $(O) is meant as a shortcut for $(SPHINXOPTS). 19 | %: Makefile 20 | @$(SPHINXBUILD) -M $@ "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O) 21 | -------------------------------------------------------------------------------- /docs/conf.py: -------------------------------------------------------------------------------- 1 | # Configuration file for the Sphinx documentation builder. 2 | # 3 | # For the full list of built-in configuration values, see the documentation: 4 | # https://www.sphinx-doc.org/en/master/usage/configuration.html 5 | 6 | # -- Project information ----------------------------------------------------- 7 | # https://www.sphinx-doc.org/en/master/usage/configuration.html#project-information 8 | 9 | project = 'qct-parse' 10 | copyright = '2024, AMIA Open-Source' 11 | author = 'AMIA Open-Source' 12 | 13 | # -- General configuration --------------------------------------------------- 14 | # https://www.sphinx-doc.org/en/master/usage/configuration.html#general-configuration 15 | 16 | extensions = ['myst_parser'] 17 | 18 | templates_path = ['_templates'] 19 | exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store'] 20 | 21 | source_suffix = { 22 | '.rst': 'restructuredtext', 23 | '.txt': 'markdown', 24 | '.md': 'markdown', 25 | } 26 | 27 | # -- Options for HTML output ------------------------------------------------- 28 | # https://www.sphinx-doc.org/en/master/usage/configuration.html#options-for-html-output 29 | 30 | html_theme = 'alabaster' 31 | html_static_path = ['_static'] 32 | -------------------------------------------------------------------------------- /docs/development.md: -------------------------------------------------------------------------------- 1 | # Development Information 2 | 3 | ## Configure Development Environment 4 | 5 | * Create a new Python Virtual Environment for qct_parse 6 | * Unix based (Mac or Linux): 7 | `python3 -m venv name_of_env` 8 | * Windows: 9 | `py -m venv name_of_env` 10 | (where 'name_of_env' is replaced with the name of your virtual environment) 11 | * Activate virtual env 12 | * Unix based (Mac or Linux): 13 | `source ./name_of_env/bin/activate` 14 | * Windows: 15 | `name_of_env\scripts\activate` 16 | * Install Package as editable package 17 | * Navigate to the repo root directory `path/to/qct-parse/` 18 | * Run the command: 19 | `python -m pip install -e .` 20 | 21 | ## Run Tests 22 | 23 | If you intend to develop the code for your proposes or contribute to the open source project, a test directory is provided in the repo. 24 | * Activate virtual env (see Configure Development Environment) 25 | * Install pytest 26 | `pip install pytest` 27 | * Run tests 28 | `python -m pytest` 29 | 30 | -------------------------------------------------------------------------------- /docs/index.rst: -------------------------------------------------------------------------------- 1 | .. qct-parse documentation master file, created by 2 | sphinx-quickstart on Tue Dec 3 20:53:22 2024. 3 | You can adapt this file completely to your liking, but it should at least 4 | contain the root `toctree` directive. 5 | 6 | qct-parse documentation 7 | ======================= 8 | 9 | .. toctree:: 10 | :maxdepth: 2 11 | :caption: Contents: 12 | 13 | readme 14 | development 15 | -------------------------------------------------------------------------------- /docs/make.bat: -------------------------------------------------------------------------------- 1 | @ECHO OFF 2 | 3 | pushd %~dp0 4 | 5 | REM Command file for Sphinx documentation 6 | 7 | if "%SPHINXBUILD%" == "" ( 8 | set SPHINXBUILD=sphinx-build 9 | ) 10 | set SOURCEDIR=. 11 | set BUILDDIR=_build 12 | 13 | %SPHINXBUILD% >NUL 2>NUL 14 | if errorlevel 9009 ( 15 | echo. 16 | echo.The 'sphinx-build' command was not found. Make sure you have Sphinx 17 | echo.installed, then set the SPHINXBUILD environment variable to point 18 | echo.to the full path of the 'sphinx-build' executable. Alternatively you 19 | echo.may add the Sphinx directory to PATH. 20 | echo. 21 | echo.If you don't have Sphinx installed, grab it from 22 | echo.https://www.sphinx-doc.org/ 23 | exit /b 1 24 | ) 25 | 26 | if "%1" == "" goto help 27 | 28 | %SPHINXBUILD% -M %1 %SOURCEDIR% %BUILDDIR% %SPHINXOPTS% %O% 29 | goto end 30 | 31 | :help 32 | %SPHINXBUILD% -M help %SOURCEDIR% %BUILDDIR% %SPHINXOPTS% %O% 33 | 34 | :end 35 | popd 36 | -------------------------------------------------------------------------------- /docs/readme.rst: -------------------------------------------------------------------------------- 1 | .. include:: ../README.md 2 | :parser: myst_parser.sphinx_ 3 | -------------------------------------------------------------------------------- /pyproject.toml: -------------------------------------------------------------------------------- 1 | [project] 2 | name = "qct-parse" 3 | version = "0.2.2.dev0" 4 | dependencies =[ 5 | 'lxml' 6 | ] 7 | 8 | [tool.setuptools] 9 | packages=['qct_parse'] 10 | include-package-data = true 11 | 12 | [tool.setuptools.package-data] 13 | qct_parse = ["./qct-parse_8bit_config.txt", "./qct-parse_10bit_config.txt"] 14 | 15 | [project.scripts] 16 | makeqctoolsreport = "qct_parse.makeqctoolsreport:main" 17 | overcatch = "qct_parse.overcatch:main" 18 | qct-parse = "qct_parse.qct_parse:main" 19 | 20 | [tool.tox] 21 | envlist = ["3.9", "3.10", "3.11", "3.12", "3.13"] 22 | 23 | [tool.tox.env_run_base] 24 | description = "Run test under {base_python}" 25 | commands = [["pytest"]] 26 | deps = ["pytest"] 27 | -------------------------------------------------------------------------------- /qct_parse/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/amiaopensource/qct-parse/4753dc8d56c7fc226fb088ccc8d25ea6e7570951/qct_parse/__init__.py -------------------------------------------------------------------------------- /qct_parse/makeqctoolsreport.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | #makeqctoolsreport.py v 0.2.0 3 | 4 | import os 5 | import subprocess 6 | import sys 7 | import re 8 | import gzip 9 | import shutil 10 | import argparse 11 | from distutils import spawn 12 | 13 | #Context manager for changing the current working directory 14 | class cd: 15 | def __init__(self, newPath): 16 | self.newPath = os.path.expanduser(newPath) 17 | 18 | def __enter__(self): 19 | self.savedPath = os.getcwd() 20 | os.chdir(self.newPath) 21 | 22 | def __exit__(self, etype, value, traceback): 23 | os.chdir(self.savedPath) 24 | 25 | #check to see that we have the required software to run this script 26 | def dependencies(): 27 | depends = ['ffmpeg','ffprobe'] 28 | for d in depends: 29 | if spawn.find_executable(d) is None: 30 | print("Buddy, you gotta install " + d) 31 | sys.exit() 32 | return 33 | 34 | def parseInput(startObj,outPath): 35 | #print ffprobe output to txt file, we'll grep it later to see if we need to transcode for j2k/mxf 36 | if outPath is not None: 37 | ffdata = open(os.path.join(outPath,os.path.basename(startObj) + ".ffdata.txt"),"w") 38 | else: 39 | ffdata = open(startObj + ".ffdata.txt","w") 40 | nul = open(os.devnull,'w') 41 | subprocess.call(['ffprobe','-show_streams','-of','flat','-sexagesimal','-i',startObj], stdout=ffdata, stderr=nul) 42 | nul.close() 43 | ffdata.close() 44 | 45 | #find which stream is the video stream 46 | if outPath is not None: 47 | ffdata = open(os.path.join(outPath,os.path.basename(startObj) + ".ffdata.txt"),"r") 48 | else: 49 | ffdata = open(startObj + ".ffdata.txt","r") 50 | for line in ffdata: 51 | #find the line for video stream 52 | if re.search('.codec_type=\"video\"', line): 53 | #separate that line by periods, the formatting provided by ffprobe 54 | foolist = re.split(r'\.', line) 55 | #3rd part of that list is the video stream 56 | whichStreamVid = foolist[2] 57 | ffdata.close() 58 | 59 | #based on the vid stream we found, find the codec 60 | if outPath is not None: 61 | ffdata = open(os.path.join(outPath,os.path.basename(startObj) + ".ffdata.txt"),"r") 62 | else: 63 | ffdata = open(startObj + ".ffdata.txt","r") 64 | for line in ffdata: 65 | if re.search('streams.stream.' + whichStreamVid + '.codec_name=', line): 66 | #dunno why we gotta remove quotes twice but there ya go 67 | matches = [f[1:-1] for f in re.findall('".+?"', line)] 68 | codecName = matches[0] 69 | ffdata.close() 70 | 71 | if outPath is not None: 72 | os.remove(os.path.join(outPath,os.path.basename(startObj) + ".ffdata.txt")) 73 | else: 74 | os.remove(startObj + ".ffdata.txt") #only takes a string so cant send ffdata var idk 75 | 76 | #set some special strings to handle j2k/mxf files 77 | if codecName == 'jpeg2000': 78 | inputCodec = ' -vcodec libopenjpeg ' 79 | filterstring = ' -vf tinterlace=mode=merge,setfield=bff ' 80 | else: 81 | inputCodec = None 82 | filterstring = None 83 | return inputCodec, filterstring 84 | 85 | 86 | def transcode(startObj,outPath): 87 | #transcode to .nut 88 | ffmpegstring = ['ffmpeg'] 89 | if inputCodec is not None: 90 | ffmpegstring.append(inputCodec) 91 | ffmpegstring.extend(['-vsync','0','-i',startObj,'-vcodec','rawvideo','-acodec','pcm_s24le']) 92 | if filterstring is not None: 93 | ffmpegstring.append(filterstring) 94 | if outPath is not None: 95 | outObj = os.path.join(outPath,os.path.basename(startObj) + '.temp1.nut') 96 | else: 97 | outObj = startObj + '.temp1.nut' 98 | ffmpegstring.extend(['-f','nut','-y',outObj]) 99 | subprocess.call(ffmpegstring) 100 | 101 | 102 | def get_audio_stream_count(startObj): 103 | audio_stream_count = subprocess.check_output(['ffprobe', '-v', 'error','-select_streams', 'a', '-show_entries', 'stream=index','-of', 'flat', startObj]).splitlines() 104 | return len(audio_stream_count) 105 | 106 | 107 | def makeReport(startObj, outPath): 108 | with cd(os.path.dirname(startObj)): #change directory into folder where orig video is. necessary because movie= fails when there's a : in path, like on windows :( 109 | #here's where we use ffprobe to make the qctools report in regular xml 110 | print("writing ffprobe output to xml...") 111 | audio_tracks = get_audio_stream_count(startObj) #find out how many audio streams there are 112 | if audio_tracks > 0: 113 | #make the ffprobe for 1 or more audio tracks 114 | ffprobe_command = ['ffprobe','-loglevel','error','-f','lavfi','-i','movie=' + os.path.basename(startObj) + ':s=v+a[in0][in1],[in0]signalstats=stat=tout+vrep+brng,cropdetect=reset=1,split[a][b];[a]field=top[a1];[b]field=bottom[b1],[a1][b1]psnr[out0];[in1]ebur128=metadata=1[out1]','-show_frames','-show_versions','-of','xml=x=1:q=1','-noprivate'] 115 | elif audio_tracks == 0: 116 | #make the ffprobe for 0 audio tracks 117 | ffprobe_command = ['ffprobe','-loglevel','error','-f','lavfi','-i','movie=' + os.path.basename(startObj) + ',signalstats=stat=tout+vrep+brng,cropdetect=reset=1,split[a][b];[a]field=top[a1];[b]field=bottom[b1],[a1][b1]psnr','-show_frames','-show_versions','-of','xml=x=1:q=1','-noprivate'] 118 | if outPath is not None: #if we have specified an output path for the reports 119 | tmpxmlpath = os.path.join(outPath,os.path.basename(startObj) + '.qctools.xml') 120 | else: #here's the default output path 121 | tmpxmlpath = startObj + '.qctools.xml' 122 | tmpxml = open(tmpxmlpath,'w') 123 | fnull = open(os.devnull,'w') 124 | retcode = subprocess.call(ffprobe_command, stdout=tmpxml,stderr=fnull) #run the ffprobe command and send the stdout to the xml file we defined 125 | #foo, bar = retcode.communicate() 126 | tmpxml.close() 127 | 128 | #gzip that tmpxml file then delete the regular xml file cause we dont need it anymore 129 | print("gzip-ing ffprobe xml output") 130 | with open(tmpxmlpath, 'rb') as f_in, gzip.open(tmpxmlpath + '.gz','wb') as f_out: #open takes string args for file to open, not the file obj itself 131 | shutil.copyfileobj(f_in,f_out) 132 | os.remove(tmpxmlpath) #remove takes a full path string not a file obj (e.g. not tmpxml) 133 | if os.path.exists(startObj + '.temp1.nut'): #get rid of the intermediate nut file if we made one 134 | os.remove(startObj + '.temp1.nut') 135 | 136 | def main(): 137 | ####init the stuff from the cli######## 138 | parser = argparse.ArgumentParser(description="parses QCTools XML files for frames beyond broadcast values") 139 | parser.add_argument('-i','--input',dest='i',help="the path to the input video file") 140 | parser.add_argument('-rop','--reportOutputPath',dest='rop',default=None,help="the path where you want to save the report, default is same dir as input video") 141 | args = parser.parse_args() 142 | 143 | ####do some string replacements for the windows folks#### 144 | startObj = args.i.replace("\\","/") 145 | 146 | #make sure it's really real 147 | if not os.path.exists(startObj): 148 | print("") 149 | print("The input file " + startObj + " does not exist") 150 | sys.exit() 151 | 152 | if args.rop is not None: 153 | outPath = args.rop.replace("\\","/") 154 | else: 155 | outPath = None 156 | 157 | #figure out how we wanna process it 158 | inputCodec, filterstring = parseInput(startObj,outPath) 159 | 160 | #if it's a j2k file, we gotta transcode 161 | if inputCodec: 162 | if 'jpeg' in inputCodec: 163 | transcode(startObj,outPath) 164 | startObj = startObj + ".temp1.nut" 165 | makeReport(startObj,outPath) 166 | 167 | dependencies() 168 | if __name__ == '__main__': 169 | main() -------------------------------------------------------------------------------- /qct_parse/overcatch.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | #overcatch.py 4 | #runs qct-parse 6 times: 5 | #against each High, Med, Low profile for bars 6 | #against each High, Med, Low profile for content 7 | #takes input for single qctools report to process 8 | 9 | import argparse 10 | import subprocess 11 | import os 12 | import sys 13 | import re 14 | import configparser #grip frame data values from a config txt file 15 | 16 | def main(): 17 | parser = argparse.ArgumentParser(description="runs input QCTools Report against high, medium, and low tolerance profiles, for bars and content") 18 | parser.add_argument('-i','--input',dest='i',help='The QCTools Report to process') 19 | parser.add_argument('-bd','--bardetection',dest='bd',action='store_true',default=False,help='run with or without bar detection, default is False') 20 | parser.add_argument('-bo','--barsonly',dest='bo',action='store_true',default=False,help="run on bars only, not content, default is False") 21 | parser.add_argument('-t','--tag',dest='t',default="YMAX",help="the tag to look for, default is YMAX") 22 | args = parser.parse_args() 23 | 24 | print("Starting analysis on " + os.path.basename(args.i)) 25 | 26 | #set the profiles we want to run against the startObj 27 | profileList = ["highTolerance","midTolerance","lowTolerance"] 28 | profileDict = {} #init dictionary for profileName : tagValue 29 | config = configparser.RawConfigParser(allow_no_value=True) #init the library for reading a config file 30 | dn, fn = os.path.split(os.path.abspath(__file__)) #grip the dir where ~this script~ is located, also where config.txt should be located 31 | config.read(os.path.join(dn,"qct-parse_config.txt")) #read in the config file 32 | 33 | #make the dictionary of profileNames : tagValues 34 | for profile in profileList: 35 | try: 36 | profileDict[profile] = config.get(profile,args.t) 37 | except: 38 | print("Buddy, theres no tag threshold defined for " + args.t + " for the profile " + profile) 39 | print("Check the config file at " + os.path.join(dn,"qct-parse_config.txt")) 40 | print("") 41 | pass 42 | 43 | #these will be filled with our ourput strings for each profile, later 44 | barOutDict = {} 45 | contentOutDict = {} 46 | 47 | #creates a log file in directory of startObj with name of [startObj]-overcatch.txt 48 | #logfile = open(os.path.join(os.path.dirname(args.i),os.path.basename(args.i + "-overcatch.txt")),"a") 49 | 50 | #do it for bars 51 | if args.bd is True: 52 | for profile in profileList: 53 | sys.stdout.flush() 54 | output = subprocess.Popen(["python","qct-parse.py","-bd","-p",profile,"-i",args.i],stdout=subprocess.PIPE,stderr=subprocess.PIPE) 55 | out = output.stdout.readlines() #grip the stdout of that call, intelligently parse tabs and newlines 56 | for f in out: 57 | match = '' 58 | match = re.match(args.t + ".*$", f) #find just the tag name 59 | if match: 60 | barOutDict[profile] = match.group() #add the output, in string form, to our dict with key of the profile name 61 | 62 | #do it for content 63 | if args.bo is False: 64 | for profile in profileList: 65 | sys.stdout.flush() 66 | output = subprocess.Popen(["python","qct-parse.py","-p",profile,"-i",args.i],stdout=subprocess.PIPE,stderr=subprocess.PIPE) 67 | out = output.stdout.readlines() 68 | for f in out: 69 | match = '' 70 | match = re.match(args.t + ".*$", f) 71 | if match: 72 | contentOutDict[profile] = match.group() 73 | 74 | printout(barOutDict,contentOutDict,profileDict) 75 | 76 | 77 | def printout(barOutDict,contentOutDict,profileDict): 78 | if barOutDict: 79 | print("") 80 | print("For bars") 81 | for bod in barOutDict: 82 | print("Frames beyond " + profileDict[bod] + " for " + barOutDict[bod]) 83 | if contentOutDict: 84 | print("") 85 | print("For content") 86 | for cod in contentOutDict: 87 | print("Frames beyond " + profileDict[cod] + " for " + contentOutDict[cod]) 88 | 89 | if __name__ == '__main__': 90 | main() 91 | -------------------------------------------------------------------------------- /qct_parse/qct-parse_10bit_config.txt: -------------------------------------------------------------------------------- 1 | # 10bit values 2 | 3 | [default] 4 | YLOW: 64 5 | YHIGH: 940 6 | ULOW: 64 7 | UHIGH: 940 8 | VLOW: 0 9 | VHIGH: 1023 10 | SATMAX: 181.02 11 | TOUT: 0.009 12 | VREP: 0.03 13 | 14 | #Higher Tolerance for Peaking 15 | [highTolerance] 16 | YLOW: 40 17 | YMAX: 1000 18 | UMIN: 64 19 | UMAX: 1000 20 | VMIN: 0 21 | VMAX: 1023 22 | SATMAX: 181.02 23 | TOUT: 0.009 24 | VREP: 0.03 25 | 26 | #Medium Tolerance for Peaking 27 | [midTolerance] 28 | YLOW: 40 29 | YMAX: 980 30 | UMIN: 64 31 | UMAX: 980 32 | VMIN: 0 33 | VMAX: 1023 34 | SATMAX: 181.02 35 | TOUT: 0.009 36 | VREP: 0.03 37 | 38 | #Low Tolerance for Peaking 39 | [lowTolerance] 40 | YLOW: 64 41 | YMAX: 940 42 | UMIN: 64 43 | UMAX: 940 44 | VMIN: 0 45 | VMAX: 1023 46 | SATMAX: 181.02 47 | TOUT: 0.009 48 | VREP: 0.03 49 | 50 | [fullTagList] 51 | YMIN: 52 | YLOW: 53 | YAVG: 54 | YHIGH 55 | YMAX: 56 | UMIN: 57 | ULOW: 58 | UAVG: 59 | UHIGH: 60 | UMAX: 61 | VMIN: 62 | VLOW: 63 | VAVG: 64 | VHIGH: 65 | VMAX: 66 | SATMIN: 67 | SATLOW: 68 | SATAVG: 69 | SATHIGH: 70 | SATMAX: 71 | HUEMED: 72 | HUEAVG: 73 | YDIF: 74 | UDIF: 75 | VDIF: 76 | TOUT: 77 | VREP: 78 | BRNG: 79 | mse_y: 80 | mse_u: 81 | mse_v: 82 | mse_avg: 83 | psnr_y: 84 | psnr_u: 85 | psnr_v: 86 | psnr_avg: 87 | -------------------------------------------------------------------------------- /qct_parse/qct-parse_8bit_config.txt: -------------------------------------------------------------------------------- 1 | # based on qctools docs 2 | # 8bit values 3 | 4 | [default] 5 | YLOW: 16 6 | YHIGH: 235 7 | ULOW: 16 8 | UHIGH: 235 9 | VLOW: 0 10 | VHIGH: 255 11 | SATMAX: 181.02 12 | TOUT: 0.009 13 | VREP: 0.03 14 | 15 | #Higher Tolerance for Peaking 16 | [highTolerance] 17 | YLOW: 10 18 | YMAX: 250 19 | UMIN: 16 20 | UMAX: 250 21 | VMIN: 0 22 | VMAX: 255 23 | SATMAX: 181.02 24 | TOUT: 0.009 25 | VREP: 0.03 26 | 27 | #Medium Tolerance for Peaking 28 | [midTolerance] 29 | YLOW: 10 30 | YMAX: 245 31 | UMIN: 16 32 | UMAX: 245 33 | VMIN: 0 34 | VMAX: 255 35 | SATMAX: 181.02 36 | TOUT: 0.009 37 | VREP: 0.03 38 | 39 | #Low Tolerance for Peaking 40 | [lowTolerance] 41 | YLOW: 16 42 | YMAX: 235 43 | UMIN: 16 44 | UMAX: 235 45 | VMIN: 0 46 | VMAX: 255 47 | SATMAX: 181.02 48 | TOUT: 0.009 49 | VREP: 0.03 50 | 51 | [fullTagList] 52 | YMIN: 53 | YLOW: 54 | YAVG: 55 | YHIGH 56 | YMAX: 57 | UMIN: 58 | ULOW: 59 | UAVG: 60 | UHIGH: 61 | UMAX: 62 | VMIN: 63 | VLOW: 64 | VAVG: 65 | VHIGH: 66 | VMAX: 67 | SATMIN: 68 | SATLOW: 69 | SATAVG: 70 | SATHIGH: 71 | SATMAX: 72 | HUEMED: 73 | HUEAVG: 74 | YDIF: 75 | UDIF: 76 | VDIF: 77 | TOUT: 78 | VREP: 79 | BRNG: 80 | mse_y: 81 | mse_u: 82 | mse_v: 83 | mse_avg: 84 | psnr_y: 85 | psnr_u: 86 | psnr_v: 87 | psnr_avg: 88 | -------------------------------------------------------------------------------- /qct_parse/qct_parse.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | #qct-parse - changes made for python3 compatibility. WIP. 3 | 4 | #see this link for lxml goodness: http://www.ibm.com/developerworks/xml/library/x-hiperfparse/ 5 | 6 | from lxml import etree # for reading XML file (you will need to install this with pip) 7 | import argparse # for parsing input args 8 | import configparser # grip frame data values from a config txt file 9 | import gzip # for opening gzip file 10 | import logging # for logging output 11 | import collections # for circular buffer 12 | import os # for running ffmpeg and other terminal commands 13 | import subprocess # not currently used 14 | import gc # not currently used 15 | import math # used for rounding up buffer half 16 | import sys # system stuff 17 | import re # can't spell parse without re fam 18 | import operator 19 | import time 20 | import json 21 | import shutil # dependency checking 22 | import csv 23 | 24 | 25 | CONFIG_ENVIRONMENT_VARIABLE_NAME = 'QCT_PARSE_CONFIG_DIRECTORY' 26 | 27 | #check that we have required software installed 28 | def dependencies(): 29 | depends = ['ffmpeg','ffprobe'] 30 | for d in depends: 31 | if shutil.which(d) is None: 32 | print("Buddy, you gotta install " + d) 33 | sys.exit() 34 | return 35 | 36 | #Creates timestamp for pkt_dts_time 37 | def dts2ts(frame_pkt_dts_time): 38 | seconds = float(frame_pkt_dts_time) 39 | hours, seconds = divmod(seconds, 3600) 40 | minutes, seconds = divmod(seconds, 60) 41 | if hours < 10: 42 | hours = "0" + str(int(hours)) 43 | else: 44 | hours = str(int(hours)) 45 | if minutes < 10: 46 | minutes = "0" + str(int(minutes)) 47 | else: 48 | minutes = str(int(minutes)) 49 | secondsStr = str(round(seconds,4)) 50 | if int(seconds) < 10: 51 | secondsStr = "0" + secondsStr 52 | else: 53 | seconds = str(minutes) 54 | while len(secondsStr) < 7: 55 | secondsStr = secondsStr + "0" 56 | timeStampString = hours + ":" + minutes + ":" + secondsStr 57 | return timeStampString 58 | 59 | #initializes the log 60 | def initLog(inputPath): 61 | """ 62 | Initializes a log file for the given input file. 63 | 64 | The log file is created with the same name as the input file but with a '.log' extension. 65 | 66 | Args: 67 | inputPath (str): The file path for the input file, used to create the log file. 68 | 69 | Returns: 70 | None 71 | """ 72 | logPath = inputPath + '.log' 73 | logging.basicConfig(filename=logPath,level=logging.INFO,format='%(asctime)s %(message)s') 74 | logging.info("Started QCT-Parse") 75 | 76 | def set_logger(input_path): 77 | log_path = f'{input_path}.log' 78 | logger = logging.getLogger() 79 | if logger.hasHandlers(): 80 | logger.handlers.clear() 81 | logger.setLevel(logging.INFO) 82 | 83 | file_handler = logging.FileHandler(filename=log_path) 84 | file_handler.setLevel(logging.INFO) 85 | file_handler.setFormatter(logging.Formatter('%(asctime)s %(message)s')) 86 | logger.addHandler(file_handler) 87 | logger.info("Started QCT-Parse") 88 | 89 | 90 | 91 | # finds stuff over/under threshold 92 | def threshFinder(inFrame,args,startObj,pkt,tag,over,thumbPath,thumbDelay,adhoc_tag): 93 | """ 94 | Evaluates whether a tag in a video frame exceeds or falls below a threshold value and logs the result. 95 | 96 | This function checks if a given frame's tag value is either below or above a threshold. 97 | It logs a warning if the value is outside the expected range and can optionally export a thumbnail. 98 | 99 | Args: 100 | inFrame (dict): Dictionary containing frame data. 101 | args (argparse.Namespace): Parsed command-line arguments. 102 | startObj (object): Path to the QCTools report file (.qctools.xml.gz) 103 | pkt (str): The key used to extract timestamps from tag in qctools.xml.gz. 104 | tag (str): Tag from frame in qctools.xml.gz, checked against thresholds. 105 | over (float): Threshold for the tag value. 106 | thumbPath (str): Path to save thumbnails if they are exported. 107 | thumbDelay (int): Current delay counter for thumbnail exports. 108 | 109 | Returns: 110 | tuple: 111 | bool: indicating if threshold was met (True or False) 112 | int: Updated `thumbDelay` value based on whether a thumbnail was exported or not. 113 | 114 | Behavior: 115 | - If the tag value is below the lower threshold (for keys containing "MIN" or "LOW"), logs a warning and may export a thumbnail. 116 | - If the tag value is above the upper threshold, logs a warning and may export a thumbnail. 117 | - Thumbnail export occurs if enabled (`args.te`) and if the delay since the last export exceeds the user-defined threshold (`args.ted`). 118 | """ 119 | tagValue = float(inFrame[tag]) 120 | frame_pkt_dts_time = inFrame[pkt] 121 | if adhoc_tag: 122 | if args.o: 123 | comparision = operator.gt 124 | elif args.u: 125 | comparision = operator.lt 126 | else: 127 | if "MIN" in tag or "LOW" in tag: 128 | comparision = operator.lt 129 | else: 130 | comparision = operator.gt 131 | 132 | if comparision(float(tagValue), float(over)): # if the attribute is over usr set threshold 133 | timeStampString = dts2ts(frame_pkt_dts_time) 134 | logging.warning(tag + " is over " + str(over) + " with a value of " + str(tagValue) + " at duration " + timeStampString) 135 | if args.te and (thumbDelay > int(args.ted)): # if thumb export is turned on and there has been enough delay between this frame and the last exported thumb, then export a new thumb 136 | printThumb(args,tag,startObj,thumbPath,tagValue,timeStampString) 137 | thumbDelay = 0 138 | return True, thumbDelay # return true because it was over and thumbDelay 139 | else: 140 | return False, thumbDelay # return false because it was NOT over and thumbDelay 141 | 142 | 143 | def get_video_resolution(input_video): 144 | """ 145 | Use ffprobe to get the resolution of the input video file. 146 | 147 | Args: 148 | input_video (str): Path to the input video file. 149 | 150 | Returns: 151 | (width, height) (tuple): The width and height of the video. 152 | """ 153 | ffprobe_command = [ 154 | 'ffprobe', '-v', 'error', '-select_streams', 'v:0', '-show_entries', 155 | 'stream=width,height', '-of', 'json', input_video 156 | ] 157 | 158 | process = subprocess.Popen(ffprobe_command, stdout=subprocess.PIPE, stderr=subprocess.PIPE) 159 | out, err = process.communicate() 160 | 161 | if process.returncode != 0: 162 | print(f"Error getting resolution with ffprobe: {err.decode('utf-8')}") 163 | return None 164 | 165 | # Parse the JSON output 166 | video_info = json.loads(out) 167 | 168 | # Extract the width and height from the video stream info 169 | width = video_info['streams'][0]['width'] 170 | height = video_info['streams'][0]['height'] 171 | 172 | return width, height 173 | 174 | 175 | # print thumbnail images of overs/unders 176 | def printThumb(args,tag,startObj,thumbPath,tagValue,timeStampString): 177 | ####init some variables using the args list 178 | inputVid = startObj.replace(".qctools.xml.gz", "") 179 | if os.path.isfile(inputVid): 180 | # Get the resolution using ffprobe 181 | resolution = get_video_resolution(inputVid) 182 | if resolution: 183 | width, height = resolution 184 | else: 185 | # Fall back to hardcoded resolution if ffprobe fails 186 | width, height = 720, 486 187 | 188 | baseName = os.path.basename(startObj) 189 | baseName = baseName.replace(".qctools.xml.gz", "") 190 | outputFramePath = os.path.join(thumbPath,baseName + "." + tag + "." + str(tagValue) + "." + timeStampString + ".png") 191 | ffoutputFramePath = outputFramePath.replace(":",".") 192 | # for windows we gotta see if that first : for the drive has been replaced by a dot and put it back 193 | 194 | match = '' 195 | match = re.search(r"[A-Z]\.\/",ffoutputFramePath) #matches pattern R./ which should be R:/ on windows 196 | if match: 197 | ffoutputFramePath = ffoutputFramePath.replace(".",":",1) # replace first instance of "." in string ffoutputFramePath 198 | 199 | ffmpegString = ( 200 | f'ffmpeg -ss {timeStampString} -i "{inputVid}" -vframes 1 ' 201 | f'-s {width}x{height} -y -update 1 "{ffoutputFramePath}"' 202 | ) 203 | output = subprocess.Popen(ffmpegString,stdout=subprocess.PIPE,stderr=subprocess.PIPE,shell=True) 204 | out,err = output.communicate() 205 | # Decode byte strings to handle newlines properly 206 | out = out.decode('utf-8') 207 | err = err.decode('utf-8') 208 | 209 | if args.q is False: 210 | print(out) 211 | print(err) 212 | else: 213 | print("Input video file not found. Ensure video file is in the same directory as the QCTools report.") 214 | exit() 215 | return 216 | 217 | 218 | # detect bars 219 | def detectBars(args,startObj,pkt,durationStart,durationEnd,framesList,buffSize,bit_depth_10): 220 | """ 221 | Detects color bars in a video by analyzing frames within a buffered window and logging the start and end times of the bars. 222 | 223 | This function iterates through the frames in a QCTools report, parses each frame, 224 | and analyzes specific tags (YMAX, YMIN, YDIF) to detect the presence of color bars. 225 | The detection checks a frame each time the buffer reaches the specified size (`buffSize`) and ends when the frame tags no longer match the expected bar values. 226 | 227 | Args: 228 | args (argparse.Namespace): Parsed command-line arguments. 229 | startObj (str): Path to the QCTools report file (.qctools.xml.gz) 230 | pkt (str): Key used to identify the packet timestamp (pkt_*ts_time) in the XML frames. 231 | durationStart (str): The timestamp when the bars start, initially an empty string. 232 | durationEnd (str): The timestamp when the bars end, initially an empty string. 233 | framesList (list): List of dictionaries storing the parsed frame data. 234 | buffSize (int): The size of the frame buffer to hold frames for analysis. 235 | 236 | Returns: 237 | tuple: 238 | float: The timestamp (`durationStart`) when the bars were first detected. 239 | float: The timestamp (`durationEnd`) when the bars were last detected. 240 | 241 | Behavior: 242 | - Parses the input XML file frame by frame. 243 | - Each frame's timestamp (`pkt_*ts_time`) and key-value pairs are stored in a dictionary (`frameDict`). 244 | - Once the buffer reaches the specified size (`buffSize`), it checks the middle frame's attributes: 245 | - Color bars are detected if `YMAX > 210`, `YMIN < 10`, and `YDIF < 3.0`. 246 | - Logs the start and end times of the bars and stops detection once the bars end. 247 | - Clears the memory of parsed elements to avoid excessive memory usage during parsing. 248 | 249 | Example log outputs: 250 | - "Bars start at [timestamp] ([formatted timestamp])" 251 | - "Bars ended at [timestamp] ([formatted timestamp])" 252 | """ 253 | if bit_depth_10: 254 | YMAX_thresh = 800 255 | YMIN_thresh = 10 256 | YDIF_thresh = 10 257 | else: 258 | YMAX_thresh = 210 259 | YMIN_thresh = 10 260 | YDIF_thresh = 3.0 261 | 262 | with gzip.open(startObj) as xml: 263 | for event, elem in etree.iterparse(xml, events=('end',), tag='frame'): #iterparse the xml doc 264 | if elem.attrib['media_type'] == "video": #get just the video frames 265 | frame_pkt_dts_time = elem.attrib[pkt] #get the timestamps for the current frame we're looking at 266 | frameDict = {} #start an empty dict for the new frame 267 | frameDict[pkt] = frame_pkt_dts_time #give the dict the timestamp, which we have now 268 | for t in list(elem): #iterating through each attribute for each element 269 | keySplit = t.attrib['key'].split(".") #split the names by dots 270 | keyName = str(keySplit[-1]) #get just the last word for the key name 271 | frameDict[keyName] = t.attrib['value'] #add each attribute to the frame dictionary 272 | framesList.append(frameDict) 273 | middleFrame = int(round(float(len(framesList))/2)) # i hate this calculation, but it gets us the middle index of the list as an integer 274 | if len(framesList) == buffSize: # wait till the buffer is full to start detecting bars 275 | ## This is where the bars detection magic actually happens 276 | # Check conditions 277 | if (float(framesList[middleFrame]['YMAX']) > YMAX_thresh and 278 | float(framesList[middleFrame]['YMIN']) < YMIN_thresh and 279 | float(framesList[middleFrame]['YDIF']) < YDIF_thresh): 280 | if durationStart == "": 281 | durationStart = float(framesList[middleFrame][pkt]) 282 | print("Bars start at " + str(framesList[middleFrame][pkt]) + " (" + dts2ts(framesList[middleFrame][pkt]) + ")") 283 | durationEnd = float(framesList[middleFrame][pkt]) 284 | else: 285 | if durationStart != "" and durationEnd != "" and durationEnd - durationStart > 2: 286 | print("Bars ended at " + str(framesList[middleFrame][pkt]) + " (" + dts2ts(framesList[middleFrame][pkt]) + ")") 287 | break 288 | elem.clear() # we're done with that element so let's get it outta memory 289 | return durationStart, durationEnd 290 | 291 | 292 | def analyzeIt(args,profile,startObj,pkt,durationStart,durationEnd,thumbPath,thumbDelay,framesList,adhoc_tag=False,frameCount=0,overallFrameFail=0): 293 | """ 294 | Analyzes video frames from the QCTools report to detect threshold exceedances for specified tags or profiles and logs frame failures. 295 | 296 | This function iteratively parses video frames from a QCTools report (`.qctools.xml.gz`) and checks whether the frame attributes exceed user-defined thresholds 297 | (either single tags or profiles). Threshold exceedances are logged, and frames can be flagged for further analysis. Optionally, thumbnails of failing frames can be generated. 298 | 299 | Args: 300 | args (argparse.Namespace): Parsed command-line arguments, including tag thresholds and options for profile, thumbnail export, etc. 301 | profile (dict): A dictionary of key-value pairs of tag names and their corresponding threshold values. 302 | startObj (str): Path to the QCTools report file (.qctools.xml.gz) 303 | pkt (str): Key used to identify the pkt_*ts_time in the XML frames. 304 | durationStart (float): The starting time for analyzing frames (in seconds). 305 | durationEnd (float): The ending time for analyzing frames (in seconds). Can be `None` to process until the end. 306 | thumbPath (str): Path to save the thumbnail images of frames exceeding thresholds. 307 | thumbDelay (int): Delay counter between consecutive thumbnail generations to prevent spamming. 308 | framesList (list): A circular buffer to hold dictionaries of parsed frame attributes. 309 | frameCount (int, optional): The total number of frames analyzed (defaults to 0). 310 | overallFrameFail (int, optional): A count of how many frames failed threshold checks across all tags (defaults to 0). 311 | 312 | Returns: 313 | tuple: 314 | - kbeyond (dict): A dictionary where each tag is associated with a count of how many times its threshold was exceeded. 315 | - frameCount (int): The total number of frames analyzed. 316 | - overallFrameFail (int): The total number of frames that exceeded thresholds across all tags. 317 | 318 | Behavior: 319 | - Iteratively parses the input XML file and analyzes frames after `durationStart` and before `durationEnd`. 320 | - Frames are stored in a circular buffer (`framesList`), and attributes (tags) are extracted into dictionaries. 321 | - For each frame, checks whether specified tags exceed user-defined thresholds (from `args.o`, `args.u`, or `profile`). 322 | - Logs threshold exceedances and updates the count of failed frames. 323 | - Optionally, generates thumbnails for frames that exceed thresholds, ensuring a delay between consecutive thumbnails. 324 | 325 | Example usage: 326 | - Analyzing frames using a single tag threshold: `analyzeIt(args, {}, startObj, pkt, durationStart, durationEnd, thumbPath, thumbDelay, framesList)` 327 | - Analyzing frames using a profile: `analyzeIt(args, profile, startObj, pkt, durationStart, durationEnd, thumbPath, thumbDelay, framesList)` 328 | """ 329 | kbeyond = {} # init a dict for each key which we'll use to track how often a given key is over 330 | fots = "" 331 | for k,v in profile.items(): 332 | kbeyond[k] = 0 333 | with gzip.open(startObj) as xml: 334 | for event, elem in etree.iterparse(xml, events=('end',), tag='frame'): #iterparse the xml doc 335 | if elem.attrib['media_type'] == "video": #get just the video frames 336 | frameCount = frameCount + 1 337 | frame_pkt_dts_time = elem.attrib[pkt] #get the timestamps for the current frame we're looking at 338 | if frame_pkt_dts_time >= str(durationStart): #only work on frames that are after the start time 339 | if durationEnd: 340 | if float(frame_pkt_dts_time) > durationEnd: #only work on frames that are before the end time 341 | print("started at " + str(durationStart) + " seconds and stopped at " + str(frame_pkt_dts_time) + " seconds (" + dts2ts(frame_pkt_dts_time) + ") or " + str(frameCount) + " frames!") 342 | break 343 | frameDict = {} #start an empty dict for the new frame 344 | frameDict[pkt] = frame_pkt_dts_time #make a key for the timestamp, which we have now 345 | for t in list(elem): #iterating through each attribute for each element 346 | keySplit = t.attrib['key'].split(".") #split the names by dots 347 | keyName = str(keySplit[-1]) #get just the last word for the key name 348 | if len(keyName) == 1: #if it's psnr or mse, keyName is gonna be a single char 349 | keyName = '.'.join(keySplit[-2:]) #full attribute made by combining last 2 parts of split with a period in btw 350 | frameDict[keyName] = t.attrib['value'] #add each attribute to the frame dictionary 351 | framesList.append(frameDict) #add this dict to our circular buffer 352 | if args.pr is True: #display "timestamp: Tag Value" (654.754100: YMAX 229) to the terminal window 353 | print(framesList[-1][pkt] + ": " + args.t + " " + framesList[-1][args.t]) 354 | # Now we can parse the frame data from the buffer! 355 | for k,v in profile.items(): 356 | tag = k 357 | over = float(v) 358 | # ACTUALLY DO THE THING ONCE FOR EACH TAG 359 | frameOver, thumbDelay = threshFinder(framesList[-1],args,startObj,pkt,tag,over,thumbPath,thumbDelay,adhoc_tag) 360 | if frameOver is True: 361 | kbeyond[k] = kbeyond[k] + 1 # note the over in the key over dict 362 | if not frame_pkt_dts_time in fots: # make sure that we only count each over frame once 363 | overallFrameFail = overallFrameFail + 1 364 | fots = frame_pkt_dts_time # set it again so we don't dupe 365 | thumbDelay = thumbDelay + 1 366 | elem.clear() #we're done with that element so let's get it outta memory 367 | return kbeyond, frameCount, overallFrameFail 368 | 369 | 370 | def detectBitdepth(startObj,pkt,framesList,buffSize): 371 | bit_depth_10 = False 372 | with gzip.open(startObj) as xml: 373 | for event, elem in etree.iterparse(xml, events=('end',), tag='frame'): # iterparse the xml doc 374 | if elem.attrib['media_type'] == "video": # get just the video frames 375 | frame_pkt_dts_time = elem.attrib[pkt] # get the timestamps for the current frame we're looking at 376 | frameDict = {} # start an empty dict for the new frame 377 | frameDict[pkt] = frame_pkt_dts_time # give the dict the timestamp, which we have now 378 | for t in list(elem): # iterating through each attribute for each element 379 | keySplit = t.attrib['key'].split(".") # split the names by dots 380 | keyName = str(keySplit[-1]) # get just the last word for the key name 381 | frameDict[keyName] = t.attrib['value'] # add each attribute to the frame dictionary 382 | framesList.append(frameDict) 383 | middleFrame = int(round(float(len(framesList))/2)) # i hate this calculation, but it gets us the middle index of the list as an integer 384 | if len(framesList) == buffSize: # wait till the buffer is full to start detecting bars 385 | ## This is where the bars detection magic actually happens 386 | bufferRange = list(range(0, buffSize)) 387 | if float(framesList[middleFrame]['YMAX']) > 250: 388 | bit_depth_10 = True 389 | break 390 | elem.clear() # we're done with that element so let's get it outta memory 391 | 392 | return bit_depth_10 393 | 394 | 395 | def evalBars(startObj,pkt,durationStart,durationEnd,framesList,buffSize): 396 | # Define the keys for which you want to calculate the average 397 | keys_to_check = ['YMAX', 'YMIN', 'UMIN', 'UMAX', 'VMIN', 'VMAX', 'SATMAX', 'SATMIN'] 398 | # Initialize a dictionary to store the highest values for each key 399 | maxBarsDict = {} 400 | # adds the list keys_to_check as keys to a dictionary 401 | for key_being_checked in keys_to_check: 402 | # assign 'dummy' threshold to be overwritten 403 | if "MAX" in key_being_checked: 404 | maxBarsDict[key_being_checked] = 0 405 | elif "MIN" in key_being_checked: 406 | maxBarsDict[key_being_checked] = 1023 407 | 408 | with gzip.open(startObj) as xml: 409 | for event, elem in etree.iterparse(xml, events=('end',), tag='frame'): # iterparse the xml doc 410 | if elem.attrib['media_type'] == "video": # get just the video frames 411 | frame_pkt_dts_time = elem.attrib[pkt] # get the timestamps for the current frame we're looking at 412 | if frame_pkt_dts_time >= str(durationStart): # only work on frames that are after the start time # only work on frames that are after the start time 413 | if float(frame_pkt_dts_time) > durationEnd: # only work on frames that are before the end time 414 | break 415 | frameDict = {} # start an empty dict for the new frame 416 | frameDict[pkt] = frame_pkt_dts_time # give the dict the timestamp, which we have now 417 | for t in list(elem): # iterating through each attribute for each element 418 | keySplit = t.attrib['key'].split(".") # split the names by dots 419 | keyName = str(keySplit[-1]) # get just the last word for the key name 420 | frameDict[keyName] = t.attrib['value'] # add each attribute to the frame dictionary 421 | framesList.append(frameDict) 422 | if len(framesList) == buffSize: # wait till the buffer is full to start detecting bars 423 | ## This is where the bars detection magic actually happens 424 | for colorbar_key in keys_to_check: 425 | if colorbar_key in frameDict: 426 | if "MAX" in colorbar_key: 427 | # Convert the value to float and compare it with the current highest value 428 | value = float(frameDict[colorbar_key]) 429 | if value > maxBarsDict[colorbar_key]: 430 | maxBarsDict[colorbar_key] = value 431 | elif "MIN" in colorbar_key: 432 | # Convert the value to float and compare it with the current highest value 433 | value = float(frameDict[colorbar_key]) 434 | if value < maxBarsDict[colorbar_key]: 435 | maxBarsDict[colorbar_key] = value 436 | # Convert highest values to integer 437 | maxBarsDict = {colorbar_key: int(value) for colorbar_key, value in maxBarsDict.items()} 438 | 439 | return maxBarsDict 440 | 441 | 442 | def extract_report_mkv(startObj): 443 | 444 | report_file_output = startObj.replace(".qctools.mkv", ".qctools.xml.gz") 445 | if os.path.isfile(report_file_output): 446 | while True: 447 | user_input = input(f"The file {os.path.basename(report_file_output)} already exists. \nExtract xml.gz from {os.path.basename(startObj)} and overwrite existing file? \n(y/n):\n") 448 | if user_input.lower() in ["yes", "y"]: 449 | os.remove(report_file_output) 450 | # Run ffmpeg command to extract xml.gz report 451 | full_command = [ 452 | 'ffmpeg', 453 | '-hide_banner', 454 | '-loglevel', 'panic', 455 | '-dump_attachment:t:0', report_file_output, 456 | '-i', startObj 457 | ] 458 | print(f'Extracting qctools.xml.gz report from {os.path.basename(startObj)}\n') 459 | print(f'Running command: {" ".join(full_command)}\n') 460 | subprocess.run(full_command) 461 | break 462 | elif user_input.lower() in ["no", "n"]: 463 | print('Processing existing qctools report, not extracting file\n') 464 | break 465 | else: 466 | print("Invalid input. Please enter yes/no.\n") 467 | else: 468 | # Run ffmpeg command to extract xml.gz report 469 | full_command = [ 470 | 'ffmpeg', 471 | '-hide_banner', 472 | '-loglevel', 'panic', 473 | '-dump_attachment:t:0', report_file_output, 474 | '-i', startObj 475 | ] 476 | print(f'Extracting qctools.xml.gz report from {os.path.basename(startObj)}\n') 477 | print(f'Running command: {" ".join(full_command)}\n') 478 | subprocess.run(full_command) 479 | 480 | if os.path.isfile(report_file_output): 481 | startObj = report_file_output 482 | else: 483 | print(f'Unable to extract XML from QCTools mkv report file\n') 484 | startObj = None 485 | exit() 486 | 487 | return startObj 488 | 489 | 490 | def print_peak_colorbars(maxBarsDict): 491 | # ASCI formatting 492 | BOLD = "\033[1m" 493 | RESET = "\033[0m" 494 | 495 | print("\nReporting frames outside of these thresholds:") 496 | 497 | # Create two lists for even and odd indices 498 | tags = list(maxBarsDict.keys()) 499 | values = list(maxBarsDict.values()) 500 | 501 | # Print even-indexed tags and values on the first line 502 | for i in range(0, len(tags), 2): 503 | print(f"{BOLD}{tags[i]:<6}{RESET} {values[i]:<5}", end=" ") 504 | print() # Move to the next line 505 | 506 | # Print odd-indexed tags and values on the second line 507 | for i in range(1, len(tags), 2): 508 | print(f"{BOLD}{tags[i]:<6}{RESET} {values[i]:<5}", end=" ") 509 | print() # Move to the next line 510 | 511 | 512 | # Print results from analyzeIt 513 | def printresults(kbeyond, frameCount, overallFrameFail): 514 | """ 515 | Prints the analysis results of frame data, including counts of frames exceeding thresholds 516 | for various tags and the percentage of total frames that are affected. 517 | 518 | Args: 519 | kbeyond (dict): A dictionary where keys are tag names and values are the counts of frames 520 | that exceed the threshold for each tag. 521 | frameCount (int): The total number of frames analyzed. 522 | overallFrameFail (int): The number of frames where at least one tag exceeds its threshold. 523 | 524 | Prints: 525 | - The total number of frames analyzed. 526 | - A breakdown of frame counts for each tag in `kbeyond` and the corresponding percentage 527 | of the total frames that exceeded the tag's threshold. 528 | - The overall count and percentage of frames that failed at least one threshold. 529 | 530 | Notes: 531 | - If `frameCount` is zero, it prints "TotalFrames: 0" and returns early. 532 | - Percentages are formatted as whole numbers (e.g., "100"), two decimal places 533 | (e.g., "12.34"), or "<0.01" for values less than 0.01%. 534 | """ 535 | # Define ANSI escape codes for color and formatting 536 | BOLD = "\033[1m" 537 | UNDERLINE = "\033[4m" 538 | RESET = "\033[0m" 539 | 540 | RED = "\033[91m" 541 | YELLOW = "\033[93m" 542 | GREEN = "\033[92m" 543 | 544 | def format_percentage(value): 545 | percent = value * 100 546 | if percent == 100: 547 | return "100" 548 | elif percent == 0: 549 | return "0" 550 | elif percent < 0.01: 551 | return "<0.01" 552 | else: 553 | return f"{percent:.2f}" 554 | 555 | def color_percentage(value): 556 | percent = value * 100 557 | if percent > 10: 558 | return RED 559 | elif percent > 1: 560 | return YELLOW 561 | else: 562 | return GREEN 563 | 564 | if frameCount == 0: 565 | print(f"{UNDERLINE}TotalFrames:{RESET}\t0") 566 | return 567 | 568 | print(f"\n{UNDERLINE}TotalFrames{RESET}:\t{frameCount}\n") 569 | print(f"{UNDERLINE}By Tag{RESET}:\n") 570 | 571 | for tag, count in kbeyond.items(): 572 | percent = count / frameCount 573 | percent_over_string = format_percentage(percent) 574 | color = color_percentage(percent) 575 | print(f"{BOLD}{tag}{RESET}:\t{count}\t{color}{percent_over_string}{RESET}\t% of the total # of frames\n") 576 | 577 | print(f"{BOLD}Overall:{RESET}\n") 578 | overall_percent = overallFrameFail / frameCount 579 | percent_overall_string = format_percentage(overall_percent) 580 | color = color_percentage(overall_percent) 581 | print(f"Frames With At Least One Fail:\t{overallFrameFail}\t{color}{percent_overall_string}{RESET}\t% of the total # of frames\n") 582 | print(f"{BOLD}**************************{RESET}\n") 583 | 584 | 585 | def print_results_to_csv(kbeyond, frameCount, overallFrameFail, startObj, output_file): 586 | """ 587 | Writes the analysis results of frame data to a CSV file. 588 | 589 | Args: 590 | kbeyond (dict): A dictionary where keys are tag names and values are the counts of frames 591 | that exceed the threshold for each tag. 592 | frameCount (int): The total number of frames analyzed. 593 | overallFrameFail (int): The number of frames where at least one tag exceeds its threshold. 594 | output_file (str): The name of the CSV file to save the results. 595 | 596 | Outputs: 597 | A CSV file with the following structure: 598 | - TotalFrames: [frameCount] 599 | - By Tag: [Tag, Count, Percentage] 600 | - Overall: Frames With At Least One Fail, Count, Percentage 601 | 602 | Notes: 603 | - Percentages are formatted as whole numbers (e.g., "100"), two decimal places 604 | (e.g., "12.34"), or "<0.01" for values less than 0.01%. 605 | """ 606 | 607 | def format_percentage(value): 608 | percent = value * 100 609 | if percent == 100: 610 | return "100" 611 | elif percent == 0: 612 | return "0" 613 | elif percent < 0.01: 614 | return "<0.01" 615 | else: 616 | return f"{percent:.2f}" 617 | 618 | # Write results to CSV 619 | with open(output_file, mode='w', newline='', encoding='utf-8') as file: 620 | writer = csv.writer(file) 621 | 622 | # Title row 623 | writer.writerow(["qct-parse summary report for file:", startObj]) 624 | 625 | # Total Frames 626 | writer.writerow(["TotalFrames", frameCount]) 627 | 628 | # By Tag 629 | writer.writerow(["By Tag"]) 630 | writer.writerow(["Tag", "Count", "Percentage of Total Frames"]) 631 | for tag, count in kbeyond.items(): 632 | percent = count / frameCount 633 | writer.writerow([tag, count, format_percentage(percent)]) 634 | 635 | # Overall 636 | writer.writerow([]) 637 | writer.writerow(["Overall"]) 638 | overall_percent = overallFrameFail / frameCount 639 | writer.writerow(["Frames With At Least One Fail", overallFrameFail, format_percentage(overall_percent)]) 640 | 641 | print(f"Results successfully written to {output_file}") 642 | 643 | def get_arg_parser(): 644 | parser = argparse.ArgumentParser(description="parses QCTools XML files for frames beyond broadcast values") 645 | parser.add_argument('-i','--input',dest='i', action='append', help="the path to the input qctools.xml.gz file") 646 | parser.add_argument('-t','--tagname',dest='t', help="the tag name you want to test, e.g. SATMAX") 647 | parser.add_argument('-o','--over',dest='o', help="the threshold overage number") 648 | parser.add_argument('-u','--under',dest='u', help="the threshold under number") 649 | parser.add_argument('-p','--profile', dest='p', nargs='*', default=None, help="use values from your qct-parse-config.txt file, provide profile/ template name, e.g. 'default'") 650 | parser.add_argument('-buff','--buffSize',dest='buff',default=11, help="Size of the circular buffer. if user enters an even number it'll default to the next largest number to make it odd (default size 11)") 651 | parser.add_argument('-te','--thumbExport',dest='te',action='store_true',default=False, help="export thumbnail") 652 | parser.add_argument('-ted','--thumbExportDelay',dest='ted',default=9000, help="minimum frames between exported thumbs") 653 | parser.add_argument('-tep','--thumbExportPath',dest='tep',default='', help="Path to thumb export. if omitted, it uses the input basename") 654 | parser.add_argument('-ds','--durationStart',dest='ds',default=0, help="the duration in seconds to start analysis") 655 | parser.add_argument('-de','--durationEnd',dest='de',default=99999999, help="the duration in seconds to stop analysis") 656 | parser.add_argument('-bd','--barsDetection',dest='bd',action ='store_true',default=False, help="turns Bar Detection on and off") 657 | parser.add_argument('-be','--barsEvaluation',dest='be',action ='store_true',default=False, help="turns Color Bar Evaluation on and off") 658 | parser.add_argument('-pr','--print',dest='pr',action='store_true',default=False, help="print over/under frame data to console window") 659 | parser.add_argument('-csv', '--csvreport',dest='csv',action ='store_true',default=False, help="print summary results to a csv sidecar file") 660 | parser.add_argument('-q','--quiet',dest='q',action='store_true',default=False, help="hide ffmpeg output from console window") 661 | return parser 662 | 663 | 664 | def parse_single_qc_tools_report(input_file, args): 665 | startObj = input_file.replace("\\","/") 666 | extension = os.path.splitext(startObj)[1] 667 | # If qctools report is in an MKV attachment, extract .qctools.xml.gz report 668 | if extension.lower().endswith('mkv'): 669 | startObj = extract_report_mkv(startObj) 670 | buffSize = int(args.buff) # cast the input buffer as an integer 671 | if buffSize%2 == 0: 672 | buffSize = buffSize + 1 673 | set_logger(startObj) 674 | overcount = 0 # init count of overs 675 | undercount = 0 # init count of unders 676 | count = 0 # init total frames counter 677 | framesList = collections.deque(maxlen=buffSize) # init framesList 678 | thumbDelay = int(args.ted) # get a seconds number for the delay in the original file btw exporting tags 679 | parentDir = os.path.dirname(startObj) 680 | baseName = os.path.basename(startObj) 681 | baseName = baseName.replace(".qctools.xml.gz", "") 682 | durationStart = args.ds 683 | durationEnd = args.de 684 | # set the path for the csv report 685 | if args.csv: 686 | result_csv_file = os.path.join(parentDir, str(baseName) + ".qct_summary_report.csv") 687 | else: 688 | result_csv_file = None 689 | 690 | # we gotta find out if the qctools report has pkt_dts_time or pkt_pts_time ugh 691 | with gzip.open(startObj) as xml: 692 | for event, elem in etree.iterparse(xml, events=('end',), tag='frame'): # iterparse the xml doc 693 | if elem.attrib['media_type'] == "video": # get just the video frames 694 | # we gotta find out if the qctools report has pkt_dts_time or pkt_pts_time ugh 695 | match = re.search(r"pkt_.ts_time", etree.tostring(elem).decode('utf-8')) 696 | if match: 697 | pkt = match.group() 698 | break 699 | 700 | ###### Initialize values from the Config Parser 701 | # Determine if video values are 10 bit depth 702 | bit_depth_10 = detectBitdepth(startObj,pkt,framesList,buffSize) 703 | # init a dictionary where we'll store reference values from our config file 704 | profile = {} 705 | # init a list of every tag available in a QCTools Report 706 | tagList = ["YMIN","YLOW","YAVG","YHIGH","YMAX","UMIN","ULOW","UAVG","UHIGH","UMAX","VMIN","VLOW","VAVG","VHIGH","VMAX","SATMIN","SATLOW","SATAVG","SATHIGH","SATMAX","HUEMED","HUEAVG","YDIF","UDIF","VDIF","TOUT","VREP","BRNG","mse_y","mse_u","mse_v","mse_avg","psnr_y","psnr_u","psnr_v","psnr_avg"] 707 | 708 | # set the start and end duration times 709 | if args.bd: 710 | durationStart = "" # if bar detection is turned on then we have to calculate this 711 | durationEnd = "" # if bar detection is turned on then we have to calculate this 712 | elif args.ds: 713 | durationStart = float(args.ds) # The duration at which we start analyzing the file if no bar detection is selected 714 | elif not args.de == 99999999: 715 | durationEnd = float(args.de) # The duration at which we stop analyzing the file if no bar detection is selected 716 | 717 | 718 | # set the path for the thumbnail export 719 | if args.tep and not args.te: 720 | print("Buddy, you specified a thumbnail export path without specifying that you wanted to export the thumbnails. Please either add '-te' to your cli call or delete '-tep [path]'") 721 | exit() 722 | 723 | if args.tep: # if user supplied thumbExportPath, use that 724 | thumbPath = str(args.tep) 725 | else: 726 | if args.t: # if they supplied a single tag 727 | if args.o: # if the supplied tag is looking for a threshold Over 728 | thumbPath = os.path.join(parentDir, str(args.t) + "." + str(args.o)) 729 | elif args.u: # if the supplied tag was looking for a threshold Under 730 | thumbPath = os.path.join(parentDir, str(args.t) + "." + str(args.u)) 731 | else: # if they're using a profile, put all thumbs in 1 dir 732 | thumbPath = os.path.join(parentDir, "ThumbExports") 733 | 734 | if args.te: # make the thumb export path if it doesn't already exist 735 | if not os.path.exists(thumbPath): 736 | os.makedirs(thumbPath) 737 | 738 | 739 | ######## Iterate Through the XML for Bars detection ######## 740 | if args.bd: 741 | print(f"\nStarting Bars Detection on {baseName}\n") 742 | durationStart, durationEnd = detectBars(args,startObj,pkt,durationStart,durationEnd,framesList,buffSize,bit_depth_10) 743 | if args.be and durationStart != "" and durationEnd != "": 744 | maxBarsDict = evalBars(startObj,pkt,durationStart,durationEnd,framesList,buffSize) 745 | if maxBarsDict is None: 746 | print("\nSomething went wrong - cannot run colorbars evaluation") 747 | else: 748 | print("\nNow comparing peak values of color bars to the rest of the video.") 749 | print_peak_colorbars(maxBarsDict) 750 | # Reset start and stop time to eval the whole video (color bars won't be flagged because we already have their max values) 751 | durationStart = 0 752 | durationEnd = 99999999 753 | profile = maxBarsDict 754 | kbeyond, frameCount, overallFrameFail = analyzeIt(args,profile,startObj,pkt,durationStart,durationEnd,thumbPath,thumbDelay,framesList,adhoc_tag=False) 755 | if args.csv: 756 | print_results_to_csv(kbeyond, frameCount, overallFrameFail, startObj, result_csv_file) 757 | printresults(kbeyond,frameCount,overallFrameFail) 758 | else: 759 | printresults(kbeyond,frameCount,overallFrameFail) 760 | else: 761 | durationStart = "" 762 | durationEnd = "" 763 | 764 | if args.p is not None: 765 | # create list of profiles 766 | list_of_templates = args.p 767 | # setup configparser 768 | config = configparser.RawConfigParser(allow_no_value=True) 769 | dn, fn = os.path.split(os.path.abspath(__file__)) # grip the dir where ~this script~ is located, also where config.txt should be located 770 | # assign config based on bit depth of tag values 771 | if CONFIG_ENVIRONMENT_VARIABLE_NAME in os.environ: 772 | print(f"Using config files in ${CONFIG_ENVIRONMENT_VARIABLE_NAME}") 773 | dn = os.environ[CONFIG_ENVIRONMENT_VARIABLE_NAME] 774 | 775 | if bit_depth_10: 776 | config.read(os.path.join(dn,"qct-parse_10bit_config.txt")) # read in the config file 777 | else: 778 | config.read(os.path.join(dn,"qct-parse_8bit_config.txt")) # read in the config file 779 | for template in list_of_templates: 780 | # Check if the template is a valid section in the config 781 | if not config.has_section(template): 782 | print(f"Profile '{template}' does not match any section in the config.") 783 | continue # Skip to the next template if section doesn't exist 784 | for t in tagList: # loop thru every tag available and 785 | try: # see if it's in the config section 786 | profile[t.replace("_",".")] = config.get(template,t) # if it is, replace _ necessary for config file with . which xml attributes use, assign the value in config 787 | except: # if no config tag exists, do nothing so we can move faster 788 | pass 789 | 790 | ######## Iterate Through the XML for General Analysis ######## 791 | print(f"\nStarting Analysis on {baseName} using assigned profile {template}\n") 792 | kbeyond, frameCount, overallFrameFail = analyzeIt(args,profile,startObj,pkt,durationStart,durationEnd,thumbPath,thumbDelay,framesList,adhoc_tag=False) 793 | if args.csv: 794 | print_results_to_csv(kbeyond, frameCount, overallFrameFail, startObj, result_csv_file) 795 | printresults(kbeyond,frameCount,overallFrameFail) 796 | else: 797 | printresults(kbeyond,frameCount,overallFrameFail) 798 | 799 | if args.t and args.o or args.u: 800 | profile = {} 801 | tag = args.t 802 | if args.o: 803 | over = float(args.o) 804 | if args.u: 805 | over = float(args.u) 806 | profile[tag] = over 807 | print(f"\nStarting Analysis on {baseName} using user specified tag {tag} w/ threshold {over}\n") 808 | kbeyond, frameCount, overallFrameFail = analyzeIt(args,profile,startObj,pkt,durationStart,durationEnd,thumbPath,thumbDelay,framesList,adhoc_tag = True) 809 | if args.csv: 810 | print_results_to_csv(kbeyond, frameCount, overallFrameFail, startObj, result_csv_file) 811 | printresults(kbeyond,frameCount,overallFrameFail) 812 | else: 813 | printresults(kbeyond,frameCount,overallFrameFail) 814 | 815 | print(f"\nFinished Processing File: {baseName}.qctools.xml.gz\n") 816 | 817 | def parse_qc_tools_report(args): 818 | ##### Initialize variables and buffers ###### 819 | for input_file in args.i: 820 | parse_single_qc_tools_report(input_file, args) 821 | 822 | def main(): 823 | """ 824 | Main function that parses QCTools XML files, applies analysis, and optionally exports thumbnails. 825 | 826 | This function handles command-line arguments to process a QCTools report, extract frame data from the XML, 827 | apply threshold analysis for broadcast values, optionally detect color bars, and export analysis results to 828 | the console or thumbnails. 829 | 830 | Command-line Arguments: 831 | -i, --input (str): Path to the input QCTools XML.gz file. 832 | -t, --tagname (str): Tag name to analyze, e.g., SATMAX. 833 | -o, --over (float): Overage threshold for the tag specified. 834 | -u, --under (float): Under threshold for the tag specified. 835 | -p, --profile (str): Profile or template name from the qct-parse_config.txt file, e.g., 'default'. 836 | -buff, --buffSize (int): Circular buffer size. Defaults to 11, ensures odd number. 837 | -te, --thumbExport: Export thumbnails if flag is set. 838 | -ted, --thumbExportDelay (int): Minimum number of frames between exported thumbnails. 839 | -tep, --thumbExportPath (str): Path to export thumbnails, defaults to input basename if not provided. 840 | -ds, --durationStart (float): Start time in seconds for analysis. 841 | -de, --durationEnd (float): End time in seconds for analysis. 842 | -bd, --barsDetection: Flag to enable color bars detection. 843 | -pr, --print: Flag to print frame data to the console. 844 | -q, --quiet: Hide ffmpeg output if flag is set. 845 | 846 | Workflow: 847 | 1. Parse command-line arguments. 848 | 2. Optionally load reference threshold values from a profile in `qct-parse_config.txt`. 849 | 3. Initialize buffers, frame counters, and paths for thumbnail export. 850 | 4. Check for `pkt_dts_time` or `pkt_pts_time` in the QCTools XML file. 851 | 5. Set the analysis duration start and end times. 852 | 6. Perform bars detection if enabled, otherwise proceed with general analysis. 853 | 7. Call the `analyzeIt` function to perform frame-by-frame analysis and calculate exceedances. 854 | 8. Print results using `printresults` if applicable. 855 | 9. Handle errors or invalid input (e.g., missing thumbnail export flag but specifying a path). 856 | 857 | Example usage: 858 | python qct-parse.py -i sample.qctools.xml.gz -t SATMAX -o 5.0 -u -5.0 -te 859 | 860 | Returns: 861 | None: The function processes the XML file, performs analysis, and optionally exports thumbnails and prints results to the console. 862 | """ 863 | #### init the stuff from the cli ######## 864 | parser = get_arg_parser() 865 | args = parser.parse_args() 866 | ## Validate required arguments 867 | if not args.i: 868 | parser.error("the following arguments are required: -i/--input [path to QCTools report]") 869 | if args.o and args.u: 870 | parser.error("Both the -o and -u options were used. Cannot set threshold for both over and under, only one at a time.") 871 | parse_qc_tools_report(args) 872 | 873 | 874 | if __name__ == '__main__': 875 | dependencies() 876 | main() 877 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | # This file was autogenerated by uv via the following command: 2 | # uv pip compile pyproject.toml 3 | lxml==5.3.0 4 | # via qct-parse (pyproject.toml) 5 | -------------------------------------------------------------------------------- /tests/test_qct_parse.py: -------------------------------------------------------------------------------- 1 | from qct_parse import qct_parse 2 | 3 | def test_dts2ts(): 4 | assert qct_parse.dts2ts("0.0330000") == '00:00:00.0330' 5 | --------------------------------------------------------------------------------