├── LICENSE ├── Makefile ├── README.md ├── main.cxx └── src ├── acoder.cxx ├── acoder.hxx ├── ahcoder.cxx ├── ahcoder.hxx ├── bhcoder.cxx ├── bhcoder.hxx ├── pcoder.cxx └── pcoder.hxx /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 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | # 2 | # Makefile 3 | # 4 | # libcoders Builder 5 | # by snovvcrash 6 | # 04.2017 7 | # 8 | 9 | # 10 | # Copyright (C) 2017 snovvcrash 11 | # 12 | # This file is part of libcoders. 13 | # 14 | # libcoders is free software: you can redistribute it and/or modify 15 | # it under the terms of the GNU General Public License as published by 16 | # the Free Software Foundation, either version 3 of the License, or 17 | # (at your option) any later version. 18 | # 19 | # libcoders is distributed in the hope that it will be useful, 20 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 21 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 22 | # GNU General Public License for more details. 23 | # 24 | # You should have received a copy of the GNU General Public License 25 | # along with libcoders. If not, see . 26 | # 27 | 28 | CXXTARGET = libcoders 29 | CTARGET = 30 | 31 | CXX = g++ 32 | CC = gcc 33 | 34 | CXXFLAGS += -Wall -c -std=c++11 -O2 35 | CFLAGS += -Wall -c 36 | LDFLAGS += -Wall 37 | 38 | CXXHEADERS = $(wildcard *.hxx) $(wildcard */*.hxx) 39 | CXXSOURCES = $(wildcard *.cxx) $(wildcard */*.cxx) 40 | CXXOBJECTS = $(patsubst %.cxx, %.o, $(CXXSOURCES)) 41 | CHEADERS = $(wildcard *.h) $(wildcard */*.h) 42 | CSOURCES = $(wildcard *.c) $(wildcard */*.c) 43 | COBJECTS = $(patsubst %.c, %.o, $(CSOURCES)) 44 | 45 | .PHONY: cxxbuild cbuild all default clean 46 | .PRECIOUS: $(CXXTARGET) $(CTARGET) $(CXXOBJECTS) $(COBJECTS) 47 | 48 | all: clean default 49 | default: cxxbuild 50 | cxxbuild: $(CXXTARGET) 51 | @echo "Build cxx-project" 52 | cbuild: $(CTARGET) 53 | @echo "Build c-project" 54 | 55 | $(CXXTARGET): $(CXXOBJECTS) 56 | @echo "(CXX) $?" 57 | @$(CXX) $(CXXOBJECTS) $(LDFLAGS) -o $@ 58 | 59 | $(CTARGET): $(COBJECTS) 60 | @echo "(CC) $?" 61 | @$(CC) $(COBJECTS) $(LDFLAGS) -o $@ 62 | 63 | %.o: %.cxx $(CXXHEADERS) 64 | @echo "(CXX) $<" 65 | @$(CXX) $(CXXFLAGS) $< -o $@ 66 | 67 | %.o: %.c $(CHEADERS) 68 | @echo "(CC) $<" 69 | @$(CC) $(CFLAGS) $< -o $@ 70 | 71 | debug: CXXFLAGS += -DDEBUG -g -O0 72 | debug: CFLAGS += -DDEBUG -g -O0 73 | debug: all 74 | @echo "DEBUG MODE" 75 | 76 | clean: 77 | @echo "Clean project" 78 | @rm -rfv *.o */*.o $(CXXTARGET) $(CTARGET) 79 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # libcoders 2 | 3 | Simple library that lets you compress files (6 algorithms available: Shennon, Fano, Huffman, Bigram Huffman, Adaptive Huffman and Arithmetic coding). 4 | 5 | Made for educational purposes. 6 | 7 | # How-to-use: 8 | 9 | ## 1. Build, run and get help 10 | 11 | * Build 12 | ``` 13 | $ make default 14 | ``` 15 | 16 | * Help 17 | ``` 18 | $ ./libcoders -h 19 | ``` 20 | 21 | * Usage example 22 | ``` 23 | $ ./libcoders -c -i input_file.txt -o encoded_file -m shennon 24 | $ ./libcoders -d -i encoded_file -o decoded_file.txt -m shennon 25 | ``` 26 | 27 | ## 2. Clean project 28 | 29 | * Clean 30 | 31 | ``` 32 | $ make clean 33 | ``` 34 | 35 | # GUI 36 | 37 | There is also a GUI version of this project available [here](https://github.com/snovvcrash/LibCoders-GUI "LibCoders-GUI"). 38 | -------------------------------------------------------------------------------- /main.cxx: -------------------------------------------------------------------------------- 1 | /** 2 | * main.cxx 3 | * 4 | * libcoders Library Entry Point 5 | * by snovvcrash 6 | * 04.2017 7 | */ 8 | 9 | /** 10 | * Copyright (C) 2017 snovvcrash 11 | * 12 | * This file is part of libcoders. 13 | * 14 | * libcoders is free software: you can redistribute it and/or modify 15 | * it under the terms of the GNU General Public License as published by 16 | * the Free Software Foundation, either version 3 of the License, or 17 | * (at your option) any later version. 18 | * 19 | * libcoders is distributed in the hope that it will be useful, 20 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 21 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 22 | * GNU General Public License for more details. 23 | * 24 | * You should have received a copy of the GNU General Public License 25 | * along with libcoders. If not, see . 26 | */ 27 | 28 | #include 29 | #include 30 | #include 31 | #include 32 | #include 33 | #include 34 | #include 35 | #include // getopt, usleep 36 | #include // PATH_MAX 37 | #include // S_ISREG 38 | #include // struct stat 39 | #include "src/pcoder.hxx" 40 | #include "src/bhcoder.hxx" 41 | #include "src/ahcoder.hxx" 42 | #include "src/acoder.hxx" 43 | 44 | #define ERROR_CODING_METHOD ( -1) 45 | #define ERROR_IFILE_PATH ( -2) 46 | #define ERROR_OFILE_PATH ( -3) 47 | #define ERROR_OPTION_TYPE ( -4) 48 | #define ERROR_OPTION_NUMBER ( -5) 49 | #define ERROR_IS_REGULAR_FILE ( -6) 50 | #define ERROR_FILE_OPEN ( -7) 51 | #define ERROR_FILE_EXIST ( -8) 52 | 53 | using std::cout; 54 | using std::endl; 55 | using std::cerr; 56 | using std::flush; 57 | using std::string; 58 | 59 | using staticcodes::shennon; 60 | using staticcodes::fano; 61 | using staticcodes::huffman; 62 | 63 | int is_regular_file(char const* path); 64 | int prepare_input_file(char const* ifilename, std::ifstream& ifile); 65 | int prepare_output_file(char const* ofilename, std::ofstream& ofile); 66 | string help(); 67 | 68 | int main(int argc, char* argv[]) { 69 | int opt = 0; 70 | int inv = -1; 71 | int method = 0; 72 | char* ifilename = nullptr; 73 | char* ofilename = nullptr; 74 | 75 | // Command line options 76 | if (argc == 8 && std::strcmp(argv[1], "-h")) 77 | while ((opt = getopt(argc, argv, "cdi:o:m:")) != -1) { 78 | switch (opt) { 79 | case 'c' : 80 | inv = 0; 81 | break; 82 | case 'd' : 83 | inv = 1; 84 | break; 85 | case 'i' : 86 | ifilename = optarg; 87 | if (std::strlen(ifilename) > PATH_MAX) { 88 | cerr << "main: Invalid input path, rerun with -h for help" << endl; 89 | return ERROR_IFILE_PATH; 90 | } 91 | break; 92 | case 'o' : 93 | ofilename = optarg; 94 | if (std::strlen(ofilename) > PATH_MAX) { 95 | cerr << "main: Invalid output path, rerun with -h for help" << endl; 96 | return ERROR_OFILE_PATH; 97 | } 98 | break; 99 | case 'm' : 100 | if (!std::strcmp(optarg, "shennon")) method = 1; 101 | else if (!std::strcmp(optarg, "fano")) method = 2; 102 | else if (!std::strcmp(optarg, "huffman")) method = 3; 103 | else if (!std::strcmp(optarg, "bhuffman")) method = 4; 104 | else if (!std::strcmp(optarg, "ahuffman")) method = 5; 105 | else if (!std::strcmp(optarg, "arithmetic")) method = 6; 106 | else { 107 | std::cerr << "main: Invalid coding method, rerun with -h for help" << std::endl; 108 | return ERROR_CODING_METHOD; 109 | } 110 | break; 111 | case '?' : 112 | cerr << "main: Invalid option, rerun with -h for help" << endl; 113 | return ERROR_OPTION_TYPE; 114 | } 115 | } 116 | else if (argc == 2 && !std::strcmp(argv[1], "-h")) { 117 | cout << help(); 118 | return 0; 119 | } 120 | else { 121 | cerr << "main: Invalid number of options, rerun with -h for help" << endl; 122 | return ERROR_OPTION_NUMBER; 123 | } 124 | 125 | // Working with files 126 | std::ifstream ifile; 127 | if (int errcode = prepare_input_file(ifilename, ifile)) 128 | return errcode; 129 | 130 | std::ofstream ofile; 131 | if (int errcode = prepare_output_file(ofilename, ofile)) 132 | return errcode; 133 | 134 | // Main part 135 | if (!inv) { 136 | cout << "Compressing, please wait... " << flush; 137 | 138 | auto start = std::chrono::steady_clock::now(); 139 | if (method == 1) staticcodes ::pcoder s(ifile, ofile); 140 | else if (method == 2) staticcodes ::pcoder f(ifile, ofile); 141 | else if (method == 3) staticcodes ::pcoder h(ifile, ofile); 142 | else if (method == 4) contextcodes ::bhcoder bh(ifile, ofile); 143 | else if (method == 5) adaptivecodes::ahcoder ah(ifile, ofile); 144 | else if (method == 6) staticcodes ::acoder a(ifile, ofile); 145 | auto end = std::chrono::steady_clock::now(); 146 | auto diff = std::chrono::duration_cast(end - start).count(); 147 | 148 | cout << "Done" << flush; 149 | usleep(250000); 150 | cout << endl << endl; 151 | 152 | ifile.clear(); 153 | ifile.seekg(0, std::ios::end); 154 | uint64_t isize = ifile.tellg(); 155 | 156 | double isize_kb = static_cast(isize) / 1024; 157 | double osize_kb = static_cast(ofile.tellp()) / 1024; 158 | int ratio = (isize_kb - osize_kb) / isize_kb * 100; 159 | 160 | std::cout.precision(6); 161 | cout << "Original file: " << ifilename << endl; 162 | cout << "Compressed file: " << ofilename << endl; 163 | cout << "--------------------" << endl; 164 | cout << "STATS" << endl; 165 | cout << "Original file size: " << isize_kb << " Kbyte" << endl; 166 | cout << "Compressed file size: " << osize_kb << " Kbyte" << endl; 167 | cout << "Compression ratio: " << ratio << '%' << endl; 168 | cout << "Time taken: " << diff << " milliseconds" << endl; 169 | cout << std::fixed; 170 | } 171 | else { 172 | cout << "Decompressing, please wait... " << flush; 173 | 174 | auto start = std::chrono::steady_clock::now(); 175 | if (method == 1) staticcodes ::pdecoder s(ifile, ofile); 176 | else if (method == 2) staticcodes ::pdecoder f(ifile, ofile); 177 | else if (method == 3) staticcodes ::pdecoder h(ifile, ofile); 178 | else if (method == 4) contextcodes ::bhdecoder bh(ifile, ofile); 179 | else if (method == 5) adaptivecodes::ahdecoder ah(ifile, ofile); 180 | else if (method == 6) staticcodes ::adecoder a(ifile, ofile); 181 | auto end = std::chrono::steady_clock::now(); 182 | auto diff = std::chrono::duration_cast(end - start).count(); 183 | 184 | cout << "Done" << flush; 185 | usleep(250000); 186 | cout << endl << endl; 187 | 188 | cout << "Original file: " << ifilename << endl; 189 | cout << "Decompressed file: " << ofilename << endl; 190 | cout << "Time taken: " << diff << " milliseconds" << endl; 191 | } 192 | 193 | // Finish 194 | ifile.close(); 195 | ofile.close(); 196 | 197 | return 0; 198 | } 199 | 200 | int is_regular_file(char const* path) { 201 | struct stat s; 202 | stat(path, &s); 203 | return S_ISREG(s.st_mode); 204 | } 205 | 206 | int prepare_input_file(char const* ifilename, std::ifstream& ifile) { 207 | if (!is_regular_file(ifilename)) { 208 | cerr << "prepare_input_file: No such input file or input file is not a regular file, rerun with -h for help" << endl; 209 | return ERROR_IS_REGULAR_FILE; 210 | } 211 | 212 | ifile.open(ifilename, std::ios::binary); 213 | 214 | if (!ifile.is_open()) { 215 | cerr << "prepare_input_file: " << std::strerror(errno) << endl; 216 | return ERROR_FILE_OPEN; 217 | } 218 | 219 | return 0; 220 | } 221 | 222 | int prepare_output_file(char const* ofilename, std::ofstream& ofile) { 223 | /* if (std::ifstream(ofilename)) { 224 | cerr << "prepare_output_file: File already exists" << endl; 225 | return ERROR_FILE_EXIST; 226 | } */ 227 | 228 | ofile.open(ofilename, std::ios::binary); 229 | 230 | if (!ofile.is_open()) { 231 | cerr << "prepare_output_file: " << std::strerror(errno) << endl; 232 | return ERROR_FILE_OPEN; 233 | } 234 | 235 | return 0; 236 | } 237 | 238 | string help() { 239 | return 240 | "REQUIRED OPTIONS\n" 241 | " -c | -d\n" 242 | " Compressing | decompressing operation respectively\n" 243 | "\n" 244 | " -i input\n" 245 | " Input file, i can be either a full path to a regular file\n" 246 | " or a filename of a regular file (if the file is in current directory)\n" 247 | " with maximum length of PATH_MAX (see value in )\n" 248 | "\n" 249 | " -o output\n" 250 | " Output file, o can be either a full path with a filename\n" 251 | " or a filename (file will be created in current directory)\n" 252 | " with maximum length of PATH_MAX (see value in )\n" 253 | "\n" 254 | " -m method\n" 255 | " Coding method, m can be \"shennon\", \"fano\", \"huffman\",\n" 256 | " \"bhuffman\", \"ahuffman\" or \"arithmetic\"\n" 257 | "\n"; 258 | } 259 | -------------------------------------------------------------------------------- /src/acoder.cxx: -------------------------------------------------------------------------------- 1 | /** 2 | * acoder.cxx 3 | * 4 | * Arithmetic Coding 5 | * by snovvcrash 6 | * 04.2017 7 | */ 8 | 9 | /** 10 | * Copyright (C) 2017 snovvcrash 11 | * 12 | * This file is part of libcoders. 13 | * 14 | * libcoders is free software: you can redistribute it and/or modify 15 | * it under the terms of the GNU General Public License as published by 16 | * the Free Software Foundation, either version 3 of the License, or 17 | * (at your option) any later version. 18 | * 19 | * libcoders is distributed in the hope that it will be useful, 20 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 21 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 22 | * GNU General Public License for more details. 23 | * 24 | * You should have received a copy of the GNU General Public License 25 | * along with libcoders. If not, see . 26 | */ 27 | 28 | #include 29 | #include 30 | #include // size_t 31 | #include 32 | #include 33 | #include 34 | #include 35 | #include // std::pair 36 | #include // std::stable_sort 37 | #include // std::greater 38 | #include // std::floor 39 | #include "pcoder.hxx" 40 | #include "acoder.hxx" 41 | 42 | namespace staticcodes { 43 | 44 | static constexpr size_t EOT = ALPHABET; // End of Transmission 45 | 46 | // ------------------------------------------------------ 47 | // --------------------- STATISTICS --------------------- 48 | // ------------------------------------------------------ 49 | 50 | void Statistics::create_range_vector() { 51 | std::vector > sorted_freq; 52 | 53 | for(size_t i = 0; i < m_freq_vec.size(); ++i) 54 | if (m_freq_vec[i]) 55 | sorted_freq.push_back(std::pair(m_freq_vec[i], i)); 56 | 57 | std::stable_sort(sorted_freq.begin(), sorted_freq.end(), std::greater >()); 58 | 59 | sorted_freq.push_back(std::pair(sorted_freq.back().first, EOT)); 60 | ++m_total_chars; 61 | 62 | std::vector sum_ranges(sorted_freq.size() + 1, 0.0); 63 | for (size_t i = 1; i < sum_ranges.size(); ++i) 64 | sum_ranges[i] = sum_ranges[i-1] + sorted_freq[i-1].first / static_cast(m_total_chars); 65 | 66 | m_range_vec.clear(); 67 | m_range_vec.resize(ALPHABET + 1); 68 | 69 | for (size_t i = 0; i < sorted_freq.size(); ++i) 70 | m_range_vec[sorted_freq[i].second] = std::pair(sum_ranges[i], sum_ranges[i+1]); 71 | } 72 | 73 | // ------------------------------------------------------ 74 | // --------------------- ARITHMETIC --------------------- 75 | // ------------------------------------------------------ 76 | 77 | class arithmetic { 78 | protected: 79 | size_t m_Max; 80 | size_t m_half; 81 | size_t m_quarter; 82 | size_t m_three_quarters; 83 | 84 | bool scaling(size_t& Low, size_t& High, int& count, bitseq_t& seq) { 85 | if (High <= m_half) { 86 | Low = 2*Low; 87 | High = 2*High; 88 | 89 | seq.push_back(0); 90 | 91 | for (int i = 0; i < count; ++i) 92 | seq.push_back(1); 93 | count = 0; 94 | 95 | return true; 96 | } 97 | else if (m_half <= Low) { 98 | Low = 2*Low - m_Max; 99 | High = 2*High - m_Max; 100 | 101 | seq.push_back(1); 102 | 103 | for (int i = 0; i < count; ++i) 104 | seq.push_back(0); 105 | count = 0; 106 | 107 | return true; 108 | } 109 | else return false; 110 | } 111 | 112 | bool expansion(size_t& Low, size_t& High, int& count) { 113 | if ((m_half < High) && (High <= m_three_quarters) && (m_quarter <= Low) && (Low < m_half)) { 114 | Low = 2*Low - m_half; 115 | High = 2*High - m_half; 116 | ++count; 117 | return true; 118 | } 119 | else return false; 120 | } 121 | 122 | void encode_symbol(int symbol, size_t& Low, size_t& High, int& count, range_vec_t const& m_range_vec, bitseq_t& seq) { 123 | size_t range = High - Low; 124 | 125 | int add_high = std::floor(m_range_vec[symbol].second * range); 126 | int add_low = std::floor(m_range_vec[symbol].first * range); 127 | 128 | High = Low + add_high; 129 | Low = Low + add_low; 130 | 131 | while(scaling(Low, High, count, seq) || expansion(Low, High, count)) 132 | ; 133 | } 134 | 135 | bool scaling(size_t& Low, size_t& High, int& l_index, int& r_index, bitseq_t& seq) { 136 | if ((High <= m_half) || (m_half <= Low)) { 137 | bool b = seq[l_index]; 138 | Low = 2*Low - b*m_Max; 139 | High = 2*High - b*m_Max; 140 | ++l_index; ++r_index; 141 | return true; 142 | } 143 | else return false; 144 | } 145 | 146 | bool expansion(size_t& Low, size_t& High, int& l_index, int& r_index, bitseq_t& seq) { 147 | if ((m_quarter <= Low) && (Low < m_half) && (m_half < High) && (High <= m_three_quarters)) { 148 | Low = 2*Low - m_half; 149 | High = 2*High - m_half; 150 | seq[l_index + 1] = seq[l_index]; 151 | ++l_index; ++r_index; 152 | return true; 153 | } 154 | else return false; 155 | } 156 | 157 | size_t get_value(int l_index, int r_index, bitseq_t& seq) { 158 | size_t value = 0; 159 | size_t i = 1; 160 | 161 | for (int index = r_index; index >= l_index; index--) { 162 | if (seq[index]) value += i; 163 | i <<= 1; 164 | } 165 | 166 | return value; 167 | } 168 | 169 | arithmetic(size_t M) 170 | : m_Max(M), m_half(M / 2), m_quarter(M / 4), m_three_quarters(m_quarter * 3) 171 | { } 172 | }; 173 | 174 | // ------------------------------------------------------- 175 | // ---------------------- CODERIMPL ---------------------- 176 | // ------------------------------------------------------- 177 | 178 | class acoder::CoderImpl : private Statistics, private arithmetic { 179 | bitseq_t m_seq; 180 | 181 | void create_bit_sequence(std::ifstream& ifile) { 182 | m_seq.clear(); 183 | 184 | ifile.clear(); 185 | ifile.seekg(0, std::ios::beg); 186 | 187 | size_t Low = 0; 188 | size_t High = m_Max; 189 | 190 | int count = 0; 191 | 192 | char c; 193 | while (ifile.read(&c, sizeof(c))) 194 | encode_symbol(static_cast(c), Low, High, count, m_range_vec, m_seq); 195 | 196 | encode_symbol(EOT, Low, High, count, m_range_vec, m_seq); 197 | 198 | if ((Low < m_quarter) && (m_half < High)) { 199 | m_seq.push_back(0); 200 | for (int i = 0; i < count + 1; ++i) 201 | m_seq.push_back(1); 202 | } 203 | 204 | if ((m_quarter <= Low) && (Low < m_half) && (m_three_quarters <= High)) { 205 | m_seq.push_back(1); 206 | for (int i = 0; i < count + 1; ++i) 207 | m_seq.push_back(0); 208 | } 209 | } 210 | 211 | public: 212 | void compress(std::ifstream& ifile, std::ofstream& ofile) { 213 | create_freq_vector(ifile); 214 | create_range_vector(); 215 | create_bit_sequence(ifile); 216 | 217 | for (const auto& freq : m_freq_vec) 218 | ofile.write(reinterpret_cast(&freq), sizeof(freq)); 219 | 220 | uint8_t bit_buffer = 0; 221 | size_t bit_counter = 0; 222 | 223 | for (const auto& bit : m_seq) { 224 | bit_buffer |= bit << (7 - bit_counter); 225 | 226 | if (++bit_counter == CHAR_BIT) { 227 | ofile.write(reinterpret_cast(&bit_buffer), sizeof(bit_buffer)); 228 | bit_buffer = 0; 229 | bit_counter = 0; 230 | } 231 | } 232 | 233 | if (bit_counter) ofile.write(reinterpret_cast(&bit_buffer), sizeof(bit_buffer)); 234 | } 235 | 236 | void operator()(std::ifstream& ifile, std::ofstream& ofile) { 237 | compress(ifile, ofile); 238 | } 239 | 240 | CoderImpl(std::ifstream& ifile, std::ofstream& ofile) : arithmetic(2147483648) { 241 | compress(ifile, ofile); 242 | } 243 | 244 | CoderImpl() : arithmetic(2147483648) 245 | { } 246 | }; 247 | 248 | void acoder::compress(std::ifstream& ifile, std::ofstream& ofile) { 249 | m_pImpl->compress(ifile, ofile); 250 | } 251 | 252 | void acoder::operator()(std::ifstream& ifile, std::ofstream& ofile) { 253 | m_pImpl->operator()(ifile, ofile); 254 | } 255 | 256 | acoder::acoder(std::ifstream& ifile, std::ofstream& ofile) 257 | : m_pImpl(new CoderImpl(ifile, ofile)) 258 | { } 259 | 260 | acoder::acoder() : m_pImpl(new CoderImpl) 261 | { } 262 | 263 | acoder::~acoder() 264 | { } 265 | 266 | // ------------------------------------------------------- 267 | // --------------------- DECODERIMPL --------------------- 268 | // ------------------------------------------------------- 269 | 270 | class adecoder::DecoderImpl : private Statistics, private arithmetic { 271 | bitseq_t m_seq; 272 | 273 | void read_bit_sequence(std::ifstream& ifile) { 274 | m_seq.clear(); 275 | 276 | char curr_byte; 277 | while (ifile.read(&curr_byte, sizeof(curr_byte))) 278 | for (size_t bit_counter = 0; bit_counter < CHAR_BIT; ++bit_counter) 279 | m_seq.push_back(curr_byte & (1 << (7 - bit_counter))); 280 | } 281 | 282 | public: 283 | void decompress(std::ifstream& ifile, std::ofstream& ofile) { 284 | m_freq_vec.clear(); 285 | m_total_chars = 0; 286 | 287 | for (size_t i = 0; i < ALPHABET; ++i) { 288 | uint32_t tmp; 289 | ifile.read(reinterpret_cast(&tmp), sizeof(tmp)); 290 | m_freq_vec.push_back(tmp); 291 | m_total_chars += tmp; 292 | } 293 | 294 | if (ifile.peek() == EOF) { 295 | if (!ifile.eof()) 296 | std::cerr << "adecoder::decompress: " << std::strerror(errno) << std::endl; 297 | return; 298 | } 299 | 300 | create_range_vector(); 301 | read_bit_sequence(ifile); 302 | 303 | size_t N = std::ceil(std::log2(static_cast(m_Max))); 304 | int l_index = 0; 305 | int r_index = N - 1; 306 | 307 | std::vector temp(r_index, false); 308 | m_seq.insert(m_seq.end(), temp.begin(), temp.end()); 309 | 310 | size_t Low = 0; 311 | size_t High = m_Max; 312 | 313 | int symbol = 0; 314 | size_t value; 315 | 316 | uint64_t cnt_chars = 0; 317 | 318 | while (true) { 319 | value = get_value(l_index, r_index, m_seq); 320 | 321 | size_t range = High - Low; 322 | 323 | for (size_t i = 0; i < m_range_vec.size(); ++i) { 324 | double H_i = Low + std::floor(m_range_vec[i].second * range); 325 | double L_i = Low + std::floor(m_range_vec[i].first * range); 326 | 327 | if ((L_i <= value) && (value < H_i)) { 328 | symbol = i; 329 | High = H_i; 330 | Low = L_i; 331 | break; 332 | } 333 | } 334 | 335 | while(scaling(Low, High, l_index, r_index, m_seq) || expansion(Low, High, l_index, r_index, m_seq)) 336 | ; 337 | 338 | if (symbol == EOT || cnt_chars == m_total_chars - 1) 339 | break; 340 | 341 | char c = symbol; 342 | ofile.write(&c, sizeof(c)); 343 | ++cnt_chars; 344 | } 345 | } 346 | 347 | void operator()(std::ifstream& ifile, std::ofstream& ofile) { 348 | decompress(ifile, ofile); 349 | } 350 | 351 | DecoderImpl(std::ifstream& ifile, std::ofstream& ofile) : arithmetic(2147483648) { 352 | decompress(ifile, ofile); 353 | } 354 | 355 | DecoderImpl() : arithmetic(2147483648) 356 | { } 357 | }; 358 | 359 | void adecoder::decompress(std::ifstream& ifile, std::ofstream& ofile) { 360 | m_pImpl->decompress(ifile, ofile); 361 | } 362 | 363 | void adecoder::operator()(std::ifstream& ifile, std::ofstream& ofile) { 364 | m_pImpl->operator()(ifile, ofile); 365 | } 366 | 367 | adecoder::adecoder(std::ifstream& ifile, std::ofstream& ofile) 368 | : m_pImpl(new DecoderImpl(ifile, ofile)) 369 | { } 370 | 371 | adecoder::adecoder() : m_pImpl(new DecoderImpl) 372 | { } 373 | 374 | adecoder::~adecoder() 375 | { } 376 | 377 | } 378 | -------------------------------------------------------------------------------- /src/acoder.hxx: -------------------------------------------------------------------------------- 1 | /** 2 | * acoder.hxx 3 | * 4 | * Arithmetic Coding 5 | * by snovvcrash 6 | * 04.2017 7 | */ 8 | 9 | /** 10 | * Copyright (C) 2017 snovvcrash 11 | * 12 | * This file is part of libcoders. 13 | * 14 | * libcoders is free software: you can redistribute it and/or modify 15 | * it under the terms of the GNU General Public License as published by 16 | * the Free Software Foundation, either version 3 of the License, or 17 | * (at your option) any later version. 18 | * 19 | * libcoders is distributed in the hope that it will be useful, 20 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 21 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 22 | * GNU General Public License for more details. 23 | * 24 | * You should have received a copy of the GNU General Public License 25 | * along with libcoders. If not, see . 26 | */ 27 | 28 | #pragma once 29 | #ifndef ACODER_HXX 30 | #define ACODER_HXX 31 | 32 | #include 33 | #include 34 | 35 | namespace staticcodes { 36 | 37 | // ------------------------------------------------------- 38 | // ----------------------- ACODER ------------------------ 39 | // ------------------------------------------------------- 40 | 41 | class acoder { 42 | class CoderImpl; 43 | std::unique_ptr m_pImpl; 44 | 45 | public: 46 | 47 | // Encodes text and writes the final bit sequence to the output file 48 | void compress(std::ifstream& ifile, std::ofstream& ofile); 49 | 50 | void operator()(std::ifstream& ifile, std::ofstream& ofile); 51 | 52 | acoder(std::ifstream& ifile, std::ofstream& ofile); 53 | 54 | acoder(); 55 | 56 | ~acoder(); 57 | }; 58 | 59 | // ------------------------------------------------------- 60 | // ----------------------- DECODER ----------------------- 61 | // ------------------------------------------------------- 62 | 63 | class adecoder { 64 | class DecoderImpl; 65 | std::unique_ptr m_pImpl; 66 | 67 | public: 68 | 69 | // Decodes text and writes the final bit sequence to the output file 70 | void decompress(std::ifstream& ifile, std::ofstream& ofile); 71 | 72 | void operator()(std::ifstream& ifile, std::ofstream& ofile); 73 | 74 | adecoder(std::ifstream& ifile, std::ofstream& ofile); 75 | 76 | adecoder(); 77 | 78 | ~adecoder(); 79 | }; 80 | 81 | } 82 | 83 | #endif // ACODER_HXX 84 | -------------------------------------------------------------------------------- /src/ahcoder.cxx: -------------------------------------------------------------------------------- 1 | /** 2 | * ahcoder.cxx 3 | * 4 | * Adaptive Huffman Coding (FGK Algorithm) 5 | * by snovvcrash 6 | * 04.2017 7 | */ 8 | 9 | /** 10 | * Copyright (C) 2017 snovvcrash 11 | * 12 | * This file is part of libcoders. 13 | * 14 | * libcoders is free software: you can redistribute it and/or modify 15 | * it under the terms of the GNU General Public License as published by 16 | * the Free Software Foundation, either version 3 of the License, or 17 | * (at your option) any later version. 18 | * 19 | * libcoders is distributed in the hope that it will be useful, 20 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 21 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 22 | * GNU General Public License for more details. 23 | * 24 | * You should have received a copy of the GNU General Public License 25 | * along with libcoders. If not, see . 26 | */ 27 | 28 | #include 29 | #include 30 | #include // size_t 31 | #include 32 | #include 33 | #include 34 | #include // CHAR_BIT 35 | #include "ahcoder.hxx" 36 | 37 | namespace adaptivecodes { 38 | 39 | using bitseq_t = std::vector; 40 | using symbseq_t = std::vector; 41 | 42 | constexpr size_t MAX_LEAF_NUM = 256; 43 | constexpr size_t MAX_NODE_NUM = 512; 44 | 45 | // NYT = Not Yet Transmitted 46 | enum node_type {NYT_NODE = -1, INTERNAL_NODE = -2}; 47 | 48 | // ------------------------------------------------------- 49 | // ------------------------ NODE ------------------------- 50 | // ------------------------------------------------------- 51 | 52 | struct Node { 53 | int symbol; 54 | int order; 55 | uint64_t weight; 56 | 57 | Node* parent; 58 | Node* left; 59 | Node* right; 60 | 61 | Node( 62 | int symbol_, 63 | int order_, 64 | uint64_t weight_ = 0, 65 | Node* parent_ = nullptr, 66 | Node* left_ = nullptr, 67 | Node* right_ = nullptr 68 | ) 69 | : symbol(symbol_), order(order_), weight(weight_), parent(parent_), left(left_), right(right_) 70 | { } 71 | }; 72 | 73 | // ------------------------------------------------------- 74 | // ------------------------- FGK ------------------------- 75 | // ------------------------------------------------------- 76 | 77 | class fgk { 78 | Node* m_nyt; 79 | Node* m_root; 80 | Node* m_leaves[MAX_LEAF_NUM]; 81 | Node* m_nodes[MAX_NODE_NUM + 1]; 82 | Node* m_dcurr; 83 | bitseq_t m_buf; 84 | 85 | void update_tree(Node* node) { 86 | while (node) { 87 | Node* highest = highest_in_class(node); 88 | swap(highest, node); 89 | 90 | ++node->weight; 91 | 92 | node = node->parent; 93 | } 94 | } 95 | 96 | Node* highest_in_class(Node* node) const { 97 | Node* highest = node; 98 | int num = node->order; 99 | 100 | for (size_t i = num + 1; i <= MAX_NODE_NUM && m_nodes[i]->weight == node->weight; ++i) 101 | highest = m_nodes[i]; 102 | 103 | return highest; 104 | } 105 | 106 | void swap(Node* a, Node* b) { 107 | if (a == m_root || b == m_root || a == b || a->parent == b || b->parent == a) 108 | return; 109 | 110 | if (a->parent->left == a && b->parent->left == b) 111 | std::swap(a->parent->left, b->parent->left); 112 | else if (a->parent->left == a && b->parent->right == b) 113 | std::swap(a->parent->left, b->parent->right); 114 | else if (a->parent->right == a && b->parent->left == b) 115 | std::swap(a->parent->right, b->parent->left); 116 | else if (a->parent->right == a && b->parent->right == b) 117 | std::swap(a->parent->right, b->parent->right); 118 | 119 | std::swap(m_nodes[a->order], m_nodes[b->order]); 120 | std::swap(a->order, b->order); 121 | std::swap(a->parent, b->parent); 122 | } 123 | 124 | bool is_in_tree(uint8_t byte) const { 125 | if (m_leaves[byte]) return 1; 126 | return 0; 127 | } 128 | 129 | bitseq_t get_symbol_code(const Node* symbolNode) const { 130 | bitseq_t code; 131 | code.reserve(16); 132 | 133 | const Node* currNode = symbolNode; 134 | while (currNode != m_root) { 135 | /* if (currNode->parent->left == currNode) 136 | code.push_back(0); 137 | else 138 | code.push_back(1); */ 139 | code.push_back(currNode->parent->right == currNode); 140 | currNode = currNode->parent; 141 | } 142 | 143 | std::reverse(code.begin(), code.end()); 144 | return code; 145 | } 146 | 147 | void encode_existing_byte(uint8_t byte) { 148 | update_tree(m_leaves[byte]); 149 | } 150 | 151 | void encode_new_byte(uint8_t byte) { 152 | m_nyt->symbol = INTERNAL_NODE; 153 | m_nyt->left = new Node(NYT_NODE, m_nyt->order - 2, 0, m_nyt); 154 | m_nyt->right = new Node(byte, m_nyt->order - 1, 0, m_nyt); 155 | 156 | m_leaves[byte] = m_nyt->right; 157 | m_nodes[m_nyt->left->order] = m_nyt->left; 158 | m_nodes[m_nyt->right->order] = m_nyt->right; 159 | 160 | m_nyt = m_nyt->left; 161 | 162 | update_tree(m_leaves[byte]); 163 | } 164 | 165 | void delete_tree() { delete_tree(m_root); } 166 | 167 | void delete_tree(const Node* m_root) { 168 | if (!m_root) return; 169 | 170 | delete_tree(m_root->left); 171 | delete_tree(m_root->right); 172 | delete m_root; 173 | } 174 | 175 | public: 176 | fgk() : m_nyt(new Node(NYT_NODE, MAX_NODE_NUM)), m_root(m_nyt), m_dcurr(m_root) { 177 | for (auto&& leaf : m_leaves) 178 | leaf = nullptr; 179 | for (auto&& node: m_nodes) 180 | node = nullptr; 181 | 182 | m_nodes[MAX_NODE_NUM] = m_nyt; 183 | } 184 | 185 | ~fgk() { delete_tree(); } 186 | 187 | bitseq_t encode(uint8_t byte) { 188 | if (is_in_tree(byte)) { 189 | bitseq_t code = get_symbol_code(m_leaves[byte]); 190 | 191 | encode_existing_byte(byte); 192 | 193 | return code; 194 | } 195 | else { 196 | bitseq_t code = get_symbol_code(m_nyt); 197 | 198 | for (size_t i = 0; i < CHAR_BIT; ++i) 199 | code.push_back(byte & (1 << (7 - i))); 200 | 201 | encode_new_byte(byte); 202 | 203 | return code; 204 | } 205 | } 206 | 207 | symbseq_t decode(const bitseq_t& codeseq) { 208 | symbseq_t symbseq; 209 | 210 | std::copy(std::begin(codeseq), std::end(codeseq), std::back_inserter(m_buf)); 211 | 212 | size_t i = 0; 213 | while (i < m_buf.size() || (!m_dcurr->left && !m_dcurr->right)) 214 | if (m_dcurr->symbol == NYT_NODE) { 215 | if (m_buf.size() - i >= CHAR_BIT) { 216 | uint8_t ascii_char = 0; 217 | 218 | for (size_t j = 0; j < CHAR_BIT; ++j) 219 | ascii_char |= m_buf[i + j] << (7 - j); 220 | 221 | symbseq.push_back(ascii_char); 222 | 223 | encode_new_byte(ascii_char); 224 | 225 | i += CHAR_BIT; 226 | m_dcurr = m_root; 227 | } 228 | else break; // end of file 229 | } 230 | else if (!m_dcurr->left && !m_dcurr->right) { 231 | symbseq.push_back(m_dcurr->symbol); 232 | 233 | encode_existing_byte(m_dcurr->symbol); 234 | 235 | m_dcurr = m_root; 236 | } 237 | else { 238 | if (m_buf[i]) m_dcurr = m_dcurr->right; 239 | else m_dcurr = m_dcurr->left; 240 | ++i; 241 | } 242 | 243 | m_buf.erase(std::begin(m_buf), std::begin(m_buf) + i); 244 | 245 | return symbseq; 246 | } 247 | 248 | bitseq_t get_nyt_code() const { 249 | return get_symbol_code(m_nyt); 250 | } 251 | }; 252 | 253 | // ------------------------------------------------------- 254 | // ---------------------- CODERIMPL ---------------------- 255 | // ------------------------------------------------------- 256 | 257 | class ahcoder::CoderImpl : private fgk { 258 | void flush_output_buffer(std::ostream& ofile, bitseq_t& outbuf) { 259 | symbseq_t out_bytes; 260 | out_bytes.reserve((MAX_NODE_NUM * CHAR_BIT) / 2); 261 | 262 | size_t pos = 0; 263 | while (pos + CHAR_BIT <= outbuf.size()) { 264 | uint8_t byte = 0; 265 | 266 | for (size_t i = 0; i < CHAR_BIT; ++i) 267 | if (outbuf[pos + i]) 268 | byte |= 1 << (7 - i); 269 | 270 | out_bytes.push_back(byte); 271 | 272 | pos += CHAR_BIT; 273 | } 274 | 275 | outbuf.erase(std::begin(outbuf), std::begin(outbuf) + pos); 276 | ofile.write(reinterpret_cast(&out_bytes.front()), out_bytes.size()); 277 | } 278 | 279 | public: 280 | void compress(std::ifstream& ifile, std::ofstream& ofile) { 281 | uint8_t inbuf[MAX_NODE_NUM]; 282 | 283 | bitseq_t outbuf; 284 | outbuf.reserve(MAX_NODE_NUM * CHAR_BIT + 64); 285 | 286 | while (ifile.good()) { 287 | ifile.read(reinterpret_cast(inbuf), MAX_NODE_NUM); 288 | size_t bytes_read = ifile.gcount(); 289 | 290 | for (size_t i = 0; i < bytes_read ; ++i) { 291 | bitseq_t code = encode(inbuf[i]); 292 | std::copy(std::begin(code), std::end(code), std::back_inserter(outbuf)); 293 | } 294 | 295 | if (outbuf.size() >= MAX_NODE_NUM * CHAR_BIT) 296 | flush_output_buffer(ofile, outbuf); 297 | } 298 | 299 | if (!outbuf.empty()) { 300 | if (outbuf.size() % CHAR_BIT != 0) { 301 | bitseq_t nyt_code = get_nyt_code(); 302 | 303 | size_t extra_bits = CHAR_BIT - outbuf.size() % CHAR_BIT; 304 | for (size_t i = 0; i < extra_bits; ++i) 305 | outbuf.push_back(nyt_code[i % nyt_code.size()]); 306 | } 307 | 308 | flush_output_buffer(ofile, outbuf); 309 | } 310 | } 311 | 312 | void operator()(std::ifstream& ifile, std::ofstream& ofile) { 313 | compress(ifile, ofile); 314 | } 315 | 316 | CoderImpl(std::ifstream& ifile, std::ofstream& ofile) { 317 | compress(ifile, ofile); 318 | } 319 | 320 | CoderImpl() 321 | { } 322 | }; 323 | 324 | void ahcoder::compress(std::ifstream& ifile, std::ofstream& ofile) { 325 | m_pImpl->compress(ifile, ofile); 326 | } 327 | 328 | void ahcoder::operator()(std::ifstream& ifile, std::ofstream& ofile) { 329 | m_pImpl->operator()(ifile, ofile); 330 | } 331 | 332 | ahcoder::ahcoder(std::ifstream& ifile, std::ofstream& ofile) 333 | : m_pImpl(new CoderImpl(ifile, ofile)) 334 | { } 335 | 336 | ahcoder::ahcoder() : m_pImpl(new CoderImpl) 337 | { } 338 | 339 | ahcoder::~ahcoder() 340 | { } 341 | 342 | // ------------------------------------------------------- 343 | // --------------------- DECODERIMPL --------------------- 344 | // ------------------------------------------------------- 345 | 346 | class ahdecoder::DecoderImpl : private fgk { 347 | public: 348 | void decompress(std::ifstream& ifile, std::ofstream& ofile) { 349 | uint8_t inbuf[MAX_NODE_NUM]; 350 | 351 | while (ifile.good()) { 352 | ifile.read(reinterpret_cast(inbuf), MAX_NODE_NUM); 353 | size_t bytes_read = ifile.gcount(); 354 | 355 | bitseq_t seq; 356 | seq.reserve(MAX_NODE_NUM * CHAR_BIT); 357 | 358 | for (size_t i = 0; i < bytes_read; ++i) { 359 | bitseq_t code(CHAR_BIT); 360 | for (size_t j = 0; j < CHAR_BIT; ++j) 361 | code[j] = inbuf[i] & (1 << (7 - j)); 362 | 363 | std::copy(std::begin(code), std::end(code), std::back_inserter(seq)); 364 | } 365 | 366 | symbseq_t outbuf = decode(seq); 367 | ofile.write(reinterpret_cast(&outbuf.front()), outbuf.size()); 368 | } 369 | } 370 | 371 | void operator()(std::ifstream& ifile, std::ofstream& ofile) { 372 | decompress(ifile, ofile); 373 | } 374 | 375 | DecoderImpl(std::ifstream& ifile, std::ofstream& ofile) { 376 | decompress(ifile, ofile); 377 | } 378 | 379 | DecoderImpl() 380 | { } 381 | }; 382 | 383 | void ahdecoder::decompress(std::ifstream& ifile, std::ofstream& ofile) { 384 | m_pImpl->decompress(ifile, ofile); 385 | } 386 | 387 | void ahdecoder::operator()(std::ifstream& ifile, std::ofstream& ofile) { 388 | m_pImpl->operator()(ifile, ofile); 389 | } 390 | 391 | ahdecoder::ahdecoder(std::ifstream& ifile, std::ofstream& ofile) 392 | : m_pImpl(new DecoderImpl(ifile, ofile)) 393 | { } 394 | 395 | ahdecoder::ahdecoder() : m_pImpl(new DecoderImpl) 396 | { } 397 | 398 | ahdecoder::~ahdecoder() 399 | { } 400 | 401 | } 402 | -------------------------------------------------------------------------------- /src/ahcoder.hxx: -------------------------------------------------------------------------------- 1 | /** 2 | * ahcoder.hxx 3 | * 4 | * Adaptive Huffman Coding (FGK Algorithm) 5 | * by snovvcrash 6 | * 04.2017 7 | */ 8 | 9 | /** 10 | * Copyright (C) 2017 snovvcrash 11 | * 12 | * This file is part of libcoders. 13 | * 14 | * libcoders is free software: you can redistribute it and/or modify 15 | * it under the terms of the GNU General Public License as published by 16 | * the Free Software Foundation, either version 3 of the License, or 17 | * (at your option) any later version. 18 | * 19 | * libcoders is distributed in the hope that it will be useful, 20 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 21 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 22 | * GNU General Public License for more details. 23 | * 24 | * You should have received a copy of the GNU General Public License 25 | * along with libcoders. If not, see . 26 | */ 27 | 28 | #pragma once 29 | #ifndef AHCODER_HXX 30 | #define AHCODER_HXX 31 | 32 | #include 33 | #include 34 | 35 | namespace adaptivecodes { 36 | 37 | // ------------------------------------------------------- 38 | // ----------------------- AHCODER ----------------------- 39 | // ------------------------------------------------------- 40 | 41 | class ahcoder { 42 | class CoderImpl; 43 | std::unique_ptr m_pImpl; 44 | 45 | public: 46 | 47 | // Encodes text and writes the final bit sequence to the output file 48 | void compress(std::ifstream& ifile, std::ofstream& ofile); 49 | 50 | void operator()(std::ifstream& ifile, std::ofstream& ofile); 51 | 52 | ahcoder(std::ifstream& ifile, std::ofstream& ofile); 53 | 54 | ahcoder(); 55 | 56 | ~ahcoder(); 57 | }; 58 | 59 | // ------------------------------------------------------- 60 | // ---------------------- AHDECODER ---------------------- 61 | // ------------------------------------------------------- 62 | 63 | class ahdecoder { 64 | class DecoderImpl; 65 | std::unique_ptr m_pImpl; 66 | 67 | public: 68 | 69 | // Decodes text and writes the final bit sequence to the output file 70 | void decompress(std::ifstream& ifile, std::ofstream& ofile); 71 | 72 | void operator()(std::ifstream& ifile, std::ofstream& ofile); 73 | 74 | ahdecoder(std::ifstream& ifile, std::ofstream& ofile); 75 | 76 | ahdecoder(); 77 | 78 | ~ahdecoder(); 79 | }; 80 | 81 | } 82 | 83 | #endif // AHCODER_HXX 84 | -------------------------------------------------------------------------------- /src/bhcoder.cxx: -------------------------------------------------------------------------------- 1 | /** 2 | * bhcoder.cxx 3 | * 4 | * Huffman Coding on Bigrams (Markov Chain with Depth 1) 5 | * by snovvcrash 6 | * 04.2017 7 | */ 8 | 9 | /** 10 | * Copyright (C) 2017 snovvcrash 11 | * 12 | * This file is part of libcoders. 13 | * 14 | * libcoders is free software: you can redistribute it and/or modify 15 | * it under the terms of the GNU General Public License as published by 16 | * the Free Software Foundation, either version 3 of the License, or 17 | * (at your option) any later version. 18 | * 19 | * libcoders is distributed in the hope that it will be useful, 20 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 21 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 22 | * GNU General Public License for more details. 23 | * 24 | * You should have received a copy of the GNU General Public License 25 | * along with libcoders. If not, see . 26 | */ 27 | 28 | #include 29 | #include 30 | #include // size_t 31 | #include 32 | #include 33 | #include 34 | #include 35 | #include 36 | #include // std::pair 37 | #include // CHAR_BIT 38 | #include "bhcoder.hxx" 39 | 40 | namespace contextcodes { 41 | 42 | using freq_vec_t = typename std::vector; 43 | using freq_table_t = typename std::vector; 44 | using scheme_vec_t = typename std::vector >; 45 | using scheme_table_t = typename std::vector; 46 | using bitseq_t = typename std::vector; 47 | 48 | constexpr size_t ALPHABET = 256; 49 | 50 | // ------------------------------------------------------ 51 | // --------------------- STATISTICS --------------------- 52 | // ------------------------------------------------------ 53 | 54 | class Statistics { 55 | protected: 56 | freq_vec_t m_freq_vec; 57 | freq_table_t m_freq_table; 58 | uint64_t m_total_chars; 59 | 60 | void create_freq_vector(std::ifstream& ifile) { 61 | m_freq_vec.clear(); 62 | m_freq_vec.resize(ALPHABET, 0); 63 | 64 | m_freq_table.clear(); 65 | m_freq_table.resize(ALPHABET); 66 | 67 | char c; 68 | char context; 69 | 70 | ifile.read(&context, sizeof(context)); 71 | ++m_freq_vec[static_cast(context)]; 72 | m_total_chars = 1; 73 | 74 | while (ifile.read(&c, sizeof(c))) { 75 | if (m_freq_table[static_cast(context)].empty()) { 76 | m_freq_table[static_cast(context)].clear(); 77 | m_freq_table[static_cast(context)].resize(ALPHABET, 0); 78 | } 79 | 80 | ++m_freq_vec[static_cast(c)]; 81 | ++m_freq_table[static_cast(context)][static_cast(c)]; 82 | 83 | ++m_total_chars; 84 | context = c; 85 | } 86 | } 87 | 88 | Statistics() 89 | { } 90 | }; 91 | 92 | // ------------------------------------------------------ 93 | // ------------------------ NODE ------------------------ 94 | // ------------------------------------------------------ 95 | 96 | struct Node { 97 | int left; 98 | int right; 99 | uint8_t symbol; 100 | 101 | Node(int l, int r, uint8_t s) { 102 | left = l; 103 | right = r; 104 | symbol = s; 105 | } 106 | }; 107 | 108 | // ------------------------------------------------------ 109 | // --------------------- CODE-TREE ---------------------- 110 | // ------------------------------------------------------ 111 | 112 | using tree_t = typename std::vector; 113 | using forest_t = typename std::vector; 114 | 115 | class CodeTree { 116 | protected: 117 | void traverse_code_tree(tree_t& m_tree, scheme_vec_t& m_scheme_vec, int index, bitseq_t code) { 118 | if (index == -1) return; 119 | 120 | if (m_tree[index].left == -1 && m_tree[index].right == -1) { 121 | m_scheme_vec[m_tree[index].symbol] = code; 122 | return; 123 | } 124 | 125 | code.push_back(0); 126 | traverse_code_tree(m_tree, m_scheme_vec, m_tree[index].left, code); 127 | code.pop_back(); 128 | 129 | code.push_back(1); 130 | traverse_code_tree(m_tree, m_scheme_vec, m_tree[index].right, code); 131 | code.pop_back(); 132 | } 133 | 134 | CodeTree() 135 | { } 136 | }; 137 | 138 | // ------------------------------------------------------- 139 | // ----------------------- HUFFMAN ----------------------- 140 | // ------------------------------------------------------- 141 | 142 | class huffman : private CodeTree { 143 | void create_code_tree(freq_vec_t& m_freq_vec) { 144 | using pair_t = typename std::pair; 145 | std::priority_queue, std::greater > queue; 146 | 147 | for (size_t i = 0; i < m_freq_vec.size(); ++i) { 148 | if (m_freq_vec[i]) { 149 | m_tree.push_back(Node(-1, -1, i)); 150 | queue.push(pair_t(m_freq_vec[i], m_tree.size() - 1)); 151 | } 152 | } 153 | 154 | while (queue.size() > 1) { 155 | pair_t child1; 156 | pair_t child2; 157 | uint32_t parent_w; 158 | 159 | child1 = queue.top(); queue.pop(); 160 | child2 = queue.top(); queue.pop(); 161 | parent_w = child1.first + child2.first; 162 | 163 | m_tree.push_back(Node(child1.second, child2.second, 0)); 164 | queue.push(pair_t(parent_w, m_tree.size() - 1)); 165 | } 166 | 167 | if (m_tree.size() == 1) m_tree.push_back(Node(0, -1, 0)); 168 | } 169 | 170 | public: 171 | tree_t m_tree; 172 | scheme_vec_t m_scheme_vec; 173 | 174 | void create_code_scheme(freq_vec_t& m_freq_vec) { 175 | m_scheme_vec.clear(); 176 | m_scheme_vec.resize(ALPHABET); 177 | 178 | if (m_freq_vec.empty()) return; 179 | if (m_freq_vec.size() == 1) { 180 | m_scheme_vec[m_freq_vec.front()] = bitseq_t(1, 0); 181 | return; 182 | } 183 | 184 | create_code_tree(m_freq_vec); 185 | traverse_code_tree(m_tree, m_scheme_vec, m_tree.size() - 1, bitseq_t()); 186 | } 187 | }; 188 | 189 | // ------------------------------------------------------- 190 | // ---------------------- CODERIMPL ---------------------- 191 | // ------------------------------------------------------- 192 | 193 | class bhcoder::CoderImpl : private Statistics, private huffman { 194 | scheme_table_t m_scheme_table; 195 | bitseq_t m_seq; 196 | char m_context; 197 | 198 | void encode_first_byte(std::ifstream& ifile) { 199 | m_seq.clear(); 200 | 201 | ifile.clear(); 202 | ifile.seekg(0, std::ios::beg); 203 | 204 | char c; 205 | if (ifile.read(&c, sizeof(c))) { 206 | m_seq.insert( 207 | m_seq.end(), 208 | m_scheme_vec[static_cast(c)].begin(), 209 | m_scheme_vec[static_cast(c)].end() 210 | ); 211 | 212 | m_context = c; 213 | } 214 | } 215 | 216 | void create_bit_sequence(std::ifstream& ifile) { 217 | char c; 218 | while (ifile.read(&c, sizeof(c))) { 219 | m_seq.insert( 220 | m_seq.end(), 221 | m_scheme_table[static_cast(m_context)][static_cast(c)].begin(), 222 | m_scheme_table[static_cast(m_context)][static_cast(c)].end() 223 | ); 224 | 225 | m_context = c; 226 | } 227 | } 228 | 229 | public: 230 | void compress(std::ifstream& ifile, std::ofstream& ofile) { 231 | create_freq_vector(ifile); 232 | create_code_scheme(m_freq_vec); 233 | encode_first_byte(ifile); 234 | m_tree.clear(); 235 | 236 | for (const auto& freq : m_freq_vec) 237 | ofile.write(reinterpret_cast(&freq), sizeof(freq)); 238 | 239 | m_scheme_table.clear(); 240 | m_scheme_table.resize(ALPHABET); 241 | 242 | for (size_t i = 0; i < m_freq_table.size(); ++i) { 243 | if (!m_freq_table[i].empty()) { 244 | create_code_scheme(m_freq_table[i]); 245 | m_scheme_table[i].clear(); 246 | m_scheme_table[i].insert(m_scheme_table[i].end(), m_scheme_vec.begin(), m_scheme_vec.end()); 247 | m_tree.clear(); 248 | } 249 | } 250 | 251 | create_bit_sequence(ifile); 252 | 253 | size_t num_not_empty = 0; 254 | for (const auto& freq_vec : m_freq_table) 255 | if (!freq_vec.empty()) 256 | ++num_not_empty; 257 | ofile.write(reinterpret_cast(&num_not_empty), sizeof(num_not_empty)); 258 | 259 | for (size_t context = 0; context < m_freq_table.size(); ++context) { 260 | if (!m_freq_table[context].empty()) { 261 | ofile.write(reinterpret_cast(&context), sizeof(context)); 262 | for (const auto& freq : m_freq_table[context]) 263 | ofile.write(reinterpret_cast(&freq), sizeof(freq)); 264 | } 265 | } 266 | 267 | uint8_t bit_buffer = 0; 268 | size_t bit_counter = 0; 269 | 270 | for (const auto& bit : m_seq) { 271 | bit_buffer |= bit << (7 - bit_counter); 272 | 273 | if (++bit_counter == CHAR_BIT) { 274 | ofile.write(reinterpret_cast(&bit_buffer), sizeof(bit_buffer)); 275 | bit_buffer = 0; 276 | bit_counter = 0; 277 | } 278 | } 279 | 280 | if (bit_counter) ofile.write(reinterpret_cast(&bit_buffer), sizeof(bit_buffer)); 281 | } 282 | 283 | void operator()(std::ifstream& ifile, std::ofstream& ofile) { 284 | compress(ifile, ofile); 285 | } 286 | 287 | CoderImpl(std::ifstream& ifile, std::ofstream& ofile) { 288 | compress(ifile, ofile); 289 | } 290 | 291 | CoderImpl() 292 | { } 293 | }; 294 | 295 | void bhcoder::compress(std::ifstream& ifile, std::ofstream& ofile) { 296 | m_pImpl->compress(ifile, ofile); 297 | } 298 | 299 | void bhcoder::operator()(std::ifstream& ifile, std::ofstream& ofile) { 300 | m_pImpl->operator()(ifile, ofile); 301 | } 302 | 303 | bhcoder::bhcoder(std::ifstream& ifile, std::ofstream& ofile) 304 | : m_pImpl(new CoderImpl(ifile, ofile)) 305 | { } 306 | 307 | bhcoder::bhcoder() : m_pImpl(new CoderImpl) 308 | { } 309 | 310 | bhcoder::~bhcoder() 311 | { } 312 | 313 | // ------------------------------------------------------- 314 | // --------------------- DECODERIMPL --------------------- 315 | // ------------------------------------------------------- 316 | 317 | class bhdecoder::DecoderImpl : private Statistics, private huffman { 318 | forest_t m_forest; 319 | char m_context; 320 | 321 | std::pair decode_first_byte(std::ifstream& ifile, std::ofstream& ofile) { 322 | char curr_byte; 323 | int curr_index = m_tree.size() - 1; 324 | size_t bit_counter = 0; 325 | 326 | ifile.read(&curr_byte, sizeof(curr_byte)); 327 | 328 | while (true) { 329 | bool curr_bit = curr_byte & (1 << (7 - bit_counter)); 330 | 331 | if (!curr_bit) curr_index = m_tree[curr_index].left; 332 | else curr_index = m_tree[curr_index].right; 333 | 334 | if (m_tree[curr_index].left == -1 && m_tree[curr_index].right == -1) { 335 | char symbol = m_tree[curr_index].symbol; 336 | ofile.write(&symbol, sizeof(symbol)); 337 | 338 | if (m_total_chars == 1) return std::make_pair(0, -1); 339 | 340 | m_context = symbol; 341 | ++bit_counter; 342 | 343 | return std::make_pair(curr_byte, bit_counter); 344 | } 345 | 346 | if (++bit_counter == CHAR_BIT) { 347 | ifile.read(&curr_byte, sizeof(curr_byte)); 348 | bit_counter = 0; 349 | } 350 | } 351 | } 352 | 353 | public: 354 | void decompress(std::ifstream& ifile, std::ofstream& ofile) { 355 | m_freq_vec.clear(); 356 | m_total_chars = 0; 357 | 358 | for (size_t i = 0; i < ALPHABET; ++i) { 359 | uint32_t tmp; 360 | ifile.read(reinterpret_cast(&tmp), sizeof(tmp)); 361 | m_freq_vec.push_back(tmp); 362 | m_total_chars += tmp; 363 | } 364 | 365 | m_freq_table.clear(); 366 | m_freq_table.resize(ALPHABET); 367 | 368 | size_t num_not_empty; 369 | ifile.read(reinterpret_cast(&num_not_empty), sizeof(num_not_empty)); 370 | 371 | for (size_t i = 0; i < num_not_empty; ++i) { 372 | size_t context; 373 | ifile.read(reinterpret_cast(&context), sizeof(context)); 374 | for (size_t j = 0; j < ALPHABET; ++j) { 375 | uint32_t tmp; 376 | ifile.read(reinterpret_cast(&tmp), sizeof(tmp)); 377 | m_freq_table[context].push_back(tmp); 378 | } 379 | } 380 | 381 | if (ifile.peek() == EOF) { 382 | if (!ifile.eof()) 383 | std::cerr << "bhdecoder::decompress: " << std::strerror(errno) << std::endl; 384 | return; 385 | } 386 | 387 | create_code_scheme(m_freq_vec); 388 | std::pair first_byte_ret = decode_first_byte(ifile, ofile); 389 | if (first_byte_ret.second == -1) return; 390 | m_tree.clear(); 391 | 392 | m_forest.clear(); 393 | m_forest.resize(ALPHABET); 394 | 395 | for (size_t i = 0; i < m_freq_table.size(); ++i) { 396 | if (!m_freq_table[i].empty()) { 397 | create_code_scheme(m_freq_table[i]); 398 | m_forest[i].insert(m_forest[i].end(), m_tree.begin(), m_tree.end()); 399 | m_tree.clear(); 400 | } 401 | } 402 | 403 | char curr_byte = first_byte_ret.first; 404 | int curr_index = m_forest[static_cast(m_context)].size() - 1;; 405 | size_t bit_counter = first_byte_ret.second; 406 | uint64_t cnt_chars = 1; 407 | 408 | if (bit_counter == CHAR_BIT) { 409 | ifile.read(&curr_byte, sizeof(curr_byte)); 410 | bit_counter = 0; 411 | } 412 | 413 | while (true) { 414 | bool curr_bit = curr_byte & (1 << (7 - bit_counter)); 415 | 416 | if (!curr_bit) curr_index = m_forest[static_cast(m_context)][curr_index].left; 417 | else curr_index = m_forest[static_cast(m_context)][curr_index].right; 418 | 419 | if (m_forest[static_cast(m_context)][curr_index].left == -1 && 420 | m_forest[static_cast(m_context)][curr_index].right == -1 421 | ) { 422 | char symbol = m_forest[static_cast(m_context)][curr_index].symbol; 423 | ofile.write(&symbol, sizeof(symbol)); 424 | 425 | m_context = symbol; 426 | ++cnt_chars; 427 | 428 | curr_index = m_forest[static_cast(m_context)].size() - 1; 429 | } 430 | 431 | if (cnt_chars == m_total_chars) break; 432 | 433 | if (++bit_counter == CHAR_BIT) { 434 | ifile.read(&curr_byte, sizeof(curr_byte)); 435 | bit_counter = 0; 436 | } 437 | } 438 | } 439 | 440 | void operator()(std::ifstream& ifile, std::ofstream& ofile) { 441 | decompress(ifile, ofile); 442 | } 443 | 444 | DecoderImpl(std::ifstream& ifile, std::ofstream& ofile) { 445 | decompress(ifile, ofile); 446 | } 447 | 448 | DecoderImpl() 449 | { } 450 | }; 451 | 452 | void bhdecoder::decompress(std::ifstream& ifile, std::ofstream& ofile) { 453 | m_pImpl->decompress(ifile, ofile); 454 | } 455 | 456 | void bhdecoder::operator()(std::ifstream& ifile, std::ofstream& ofile) { 457 | m_pImpl->operator()(ifile, ofile); 458 | } 459 | 460 | bhdecoder::bhdecoder(std::ifstream& ifile, std::ofstream& ofile) 461 | : m_pImpl(new DecoderImpl(ifile, ofile)) 462 | { } 463 | 464 | bhdecoder::bhdecoder() : m_pImpl(new DecoderImpl) 465 | { } 466 | 467 | bhdecoder::~bhdecoder() 468 | { } 469 | 470 | } 471 | -------------------------------------------------------------------------------- /src/bhcoder.hxx: -------------------------------------------------------------------------------- 1 | /** 2 | * bhcoder.hxx 3 | * 4 | * Huffman Coding on Bigrams (Markov Chain with Depth 1) 5 | * by snovvcrash 6 | * 04.2017 7 | */ 8 | 9 | /** 10 | * Copyright (C) 2017 snovvcrash 11 | * 12 | * This file is part of libcoders. 13 | * 14 | * libcoders is free software: you can redistribute it and/or modify 15 | * it under the terms of the GNU General Public License as published by 16 | * the Free Software Foundation, either version 3 of the License, or 17 | * (at your option) any later version. 18 | * 19 | * libcoders is distributed in the hope that it will be useful, 20 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 21 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 22 | * GNU General Public License for more details. 23 | * 24 | * You should have received a copy of the GNU General Public License 25 | * along with libcoders. If not, see . 26 | */ 27 | 28 | #pragma once 29 | #ifndef BHCODER_HXX 30 | #define BHCODER_HXX 31 | 32 | #include 33 | #include 34 | 35 | namespace contextcodes { 36 | 37 | // ------------------------------------------------------- 38 | // ----------------------- BHCODER ----------------------- 39 | // ------------------------------------------------------- 40 | 41 | class bhcoder { 42 | class CoderImpl; 43 | std::unique_ptr m_pImpl; 44 | 45 | public: 46 | 47 | // Encodes text and writes the final bit sequence to the output file 48 | void compress(std::ifstream& ifile, std::ofstream& ofile); 49 | 50 | void operator()(std::ifstream& ifile, std::ofstream& ofile); 51 | 52 | bhcoder(std::ifstream& ifile, std::ofstream& ofile); 53 | 54 | bhcoder(); 55 | 56 | ~bhcoder(); 57 | }; 58 | 59 | // ------------------------------------------------------- 60 | // ---------------------- BHDECODER ---------------------- 61 | // ------------------------------------------------------- 62 | 63 | class bhdecoder { 64 | class DecoderImpl; 65 | std::unique_ptr m_pImpl; 66 | 67 | public: 68 | 69 | // Decodes text and writes the final bit sequence to the output file 70 | void decompress(std::ifstream& ifile, std::ofstream& ofile); 71 | 72 | void operator()(std::ifstream& ifile, std::ofstream& ofile); 73 | 74 | bhdecoder(std::ifstream& ifile, std::ofstream& ofile); 75 | 76 | bhdecoder(); 77 | 78 | ~bhdecoder(); 79 | }; 80 | 81 | } 82 | 83 | #endif // BHCODER_HXX 84 | -------------------------------------------------------------------------------- /src/pcoder.cxx: -------------------------------------------------------------------------------- 1 | /** 2 | * pcoder.cxx 3 | * 4 | * Shennon, Fano, Huffman Coding 5 | * by snovvcrash 6 | * 04.2017 7 | */ 8 | 9 | /** 10 | * Copyright (C) 2017 snovvcrash 11 | * 12 | * This file is part of libcoders. 13 | * 14 | * libcoders is free software: you can redistribute it and/or modify 15 | * it under the terms of the GNU General Public License as published by 16 | * the Free Software Foundation, either version 3 of the License, or 17 | * (at your option) any later version. 18 | * 19 | * libcoders is distributed in the hope that it will be useful, 20 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 21 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 22 | * GNU General Public License for more details. 23 | * 24 | * You should have received a copy of the GNU General Public License 25 | * along with libcoders. If not, see . 26 | */ 27 | 28 | #include 29 | #include 30 | #include // size_t, std::abs 31 | #include 32 | #include 33 | #include 34 | #include // std::pair 35 | #include // std::stable_sort 36 | #include // std::greater 37 | #include "pcoder.hxx" 38 | 39 | namespace staticcodes { 40 | 41 | // ------------------------------------------------------ 42 | // --------------------- STATISTICS --------------------- 43 | // ------------------------------------------------------ 44 | 45 | void Statistics::create_freq_vector(std::ifstream& ifile) { 46 | m_freq_vec.clear(); 47 | m_freq_vec.resize(ALPHABET, 0); 48 | 49 | m_total_chars = 0; 50 | 51 | char c; 52 | while (ifile.read(&c, sizeof(c))) { 53 | ++m_freq_vec[static_cast(c)]; 54 | ++m_total_chars; 55 | } 56 | } 57 | 58 | void Statistics::create_distr_vector() { 59 | m_distr_vec.clear(); 60 | 61 | if (!m_total_chars) return; 62 | using pair_t = typename std::pair; 63 | 64 | for (size_t i = 0; i < m_freq_vec.size(); ++i) { 65 | pair_t tmp; 66 | tmp.first = i; 67 | tmp.second = m_freq_vec[i] / static_cast(m_total_chars); 68 | if (tmp.second > 0) m_distr_vec.push_back(tmp); 69 | } 70 | 71 | std::stable_sort( 72 | m_distr_vec.begin(), 73 | m_distr_vec.end(), 74 | [&](pair_t const& lhs, pair_t const& rhs) { 75 | return lhs.second > rhs.second; 76 | } 77 | ); 78 | } 79 | 80 | Statistics::Statistics() 81 | { } 82 | 83 | // ------------------------------------------------------ 84 | // ------------------------ NODE ------------------------ 85 | // ------------------------------------------------------ 86 | 87 | Node::Node(int l, int r, uint8_t s, double w) { 88 | left = l; 89 | right = r; 90 | symbol = s; 91 | weight = w; 92 | } 93 | 94 | // ------------------------------------------------------ 95 | // --------------------- CODE-TREE ---------------------- 96 | // ------------------------------------------------------ 97 | 98 | void CodeTree::tree_from_scheme(tree_t& m_tree, scheme_vec_t& m_scheme_vec) { 99 | m_tree.push_back(Node(-1, -1, 0, 0)); // ROOT 100 | 101 | for (size_t i = 0; i < m_scheme_vec.size(); ++i) { 102 | int index = 0; 103 | 104 | for (size_t j = 0; j < m_scheme_vec[i].size(); ++j) { 105 | // If 0 and there is no left node -> add left node 106 | if (!m_scheme_vec[i][j]) { 107 | if (m_tree[index].left == -1) { 108 | m_tree.push_back(Node(-1, -1, 0, 0)); 109 | m_tree[index].left = m_tree.size() - 1; 110 | } 111 | index = m_tree[index].left; 112 | } 113 | // If 1 and there is no right node -> add right node 114 | else { 115 | if (m_tree[index].right == -1) { 116 | m_tree.push_back(Node(-1, -1, 0, 0)); 117 | m_tree[index].right = m_tree.size() - 1; 118 | } 119 | index = m_tree[index].right; 120 | } 121 | } 122 | 123 | // Assign current symbol to the leaf node 124 | if (index != 0) m_tree[index].symbol = i; 125 | } 126 | } 127 | 128 | void CodeTree::truncate_code_tree(tree_t& m_tree, int index = 0) { 129 | if (index == -1) return; // exit if we found leaf 130 | 131 | int t = -1; 132 | 133 | if (m_tree[index].left == -1 && m_tree[index].right != -1) 134 | t = m_tree[index].left; 135 | else if (m_tree[index].left != -1 && m_tree[index].right == -1) 136 | t = m_tree[index].right; 137 | 138 | if (t != -1) { 139 | m_tree[index].symbol = m_tree[t].symbol; 140 | m_tree[index].left = m_tree[t].left; 141 | m_tree[index].right = m_tree[t].right; 142 | } 143 | 144 | truncate_code_tree(m_tree, m_tree[index].left); 145 | truncate_code_tree(m_tree, m_tree[index].right); 146 | } 147 | 148 | void CodeTree::traverse_code_tree(tree_t& m_tree, scheme_vec_t& m_scheme_vec, int index, bitseq_t code) { 149 | if (index == -1) return; 150 | 151 | if (m_tree[index].left == -1 && m_tree[index].right == -1) { 152 | m_scheme_vec[m_tree[index].symbol] = code; 153 | return; 154 | } 155 | 156 | code.push_back(0); 157 | traverse_code_tree(m_tree, m_scheme_vec, m_tree[index].left, code); 158 | code.pop_back(); 159 | 160 | code.push_back(1); 161 | traverse_code_tree(m_tree, m_scheme_vec, m_tree[index].right, code); 162 | code.pop_back(); 163 | } 164 | 165 | CodeTree::CodeTree() 166 | { } 167 | 168 | // ------------------------------------------------------- 169 | // ----------------------- SHENNON ----------------------- 170 | // ------------------------------------------------------- 171 | 172 | std::vector shennon::dec_to_bin(double s, size_t l) { 173 | std::vector code; 174 | 175 | for (size_t i = 1; i <= l; ++i) { 176 | s *= 2; 177 | if (s >= 1) { 178 | code.push_back(1); 179 | --s; 180 | } 181 | else code.push_back(0); 182 | } 183 | 184 | return code; 185 | } 186 | 187 | std::vector shennon::create_prob_sum_vector(distr_vec_t& m_distr_vec) { 188 | std::vector prob_sum(m_distr_vec.size(), 0); 189 | 190 | for (size_t i = 1; i < prob_sum.size(); ++i) 191 | prob_sum[i] = prob_sum[i - 1] + m_distr_vec[i - 1].second; 192 | 193 | return prob_sum; 194 | } 195 | 196 | std::vector shennon::create_code_lengths_vector(distr_vec_t& m_distr_vec) { 197 | std::vector code_lengths; 198 | 199 | size_t two_l = 2; // 2^l 200 | size_t l = 1; 201 | 202 | for (const auto& prob : m_distr_vec) { 203 | double p = prob.second; 204 | while (!(( ( 1.0 / two_l ) <= p) && (p < ( 1.0 / ( two_l >> 1 ) ) ))) { 205 | two_l <<= 1; 206 | ++l; 207 | } 208 | code_lengths.push_back(l); 209 | } 210 | 211 | return code_lengths; 212 | } 213 | 214 | void shennon::create_code_scheme(distr_vec_t& m_distr_vec) { 215 | m_scheme_vec.clear(); 216 | m_scheme_vec.resize(ALPHABET); 217 | 218 | if (m_distr_vec.empty()) return; 219 | if (m_distr_vec.size() == 1) { 220 | m_scheme_vec[m_distr_vec.front().first] = bitseq_t(1, 0); 221 | return; 222 | } 223 | 224 | std::vector prob_sum = create_prob_sum_vector(m_distr_vec); 225 | std::vector code_lengths = create_code_lengths_vector(m_distr_vec); 226 | 227 | for (size_t i = 0; i < prob_sum.size(); ++i) 228 | m_scheme_vec[m_distr_vec[i].first] = dec_to_bin(prob_sum[i], code_lengths[i]); 229 | 230 | tree_from_scheme(m_tree, m_scheme_vec); 231 | for (auto&& v : m_scheme_vec) v.clear(); 232 | truncate_code_tree(m_tree); 233 | traverse_code_tree(m_tree, m_scheme_vec, 0, bitseq_t()); 234 | 235 | // Tree was build from root to leaves => m_root index is 0 236 | m_root = 0; 237 | } 238 | 239 | // ------------------------------------------------------- 240 | // ------------------------ FANO ------------------------- 241 | // ------------------------------------------------------- 242 | 243 | void fano::create_code_scheme_helper(distr_vec_t& m_distr_vec, int begin, int end) { 244 | if ((end - begin) <= 0) return; 245 | 246 | double first_sum = 0.0; 247 | double second_sum = 0.0; 248 | 249 | for (int i = begin; i <= end; ++i) second_sum += m_distr_vec[i].second; 250 | 251 | double min_diff = second_sum; 252 | int begin_part = 0; 253 | 254 | for (int i = begin; i <= end; ++i) { 255 | first_sum += m_distr_vec[i].second; 256 | second_sum -= m_distr_vec[i].second; 257 | 258 | double diff = std::abs(second_sum - first_sum); 259 | 260 | if (diff <= min_diff) { 261 | min_diff = diff; 262 | begin_part = i; 263 | } 264 | else break; 265 | } 266 | 267 | for (int i = begin; i <= begin_part; ++i) m_scheme_vec[m_distr_vec[i].first].push_back(0); 268 | for (int i = begin_part + 1; i <= end; ++i) m_scheme_vec[m_distr_vec[i].first].push_back(1); 269 | 270 | create_code_scheme_helper(m_distr_vec, begin, begin_part); 271 | create_code_scheme_helper(m_distr_vec, begin_part + 1, end); 272 | } 273 | 274 | void fano::create_code_scheme(distr_vec_t& m_distr_vec) { 275 | m_scheme_vec.clear(); 276 | m_scheme_vec.resize(ALPHABET); 277 | 278 | if (m_distr_vec.empty()) return; 279 | if (m_distr_vec.size() == 1) { 280 | m_scheme_vec[m_distr_vec.front().first] = bitseq_t(1, 0); 281 | return; 282 | } 283 | 284 | create_code_scheme_helper(m_distr_vec, 0, m_distr_vec.size() - 1); 285 | tree_from_scheme(m_tree, m_scheme_vec); 286 | 287 | // Tree was build from root to leaves => m_root index is 0 288 | m_root = 0; 289 | } 290 | 291 | // ------------------------------------------------------- 292 | // ----------------------- HUFFMAN ----------------------- 293 | // ------------------------------------------------------- 294 | 295 | void huffman::create_code_tree(distr_vec_t& m_distr_vec) { 296 | using pair_t = typename std::pair; 297 | std::priority_queue, std::greater > queue; 298 | 299 | for (const auto& prob : m_distr_vec) 300 | m_tree.push_back(Node(-1, -1, prob.first, prob.second)); 301 | 302 | for (size_t i = 0; i < m_tree.size(); ++i) 303 | queue.push(pair_t(m_tree[i].weight, i)); 304 | 305 | while (queue.size() > 1) { 306 | pair_t child1; 307 | pair_t child2; 308 | double parent_w; 309 | 310 | child1 = queue.top(); queue.pop(); 311 | child2 = queue.top(); queue.pop(); 312 | parent_w = child1.first + child2.first; 313 | 314 | m_tree.push_back(Node(child1.second, child2.second, 0, parent_w)); 315 | queue.push(pair_t(parent_w, m_tree.size() - 1)); 316 | } 317 | } 318 | 319 | void huffman::create_code_scheme(distr_vec_t& m_distr_vec) { 320 | m_scheme_vec.clear(); 321 | m_scheme_vec.resize(ALPHABET); 322 | 323 | if (m_distr_vec.empty()) return; 324 | if (m_distr_vec.size() == 1) { 325 | m_scheme_vec[m_distr_vec.front().first] = bitseq_t(1, 0); 326 | return; 327 | } 328 | 329 | create_code_tree(m_distr_vec); 330 | traverse_code_tree(m_tree, m_scheme_vec, m_tree.size() - 1, bitseq_t()); 331 | 332 | // Tree was build from leaves to root => m_root index is m_tree.size()-1 333 | m_root = m_tree.size() - 1; 334 | } 335 | 336 | } 337 | -------------------------------------------------------------------------------- /src/pcoder.hxx: -------------------------------------------------------------------------------- 1 | /** 2 | * pcoder.hxx 3 | * 4 | * Shennon, Fano, Huffman Coding 5 | * by snovvcrash 6 | * 04.2017 7 | */ 8 | 9 | /** 10 | * Copyright (C) 2017 snovvcrash 11 | * 12 | * This file is part of libcoders. 13 | * 14 | * libcoders is free software: you can redistribute it and/or modify 15 | * it under the terms of the GNU General Public License as published by 16 | * the Free Software Foundation, either version 3 of the License, or 17 | * (at your option) any later version. 18 | * 19 | * libcoders is distributed in the hope that it will be useful, 20 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 21 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 22 | * GNU General Public License for more details. 23 | * 24 | * You should have received a copy of the GNU General Public License 25 | * along with libcoders. If not, see . 26 | */ 27 | 28 | #pragma once 29 | #ifndef PCODER_HXX 30 | #define PCODER_HXX 31 | 32 | #include 33 | #include 34 | #include // size_t 35 | #include 36 | #include 37 | #include 38 | #include 39 | #include // std::pair 40 | #include // CHAR_BIT 41 | 42 | namespace staticcodes { 43 | 44 | using freq_vec_t = typename std::vector; 45 | using distr_vec_t = typename std::vector >; 46 | using range_vec_t = typename std::vector >; 47 | using scheme_vec_t = typename std::vector >; 48 | using bitseq_t = typename std::vector; 49 | 50 | static constexpr size_t ALPHABET = 256; 51 | 52 | // ------------------------------------------------------ 53 | // --------------------- STATISTICS --------------------- 54 | // ------------------------------------------------------ 55 | 56 | class Statistics { 57 | protected: 58 | freq_vec_t m_freq_vec; 59 | distr_vec_t m_distr_vec; 60 | range_vec_t m_range_vec; 61 | uint64_t m_total_chars; 62 | 63 | // Creates a frequency vector containing number of occurrencies of every char in the input file 64 | void create_freq_vector(std::ifstream& ifile); 65 | 66 | // Creates a probability distribution vector containing pairs 67 | void create_distr_vector(); 68 | 69 | // Creates a probability ranges vector containing pairs (acoder only) 70 | void create_range_vector(); 71 | 72 | Statistics(); 73 | }; 74 | 75 | // ------------------------------------------------------ 76 | // ------------------------ NODE ------------------------ 77 | // ------------------------------------------------------ 78 | 79 | struct Node { 80 | int left; 81 | int right; 82 | uint8_t symbol; 83 | double weight; 84 | 85 | Node(int l, int r, uint8_t s, double w); 86 | }; 87 | 88 | using tree_t = typename std::vector; 89 | 90 | // ------------------------------------------------------ 91 | // --------------------- CODE-TREE ---------------------- 92 | // ------------------------------------------------------ 93 | 94 | class CodeTree { 95 | protected: 96 | 97 | // Creates code tree from filled code scheme 98 | void tree_from_scheme(tree_t& m_tree, scheme_vec_t& m_scheme_vec); 99 | 100 | // Recursively truncate (optimize) code tree 101 | void truncate_code_tree(tree_t& m_tree, int index); 102 | 103 | // Creates code scheme by recursively traversalling the code tree 104 | void traverse_code_tree(tree_t& m_tree, scheme_vec_t& m_scheme_vec, int index, bitseq_t code); 105 | 106 | CodeTree(); 107 | }; 108 | 109 | // ------------------------------------------------------- 110 | // ----------------------- SHENNON ----------------------- 111 | // ------------------------------------------------------- 112 | 113 | class shennon : private CodeTree { 114 | 115 | // Convert a fraction "s" with "l" digits after the demical point from DEC to BIN 116 | std::vector dec_to_bin(double s, size_t l); 117 | 118 | // Creates vector containing sums of probabilities 119 | std::vector create_prob_sum_vector(distr_vec_t& m_distr_vec); 120 | 121 | // Creates vector containing lengths of codes of each symbol 122 | std::vector create_code_lengths_vector(distr_vec_t& m_distr_vec); 123 | 124 | public: 125 | tree_t m_tree; 126 | scheme_vec_t m_scheme_vec; 127 | int m_root; 128 | 129 | // Creates code scheme and code tree 130 | void create_code_scheme(distr_vec_t& m_distr_vec); 131 | }; 132 | 133 | // ------------------------------------------------------- 134 | // ------------------------ FANO ------------------------- 135 | // ------------------------------------------------------- 136 | 137 | class fano : private CodeTree { 138 | 139 | // Recursively splits the distribution vector into two parts (close or equal to each other by the sum of probabilities) 140 | // and creates a code scheme by adding 0 or 1 to it on each step of the recursion 141 | void create_code_scheme_helper(distr_vec_t& m_distr_vec, int begin, int end); 142 | 143 | public: 144 | tree_t m_tree; 145 | scheme_vec_t m_scheme_vec; 146 | int m_root; 147 | 148 | // Creates code scheme and code tree 149 | void create_code_scheme(distr_vec_t& m_distr_vec); 150 | }; 151 | 152 | // ------------------------------------------------------- 153 | // ----------------------- HUFFMAN ----------------------- 154 | // ------------------------------------------------------- 155 | 156 | class huffman : private CodeTree { 157 | 158 | // Creates code tree via Huffman method 159 | void create_code_tree(distr_vec_t& m_distr_vec); 160 | 161 | public: 162 | tree_t m_tree; 163 | scheme_vec_t m_scheme_vec; 164 | int m_root; 165 | 166 | // Creates code scheme and code tree 167 | void create_code_scheme(distr_vec_t& m_distr_vec); 168 | }; 169 | 170 | // ------------------------------------------------------- 171 | // ----------------------- PCODER ------------------------ 172 | // ------------------------------------------------------- 173 | 174 | template 175 | class pcoder : private Statistics { 176 | Algorithm m_alg; 177 | bitseq_t m_seq; 178 | 179 | // Creates a vector with a bit sequence containing binary code that will be written to the output file 180 | void create_bit_sequence(std::ifstream& ifile); 181 | 182 | public: 183 | 184 | // Encodes text and writes the final bit sequence to the output file 185 | void compress(std::ifstream& ifile, std::ofstream& ofile); 186 | 187 | void operator()(std::ifstream& ifile, std::ofstream& ofile); 188 | 189 | pcoder(std::ifstream& ifile, std::ofstream& ofile); 190 | 191 | pcoder(); 192 | }; 193 | 194 | // ------------------------------------------------------- 195 | // ---------------------- PDECODER ----------------------- 196 | // ------------------------------------------------------- 197 | 198 | template 199 | class pdecoder : private Statistics { 200 | Algorithm m_alg; 201 | 202 | public: 203 | 204 | // Decodes text and writes the final bit sequence to the output file 205 | void decompress(std::ifstream& ifile, std::ofstream& ofile); 206 | 207 | void operator()(std::ifstream& ifile, std::ofstream& ofile); 208 | 209 | pdecoder(std::ifstream& ifile, std::ofstream& ofile); 210 | 211 | pdecoder(); 212 | }; 213 | 214 | // ------------------------------------------------------- 215 | // --------------------- PCODER IMPL --------------------- 216 | // ------------------------------------------------------- 217 | 218 | template 219 | void pcoder::create_bit_sequence(std::ifstream& ifile) { 220 | m_seq.clear(); 221 | 222 | ifile.clear(); 223 | ifile.seekg(0, std::ios::beg); 224 | 225 | char c; 226 | while (ifile.read(&c, sizeof(c))) 227 | m_seq.insert( 228 | m_seq.end(), 229 | m_alg.m_scheme_vec[static_cast(c)].begin(), 230 | m_alg.m_scheme_vec[static_cast(c)].end() 231 | ); 232 | } 233 | 234 | template 235 | void pcoder::compress(std::ifstream& ifile, std::ofstream& ofile) { 236 | create_freq_vector(ifile); 237 | create_distr_vector(); 238 | m_alg.create_code_scheme(m_distr_vec); 239 | create_bit_sequence(ifile); 240 | 241 | // Writing the frequency table to file (in binary notation) 242 | for (const auto& freq : m_freq_vec) 243 | ofile.write(reinterpret_cast(&freq), sizeof(freq)); 244 | 245 | uint8_t bit_buffer = 0; 246 | size_t bit_counter = 0; 247 | 248 | // Writing the bit sequence to the output file: due to the impossibility of direct bit-by-bit data writing 249 | // to file we wait until an 8-bit (byte) chunk of data is filled with single bits and send it to file 250 | for (const auto& bit : m_seq) { 251 | bit_buffer |= bit << (7 - bit_counter); 252 | 253 | if (++bit_counter == CHAR_BIT) { 254 | ofile.write(reinterpret_cast(&bit_buffer), sizeof(bit_buffer)); 255 | bit_buffer = 0; 256 | bit_counter = 0; 257 | } 258 | } 259 | 260 | // If there are bits left -> send them with last byte (chunk) padded with zeros 261 | if (bit_counter) ofile.write(reinterpret_cast(&bit_buffer), sizeof(bit_buffer)); 262 | } 263 | 264 | template 265 | void pcoder::operator()(std::ifstream& ifile, std::ofstream& ofile) { 266 | compress(ifile, ofile); 267 | } 268 | 269 | template 270 | pcoder::pcoder(std::ifstream& ifile, std::ofstream& ofile) { 271 | compress(ifile, ofile); 272 | } 273 | 274 | template 275 | pcoder::pcoder() 276 | { } 277 | 278 | // ------------------------------------------------------- 279 | // -------------------- PDECODER IMPL -------------------- 280 | // ------------------------------------------------------- 281 | 282 | template 283 | void pdecoder::decompress(std::ifstream& ifile, std::ofstream& ofile) { 284 | m_freq_vec.clear(); 285 | m_total_chars = 0; 286 | 287 | // Reading the frequency table and filling the frequency vector with it 288 | for (size_t i = 0; i < ALPHABET; ++i) { 289 | uint32_t tmp; 290 | ifile.read(reinterpret_cast(&tmp), sizeof(tmp)); 291 | m_freq_vec.push_back(tmp); 292 | m_total_chars += tmp; 293 | } 294 | 295 | // If there is no coded text in the input file after the header (frequency table) -> exit 296 | if (ifile.peek() == EOF) { 297 | if (!ifile.eof()) 298 | std::cerr << "pdecoder::decompress: " << std::strerror(errno) << std::endl; 299 | return; 300 | } 301 | 302 | create_distr_vector(); 303 | m_alg.create_code_scheme(m_distr_vec); 304 | 305 | char curr_byte; 306 | int curr_index = m_alg.m_root; 307 | size_t bit_counter = 0; 308 | uint64_t cnt_chars = 0; 309 | 310 | ifile.read(&curr_byte, sizeof(curr_byte)); 311 | 312 | // Decoding 313 | while (true) { 314 | // Read 1 bit from current byte 315 | bool curr_bit = curr_byte & (1 << (7 - bit_counter)); 316 | 317 | // Traverse the code tree 318 | if (!curr_bit) curr_index = m_alg.m_tree[curr_index].left; 319 | else curr_index = m_alg.m_tree[curr_index].right; 320 | 321 | // If current node is a list -> send it to file 322 | if (m_alg.m_tree[curr_index].left == -1 && m_alg.m_tree[curr_index].right == -1) { 323 | char symbol = m_alg.m_tree[curr_index].symbol; 324 | ofile.write(&symbol, sizeof(symbol)); 325 | curr_index = m_alg.m_root; 326 | ++cnt_chars; 327 | } 328 | 329 | // If number of decoded chars != number of chars in original text (~ remove padding) -> exit loop 330 | if (cnt_chars == m_total_chars) break; 331 | 332 | // Read next data chunk 333 | if (++bit_counter == CHAR_BIT) { 334 | ifile.read(&curr_byte, sizeof(curr_byte)); 335 | bit_counter = 0; 336 | } 337 | } 338 | } 339 | 340 | template 341 | void pdecoder::operator()(std::ifstream& ifile, std::ofstream& ofile) { 342 | decompress(ifile, ofile); 343 | } 344 | 345 | template 346 | pdecoder::pdecoder(std::ifstream& ifile, std::ofstream& ofile) { 347 | decompress(ifile, ofile); 348 | } 349 | 350 | template 351 | pdecoder::pdecoder() 352 | { } 353 | 354 | } 355 | 356 | #endif // PCODER_HXX 357 | --------------------------------------------------------------------------------