├── COPYING ├── Makefile ├── NEWS ├── README ├── combine_reads.c ├── combine_reads.h ├── flash.c ├── iostream.c ├── iostream.h ├── read.h ├── read_io.c ├── read_io.h ├── read_queue.c ├── read_queue.h ├── read_util.c ├── util.c └── util.h /COPYING: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | # 2 | # Makefile for FLASH. Process this using GNU make by simply running 3 | # 4 | # $ make 5 | # 6 | # You may set CPPFLAGS, LDFLAGS, or CC in the environment if you would like to 7 | # use a non-default compiler, extra preprocessor flags (e.g. to find headers), 8 | # or extra linker flags (e.g. to find libraries). 9 | 10 | CFLAGS += -O2 -Wall -std=c99 -D_GNU_SOURCE -D_FILE_OFFSET_BITS=64 11 | LDLIBS := -lz -lpthread 12 | OBJ := combine_reads.o flash.o iostream.o read_io.o read_queue.o read_util.o util.o 13 | EXE := flash 14 | 15 | $(EXE):$(OBJ) 16 | 17 | clean: 18 | rm -f $(OBJ) $(EXE) 19 | 20 | .PHONY: clean 21 | -------------------------------------------------------------------------------- /NEWS: -------------------------------------------------------------------------------- 1 | Version 1.2.11 2 | -------------- 3 | - Fixed a bug that caused FLASH to crash under the following set of 4 | circumstances: the --allow-outies option (added in v1.2.10) was specified; and 5 | in a read pair, read 1 was longer than read 2; and the chosen merge aligned 6 | the end of read 2 to the very beginning of read 1, e.g. 7 | 8 | Read 1: -----------------------------------> 9 | Read 2: <------------------------- 10 | 11 | This bug was extremely likely to crash the program. Therefore, the output of 12 | successful runs of FLASH should not have been affected. 13 | 14 | Version 1.2.10 15 | -------------- 16 | - FLASH now supports combining read pairs in outie orientation. See help for 17 | the new --allow-outies option. 18 | - Added warning messages in a few cases where it may be helpful to specify 19 | different parameters. 20 | 21 | Version 1.2.9 22 | ------------------- 23 | - The core algorithm of FLASH has been optimized using SSE and SSE2 24 | instructions. On x86_64 CPUs it now can run over twice as fast. 25 | - The help output of FLASH has been improved. 26 | - Added supported for tab-delimited input and output. 27 | - FLASH now displays more informative error messages in some cases. 28 | - Reorganized some of the code so that it's easier to modify. 29 | - Reading the data from standard input now works correctly. 30 | - With --to-stdout specified, informational messages are now written to standard 31 | error rather than omitted. 32 | 33 | Version 1.2.8 34 | ------------------- 35 | - FLASH's default behavior when assigning quality scores to mismatch sites in 36 | the overlap region of combined reads has been improved. See the documentation 37 | for the new --cap-mismatch-quals option (which can be provided to request the 38 | old behavior if desired) for more information about this change. 39 | 40 | Version 1.2.7 41 | ------------------- 42 | - FLASH is now supported on Windows. See the README. 43 | - Minor bug-fixes regarding printing of error messages. 44 | - Fixed a bug where the time that FLASH took to run may have been mis-calculated 45 | on 32-bit systems in an unlikely case. This only affected the printed 46 | informational output. 47 | - Updated PERFORMANCE section in README to be accurate for the current version 48 | of FLASH. 49 | 50 | Version 1.2.6 51 | ------------------- 52 | - FLASH now works on files larger than 2GiB on 32-bit operating systems, unless 53 | the system zlib library does not support such files. 64-bit operating systems 54 | are unaffected as they already supported large files by default. 55 | 56 | Version 1.2.5 57 | ------------------- 58 | - FLASH will now compile and run on Mac OS X. 59 | 60 | Version 1.2.4 61 | ------------------- 62 | - Support for piping the output of FLASH through arbitrary compression programs 63 | has been added via the --compress-prog option. The --compress-prog-args 64 | and/or --output-suffix options also may be useful. 65 | - FLASH with the --interleaved option will now use an interleaved output format 66 | in addition to assuming interleaved input. Use --interleaved-input or 67 | --interleaved-output to specify only interleaved input or only interleaved 68 | output, respectively. 69 | - The entirely single-threaded configuration of FLASH is no longer supported. 70 | You can still use --threads=1 to use only 1 combiner thread, however. 71 | 72 | Version 1.2.3 73 | ------------------- 74 | - Support for interleaved reads (-I, --interleaved), which may be read from one 75 | FASTQ file or piped in from stdin 76 | - Fix --read-len option 77 | - Fix default --fragment-len-stddev option 78 | - Fix reading FASTQ files with embedded zero bytes 79 | - Fix memory leaks 80 | - Added license file 81 | 82 | Version 1.2.2 83 | ------------------- 84 | - Fix linking problem in Makefile 85 | 86 | Version 1.2.1 87 | ------------------- 88 | - There is no longer any read length or tag length limit, although you may still 89 | specify the --read-len parameter for the purpose of automatically computing the 90 | maximum overlap. 91 | - FLASH now prints some informational output while it's running, unless running 92 | with --quiet or --to-stdout. 93 | 94 | Version 1.2 95 | ------------------- 96 | 97 | - Support for writing extended fragments directly to standard output. 98 | - Support for writing compressed output files. 99 | - Support for multithreading. There are multiple I/O threads as well as 100 | multiple combiner threads. Speedup of 3.6 times has been observed. Compiling 101 | without support for multithreading is still supported. 102 | 103 | Version 1.1 104 | ------------------- 105 | Rewrote the entire program. 106 | - Removed at least 3 instances of undefined behavior (such as using 107 | uninitialized variables). 108 | - Performance improvements. Neglecting I/O, the program now runs over twice as 109 | fast. This improvement is not due to a change in algorithm; I expect it is due 110 | mainly to the rewritten align_position() function. 111 | - Use getopt_long() for option parsing. Now, long options are accepted, and 112 | options do not have to be given after the mate pair FASTQ files. 113 | - Removed many fixed-size buffers. This saves memory, removes many buffer 114 | overflow problems, and removes the READ_LENGTH parameter. Note: the maximum tag 115 | length is still hard-coded as 1024 bytes. 116 | - Much more error checking, so the program will cleanly fail if something goes 117 | wrong. 118 | - Use a Makefile instead of a shell script. 119 | - The '.histogram' file is written a bit more narrowly (80 columns), but other 120 | than that, the output of the program should be the same (unless it was affected 121 | by any of the cases of undefined behavior I found). 122 | - Some changes to the MANUAL, although I didn't feel like changing the 123 | information that is redundant with the program help. 124 | - Note: I am calling this version 1.1, but feel free to call it something else. 125 | The version number is also listed in the version() function in flash.c. 126 | 127 | Version v1.0.3 128 | -------------- 129 | 1. FLASH allows reads files to be in gzip format. 130 | 2. FLASH builds a histogram of fragment lengths produced by merged read pairs. 131 | 3. FLASH now allows for reads longer than 170bp to be processed (READ_LENGTH is utilities.h file still needs to be changed manually to the read length if it is greater than 170). 132 | 4. If original reads' ID contains barcode, the barcode is kept as a part of the ID in the output fragments. 133 | 134 | 135 | 136 | Version v1.0.2 137 | -------------- 138 | Fixed bugs: 139 | 1. In combine function in combineReads.c: modified selection of the base when quality values of bases are the same. Instead of random selection of the base, first check whether any base is "N" to avoid selection of "N" if not necessary. 140 | 141 | Added options for easier handling of the program: 142 | 1. Added error messages in case no input files and no parameters are specified. 143 | 2. Added the parameter to print 'help' for running the program. 144 | 3. Added the option to specify prefix of the output files. 145 | 4. Added the option to specify directory of the output files. 146 | 147 | Functional changes: 148 | 1. Changed read length to 170. 149 | 2. Automatic calculation of maximum overlap length given average read length, average fragment length, and fragment standard deviation. 150 | 151 | 152 | Version v1.0.1 153 | -------------- 154 | Fixed bugs: 155 | 1. In align_position function in combineReads.c: added the line *score=10001 when readLength2 < overlap. 156 | 2. idSet function in utilities.c: added the part of the condition to end reading the line of file1[0] if '\n' is found. 157 | -------------------------------------------------------------------------------- /README: -------------------------------------------------------------------------------- 1 | INTRODUCTION 2 | 3 | FLASH (Fast Length Adjustment of SHort reads) is an accurate and fast tool 4 | to merge paired-end reads that were generated from DNA fragments whose 5 | lengths are shorter than twice the length of reads. Merged read pairs result 6 | in unpaired longer reads, which are generally more desired in genome 7 | assembly and genome analysis processes. 8 | 9 | Briefly, the FLASH algorithm considers all possible overlaps at or above a 10 | minimum length between the reads in a pair and chooses the overlap that 11 | results in the lowest mismatch density (proportion of mismatched bases in 12 | the overlapped region). Ties between multiple overlaps are broken by 13 | considering quality scores at mismatch sites. When building the merged 14 | sequence, FLASH computes a consensus sequence in the overlapped region. 15 | More details can be found in the original publication 16 | (http://bioinformatics.oxfordjournals.org/content/27/21/2957.full). 17 | 18 | Limitations of FLASH include: 19 | - FLASH cannot merge paired-end reads that do not overlap. 20 | - FLASH is not designed for data that has a significant amount of indel 21 | errors (such as Sanger sequencing data). It is best suited for Illumina 22 | data. 23 | 24 | INSTALLATION 25 | 26 | On UNIX-compatible systems, including GNU/Linux and Mac OS X, you must compile 27 | FLASH from source. The only dependency, other than functions that are expected 28 | to be available in the C library, is the zlib data compression library. To 29 | install FLASH, download the tarball, untar it, and compile the code using the 30 | provided Makefile: 31 | 32 | $ tar xzf FLASH-1.2.11.tar.gz 33 | $ cd FLASH-1.2.11 34 | $ make 35 | 36 | The executable file that is produced is named 'flash'. To run it from the 37 | command line you must copy it to a location on your $PATH variable, or else run 38 | it with a path including a directory, such as "./flash". 39 | 40 | FLASH also runs on Windows, and you can compile it on Windows using MinGW. 41 | However, for convenience you may instead download a standalone Windows binary 42 | from the SourceForge page (https://sourceforge.net/projects/flashpage/). 43 | 44 | USAGE 45 | 46 | Please compile FLASH and run `flash --help' to see command-line usage 47 | information and information about input/output files. 48 | 49 | MULTITHREADING 50 | 51 | By default, FLASH uses multiple threads. There are "combiner" threads that do 52 | the actual read combining, as well as up to 5 threads that are used for I/O (up 53 | to 2 readers, up to 3 writers). The default number of combiner threads is the 54 | number of processors; however, it can be adjusted with the -t option (long 55 | option: --threads). 56 | 57 | When multiple combiner threads are used, the order of the combined and 58 | uncombined reads in the output files will be nondeterministic. If you need to 59 | enforce that the output reads appear in the same order as the input, you must 60 | specify --threads=1. 61 | 62 | PERFORMANCE 63 | 64 | Since the FLASH algorithm considers each read pair independently, FLASH will, by 65 | default, process read pairs in parallel. FLASH v1.2.9 and later also make use 66 | of vector instructions available on modern x86 CPUs. Consequently, FLASH works 67 | quite fast, even with low-cost computing resources. As an example, we ran FLASH 68 | v1.2.9 on a laptop with a dual-core 2.3 GHz AMD x86_64 processor and it 69 | processed one million 101-bp read pairs in 11.6 seconds with the default 70 | parameters. Less than 2 MB of memory was used. Actual timing results will 71 | vary, but they will depend primarily on the number of CPUs available, the speed 72 | of each CPU, and on the I/O speed of reading the input files and writing the 73 | output files. FLASH is designed to be scalable to dozens of processors, 74 | although its speed may be limited by I/O in such cases. 75 | 76 | ACCURACY 77 | 78 | With reads' error rate of 1% or less, FLASH processes over 99% of read pairs 79 | correctly. With error rate of 2%, FLASH processes over 98% of read pairs 80 | correctly when default parameters are used. With more aggressive parameters 81 | (i.e., -x 0.35), FLASH processes over 90% of read pairs correctly even when the 82 | error rate is 5%. 83 | 84 | PUBLICATION 85 | 86 | Title: FLASH: fast length adjustment of short reads to improve genome assemblies 87 | Authors: Tanja Magoč and Steven L. Salzberg 88 | URL: http://bioinformatics.oxfordjournals.org/content/27/21/2957.full 89 | 90 | LICENSE 91 | 92 | FLASH is released under the GNU General Public License Version 3 or later (see 93 | COPYING). 94 | 95 | COMMENTS/QUESTIONS/REQUESTS 96 | 97 | Send an e-mail to flash.comment@gmail.com 98 | 99 | Other versions are available from the SourceForge page: 100 | 101 | https://sourceforge.net/projects/flashpage/ 102 | -------------------------------------------------------------------------------- /combine_reads.c: -------------------------------------------------------------------------------- 1 | /* 2 | * combine_reads.c: This file contains the code implementing the core algorithm 3 | * to combine reads in FLASH. 4 | */ 5 | 6 | /* 7 | * Copyright (C) 2012 Tanja Magoc 8 | * Copyright (C) 2012, 2013, 2014 Eric Biggers 9 | * 10 | * This file is part of FLASH, a fast tool to merge overlapping paired-end 11 | * reads. 12 | * 13 | * FLASH is free software; you can redistribute it and/or modify it under the 14 | * terms of the GNU General Public License as published by the Free 15 | * Software Foundation; either version 3 of the License, or (at your option) 16 | * any later version. 17 | * 18 | * FLASH is distributed in the hope that it will be useful, but WITHOUT ANY 19 | * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR 20 | * A PARTICULAR PURPOSE. See the GNU General Public License for more 21 | * details. 22 | * 23 | * You should have received a copy of the GNU General Public License 24 | * along with FLASH; if not, see http://www.gnu.org/licenses/. 25 | */ 26 | 27 | #include "combine_reads.h" 28 | #include "read.h" 29 | #include "util.h" 30 | 31 | #include 32 | #include 33 | #include 34 | #include 35 | 36 | #if defined(__GNUC__) && defined(__SSE2__) 37 | # define WITH_SSE2 38 | #endif 39 | 40 | #ifdef WITH_SSE2 41 | # include 42 | # include 43 | #endif 44 | 45 | #ifdef WITH_SSE2 46 | 47 | /* Sum the values an 8 x 8 bit vector and return a 32-bit result. */ 48 | static inline uint32_t 49 | hsum32_v8(__m128i v) 50 | { 51 | v = _mm_sad_epu8(v, _mm_set1_epi8(0)); 52 | return (uint32_t)_mm_extract_epi16(v, 0) + 53 | (uint32_t)_mm_extract_epi16(v, 4); 54 | } 55 | 56 | /* Sum the values an 8 x 16 bit vector and return a 32-bit result. */ 57 | static inline uint32_t 58 | hsum32_v16(__m128i v) 59 | { 60 | __m128i mask = _mm_set1_epi32(0x0000ffff); 61 | v = _mm_add_epi32(v & mask, _mm_srli_si128(v, 2) & mask); 62 | v = _mm_add_epi32(v, _mm_srli_si128(v, 4)); 63 | v = _mm_add_epi32(v, _mm_srli_si128(v, 8)); 64 | return _mm_cvtsi128_si32(v); 65 | } 66 | 67 | #endif /* WITH_SSE2 */ 68 | 69 | /* 70 | * Compute mismatch statistics between two sequences. 71 | * 72 | * @seq_1, @seq_2: 73 | * The two sequences to compare (ASCII characters A, C, G, T, N). 74 | * @qual_1, @qual_2: 75 | * Quality scores for the two sequences, based at 0. 76 | * @haveN 77 | * As an optimization, this can be set to %false to indicate that neither 78 | * sequence contains an uncalled base (represented as an N character). 79 | * @len_p 80 | * Pointer to the length of the sequence. This value will be updated to 81 | * subtract the number of positions at which an uncalled base (N) exists in 82 | * either sequence. 83 | * @num_mismatches_ret 84 | * Location into which to return the number of positions at which the bases 85 | * were mismatched. 86 | * @mismatch_qual_total_ret 87 | * Location into which to return the sum of lesser quality scores at 88 | * mismatch sites. 89 | */ 90 | static inline void 91 | compute_mismatch_stats(const char * restrict seq_1, 92 | const char * restrict seq_2, 93 | const char * restrict qual_1, 94 | const char * restrict qual_2, 95 | bool haveN, 96 | int * restrict len_p, 97 | unsigned * restrict num_mismatches_ret, 98 | unsigned * restrict mismatch_qual_total_ret) 99 | { 100 | int num_uncalled = 0; 101 | unsigned num_mismatches = 0; 102 | unsigned mismatch_qual_total = 0; 103 | int len = *len_p; 104 | 105 | if (haveN) { 106 | for (int i = 0; i < len; i++) { 107 | if (seq_1[i] == 'N' || seq_2[i] == 'N') { 108 | num_uncalled++; 109 | } else { 110 | if (seq_1[i] != seq_2[i]) { 111 | num_mismatches++; 112 | mismatch_qual_total += min(qual_1[i], qual_2[i]); 113 | } 114 | } 115 | } 116 | } else { 117 | /* This part of the 'if' statement is for optimization purposes 118 | * only; its behavior is equivalent to the block above, except 119 | * this block assumes there are no N characters in the input, 120 | * and therefore no further checks for N's are needed. 121 | * 122 | * Note: this optimization is only useful if most reads don't 123 | * contain N characters. */ 124 | 125 | #ifdef WITH_SSE2 126 | 127 | /* Optional vectorized implementation (about twice as fast as 128 | * nonvectorized on x86_64). */ 129 | 130 | while (len >= 16) { 131 | 132 | /* 16 x 8 bit counters for number of mismatches */ 133 | __m128i num_mismatches_v8 = _mm_set1_epi8(0); 134 | 135 | /* 8 x 16 bit counters for mismatch quality total */ 136 | __m128i mismatch_qual_total_v16 = _mm_set1_epi16(0); 137 | 138 | /* The counters of num_mismatches_v8 will overflow if 139 | * 256 mismatches are detected at the same position 140 | * modulo 16 bytes. So, don't process 4096 or more 141 | * bytes before reducing the counters. 142 | * 143 | * mismatch_qual_total_v16 would overflow even faster, 144 | * but we use 16-bit counters for it. */ 145 | 146 | int todo = min(len, 255 * 16) & ~0xf; 147 | len -= todo; 148 | 149 | do { 150 | 151 | /* Load 16 bases */ 152 | __m128i s1_v8 = _mm_loadu_si128((const void *)seq_1); 153 | __m128i s2_v8 = _mm_loadu_si128((const void *)seq_2); 154 | 155 | /* Load 16 quality scores */ 156 | __m128i q1_v8 = _mm_loadu_si128((const void *)qual_1); 157 | __m128i q2_v8 = _mm_loadu_si128((const void *)qual_2); 158 | 159 | /* Compare bases with each other and negate the 160 | * result. This will produce 0xff in bytes 161 | * where the bases differ and 0x00 in bytes 162 | * where the bases were the same. */ 163 | __m128i cmpresult = ~_mm_cmpeq_epi8(s1_v8, s2_v8); 164 | 165 | /* Tally mismatched bases. Subtracting 0x00 and 166 | * 0xff is equivalent to adding 0 and 1, 167 | * respectively. */ 168 | num_mismatches_v8 = _mm_sub_epi8(num_mismatches_v8, 169 | cmpresult); 170 | 171 | /* Tally quality scores for mismatched bases. 172 | */ 173 | 174 | /* Get minimum of each quality score. */ 175 | __m128i qmin_v8 = _mm_min_epu8(q1_v8, q2_v8); 176 | 177 | /* Select only quality scores at mismatch sites 178 | */ 179 | __m128i qadd_v8 = qmin_v8 & cmpresult; 180 | 181 | /* Double the precision (8 => 16 bits) and tally */ 182 | __m128i qadd_v16_1 = _mm_unpacklo_epi8(qadd_v8, 183 | _mm_set1_epi8(0)); 184 | 185 | __m128i qadd_v16_2 = _mm_unpackhi_epi8(qadd_v8, 186 | _mm_set1_epi8(0)); 187 | 188 | mismatch_qual_total_v16 = _mm_add_epi16(mismatch_qual_total_v16, 189 | qadd_v16_1); 190 | 191 | mismatch_qual_total_v16 = _mm_add_epi16(mismatch_qual_total_v16, 192 | qadd_v16_2); 193 | 194 | /* Advance pointers */ 195 | seq_1 += 16, seq_2 += 16; 196 | qual_1 += 16, qual_2 += 16; 197 | todo -= 16; 198 | } while (todo); 199 | 200 | /* Reduce the counters. */ 201 | num_mismatches += hsum32_v8(num_mismatches_v8); 202 | mismatch_qual_total += hsum32_v16(mismatch_qual_total_v16); 203 | } 204 | 205 | #endif /* WITH_SSE2 */ 206 | 207 | #if 0 208 | /* Verify the values computed by the vectorized implementation. 209 | */ 210 | { 211 | int veclen = *len_p & ~0xf; 212 | const char *_seq_1 = seq_1 - veclen; 213 | const char *_seq_2 = seq_2 - veclen; 214 | const char *_qual_1 = qual_1 - veclen; 215 | const char *_qual_2 = qual_2 - veclen; 216 | unsigned _num_mismatches = 0; 217 | unsigned _mismatch_qual_total = 0; 218 | for (int i = 0; i < veclen; i++) { 219 | if (_seq_1[i] != _seq_2[i]) { 220 | _num_mismatches++; 221 | _mismatch_qual_total += min(_qual_1[i], _qual_2[i]); 222 | } 223 | } 224 | assert(num_mismatches == _num_mismatches); 225 | assert(mismatch_qual_total == _mismatch_qual_total); 226 | } 227 | #endif 228 | 229 | /* Process any remainder that wasn't processed by the vectorized 230 | * implementation. */ 231 | for (int i = 0; i < len; i++) { 232 | if (seq_1[i] != seq_2[i]) { 233 | num_mismatches++; 234 | mismatch_qual_total += min(qual_1[i], qual_2[i]); 235 | } 236 | } 237 | } 238 | 239 | /* Return results in pointer arguments */ 240 | *num_mismatches_ret = num_mismatches; 241 | *mismatch_qual_total_ret = mismatch_qual_total; 242 | *len_p -= num_uncalled; 243 | } 244 | 245 | #define NO_ALIGNMENT INT_MIN 246 | 247 | static inline int 248 | pair_align(const struct read *read_1, const struct read *read_2, 249 | int min_overlap, int max_overlap, float max_mismatch_density, 250 | bool allow_outies, bool * was_outie) 251 | { 252 | bool haveN = memchr(read_1->seq, 'N', read_1->seq_len) || 253 | memchr(read_2->seq, 'N', read_2->seq_len); 254 | 255 | /* Best (smallest) mismatch density that has been found so far in an 256 | * overlap. */ 257 | float best_mismatch_density = max_mismatch_density + 1.0f; 258 | float best_qual_score = 0.0f; 259 | int best_position = NO_ALIGNMENT; 260 | bool best_was_outie; 261 | bool doing_outie = false; 262 | int start; 263 | int end; 264 | 265 | again: 266 | /* Require at least min_overlap bases overlap, and require that the 267 | * second read is not overlapped such that it is completely contained in 268 | * the first read. */ 269 | start = max(0, read_1->seq_len - read_2->seq_len); 270 | end = read_1->seq_len - min_overlap + 1; 271 | for (int i = start; i < end; i++) { 272 | unsigned num_mismatches; 273 | unsigned mismatch_qual_total; 274 | int overlap_len = read_1->seq_len - i; 275 | 276 | compute_mismatch_stats(read_1->seq + i, 277 | read_2->seq, 278 | read_1->qual + i, 279 | read_2->qual, 280 | haveN, 281 | &overlap_len, 282 | &num_mismatches, 283 | &mismatch_qual_total); 284 | 285 | if (overlap_len >= min_overlap) { 286 | float score_len = (float)min(overlap_len, max_overlap); 287 | float qual_score = mismatch_qual_total / score_len; 288 | float mismatch_density = num_mismatches / score_len; 289 | 290 | if (mismatch_density <= best_mismatch_density && 291 | (mismatch_density < best_mismatch_density || 292 | qual_score < best_qual_score)) 293 | { 294 | best_qual_score = qual_score; 295 | best_mismatch_density = mismatch_density; 296 | best_position = i; 297 | best_was_outie = doing_outie; 298 | } 299 | } 300 | } 301 | 302 | if (allow_outies) { 303 | const struct read *tmp = read_1; 304 | read_1 = read_2; 305 | read_2 = tmp; 306 | allow_outies = false; 307 | doing_outie = true; 308 | goto again; 309 | } 310 | 311 | if (best_mismatch_density > max_mismatch_density) 312 | return NO_ALIGNMENT; 313 | 314 | *was_outie = best_was_outie; 315 | return best_position; 316 | } 317 | 318 | /* Fills in the combined read from the specified alignment. */ 319 | static void 320 | generate_combined_read(const struct read *read_1, 321 | const struct read *read_2, 322 | struct read *combined_read, 323 | int overlap_begin, 324 | bool cap_mismatch_quals) 325 | { 326 | /* Length of the overlapping part of two reads. */ 327 | int overlap_len = read_1->seq_len - overlap_begin; 328 | 329 | /* Length of the part of the second read not overlapped with the first 330 | * read. */ 331 | int remaining_len = read_2->seq_len - overlap_len; 332 | 333 | int combined_seq_len = read_1->seq_len + remaining_len; 334 | 335 | const char * restrict seq_1 = read_1->seq; 336 | const char * restrict seq_2 = read_2->seq; 337 | const char * restrict qual_1 = read_1->qual; 338 | const char * restrict qual_2 = read_2->qual; 339 | char * restrict combined_seq; 340 | char * restrict combined_qual; 341 | 342 | if (combined_read->seq_bufsz < combined_seq_len) { 343 | combined_read->seq = xrealloc(combined_read->seq, 344 | combined_seq_len); 345 | combined_read->seq_bufsz = combined_seq_len; 346 | } 347 | if (combined_read->qual_bufsz < combined_seq_len) { 348 | combined_read->qual = xrealloc(combined_read->qual, 349 | combined_seq_len); 350 | combined_read->qual_bufsz = combined_seq_len; 351 | } 352 | 353 | combined_seq = combined_read->seq; 354 | combined_qual = combined_read->qual; 355 | 356 | combined_read->seq_len = combined_seq_len; 357 | combined_read->qual_len = combined_seq_len; 358 | 359 | /* Copy the beginning of read 1 (not in the overlapped region). */ 360 | while (overlap_begin--) { 361 | *combined_seq++ = *seq_1++; 362 | *combined_qual++ = *qual_1++; 363 | } 364 | 365 | /* Copy the overlapped region. */ 366 | while (overlap_len--) { 367 | if (*seq_1 == *seq_2) { 368 | /* Same base in both reads. Take the higher quality 369 | * value. */ 370 | *combined_seq = *seq_1; 371 | *combined_qual = max(*qual_1, *qual_2); 372 | } else { 373 | /* Different bases in the two reads; use the higher 374 | * quality one. 375 | * 376 | * The old way of calculating the resulting quality 377 | * value (params->cap_mismatch_quals == %true) is to use 378 | * the lower quality value, and use a quality value of 379 | * at most 2 (+ phred_offset in the final output--- here 380 | * the quality values are all scaled to start at 0). 381 | * The motivation for this behavior is that the read 382 | * combination shows there was sequencing error at the 383 | * mismatch location, so the corresponding base call in 384 | * the combined read should be given a low quality 385 | * score. 386 | * 387 | * The new way (params->cap_mismatch_quals == %false, 388 | * default as of FLASH v1.2.8) is to use the absolute 389 | * value of the difference in quality scores, but at 390 | * least 2. This allows a base call with a high quality 391 | * score to override a base call with a low quality 392 | * score without too much penalty. 393 | */ 394 | 395 | if (cap_mismatch_quals) 396 | *combined_qual = min(min(*qual_1, *qual_2), 2); 397 | else 398 | *combined_qual = max(abs(*qual_1 - *qual_2), 2); 399 | 400 | if (*qual_1 > *qual_2) { 401 | *combined_seq = *seq_1; 402 | } else if (*qual_1 < *qual_2) { 403 | *combined_seq = *seq_2; 404 | } else { 405 | /* Same quality value; take the base from the 406 | * first read if the base from the second read 407 | * is an 'N'; otherwise take the base from the 408 | * second read. */ 409 | if (*seq_2 == 'N') 410 | *combined_seq = *seq_1; 411 | else 412 | *combined_seq = *seq_2; 413 | } 414 | } 415 | combined_seq++; 416 | combined_qual++; 417 | seq_1++; 418 | seq_2++; 419 | qual_1++; 420 | qual_2++; 421 | } 422 | 423 | /* Copy the end of read 2 (not in the overlapped region). */ 424 | while (remaining_len--) { 425 | *combined_seq++ = *seq_2++; 426 | *combined_qual++ = *qual_2++; 427 | } 428 | } 429 | 430 | /* This is the entry point for the core algorithm of FLASH. The following 431 | * function attempts to combine @read_1 with @read_2, and writes the result into 432 | * @combined_read. COMBINED_AS_INNIE or COMBINED_AS_OUTIE is returned if 433 | * combination was successful. COMBINED_AS_OUTIE is only possible if 434 | * params->allow_outies is set. 435 | * 436 | * Note: @read_2 is provided to this function after having been 437 | * reverse-complemented. Hence, the code just aligns the reads in the forward 438 | * orientation, which is equivalent to aligning the original reads in the 439 | * desired reverse-complement orientation. 440 | * 441 | * Please see the help output of FLASH for the description of the min_overlap, 442 | * max_overlap, and max_mismatch_density parameters. (--min-overlap, 443 | * --max-overlap, and --max-mismatch-density on the command line). 444 | * 445 | * You may also want to read the original FLASH publication for a description of 446 | * the algorithm used here: 447 | * 448 | * Title: FLASH: fast length adjustment of short reads to improve genome assemblies 449 | * Authors: Tanja Magoč and Steven L. Salzberg 450 | * URL: http://bioinformatics.oxfordjournals.org/content/27/21/2957.full 451 | * 452 | */ 453 | enum combine_status 454 | combine_reads(const struct read *read_1, const struct read *read_2, 455 | struct read *combined_read, 456 | const struct combine_params *params) 457 | { 458 | int overlap_begin; 459 | enum combine_status status; 460 | bool was_outie; 461 | 462 | /* Do the alignment. */ 463 | 464 | overlap_begin = pair_align(read_1, read_2, 465 | params->min_overlap, 466 | params->max_overlap, 467 | params->max_mismatch_density, 468 | params->allow_outies, 469 | &was_outie); 470 | /* 471 | * If overlap_begin == NO_ALIGNMENT, then no sufficient overlap between 472 | * the reads was found. 473 | * 474 | * If !@was_outie, then the pair forms an "innie" overlap, and 475 | * overlap_begin is the 0-based position in read_1 at which read_2 476 | * begins. (Shown below with read 2 already reverse complemented!) 477 | * 478 | * 0 overlap_begin 479 | * | | 480 | * Read 1: ------------------> 481 | * Read 2: ----------------------> 482 | * 483 | * If @was_outie, then the pair forms an "outie" overlap, and 484 | * overlap_begin is the 0-based position in read_2 at which read_1 485 | * begins. (Shown below with read 2 already reverse complemented!) 486 | * 487 | * 0 overlap_begin 488 | * | | 489 | * Read 2: ------------------> 490 | * Read 1: ----------------------> 491 | */ 492 | 493 | if (overlap_begin == NO_ALIGNMENT) 494 | return NOT_COMBINED; 495 | 496 | if (!was_outie) { 497 | status = COMBINED_AS_INNIE; 498 | } else { 499 | const struct read *tmp; 500 | 501 | /* Simplify generation of the combined read by turning the outie 502 | * case into the innie case. */ 503 | 504 | tmp = read_1; 505 | read_1 = read_2; 506 | read_2 = tmp; 507 | 508 | status = COMBINED_AS_OUTIE; 509 | /* 510 | * Now it's just: 511 | * 512 | * 0 overlap_begin 513 | * | | 514 | * Read 1: ------------------> 515 | * Read 2: ----------------------> 516 | * 517 | * The same as the "innie" case. 518 | */ 519 | } 520 | 521 | /* Fill in the combined read. */ 522 | generate_combined_read(read_1, read_2, combined_read, 523 | overlap_begin, params->cap_mismatch_quals); 524 | return status; 525 | } 526 | -------------------------------------------------------------------------------- /combine_reads.h: -------------------------------------------------------------------------------- 1 | #ifndef _FLASH_COMBINE_READS_H_ 2 | #define _FLASH_COMBINE_READS_H_ 3 | 4 | #include 5 | 6 | struct read; 7 | 8 | /* Parameters for the core algorithm of FLASH. See the help output for more 9 | * information. */ 10 | struct combine_params { 11 | /* --min-overlap */ 12 | int min_overlap; 13 | 14 | /* --max-overlap */ 15 | int max_overlap; 16 | 17 | /* --max-mismatch-density */ 18 | float max_mismatch_density; 19 | 20 | /* --cap-mismatch-quals */ 21 | bool cap_mismatch_quals; 22 | 23 | /* --allow-outies */ 24 | bool allow_outies; 25 | }; 26 | 27 | /* Result of a call to combine_reads() */ 28 | enum combine_status { 29 | /* The reads could not be combined. */ 30 | NOT_COMBINED = 0, 31 | 32 | /* The reads were combined in "innie" orientation, like the following: 33 | * 34 | * ----------> 35 | * <------------ 36 | * 37 | * (Note: read_2 is reverse complemented before the call to 38 | * combine_reads()). */ 39 | COMBINED_AS_INNIE, 40 | 41 | /* The reads were combined in "outie" orientation, like the following: 42 | * 43 | * <---------- 44 | * ------------> 45 | * 46 | * (Note: read_2 is reverse complemented before the call to 47 | * combine_reads()). */ 48 | COMBINED_AS_OUTIE, 49 | }; 50 | 51 | extern enum combine_status 52 | combine_reads(const struct read *read_1, const struct read *read_2, 53 | struct read *combined_read, 54 | const struct combine_params *params); 55 | 56 | #endif /* _FLASH_COMBINE_READS_H_ */ 57 | -------------------------------------------------------------------------------- /flash.c: -------------------------------------------------------------------------------- 1 | /* 2 | * flash.c: parse arguments and set up and run the FLASH pipeline. 3 | * 4 | * Please see combine_reads.c if you are looking for the core algorithm used to 5 | * combine reads in FLASH. 6 | */ 7 | 8 | /* 9 | * Copyright (C) 2012 Tanja Magoc 10 | * Copyright (C) 2012, 2013, 2014 Eric Biggers 11 | * 12 | * This file is part of FLASH, a fast tool to merge overlapping paired-end 13 | * reads. 14 | * 15 | * FLASH is free software; you can redistribute it and/or modify it under the 16 | * terms of the GNU General Public License as published by the Free 17 | * Software Foundation; either version 3 of the License, or (at your option) 18 | * any later version. 19 | * 20 | * FLASH is distributed in the hope that it will be useful, but WITHOUT ANY 21 | * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR 22 | * A PARTICULAR PURPOSE. See the GNU General Public License for more 23 | * details. 24 | * 25 | * You should have received a copy of the GNU General Public License 26 | * along with FLASH; if not, see http://www.gnu.org/licenses/. 27 | */ 28 | 29 | #include 30 | #include 31 | #include 32 | #include 33 | #include 34 | #include 35 | #include 36 | #include 37 | #include 38 | #include 39 | 40 | #include "combine_reads.h" 41 | #include "iostream.h" 42 | #include "read.h" 43 | #include "read_io.h" 44 | #include "read_queue.h" 45 | #include "util.h" 46 | 47 | #define VERSION_STR "v1.2.11" 48 | 49 | #ifdef __WIN32__ 50 | # define PAGER "more" 51 | #else 52 | # define PAGER "less" 53 | #endif 54 | 55 | #define TO_PERCENT(n, d) \ 56 | ((d) == 0 ? 0 : ((double)(n) * 100 / (d))) 57 | 58 | static void 59 | usage(const char *argv0) 60 | { 61 | const char *usage_str = 62 | "Usage: flash [OPTIONS] MATES_1.FASTQ MATES_2.FASTQ\n" 63 | " flash [OPTIONS] --interleaved-input (MATES.FASTQ | -)\n" 64 | " flash [OPTIONS] --tab-delimited-input (MATES.TAB | -)\n" 65 | "\n" 66 | "----------------------------------------------------------------------------\n" 67 | " DESCRIPTION \n" 68 | "----------------------------------------------------------------------------\n" 69 | "\n" 70 | "FLASH (Fast Length Adjustment of SHort reads) is an accurate and fast tool\n" 71 | "to merge paired-end reads that were generated from DNA fragments whose\n" 72 | "lengths are shorter than twice the length of reads. Merged read pairs result\n" 73 | "in unpaired longer reads, which are generally more desired in genome\n" 74 | "assembly and genome analysis processes.\n" 75 | "\n" 76 | "Briefly, the FLASH algorithm considers all possible overlaps at or above a\n" 77 | "minimum length between the reads in a pair and chooses the overlap that\n" 78 | "results in the lowest mismatch density (proportion of mismatched bases in\n" 79 | "the overlapped region). Ties between multiple overlaps are broken by\n" 80 | "considering quality scores at mismatch sites. When building the merged\n" 81 | "sequence, FLASH computes a consensus sequence in the overlapped region.\n" 82 | "More details can be found in the original publication\n" 83 | "(http://bioinformatics.oxfordjournals.org/content/27/21/2957.full).\n" 84 | "\n" 85 | "Limitations of FLASH include:\n" 86 | " - FLASH cannot merge paired-end reads that do not overlap.\n" 87 | " - FLASH is not designed for data that has a significant amount of indel\n" 88 | " errors (such as Sanger sequencing data). It is best suited for Illumina\n" 89 | " data.\n" 90 | "\n" 91 | "----------------------------------------------------------------------------\n" 92 | " MANDATORY INPUT\n" 93 | "----------------------------------------------------------------------------\n" 94 | "\n" 95 | "The most common input to FLASH is two FASTQ files containing read 1 and read 2\n" 96 | "of each mate pair, respectively, in the same order.\n" 97 | "\n" 98 | "Alternatively, you may provide one FASTQ file, which may be standard input,\n" 99 | "containing paired-end reads in either interleaved FASTQ (see the\n" 100 | "--interleaved-input option) or tab-delimited (see the --tab-delimited-input\n" 101 | "option) format. In all cases, gzip compressed input is autodetected. Also,\n" 102 | "in all cases, the PHRED offset is, by default, assumed to be 33; use the\n" 103 | "--phred-offset option to change it.\n" 104 | "\n" 105 | "----------------------------------------------------------------------------\n" 106 | " OUTPUT\n" 107 | "----------------------------------------------------------------------------\n" 108 | "\n" 109 | "The default output of FLASH consists of the following files:\n" 110 | "\n" 111 | " - out.extendedFrags.fastq The merged reads.\n" 112 | " - out.notCombined_1.fastq Read 1 of mate pairs that were not merged.\n" 113 | " - out.notCombined_2.fastq Read 2 of mate pairs that were not merged.\n" 114 | " - out.hist Numeric histogram of merged read lengths.\n" 115 | " - out.histogram Visual histogram of merged read lengths.\n" 116 | "\n" 117 | "FLASH also logs informational messages to standard output. These can also be\n" 118 | "redirected to a file, as in the following example:\n" 119 | "\n" 120 | " $ flash reads_1.fq reads_2.fq 2>&1 | tee flash.log\n" 121 | "\n" 122 | "In addition, FLASH supports several features affecting the output:\n" 123 | "\n" 124 | " - Writing the merged reads directly to standard output (--to-stdout)\n" 125 | " - Writing gzip compressed output files (-z) or using an external\n" 126 | " compression program (--compress-prog)\n" 127 | " - Writing the uncombined read pairs in interleaved FASTQ format\n" 128 | " (--interleaved-output)\n" 129 | " - Writing all output reads to a single file in tab-delimited format\n" 130 | " (--tab-delimited-output)\n" 131 | "\n" 132 | "----------------------------------------------------------------------------\n" 133 | " OPTIONS\n" 134 | "----------------------------------------------------------------------------\n" 135 | "\n" 136 | " -m, --min-overlap=NUM The minimum required overlap length between two\n" 137 | " reads to provide a confident overlap. Default:\n" 138 | " 10bp.\n" 139 | "\n" 140 | " -M, --max-overlap=NUM Maximum overlap length expected in approximately\n" 141 | " 90% of read pairs. It is by default set to 65bp,\n" 142 | " which works well for 100bp reads generated from a\n" 143 | " 180bp library, assuming a normal distribution of\n" 144 | " fragment lengths. Overlaps longer than the maximum\n" 145 | " overlap parameter are still considered as good\n" 146 | " overlaps, but the mismatch density (explained below)\n" 147 | " is calculated over the first max_overlap bases in\n" 148 | " the overlapped region rather than the entire\n" 149 | " overlap. Default: 65bp, or calculated from the\n" 150 | " specified read length, fragment length, and fragment\n" 151 | " length standard deviation.\n" 152 | "\n" 153 | " -x, --max-mismatch-density=NUM\n" 154 | " Maximum allowed ratio between the number of\n" 155 | " mismatched base pairs and the overlap length.\n" 156 | " Two reads will not be combined with a given overlap\n" 157 | " if that overlap results in a mismatched base density\n" 158 | " higher than this value. Note: Any occurence of an\n" 159 | " 'N' in either read is ignored and not counted\n" 160 | " towards the mismatches or overlap length. Our\n" 161 | " experimental results suggest that higher values of\n" 162 | " the maximum mismatch density yield larger\n" 163 | " numbers of correctly merged read pairs but at\n" 164 | " the expense of higher numbers of incorrectly\n" 165 | " merged read pairs. Default: 0.25.\n" 166 | "\n" 167 | " -O, --allow-outies Also try combining read pairs in the \"outie\"\n" 168 | " orientation, e.g.\n" 169 | "\n" 170 | " Read 1: <-----------\n" 171 | " Read 2: ------------>\n" 172 | "\n" 173 | " as opposed to only the \"innie\" orientation, e.g.\n" 174 | "\n" 175 | " Read 1: <------------\n" 176 | " Read 2: ----------->\n" 177 | "\n" 178 | " FLASH uses the same parameters when trying each\n" 179 | " orientation. If a read pair can be combined in\n" 180 | " both \"innie\" and \"outie\" orientations, the\n" 181 | " better-fitting one will be chosen using the same\n" 182 | " scoring algorithm that FLASH normally uses.\n" 183 | "\n" 184 | " This option also causes extra .innie and .outie\n" 185 | " histogram files to be produced.\n" 186 | "\n" 187 | " -p, --phred-offset=OFFSET\n" 188 | " The smallest ASCII value of the characters used to\n" 189 | " represent quality values of bases in FASTQ files.\n" 190 | " It should be set to either 33, which corresponds\n" 191 | " to the later Illumina platforms and Sanger\n" 192 | " platforms, or 64, which corresponds to the\n" 193 | " earlier Illumina platforms. Default: 33.\n" 194 | "\n" 195 | " -r, --read-len=LEN\n" 196 | " -f, --fragment-len=LEN\n" 197 | " -s, --fragment-len-stddev=LEN\n" 198 | " Average read length, fragment length, and fragment\n" 199 | " standard deviation. These are convenience parameters\n" 200 | " only, as they are only used for calculating the\n" 201 | " maximum overlap (--max-overlap) parameter.\n" 202 | " The maximum overlap is calculated as the overlap of\n" 203 | " average-length reads from an average-size fragment\n" 204 | " plus 2.5 times the fragment length standard\n" 205 | " deviation. The default values are -r 100, -f 180,\n" 206 | " and -s 18, so this works out to a maximum overlap of\n" 207 | " 65 bp. If --max-overlap is specified, then the\n" 208 | " specified value overrides the calculated value.\n" 209 | "\n" 210 | " If you do not know the standard deviation of the\n" 211 | " fragment library, you can probably assume that the\n" 212 | " standard deviation is 10% of the average fragment\n" 213 | " length.\n" 214 | "\n" 215 | " --cap-mismatch-quals Cap quality scores assigned at mismatch locations\n" 216 | " to 2. This was the default behavior in FLASH v1.2.7\n" 217 | " and earlier. Later versions will instead calculate\n" 218 | " such scores as max(|q1 - q2|, 2); that is, the\n" 219 | " absolute value of the difference in quality scores,\n" 220 | " but at least 2. Essentially, the new behavior\n" 221 | " prevents a low quality base call that is likely a\n" 222 | " sequencing error from significantly bringing down\n" 223 | " the quality of a high quality, likely correct base\n" 224 | " call.\n" 225 | "\n" 226 | " --interleaved-input Instead of requiring files MATES_1.FASTQ and\n" 227 | " MATES_2.FASTQ, allow a single file MATES.FASTQ that\n" 228 | " has the paired-end reads interleaved. Specify \"-\"\n" 229 | " to read from standard input.\n" 230 | "\n" 231 | " --interleaved-output Write the uncombined pairs in interleaved FASTQ\n" 232 | " format.\n" 233 | "\n" 234 | " -I, --interleaved Equivalent to specifying both --interleaved-input\n" 235 | " and --interleaved-output.\n" 236 | "\n" 237 | " -Ti, --tab-delimited-input\n" 238 | " Assume the input is in tab-delimited format\n" 239 | " rather than FASTQ, in the format described below in\n" 240 | " '--tab-delimited-output'. In this mode you should\n" 241 | " provide a single input file, each line of which must\n" 242 | " contain either a read pair (5 fields) or a single\n" 243 | " read (3 fields). FLASH will try to combine the read\n" 244 | " pairs. Single reads will be written to the output\n" 245 | " file as-is if also using --tab-delimited-output;\n" 246 | " otherwise they will be ignored. Note that you may\n" 247 | " specify \"-\" as the input file to read the\n" 248 | " tab-delimited data from standard input.\n" 249 | "\n" 250 | " -To, --tab-delimited-output\n" 251 | " Write output in tab-delimited format (not FASTQ).\n" 252 | " Each line will contain either a combined pair in the\n" 253 | " format 'tag seq qual' or an uncombined\n" 254 | " pair in the format 'tag seq_1 qual_1\n" 255 | " seq_2 qual_2'.\n" 256 | "\n" 257 | " -o, --output-prefix=PREFIX\n" 258 | " Prefix of output files. Default: \"out\".\n" 259 | "\n" 260 | " -d, --output-directory=DIR\n" 261 | " Path to directory for output files. Default:\n" 262 | " current working directory.\n" 263 | "\n" 264 | " -c, --to-stdout Write the combined reads to standard output. In\n" 265 | " this mode, with FASTQ output (the default) the\n" 266 | " uncombined reads are discarded. With tab-delimited\n" 267 | " output, uncombined reads are included in the\n" 268 | " tab-delimited data written to standard output.\n" 269 | " In both cases, histogram files are not written,\n" 270 | " and informational messages are sent to standard\n" 271 | " error rather than to standard output.\n" 272 | "\n" 273 | " -z, --compress Compress the output files directly with zlib,\n" 274 | " using the gzip container format. Similar to\n" 275 | " specifying --compress-prog=gzip and --suffix=gz,\n" 276 | " but may be slightly faster.\n" 277 | "\n" 278 | " --compress-prog=PROG Pipe the output through the compression program\n" 279 | " PROG, which will be called as `PROG -c -',\n" 280 | " plus any arguments specified by --compress-prog-args.\n" 281 | " PROG must read uncompressed data from standard input\n" 282 | " and write compressed data to standard output when\n" 283 | " invoked as noted above.\n" 284 | " Examples: gzip, bzip2, xz, pigz.\n" 285 | "\n" 286 | " --compress-prog-args=ARGS\n" 287 | " A string of additional arguments that will be passed\n" 288 | " to the compression program if one is specified with\n" 289 | " --compress-prog=PROG. (The arguments '-c -' are\n" 290 | " still passed in addition to explicitly specified\n" 291 | " arguments.)\n" 292 | "\n" 293 | " --suffix=SUFFIX, --output-suffix=SUFFIX\n" 294 | " Use SUFFIX as the suffix of the output files\n" 295 | " after \".fastq\". A dot before the suffix is assumed,\n" 296 | " unless an empty suffix is provided. Default:\n" 297 | " nothing; or 'gz' if -z is specified; or PROG if\n" 298 | " --compress-prog=PROG is specified.\n" 299 | "\n" 300 | " -t, --threads=NTHREADS Set the number of worker threads. This is in\n" 301 | " addition to the I/O threads. Default: number of\n" 302 | " processors. Note: if you need FLASH's output to\n" 303 | " appear deterministically or in the same order as\n" 304 | " the original reads, you must specify -t 1\n" 305 | " (--threads=1).\n" 306 | "\n" 307 | " -q, --quiet Do not print informational messages.\n" 308 | "\n" 309 | " -h, --help Display this help and exit.\n" 310 | "\n" 311 | " -v, --version Display version.\n" 312 | ; 313 | fputs(usage_str, stdout); 314 | if (isatty(STDOUT_FILENO)) { 315 | /* Just to be extra user-friendly... */ 316 | printf("\nRun `%s --help | "PAGER"' to " 317 | "prevent this text from scrolling by.\n", argv0); 318 | } 319 | } 320 | 321 | static void 322 | usage_short(const char *argv0) 323 | { 324 | fprintf(stderr, 325 | "Usage: flash [OPTIONS] MATES_1.FASTQ MATES_2.FASTQ\n" 326 | "Run `%s --help | "PAGER"' for more information.\n", argv0); 327 | } 328 | 329 | static void 330 | version(void) 331 | { 332 | fputs( 333 | "FLASH "VERSION_STR"\n" 334 | "Copyright (C) 2012 Tanja Magoc\n" 335 | "Copyright (C) 2012, 2013, 2014 Eric Biggers\n" 336 | "License GPLv3+; GNU GPL version 3 or later .\n" 337 | "This is free software: you are free to change and redistribute it.\n" 338 | "There is NO WARRANTY, to the extent permitted by law.\n" 339 | "\n" 340 | "Report bugs to flash.comment@gmail.com or https://sourceforge.net/p/flashpage/bugs\n" 341 | , stdout); 342 | } 343 | 344 | enum { 345 | INTERLEAVED_INPUT_OPTION = 257, 346 | INTERLEAVED_OUTPUT_OPTION, 347 | CAP_MISMATCH_QUALS_OPTION, 348 | COMPRESS_PROG_OPTION, 349 | COMPRESS_PROG_ARGS_OPTION, 350 | SUFFIX_OPTION, 351 | TAB_DELIMITED_INPUT_OPTION, 352 | TAB_DELIMITED_OUTPUT_OPTION, 353 | }; 354 | 355 | static const char *optstring = "m:M:x:p:Or:f:s:IT:o:d:czt:qhv"; 356 | static const struct option longopts[] = { 357 | {"min-overlap", required_argument, NULL, 'm'}, 358 | {"max-overlap", required_argument, NULL, 'M'}, 359 | {"max-mismatch-density", required_argument, NULL, 'x'}, 360 | {"phred-offset", required_argument, NULL, 'p'}, 361 | {"allow-outies", no_argument, NULL, 'O'}, 362 | {"read-len", required_argument, NULL, 'r'}, 363 | {"fragment-len", required_argument, NULL, 'f'}, 364 | {"fragment-len-stddev", required_argument, NULL, 's'}, 365 | {"cap-mismatch-quals", no_argument, NULL, CAP_MISMATCH_QUALS_OPTION}, 366 | {"interleaved", no_argument, NULL, 'I'}, 367 | {"interleaved-input", no_argument, NULL, INTERLEAVED_INPUT_OPTION}, 368 | {"interleaved-output", no_argument, NULL, INTERLEAVED_OUTPUT_OPTION}, 369 | {"tab-delimited-input", no_argument, NULL, TAB_DELIMITED_INPUT_OPTION}, 370 | {"tab-delimited-output", no_argument, NULL, TAB_DELIMITED_OUTPUT_OPTION}, 371 | {"output-prefix", required_argument, NULL, 'o'}, 372 | {"output-directory", required_argument, NULL, 'd'}, 373 | {"to-stdout", no_argument, NULL, 'c'}, 374 | {"compress", no_argument, NULL, 'z'}, 375 | {"compress-prog", required_argument, NULL, COMPRESS_PROG_OPTION}, 376 | {"compress-prog-args", required_argument, NULL, COMPRESS_PROG_ARGS_OPTION}, 377 | {"suffix", required_argument, NULL, SUFFIX_OPTION}, 378 | {"output-suffix", required_argument, NULL, SUFFIX_OPTION}, 379 | {"threads", required_argument, NULL, 't'}, 380 | {"quiet", no_argument, NULL, 'q'}, 381 | {"help", no_argument, NULL, 'h'}, 382 | {"version", no_argument, NULL, 'v'}, 383 | {NULL, 0, NULL, 0} 384 | }; 385 | 386 | static char * 387 | input_format_str(char *buf, size_t bufsize, 388 | const struct read_format_params *iparams, 389 | bool interleaved) 390 | { 391 | switch (iparams->fmt) { 392 | case READ_FORMAT_FASTQ: 393 | snprintf(buf, bufsize, "FASTQ, phred_offset=%d%s", 394 | iparams->phred_offset, 395 | (interleaved ? ", interleaved" : "")); 396 | break; 397 | case READ_FORMAT_TAB_DELIMITED: 398 | snprintf(buf, bufsize, "Tab-delimited, phred_offset=%d", 399 | iparams->phred_offset); 400 | break; 401 | default: 402 | assert(0); 403 | break; 404 | } 405 | return buf; 406 | } 407 | 408 | static char * 409 | output_format_str(char *buf, size_t bufsize, 410 | const struct read_format_params *oparams, 411 | bool interleaved_output, 412 | enum out_compression_type out_ctype, 413 | const char *compress_prog, 414 | const char *compress_prog_args) 415 | { 416 | input_format_str(buf, bufsize, oparams, interleaved_output); 417 | switch (out_ctype) { 418 | case OUT_COMPRESSION_NONE: 419 | if (compress_prog) { 420 | char *p = strchr(buf, '\0'); 421 | snprintf(p, &buf[bufsize] - p, 422 | ", filtered through '%s %s'", 423 | compress_prog, compress_prog_args); 424 | } 425 | break; 426 | case OUT_COMPRESSION_GZIP: 427 | { 428 | char *p = strchr(buf, '\0'); 429 | snprintf(p, &buf[bufsize] - p, ", gzip"); 430 | } 431 | break; 432 | } 433 | return buf; 434 | } 435 | 436 | /* This is just a dynamic array used as a histogram. It's needed to count the 437 | * frequencies of the lengths of the combined reads. */ 438 | struct histogram { 439 | uint64_t *array; 440 | size_t len; 441 | }; 442 | 443 | static void 444 | hist_init(struct histogram *hist) 445 | { 446 | hist->array = NULL; 447 | hist->len = 0; 448 | } 449 | 450 | static void 451 | hist_destroy(struct histogram *hist) 452 | { 453 | xfree(hist->array, hist->len * sizeof(hist->array[0])); 454 | } 455 | 456 | static void 457 | hist_add(struct histogram *hist, size_t idx, uint64_t amount) 458 | { 459 | uint64_t *array = hist->array; 460 | size_t old_len = hist->len; 461 | if (idx >= old_len) { 462 | size_t new_len = idx + 1; 463 | array = xrealloc(array, new_len * sizeof(array[0])); 464 | memset(&array[old_len], 0, 465 | (new_len - old_len) * sizeof(array[0])); 466 | hist->len = new_len; 467 | hist->array = array; 468 | } 469 | array[idx] += amount; 470 | } 471 | 472 | static void 473 | hist_inc(struct histogram *hist, size_t idx) 474 | { 475 | hist_add(hist, idx, 1); 476 | } 477 | 478 | static void 479 | hist_combine(struct histogram *hist, const struct histogram *other) 480 | { 481 | for (size_t i = 0; i < other->len; i++) 482 | hist_add(hist, i, other->array[i]); 483 | } 484 | 485 | static uint64_t 486 | hist_count_at(const struct histogram *hist, size_t idx) 487 | { 488 | assert(idx < hist->len); 489 | return hist->array[idx]; 490 | } 491 | 492 | static void 493 | hist_stats(const struct histogram *hist, uint64_t *max_freq_ret, 494 | long *first_nonzero_idx_ret, long *last_nonzero_idx_ret) 495 | { 496 | *max_freq_ret = 0; 497 | *first_nonzero_idx_ret = -1; 498 | *last_nonzero_idx_ret = -2; 499 | for (size_t i = 1; i < hist->len; i++) { 500 | uint64_t freq = hist->array[i]; 501 | if (freq != 0) { 502 | if (*first_nonzero_idx_ret == -1) 503 | *first_nonzero_idx_ret = i; 504 | *last_nonzero_idx_ret = i; 505 | if (freq > *max_freq_ret) 506 | *max_freq_ret = freq; 507 | } 508 | } 509 | } 510 | 511 | 512 | static void 513 | write_hist_file(const char *hist_file, const struct histogram *hist, 514 | long first_nonzero_idx, long last_nonzero_idx) 515 | { 516 | FILE *fp = xfopen(hist_file, "w"); 517 | for (long i = first_nonzero_idx; i <= last_nonzero_idx; i++) { 518 | uint64_t count = hist_count_at(hist, i); 519 | if (count != 0) 520 | if (fprintf(fp, "%ld\t%"PRIu64"\n", i, count) < 0) 521 | goto write_error; 522 | } 523 | xfclose(fp, hist_file); 524 | return; 525 | 526 | write_error: 527 | fatal_error_with_errno("Error writing to \"%s\"", hist_file); 528 | } 529 | 530 | static void 531 | write_histogram_file(const char *histogram_file, const struct histogram *hist, 532 | long first_nonzero_idx, long last_nonzero_idx, 533 | uint64_t max_freq) 534 | { 535 | const double max_num_asterisks = 72; 536 | double scale = max_num_asterisks / (double)max_freq; 537 | 538 | FILE *fp = xfopen(histogram_file, "w"); 539 | 540 | for (long i = first_nonzero_idx; i <= last_nonzero_idx; i++) { 541 | if (fprintf(fp, "%ld\t", i) < 0) 542 | goto write_error; 543 | size_t num_asterisks = (size_t)(scale * (double)hist_count_at(hist, i)); 544 | while (num_asterisks--) 545 | if (fputc('*', fp) == EOF) 546 | goto write_error; 547 | if (fputc('\n', fp) == EOF) 548 | goto write_error; 549 | } 550 | xfclose(fp, histogram_file); 551 | return; 552 | write_error: 553 | fatal_error_with_errno("Error writing to \"%s\"", histogram_file); 554 | } 555 | 556 | struct flash_stats { 557 | struct histogram innie_lens; 558 | struct histogram outie_lens; 559 | struct histogram overlap_lens; 560 | uint64_t num_uncombined; 561 | uint64_t num_innie; 562 | uint64_t num_outie; 563 | }; 564 | 565 | static void 566 | flash_stats_init(struct flash_stats *stats) 567 | { 568 | hist_init(&stats->innie_lens); 569 | hist_init(&stats->outie_lens); 570 | hist_init(&stats->overlap_lens); 571 | stats->num_uncombined = 0; 572 | stats->num_innie = 0; 573 | stats->num_outie = 0; 574 | } 575 | 576 | static void 577 | flash_stats_combine(struct flash_stats *stats, const struct flash_stats *other) 578 | { 579 | hist_combine(&stats->innie_lens, &other->innie_lens); 580 | hist_combine(&stats->outie_lens, &other->outie_lens); 581 | hist_combine(&stats->overlap_lens, &other->overlap_lens); 582 | stats->num_uncombined += other->num_uncombined; 583 | stats->num_innie += other->num_innie; 584 | stats->num_outie += other->num_outie; 585 | } 586 | 587 | static void 588 | flash_stats_destroy(struct flash_stats *stats) 589 | { 590 | hist_destroy(&stats->innie_lens); 591 | hist_destroy(&stats->outie_lens); 592 | hist_destroy(&stats->overlap_lens); 593 | } 594 | 595 | struct common_combiner_thread_params { 596 | struct read_io_handle *iohandle; 597 | struct combine_params alg_params; 598 | }; 599 | 600 | struct combiner_thread_params { 601 | struct common_combiner_thread_params *common; 602 | struct flash_stats *stats; 603 | }; 604 | 605 | /* Buffer for read_sets for which all the read pointers have been invalidated. 606 | */ 607 | struct empty_sets { 608 | struct read_set *q1[2]; 609 | struct read_set *q2[2]; 610 | }; 611 | 612 | static void 613 | hold_empty_set(struct read_set *q[2], struct read_set *s) 614 | { 615 | if (!q[0]) { 616 | q[0] = s; 617 | } else { 618 | assert(!q[1]); 619 | q[1] = s; 620 | } 621 | } 622 | 623 | static void 624 | hold_empty_sets(struct empty_sets *e, struct read_set *s1, struct read_set *s2) 625 | { 626 | hold_empty_set(e->q1, s1); 627 | hold_empty_set(e->q2, s2); 628 | } 629 | 630 | static struct read_set * 631 | get_empty_set(struct read_set *q[2]) 632 | { 633 | struct read_set *s; 634 | 635 | assert(q[0]); 636 | s = q[0]; 637 | q[0] = q[1]; 638 | q[1] = NULL; 639 | 640 | return s; 641 | } 642 | 643 | static void 644 | get_empty_sets(struct empty_sets *e, 645 | struct read_set **s1_ret, struct read_set **s2_ret) 646 | { 647 | 648 | *s1_ret = get_empty_set(e->q1); 649 | *s2_ret = get_empty_set(e->q2); 650 | } 651 | 652 | static void 653 | free_empty_sets(struct empty_sets *e) 654 | { 655 | free_read_set(e->q1[0]); 656 | free_read_set(e->q1[1]); 657 | 658 | free_read_set(e->q2[0]); 659 | free_read_set(e->q2[1]); 660 | } 661 | 662 | /* This procedure is executed in parallel by all the combiner threads. */ 663 | static void * 664 | combiner_thread_proc(void *_params) 665 | { 666 | struct combiner_thread_params *params = _params; 667 | 668 | struct flash_stats *stats = params->stats; 669 | struct read_io_handle *iohandle = params->common->iohandle; 670 | const struct combine_params *alg_params = ¶ms->common->alg_params; 671 | 672 | struct read_set *s_avail_1 = new_empty_read_set(iohandle); 673 | struct read_set *s_avail_2 = new_empty_read_set(iohandle); 674 | struct read_set *s_uncombined_1 = new_empty_read_set(iohandle); 675 | struct read_set *s_uncombined_2 = new_empty_read_set(iohandle); 676 | struct read_set *s_combined = get_avail_read_set(iohandle); 677 | struct empty_sets empty = {}; 678 | 679 | struct read_set *s1; 680 | struct read_set *s2; 681 | 682 | /* While there are read pairs to process ... */ 683 | while (get_unprocessed_read_pairs(iohandle, &s1, &s2)) { 684 | 685 | /* ... process each read pair. */ 686 | for (size_t i = 0; i < s1->filled; i++) { 687 | struct read *r1 = s1->reads[i]; 688 | struct read *r2 = s2->reads[i]; 689 | struct read *r_combined; 690 | enum combine_status status; 691 | 692 | s1->reads[i] = NULL; 693 | s2->reads[i] = NULL; 694 | 695 | reverse_complement(r2); 696 | 697 | /* Get available read in which to try the combination. 698 | */ 699 | r_combined = s_combined->reads[s_combined->filled]; 700 | 701 | /* Try combining the reads. */ 702 | status = combine_reads(r1, r2, r_combined, alg_params); 703 | 704 | switch (status) { 705 | 706 | case COMBINED_AS_INNIE: 707 | stats->num_innie++; 708 | hist_inc(&stats->innie_lens, r_combined->seq_len); 709 | goto combined; 710 | 711 | case COMBINED_AS_OUTIE: 712 | stats->num_outie++; 713 | hist_inc(&stats->outie_lens, r_combined->seq_len); 714 | goto combined; 715 | 716 | combined: 717 | /* Combination was successful. */ 718 | 719 | hist_inc(&stats->overlap_lens, 720 | r1->seq_len + r2->seq_len - r_combined->seq_len); 721 | 722 | /* Uncombined read structures are unneeded; mark 723 | * them as available. */ 724 | 725 | if (s_avail_1->filled == s_avail_1->num_reads) { 726 | put_avail_read_pairs(iohandle, 727 | s_avail_1, 728 | s_avail_2); 729 | get_empty_sets(&empty, 730 | &s_avail_1, 731 | &s_avail_2); 732 | } 733 | s_avail_1->reads[s_avail_1->filled++] = r1; 734 | s_avail_2->reads[s_avail_2->filled++] = r2; 735 | 736 | /* Compute tag for combined read. */ 737 | get_combined_tag(r1, r2, r_combined); 738 | 739 | /* Send combined read. */ 740 | if (++s_combined->filled == s_combined->num_reads) { 741 | put_combined_reads(iohandle, s_combined); 742 | s_combined = get_avail_read_set(iohandle); 743 | } 744 | break; 745 | 746 | case NOT_COMBINED: 747 | stats->num_uncombined++; 748 | 749 | /* Send uncombined reads. */ 750 | if (s_uncombined_1->filled == s_uncombined_1->num_reads) { 751 | put_uncombined_read_pairs(iohandle, 752 | s_uncombined_1, 753 | s_uncombined_2); 754 | get_empty_sets(&empty, 755 | &s_uncombined_1, 756 | &s_uncombined_2); 757 | } 758 | 759 | s_uncombined_1->reads[s_uncombined_1->filled++] = r1; 760 | s_uncombined_2->reads[s_uncombined_2->filled++] = r2; 761 | reverse_complement(r2); 762 | } 763 | } 764 | 765 | s1->filled = 0; 766 | s2->filled = 0; 767 | hold_empty_sets(&empty, s1, s2); 768 | } 769 | 770 | /* No more reads to combine. */ 771 | 772 | /* Free read sets owned by this thread */ 773 | free_read_set(s_avail_1); 774 | free_read_set(s_avail_2); 775 | free_empty_sets(&empty); 776 | 777 | /* Send out any remaining uncombined and combined reads. 778 | * If there are none, free the corresponding read sets. */ 779 | 780 | if (s_uncombined_1->filled) { 781 | put_uncombined_read_pairs(iohandle, s_uncombined_1, s_uncombined_2); 782 | } else { 783 | free_read_set(s_uncombined_1); 784 | free_read_set(s_uncombined_2); 785 | } 786 | if (s_combined->filled) 787 | put_combined_reads(iohandle, s_combined); 788 | else 789 | free_read_set(s_combined); 790 | 791 | notify_combiner_terminated(iohandle); 792 | 793 | xfree(params, sizeof(*params)); 794 | return NULL; 795 | } 796 | 797 | static void 798 | warn_about_long_overlaps(const struct flash_stats *stats, int max_overlap) 799 | { 800 | uint64_t long_overlap_count; 801 | double long_overlap_percent; 802 | 803 | long_overlap_count = 0; 804 | for (size_t i = max_overlap + 1; i < stats->overlap_lens.len; i++) 805 | long_overlap_count += hist_count_at(&stats->overlap_lens, i); 806 | 807 | long_overlap_percent = TO_PERCENT(long_overlap_count, 808 | stats->num_innie + stats->num_outie); 809 | 810 | if (long_overlap_percent > 10.0) { 811 | warning("An unexpectedly high proportion of combined pairs " 812 | "(%.2f%%)\n" 813 | "overlapped by more than %d bp, the --max-overlap (-M) " 814 | "parameter. Consider\n" 815 | "increasing this parameter. (As-is, FLASH is " 816 | "penalizing overlaps longer than\n" 817 | "%d bp when considering them for possible combining!)", 818 | long_overlap_percent, max_overlap, max_overlap); 819 | } 820 | } 821 | 822 | int 823 | main(int argc, char **argv) 824 | { 825 | infofile = stdout; 826 | 827 | const char *argv0 = argv[0]; 828 | 829 | struct combine_params alg_params = { 830 | .max_overlap = 0, 831 | .min_overlap = 10, 832 | .max_mismatch_density = 0.25, 833 | .cap_mismatch_quals = false, 834 | .allow_outies = false, 835 | }; 836 | bool max_overlap_specified = false; 837 | struct read_format_params iparams = { 838 | .fmt = READ_FORMAT_FASTQ, 839 | .phred_offset = 33, 840 | }; 841 | struct read_format_params oparams = { 842 | .fmt = READ_FORMAT_FASTQ, 843 | .phred_offset = 33, 844 | }; 845 | int read_len = 100; 846 | int fragment_len = 180; 847 | int fragment_len_stddev = 18; 848 | bool read_len_specified = false; 849 | bool fragment_len_specified = false; 850 | bool fragment_len_stddev_specified = false; 851 | const char *prefix = "out"; 852 | const char *output_dir = "."; 853 | bool to_stdout = false; 854 | bool verbose = true; 855 | bool interleaved_input = false; 856 | bool interleaved_output = false; 857 | struct input_stream *mates1_in = NULL; 858 | struct input_stream *mates2_in = NULL; 859 | enum out_compression_type out_ctype = OUT_COMPRESSION_NONE; 860 | const char *compress_prog = NULL; 861 | char *compress_prog_args = "-c -"; 862 | bool compress_prog_args_allocated = false; 863 | struct output_stream *out_combined = NULL; 864 | struct output_stream *out_notcombined_1 = NULL; 865 | struct output_stream *out_notcombined_2 = NULL; 866 | const char *out_filetype = "fastq"; 867 | char *out_suffix = ""; 868 | bool out_suffix_allocated = false; 869 | unsigned long num_combiner_threads = 0; 870 | int c; 871 | char *tmp; 872 | struct timeval start_time; 873 | gettimeofday(&start_time, NULL); 874 | 875 | while ((c = getopt_long(argc, argv, optstring, longopts, NULL)) != -1) { 876 | switch (c) { 877 | case 'm': 878 | alg_params.min_overlap = strtol(optarg, &tmp, 10); 879 | if (tmp == optarg || *tmp || alg_params.min_overlap < 1) 880 | fatal_error("Minimum overlap must be a " 881 | "positive integer! Please check " 882 | "option -m."); 883 | break; 884 | case 'M': 885 | alg_params.max_overlap = strtol(optarg, &tmp, 10); 886 | if (tmp == optarg || *tmp || alg_params.max_overlap < 1) 887 | fatal_error("Maximum overlap must be " 888 | "a positive integer! Please check " 889 | "option -M."); 890 | max_overlap_specified = true; 891 | break; 892 | case 'x': 893 | alg_params.max_mismatch_density = strtod(optarg, &tmp); 894 | if (tmp == optarg || *tmp || alg_params.max_mismatch_density < 0.0 || 895 | alg_params.max_mismatch_density > 1.0) 896 | { 897 | fatal_error("Max mismatch density must be a " 898 | "number in the interval [0, 1]! " 899 | "Please check option -x."); 900 | } 901 | break; 902 | case 'p': 903 | oparams.phred_offset = 904 | iparams.phred_offset = 905 | strtol(optarg, &tmp, 10); 906 | if (tmp == optarg || *tmp || 907 | iparams.phred_offset < 0 || 908 | iparams.phred_offset > 127) 909 | { 910 | fatal_error("Phred offset must be an integer " 911 | "in the range [0, 127]! Please " 912 | "check option -p."); 913 | } 914 | if (iparams.phred_offset != 33 && 915 | iparams.phred_offset != 64) 916 | { 917 | warning("Phred offset is usually either " 918 | "64 (for earlier Illumina data) or 33 " 919 | "(for Sanger and later Illumina data)."); 920 | } 921 | break; 922 | case 'O': 923 | alg_params.allow_outies = true; 924 | break; 925 | case 'f': 926 | fragment_len = strtol(optarg, &tmp, 10); 927 | if (tmp == optarg || *tmp || fragment_len <= 0) 928 | fatal_error("Fragment length must be a " 929 | "positive integer! Please check " 930 | "option -f."); 931 | fragment_len_specified = true; 932 | break; 933 | case 's': 934 | fragment_len_stddev = strtol(optarg, &tmp, 10); 935 | if (tmp == optarg || *tmp || fragment_len_stddev <= 0) 936 | fatal_error("Fragment length standard deviation " 937 | "must be a positive integer! " 938 | "Please check option -s."); 939 | fragment_len_stddev_specified = true; 940 | break; 941 | case 'r': 942 | read_len = strtol(optarg, &tmp, 10); 943 | if (tmp == optarg || *tmp || read_len <= 0) 944 | fatal_error("Read length must be a " 945 | "positive integer! Please check " 946 | "option -r."); 947 | read_len_specified = true; 948 | break; 949 | case CAP_MISMATCH_QUALS_OPTION: 950 | alg_params.cap_mismatch_quals = true; 951 | break; 952 | case 'I': 953 | interleaved_input = true; 954 | interleaved_output = true; 955 | break; 956 | case INTERLEAVED_INPUT_OPTION: 957 | interleaved_input = true; 958 | break; 959 | case INTERLEAVED_OUTPUT_OPTION: 960 | interleaved_output = true; 961 | break; 962 | case 'T': 963 | if ((*optarg != 'i' && *optarg != 'o') || 964 | *(optarg + 1)) 965 | { 966 | fatal_error("Invalid option -T%s! Use -Ti " 967 | "(short for --tab-delimited-input)\n\t" 968 | "or -To (short for " 969 | "--tab-delimited-output)", optarg); 970 | } 971 | if (*optarg == 'i') { 972 | case TAB_DELIMITED_INPUT_OPTION: 973 | iparams.fmt = READ_FORMAT_TAB_DELIMITED; 974 | } else { 975 | case TAB_DELIMITED_OUTPUT_OPTION: 976 | oparams.fmt = READ_FORMAT_TAB_DELIMITED; 977 | out_filetype = "tab"; 978 | } 979 | break; 980 | case 'o': 981 | prefix = optarg; 982 | break; 983 | case 'd': 984 | output_dir = optarg; 985 | break; 986 | case 'c': 987 | to_stdout = true; 988 | infofile = stderr; 989 | break; 990 | case 'z': 991 | out_ctype = OUT_COMPRESSION_GZIP; 992 | if (out_suffix_allocated) 993 | free(out_suffix); 994 | out_suffix = ".gz"; 995 | out_suffix_allocated = false; 996 | compress_prog = NULL; 997 | break; 998 | case COMPRESS_PROG_OPTION: 999 | if (out_suffix_allocated) 1000 | free(out_suffix); 1001 | out_suffix = xmalloc(strlen(optarg) + 2); 1002 | sprintf(out_suffix, ".%s", optarg); 1003 | out_suffix_allocated = true; 1004 | compress_prog = optarg; 1005 | out_ctype = OUT_COMPRESSION_NONE; 1006 | break; 1007 | case COMPRESS_PROG_ARGS_OPTION: 1008 | if (compress_prog_args_allocated) 1009 | free(compress_prog_args); 1010 | compress_prog_args = xmalloc(strlen(optarg) + 6); 1011 | sprintf(compress_prog_args, "%s -c -", optarg); 1012 | compress_prog_args_allocated = true; 1013 | break; 1014 | case SUFFIX_OPTION: 1015 | if (out_suffix_allocated) 1016 | free(out_suffix); 1017 | if (*optarg) { 1018 | out_suffix = xmalloc(strlen(optarg) + 2); 1019 | sprintf(out_suffix, ".%s", optarg); 1020 | out_suffix_allocated = true; 1021 | } else { 1022 | out_suffix = optarg; 1023 | out_suffix_allocated = false; 1024 | } 1025 | break; 1026 | case 't': 1027 | num_combiner_threads = strtoul(optarg, &tmp, 10); 1028 | if (tmp == optarg || *tmp || num_combiner_threads < 1 || 1029 | num_combiner_threads > UINT_MAX) { 1030 | fatal_error("Number of threads must be " 1031 | "a positive integer! Please " 1032 | "check option -t."); 1033 | } 1034 | break; 1035 | case 'q': 1036 | verbose = false; 1037 | break; 1038 | case 'v': 1039 | version(); 1040 | return 0; 1041 | case 'h': 1042 | usage(argv0); 1043 | return 0; 1044 | default: 1045 | usage_short(argv0); 1046 | return 2; 1047 | } 1048 | } 1049 | 1050 | if (max_overlap_specified) { 1051 | if (read_len_specified) { 1052 | warning("--read-len (-r) has no effect when " 1053 | "--max-overlap (-M) is also\n" 1054 | "specified!"); 1055 | } 1056 | if (fragment_len_specified) { 1057 | warning("--fragment-len (-f) has no effect when " 1058 | "--max-overlap (-M) is\n" 1059 | "also specified!"); 1060 | } 1061 | if (fragment_len_stddev_specified) { 1062 | warning("--fragment-len-stddev (-s) has no effect when " 1063 | "--max-overlap\n" 1064 | "(-M) is also specified!"); 1065 | } 1066 | } else { 1067 | int count = (int)read_len_specified + 1068 | (int)fragment_len_specified + 1069 | (int)fragment_len_stddev_specified; 1070 | 1071 | alg_params.max_overlap = (int)(2 * read_len - fragment_len + 1072 | 2.5 * fragment_len_stddev); 1073 | 1074 | if (count == 1 || count == 2) { 1075 | warning("You specified at least one, but not all, " 1076 | "of --read-len (-r),\n" 1077 | "--fragment-len (-f), and " 1078 | "--fragment-len-stddev (-s). FLASH is using\n" 1079 | "read_len=%d, fragment_len=%d, and " 1080 | "fragment_len_stddev=%d to compute\n" 1081 | "max_overlap=%d. If this is not correct for " 1082 | "your data you must either specify\n" 1083 | "all these options or specify --max-overlap (-M).", 1084 | read_len, 1085 | fragment_len, 1086 | fragment_len_stddev, 1087 | alg_params.max_overlap); 1088 | } 1089 | #if 0 1090 | if (count == 0) { 1091 | warning("Using default maximum overlap of %d bp! " 1092 | "Use --max-overlap (-M)\n" 1093 | "to change it. Or specify all of --read-len " 1094 | "(-r), --fragment-len (-f), and\n" 1095 | "--fragment-len-stddev (-s).", 1096 | alg_params.max_overlap); 1097 | } 1098 | #endif 1099 | } 1100 | 1101 | if (alg_params.max_overlap < alg_params.min_overlap) { 1102 | fatal_error( 1103 | "Maximum overlap (%d) cannot be less than the minimum overlap (%d).\n" 1104 | "Please make sure you have provided the read length and fragment length\n" 1105 | "correctly. Or, alternatively, specify the minimum and maximum overlap\n" 1106 | "manually with the --min-overlap and --max-overlap options.", 1107 | alg_params.max_overlap, alg_params.min_overlap); 1108 | } 1109 | 1110 | if (num_combiner_threads == 0) 1111 | num_combiner_threads = get_default_num_threads(); 1112 | 1113 | argc -= optind; 1114 | argv += optind; 1115 | 1116 | if (argc == 0 || argc > 2) { 1117 | usage_short(argv0); 1118 | return 2; 1119 | } 1120 | if (interleaved_input && argc != 1) 1121 | fatal_error("With --interleaved-input, only 1 input " 1122 | "file is allowed!"); 1123 | 1124 | if (interleaved_input && iparams.fmt != READ_FORMAT_FASTQ) 1125 | fatal_error("--interleaved-input is only relevant for FASTQ input!"); 1126 | 1127 | if (argc == 1 && !interleaved_input && iparams.fmt == READ_FORMAT_FASTQ) 1128 | fatal_error("Only 1 input file was specified! Specify " 1129 | "--interleaved-input\n" 1130 | "\tif you're providing an interleaved FASTQ file, " 1131 | "or --tab-delimited-input\n" 1132 | "\tif you're providing a tab-delimited input file. " 1133 | "Or specify two input\n" 1134 | "\tfiles (for read 1 and read 2 of each pair)."); 1135 | 1136 | mates1_in = new_input_stream(argv[0]); 1137 | if (argc > 1) 1138 | mates2_in = new_input_stream(argv[1]); 1139 | 1140 | mkdir_p(output_dir); 1141 | 1142 | /* Open the output files. */ 1143 | 1144 | char name_buf[strlen(output_dir) + 1 + strlen(prefix) + 1145 | 100 + strlen(out_suffix) + 1]; 1146 | char *suffix; 1147 | suffix = name_buf + sprintf(name_buf, "%s/%s", output_dir, prefix); 1148 | 1149 | if (oparams.fmt == READ_FORMAT_TAB_DELIMITED) { 1150 | sprintf(suffix, ".readsAndPairs.%s%s", out_filetype, out_suffix); 1151 | out_combined = new_output_stream(out_ctype, 1152 | (to_stdout ? "-" : name_buf), 1153 | compress_prog, 1154 | compress_prog_args); 1155 | } else { 1156 | sprintf(suffix, ".extendedFrags.%s%s", out_filetype, out_suffix); 1157 | out_combined = new_output_stream(out_ctype, 1158 | (to_stdout ? "-" : name_buf), 1159 | compress_prog, 1160 | compress_prog_args); 1161 | 1162 | if (!to_stdout) { 1163 | if (interleaved_output) { 1164 | sprintf(suffix, ".notCombined.%s%s", 1165 | out_filetype, out_suffix); 1166 | out_notcombined_1 = new_output_stream(out_ctype, 1167 | name_buf, 1168 | compress_prog, 1169 | compress_prog_args); 1170 | } else { 1171 | sprintf(suffix, ".notCombined_1.%s%s", 1172 | out_filetype, out_suffix); 1173 | out_notcombined_1 = new_output_stream(out_ctype, 1174 | name_buf, 1175 | compress_prog, 1176 | compress_prog_args); 1177 | 1178 | sprintf(suffix, ".notCombined_2.%s%s", 1179 | out_filetype, out_suffix); 1180 | out_notcombined_2 = new_output_stream(out_ctype, 1181 | name_buf, 1182 | compress_prog, 1183 | compress_prog_args); 1184 | } 1185 | } 1186 | } 1187 | 1188 | *suffix = '\0'; 1189 | 1190 | if (verbose) { 1191 | info("Starting FLASH " VERSION_STR); 1192 | info("Fast Length Adjustment of SHort reads"); 1193 | info(" "); 1194 | info("Input files:"); 1195 | info(" %s", input_stream_get_name(mates1_in)); 1196 | if (mates2_in) 1197 | info(" %s", input_stream_get_name(mates2_in)); 1198 | info(" "); 1199 | info("Output files:"); 1200 | info(" %s", output_stream_get_name(out_combined)); 1201 | if (out_notcombined_1) 1202 | info(" %s", output_stream_get_name(out_notcombined_1)); 1203 | if (out_notcombined_2) 1204 | info(" %s", output_stream_get_name(out_notcombined_2)); 1205 | if (!to_stdout) { 1206 | info(" %s.hist", name_buf); 1207 | info(" %s.histogram", name_buf); 1208 | } 1209 | info(" "); 1210 | info("Parameters:"); 1211 | info(" Min overlap: %d", 1212 | alg_params.min_overlap); 1213 | info(" Max overlap: %d", 1214 | alg_params.max_overlap); 1215 | info(" Max mismatch density: %f", 1216 | alg_params.max_mismatch_density); 1217 | info(" Allow \"outie\" pairs: %s", 1218 | alg_params.allow_outies ? "true" : "false"); 1219 | info(" Cap mismatch quals: %s", 1220 | alg_params.cap_mismatch_quals ? "true" : "false"); 1221 | info(" Combiner threads: %u", 1222 | (unsigned)num_combiner_threads); 1223 | 1224 | char buf[256]; 1225 | info(" Input format: %s", 1226 | input_format_str(buf, ARRAY_LEN(buf), 1227 | &iparams, interleaved_input)); 1228 | info(" Output format: %s", 1229 | output_format_str(buf, ARRAY_LEN(buf), 1230 | &oparams, interleaved_output, 1231 | out_ctype, 1232 | compress_prog, compress_prog_args)); 1233 | info(" "); 1234 | } 1235 | 1236 | /* 1237 | * We wish to do the following: 1238 | * 1239 | * "Go through each mate pair in the input files. Determine if it can 1240 | * be combined, given the input parameters to the program. If it can, 1241 | * write the combined read to the PREFIX.extendedFrags.fastq file. 1242 | * Otherwise, write the reads in the mate pair to the 1243 | * PREFIX.notCombined_1.fastq and PREFIX.notCombined_2.fastq files, or 1244 | * PREFIX.notCombined.fastq for interleaved output. Or, if the -c / 1245 | * --to-stdout option is specified, write the combined reads to standard 1246 | * output, and ignore the uncombined reads." 1247 | * 1248 | * In the following implementation, there will be @num_combiner_threads 1249 | * combiner threads created that will process the reads in parallel by 1250 | * retrieving `struct read_set'-sized chunks of reads from the reader 1251 | * thread(s), and providing `struct read_set'-sized chunks of combined 1252 | * or uncombined reads to the writer threads. 1253 | */ 1254 | 1255 | struct flash_stats stats[num_combiner_threads]; 1256 | struct flash_stats *total_stats = &stats[num_combiner_threads - 1]; 1257 | for (size_t i = 0; i < num_combiner_threads; i++) 1258 | flash_stats_init(&stats[i]); 1259 | 1260 | struct read_io_handle *iohandle = 1261 | start_readers_and_writers(mates1_in, 1262 | mates2_in, 1263 | out_combined, 1264 | out_notcombined_1, 1265 | out_notcombined_2, 1266 | &iparams, &oparams, 1267 | num_combiner_threads, verbose); 1268 | struct common_combiner_thread_params common = { 1269 | .iohandle = iohandle, 1270 | .alg_params = alg_params, 1271 | }; 1272 | 1273 | if (verbose) 1274 | info("Starting %u combiner threads", (unsigned)num_combiner_threads); 1275 | 1276 | pthread_t other_combiner_threads[num_combiner_threads - 1]; 1277 | for (unsigned i = 0; i < num_combiner_threads; i++) { 1278 | struct combiner_thread_params *p; 1279 | 1280 | p = xmalloc(sizeof(*p)); 1281 | p->common = &common; 1282 | p->stats = &stats[i]; 1283 | if (i < num_combiner_threads - 1) 1284 | other_combiner_threads[i] = 1285 | create_thread(combiner_thread_proc, p); 1286 | else 1287 | combiner_thread_proc(p); 1288 | } 1289 | for (unsigned i = 0; i < num_combiner_threads - 1; i++) { 1290 | join_thread(other_combiner_threads[i]); 1291 | flash_stats_combine(total_stats, &stats[i]); 1292 | flash_stats_destroy(&stats[i]); 1293 | } 1294 | stop_readers_and_writers(iohandle); 1295 | 1296 | if (verbose) { 1297 | uint64_t num_combined_pairs; 1298 | uint64_t num_uncombined_pairs; 1299 | uint64_t num_total_pairs; 1300 | 1301 | num_combined_pairs = total_stats->num_innie + total_stats->num_outie; 1302 | num_uncombined_pairs = total_stats->num_uncombined; 1303 | num_total_pairs = num_combined_pairs + num_uncombined_pairs; 1304 | 1305 | info(" "); 1306 | info("Read combination statistics:"); 1307 | info(" Total pairs: %"PRIu64, num_total_pairs); 1308 | info(" Combined pairs: %"PRIu64, num_combined_pairs); 1309 | if (alg_params.allow_outies) { 1310 | info(" Innie pairs: %"PRIu64" " 1311 | "(%.2f%% of combined)", 1312 | total_stats->num_innie, 1313 | TO_PERCENT(total_stats->num_innie, 1314 | num_combined_pairs)); 1315 | info(" Outie pairs: %"PRIu64" " 1316 | "(%.2f%% of combined)", 1317 | total_stats->num_outie, 1318 | TO_PERCENT(total_stats->num_outie, 1319 | num_combined_pairs)); 1320 | } 1321 | info(" Uncombined pairs: %"PRIu64, num_uncombined_pairs); 1322 | info(" Percent combined: %.2f%%", 1323 | TO_PERCENT(num_combined_pairs, num_total_pairs)); 1324 | info(" "); 1325 | } 1326 | 1327 | if (!to_stdout) { 1328 | struct histogram _combined_read_lens; 1329 | int hist_count; 1330 | struct histogram *combined_read_lens; 1331 | 1332 | if (verbose) 1333 | info("Writing histogram files."); 1334 | 1335 | if (alg_params.allow_outies) { 1336 | hist_count = 3; 1337 | hist_init(&_combined_read_lens); 1338 | hist_combine(&_combined_read_lens, &total_stats->innie_lens); 1339 | hist_combine(&_combined_read_lens, &total_stats->outie_lens); 1340 | combined_read_lens = &_combined_read_lens; 1341 | } else { 1342 | hist_count = 1; 1343 | combined_read_lens = &total_stats->innie_lens; 1344 | } 1345 | 1346 | struct { 1347 | const char *suffix; 1348 | const struct histogram *hist; 1349 | } hist_specs[] = { 1350 | { "", combined_read_lens }, 1351 | { ".innie", &total_stats->innie_lens }, 1352 | { ".outie", &total_stats->outie_lens }, 1353 | }; 1354 | 1355 | for (int i = 0; i < hist_count; i++) { 1356 | uint64_t max_freq; 1357 | long first_nonzero_idx; 1358 | long last_nonzero_idx; 1359 | 1360 | hist_stats(hist_specs[i].hist, 1361 | &max_freq, &first_nonzero_idx, &last_nonzero_idx); 1362 | 1363 | /* Write the raw numbers of the combined read length 1364 | * histogram to the PREFIX.hist file. */ 1365 | sprintf(suffix, ".hist%s", hist_specs[i].suffix); 1366 | write_hist_file(name_buf, hist_specs[i].hist, 1367 | first_nonzero_idx, last_nonzero_idx); 1368 | 1369 | /* Write a pretty representation of the combined read 1370 | * length histogram to the PREFIX.histogram file. */ 1371 | sprintf(suffix, ".histogram%s", hist_specs[i].suffix); 1372 | write_histogram_file(name_buf, hist_specs[i].hist, 1373 | first_nonzero_idx, last_nonzero_idx, 1374 | max_freq); 1375 | } 1376 | 1377 | if (alg_params.allow_outies) 1378 | hist_destroy(combined_read_lens); 1379 | } 1380 | 1381 | warn_about_long_overlaps(total_stats, alg_params.max_overlap); 1382 | 1383 | flash_stats_destroy(total_stats); 1384 | 1385 | if (verbose) { 1386 | struct timeval end_time; 1387 | gettimeofday(&end_time, NULL); 1388 | uint64_t start_usec = (uint64_t)start_time.tv_sec * 1000000 + start_time.tv_usec; 1389 | uint64_t end_usec = (uint64_t)end_time.tv_sec * 1000000 + end_time.tv_usec; 1390 | info(" "); 1391 | info("FLASH " VERSION_STR " complete!"); 1392 | info("%.3f seconds elapsed", (double)(end_usec - start_usec) / 1000000); 1393 | } 1394 | 1395 | if (warning_count > 0) { 1396 | info("Finished with %lu warning%s (see above)", 1397 | warning_count, warning_count == 1 ? "" : "s"); 1398 | } 1399 | 1400 | if (out_suffix_allocated) 1401 | free(out_suffix); 1402 | if (compress_prog_args_allocated) 1403 | free(compress_prog_args); 1404 | return 0; 1405 | } 1406 | -------------------------------------------------------------------------------- /iostream.c: -------------------------------------------------------------------------------- 1 | /* 2 | * iostream.c: Buffered file input and output streams with automatic error 3 | * checking and extra features such as gzip compression. 4 | */ 5 | 6 | /* 7 | * Copyright (C) 2012 Tanja Magoc 8 | * Copyright (C) 2012, 2013, 2014 Eric Biggers 9 | * 10 | * This file is part of FLASH, a fast tool to merge overlapping paired-end 11 | * reads. 12 | * 13 | * FLASH is free software; you can redistribute it and/or modify it under the 14 | * terms of the GNU General Public License as published by the Free 15 | * Software Foundation; either version 3 of the License, or (at your option) 16 | * any later version. 17 | * 18 | * FLASH is distributed in the hope that it will be useful, but WITHOUT ANY 19 | * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR 20 | * A PARTICULAR PURPOSE. See the GNU General Public License for more 21 | * details. 22 | * 23 | * You should have received a copy of the GNU General Public License 24 | * along with FLASH; if not, see http://www.gnu.org/licenses/. 25 | */ 26 | 27 | #include "iostream.h" 28 | #include "util.h" 29 | 30 | #include 31 | #include 32 | #include 33 | #include 34 | #include 35 | #include 36 | #include 37 | #include 38 | #include 39 | 40 | /* Return true iff the specified string is a single hyphen, which may represent 41 | * standard input or standard output. */ 42 | static bool 43 | string_is_hyphen(const char *str) 44 | { 45 | return str[0] == '-' && str[1] == '\0'; 46 | } 47 | 48 | static bool 49 | mode_is_writing(const char *mode) 50 | { 51 | return strchr(mode, 'w') != NULL; 52 | } 53 | 54 | static bool 55 | flags_is_writing(int flags) 56 | { 57 | int accmode = (flags & O_ACCMODE); 58 | return (accmode == O_WRONLY || accmode == O_RDWR); 59 | } 60 | 61 | static const char * 62 | access_mode_string(const char *mode) 63 | { 64 | return mode_is_writing(mode) ? "writing" : "reading"; 65 | } 66 | 67 | static const char * 68 | access_flags_string(int flags) 69 | { 70 | return flags_is_writing(flags) ? "writing" : "reading"; 71 | } 72 | 73 | static int 74 | mode_to_flags(const char *mode) 75 | { 76 | return mode_is_writing(mode) ? O_WRONLY | O_TRUNC | O_CREAT : O_RDONLY; 77 | } 78 | 79 | /* Returns a standard file descriptor depending on the flags: 80 | * 81 | * reading => standard input 82 | * writing => standard output 83 | */ 84 | static int 85 | standard_fd_from_flags(int flags) 86 | { 87 | return flags_is_writing(flags) ? STDOUT_FILENO : STDIN_FILENO; 88 | } 89 | 90 | /* Like fopen(), but aborts on error. */ 91 | void * 92 | xfopen(const char *path, const char *mode) 93 | { 94 | FILE *fp = fopen(path, mode); 95 | if (!fp) 96 | fatal_error_with_errno("Failed to open \"%s\" for %s", 97 | path, access_mode_string(mode)); 98 | return fp; 99 | } 100 | 101 | /* Like fclose(), but aborts on error. */ 102 | void 103 | xfclose(FILE *fp, const char *name) 104 | { 105 | if (fclose(fp)) 106 | fatal_error_with_errno("Error closing \"%s\"", name); 107 | } 108 | 109 | #ifndef O_BINARY 110 | # define O_BINARY 0 111 | #endif 112 | 113 | /* Like open(), but aborts on error, and also interprets "-" as standard output 114 | * or standard input rather than a path, depending on the requested mode. Also 115 | * automatically provides O_BINARY on Windows. */ 116 | static void * 117 | xopen(const char *path, int flags, mode_t mode) 118 | { 119 | int fd; 120 | 121 | if (string_is_hyphen(path)) { 122 | fd = standard_fd_from_flags(flags); 123 | #ifdef __WIN32__ 124 | _setmode(fd, O_BINARY); 125 | #endif 126 | } else { 127 | fd = open(path, flags | O_BINARY, mode); 128 | } 129 | 130 | if (fd < 0) 131 | fatal_error_with_errno("Failed to open \"%s\" for %s", 132 | path, access_flags_string(flags)); 133 | 134 | /* XXX: autodetect whether posix_fadvise() is available or not. */ 135 | #ifdef __linux__ 136 | /* Advise the operating system that the file will be read or written 137 | * sequentially. */ 138 | posix_fadvise(fd, 0, 0, POSIX_FADV_SEQUENTIAL); 139 | #endif 140 | 141 | return (void*)(intptr_t)fd; 142 | } 143 | 144 | /* Like gzopen(), but aborts on error, and also interprets "-" as standard 145 | * output or standard input rather than a path, depending on the requested mode. 146 | */ 147 | static void * 148 | xgzopen(const char *path, const char *mode) 149 | { 150 | gzFile gzf; 151 | int fd; 152 | 153 | fd = (int)(intptr_t)xopen(path, mode_to_flags(mode), 0644); 154 | errno = 0; 155 | gzf = gzdopen(fd, mode); 156 | if (!gzf) 157 | fatal_error_with_errno("Failed to open \"%s\" for %s", 158 | path, access_mode_string(mode)); 159 | return gzf; 160 | } 161 | 162 | /* Like gzclose(), but aborts on error. */ 163 | static void 164 | xgzclose(void *_fp, const char *name) 165 | { 166 | gzFile gzf = (gzFile)_fp; 167 | errno = 0; 168 | if (gzclose(gzf) != Z_OK) 169 | fatal_error_with_errno("Error closing \"%s\"", name); 170 | } 171 | 172 | /* Checks the error status on a gzFile. Returns only if no error occurred or if 173 | * the error was caused by an interruption (EINTR). */ 174 | static void 175 | check_gzerror(gzFile gzf, bool was_writing, const char *name) 176 | { 177 | int errnum; 178 | const char *error_str; 179 | 180 | error_str = gzerror(gzf, &errnum); 181 | switch (errnum) { 182 | case Z_OK: 183 | return; 184 | case Z_ERRNO: 185 | if (errno == EINTR) 186 | return; 187 | fatal_error_with_errno("Error %s \"%s\"", 188 | (was_writing ? "writing" : "reading"), 189 | name); 190 | default: 191 | fatal_error("zlib error %s \"%s\": %s", 192 | (was_writing ? "writing" : "reading"), 193 | name, error_str); 194 | } 195 | } 196 | 197 | /* Reads data from gzFile, with error checking. Returns the number of bytes 198 | * successfully read, which will be less than or equal to @count; 0 implies the 199 | * stream is at end-of-file. Aborts on error. */ 200 | static size_t 201 | xgzread(void *_fp, void *buf, size_t count, const char *name) 202 | { 203 | gzFile gzf = (gzFile)_fp; 204 | int trycount = min(count, INT_MAX); 205 | 206 | for (;;) { 207 | int ret = gzread(gzf, buf, trycount); 208 | if (ret >= 0) 209 | return ret; 210 | if (gzeof(gzf)) 211 | return 0; 212 | check_gzerror(gzf, false, name); 213 | } 214 | } 215 | 216 | /* Writes data to a gzFile, with error checking. */ 217 | static void 218 | xgzwrite(void *_fp, const void *_buf, size_t count, const char *name) 219 | { 220 | gzFile gzf = (gzFile)_fp; 221 | const char *ptr = _buf; 222 | 223 | while (count) { 224 | int trycount = min(count, INT_MAX); 225 | int ret = gzwrite(gzf, ptr, trycount); 226 | if (!ret) { 227 | check_gzerror(gzf, true, name); 228 | continue; 229 | } 230 | ptr += ret; 231 | count -= ret; 232 | } 233 | } 234 | 235 | /* Reads data from a file descriptor, with error checking. Returns the number 236 | * of bytes successfully read, which will be less than or equal to @count; 0 237 | * implies end-of-file has been reached. Aborts on error. */ 238 | static size_t 239 | xread(void *_fp, void *buf, size_t count, const char *name) 240 | { 241 | int fd = (int)(intptr_t)_fp; 242 | ssize_t trycount = min(count, SSIZE_MAX); 243 | 244 | for (;;) { 245 | ssize_t ret = read(fd, buf, trycount); 246 | if (ret >= 0) 247 | return ret; 248 | if (errno != EINTR) 249 | fatal_error_with_errno("Error reading \"%s\"", name); 250 | } 251 | } 252 | 253 | /* Similar to xread(), but retries on short reads. */ 254 | static size_t 255 | full_xread(void *fp, void *_buf, size_t count, const char *name) 256 | { 257 | char *ptr = _buf; 258 | while (count) { 259 | size_t ret = xread(fp, ptr, count, name); 260 | if (ret == 0) 261 | break; 262 | ptr += ret; 263 | count -= ret; 264 | } 265 | return ptr - (char*)_buf; 266 | } 267 | 268 | /* Writes data to a file descriptor, with error checking. */ 269 | static void 270 | xwrite(void *_fp, const void *_buf, size_t count, const char *name) 271 | { 272 | int fd = (int)(intptr_t)_fp; 273 | const char *ptr = _buf; 274 | 275 | while (count) { 276 | ssize_t trycount = min(count, SSIZE_MAX); 277 | ssize_t ret = write(fd, ptr, trycount); 278 | if (ret < 0) { 279 | if (errno == EINTR) 280 | continue; 281 | fatal_error_with_errno("Error writing \"%s\"", name); 282 | } 283 | ptr += ret; 284 | count -= ret; 285 | } 286 | } 287 | 288 | /* Closes a file descriptor, with error checking. */ 289 | static void 290 | xclose(void *_fp, const char *name) 291 | { 292 | int fd = (int)(intptr_t)_fp; 293 | if (close(fd)) 294 | fatal_error_with_errno("Error closing \"%s\"", name); 295 | } 296 | 297 | /* Writes data to a FILE *, with error checking. */ 298 | static void 299 | xfwrite(void *_fp, const void *buf, size_t count, const char *name) 300 | { 301 | FILE *fp = (FILE*)_fp; 302 | 303 | if (fwrite(buf, 1, count, fp) != count) 304 | fatal_error_with_errno("Error writing \"%s\"", name); 305 | } 306 | 307 | /* Closes a FILE * opened with popen(), with error checking. */ 308 | static void 309 | xpclose(void *_fp, const char *name) 310 | { 311 | FILE *fp = (FILE*)_fp; 312 | int status = pclose(fp); 313 | 314 | if (status == -1) 315 | fatal_error_with_errno("Error closing pipe to \"%s\"", name); 316 | if (status) 317 | fatal_error("Program writing to \"%s\" " 318 | "exited with failure status", name); 319 | } 320 | 321 | #define IOSTREAM_BUFSIZE 32768 322 | 323 | /***************************** 324 | * Input stream functions * 325 | *****************************/ 326 | 327 | static void * 328 | input_gzfile_open(const char *path) 329 | { 330 | return xgzopen(path, "rb"); 331 | } 332 | 333 | static void * 334 | input_fd_open(const char *path) 335 | { 336 | return xopen(path, O_RDONLY, 0); 337 | } 338 | 339 | struct input_stream { 340 | const struct input_stream_operations *ops; 341 | void *fp; 342 | char *name; 343 | char *buf_begin; 344 | char *buf_end; 345 | char *buf_cur_begin; 346 | char *buf_cur_end; 347 | }; 348 | 349 | struct input_stream_operations { 350 | /* Open the specified file for reading. */ 351 | void * (*open)(const char *path); 352 | 353 | /* Read data from the specified file (up to @count bytes; 354 | * return 0 if at end of file). */ 355 | size_t (*read)(void *fp, void *buf, size_t count, const char *name); 356 | 357 | /* Close the specified file. */ 358 | void (*close)(void *fp, const char *name); 359 | }; 360 | 361 | /* Input stream operations for reading raw data from a file descriptor */ 362 | static const struct input_stream_operations fd_input_stream_ops = { 363 | .open = input_fd_open, 364 | .read = xread, 365 | .close = xclose, 366 | }; 367 | 368 | /* Input stream operations for reading a gzip compressed file using zlib */ 369 | static const struct input_stream_operations gzfile_input_stream_ops = { 370 | .open = input_gzfile_open, 371 | .read = xgzread, 372 | .close = xgzclose, 373 | }; 374 | 375 | /* Auto-detects the correct input_stream_operations to use for the specified 376 | * file. */ 377 | static const struct input_stream_operations * 378 | select_input_stream_ops(const char *path) 379 | { 380 | /* XXX: We can't rewind standard input after checking for magic bytes, 381 | * so for that case we rely on the fact that gzread returns the literal 382 | * data if the stream does not, in fact, contain gzipped data. */ 383 | if (string_is_hyphen(path)) 384 | return &gzfile_input_stream_ops; 385 | 386 | /* Test for gzip magic bytes { 0x1f, 0x8b} */ 387 | 388 | unsigned char magic[2] = {0, 0}; 389 | void *tmp_fp; 390 | 391 | tmp_fp = input_fd_open(path); 392 | full_xread(tmp_fp, magic, sizeof(magic), path); 393 | xclose(tmp_fp, path); 394 | 395 | if (magic[0] == 0x1f && magic[1] == 0x8b) 396 | return &gzfile_input_stream_ops; 397 | 398 | /* Default to reading the raw data */ 399 | 400 | return &fd_input_stream_ops; 401 | } 402 | 403 | /* Creates an input stream to read lines from the file specified by @path. 404 | * 405 | * Gzip files are auto-detected. */ 406 | struct input_stream * 407 | new_input_stream(const char *path) 408 | { 409 | struct input_stream *in = xmalloc(sizeof(*in)); 410 | 411 | assert(path != NULL); 412 | 413 | /* Select input_stream_operations and open stream */ 414 | in->ops = select_input_stream_ops(path); 415 | in->fp = (*in->ops->open)(path); 416 | in->name = xstrdup(path); 417 | 418 | /* Allocate internal buffer */ 419 | in->buf_begin = xmalloc(IOSTREAM_BUFSIZE); 420 | in->buf_end = in->buf_begin + IOSTREAM_BUFSIZE; 421 | in->buf_cur_begin = in->buf_begin; 422 | in->buf_cur_end = in->buf_begin; 423 | 424 | return in; 425 | } 426 | 427 | /* Returns the name of the file being read. */ 428 | const char * 429 | input_stream_get_name(struct input_stream *in) 430 | { 431 | return in->name; 432 | } 433 | 434 | /* Returns a pointer to the next instance in any of the @delims in @buf of 435 | * length @size. 436 | * 437 | * There must be at least one delimiter. */ 438 | static char * 439 | find_delim(char *buf, size_t size, const char *delims) 440 | { 441 | /* Fast case: just one delimiter. */ 442 | if (delims[1] == '\0') 443 | return memchr(buf, delims[0], size); 444 | 445 | /* Multiple delimiters. */ 446 | for (size_t i = 0; i < size; i++) { 447 | const char *p = delims; 448 | do { 449 | if (buf[i] == *p) 450 | return &buf[i]; 451 | } while (*++p); 452 | } 453 | return NULL; 454 | } 455 | 456 | /* Reads delimited data from an input stream. Semantics are like getdelim(), 457 | * but aborts on read error and also allows multiple delimiters. */ 458 | ssize_t 459 | input_stream_getdelims(struct input_stream *in, char **lineptr, size_t *n, 460 | const char *delims) 461 | { 462 | assert(*delims != '\0'); 463 | 464 | /* offset = number of bytes copied to *lineptr buffer, excluding 465 | * terminating null byte */ 466 | size_t offset = 0; 467 | 468 | for (;;) { 469 | size_t navail; 470 | char *delim_ptr; 471 | size_t copysize; 472 | 473 | navail = in->buf_cur_end - in->buf_cur_begin; 474 | 475 | if (navail == 0) { 476 | /* No more data in internal buffer; try to fill it */ 477 | 478 | in->buf_cur_begin = in->buf_begin; 479 | navail = (*in->ops->read)(in->fp, 480 | in->buf_cur_begin, 481 | in->buf_end - in->buf_cur_begin, 482 | in->name); 483 | in->buf_cur_end = in->buf_cur_begin + navail; 484 | 485 | if (navail == 0) /* At end-of-file */ 486 | break; 487 | } 488 | 489 | /* Find the first delimiter in the internal buffer. If found, 490 | * copy up to and including the delimiter, then return (break 491 | * loop). If not found, copy all the data and try to read more 492 | * (continue loop). */ 493 | delim_ptr = find_delim(in->buf_cur_begin, navail, delims); 494 | if (delim_ptr) 495 | copysize = delim_ptr - in->buf_cur_begin + 1; 496 | else 497 | copysize = navail; 498 | 499 | if (offset + copysize + 1 < offset) { 500 | /* Very unlikely: size would overflow. */ 501 | fatal_error("Line or field in \"%s\" is too long!", 502 | in->name); 503 | } 504 | 505 | if (*n < offset + copysize + 1) { 506 | *n = max(*n * 3 / 2, offset + copysize + 1); 507 | *n = max(*n, 128); 508 | *lineptr = xrealloc(*lineptr, *n); 509 | } 510 | 511 | memcpy(*lineptr + offset, in->buf_cur_begin, copysize); 512 | offset += copysize; 513 | in->buf_cur_begin += copysize; 514 | if (delim_ptr) 515 | break; 516 | } 517 | 518 | if (offset == 0) 519 | return -1; 520 | 521 | (*lineptr)[offset] = '\0'; 522 | return offset; 523 | } 524 | 525 | /* Reads a line from an input stream. Semantics are like getline(), but aborts 526 | * on read error. */ 527 | ssize_t 528 | input_stream_getline(struct input_stream *in, char **lineptr, size_t *n) 529 | { 530 | return input_stream_getdelims(in, lineptr, n, "\n"); 531 | } 532 | 533 | /* Closes and frees an input stream. */ 534 | void 535 | free_input_stream(struct input_stream *in) 536 | { 537 | if (in) { 538 | (*in->ops->close)(in->fp, in->name); 539 | xfree(in->name, strlen(in->name)); 540 | xfree(in->buf_begin, IOSTREAM_BUFSIZE); 541 | xfree(in, sizeof(*in)); 542 | } 543 | } 544 | 545 | /***************************** 546 | * Output stream functions * 547 | *****************************/ 548 | 549 | static void * 550 | output_fd_open(const char *path, const char *filter_prog, 551 | const char *filter_prog_args) 552 | { 553 | assert(filter_prog == NULL); 554 | return xopen(path, O_WRONLY | O_CREAT | O_TRUNC, 0644); 555 | } 556 | 557 | static void * 558 | output_filter_open(const char *path, const char *filter_prog, 559 | const char *filter_prog_args) 560 | { 561 | assert(filter_prog != NULL); 562 | 563 | if (filter_prog_args == NULL) 564 | filter_prog_args = ""; 565 | 566 | size_t len = strlen(filter_prog) + 32 + 567 | strlen(path) + strlen(filter_prog_args); 568 | char command[len + 1]; 569 | FILE *f; 570 | char *p = command; 571 | 572 | p += sprintf(p, "%s %s", filter_prog, filter_prog_args); 573 | if (!string_is_hyphen(path)) 574 | sprintf(p, " > '%s'", path); 575 | 576 | f = popen(command, "w"); 577 | if (!f) 578 | fatal_error_with_errno("Failed to launch the command \"%s\"", 579 | command); 580 | return f; 581 | } 582 | 583 | static void * 584 | output_gzfile_open(const char *path, const char *filter_prog, 585 | const char *filter_prog_args) 586 | { 587 | assert(filter_prog == NULL); 588 | return xgzopen(path, "wb"); 589 | } 590 | 591 | struct output_stream_operations { 592 | /* Open the specified file for writing, possibly filtering the data 593 | * through a filter program. Must return the open file handle, 594 | * descriptor, or pointer cast to a void *. */ 595 | void *(*open)(const char *path, 596 | const char *filter_prog, const char *filter_prog_args); 597 | 598 | /* Write a buffer of data to the stream. */ 599 | void (*write)(void *fp, const void *buf, size_t count, 600 | const char *name); 601 | 602 | /* Flush and close the stream. */ 603 | void (*close)(void *fp, const char *name); 604 | }; 605 | 606 | /* Operations to write raw data to a file descriptor. */ 607 | static const struct output_stream_operations fd_output_stream_ops = { 608 | .open = output_fd_open, 609 | .write = xwrite, 610 | .close = xclose, 611 | }; 612 | 613 | /* Operations to write data through a filter program to the file. */ 614 | static const struct output_stream_operations filter_output_stream_ops = { 615 | .open = output_filter_open, 616 | .write = xfwrite, 617 | .close = xpclose, 618 | }; 619 | 620 | /* Operations to write gzip-compressed data. */ 621 | static const struct output_stream_operations gzfile_output_stream_ops = { 622 | .open = output_gzfile_open, 623 | .write = xgzwrite, 624 | .close = xgzclose, 625 | }; 626 | 627 | struct output_stream { 628 | const struct output_stream_operations *ops; 629 | void *fp; 630 | char *name; 631 | char *buf_begin; 632 | char *buf_end; 633 | char *buf_cur_end; 634 | }; 635 | 636 | /* Select the appropriate output_stream_operations based on the requested 637 | * compression type and whether a filter program was specified. */ 638 | static const struct output_stream_operations * 639 | select_output_stream_ops(enum out_compression_type ctype, bool have_filter_prog) 640 | { 641 | switch (ctype) { 642 | case OUT_COMPRESSION_NONE: 643 | if (have_filter_prog) 644 | return &filter_output_stream_ops; 645 | else 646 | return &fd_output_stream_ops; 647 | case OUT_COMPRESSION_GZIP: 648 | assert(!have_filter_prog); 649 | return &gzfile_output_stream_ops; 650 | default: 651 | assert(0); 652 | return NULL; 653 | } 654 | } 655 | 656 | /* 657 | * Creates a new output stream. 658 | * 659 | * @ctype 660 | * The compression type to use. 661 | * @path 662 | * Path to the file to write, or "-" for standard output. 663 | * @filter_prog 664 | * If non-NULL, the name of a program through which to filter the output, 665 | * and @ctype must be OUT_COMPRESSION_NONE. The filter program must read 666 | * from standard input and write to standard output. 667 | * @filter_prog_args 668 | * Additional text (arguments) to place on the command line for 669 | * @filter_prog. 670 | * 671 | * Returns the new, opened output stream; aborts on error. 672 | */ 673 | struct output_stream * 674 | new_output_stream(enum out_compression_type ctype, 675 | const char *path, 676 | const char *filter_prog, 677 | const char *filter_prog_args) 678 | { 679 | struct output_stream *out = xmalloc(sizeof(*out)); 680 | 681 | assert(path != NULL); 682 | 683 | /* Select output_stream_operations and open stream. */ 684 | out->ops = select_output_stream_ops(ctype, filter_prog != NULL); 685 | out->fp = (*out->ops->open)(path, filter_prog, filter_prog_args); 686 | out->name = xstrdup(path); 687 | 688 | /* Allocate internal buffer. */ 689 | out->buf_begin = xmalloc(IOSTREAM_BUFSIZE); 690 | out->buf_end = out->buf_begin + IOSTREAM_BUFSIZE; 691 | out->buf_cur_end = out->buf_begin; 692 | 693 | return out; 694 | } 695 | 696 | /* Returns the name of the file to which the output stream is writing. */ 697 | const char * 698 | output_stream_get_name(struct output_stream *out) 699 | { 700 | return out->name; 701 | } 702 | 703 | static void 704 | flush_output_stream(struct output_stream *out) 705 | { 706 | (*out->ops->write)(out->fp, out->buf_begin, 707 | out->buf_cur_end - out->buf_begin, out->name); 708 | out->buf_cur_end = out->buf_begin; 709 | } 710 | 711 | /* Writes a buffer of data to an output stream. */ 712 | void 713 | output_stream_write(struct output_stream *out, const void *_buf, size_t count) 714 | { 715 | const char *ptr = _buf; 716 | 717 | while (count) { 718 | if (out->buf_cur_end == out->buf_end) { 719 | /* Output buffer full; flush it. */ 720 | flush_output_stream(out); 721 | } 722 | 723 | /* Buffer as much data as possible. */ 724 | 725 | size_t tocopy = min(count, out->buf_end - out->buf_cur_end); 726 | 727 | memcpy(out->buf_cur_end, ptr, tocopy); 728 | out->buf_cur_end += tocopy; 729 | ptr += tocopy; 730 | count -= tocopy; 731 | } 732 | } 733 | 734 | /* Writes a null-terminated string to an output stream. */ 735 | void 736 | output_stream_fputs(struct output_stream *out, const char *s) 737 | { 738 | output_stream_write(out, s, strlen(s)); 739 | } 740 | 741 | /* Writes a byte to an output stream. */ 742 | void 743 | output_stream_fputc(struct output_stream *out, char c) 744 | { 745 | if (out->buf_cur_end == out->buf_end) 746 | flush_output_stream(out); 747 | *out->buf_cur_end++ = c; 748 | } 749 | 750 | /* Flushes, closes, and frees an output stream. */ 751 | void 752 | free_output_stream(struct output_stream *out) 753 | { 754 | if (out) { 755 | if (out->buf_cur_end > out->buf_begin) 756 | flush_output_stream(out); 757 | (*out->ops->close)(out->fp, out->name); 758 | xfree(out->name, strlen(out->name)); 759 | xfree(out->buf_begin, IOSTREAM_BUFSIZE); 760 | xfree(out, sizeof(*out)); 761 | } 762 | } 763 | -------------------------------------------------------------------------------- /iostream.h: -------------------------------------------------------------------------------- 1 | #ifndef _FLASH_IOSTREAM_H_ 2 | #define _FLASH_IOSTREAM_H_ 3 | 4 | #include 5 | #include 6 | #include 7 | 8 | /* Input stream functions */ 9 | 10 | struct input_stream; 11 | 12 | extern struct input_stream * 13 | new_input_stream(const char *filename); 14 | 15 | extern const char * 16 | input_stream_get_name(struct input_stream *in); 17 | 18 | extern ssize_t 19 | input_stream_getdelims(struct input_stream *in, char **lineptr, 20 | size_t *n, const char *delims); 21 | extern ssize_t 22 | input_stream_getline(struct input_stream *in, char **lineptr, size_t *n); 23 | 24 | extern void 25 | free_input_stream(struct input_stream *in); 26 | 27 | /* Output stream functions */ 28 | 29 | struct output_stream; 30 | 31 | enum out_compression_type { 32 | OUT_COMPRESSION_NONE, 33 | OUT_COMPRESSION_GZIP, 34 | }; 35 | 36 | extern struct output_stream * 37 | new_output_stream(enum out_compression_type ctype, 38 | const char *path, 39 | const char *filter_prog, 40 | const char *filter_prog_args); 41 | extern const char * 42 | output_stream_get_name(struct output_stream *out); 43 | 44 | extern void 45 | output_stream_write(struct output_stream *out, 46 | const void *buf, size_t count); 47 | 48 | extern void 49 | output_stream_fputs(struct output_stream *out, const char *s); 50 | 51 | extern void 52 | output_stream_fputc(struct output_stream *out, char c); 53 | 54 | extern void 55 | free_output_stream(struct output_stream *out); 56 | 57 | /* fopen() and fclose() wrappers */ 58 | 59 | extern void * 60 | xfopen(const char *filename, const char *mode); 61 | 62 | extern void 63 | xfclose(FILE *fp, const char *name); 64 | 65 | #endif /* _FLASH_IOSTREAM_H_ */ 66 | -------------------------------------------------------------------------------- /read.h: -------------------------------------------------------------------------------- 1 | #ifndef _FLASH_READ_H_ 2 | #define _FLASH_READ_H_ 3 | 4 | #include 5 | 6 | /* In-memory representation of a DNA sequence read. */ 7 | struct read { 8 | /* The "tag" that identifies the read. */ 9 | char *tag; 10 | 11 | /* The sequence of the read in ASCII characters (A, C, G, T, N). */ 12 | char *seq; 13 | 14 | /* The quality scores of the read, scaled to start at 0. */ 15 | char *qual; 16 | 17 | /* Length of the tag string. */ 18 | int tag_len; 19 | 20 | /* Length of the sequence string (number of bases in the read). */ 21 | int seq_len; 22 | 23 | /* Length of the quality string (will be equal to seq_len). */ 24 | int qual_len; 25 | 26 | /* Allocated sizes of the seq, tag, and qual buffers, respectively. */ 27 | size_t seq_bufsz; 28 | size_t tag_bufsz; 29 | size_t qual_bufsz; 30 | }; 31 | 32 | struct input_stream; 33 | #include 34 | 35 | extern void 36 | reverse_complement(struct read *r); 37 | 38 | extern void 39 | clean_read(struct read *r, int phred_offset, struct input_stream *in, 40 | uint64_t line_no); 41 | 42 | extern void 43 | clean_read_for_write(struct read *r, int phred_offset); 44 | 45 | extern void 46 | copy_tag(struct read *to, const struct read *from); 47 | 48 | extern void 49 | get_combined_tag(const struct read *read_1, 50 | const struct read *read_2, 51 | struct read *combined_read); 52 | 53 | #endif /* _FLASH_READ_H_ */ 54 | -------------------------------------------------------------------------------- /read_io.c: -------------------------------------------------------------------------------- 1 | /* 2 | * read_io.c: Code for input and output of reads, e.g. from/to FASTQ files. 3 | */ 4 | 5 | /* 6 | * Copyright (C) 2012 Tanja Magoc 7 | * Copyright (C) 2012, 2013, 2014 Eric Biggers 8 | * 9 | * This file is part of FLASH, a fast tool to merge overlapping paired-end 10 | * reads. 11 | * 12 | * FLASH is free software; you can redistribute it and/or modify it under the 13 | * terms of the GNU General Public License as published by the Free 14 | * Software Foundation; either version 3 of the License, or (at your option) 15 | * any later version. 16 | * 17 | * FLASH is distributed in the hope that it will be useful, but WITHOUT ANY 18 | * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR 19 | * A PARTICULAR PURPOSE. See the GNU General Public License for more 20 | * details. 21 | * 22 | * You should have received a copy of the GNU General Public License 23 | * along with FLASH; if not, see http://www.gnu.org/licenses/. 24 | */ 25 | 26 | #include "iostream.h" 27 | #include "read.h" 28 | #include "read_io.h" 29 | #include "util.h" 30 | 31 | #include 32 | #include 33 | 34 | /****************************************** 35 | * Read input * 36 | ******************************************/ 37 | 38 | static bool 39 | load_fastq_read(struct input_stream *in, struct read *r, 40 | uint64_t *line_no_p) 41 | { 42 | ssize_t ret; 43 | 44 | /* tag 45 | * sequence 46 | * + 47 | * quality */ 48 | 49 | ret = input_stream_getline(in, &r->tag, &r->tag_bufsz); 50 | if (ret <= 0) 51 | return false; 52 | if (ret > INT_MAX) 53 | goto too_long; 54 | ++*line_no_p; 55 | r->tag_len = ret; 56 | 57 | ret = input_stream_getline(in, &r->seq, &r->seq_bufsz); 58 | if (ret <= 0) 59 | goto unexpected_eof; 60 | if (ret > INT_MAX) 61 | goto too_long; 62 | ++*line_no_p; 63 | r->seq_len = ret; 64 | 65 | ret = input_stream_getline(in, &r->qual, &r->qual_bufsz); 66 | if (ret <= 0) 67 | goto unexpected_eof; 68 | if (r->qual[0] != '+') 69 | goto expected_plus; 70 | ++*line_no_p; 71 | 72 | ret = input_stream_getline(in, &r->qual, &r->qual_bufsz); 73 | if (ret <= 0) 74 | goto unexpected_eof; 75 | if (ret > INT_MAX) 76 | goto too_long; 77 | ++*line_no_p; 78 | r->qual_len = ret; 79 | 80 | return true; 81 | 82 | 83 | unexpected_eof: 84 | fatal_error("Unexpected EOF reading \"%s\" (line %"PRIu64")", 85 | input_stream_get_name(in), *line_no_p); 86 | 87 | expected_plus: 88 | fatal_error("Expected '+' character in FASTQ separator in \"%s\" " 89 | "(line %"PRIu64")", input_stream_get_name(in), 90 | *line_no_p); 91 | 92 | too_long: 93 | fatal_error("Line %"PRIu64" in \"%s\" is too long", 94 | *line_no_p, input_stream_get_name(in)); 95 | } 96 | 97 | static bool 98 | load_tab_delimited_read(struct input_stream *in, struct read *r, 99 | uint64_t *line_no_p) 100 | { 101 | ssize_t ret; 102 | const char *delims = "\t\n"; 103 | 104 | /* tag sequence quality */ 105 | 106 | ret = input_stream_getdelims(in, &r->tag, &r->tag_bufsz, delims); 107 | if (ret <= 0) 108 | return false; 109 | if (ret > INT_MAX) 110 | goto too_long; 111 | if (r->tag[ret - 1] != '\t') 112 | goto expected_tab; 113 | r->tag_len = ret; 114 | 115 | ret = input_stream_getdelims(in, &r->seq, &r->seq_bufsz, delims); 116 | if (ret <= 0) 117 | goto unexpected_eof; 118 | if (ret > INT_MAX) 119 | goto too_long; 120 | if (r->seq[ret - 1] != '\t') 121 | goto expected_tab; 122 | r->seq_len = ret; 123 | 124 | ret = input_stream_getdelims(in, &r->qual, &r->qual_bufsz, delims); 125 | if (ret <= 0) 126 | goto unexpected_eof; 127 | if (ret > INT_MAX) 128 | goto too_long; 129 | if (r->qual[ret - 1] == '\t') 130 | goto expected_newline; 131 | r->qual_len = ret; 132 | ++*line_no_p; 133 | 134 | return true; 135 | 136 | too_long: 137 | fatal_error("Field in line %"PRIu64" of \"%s\" is too long", 138 | *line_no_p, input_stream_get_name(in)); 139 | 140 | unexpected_eof: 141 | fatal_error("Unexpected EOF reading \"%s\" (line %"PRIu64")", 142 | input_stream_get_name(in), *line_no_p); 143 | 144 | expected_tab: 145 | fatal_error("Invalid data in \"%s\": " 146 | "expected tab character (line %"PRIu64")", 147 | input_stream_get_name(in), *line_no_p); 148 | 149 | expected_newline: 150 | fatal_error("Invalid data in \"%s\": " 151 | "expected newline character (line %"PRIu64")", 152 | input_stream_get_name(in), *line_no_p); 153 | } 154 | 155 | static bool 156 | load_tab_delimited_pair(struct input_stream *in, 157 | struct read *r1, struct read *r2, uint64_t *line_no_p) 158 | { 159 | ssize_t ret; 160 | const char *delims = "\t\n"; 161 | 162 | /* tag seq_1 qual_1 seq_2 qual_2 */ 163 | 164 | ret = input_stream_getdelims(in, &r1->tag, &r1->tag_bufsz, delims); 165 | if (ret <= 0) 166 | return false; 167 | if (ret > INT_MAX) 168 | goto too_long; 169 | if (r1->tag[ret - 1] != '\t') 170 | goto expected_tab; 171 | r1->tag_len = ret; 172 | 173 | ret = input_stream_getdelims(in, &r1->seq, &r1->seq_bufsz, delims); 174 | if (ret <= 0) 175 | goto unexpected_eof; 176 | if (ret > INT_MAX) 177 | goto too_long; 178 | if (r1->seq[ret - 1] != '\t') 179 | goto expected_tab; 180 | r1->seq_len = ret; 181 | 182 | ret = input_stream_getdelims(in, &r1->qual, &r1->qual_bufsz, delims); 183 | if (ret <= 0) 184 | goto unexpected_eof; 185 | if (ret > INT_MAX) 186 | goto too_long; 187 | r1->qual_len = ret; 188 | 189 | if (r1->qual[ret - 1] == '\n') { 190 | /* Actually just a single read; use a void second read. */ 191 | r2->tag_len = 0; 192 | r2->seq_len = 0; 193 | r2->qual_len = 0; 194 | ++*line_no_p; 195 | return true; 196 | } 197 | 198 | /* Set tag of read 2 to be the same as the tag of read 1 */ 199 | copy_tag(r2, r1); 200 | 201 | ret = input_stream_getdelims(in, &r2->seq, &r2->seq_bufsz, delims); 202 | if (ret <= 0) 203 | goto unexpected_eof; 204 | if (ret > INT_MAX) 205 | goto too_long; 206 | if (r2->seq[ret - 1] != '\t') 207 | goto expected_tab; 208 | r2->seq_len = ret; 209 | 210 | ret = input_stream_getdelims(in, &r2->qual, &r2->qual_bufsz, delims); 211 | if (ret <= 0) 212 | goto unexpected_eof; 213 | if (ret > INT_MAX) 214 | goto too_long; 215 | if (r2->qual[ret - 1] == '\t') 216 | goto expected_newline; 217 | r2->qual_len = ret; 218 | ++*line_no_p; 219 | 220 | return true; 221 | 222 | too_long: 223 | fatal_error("Field in line %"PRIu64" of \"%s\" is too long", 224 | *line_no_p, input_stream_get_name(in)); 225 | 226 | unexpected_eof: 227 | fatal_error("Unexpected EOF reading \"%s\" (line %"PRIu64")", 228 | input_stream_get_name(in), *line_no_p); 229 | 230 | expected_tab: 231 | fatal_error("Invalid data in \"%s\": " 232 | "expected tab character (line %"PRIu64")", 233 | input_stream_get_name(in), *line_no_p); 234 | 235 | expected_newline: 236 | fatal_error("Invalid data in \"%s\": " 237 | "expected newline character (line %"PRIu64")", 238 | input_stream_get_name(in), *line_no_p); 239 | } 240 | 241 | /* 242 | * Loads the next read from the stream @in. 243 | * 244 | * @iparams specifies the format being used; e.g. FASTQ with a certain phred 245 | * offset. 246 | * 247 | * In each resulting read, whitespace is stripped from the end of the sequence, 248 | * tag, and quality scores. The sequence is translated into only the characters 249 | * A, C, G, T, and N, and the quality values are re-scaled to start at 0. 250 | * 251 | * Returns true on success, false on end-of-file. Aborts on read error or if 252 | * the data is invalid. 253 | */ 254 | bool 255 | load_read(struct input_stream *in, const struct read_format_params *iparams, 256 | struct read *r, uint64_t *line_no_p) 257 | { 258 | bool ret; 259 | 260 | switch (iparams->fmt) { 261 | case READ_FORMAT_FASTQ: 262 | ret = load_fastq_read(in, r, line_no_p); 263 | break; 264 | case READ_FORMAT_TAB_DELIMITED: 265 | ret = load_tab_delimited_read(in, r, line_no_p); 266 | break; 267 | default: 268 | assert(0); 269 | ret = false; 270 | } 271 | 272 | if (ret) 273 | clean_read(r, iparams->phred_offset, in, *line_no_p); 274 | return ret; 275 | } 276 | 277 | /* 278 | * Similar to load_read(), but loads a pair of reads from the file instead. 279 | * This is only relevant (and must only be called) for file formats that store 280 | * both reads of the pair in the same sequential file. 281 | * 282 | * As a special case, this function may only fill in @r1, and set @r2->seq_len 283 | * to 0, to indicate that the next record in the file was actually an unpaired 284 | * read, not a read pair. This is possible in formats for which 285 | * read_format_supports_mixed_reads() returns true (e.g. tab-delimited). 286 | */ 287 | bool 288 | load_read_pair(struct input_stream *in, const struct read_format_params *iparams, 289 | struct read *r1, struct read *r2, 290 | uint64_t *line_no_p) 291 | { 292 | bool ret; 293 | 294 | switch (iparams->fmt) { 295 | case READ_FORMAT_FASTQ: 296 | ret = load_fastq_read(in, r1, line_no_p); 297 | if (ret && !load_fastq_read(in, r2, line_no_p)) 298 | fatal_error("Interleaved FASTQ file \"%s\" has an " 299 | "odd number of reads", 300 | input_stream_get_name(in)); 301 | break; 302 | case READ_FORMAT_TAB_DELIMITED: 303 | ret = load_tab_delimited_pair(in, r1, r2, line_no_p); 304 | break; 305 | default: 306 | assert(0); 307 | ret = false; 308 | } 309 | if (ret) { 310 | clean_read(r1, iparams->phred_offset, in, *line_no_p); 311 | clean_read(r2, iparams->phred_offset, in, *line_no_p); 312 | } 313 | return ret; 314 | } 315 | 316 | /****************************************** 317 | * Read output * 318 | ******************************************/ 319 | 320 | static void 321 | write_fastq_read(struct output_stream *out, const struct read *r) 322 | { 323 | /* Add '@' to tag if missing */ 324 | if (r->tag_len == 0 || r->tag[0] != '@') 325 | output_stream_fputc(out, '@'); 326 | 327 | output_stream_write(out, r->tag, r->tag_len); 328 | output_stream_fputc(out, '\n'); 329 | output_stream_write(out, r->seq, r->seq_len); 330 | output_stream_fputc(out, '\n'); 331 | output_stream_fputc(out, '+'); 332 | output_stream_fputc(out, '\n'); 333 | output_stream_write(out, r->qual, r->qual_len); 334 | output_stream_fputc(out, '\n'); 335 | } 336 | 337 | static void 338 | write_tab_delimited_read(struct output_stream *out, const struct read *r) 339 | { 340 | const char *tag = r->tag; 341 | int tag_len = r->tag_len; 342 | 343 | /* Strip '@' from tag */ 344 | if (tag_len > 0 && tag[0] == '@') 345 | tag++, tag_len--; 346 | 347 | output_stream_write(out, tag, tag_len); 348 | output_stream_fputc(out, '\t'); 349 | output_stream_write(out, r->seq, r->seq_len); 350 | output_stream_fputc(out, '\t'); 351 | output_stream_write(out, r->qual, r->qual_len); 352 | output_stream_fputc(out, '\n'); 353 | } 354 | 355 | static void 356 | write_tab_delimited_pair(struct output_stream *out, 357 | const struct read *r1, const struct read *r2) 358 | { 359 | const char *tag = r1->tag; 360 | int tag_len = r1->tag_len; 361 | 362 | /* Strip '@' and /1 or /2 from tag */ 363 | if (tag_len > 0 && tag[0] == '@') 364 | tag++, tag_len--; 365 | if (tag_len >= 2 && tag[tag_len - 2] == '/' && 366 | (tag[tag_len - 1] == '1' || tag[tag_len - 1] == '2')) 367 | tag_len -= 2; 368 | 369 | output_stream_write(out, tag, tag_len); 370 | output_stream_fputc(out, '\t'); 371 | 372 | output_stream_write(out, r1->seq, r1->seq_len); 373 | output_stream_fputc(out, '\t'); 374 | output_stream_write(out, r1->qual, r1->qual_len); 375 | output_stream_fputc(out, '\t'); 376 | output_stream_write(out, r2->seq, r2->seq_len); 377 | output_stream_fputc(out, '\t'); 378 | output_stream_write(out, r2->qual, r2->qual_len); 379 | output_stream_fputc(out, '\n'); 380 | } 381 | 382 | /* Writes a read to the specified output stream in the format specified by 383 | * @oparams. 384 | * 385 | * Modifies the qual string of @r! */ 386 | void 387 | write_read(struct output_stream *out, const struct read_format_params *oparams, 388 | struct read *r) 389 | { 390 | clean_read_for_write(r, oparams->phred_offset); 391 | 392 | switch (oparams->fmt) { 393 | case READ_FORMAT_FASTQ: 394 | write_fastq_read(out, r); 395 | break; 396 | case READ_FORMAT_TAB_DELIMITED: 397 | write_tab_delimited_read(out, r); 398 | break; 399 | default: 400 | assert(0); 401 | } 402 | } 403 | 404 | /* Writes a read pair to the specified output stream in the format specified by 405 | * @oparams. 406 | * 407 | * Modifies the qual string of @r1 and @r2! */ 408 | void 409 | write_read_pair(struct output_stream *out, 410 | const struct read_format_params *oparams, 411 | struct read *r1, struct read *r2) 412 | { 413 | clean_read_for_write(r1, oparams->phred_offset); 414 | clean_read_for_write(r2, oparams->phred_offset); 415 | 416 | switch (oparams->fmt) { 417 | case READ_FORMAT_FASTQ: 418 | /* Interleaved FASTQ format */ 419 | write_fastq_read(out, r1); 420 | write_fastq_read(out, r2); 421 | break; 422 | case READ_FORMAT_TAB_DELIMITED: 423 | /* Tab-delimited format, with two reads in a pair on one line */ 424 | write_tab_delimited_pair(out, r1, r2); 425 | break; 426 | default: 427 | assert(0); 428 | } 429 | } 430 | -------------------------------------------------------------------------------- /read_io.h: -------------------------------------------------------------------------------- 1 | #ifndef _FLASH_READ_IO_H_ 2 | #define _FLASH_READ_IO_H_ 3 | 4 | #include 5 | #include 6 | 7 | struct output_stream; 8 | struct input_stream; 9 | struct read; 10 | 11 | struct read_format_params { 12 | enum { 13 | READ_FORMAT_FASTQ, 14 | READ_FORMAT_TAB_DELIMITED, 15 | } fmt; 16 | int phred_offset; 17 | }; 18 | 19 | /* Returns true iff the specified read format supports both unpaired and paired 20 | * reads in the same file. */ 21 | static inline bool 22 | read_format_supports_mixed_reads(const struct read_format_params *params) 23 | { 24 | return params->fmt == READ_FORMAT_TAB_DELIMITED; 25 | } 26 | 27 | extern void 28 | write_read(struct output_stream *out, 29 | const struct read_format_params *oparams, 30 | struct read *read); 31 | 32 | extern void 33 | write_read_pair(struct output_stream *out, 34 | const struct read_format_params *oparams, 35 | struct read *read_1, struct read *read_2); 36 | 37 | extern bool 38 | load_read(struct input_stream *in, 39 | const struct read_format_params *iparams, 40 | struct read *read, uint64_t *line_no_p); 41 | 42 | extern bool 43 | load_read_pair(struct input_stream *in, 44 | const struct read_format_params *iparams, 45 | struct read *read_1, struct read *read_2, 46 | uint64_t *line_no_p); 47 | 48 | #endif /* _FLASH_READ_IO_H_ */ 49 | -------------------------------------------------------------------------------- /read_queue.c: -------------------------------------------------------------------------------- 1 | /* 2 | * read_queue.c: Code to set up reader/writer threads and shared queues to pass 3 | * reads between threads in memory. 4 | */ 5 | 6 | /* 7 | * Copyright (C) 2012 Tanja Magoc 8 | * Copyright (C) 2012, 2013, 2014 Eric Biggers 9 | * 10 | * This file is part of FLASH, a fast tool to merge overlapping paired-end 11 | * reads. 12 | * 13 | * FLASH is free software; you can redistribute it and/or modify it under the 14 | * terms of the GNU General Public License as published by the Free 15 | * Software Foundation; either version 3 of the License, or (at your option) 16 | * any later version. 17 | * 18 | * FLASH is distributed in the hope that it will be useful, but WITHOUT ANY 19 | * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR 20 | * A PARTICULAR PURPOSE. See the GNU General Public License for more 21 | * details. 22 | * 23 | * You should have received a copy of the GNU General Public License 24 | * along with FLASH; if not, see http://www.gnu.org/licenses/. 25 | */ 26 | 27 | #include "iostream.h" 28 | #include "read.h" 29 | #include "read_io.h" 30 | #include "read_queue.h" 31 | #include "util.h" 32 | 33 | #include 34 | #include 35 | #include 36 | #include 37 | #include 38 | #include 39 | 40 | static struct read * 41 | new_read(void) 42 | { 43 | return xzalloc(sizeof(struct read)); 44 | } 45 | 46 | static void 47 | free_read(struct read *r) 48 | { 49 | if (r) { 50 | xfree(r->tag, r->tag_bufsz); 51 | xfree(r->seq, r->seq_bufsz); 52 | xfree(r->qual, r->qual_bufsz); 53 | xfree(r, sizeof(*r)); 54 | } 55 | } 56 | 57 | static struct read_set * 58 | new_read_set(size_t num_reads, bool full) 59 | { 60 | struct read_set *s = xmalloc(sizeof(*s) + num_reads * sizeof(s->reads[0])); 61 | if (full) { 62 | for (size_t i = 0; i < num_reads; i++) 63 | s->reads[i] = new_read(); 64 | } else { 65 | for (size_t i = 0; i < num_reads; i++) 66 | s->reads[i] = NULL; 67 | } 68 | s->filled = 0; 69 | s->num_reads = num_reads; 70 | return s; 71 | } 72 | 73 | void 74 | free_read_set(struct read_set *s) 75 | { 76 | if (s) { 77 | for (size_t i = 0; i < s->num_reads; i++) 78 | free_read(s->reads[i]); 79 | xfree(s, sizeof(*s)); 80 | } 81 | } 82 | 83 | static void 84 | init_mutex(pthread_mutex_t *mutex) 85 | { 86 | if (pthread_mutex_init(mutex, NULL)) 87 | fatal_error_with_errno("Failed to initialize mutex"); 88 | } 89 | 90 | static void 91 | init_cond(pthread_cond_t *cond) 92 | { 93 | if (pthread_cond_init(cond, NULL)) 94 | fatal_error_with_errno("Failed to initialize condition variable"); 95 | } 96 | 97 | /* 98 | * Producer-consumer queue; it holds pointers to `struct read_sets', which can 99 | * be added or removed from the queue in a thread-safe manner using 100 | * read_queue_put() and read_queue_get(), respectively. 101 | */ 102 | struct read_queue { 103 | size_t size; 104 | size_t front; 105 | size_t filled; 106 | bool terminated; 107 | struct read_set **read_sets; 108 | pthread_mutex_t lock; 109 | pthread_cond_t read_set_avail_cond; 110 | pthread_cond_t space_avail_cond; 111 | }; 112 | 113 | static struct read_queue * 114 | new_read_queue(size_t size, size_t reads_per_set, bool full) 115 | { 116 | struct read_queue *q = xmalloc(sizeof(*q)); 117 | 118 | q->read_sets = xmalloc(size * sizeof(q->read_sets[0])); 119 | q->size = size; 120 | q->front = 0; 121 | if (full) { 122 | for (size_t i = 0; i < size; i++) 123 | q->read_sets[i] = new_read_set(reads_per_set, true); 124 | q->filled = size; 125 | } else { 126 | for (size_t i = 0; i < size; i++) 127 | q->read_sets[i] = NULL; 128 | q->filled = 0; 129 | } 130 | q->terminated = false; 131 | init_mutex(&q->lock); 132 | init_cond(&q->read_set_avail_cond); 133 | init_cond(&q->space_avail_cond); 134 | return q; 135 | } 136 | 137 | static void 138 | free_read_queue(struct read_queue *q) 139 | { 140 | if (q) { 141 | size_t filled = q->filled; 142 | size_t i = q->front; 143 | 144 | while (filled--) { 145 | free_read_set(q->read_sets[i]); 146 | i = (i + 1) % q->size; 147 | } 148 | 149 | xfree(q->read_sets, q->size * sizeof(q->read_sets[0])); 150 | 151 | pthread_mutex_destroy(&q->lock); 152 | pthread_cond_destroy(&q->read_set_avail_cond); 153 | pthread_cond_destroy(&q->space_avail_cond); 154 | 155 | xfree(q, sizeof(*q)); 156 | } 157 | } 158 | 159 | /* Retrieves the next available read set from the queue, blocking until one is 160 | * available. Or, returns NULL if the queue has terminated and no more read 161 | * sets are available. */ 162 | static struct read_set * 163 | read_queue_get(struct read_queue *q) 164 | { 165 | struct read_set *s; 166 | 167 | pthread_mutex_lock(&q->lock); 168 | while (q->filled == 0 && !q->terminated) 169 | pthread_cond_wait(&q->read_set_avail_cond, &q->lock); 170 | 171 | if (q->filled != 0) { 172 | s = q->read_sets[q->front]; 173 | q->front = (q->front + 1) % q->size; 174 | q->filled--; 175 | pthread_cond_signal(&q->space_avail_cond); 176 | } else 177 | s = NULL; 178 | 179 | pthread_mutex_unlock(&q->lock); 180 | return s; 181 | } 182 | 183 | /* Put a read set into the queue, blocking until there is an empty space 184 | * available. */ 185 | static void 186 | read_queue_put(struct read_queue *q, struct read_set *s) 187 | { 188 | pthread_mutex_lock(&q->lock); 189 | while (q->filled == q->size) 190 | pthread_cond_wait(&q->space_avail_cond, &q->lock); 191 | 192 | q->read_sets[(q->front + q->filled) % q->size] = s; 193 | q->filled++; 194 | 195 | pthread_cond_signal(&q->read_set_avail_cond); 196 | pthread_mutex_unlock(&q->lock); 197 | } 198 | 199 | /* "Terminate" the specified queue. This will cause read_queue_get() to return 200 | * NULL once the queue is empty. */ 201 | static void 202 | read_queue_terminate(struct read_queue *q) 203 | { 204 | pthread_mutex_lock(&q->lock); 205 | q->terminated = true; 206 | pthread_cond_broadcast(&q->read_set_avail_cond); 207 | pthread_mutex_unlock(&q->lock); 208 | } 209 | 210 | struct reader_params { 211 | struct input_stream *in; 212 | const struct read_format_params *iparams; 213 | bool verbose; 214 | struct read_queue *avail_read_q; 215 | struct read_queue *unprocessed_read_1_q; 216 | struct read_queue *unprocessed_read_2_q; 217 | struct read_queue *unpaired_read_q; 218 | }; 219 | 220 | struct writer_params { 221 | struct output_stream *out; 222 | const struct read_format_params *oparams; 223 | struct read_queue *to_write_queue_1; 224 | struct read_queue *to_write_queue_2; 225 | struct read_queue *avail_queue; 226 | }; 227 | 228 | static void 229 | processed(uint64_t pair_no) 230 | { 231 | info("Processed %"PRIu64" read pairs", pair_no); 232 | } 233 | 234 | static void * 235 | reader1_proc(void *_params) 236 | { 237 | struct reader_params *params = _params; 238 | uint64_t pair_no = 0; 239 | uint64_t line_no = 1; 240 | struct read_set *s; 241 | 242 | for (;;) { 243 | 244 | s = read_queue_get(params->avail_read_q); 245 | 246 | for (s->filled = 0; 247 | s->filled < s->num_reads; 248 | s->filled++) 249 | { 250 | if (!load_read(params->in, params->iparams, 251 | s->reads[s->filled], &line_no)) 252 | goto eof_reached; 253 | 254 | if (params->verbose && ++pair_no % 25000 == 0) 255 | processed(pair_no); 256 | } 257 | 258 | /* Note: although we're placing the set in 259 | * 'unprocessed_read_1_q', the set may in fact be read 2, not 260 | * read 1. This procedure works the same way in both cases. */ 261 | 262 | read_queue_put(params->unprocessed_read_1_q, s); 263 | } 264 | 265 | eof_reached: 266 | if (params->verbose && pair_no % 25000 != 0) 267 | processed(pair_no); 268 | 269 | if (s->filled) 270 | read_queue_put(params->unprocessed_read_1_q, s); 271 | else 272 | free_read_set(s); 273 | 274 | read_queue_terminate(params->unprocessed_read_1_q); 275 | 276 | free_input_stream(params->in); 277 | xfree(params, sizeof(*params)); 278 | return NULL; 279 | } 280 | 281 | static void * 282 | reader2_proc(void *_params) 283 | { 284 | struct reader_params *params = _params; 285 | struct read_set *s_read1, *s_read2, *s_unpaired = NULL; 286 | uint64_t pair_no = 0; 287 | uint64_t line_no = 1; 288 | 289 | s_read1 = read_queue_get(params->avail_read_q); 290 | s_read1->filled = 0; 291 | s_read2 = read_queue_get(params->avail_read_q); 292 | s_read2->filled = 0; 293 | if (params->unpaired_read_q) { 294 | s_unpaired = read_queue_get(params->avail_read_q); 295 | s_unpaired->filled = 0; 296 | } 297 | 298 | while (load_read_pair(params->in, params->iparams, 299 | s_read1->reads[s_read1->filled], 300 | s_read2->reads[s_read1->filled], 301 | &line_no)) 302 | { 303 | if (s_read2->reads[s_read1->filled]->seq_len) { 304 | /* Read pair. */ 305 | ++s_read1->filled; 306 | ++s_read2->filled; 307 | if (s_read1->filled == s_read1->num_reads) { 308 | read_queue_put(params->unprocessed_read_1_q, s_read1); 309 | read_queue_put(params->unprocessed_read_2_q, s_read2); 310 | s_read1 = read_queue_get(params->avail_read_q); 311 | s_read1->filled = 0; 312 | s_read2 = read_queue_get(params->avail_read_q); 313 | s_read2->filled = 0; 314 | } 315 | if (params->verbose && ++pair_no % 25000 == 0) 316 | processed(pair_no); 317 | } else if (params->unpaired_read_q) { 318 | /* Actually an unpaired read. */ 319 | struct read *r = s_read1->reads[s_read1->filled]; 320 | s_read1->reads[s_read1->filled] = 321 | s_unpaired->reads[s_unpaired->filled]; 322 | s_unpaired->reads[s_unpaired->filled] = r; 323 | ++s_unpaired->filled; 324 | if (s_unpaired->filled == s_unpaired->num_reads) { 325 | s_unpaired->type = READS_UNPAIRED; 326 | read_queue_put(params->unpaired_read_q, s_unpaired); 327 | s_unpaired = read_queue_get(params->avail_read_q); 328 | s_unpaired->filled = 0; 329 | } 330 | } 331 | } 332 | 333 | if (params->verbose && pair_no % 25000 != 0) 334 | processed(pair_no); 335 | 336 | if (s_read1->filled) 337 | read_queue_put(params->unprocessed_read_1_q, s_read1); 338 | else 339 | free_read_set(s_read1); 340 | 341 | if (s_read2->filled) 342 | read_queue_put(params->unprocessed_read_2_q, s_read2); 343 | else 344 | free_read_set(s_read2); 345 | 346 | if (s_unpaired) { 347 | if (s_unpaired->filled) { 348 | s_unpaired->type = READS_UNPAIRED; 349 | read_queue_put(params->unpaired_read_q, s_unpaired); 350 | } else { 351 | free_read_set(s_unpaired); 352 | } 353 | } 354 | 355 | read_queue_terminate(params->unprocessed_read_1_q); 356 | read_queue_terminate(params->unprocessed_read_2_q); 357 | 358 | free_input_stream(params->in); 359 | xfree(params, sizeof(*params)); 360 | return NULL; 361 | } 362 | 363 | static void * 364 | writer_proc(void *_params) 365 | { 366 | struct writer_params *params = _params; 367 | struct read_set *s1, *s2; 368 | 369 | for (;;) { 370 | s1 = read_queue_get(params->to_write_queue_1); 371 | if (!s1) 372 | break; 373 | 374 | if (params->to_write_queue_2 && s1->type == READS_UNCOMBINED) { 375 | /* Get other read in uncombined pair */ 376 | s2 = read_queue_get(params->to_write_queue_2); 377 | assert(s2); 378 | assert(s1->filled == s2->filled); 379 | } else { 380 | s2 = NULL; 381 | } 382 | 383 | for (size_t i = 0; i < s1->filled; i++) { 384 | if (s2) 385 | write_read_pair(params->out, params->oparams, 386 | s1->reads[i], s2->reads[i]); 387 | else 388 | write_read(params->out, params->oparams, 389 | s1->reads[i]); 390 | } 391 | read_queue_put(params->avail_queue, s1); 392 | if (s2) 393 | read_queue_put(params->avail_queue, s2); 394 | } 395 | free_output_stream(params->out); 396 | xfree(params, sizeof(*params)); 397 | return NULL; 398 | } 399 | 400 | static pthread_t 401 | start_reader2(struct input_stream *in, 402 | const struct read_format_params *iparams, 403 | bool verbose, 404 | struct read_queue *avail_read_q, 405 | struct read_queue *unprocessed_read_1_q, 406 | struct read_queue *unprocessed_read_2_q, 407 | struct read_queue *unpaired_read_q) 408 | { 409 | struct reader_params *params = xmalloc(sizeof(*params)); 410 | 411 | params->in = in; 412 | params->iparams = iparams; 413 | params->verbose = verbose; 414 | params->avail_read_q = avail_read_q; 415 | params->unprocessed_read_1_q = unprocessed_read_1_q; 416 | params->unprocessed_read_2_q = unprocessed_read_2_q; 417 | params->unpaired_read_q = unpaired_read_q; 418 | 419 | return create_thread(reader2_proc, params); 420 | } 421 | 422 | static pthread_t 423 | start_reader1(struct input_stream *in, 424 | const struct read_format_params *iparams, 425 | bool verbose, 426 | struct read_queue *avail_read_q, 427 | struct read_queue *unprocessed_read_q) 428 | { 429 | struct reader_params *params = xmalloc(sizeof(*params)); 430 | 431 | params->in = in; 432 | params->iparams = iparams; 433 | params->verbose = verbose; 434 | params->avail_read_q = avail_read_q; 435 | params->unprocessed_read_1_q = unprocessed_read_q; 436 | params->unprocessed_read_2_q = NULL; 437 | params->unpaired_read_q = NULL; 438 | 439 | return create_thread(reader1_proc, params); 440 | } 441 | 442 | static pthread_t 443 | start_writer2(struct output_stream *out, 444 | const struct read_format_params *oparams, 445 | struct read_queue *to_write_queue_1, 446 | struct read_queue *to_write_queue_2, 447 | struct read_queue *avail_queue) 448 | { 449 | struct writer_params *params = xmalloc(sizeof(*params)); 450 | 451 | params->out = out; 452 | params->oparams = oparams; 453 | params->to_write_queue_1 = to_write_queue_1; 454 | params->to_write_queue_2 = to_write_queue_2; 455 | params->avail_queue = avail_queue; 456 | 457 | return create_thread(writer_proc, params); 458 | } 459 | 460 | static pthread_t 461 | start_writer1(struct output_stream *out, 462 | const struct read_format_params *oparams, 463 | struct read_queue *to_write_queue, 464 | struct read_queue *avail_queue) 465 | { 466 | return start_writer2(out, oparams, to_write_queue, NULL, avail_queue); 467 | } 468 | 469 | 470 | struct read_io_handle { 471 | 472 | pthread_t reader_1; 473 | pthread_t reader_2; 474 | pthread_t writer_1; 475 | pthread_t writer_2; 476 | pthread_t writer_3; 477 | bool reader_1_started; 478 | bool reader_2_started; 479 | bool writer_1_started; 480 | bool writer_2_started; 481 | bool writer_3_started; 482 | 483 | unsigned combiner_threads_remaining; 484 | pthread_mutex_t combiner_threads_remaining_mutex; 485 | 486 | struct read_queue *avail_read_q; 487 | struct read_queue *unprocessed_read_1_q; 488 | struct read_queue *unprocessed_read_2_q; 489 | 490 | struct read_queue *combined_read_q; 491 | struct read_queue *uncombined_read_1_q; 492 | struct read_queue *uncombined_read_2_q; 493 | 494 | pthread_mutex_t get_unprocessed_pair_mutex; 495 | pthread_mutex_t put_uncombined_pair_mutex; 496 | }; 497 | 498 | /* Retrieves some unprocessed read pairs from the I/O layer. Returns %true iff 499 | * more reads were available; returns false if end of file was reached. */ 500 | bool 501 | get_unprocessed_read_pairs(struct read_io_handle *h, struct read_set **s1_p, 502 | struct read_set **s2_p) 503 | { 504 | /* get_unprocessed_pair_mutex ensures the reads are paired up correctly. 505 | */ 506 | struct read_set *s1, *s2; 507 | 508 | pthread_mutex_lock(&h->get_unprocessed_pair_mutex); 509 | 510 | s1 = read_queue_get(h->unprocessed_read_1_q); 511 | s2 = read_queue_get(h->unprocessed_read_2_q); 512 | 513 | pthread_mutex_unlock(&h->get_unprocessed_pair_mutex); 514 | 515 | if (s1 && s2) { 516 | if (s1->filled != s2->filled) 517 | goto mismatch; 518 | *s1_p = s1; 519 | *s2_p = s2; 520 | return true; 521 | } 522 | 523 | if (s1 || s2) 524 | goto mismatch; 525 | return false; 526 | 527 | mismatch: 528 | fatal_error("Input files do not contain the same number of reads"); 529 | } 530 | 531 | /* Submits a set of combined reads to the I/O layer to be written. */ 532 | void 533 | put_combined_reads(struct read_io_handle *h, struct read_set *s) 534 | { 535 | s->type = READS_COMBINED; 536 | 537 | read_queue_put(h->combined_read_q, s); 538 | } 539 | 540 | /* Submits a set of uncombined read pairs to the I/O layer to be written. */ 541 | void 542 | put_uncombined_read_pairs(struct read_io_handle *h, 543 | struct read_set *s1, struct read_set *s2) 544 | { 545 | s1->type = READS_UNCOMBINED; 546 | s2->type = READS_UNCOMBINED; 547 | 548 | /* put_unprocessed_pair_mutex ensures the reads are paired up correctly. 549 | */ 550 | 551 | pthread_mutex_lock(&h->put_uncombined_pair_mutex); 552 | 553 | read_queue_put(h->uncombined_read_1_q, s1); 554 | read_queue_put(h->uncombined_read_2_q, s2); 555 | 556 | pthread_mutex_unlock(&h->put_uncombined_pair_mutex); 557 | } 558 | 559 | 560 | /* Retrieve a read set (full of read structures) that is ready to be reused. */ 561 | struct read_set * 562 | get_avail_read_set(struct read_io_handle *h) 563 | { 564 | struct read_set *s; 565 | 566 | s = read_queue_get(h->avail_read_q); 567 | s->filled = 0; 568 | return s; 569 | } 570 | 571 | /* Return a set of read pairs to the pool for reuse. */ 572 | void 573 | put_avail_read_pairs(struct read_io_handle *h, 574 | struct read_set *s1, struct read_set *s2) 575 | { 576 | read_queue_put(h->avail_read_q, s1); 577 | read_queue_put(h->avail_read_q, s2); 578 | } 579 | 580 | /* Notify the I/O layer that a combiner thread has terminated. 581 | * When all the combiner threads have been terminated, the writers will shut 582 | * down. */ 583 | void 584 | notify_combiner_terminated(struct read_io_handle *h) 585 | { 586 | pthread_mutex_lock(&h->combiner_threads_remaining_mutex); 587 | 588 | if (--h->combiner_threads_remaining == 0) { 589 | 590 | /* Terminate the writer queues. */ 591 | 592 | read_queue_terminate(h->combined_read_q); 593 | 594 | if (h->uncombined_read_1_q != h->avail_read_q && 595 | h->uncombined_read_1_q != h->combined_read_q) 596 | read_queue_terminate(h->uncombined_read_1_q); 597 | 598 | if (h->uncombined_read_2_q != h->avail_read_q) 599 | read_queue_terminate(h->uncombined_read_2_q); 600 | } 601 | 602 | pthread_mutex_unlock(&h->combiner_threads_remaining_mutex); 603 | } 604 | 605 | struct read_set * 606 | new_empty_read_set(struct read_io_handle *h) 607 | { 608 | return new_read_set(BASE_READS_PER_READ_SET + 609 | (h->combiner_threads_remaining * PERTHREAD_READS_PER_READ_SET), 610 | false); 611 | } 612 | 613 | /* Starts the FLASH I/O layer, which is responsible for input/output of reads. 614 | * 615 | * If @in_2 is not NULL, then @in_1 and @in_2 are the input files for read 1 and 616 | * read 2 of the pairs, respectively. Otherwise @in_1 contains both read 1 and 617 | * read 2 of the pairs interleaved. 618 | * 619 | * Either 1, 2, or 3 output files may be specified --- see below for more 620 | * details. */ 621 | struct read_io_handle * 622 | start_readers_and_writers(struct input_stream *in_1, 623 | struct input_stream *in_2, 624 | struct output_stream *out_combined, 625 | struct output_stream *out_uncombined_1, 626 | struct output_stream *out_uncombined_2, 627 | const struct read_format_params *iparams, 628 | const struct read_format_params *oparams, 629 | unsigned num_combiner_threads, 630 | bool verbose) 631 | { 632 | assert(in_1 != NULL); 633 | assert(out_combined != NULL && 634 | (out_uncombined_1 != NULL || out_uncombined_2 == NULL)); 635 | assert(iparams != NULL); 636 | assert(oparams != NULL); 637 | assert(num_combiner_threads > 0); 638 | 639 | if (verbose) 640 | info("Starting reader and writer threads"); 641 | 642 | struct read_io_handle *h = xzalloc(sizeof(*h)); 643 | 644 | size_t reads_per_set = BASE_READS_PER_READ_SET + 645 | (num_combiner_threads * PERTHREAD_READS_PER_READ_SET); 646 | size_t queue_size = num_combiner_threads * QUEUE_SIZE_PER_THREAD; 647 | 648 | h->avail_read_q = new_read_queue(queue_size * 3, reads_per_set, true); 649 | h->unprocessed_read_1_q = new_read_queue(queue_size, reads_per_set, false); 650 | h->unprocessed_read_2_q = new_read_queue(queue_size, reads_per_set, false); 651 | h->combined_read_q = new_read_queue(queue_size, reads_per_set, false); 652 | 653 | init_mutex(&h->get_unprocessed_pair_mutex); 654 | init_mutex(&h->put_uncombined_pair_mutex); 655 | 656 | h->combiner_threads_remaining = num_combiner_threads; 657 | init_mutex(&h->combiner_threads_remaining_mutex); 658 | 659 | /* Start writers. */ 660 | 661 | if (out_uncombined_2) { 662 | /* All 3 output files specified: one for combined reads, one for 663 | * read 1 of uncombined pairs, and one for read 2 of uncombined 664 | * pairs. */ 665 | 666 | h->uncombined_read_1_q = new_read_queue(queue_size, reads_per_set, false); 667 | h->uncombined_read_2_q = new_read_queue(queue_size, reads_per_set, false); 668 | 669 | h->writer_1 = start_writer1(out_combined, oparams, 670 | h->combined_read_q, 671 | h->avail_read_q); 672 | h->writer_1_started = true; 673 | 674 | h->writer_2 = start_writer1(out_uncombined_1, oparams, 675 | h->uncombined_read_1_q, 676 | h->avail_read_q); 677 | h->writer_2_started = true; 678 | 679 | h->writer_3 = start_writer1(out_uncombined_2, oparams, 680 | h->uncombined_read_2_q, 681 | h->avail_read_q); 682 | h->writer_3_started = true; 683 | } else if (out_uncombined_1) { 684 | /* 2 output files specified: one for combined reads and one for 685 | * uncombined pairs. */ 686 | 687 | h->uncombined_read_1_q = new_read_queue(queue_size, reads_per_set, false); 688 | h->uncombined_read_2_q = new_read_queue(queue_size, reads_per_set, false); 689 | 690 | h->writer_1 = start_writer1(out_combined, oparams, 691 | h->combined_read_q, 692 | h->avail_read_q); 693 | h->writer_1_started = true; 694 | 695 | h->writer_2 = start_writer2(out_uncombined_1, oparams, 696 | h->uncombined_read_1_q, 697 | h->uncombined_read_2_q, 698 | h->avail_read_q); 699 | h->writer_2_started = true; 700 | } else { 701 | /* 1 output file specified: combined reads, plus optionally 702 | * uncombined pairs if supported by the format. */ 703 | 704 | if (read_format_supports_mixed_reads(oparams)) { 705 | h->uncombined_read_1_q = h->combined_read_q; 706 | h->uncombined_read_2_q = new_read_queue(queue_size, reads_per_set, false); 707 | 708 | h->writer_1 = start_writer2(out_combined, oparams, 709 | h->combined_read_q, 710 | h->uncombined_read_2_q, 711 | h->avail_read_q); 712 | h->writer_1_started = true; 713 | } else { 714 | /* Can only output combined reads. 715 | * Reroute uncombined reads back to the queue of 716 | * available (for reuse) reads. */ 717 | h->uncombined_read_1_q = h->avail_read_q; 718 | h->uncombined_read_2_q = h->avail_read_q; 719 | 720 | h->writer_1 = start_writer1(out_combined, oparams, 721 | h->combined_read_q, 722 | h->avail_read_q); 723 | h->writer_1_started = true; 724 | } 725 | } 726 | 727 | /* Start readers. */ 728 | 729 | if (in_2) { 730 | /* Two input files: read 1 in each pair comes from the first 731 | * file, and read 2 in each pair comes from the second file. 732 | * 733 | * Only set @verbose for one. */ 734 | h->reader_1 = start_reader1(in_1, 735 | iparams, 736 | verbose, 737 | h->avail_read_q, 738 | h->unprocessed_read_1_q); 739 | h->reader_1_started = true; 740 | 741 | h->reader_2 = start_reader1(in_2, 742 | iparams, 743 | false, 744 | h->avail_read_q, 745 | h->unprocessed_read_2_q); 746 | h->reader_2_started = true; 747 | } else { 748 | /* One input file: both reads in each pair come from the same 749 | * file. */ 750 | struct read_queue *unpaired_read_q = NULL; 751 | 752 | if (read_format_supports_mixed_reads(iparams)) { 753 | if (!out_uncombined_2 && 754 | read_format_supports_mixed_reads(oparams)) 755 | unpaired_read_q = h->uncombined_read_1_q; 756 | else 757 | warning("Any unpaired reads in the input file " 758 | "will be ignored!\n\t" 759 | "Use tab-delimited output to " 760 | "preserve them."); 761 | } 762 | 763 | h->reader_1 = start_reader2(in_1, 764 | iparams, 765 | verbose, 766 | h->avail_read_q, 767 | h->unprocessed_read_1_q, 768 | h->unprocessed_read_2_q, 769 | unpaired_read_q); 770 | h->reader_1_started = true; 771 | } 772 | 773 | 774 | return h; 775 | } 776 | 777 | /* Terminates the FLASH I/O layer, which is responsible for input/output of 778 | * reads. 779 | */ 780 | void 781 | stop_readers_and_writers(struct read_io_handle *h) 782 | { 783 | if (h->reader_1_started) 784 | join_thread(h->reader_1); 785 | if (h->reader_2_started) 786 | join_thread(h->reader_2); 787 | if (h->writer_1_started) 788 | join_thread(h->writer_1); 789 | if (h->writer_2_started) 790 | join_thread(h->writer_2); 791 | if (h->writer_3_started) 792 | join_thread(h->writer_3); 793 | 794 | free_read_queue(h->avail_read_q); 795 | free_read_queue(h->unprocessed_read_1_q); 796 | free_read_queue(h->unprocessed_read_2_q); 797 | free_read_queue(h->combined_read_q); 798 | 799 | if (h->uncombined_read_1_q != h->avail_read_q && 800 | h->uncombined_read_1_q != h->combined_read_q) 801 | free_read_queue(h->uncombined_read_1_q); 802 | 803 | if (h->uncombined_read_2_q != h->avail_read_q) 804 | free_read_queue(h->uncombined_read_2_q); 805 | 806 | pthread_mutex_destroy(&h->put_uncombined_pair_mutex); 807 | pthread_mutex_destroy(&h->get_unprocessed_pair_mutex); 808 | pthread_mutex_destroy(&h->combiner_threads_remaining_mutex); 809 | 810 | xfree(h, sizeof(*h)); 811 | } 812 | -------------------------------------------------------------------------------- /read_queue.h: -------------------------------------------------------------------------------- 1 | #ifndef _FLASH_READ_QUEUE_H_ 2 | #define _FLASH_READ_QUEUE_H_ 3 | 4 | #include 5 | 6 | struct read; 7 | struct read_format_params; 8 | struct input_stream; 9 | struct output_stream; 10 | 11 | /* BASE_READS_PER_READ_SET: The base number of reads per read set (i.e. per 12 | * chunk processed by combiner threads). This number must be at least 1; it is 13 | * a heuristic value that affects performance only. The faster the core 14 | * algorithm runs, the higher it should be. 15 | * 16 | * PERTHREAD_READS_PER_READ_SET: Additional number of reads per read set per 17 | * combiner thread. 18 | */ 19 | #if defined(__GNUC__) && defined(__SSE2__) 20 | # define BASE_READS_PER_READ_SET 30 21 | # define PERTHREAD_READS_PER_READ_SET 5 22 | #else 23 | # define BASE_READS_PER_READ_SET 24 24 | # define PERTHREAD_READS_PER_READ_SET 4 25 | #endif 26 | 27 | /* NUmber of read sets to allocate per combiner thread. Must be at least 6. */ 28 | #define QUEUE_SIZE_PER_THREAD 8 29 | 30 | struct read_io_handle; 31 | 32 | struct read_set { 33 | unsigned filled; 34 | unsigned num_reads; 35 | enum { 36 | READS_UNCOMBINED, 37 | READS_COMBINED, 38 | READS_UNPAIRED, 39 | } type; 40 | struct read *reads[]; 41 | }; 42 | 43 | extern struct read_io_handle * 44 | start_readers_and_writers(struct input_stream *in_1, 45 | struct input_stream *in_2, 46 | struct output_stream *out_combined, 47 | struct output_stream *out_uncombined_1, 48 | struct output_stream *out_uncombined_2, 49 | const struct read_format_params *iparams, 50 | const struct read_format_params *oparams, 51 | unsigned num_combiner_threads, 52 | bool verbose); 53 | 54 | extern struct read_set * 55 | get_avail_read_set(struct read_io_handle *handle); 56 | 57 | extern bool 58 | get_unprocessed_read_pairs(struct read_io_handle *handle, 59 | struct read_set **s1_ret, struct read_set **s2_ret); 60 | 61 | extern void 62 | put_combined_reads(struct read_io_handle *handle, struct read_set *s); 63 | 64 | extern void 65 | put_uncombined_read_pairs(struct read_io_handle *handle, 66 | struct read_set *s1, struct read_set *s2); 67 | 68 | extern void 69 | put_avail_read_pairs(struct read_io_handle *handle, 70 | struct read_set *s1, struct read_set *s2); 71 | 72 | extern void 73 | notify_combiner_terminated(struct read_io_handle *h); 74 | 75 | extern struct read_set * 76 | new_empty_read_set(struct read_io_handle *h); 77 | 78 | extern void 79 | free_read_set(struct read_set *s); 80 | 81 | extern void 82 | stop_readers_and_writers(struct read_io_handle *h); 83 | 84 | #endif /* _FLASH_READ_QUEUE_H_ */ 85 | -------------------------------------------------------------------------------- /read_util.c: -------------------------------------------------------------------------------- 1 | /* 2 | * read_util.c: Utility functions for processing reads 3 | */ 4 | 5 | /* 6 | * Copyright (C) 2012 Tanja Magoc 7 | * Copyright (C) 2012, 2013, 2014 Eric Biggers 8 | * 9 | * This file is part of FLASH, a fast tool to merge overlapping paired-end 10 | * reads. 11 | * 12 | * FLASH is free software; you can redistribute it and/or modify it under the 13 | * terms of the GNU General Public License as published by the Free 14 | * Software Foundation; either version 3 of the License, or (at your option) 15 | * any later version. 16 | * 17 | * FLASH is distributed in the hope that it will be useful, but WITHOUT ANY 18 | * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR 19 | * A PARTICULAR PURPOSE. See the GNU General Public License for more 20 | * details. 21 | * 22 | * You should have received a copy of the GNU General Public License 23 | * along with FLASH; if not, see http://www.gnu.org/licenses/. 24 | */ 25 | 26 | #include "read.h" 27 | #include "iostream.h" 28 | #include "util.h" 29 | 30 | #include 31 | #include 32 | #include 33 | 34 | /* 35 | * A table mapping ASCII characters (actually, 8-bit bytes) to "canonical" form 36 | * for base processing: 37 | * 38 | * a, A => A 39 | * c, C => C 40 | * g, G => G 41 | * t, T => T 42 | * everything else => N 43 | */ 44 | static const char canonical_ascii_tab[256] = { 45 | 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 46 | 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 47 | 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 48 | 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 49 | 'N', /* A */ 'A', 'N', /* C */ 'C', 'N', 'N', 'N', /* G */ 'G', 50 | 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 51 | 'N', 'N', 'N', 'N', /* T */ 'T', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 52 | 'N', /* a */ 'A', 'N', /* c */ 'C', 'N', 'N', 'N', /* g */ 'G', 53 | 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 54 | 'N', 'N', 'N', 'N', /* t */ 'T', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 55 | 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 56 | 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 57 | 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 58 | 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 59 | 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 60 | 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 61 | 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 62 | 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 63 | }; 64 | 65 | /* Turns lowercase a, c, g, t into uppercase; 66 | * uppercase A, C, G, T stay the same; 67 | * everything else turns into 'N'. */ 68 | static inline char 69 | canonical_ascii_char(char c) 70 | { 71 | return canonical_ascii_tab[(unsigned char)c]; 72 | } 73 | 74 | /* A table mapping an ASCII base character in canonical form to its complement. 75 | * Unknown bases (N's) stay unknown. */ 76 | static const char complement_tab[] = { 77 | ['A'] = 'T', 78 | ['C'] = 'G', 79 | ['G'] = 'C', 80 | ['T'] = 'A', 81 | ['N'] = 'N', 82 | }; 83 | 84 | /* Complements a canonical ASCII base (A, C, G, T, N). */ 85 | static inline char 86 | complement(char c) 87 | { 88 | return complement_tab[(unsigned char)c]; 89 | } 90 | 91 | static inline char 92 | identity_mapping(char c) 93 | { 94 | return c; 95 | } 96 | 97 | /* Reverse a sequence of @len chars, applying the mapping function @map_char to 98 | * each, including the middle char if @len is odd. */ 99 | static inline void 100 | reverse_with_mapping(char *p, size_t len, char (*map_char)(char)) 101 | { 102 | char tmp; 103 | char *pp = p + len; 104 | while (pp > p) { 105 | --pp; 106 | tmp = *p; 107 | *p = (*map_char)(*pp); 108 | *pp = (*map_char)(tmp); 109 | ++p; 110 | } 111 | } 112 | 113 | /* Reverse-complement a read in place. */ 114 | void 115 | reverse_complement(struct read *r) 116 | { 117 | reverse_with_mapping(r->seq, r->seq_len, complement); 118 | reverse_with_mapping(r->qual, r->seq_len, identity_mapping); 119 | } 120 | 121 | /* Remove all whitespace from the end of the line/string. Return the length of 122 | * the trimmed string. */ 123 | static inline int 124 | trim(char *s, int len) 125 | { 126 | while (len > 0 && isspace((unsigned char)s[len - 1])) 127 | s[--len] = '\0'; 128 | return len; 129 | } 130 | 131 | void 132 | clean_read(struct read *r, int phred_offset, struct input_stream *in, 133 | uint64_t line_no) 134 | { 135 | int seq_len; 136 | char *seq; 137 | char *qual; 138 | 139 | r->seq_len = trim(r->seq, r->seq_len); 140 | r->tag_len = trim(r->tag, r->tag_len); 141 | r->qual_len = trim(r->qual, r->qual_len); 142 | 143 | seq_len = r->seq_len; 144 | 145 | if (r->qual_len != seq_len) { 146 | fatal_error("Qual string length (%d) not the same as sequence " 147 | "length (%d) (file \"%s\", near line %"PRIu64")", 148 | r->qual_len, seq_len, 149 | input_stream_get_name(in), line_no); 150 | } 151 | 152 | seq = r->seq; 153 | for (int i = 0; i < seq_len; i++) { 154 | if (isspace((unsigned char)seq[i])) { 155 | fatal_error("Invalid sequence string: " 156 | "contains whitespace " 157 | "(file \"%s\", near line %"PRIu64")", 158 | input_stream_get_name(in), line_no); 159 | } 160 | seq[i] = canonical_ascii_char(seq[i]); 161 | } 162 | 163 | qual = r->qual; 164 | 165 | if (phred_offset > 0) { 166 | for (int i = 0; i < seq_len; i++) { 167 | if (qual[i] < phred_offset) { 168 | fatal_error("Qual string contains character " 169 | "under phred_offset = %d " 170 | "(file \"%s\", near line %"PRIu64")", 171 | phred_offset, 172 | input_stream_get_name(in), line_no); 173 | } 174 | qual[i] -= phred_offset; 175 | } 176 | } 177 | } 178 | 179 | void 180 | clean_read_for_write(struct read *r, int phred_offset) 181 | { 182 | 183 | assert(r->seq_len == r->qual_len); 184 | 185 | if (phred_offset > 0) { 186 | char *qual = r->qual; 187 | int qual_len = r->qual_len; 188 | for (int i = 0; i < qual_len; i++) 189 | qual[i] += phred_offset; 190 | } 191 | } 192 | 193 | void 194 | copy_tag(struct read *to, const struct read *from) 195 | { 196 | if (to->tag_bufsz < from->tag_len + 1) { 197 | to->tag = xrealloc(to->tag, from->tag_len + 1); 198 | to->tag_bufsz = from->tag_len + 1; 199 | } 200 | to->tag_len = from->tag_len; 201 | memcpy(to->tag, from->tag, from->tag_len + 1); 202 | } 203 | 204 | /* 205 | * Given the FASTQ tags of two paired-end reads, find the FASTQ tag to give to 206 | * the combined read. 207 | * 208 | * This is done by stripping off the characters trailing the '/' (e.g. "/1" and 209 | * "/2"), unless there is a "barcode" beginning with the '#' character, which is 210 | * kept. 211 | */ 212 | void 213 | get_combined_tag(const struct read *read_1, 214 | const struct read *read_2, 215 | struct read *combined_read) 216 | { 217 | char *p; 218 | copy_tag(combined_read, read_1); 219 | for (p = &combined_read->tag[combined_read->tag_len - 1]; 220 | p >= combined_read->tag; 221 | p--) 222 | { 223 | if (*p == '/') { 224 | /* Tags are different, and there's a forward slash in 225 | * the first tag. Remove everything after the forward 226 | * slash, unless there's a barcode, which we keep. */ 227 | if (*(p + 1) != '\0' && *(p + 2) == '#') { 228 | /* read ID has a barcode. */ 229 | do { 230 | *p = *(p + 2); 231 | } while (*(++p + 2) != '\0'); 232 | } 233 | *p = '\0'; 234 | combined_read->tag_len = p - combined_read->tag; 235 | break; 236 | } 237 | } 238 | } 239 | -------------------------------------------------------------------------------- /util.c: -------------------------------------------------------------------------------- 1 | /* 2 | * util.c: miscellaneous useful functions for FLASH 3 | */ 4 | 5 | /* 6 | * Copyright (C) 2012 Tanja Magoc 7 | * Copyright (C) 2012, 2013, 2014 Eric Biggers 8 | * 9 | * This file is part of FLASH, a fast tool to merge overlapping paired-end 10 | * reads. 11 | * 12 | * FLASH is free software; you can redistribute it and/or modify it under the 13 | * terms of the GNU General Public License as published by the Free 14 | * Software Foundation; either version 3 of the License, or (at your option) 15 | * any later version. 16 | * 17 | * FLASH is distributed in the hope that it will be useful, but WITHOUT ANY 18 | * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR 19 | * A PARTICULAR PURPOSE. See the GNU General Public License for more 20 | * details. 21 | * 22 | * You should have received a copy of the GNU General Public License 23 | * along with FLASH; if not, see http://www.gnu.org/licenses/. 24 | */ 25 | 26 | #include 27 | #include 28 | #include 29 | #include 30 | #include 31 | #include 32 | #include 33 | #include 34 | #include 35 | #include 36 | #include 37 | #include "util.h" 38 | 39 | #ifdef __WIN32__ 40 | /* Get the pthread mutex declarations as a replacement for flockfile() and 41 | * funlockfile(). */ 42 | # include 43 | /* Get the GetSystemInfo() declaration as replacement for 44 | * sysconf(_SC_NPROCESSORS_ONLN). */ 45 | # include 46 | #endif 47 | 48 | #ifdef __WIN32__ 49 | static pthread_mutex_t infofile_lock = PTHREAD_MUTEX_INITIALIZER; 50 | static pthread_mutex_t stderr_lock = PTHREAD_MUTEX_INITIALIZER; 51 | #endif 52 | 53 | /* File to which to write informational messages. */ 54 | FILE *infofile; 55 | 56 | static void 57 | lock_infofile(void) 58 | { 59 | #ifdef __WIN32__ 60 | pthread_mutex_lock(&infofile_lock); 61 | #else 62 | flockfile(infofile); 63 | #endif 64 | } 65 | 66 | static void 67 | lock_stderr(void) 68 | { 69 | #ifdef __WIN32__ 70 | pthread_mutex_lock(&stderr_lock); 71 | #else 72 | flockfile(stderr); 73 | #endif 74 | } 75 | 76 | static void 77 | unlock_infofile(void) 78 | { 79 | #ifdef __WIN32__ 80 | pthread_mutex_unlock(&infofile_lock); 81 | #else 82 | funlockfile(infofile); 83 | #endif 84 | } 85 | 86 | static void 87 | unlock_stderr(void) 88 | { 89 | #ifdef __WIN32__ 90 | pthread_mutex_unlock(&stderr_lock); 91 | #else 92 | funlockfile(stderr); 93 | #endif 94 | } 95 | 96 | #define PROGRAM_TAG "[FLASH] " 97 | 98 | static void __noreturn 99 | fatal(void) 100 | { 101 | info("FLASH did not complete successfully; exiting with failure status (1)"); 102 | exit(1); 103 | } 104 | 105 | /* Prints an error message and exits the program with failure status. */ 106 | void 107 | fatal_error(const char *msg, ...) 108 | { 109 | va_list va; 110 | 111 | lock_stderr(); 112 | 113 | va_start(va, msg); 114 | fflush(stdout); 115 | fputs(PROGRAM_TAG "ERROR: ", stderr); 116 | vfprintf(stderr, msg, va); 117 | putc('\n', stderr); 118 | va_end(va); 119 | 120 | unlock_stderr(); 121 | 122 | fatal(); 123 | } 124 | 125 | /* Prints an error message, with added text for errno if it is nonzero, and 126 | * exits the program with failure status. */ 127 | void 128 | fatal_error_with_errno(const char *msg, ...) 129 | { 130 | va_list va; 131 | 132 | lock_stderr(); 133 | 134 | va_start(va, msg); 135 | fflush(stdout); 136 | fputs(PROGRAM_TAG "ERROR: ", stderr); 137 | vfprintf(stderr, msg, va); 138 | if (errno) 139 | fprintf(stderr, ": %s\n", strerror(errno)); 140 | else 141 | putc('\n', stderr); 142 | va_end(va); 143 | 144 | unlock_stderr(); 145 | 146 | fatal(); 147 | } 148 | 149 | unsigned long warning_count = 0; 150 | 151 | /* Prints a warning message. */ 152 | void 153 | warning(const char *msg, ...) 154 | { 155 | va_list va; 156 | 157 | lock_stderr(); 158 | 159 | warning_count++; 160 | 161 | va_start(va, msg); 162 | fputs(PROGRAM_TAG "WARNING: ", stderr); 163 | vfprintf(stderr, msg, va); 164 | putc('\n', stderr); 165 | va_end(va); 166 | 167 | unlock_stderr(); 168 | } 169 | 170 | /* Prints an informational message. */ 171 | void 172 | info(const char *msg, ...) 173 | { 174 | va_list va; 175 | 176 | lock_infofile(); 177 | 178 | va_start(va, msg); 179 | fputs(PROGRAM_TAG, infofile); 180 | vfprintf(infofile, msg, va); 181 | putc('\n', infofile); 182 | fflush(infofile); 183 | va_end(va); 184 | 185 | unlock_infofile(); 186 | } 187 | 188 | /* Like malloc(), but aborts if out of memory, and always returns non-NULL, even 189 | * if 0 bytes were requested. */ 190 | void * 191 | xmalloc(size_t size) 192 | { 193 | void *p = malloc(size); 194 | if (p) 195 | return p; 196 | if (!size) { 197 | p = malloc(1); 198 | if (p) 199 | return p; 200 | } 201 | fatal_error("Out of memory: tried to allocate %zu bytes", size); 202 | } 203 | 204 | void * 205 | xzalloc(size_t size) 206 | { 207 | return memset(xmalloc(size), 0, size); 208 | } 209 | 210 | /* Like strdup(), but aborts if out of memory. */ 211 | char * 212 | xstrdup(const char *str) 213 | { 214 | return strcpy(xmalloc(strlen(str) + 1), str); 215 | } 216 | 217 | /* Like realloc(), but aborts if out of memory, and always returns non-NULL, 218 | * even if 0 bytes were requested. */ 219 | void * 220 | xrealloc(void *ptr, size_t size) 221 | { 222 | void *p = realloc(ptr, size); 223 | if (p) 224 | return p; 225 | if (!size) { 226 | p = malloc(1); 227 | if (p) 228 | return p; 229 | } 230 | fatal_error("Out of memory: tried to reallocate %zu bytes", size); 231 | } 232 | 233 | #ifndef NDEBUG 234 | void 235 | xfree(void *p, size_t size) 236 | { 237 | if (p) { 238 | memset(p, 0xfd, size); 239 | free(p); 240 | } 241 | } 242 | #endif 243 | 244 | /* Returns the number of available processors if it can be determined. 245 | * Otherwise returns 1. */ 246 | unsigned 247 | get_default_num_threads(void) 248 | { 249 | #ifdef __WIN32__ 250 | SYSTEM_INFO si; 251 | GetSystemInfo(&si); 252 | if (si.dwNumberOfProcessors > 0 && si.dwNumberOfProcessors <= UINT_MAX) 253 | return si.dwNumberOfProcessors; 254 | #else 255 | long nproc = sysconf(_SC_NPROCESSORS_ONLN); 256 | if (nproc > 0 && nproc <= UINT_MAX) 257 | return nproc; 258 | #endif 259 | warning("Could not determine number of processors! Assuming 1"); 260 | return 1; 261 | } 262 | 263 | 264 | /* Returns true if the specified character is a path separator on the current 265 | * platform. */ 266 | static bool 267 | is_path_separator(char c) 268 | { 269 | #ifdef __WIN32__ 270 | return (c == '/') || (c == '\\'); 271 | #else 272 | return (c == '/'); 273 | #endif 274 | } 275 | 276 | 277 | /* mkdir() on Windows doesn't take a mode argument. */ 278 | #ifdef __WIN32__ 279 | # define mkdir(path, mode) mkdir(path) 280 | #endif 281 | 282 | /* Like `mkdir -p': create the specified directory, and all parent directories, 283 | * as needed, failing only if a needed directory cannot be created. */ 284 | void 285 | mkdir_p(const char *dir) 286 | { 287 | size_t len = strlen(dir); 288 | char dir_copy[len + 1]; 289 | char *p = dir_copy; 290 | /* Copy the directory name to the @dir_copy array, squashing together 291 | * consecutive path separators. */ 292 | for (size_t i = 0; i < len; i++) { 293 | if (!is_path_separator(dir[i]) || 294 | !is_path_separator(dir[i + 1])) 295 | *p++ = dir[i]; 296 | } 297 | *p = '\0'; 298 | 299 | p = dir_copy; 300 | do { 301 | if (p != dir_copy && (*p == '\0' || is_path_separator(*p))) { 302 | char orig_char = *p; 303 | *p = '\0'; 304 | 305 | if (mkdir(dir_copy, 0755) != 0 && errno != EEXIST) { 306 | fatal_error_with_errno("Failed to create " 307 | "directory \"%s\"", 308 | dir_copy); 309 | } 310 | *p = orig_char; 311 | } 312 | } while (*p++ != '\0'); 313 | } 314 | 315 | pthread_t 316 | create_thread(void *(*proc)(void *), void *params) 317 | { 318 | int result; 319 | pthread_t t; 320 | 321 | result = pthread_create(&t, NULL, proc, params); 322 | if (result) { 323 | errno = result; 324 | fatal_error_with_errno("Failed to create new thread"); 325 | } 326 | return t; 327 | } 328 | 329 | void 330 | join_thread(pthread_t t) 331 | { 332 | int result = pthread_join(t, NULL); 333 | if (result) { 334 | errno = result; 335 | fatal_error_with_errno("Failed to join thread"); 336 | } 337 | } 338 | -------------------------------------------------------------------------------- /util.h: -------------------------------------------------------------------------------- 1 | #ifndef _FLASH_UTIL_H_ 2 | #define _FLASH_UTIL_H_ 3 | 4 | #include 5 | #include 6 | #include 7 | 8 | #define ARRAY_LEN(A) (sizeof(A) / sizeof((A)[0])) 9 | 10 | #ifdef __GNUC__ 11 | # if __GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 4) 12 | # define __cold __attribute__((cold)) 13 | # else 14 | # define __cold 15 | # endif 16 | # define __noreturn __attribute__((noreturn)) 17 | # define __format(type, format_str, args_start) \ 18 | __attribute__((format(type, format_str, args_start))) 19 | # define max(a,b) ({ __typeof__(a) _a = (a); __typeof__(b) _b = (b); _a > _b ? _a : _b; }) 20 | # define min(a,b) ({ __typeof__(a) _a = (a); __typeof__(b) _b = (b); _a < _b ? _a : _b; }) 21 | # define inline inline __attribute__((always_inline)) 22 | #else 23 | # define __noreturn 24 | # define __cold 25 | # define __format(type, format_str, args_start) 26 | # define max(a,b) (((a) > (b)) ? (a) : (b)) 27 | # define min(a,b) (((a) < (b)) ? (a) : (b)) 28 | #endif 29 | 30 | extern void 31 | fatal_error(const char *msg, ...) __noreturn __cold __format(printf, 1, 2); 32 | 33 | extern void 34 | fatal_error_with_errno(const char *msg, ...) __noreturn __cold __format(printf, 1, 2); 35 | 36 | extern unsigned long warning_count; 37 | 38 | extern void 39 | warning(const char *msg, ...) __cold __format(printf, 1, 2); 40 | 41 | extern FILE *infofile; 42 | 43 | extern void 44 | info(const char *msg, ...) __format(printf, 1, 2); 45 | 46 | extern void * 47 | xmalloc(size_t size); 48 | 49 | #ifdef NDEBUG 50 | # define xfree(p, size) free(p) 51 | #else 52 | extern void 53 | xfree(void *p, size_t size); 54 | #endif 55 | 56 | extern void * 57 | xzalloc(size_t size); 58 | 59 | extern char * 60 | xstrdup(const char *str); 61 | 62 | extern void * 63 | xrealloc(void *ptr, size_t size); 64 | 65 | extern unsigned 66 | get_default_num_threads(void); 67 | 68 | extern void 69 | mkdir_p(const char *dir); 70 | 71 | extern pthread_t 72 | create_thread(void *(*proc)(void *), void *params); 73 | 74 | extern void 75 | join_thread(pthread_t t); 76 | 77 | #endif /* _FLASH_UTIL_H_ */ 78 | --------------------------------------------------------------------------------