| 1657 | }; |
| 1658 | |
| 1659 | uint8_t *read_tga(const uint8_t *pBuf, uint32_t buf_size, int &width, int &height, int &n_chans) |
| 1660 | { |
| 1661 | width = 0; |
| 1662 | height = 0; |
| 1663 | n_chans = 0; |
| 1664 | |
| 1665 | if (buf_size <= sizeof(tga_header)) |
| 1666 | return nullptr; |
| 1667 | |
| 1668 | const tga_header &hdr = *reinterpret_cast<const tga_header *>(pBuf); |
| 1669 | |
| 1670 | if ((!hdr.m_width) || (!hdr.m_height) || (hdr.m_width > MAX_TGA_IMAGE_SIZE) || (hdr.m_height > MAX_TGA_IMAGE_SIZE)) |
| 1671 | return nullptr; |
| 1672 | |
| 1673 | if (hdr.m_desc >> 6) |
| 1674 | return nullptr; |
| 1675 | |
| 1676 | // Simple validation |
| 1677 | if ((hdr.m_cmap != 0) && (hdr.m_cmap != 1)) |
| 1678 | return nullptr; |
| 1679 | |
| 1680 | if (hdr.m_cmap) |
| 1681 | { |
| 1682 | if ((hdr.m_cmap_bpp == 0) || (hdr.m_cmap_bpp > 32)) |
| 1683 | return nullptr; |
| 1684 | |
| 1685 | // Nobody implements CMapFirst correctly, so we're not supporting it. Never seen it used, either. |
| 1686 | if (hdr.m_cmap_first != 0) |
| 1687 | return nullptr; |
| 1688 | } |
| 1689 | |
| 1690 | const bool x_flipped = (hdr.m_desc & 0x10) != 0; |
| 1691 | const bool y_flipped = (hdr.m_desc & 0x20) == 0; |
| 1692 | |
| 1693 | bool rle_flag = false; |
| 1694 | int file_image_type = hdr.m_type; |
| 1695 | if (file_image_type > 8) |
| 1696 | { |
| 1697 | file_image_type -= 8; |
| 1698 | rle_flag = true; |
| 1699 | } |
| 1700 | |
| 1701 | const tga_image_type image_type = static_cast<tga_image_type>(file_image_type); |
| 1702 | |
| 1703 | switch (file_image_type) |
| 1704 | { |
| 1705 | case cITRGB: |
| 1706 | if (hdr.m_depth == 8) |
| 1707 | return nullptr; |
| 1708 | break; |
| 1709 | case cITPalettized: |
| 1710 | if ((hdr.m_depth != 8) || (hdr.m_cmap != 1) || (hdr.m_cmap_len == 0)) |
| 1711 | return nullptr; |
| 1712 | break; |
| 1713 | case cITGrayscale: |
| 1714 | if ((hdr.m_cmap != 0) || (hdr.m_cmap_len != 0)) |
| 1715 | return nullptr; |
| 1716 | if ((hdr.m_depth != 8) && (hdr.m_depth != 16)) |