repo_name
stringlengths 5
122
| path
stringlengths 3
232
| text
stringlengths 6
1.05M
|
|---|---|---|
straight-coding/straight-httpd-lwip-mbedtls-simulator
|
lwip-port/win32/lwipopts.h
|
/* lwipopts.h, lwIP Options Configuration. */
#ifndef __LWIPOPTS_H__
#define __LWIPOPTS_H__
#define ENABLE_HTTPS 1
/*
if lwip is used with mbedtls package, there are three options that need to be set carefully.
MEM_SIZE: More memory is better
TCP_MSS: MUST be bigger enough
TCP_WND: MUST be greater than MBEDTLS_SSL_MAX_CONTENT_LEN (it could not be changed less than 16384)
*/
/* ---------- Memory options ---------- */
/* MEM_LIBC_MALLOC==1: Use malloc/free/realloc provided by your C-library
* instead of the lwip internal allocator. Can save code size if you
* already use it. */
#undef MEM_LIBC_MALLOC
#define MEM_LIBC_MALLOC 0
/* MEMP_MEM_MALLOC==1: Use mem_malloc/mem_free instead of the lwip pool allocator.
* Especially useful with MEM_LIBC_MALLOC but handle with care regarding execution
* speed (heap alloc can be much slower than pool alloc) and usage from interrupts
* (especially if your netif driver allocates PBUF_POOL pbufs for received frames
* from interrupt)!
* ATTENTION: Currently, this uses the heap for ALL pools (also for private pools,
* not only for internal pools defined in memp_std.h)! */
#undef MEMP_MEM_MALLOC
#define MEMP_MEM_MALLOC 1 //Only one can be selected with MEM_USE_POOLS
/* MEM_USE_POOLS==1: Use an alternative to malloc() by allocating from a set
* of memory pools of various sizes. When mem_malloc is called, an element of
* the smallest pool that can provide the length needed is returned.
* To use this, MEMP_USE_CUSTOM_POOLS also has to be enabled. */
#undef MEM_USE_POOLS
#define MEM_USE_POOLS 0 //Only one can be selected with MEMP_MEM_MALLOC
/* MEM_SIZE: the size of the heap memory. If the application will send
a lot of data that needs to be copied, this should be set high. */
//100kB to support large file downloading and uploading, and keep-alive works good, 130kB may be better for Chrome/Edge
//57kB basic memory to create TLS connections, and support large file downloading and uploading, but keep-alive may fail
#undef MEM_SIZE
#if (ENABLE_HTTPS > 0)
#define MEM_SIZE (130*1024)
#else
#define MEM_SIZE (24*1024)
#endif
/* ---------- Memory options ---------- */
/* MEM_ALIGNMENT: should be set to the alignment of the CPU for which
lwIP is compiled. 4 byte alignment -> define MEM_ALIGNMENT to 4, 2
byte alignment -> define MEM_ALIGNMENT to 2. */
#undef MEM_ALIGNMENT
#define MEM_ALIGNMENT 4
/* MEMP_NUM_RAW_PCB: Number of raw connection PCBs
(requires the LWIP_RAW option) */
#undef MEMP_NUM_RAW_PCB
#define MEMP_NUM_RAW_PCB 0
/* MEMP_NUM_UDP_PCB: the number of UDP protocol control blocks. One
per active UDP "connection". */
#undef MEMP_NUM_UDP_PCB
#define MEMP_NUM_UDP_PCB 2
/* MEMP_NUM_TCP_PCB: the number of simulatenously active TCP connections. */
#undef MEMP_NUM_TCP_PCB
#define MEMP_NUM_TCP_PCB 6
/* MEMP_NUM_TCP_PCB_LISTEN: the number of listening TCP connections. */
#undef MEMP_NUM_TCP_PCB_LISTEN
#define MEMP_NUM_TCP_PCB_LISTEN 6
/* MEMP_NUM_TCP_SEG: the number of simultaneously queued TCP segments. */
#undef MEMP_NUM_TCP_SEG
#define MEMP_NUM_TCP_SEG 16
#define ETH_PAD_SIZE 0
#define LWIP_TCP 1
/* TCP Maximum segment size. http://lwip.wikia.com/wiki/Tuning_TCP */
#undef TCP_MSS
//for HTTPS, at least 800; for HTTP can be smaller
#define TCP_MSS 800 /* TCP_MSS = (Ethernet MTU - IP header size - TCP header size) */
/* TCP receive window. */
#undef TCP_WND
#if (ENABLE_HTTPS > 0)
#define TCP_WND (22 * TCP_MSS) //TCP_WND >= MBEDTLS_SSL_MAX_CONTENT_LEN
#else
#define TCP_WND (4 * TCP_MSS) //TCP_WND >= MBEDTLS_SSL_MAX_CONTENT_LEN
#endif
/* Controls if TCP should queue segments that arrive out of
order. Define to 0 if your device is low on memory. */
#undef TCP_QUEUE_OOSEQ
#define TCP_QUEUE_OOSEQ 0
#define LWIP_TCP_SACK_OUT 0
/* TCPIP_MBOX_SIZE: The mailbox size for the tcpip thread messages
* The queue size value itself is platform-dependent, but is passed to
* sys_mbox_new() when tcpip_init is called. */
#undef TCPIP_MBOX_SIZE
#define TCPIP_MBOX_SIZE 64
/* DEFAULT_TCP_RECVMBOX_SIZE: The mailbox size for the incoming packets on a
* NETCONN_TCP. The queue size value itself is platform-dependent, but is passed
* to sys_mbox_new() when the recvmbox is created. */
#undef DEFAULT_TCP_RECVMBOX_SIZE
#define DEFAULT_TCP_RECVMBOX_SIZE 64
/* DEFAULT_ACCEPTMBOX_SIZE: The mailbox size for the incoming connections.
* The queue size value itself is platform-dependent, but is passed to
* sys_mbox_new() when the acceptmbox is created. */
#undef DEFAULT_ACCEPTMBOX_SIZE
#define DEFAULT_ACCEPTMBOX_SIZE 64
/* LWIP_ICMP==1: Enable ICMP module inside the IP stack.
* Be careful, disable that make your product non-compliant to RFC1122 */
#define LWIP_ICMP 1
/* Define LWIP_DHCP to 1 if you want DHCP configuration of
interfaces. DHCP is not implemented in lwIP 0.5.1, however, so
turning this on does currently not work. */
#define LWIP_DHCP 1
/* LWIP_UDP==1: Turn on UDP. */
#define LWIP_UDP 1
/* LWIP_STATS==1: Enable statistics collection in lwip_stats. */
#undef LWIP_STATS
#define LWIP_STATS 0
/* LWIP_PROVIDE_ERRNO==1: Let lwIP provide ERRNO values and the 'errno' variable.
* If this is disabled, cc.h must either define 'errno', include <errno.h>,
* define LWIP_ERRNO_STDINCLUDE to get <errno.h> included or
* define LWIP_ERRNO_INCLUDE to <errno.h> or equivalent. */
#define LWIP_PROVIDE_ERRNO 1
#ifdef CHECKSUM_BY_HARDWARE
/* CHECKSUM_GEN_IP==0: Generate checksums by hardware for outgoing IP packets.*/
#undef CHECKSUM_GEN_IP
#define CHECKSUM_GEN_IP 0
/* CHECKSUM_GEN_UDP==0: Generate checksums by hardware for outgoing UDP packets.*/
#undef CHECKSUM_GEN_UDP
#define CHECKSUM_GEN_UDP 0
/* CHECKSUM_GEN_TCP==0: Generate checksums by hardware for outgoing TCP packets.*/
#undef CHECKSUM_GEN_TCP
#define CHECKSUM_GEN_TCP 0
/* CHECKSUM_CHECK_IP==0: Check checksums by hardware for incoming IP packets.*/
#undef CHECKSUM_CHECK_IP
#define CHECKSUM_CHECK_IP 0
/* CHECKSUM_CHECK_UDP==0: Check checksums by hardware for incoming UDP packets.*/
#undef CHECKSUM_CHECK_UDP
#define CHECKSUM_CHECK_UDP 0
/* CHECKSUM_CHECK_TCP==0: Check checksums by hardware for incoming TCP packets.*/
#undef CHECKSUM_CHECK_TCP
#define CHECKSUM_CHECK_TCP 0
#else
/* CHECKSUM_GEN_IP==1: Generate checksums in software for outgoing IP packets.*/
#define CHECKSUM_GEN_IP 1
/* CHECKSUM_GEN_UDP==1: Generate checksums in software for outgoing UDP packets.*/
#define CHECKSUM_GEN_UDP 1
/* CHECKSUM_GEN_TCP==1: Generate checksums in software for outgoing TCP packets.*/
#define CHECKSUM_GEN_TCP 1
/* CHECKSUM_CHECK_IP==1: Check checksums in software for incoming IP packets.*/
#define CHECKSUM_CHECK_IP 1
/* CHECKSUM_CHECK_UDP==1: Check checksums in software for incoming UDP packets.*/
#define CHECKSUM_CHECK_UDP 1
/* CHECKSUM_CHECK_TCP==1: Check checksums in software for incoming TCP packets.*/
#define CHECKSUM_CHECK_TCP 1
#endif
/* LWIP_NETCONN==1: Enable Netconn API (require to use api_lib.c) */
#define LWIP_NETCONN 0
#define LWIP_NETCONN_FULLDUPLEX 0
/* LWIP_SOCKET==1: Enable Socket API (require to use sockets.c) */
#define LWIP_SOCKET 0
#define LWIP_COMPAT_MUTEX 0
/*##############################################################################################*/
#define LWIP_DEBUG 1
#define LWIP_DBG_MIN_LEVEL LWIP_DBG_LEVEL_ALL //LWIP_DBG_LEVEL_WARNING //LWIP_DBG_LEVEL_ALL
#define LWIP_DBG_TYPES_ON LWIP_DBG_ON
#define ICMP_DEBUG LWIP_DBG_OFF
#define IGMP_DEBUG LWIP_DBG_OFF
#define MEM_DEBUG LWIP_DBG_OFF
#define MEMP_DEBUG LWIP_DBG_OFF
#define TIMERS_DEBUG LWIP_DBG_OFF
#define TCP_DEBUG LWIP_DBG_OFF
#define TCP_INPUT_DEBUG LWIP_DBG_OFF
#define TCP_FR_DEBUG LWIP_DBG_OFF
#define TCP_RTO_DEBUG LWIP_DBG_OFF
#define TCP_CWND_DEBUG LWIP_DBG_OFF
#define TCP_WND_DEBUG LWIP_DBG_OFF
#define TCP_OUTPUT_DEBUG LWIP_DBG_OFF
#define TCP_RST_DEBUG LWIP_DBG_OFF
#define TCP_QLEN_DEBUG LWIP_DBG_OFF
#define UDP_DEBUG LWIP_DBG_OFF
#define DHCP_DEBUG LWIP_DBG_OFF
#define SSDP_DEBUG LWIP_DBG_ON
#define REST_DEBUG LWIP_DBG_ON
#define ALTCP_MBEDTLS_LIB_DEBUG LWIP_DBG_ON
#define LWIP_IPV4 1
#define LWIP_IPV6 0
#define LWIP_UDP 1
#define LWIP_TCP 1
#define LWIP_DNS 0
#define LWIP_RAW 0
#define LWIP_AUTOIP 0
#define LWIP_IGMP 1
#define TCP_LISTEN_BACKLOG 4
#define LWIP_SINGLE_NETIF 1
#define LWIP_NETBIOS_RESPOND_NAME_QUERY 1
#define LWIP_RAND() ((u32_t)rand())
#define LWIP_CHECKSUM_ON_COPY 1
#define LWIP_TCPIP_TIMEOUT 1
#define LWIP_ALTCP 1
#if (ENABLE_HTTPS > 0)
#define LWIP_ALTCP_TLS 1
#define LWIP_ALTCP_TLS_MBEDTLS 1
#else
#define LWIP_ALTCP_TLS 0
#define LWIP_ALTCP_TLS_MBEDTLS 0
#endif
#define ALTCP_MBEDTLS_DEBUG LWIP_DBG_ON
//#define ALTCP_MBEDTLS_SESSION_CACHE_TIMEOUT_SECONDS (3*60)
#define LWIP_SO_SNDTIMEO 1
#define LWIP_SO_RCVTIMEO 1
#define LWIP_SO_RCVBUF 1
#define HTTPD_SERVER_AGENT "Straight httpd/1.1"
#define PACK_STRUCT_USE_INCLUDES 1
#define LWIP_NO_INTTYPES_H 1
/*##############################################################################################*/
void LwipLogPrint(char* format, ... );
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include <string.h>
#ifdef WIN32
//C4103: alignment changed after including header, may be due to missing #pragma pack(pop)
#pragma warning(disable:4103)
#endif
#endif /* __LWIPOPTS_H__ */
|
straight-coding/straight-httpd-lwip-mbedtls-simulator
|
straight-httpd/straight-httpd/straight-httpd.c
|
<filename>straight-httpd/straight-httpd/straight-httpd.c<gh_stars>1-10
/*
straight-httpd.c
Author: <NAME><<EMAIL>>
Date: April 12, 2020
*/
#include <stdlib.h>
#include <stdio.h>
#include <conio.h>
#include <time.h>
#include "../../lwip-port/win32/arch/port.h"
#include "ssdp/ssdp.h"
#include "lwip/apps/netbiosns.h"
#pragma warning(disable:4996)
extern void LogPrint(int level, char* format, ...);
extern void sys_init();
extern void PrintLwipStatus(void);
extern void tcp_kill_all(void);
extern void WEB_fs_init(void);
extern void SetupHttpContext(void);
extern struct altcp_pcb* HttpdInit(int tls, unsigned long port);
extern int HttpdStop(struct altcp_pcb *pcbListen);
extern void SessionClearAll(void);
extern void SessionCheck(long long tick);
#include <winsock2.h>
#pragma comment(lib, "Ws2_32.lib")
#include "pcap.h"
#pragma comment(lib, "../../pcap/lib/Packet.lib")
#pragma comment(lib, "../../pcap/lib/wpcap.lib")
pcap_t* g_hPcap = NULL;
long g_nKeepRunning = 0;
HANDLE g_appThread = NULL;
DWORD WINAPI AppThread(void* data);
extern long g_ipIsReady;
HANDLE g_dmaQLock = NULL;
long g_qLength = 0;
struct packet_wrapper* g_dmaQueue = NULL;
void DMA_push(const struct pcap_pkthdr* packet_header, const u_char* packet)
{
struct packet_wrapper* newPacket = (struct packet_wrapper*)malloc(sizeof(struct packet_wrapper));
if (newPacket == NULL)
return;
newPacket->packet = (unsigned char*)malloc(packet_header->caplen);
if (newPacket->packet == NULL)
{
free(newPacket);
return;
}
newPacket->next = NULL;
newPacket->len = packet_header->caplen;
memcpy(newPacket->packet, packet, packet_header->caplen);
if (g_dmaQLock != NULL)
WaitForSingleObject(g_dmaQLock, INFINITE);
if (g_qLength < MAX_DMA_QUEUE)
{
g_qLength++;
if (g_dmaQueue == NULL)
{
g_dmaQueue = newPacket;
}
else
{
struct packet_wrapper* prev = g_dmaQueue;
while (prev->next != NULL)
prev = (struct packet_wrapper*)prev->next;
prev->next = newPacket;
}
}
else
{
printf("Packet queue is full: length = %d\n", g_qLength);
}
if (g_dmaQLock != NULL)
ReleaseMutex(g_dmaQLock);
NotifyFromEthISR(); //send event to lwip thread
}
struct packet_wrapper* DMA_pop()
{
struct packet_wrapper* pkt = NULL;
if (g_dmaQLock != NULL)
WaitForSingleObject(g_dmaQLock, INFINITE);
if (g_dmaQueue != NULL)
{
pkt = g_dmaQueue;
g_dmaQueue = (struct packet_wrapper*)g_dmaQueue->next;
pkt->next = NULL; //just the first packet
g_qLength--;
//printf("Packet consumed: length = %d\n", g_qLength);
}
if (g_dmaQLock != NULL)
ReleaseMutex(g_dmaQLock);
return pkt;
}
void DMA_free(struct packet_wrapper* pkt)
{
struct packet_wrapper* prev = pkt;
while(prev != NULL)
{
struct packet_wrapper* next = (struct packet_wrapper*)prev->next;
if (prev->packet != NULL)
free(prev->packet);
free(prev);
prev = next;
}
}
unsigned char* NIC_GetBuffer(int size)
{
unsigned char* buf = (unsigned char*)malloc(size);
//LogPrint(0, "NIC_GetBuffer...\r\n");
return buf;
}
long NIC_Send(unsigned char *buf, int size)
{
long nSent = -1;
//LogPrint(0, "NIC_Send...\r\n");
if ((g_hPcap != NULL) && (buf != NULL))
{
nSent = pcap_sendpacket(g_hPcap, buf, size);
if (nSent == PCAP_ERROR)
{
LogPrint(0, "pcap_sendpacket failed: %s, len=%d\r\n", pcap_geterr(g_hPcap), size);
}
}
if (buf != NULL)
free(buf);
//LogPrint(0, "NIC_Send done\r\n");
return nSent;
}
int main(int argc, char* argv[])
{
int i = 0;
bpf_u_int32 ip;
bpf_u_int32 subnet_mask;
struct in_addr address;
DWORD exitCode = 0;
// struct bpf_program filterCompile;
char szError[PCAP_ERRBUF_SIZE];
pcap_if_t *allDevices, *dev;
char szHostName[256];
char szHostIP[128];
char szHostSubnet[128];
char szFilter[512];
if (argc > 0)
{ //D:\straight\straight-httpd\straight-httpd\Debug\straight-httpd.exe
char drive[_MAX_DRIVE];
char dir[_MAX_DIR];
char fname[_MAX_FNAME];
char ext[_MAX_EXT];
char path[_MAX_PATH];
_splitpath(argv[0], drive, dir, fname, ext );
if (dir[strlen(dir)-1] == '\\')
dir[strlen(dir)-1] = 0;
sprintf(path, "%s%s", drive, dir);
_splitpath(path, drive, dir, fname, ext );
sprintf(path, "%s%s", drive, dir);
for(i = 0; i < (int)strlen(path); i ++)
{
if (path[i] == '\\')
path[i] = '/'; //D:/straight/straight-httpd/straight-httpd/
}
if (strnicmp(path, "D:/straight/straight-httpd/straight-httpd/straight-httpd/httpd/", strlen(path)) != 0)
{
int key = 0;
printf("Please change LOCAL_WEBROOT(in http_fs.c) to \r\n\t%sstraight-httpd/httpd/cncweb/\r\n", path);
printf("Please change both UPLOAD_TO_FOLDER(in cgi_upload.c) and FOLDER_TO_LIST(in cgi_files.c) to \r\n\t%sstraight-httpd/httpd/cncweb/app/cache/\n", path);
printf("Please press any key to quit\n ");
key = _getch();
exit(1);
}
}
memset(szHostName, 0, sizeof(szHostName));
memset(szFilter, 0, sizeof(szFilter));
if (pcap_findalldevs(&allDevices, szError) == -1)
{
fprintf(stderr, "Error in pcap_findalldevs: %s\n", szError);
{
int key = 0;
printf("Please press any key to quit\n ");
key = _getch();
}
exit(1);
}
printf("Here is a list of available devices on your system:\n\n");
for (dev = allDevices; dev != NULL; dev = dev->next)
{
bpf_u_int32 ipValid = 0;
char* pStr;
pcap_addr_t *dev_addr;
if ((dev->flags & PCAP_IF_LOOPBACK) != 0)
continue;
if ((dev->flags & PCAP_IF_UP) == 0)
continue;
if ((dev->flags & PCAP_IF_RUNNING) == 0)
continue;
if ((dev->flags & PCAP_IF_CONNECTION_STATUS_CONNECTED) == 0)
continue;
//#define PCAP_IF_LOOPBACK 0x00000001 /* interface is loopback */
//#define PCAP_IF_UP 0x00000002 /* interface is up */
//#define PCAP_IF_RUNNING 0x00000004 /* interface is running */
//#define PCAP_IF_WIRELESS 0x00000008 /* interface is wireless (*NOT* necessarily Wi-Fi!) */
//#define PCAP_IF_CONNECTION_STATUS 0x00000030 /* connection status: */
//#define PCAP_IF_CONNECTION_STATUS_UNKNOWN 0x00000000 /* unknown */
//#define PCAP_IF_CONNECTION_STATUS_CONNECTED 0x00000010 /* connected */
//#define PCAP_IF_CONNECTION_STATUS_DISCONNECTED 0x00000020 /* disconnected */
//#define PCAP_IF_CONNECTION_STATUS_NOT_APPLICABLE 0x00000030 /* not applicable */
if ((dev->description == NULL) || (strlen(dev->description) <= 0))
continue;
if (strstr(dev->description, "NdisWan") != NULL)
continue;
if (strstr(dev->description, "VMware") != NULL)
continue;
if (strstr(dev->description, "Oracle") != NULL)
continue;
for (dev_addr = dev->addresses; dev_addr != NULL; dev_addr = dev_addr->next)
{
if ((dev_addr->addr->sa_family == AF_INET) && dev_addr->addr && dev_addr->netmask)
{
if (((struct sockaddr_in *)dev_addr->addr)->sin_addr.S_un.S_addr == 0)
continue;
printf("%d. %s\n", ++i, dev->description);
printf(" Found a device %s on address %s with netmask %s, broadaddr %s\n", dev->name,
inet_ntoa(((struct sockaddr_in *)dev_addr->addr)->sin_addr),
inet_ntoa(((struct sockaddr_in *)dev_addr->netmask)->sin_addr),
inet_ntoa(((struct sockaddr_in *)dev_addr->broadaddr)->sin_addr));
ipValid = ((struct sockaddr_in *)dev_addr->addr)->sin_addr.S_un.S_addr;
break;
}
}
if (ipValid == 0)
continue;
if (-1 == pcap_lookupnet(dev->name, &ip, &subnet_mask, szError))
{
printf("%s\n", szError);
continue;
}
address.s_addr = ip;
pStr = inet_ntoa(address);
if (pStr == NULL)
continue;
strcpy(szHostIP, pStr);
if (strstr(szHostIP, "0.0.0.0") == szHostIP)
continue;
if (strstr(szHostIP, "127.0.") == szHostIP)
continue;
if (strstr(szHostIP, "169.254.") == szHostIP)
continue;
address.s_addr = subnet_mask;
pStr = inet_ntoa(address);
if (pStr == NULL)
continue;
strcpy(szHostSubnet, pStr);
strcpy(szHostName, dev->name);
printf(" Selected Host: %s\n", szHostName);
printf(" IP address: %s, %08lX\n", szHostIP, ip);
printf(" Subnet Mask: %s\n", szHostSubnet);
//break;
}
pcap_freealldevs(allDevices);
g_hPcap = pcap_open(szHostName,
65536,
PCAP_OPENFLAG_PROMISCUOUS | PCAP_OPENFLAG_MAX_RESPONSIVENESS,
100,
NULL,
szError);
if (g_hPcap == NULL)
{
fprintf(stderr, "\nUnable to open the adapter. \r\nYou may need to install the npcap driver from https://nmap.org/npcap/dist/npcap-0.9995.exe\r\n");
{
int key = 0;
printf("Please press any key to quit\n ");
key = _getch();
}
return -2;
}
pcap_setdirection(g_hPcap, PCAP_D_INOUT);
pcap_setmode(g_hPcap, MODE_MON);// MODE_CAPT);
g_dmaQLock = CreateMutex(NULL, FALSE, NULL);
InterlockedExchange(&g_nKeepRunning, 1);
g_appThread = CreateThread(NULL, 0, AppThread, NULL, 0, NULL);
//g_mainThread = CreateThread(NULL, 0, LwipLoopThread, NULL, 0, NULL);
if (g_appThread != NULL)
printf("Please press ESC key to quit\n ");
sys_init();
while(g_appThread != NULL)
{
struct pcap_pkthdr* pkt_header;
u_char* pkt_data;
int result = pcap_next_ex(g_hPcap, &pkt_header, &pkt_data);
/*
1 if the packet has been read without problems
0 if the timeout set with pcap_open_live() has elapsed. In this case pkt_header and pkt_data don't point to a valid packet
-1 if an error occurred
-2 if EOF was reached reading from an offline capture
*/
if (result == 1)
DMA_push(pkt_header, pkt_data);
{
int key = 0;
if (_kbhit()) //check key press
{
key = _getch();
if (key == 27)
{
InterlockedExchange(&g_nKeepRunning, 1);
Sleep(100);
break;
}
}
}
if (!GetExitCodeThread(g_appThread, &exitCode))
break;
if ((exitCode & STILL_ACTIVE) == 0)
break;
}
pcap_close(g_hPcap);
if (g_appThread != NULL)
CloseHandle(g_appThread);
//free the packet queue
while (TRUE)
{
struct packet_wrapper* pkt = NULL;
pkt = DMA_pop();
if (pkt == NULL)
break;
DMA_free(pkt);
}
}
extern struct netif main_netif;
struct altcp_pcb *g_pcbListen80 = NULL;
struct altcp_pcb *g_pcbListen443 = NULL;
extern void tcp_kill_all(void);
DWORD WINAPI AppThread(void* data)
{
InitDevInfo(NULL); //initiate device settings
WEB_fs_init(); //initiate file system in memory
SetupHttpContext(); //initiate http receiving context
LwipInit(); //initiate lwip stack and start dhcp
while (g_nKeepRunning)
{
SessionClearAll(); //clear http session context
while (g_ipIsReady == 0)
{
if (tcpip_inloop() > 0)
continue;
SessionCheck(GetTickCount64());
}
PrintLwipStatus();
netbiosns_set_name("lwipSimu");// GetDeviceName());
netbiosns_init();
ssdpInit(&main_netif);
g_pcbListen80 = HttpdInit(0, 80);
g_pcbListen443 = HttpdInit(1, 443);
LogPrint(0, "App Service started\r\n");
PrintLwipStatus();
while(TRUE)
{
if (g_ipIsReady == 0)
break;
if (tcpip_inloop() > 0)
continue;
SessionCheck(GetTickCount64());
}
if (g_pcbListen80 != NULL)
HttpdStop(g_pcbListen80);
if (g_pcbListen443 != NULL)
HttpdStop(g_pcbListen443);
LogPrint(0, "App Service stopped\r\n");
ssdpDown();
netbiosns_stop();
PrintLwipStatus();
tcp_kill_all();
if (g_ipIsReady == 0)
break;
}
LwipStop();
return 0;
}
|
straight-coding/straight-httpd-lwip-mbedtls-simulator
|
straight-httpd/straight-httpd/utils.c
|
<filename>straight-httpd/straight-httpd/utils.c
/*
utils.c
Author: <NAME><<EMAIL>>
Date: April 12, 2020
*/
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#ifdef WIN32
#include <direct.h>
#endif
#include "utils.h"
static const TypeHeader contentTypes[] = {
{ "html", "text/html"},
{ "htm", "text/html"},
{ "shtml", "text/html"},
{ "shtm", "text/html"},
{ "ssi", "text/html"},
{ "css", "text/css"},
{ "json", "application/json"},
{ "js", "application/javascript"},
{ "gif", "image/gif"},
{ "png", "image/png"},
{ "jpg", "image/jpeg"},
{ "bmp", "image/bmp"},
{ "ico", "image/x-icon"},
{ "mp4", "video/mp4"},
{ "flv", "video/x-flv"},
{ "3gp", "video/3gpp"},
{ "mov", "video/quicktime"},
{ "avi", "video/x-msvideo"},
{ "wmv", "video/x-ms-wmv"},
{ "class", "application/octet-stream"},
{ "cls", "application/octet-stream"},
{ "swf", "application/x-shockwave-flash"},
{ "ram", "application/javascript"},
{ "pdf", "application/pdf"},
{ "xml", "text/xml"},
{ "xsl", "text/xml"},
{ "", "text/plain"}
};
long ston(unsigned char* s)
{
long sign = +1;
long result = 0;
char* p = (char*)s;
if ((p == 0) || (*p == 0))
return result;
while ((*p != 0) && ((*p == ' ') || (*p == '\t')))
{
p++;
}
if (p[0] == '-')
{
p++;
sign = -1;
}
if (p[0] == '+')
{
p++;
}
while ((*p != 0) && (*p >= '0') && (*p <= '9'))
{
result *= 10;
result += (*p - '0');
p++;
}
return (sign*result);
}
void ntos(long n, unsigned char* s)
{
const unsigned char hex_alpha[16] = "0123456789";
unsigned long i, first, div, remain;
i = 0;
if (n == 0)
{
s[i++] = '0';
s[i] = 0;
return;
}
if (n < 0)
{
s[i++] = '-';
n *= (-1);
}
first = 1;
div = 1000000000;
while (1)
{
remain = n / div;
if (remain != 0)
{
n -= (div*remain);
first = 0;
}
if (first == 0)
{
s[i++] = hex_alpha[remain];
s[i] = 0;
}
if (div == 1)
break;
div /= 10;
}
}
int ToLower(int nChar)
{
unsigned char cTemp = (unsigned char)nChar;
if ((cTemp >= 'A') && (cTemp <= 'Z'))
cTemp |= 0x20;
return cTemp;
}
int ToUpper(int nChar)
{
unsigned char cTemp = (unsigned char)nChar;
if ((cTemp >= 'a') && (cTemp <= 'z'))
cTemp &= 0xDF;
return cTemp;
}
int token_match(const char *s1, const char *s2)
{
int c1;
int c2;
int end1 = 0;
int end2 = 0;
for (;;)
{
c1 = *s1++;
c2 = *s2++;
if (isalpha(c1) && isupper(c1)) //alphabet
c1 = tolower(c1);
if (isalpha(c2) && isupper(c2)) //alphabet
c2 = tolower(c2);
end1 = !(isalnum(c1) || (c1 == '_') || (c1 == '-')); //not (alphabet and number)
end2 = !(isalnum(c2) || (c2 == '_') || (c2 == '-')); //not (alphabet and number)
if (end1 || end2 || (c1 != c2))
break;
}
return end1 && end2;
}
int Strnicmp(char *str1, char *str2, int n)
{
while (*str1 && *str2 && n)
{
int res = ToUpper((unsigned)*str1) - ToUpper((unsigned)*str2);
if (res)
return res < 0 ? -1 : 1;
str1++;
str2++;
n--;
}
if (n == 0) return 0;
if (*str1) return 1;
if (*str2) return -1;
return 0;
}
void TrimFloat(char* floatString)
{
int len = strlen(floatString);
if (strchr(floatString, '.') <= 0)
return;
while (len > 0)
{
if (floatString[len - 1] != '0')
{
if (floatString[len - 1] == '.')
floatString[len - 1] = 0;
break;
}
floatString[len - 1] = 0;
len--;
}
}
char* base64Chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
int DecodeB64(unsigned char* data)
{
int i = 0;
int resultCount = 0;
int validCount = 0;
int value = 0;
unsigned long convered = 0;
while (data[i] != 0)
{
if ((data[i] == '\r') || (data[i] == '\n') || (data[i] == '='))
{ //ingnored
i++;
continue;
}
if ((data[i] >= 'A') && (data[i] <= 'Z'))
{
value = (int)(data[i] - 'A');
}
else if ((data[i] >= 'a') && (data[i] <= 'z'))
{
value = (int)(data[i] - 'a' + 26);
}
else if ((data[i] >= '0') && (data[i] <= '9'))
{
value = (int)(data[i] - '0' + 52);
}
else if (data[i] == '+')
{
value = 62;
}
else if (data[i] >= '/')
{
value = 63;
}
else
{ //bad character
return 0;
}
i++;
validCount++;
convered <<= 6;
convered += value;
if ((validCount & 0x3) == 0)
{
data[resultCount+0] = (unsigned char)((convered >> 16) & 0xFF);
data[resultCount+1] = (unsigned char)((convered >> 8) & 0xFF);
data[resultCount+2] = (unsigned char)((convered) & 0xFF);
resultCount += 3;
convered = 0;
}
}
if ((validCount & 0x3) == 3)
{
data[resultCount + 0] = (unsigned char)((convered >> 10) & 0xFF);
data[resultCount + 1] = (unsigned char)((convered >> 2) & 0xFF);
resultCount += 2;
}
else if ((validCount & 0x3) == 2)
{
data[resultCount] = (unsigned char)((convered >> 4) & 0xFF);
resultCount ++;
}
else if ((validCount & 0x3) == 1)
{
}
data[resultCount] = 0;
return resultCount;
}
int Hex2Int(char c)
{
char* set = "00112233445566778899AaBbCcDdEeFf";
int i = 0;
while (set[i] != 0)
{
if (c == set[i])
return (i>>1);
i++;
}
return -1;
}
int URLDecode(char* url)
{
int i = 0;
int len = strlen(url);
while((i < len) && (url[i] != 0))
{
if (url[i] != '%')
{
i++;
continue;
}
if (i < len - 2)
{
int a = Hex2Int(url[i + 1]);
int b = Hex2Int(url[i + 2]);
if ((a >= 0) && (b >= 0))
{
a = (a << 4) + b;
url[i] = a;
memmove(url + i + 1, url + i + 3, len - i - 3);
len -= 2;
i++;
continue;
}
}
i++;
}
return i;
}
char* GetContentType(const char* extension)
{
int i = 0;
int extLen = strlen(extension);
while (1)
{
int typeLen = strlen(contentTypes[i].extension);
if (typeLen == 0)
return contentTypes[i].content_type;
if (typeLen == extLen)
{
if (Strnicmp((char*)extension, contentTypes[i].extension, typeLen) == 0)
return contentTypes[i].content_type;
}
i++;
}
}
unsigned long GetIpAddress(char* addr)
{
unsigned char* p = (unsigned char*)addr;
unsigned long ip = (unsigned char)ston(p);
p = strchr(p, '.');
if (p != NULL)
{
p ++; ip <<= 8; ip += ston(p);
p = strchr(p, '.');
if (p != NULL)
{
p ++; ip <<= 8; ip += ston(p);
p = strchr(p, '.');
if (p != NULL)
{
p++; ip <<= 8; ip += ston(p);
}
}
}
return ip;
}
|
straight-coding/straight-httpd-lwip-mbedtls-simulator
|
lwip-port/win32/arch/port.h
|
/*
port.h
Author: <NAME><<EMAIL>>
Date: April 12, 2020
*/
#ifndef _PORT_H_
#define _PORT_H_
///////////////////////////////////////////////////////////////////////////////////////////
// Network
///////////////////////////////////////////////////////////////////////////////////////////
#define MAX_DMA_QUEUE 1024
struct packet_wrapper
{
long len;
unsigned char* packet; /* allocated */
void* next; /* next packet */
};
typedef struct _DeviceConfig
{
unsigned long nDhcpEnabled;// = 1;// 0 or 1;
unsigned long dwIP;// = 0; // 0xC0A80563;
unsigned long dwSubnet;// = 0; // 0xFFFFFF00;
unsigned long dwGateway;// = 0; // 0xC0A80501;
long nLog;// = 0;
long nSessionTimeout;// = 3 * 60 * 1000;
char szColor[16];// = { 0 };
char szDate[16];// = { 0 };
char szFont[16];// = { 0 };
char szLocation[16];// = { 0 };
}DeviceConfig;
void LwipInit(void);
void LwipStop(void);
extern int tcpip_inloop(void);
void InitDevInfo(unsigned long* cpuSN);
struct packet_wrapper* DMA_pop();
void DMA_free(struct packet_wrapper* pkt);
unsigned char* NIC_GetBuffer(int size);
long NIC_Send(unsigned char *buf, int size);
void NotifyFromEthISR();
///////////////////////////////////////////////////////////////////////////////////////////
// Network
///////////////////////////////////////////////////////////////////////////////////////////
void LoadConfig4Edit();
void AppyConfig();
unsigned char* GetMyMAC(void);
int FillMAC(void* context, char* buffer, int maxSize);
unsigned long GetMyIP(void);
int FillIP(void* context, char* buffer, int maxSize);
void SetMyIPLong(unsigned long addr);
void SetMyIP(char* addr);
unsigned long GetGateway(void);
int FillGateway(void* context, char* buffer, int maxSize);
void SetGatewayLong(unsigned long addr);
void SetGateway(char* addr);
unsigned long GetSubnet(void);
int FillSubnet(void* context, char* buffer, int maxSize);
void SetSubnetLong(unsigned long addr);
void SetSubnet(char* addr);
unsigned long IsDhcpEnabled();
int FillDhcp(void* context, char* buffer, int maxSize);
void SetDhcpEnabled(char* value);
void OnDhcpFinished(void);
long GetSessionTimeout();
int FillSessionTimeout(void* context, char* buffer, int maxSize);
void SetSessionTimeout(char* value);
///////////////////////////////////////////////////////////////////////////////////////////
// Device
///////////////////////////////////////////////////////////////////////////////////////////
char* GetVendor(void);
char* GetVendorURL(void);
char* GetModel(void);
char* GetModelURL(void);
char* GetDeviceName(void);
char* GetDeviceSN(void);
char* GetDeviceUUID(void);
char* GetDeviceVersion(void);
char* GetLocation();
void SetLocation(char* value);
char* GetColor();
void SetColor(char* value);
char* GetDate();
void SetDate(char* value);
char* GetFont();
void SetFont(char* value);
int FillLog(void* context, char* buffer, int maxSize);
void SetLog(char* value);
#endif
|
vineetrc/CS411EC
|
Join.h
|
<reponame>vineetrc/CS411EC
#pragma once
#include <cmath>
#include <string>
#include <vector>
class Join {
public:
Join(std::string input1, std::string input2, std::string joinkey);
void LoopJoin(std::string output);
void HashJoin(std::string output);
private:
std::vector< std::vector<std::string> > table1;
std::vector< std::vector<std::string> > table2;
std::vector<std::string> cols1;
std::vector<std::string> cols2;
int join_key_idx1;
int join_key_idx2;
std::string joinkey;
};
|
josuegaleas/JayKey
|
Firmware/config.h
|
<reponame>josuegaleas/JayKey<filename>Firmware/config.h
/*
* Author: <NAME>
* Last Edit: 2019.11.09
*/
#ifndef CONFIG_H
#define CONFIG_H
#define VENDOR_ID 0xDEAD
#define PRODUCT_ID 0x0001
#define DEVICE_VER 0x0002
#define MANUFACTURER Josue Galeas
#define PRODUCT JayK
#define DESCRIPTION Firmware for JayK
#define MATRIX_ROWS 5
#define MATRIX_COLS 21
#define MATRIX_HAS_GHOST
#endif /* CONFIG_H */
|
bferguson3/quasi88-port
|
src/SDL2/graph.c
|
/***********************************************************************
* �����ե��å����� (�����ƥ���¸)
*
* �ܺ٤ϡ� graph.h ����
************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <SDL.h>
#include "quasi88.h"
#include "graph.h"
#include "device.h"
/************************************************************************/
/*#define DEBUG_PRINTF*/
/* �ʲ��� static ���ѿ������ץ��������ѹ��Ǥ����Τǥ������Х��ˤ��Ƥ��� */
int use_hwsurface = TRUE; /* HW SURFACE ���Ȥ����ɤ��� */
int use_doublebuf = FALSE; /* ���֥��Хåե����Ȥ����ɤ��� */
/* �ʲ��ϡ� event.c �ʤɤǻ��Ѥ��롢 OSD �ʥ������Х��ѿ� */
int sdl_mouse_rel_move; /* �ޥ������а�ư�̸��β�ǽ�� */
/************************************************************************/
static T_GRAPH_SPEC graph_spec; /* ���ܾ��� */
static int graph_exist; /* ���ǡ����������Ѥ� */
static T_GRAPH_INFO graph_info; /* ���λ��Ρ����̾��� */
/************************************************************************
* SDL�����
* SDL�ν�λ
************************************************************************/
int sdl_init(void)
{
SDL_version libver;
SDL_GetVersion(&libver);
if (verbose_proc) {
printf("Initializing SDL (%d.%d.%d) ... ",
libver.major, libver.minor, libver.patch); fflush(NULL);
}
if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_AUDIO) < 0) {
if (verbose_proc) printf("Failed\n");
fprintf(stderr, "SDL Error: %s\n", SDL_GetError());
return FALSE;
} else {
if (verbose_proc) printf("OK\n");
return TRUE;
}
}
/************************************************************************/
void sdl_exit(void)
{
SDL_Quit();
}
/************************************************************************
* �����ե��å������ν�����
* �����ե��å�������ư��
* �����ե��å������ν�λ
************************************************************************/
static char sdl_vname[16];
static int sdl_depth;
static int sdl_byte_per_pixel;
static SDL_Rect **sdl_mode;
static Uint32 sdl_mode_flags;
const T_GRAPH_SPEC *graph_init(void)
{
/*int win_w, win_h;
int ful_w, ful_h;
int i;
const SDL_VideoInfo *vi;
sdl_vname[0] = '\0';
SDL_VideoDriverName(sdl_vname, sizeof(sdl_vname));
vi = SDL_GetVideoInfo();
if (verbose_proc) {
printf("Initializing Graphic System (SDL:%s) ... \n", sdl_vname);
}
// �����٤ȡ��ԥ����뤢�����ΥХ��ȿ��������å�
sdl_depth = vi->vfmt->BitsPerPixel;
sdl_byte_per_pixel = vi->vfmt->BytesPerPixel;
#if defined(SUPPORT_16BPP) && defined(SUPPORT_32BPP)
if (sdl_byte_per_pixel == 2 ||
sdl_byte_per_pixel == 4) {
; // OK
} else {
sdl_depth = 16;
sdl_byte_per_pixel = 2;
}
#elif defined(SUPPORT_16BPP)
sdl_depth = 16;
sdl_byte_per_pixel = 2;
#elif defined(SUPPORT_32BPP)
sdl_depth = 32;
sdl_byte_per_pixel = 4;
#endif
#ifdef DEBUG_PRINTF
printf(" <VideoInfo> %s\n", sdl_vname);
printf(" hw_available %d ", vi->hw_available);
printf(" wm_available %d\n", vi->wm_available);
printf(" blit_hw %d ", vi->blit_hw );
printf(" blit_hw_CC %d ", vi->blit_hw_CC );
printf(" blit_hw_A %d\n", vi->blit_hw_A );
printf(" blit_sw %d ", vi->blit_sw );
printf(" blit_sw_CC %d ", vi->blit_sw_CC );
printf(" blit_sw_A %d\n", vi->blit_sw_A );
printf(" blit_fill %d ", vi->blit_fill );
printf(" video_mem %d\n", vi->video_mem );
printf(" palette %p\n", vi->vfmt->palette );
printf(" BitsPerPixel %2d ", vi->vfmt->BitsPerPixel );
printf(" BytesPerPixel %2d\n", vi->vfmt->BytesPerPixel );
printf(" Rmask %8x ", vi->vfmt->Rmask );
printf(" Gmask %8x ", vi->vfmt->Gmask );
printf(" Bmask %8x ", vi->vfmt->Bmask );
printf(" Amask %8x\n", vi->vfmt->Amask );
printf(" Rshift %2d ", vi->vfmt->Rshift );
printf(" Gshift %2d ", vi->vfmt->Gshift );
printf(" Bshift %2d ", vi->vfmt->Bshift );
printf(" Ashift %2d\n", vi->vfmt->Ashift );
printf(" Rloss %d ", vi->vfmt->Rloss );
printf(" Gloss %d ", vi->vfmt->Gloss );
printf(" Bloss %d ", vi->vfmt->Bloss );
printf(" Aloss %d\n", vi->vfmt->Aloss );
printf(" colorkey %x ", vi->vfmt->colorkey );
printf(" alpha %d\n", vi->vfmt->alpha );
printf("\n");
#endif
// ���Ѳ�ǽ�ʥ������ɥ��Υ�������Ĵ�٤Ƥ���
for (i = 0; i < 2; i++) {
Uint32 flags = 0;
int w, h;
if (i == 0) flags = 0; // 1���ܤϥ������ɥ���
else flags = SDL_FULLSCREEN; // 2���ܤ������̤������å�
if (use_hwsurface) flags |= SDL_HWPALETTE | SDL_HWSURFACE;
else flags |= SDL_HWPALETTE | SDL_SWSURFACE;
if (use_doublebuf) flags |= SDL_DOUBLEBUF;
// ���Ѳ�ǽ�ʺ��祵����������
sdl_mode = SDL_ListModes(NULL, flags);
if (sdl_mode == (SDL_Rect**) 0) { // ���⡼���Բ�
w = 0;
h = 0;
} else if (sdl_mode == (SDL_Rect**)-1) { // ���⡼�ɲ�
w = 10000;
h = 10000;
} else { // �⡼�ɤ������å�
w = sdl_mode[0]->w; // �ǽ餬
h = sdl_mode[0]->h; // ������
#ifdef DEBUG_PRINTF
{
int j;
for (j=0; sdl_mode[j]; j++)
printf(" %sSize %3d: %4d x %4d (%.4f)\n",
(i==0) ? "Window" : "Fullscreen", j, sdl_mode[j]->w,
sdl_mode[j]->h, (double)sdl_mode[j]->w/sdl_mode[j]->h);
}
#endif
}
if (i == 0) { win_w = w; win_h = h; }
else { ful_w = w; ful_h = h; }
sdl_mode_flags = flags;
}
// ���λ����ǡ� sdl_mode �ˤϡ������̻��Υ⡼�ɰ��������åȤ����Ƥ��롣
// sdl_mode_flags �ˤϡ������̻��Υ⡼�ɤΥե饰�����åȤ����Ƥ��롣
graph_spec.window_max_width = win_w;
graph_spec.window_max_height = win_h;
graph_spec.fullscreen_max_width = ful_w;
graph_spec.fullscreen_max_height = ful_h;
graph_spec.forbid_status = FALSE;
graph_spec.forbid_half = FALSE;
if (verbose_proc)
printf(" INFO:%dbpp(%dbyte), Maxsize=win(%d,%d),full(%d,%d)\n",
sdl_depth, sdl_byte_per_pixel, win_w, win_h, ful_w, ful_h);
return &graph_spec;*/
// FIXME: identify available video modes (SDL_GetDisplayMode)
// The maximum render size (double) is 1280x800, so
// 1296 x 816 (per x16) gives a small border for those who want it
// Currently this does nothing to limit -height/-width
graph_spec.window_max_width = 1296;
graph_spec.window_max_height = 816;
graph_spec.fullscreen_max_width = 0;
graph_spec.fullscreen_max_height = 0;
graph_spec.forbid_status = FALSE;
graph_spec.forbid_half = FALSE;
return &graph_spec;
}
/************************************************************************/
static int search_mode(int w, int h, double aspect);
//static SDL_Surface *sdl_display;
static SDL_Surface *sdl_offscreen;
static SDL_Texture *sdl_texture;
static SDL_Window *sdl_window;
static SDL_Renderer* sdl_renderer;
const T_GRAPH_INFO *graph_setup(int width, int height,
int fullscreen, double aspect)
{
/*Uint32 flags;
// �������ѹ��䡢�������ɥ������������ؤκݤϡ����� SDL_SetVideoMode() ��
// �Ƥ֤����������˰�ö�ӥǥ����֥����ƥ�����λ������ɬ�פ������餷��(?)��
// (�ӥǥ��ɥ饤�а�¸���� x11, windib, directx �ϡ���λ������)
if (graph_exist) {
if (verbose_proc) printf("Re-Initializing Graphic System (SDL:%s) ...",
sdl_vname);
if ((graph_info.fullscreen == FALSE && fullscreen == FALSE) &&
(! (sdl_display->flags & SDL_FULLSCREEN))) {
// �������ɥ��Υ������ѹ����ϡ���λ��ɬ�פϤʤ����������ġ�
if (verbose_proc) printf("\n");
} else {
SDL_QuitSubSystem(SDL_INIT_VIDEO);
graph_exist = FALSE;
}
}
// VIDEO����ö��λ�����ʤ顢VIDEO�κƽ�����
if (! SDL_WasInit(SDL_INIT_VIDEO)) {
if (SDL_InitSubSystem(SDL_INIT_VIDEO) != 0) {
if (verbose_proc) printf(" FAILED\n");
return NULL;
}
// VIDEO����ö��λ�����ȡ� sdl_mode ��̵���ˤʤ롣(�ǥХ����ˤ��롩)
sdl_mode = SDL_ListModes(NULL, sdl_mode_flags);
// sdl_mode �����Ƥ����������Ѥ��äƤ��ޤä����ɤ����褦��
if (verbose_proc) printf(" OK\n");
}
// �����̥⡼�ɤξ��硢Ŭ�ڤʥ⡼�ɤ�����
if (fullscreen) {
int fit = search_mode(width, height, aspect);
if (fit < 0) {
fullscreen = FALSE;
} else {
width = sdl_mode[fit]->w;
height = sdl_mode[fit]->h;
}
}
// �������ɥ��������̡ˤ�
if (verbose_proc) {
if (fullscreen) printf(" Trying full screen mode ... ");
else printf(" Opening window ... ");
}
if (fullscreen) flags = SDL_FULLSCREEN;
else flags = 0;
if (use_hwsurface) flags |= SDL_HWPALETTE | SDL_HWSURFACE;
else flags |= SDL_HWPALETTE | SDL_SWSURFACE;
if (use_doublebuf) flags |= SDL_DOUBLEBUF;
sdl_display = SDL_SetVideoMode(width, height, sdl_depth, flags);
if (verbose_proc)
printf("%s (%dx%d)\n", (sdl_display ? "OK" : "FAILED"), width, height);
if (sdl_display == NULL) return NULL;
// ��������Хåե�������
if (verbose_proc) printf(" Allocating screen buffer ... ");
sdl_offscreen = SDL_CreateRGBSurface(SDL_SWSURFACE,
width, height, sdl_depth,
0, 0, 0, 0);
if (verbose_proc) printf("%s\n", (sdl_offscreen ? "OK" : "FAILED"));
if (sdl_offscreen == NULL) return NULL;
// ���̾����åȤ��ơ��֤�
graph_info.fullscreen = fullscreen;
graph_info.width = sdl_offscreen->w;
graph_info.height = sdl_offscreen->h;
graph_info.byte_per_pixel = sdl_byte_per_pixel;
graph_info.byte_per_line = sdl_offscreen->pitch;
graph_info.buffer = sdl_offscreen->pixels;
graph_info.nr_color = 255;
graph_info.write_only = FALSE;
graph_info.broken_mouse = FALSE;
graph_info.draw_start = NULL;
graph_info.draw_finish = NULL;
graph_info.dont_frameskip = FALSE;
graph_exist = TRUE;
if (verbose_proc)
printf(" VideoMode %dx%d -> %dx%dx%d(%d) %c%c%c%c R:%x G:%x B:%x\n",
width, height, sdl_display->w, sdl_display->h,
sdl_display->format->BitsPerPixel,
sdl_display->format->BytesPerPixel,
(sdl_display->flags & SDL_SWSURFACE) ? 'S' : '-',
(sdl_display->flags & SDL_HWSURFACE) ? 'H' : 'S',
(sdl_display->flags & SDL_DOUBLEBUF) ? 'D' : '-',
(sdl_display->flags & SDL_FULLSCREEN) ? 'F' : '-',
sdl_display->format->Rmask,
sdl_display->format->Gmask, sdl_display->format->Bmask);
#if 0 // debug
printf("@ fullscreen %d\n", graph_info.fullscreen );
printf("@ width %d\n", graph_info.width );
printf("@ height %d\n", graph_info.height );
printf("@ byte_per_pixel %d\n", graph_info.byte_per_pixel);
printf("@ byte_per_line %d\n", graph_info.byte_per_line );
printf("@ buffer %p\n", graph_info.buffer );
printf("@ nr_color %d\n", graph_info.nr_color );
printf("@ write_only %d\n", graph_info.write_only );
printf("@ broken_mouse %d\n", graph_info.broken_mouse );
printf("@ dont_frameskip %d\n", graph_info.dont_frameskip);
#endif
return &graph_info;*/
// If the program (sdl) window size is not defined in the rc file
// then set the window size based on rc file's -half|-full|-double.
// If this is undefined, then the default is -full
static int sdl_width;
static int sdl_height;
static int render_width;
static int render_height;
if (screen_size == SCREEN_SIZE_FULL) {
sdl_width = 640;
sdl_height = 400;
render_width = 640;
render_height= 400;
}
if (screen_size == SCREEN_SIZE_DOUBLE) {
sdl_width = 1280;
sdl_height = 800;
render_width = 1280;
render_height = 800;
}
if (screen_size == SCREEN_SIZE_HALF) {
sdl_width = 320;
sdl_height = 200;
render_width = 320;
render_height = 200;
}
// try to avoid an rc defined screen size smaller than the render size
if ( WIDTH && HEIGHT ) {
sdl_width = WIDTH;
sdl_height = HEIGHT;
if ( sdl_width < render_width ) {
sdl_width = render_width;
sdl_height = render_height;
}
if ( sdl_height < render_height ) {
sdl_height = render_height;
sdl_width = render_width;
}
}
// FIXME HACK just trying to get this damn thing to work
sdl_window = SDL_CreateWindow("quasi88",
SDL_WINDOWPOS_UNDEFINED,
SDL_WINDOWPOS_UNDEFINED,
sdl_width, sdl_height, 0);
sdl_renderer = SDL_CreateRenderer(sdl_window, -1, 0);
sdl_offscreen = SDL_CreateRGBSurface(0, sdl_width, sdl_height, 32,
0x00ff0000,
0x0000ff00,
0x000000ff,
0xff000000);
sdl_texture = SDL_CreateTexture(
sdl_renderer,
SDL_PIXELFORMAT_ARGB8888,
SDL_TEXTUREACCESS_STREAMING,
sdl_width, sdl_height);
// HACKS
sdl_byte_per_pixel = 4;
graph_info.fullscreen = FALSE;
graph_info.width = sdl_offscreen->w;
graph_info.height = sdl_offscreen->h;
graph_info.byte_per_pixel = sdl_byte_per_pixel;
graph_info.byte_per_line = sdl_offscreen->pitch;
graph_info.buffer = sdl_offscreen->pixels;
graph_info.nr_color = 255;
graph_info.write_only = FALSE;
graph_info.broken_mouse = FALSE;
graph_info.draw_start = NULL;
graph_info.draw_finish = NULL;
graph_info.dont_frameskip = FALSE;
return &graph_info;
}
/*======================================================================*/
#define FABS(a) (((a) >= 0.0) ? (a) : -(a))
static int search_mode(int w, int h, double aspect)
{
int i;
int fit = -1;
int fit_w = 0, fit_h = 0;
double fit_a = 0.0;
for (i=0; sdl_mode[i]; i++) {
/* ���̥������˼��ޤäƤ��뤳�� */
if (w <= sdl_mode[i]->w &&
h <= sdl_mode[i]->h) {
int tmp_w = sdl_mode[i]->w;
int tmp_h = sdl_mode[i]->h;
double tmp_a = FABS(((double)tmp_w / tmp_h) - aspect);
/* �ǽ��˸��Ĥ��ä����Τ��ޤ��ϥ��祤�� */
if (fit == -1) {
fit = i;
fit_w = tmp_w;
fit_h = tmp_h;
fit_a = tmp_a;
} else {
/* �������ϡ������Τ����٤ơ������ե��åȤ����Х��祤�� */
/* ��Ĺ���˥������ʤ����������ڥ���̤�����ξ��� */
if (aspect >= 1.0 || aspect < 0.01) {
/* �Ĥκ��ξ��ʤ��ۤ����ޤ��ϥ����ڥ������ζᤤ�ۤ� */
if (((tmp_h - h) < (fit_h - h)) ||
((tmp_h == fit_h) && (tmp_a < fit_a))) {
fit = i;
fit_w = tmp_w;
fit_h = tmp_h;
fit_a = tmp_a;
}
} else { /* ��Ĺ���˥��� (�ʤ��ư���Ū�ʤ�?) �ξ��� */
/* ���κ��ξ��ʤ��ۤ����ޤ��ϥ����ڥ������ζᤤ�ۤ� */
if (((tmp_w - w) < (fit_w - w)) ||
((tmp_w == fit_w) && (tmp_a < fit_a))) {
fit = i;
fit_w = tmp_w;
fit_h = tmp_h;
fit_a = tmp_a;
}
}
}
}
}
/* ���������Τ������ʤ������ϡ� -1 ���֤� */
return fit;
}
/************************************************************************/
void graph_exit(void)
{
SDL_SetWindowGrab(sdl_window, FALSE);
SDL_QuitSubSystem(SDL_INIT_VIDEO);
}
/************************************************************************
* �����
* �����
************************************************************************/
void graph_add_color(const PC88_PALETTE_T color[],
int nr_color, unsigned long pixel[])
{
int i;
for (i=0; i<nr_color; i++) {
pixel[i] = SDL_MapRGB(sdl_offscreen->format,
color[i].red, color[i].green, color[i].blue);
}
}
/************************************************************************/
void graph_remove_color(int nr_pixel, unsigned long pixel[])
{
/* ���˴ؤ��Ƥϲ����������ʤ��Τǡ������Ǥ��ʤˤ⤷�ʤ� */
}
/************************************************************************
* �����ե��å��ι���
************************************************************************/
void graph_update(int nr_rect, T_GRAPH_RECT rect[])
{
SDL_Rect srect[16], drect;
int i;
if (nr_rect > 16) {
fprintf(stderr, "SDL: Maybe Update Failied...\n");
nr_rect = 16;
}
for (i=0; i<nr_rect; i++) {
srect[i].x = rect[i].x;
srect[i].y = rect[i].y;
srect[i].w = rect[i].width;
srect[i].h = rect[i].height;
drect = srect[i];
/*if (SDL_BlitSurface(sdl_offscreen, &srect[i], sdl_display, &drect) <0) {
fprintf(stderr, "SDL: Unsuccessful blitting to %i, %i (%i x %i)\n", srect[i].x, srect[i].y, srect[i].w, srect[i].h);
}*/
}
// Copy the SDL_Surface into an SDL_Texture
SDL_UpdateTexture(sdl_texture, NULL, sdl_offscreen->pixels, sdl_offscreen->pitch);
// Write the texture to screen
SDL_RenderClear(sdl_renderer);
SDL_RenderCopy(sdl_renderer, sdl_texture, NULL, NULL);
// Flip
SDL_RenderPresent(sdl_renderer);
// FIXME: no idea what this piece of code was supposed to do
/*for (i=0; i<nr_rect; i++) {
drect = srect[i];
SDL_BlitSurface(sdl_offscreen, &srect[i], sdl_display, &drect);
}*/
}
/************************************************************************
* �����ȥ�������
* °��������
************************************************************************/
void graph_set_window_title(const char *title)
{
SDL_SetWindowTitle(sdl_window, title);
}
/************************************************************************/
void graph_set_attribute(int mouse_show, int grab, int keyrepeat_on)
{
if (mouse_show) SDL_ShowCursor(SDL_ENABLE);
else SDL_ShowCursor(SDL_DISABLE);
if (grab) SDL_SetWindowGrab(sdl_window, TRUE);
else SDL_SetWindowGrab(sdl_window, FALSE);
/*if (keyrepeat_on) SDL_EnableKeyRepeat(SDL_DEFAULT_REPEAT_DELAY,
SDL_DEFAULT_REPEAT_INTERVAL);
else SDL_EnableKeyRepeat(0, 0);*/
// FIXME ^
sdl_mouse_rel_move = (mouse_show == FALSE && grab) ? TRUE : FALSE;
/* SDL �ϡ��������椫�ĥޥ������դʤ顢�������ɥ���ü�˥ޥ�����
�Ҥä����äƤ⡢�ޥ�����ư�������̤����ΤǤ��롣
�ʤΤǡ����ξ����� sdl_mouse_rel_move �˥��åȤ��Ƥ�����
���ʤ顢�ޥ�����ư�������̡����ʤ����а��֤Ȥ��� (event.c)
���˥塼�Ǥϡ����ʤ餺�����֤ʤ� (�ޥ����Ϥ��� or �ʤ�) �ʤΤǡ�
���ξ����ˤϤ����餺�����˥������ɥ���ü�ǥޥ��������ߤ��롣
*/
}
/*
-videodrv directx �ˤĤ���
�����֤��ꡢ�ޥ��������ξ��硢�����֤����ʤ�������
�����̤ǡ������֤ʤ����ޥ����ʤ��ˤ����ȡ�
�ޥ��������̤�ü�����ߤ��Ƥ��ޤ����������ޤ�������
�����̤ξ��硢�����֤ʤ��ϰ�̣�������Τ��� �ޥ����ǥ����ץ쥤�Ǹ���
-videodrv dga �ˤĤ���
�������ɥ��Ǥ������̤Ǥ⡢�����̥ե饰��Ω�äƤ��롣
�ǥե����Ȥ� -hwsurface �ˤʤäƤ��롣 -swsurface �λ����ϲ�ǽ��
-doublebuf �����ꤹ���ȡ� -hwsurface �⥻�åȤ�ͭ���ˤʤ롣
�����̢����������ɥ����֤��ȥ������Ǥ���
-hwsurface �Ǥϡ��ޥ�����ɽ���˻����ij����Ĥ롣
-swsurface �����ꤵ�ʤ���
-doublebuf �����ꤹ���ȡ��ޥ�����ɽ�������ʤ��ʤ롣
*/
|
bferguson3/quasi88-port
|
src/WIN32/resource.h
|
#ifndef RESOURCE_H_INCLUDED
#define RESOURCE_H_INCLUDED
/*---------------------------------------------------------------------------*/
#define M_SYS 10000
/*---------------------------------------------------------------------------*/
#define M_SYS_RESET 10100
#define M_SYS_MODE 10200
#define M_SYS_MODE_V2 10201
#define M_SYS_MODE_V1H 10202
#define M_SYS_MODE_V1S 10203
#define M_SYS_MODE_N 10204
#define M_SYS_MODE_4MH 10205
#define M_SYS_MODE_8MH 10206
#define M_SYS_MODE_SB 10207
#define M_SYS_MODE_SB2 10208
#define M_SYS_RESET_V2 10300
#define M_SYS_RESET_V1H 10400
#define M_SYS_RESET_V1S 10500
#define M_SYS_MENU 10600
#define M_SYS_SAVE 10700
#define M_SYS_EXIT 10800
/*---------------------------------------------------------------------------*/
#define M_SET 20000
/*---------------------------------------------------------------------------*/
#define M_SET_SPD 20100
#define M_SET_SPD_25 20101
#define M_SET_SPD_50 20102
#define M_SET_SPD_100 20103
#define M_SET_SPD_200 20104
#define M_SET_SPD_400 20105
#define M_SET_SPD_MAX 20199
#define M_SET_SUB 20200
#define M_SET_SUB_SOME 20201
#define M_SET_SUB_OFT 20202
#define M_SET_SUB_ALL 20203
#define M_SET_FDCWAIT 20300
#define M_SET_REF 20400
#define M_SET_REF_60 20401
#define M_SET_REF_30 20402
#define M_SET_REF_20 20403
#define M_SET_REF_15 20404
#define M_SET_INT 20500
#define M_SET_INT_NO 20501
#define M_SET_INT_SKIP 20502
#define M_SET_INT_YES 20503
#define M_SET_SIZ 20600
#define M_SET_SIZ_FULL 20601
#define M_SET_SIZ_HALF 20602
#define M_SET_SIZ_DOUBLE 20603
#define M_SET_PCG 20700
#define M_SET_MO 20800
#define M_SET_MO_NO 20801
#define M_SET_MO_MOUSE 20802
#define M_SET_MO_JOYMO 20803
#define M_SET_MO_JOY 20804
#define M_SET_CUR 20900
#define M_SET_CUR_DEF 20901
#define M_SET_CUR_TEN 20902
#define M_SET_NUMLOCK 21000
#define M_SET_ROMAJI 21100
#define M_SET_FM 21200
#define M_SET_FM_MAME 21201
#define M_SET_FM_FMGEN 21202
#define M_SET_FRQ 21300
#define M_SET_FRQ_48 21301
#define M_SET_FRQ_44 21302
#define M_SET_FRQ_22 21303
#define M_SET_FRQ_11 21304
#define M_SET_BUF 21400
#define M_SET_BUF_800 21401
#define M_SET_BUF_400 21402
#define M_SET_BUF_200 21403
#define M_SET_BUF_100 21404
/*---------------------------------------------------------------------------*/
#define M_DRV 30000
/*---------------------------------------------------------------------------*/
#define M_DRV_DRV1 30100
#define M_DRV_DRV1_1 30101
#define M_DRV_DRV1_2 30102
#define M_DRV_DRV1_3 30103
#define M_DRV_DRV1_4 30104
#define M_DRV_DRV1_5 30105
#define M_DRV_DRV1_6 30106
#define M_DRV_DRV1_7 30107
#define M_DRV_DRV1_8 30108
#define M_DRV_DRV1_9 30109
#define M_DRV_DRV1_NO 30110
#define M_DRV_DRV1_CHG 30111
#define M_DRV_DRV2 30200
#define M_DRV_DRV2_1 30201
#define M_DRV_DRV2_2 30202
#define M_DRV_DRV2_3 30203
#define M_DRV_DRV2_4 30204
#define M_DRV_DRV2_5 30205
#define M_DRV_DRV2_6 30206
#define M_DRV_DRV2_7 30207
#define M_DRV_DRV2_8 30208
#define M_DRV_DRV2_9 30209
#define M_DRV_DRV2_NO 30210
#define M_DRV_DRV2_CHG 30211
#define M_DRV_CHG 30300
#define M_DRV_UNSET 30400
/*---------------------------------------------------------------------------*/
#define M_MISC 40000
/*---------------------------------------------------------------------------*/
#define M_MISC_CAPTURE 40100
#define M_MISC_RECORD 40200
#define M_MISC_CLOAD 40300
#define M_MISC_CLOAD_S 40301
#define M_MISC_CLOAD_U 40302
#define M_MISC_CSAVE 40400
#define M_MISC_CSAVE_S 40401
#define M_MISC_CSAVE_U 40402
#define M_MISC_SLOAD 40500
#define M_MISC_SLOAD_1 40501
#define M_MISC_SLOAD_2 40502
#define M_MISC_SLOAD_3 40503
#define M_MISC_SLOAD_4 40504
#define M_MISC_SLOAD_5 40505
#define M_MISC_SLOAD_6 40506
#define M_MISC_SLOAD_7 40507
#define M_MISC_SLOAD_8 40508
#define M_MISC_SLOAD_9 40509
#define M_MISC_SSAVE 40600
#define M_MISC_SSAVE_1 40601
#define M_MISC_SSAVE_2 40602
#define M_MISC_SSAVE_3 40603
#define M_MISC_SSAVE_4 40604
#define M_MISC_SSAVE_5 40605
#define M_MISC_SSAVE_6 40606
#define M_MISC_SSAVE_7 40607
#define M_MISC_SSAVE_8 40608
#define M_MISC_SSAVE_9 40609
#define M_MISC_STATUS 40700
/*---------------------------------------------------------------------------*/
#define M_HELP 50000
/*---------------------------------------------------------------------------*/
#define M_HELP_ABOUT 50100
#endif /* RESOURCE_H_INCLUDED */
|
bferguson3/quasi88-port
|
src/SDL2/event.c
|
<reponame>bferguson3/quasi88-port<gh_stars>0
#include <SDL.h>
#include "quasi88.h"
#include "keyboard.h" // KEY88_xxx syms
#include "event.h" // quasi88_key
// globals...
int use_cmdkey = FALSE;
int keyboard_type = 1; // never changed in SDL2
int use_joydevice = FALSE;
int show_fps = FALSE;
char* file_keyboard = NULL; // not used in SDL2 version
// internals...
void numlock_setup(int enabled) {
// FIXME: whatever switching this does
}
// callbacks...
void event_init() {
}
#define SDL_TO_PC88_KEY(keysdl, key88) if(keysym.sym == keysdl) { return key88; }
int keydown_to_key88(SDL_Keysym keysym) {
// TODO: use a map for this (or a macro)
if(keysym.sym >= SDLK_0 && keysym.sym <= SDLK_9) {
return KEY88_0 + (keysym.sym - SDLK_0); // hack
}
SDL_TO_PC88_KEY(SDLK_RETURN, KEY88_RETURNL);
SDL_TO_PC88_KEY(SDLK_BACKSPACE, KEY88_DEL);
SDL_TO_PC88_KEY(SDLK_SPACE, KEY88_SPACE);
SDL_TO_PC88_KEY(SDLK_KP_ENTER, KEY88_RETURNR);
SDL_TO_PC88_KEY(SDLK_a, KEY88_A);
SDL_TO_PC88_KEY(SDLK_b, KEY88_B);
SDL_TO_PC88_KEY(SDLK_c, KEY88_C);
SDL_TO_PC88_KEY(SDLK_d, KEY88_D);
SDL_TO_PC88_KEY(SDLK_e, KEY88_E);
SDL_TO_PC88_KEY(SDLK_f, KEY88_F);
SDL_TO_PC88_KEY(SDLK_g, KEY88_G);
SDL_TO_PC88_KEY(SDLK_h, KEY88_H);
SDL_TO_PC88_KEY(SDLK_i, KEY88_I);
SDL_TO_PC88_KEY(SDLK_j, KEY88_J);
SDL_TO_PC88_KEY(SDLK_k, KEY88_K);
SDL_TO_PC88_KEY(SDLK_l, KEY88_L);
SDL_TO_PC88_KEY(SDLK_m, KEY88_M);
SDL_TO_PC88_KEY(SDLK_n, KEY88_N);
SDL_TO_PC88_KEY(SDLK_o, KEY88_O);
SDL_TO_PC88_KEY(SDLK_p, KEY88_P);
SDL_TO_PC88_KEY(SDLK_q, KEY88_Q);
SDL_TO_PC88_KEY(SDLK_r, KEY88_R);
SDL_TO_PC88_KEY(SDLK_s, KEY88_S);
SDL_TO_PC88_KEY(SDLK_t, KEY88_T);
SDL_TO_PC88_KEY(SDLK_u, KEY88_U);
SDL_TO_PC88_KEY(SDLK_v, KEY88_V);
SDL_TO_PC88_KEY(SDLK_w, KEY88_W);
SDL_TO_PC88_KEY(SDLK_x, KEY88_X);
SDL_TO_PC88_KEY(SDLK_y, KEY88_Y);
SDL_TO_PC88_KEY(SDLK_z, KEY88_Z);
SDL_TO_PC88_KEY(SDLK_COMMA, KEY88_COMMA);
SDL_TO_PC88_KEY(SDLK_PERIOD, KEY88_PERIOD);
SDL_TO_PC88_KEY(SDLK_SLASH, KEY88_SLASH);
SDL_TO_PC88_KEY(SDLK_SEMICOLON, KEY88_SEMICOLON);
SDL_TO_PC88_KEY(SDLK_QUOTE, KEY88_COLON);
// TODO: what about ]?
SDL_TO_PC88_KEY(SDLK_ESCAPE, KEY88_ESC);
SDL_TO_PC88_KEY(SDLK_BACKQUOTE, KEY88_STOP); // not 100% sure this is a good idea, but my mac doesn't have a pause key
SDL_TO_PC88_KEY(SDLK_LCTRL, KEY88_CTRL);
SDL_TO_PC88_KEY(SDLK_CAPSLOCK, KEY88_CAPS);
SDL_TO_PC88_KEY(SDLK_LSHIFT, KEY88_SHIFT);
SDL_TO_PC88_KEY(SDLK_RSHIFT, KEY88_SHIFT);
SDL_TO_PC88_KEY(SDLK_MINUS, KEY88_MINUS);
SDL_TO_PC88_KEY(SDLK_EQUALS, KEY88_CARET);
SDL_TO_PC88_KEY(SDLK_BACKSLASH, KEY88_YEN);
SDL_TO_PC88_KEY(SDLK_TAB, KEY88_TAB);
SDL_TO_PC88_KEY(SDLK_PAGEUP, KEY88_ROLLDOWN);
SDL_TO_PC88_KEY(SDLK_PAGEDOWN, KEY88_ROLLUP);
SDL_TO_PC88_KEY(SDLK_F1, KEY88_F1);
SDL_TO_PC88_KEY(SDLK_F2, KEY88_F2);
SDL_TO_PC88_KEY(SDLK_F3, KEY88_F3);
SDL_TO_PC88_KEY(SDLK_F4, KEY88_F4);
SDL_TO_PC88_KEY(SDLK_F5, KEY88_F5);
SDL_TO_PC88_KEY(SDLK_F6, KEY88_F6);
SDL_TO_PC88_KEY(SDLK_F7, KEY88_F7);
SDL_TO_PC88_KEY(SDLK_F8, KEY88_F8);
SDL_TO_PC88_KEY(SDLK_F9, KEY88_F9);
SDL_TO_PC88_KEY(SDLK_F10, KEY88_F10);
SDL_TO_PC88_KEY(SDLK_F11, KEY88_F12); // status
SDL_TO_PC88_KEY(SDLK_F12, KEY88_F12); // menu
// TODO: think about doing a mode here to switch between cursor
// and numpad emulation, since almost all games use numpad
SDL_TO_PC88_KEY(SDLK_UP, KEY88_UP);
SDL_TO_PC88_KEY(SDLK_DOWN, KEY88_DOWN);
SDL_TO_PC88_KEY(SDLK_LEFT, KEY88_LEFT);
SDL_TO_PC88_KEY(SDLK_RIGHT, KEY88_RIGHT);
SDL_TO_PC88_KEY(SDLK_KP_0, KEY88_KP_0);
SDL_TO_PC88_KEY(SDLK_KP_1, KEY88_KP_1);
SDL_TO_PC88_KEY(SDLK_KP_2, KEY88_KP_2);
SDL_TO_PC88_KEY(SDLK_KP_3, KEY88_KP_3);
SDL_TO_PC88_KEY(SDLK_KP_4, KEY88_KP_4);
SDL_TO_PC88_KEY(SDLK_KP_5, KEY88_KP_5);
SDL_TO_PC88_KEY(SDLK_KP_6, KEY88_KP_6);
SDL_TO_PC88_KEY(SDLK_KP_7, KEY88_KP_7);
SDL_TO_PC88_KEY(SDLK_KP_8, KEY88_KP_8);
SDL_TO_PC88_KEY(SDLK_KP_9, KEY88_KP_9);
printf("Unknown key %s\n", SDL_GetKeyName(keysym.sym));
return KEY88_Z;
}
void event_update() {
SDL_Event event;
SDL_PollEvent(&event);
int key88 = 0;
int x, y;
switch(event.type) {
case SDL_QUIT:
exit(0); // FIXME make this actually work
break;
case SDL_KEYDOWN:
case SDL_KEYUP:
key88 = keydown_to_key88(event.key.keysym);
quasi88_key(key88, (event.type == SDL_KEYDOWN));
break;
case SDL_MOUSEMOTION: /*------------------------------------------*/
x = event.motion.x;
y = event.motion.y;
quasi88_mouse_moved_abs(x, y);
break;
case SDL_MOUSEBUTTONDOWN:/*------------------------------------------*/
case SDL_MOUSEBUTTONUP:
/* マウス移動イベントも同時に処理する必要があるなら、
quasi88_mouse_moved_abs/rel 関数をここで呼び出しておく */
switch (event.button.button) {
case SDL_BUTTON_LEFT: key88 = KEY88_MOUSE_L; break;
case SDL_BUTTON_MIDDLE: key88 = KEY88_MOUSE_M; break;
case SDL_BUTTON_RIGHT: key88 = KEY88_MOUSE_R; break;
default: key88 = 0; break;
}
if (key88) {
quasi88_mouse(key88, (event.type == SDL_MOUSEBUTTONDOWN));
}
break;
case SDL_MOUSEWHEEL:
if (event.wheel.y < 0)
key88 = KEY88_MOUSE_WDN;
else
key88 = KEY88_MOUSE_WUP;
break;
case SDL_WINDOWEVENT_EXPOSED: /*------------------------------------------*/
quasi88_expose();
break;
}
}
void event_exit() {
// FIXME: joystick_exit
}
void event_numlock_off() {
numlock_setup(FALSE);
}
int event_numlock_on() {
numlock_setup(TRUE);
return TRUE;
}
int event_get_joystick_num() {
return 0; // FIXME
}
void event_switch() {
// FIXME: toggle unicode mode, i guess
}
void event_get_mouse_pos(int* x, int* y) {
int win_x, win_y;
SDL_PumpEvents();
SDL_GetMouseState(&win_x, &win_y);
*x = win_x; *y = win_y;
}
|
bferguson3/quasi88-port
|
src/snddrv-old/quasi88/X11/audio.h
|
/*
* MAME/XMAME の サウンドドライバとのインターフェイス
*/
#ifndef SNDDRV_X11_H_INCLUDED
#define SNDDRV_X11_H_INCLUDED
#undef EXTERN
#ifdef SNDDRV_WORK_DEFINE
#define EXTERN
#else
#define EXTERN extern
#endif
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "quasi88.h"
#include "snddrv.h"
#include "initval.h"
#include "soundbd.h"
/* src/unix/xmame.h ======================================================== */
#include "sysdep/rc.h"
#include "sysdep/sound_stream.h"
#define OSD_OK (0)
#define OSD_NOT_OK (1)
/* global variables and miscellaneous flags */
EXTERN int sound_enabled;
EXTERN struct sound_stream_struct *sound_stream;
/* QUASI88 ***************************************************************** */
extern int osd_has_sound_mixer(void); /* 1:Volume adjustable / 0:not */
#undef EXTERN
#endif /* SNDDRV_X11_H_INCLUDED */
|
bferguson3/quasi88-port
|
src/WIN32/graph.c
|
<reponame>bferguson3/quasi88-port
/***********************************************************************
* グラフィック処理 (システム依存)
*
* 詳細は、 graph.h 参照
************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include "quasi88.h"
#include "graph.h"
#include "device.h"
HINSTANCE g_hInstance;
HWND g_hWnd;
HMENU g_hMenu;
int g_keyrepeat;
static T_GRAPH_SPEC graph_spec; /* 基本情報 */
static int graph_exist; /* 真で、画面生成済み */
static T_GRAPH_INFO graph_info; /* その時の、画面情報 */
/************************************************************************
* グラフィック処理の初期化
* グラフィック処理の動作
* グラフィック処理の終了
************************************************************************/
const T_GRAPH_SPEC *graph_init(void)
{
if (verbose_proc) {
printf("Initializing Graphic System ... ");
}
#ifdef SUPPORT_DOUBLE
graph_spec.window_max_width = 1280;
graph_spec.window_max_height = 960;
#else
graph_spec.window_max_width = 640;
graph_spec.window_max_height = 480;
#endif
graph_spec.fullscreen_max_width = 0;
graph_spec.fullscreen_max_height = 0;
graph_spec.forbid_status = FALSE;
graph_spec.forbid_half = FALSE;
if (verbose_proc)
printf("OK\n");
return &graph_spec;
}
/************************************************************************/
static DWORD winStyle;
static int create_window(int width, int height);
static void calc_window_size(int *width, int *height);
static unsigned char *buffer = NULL;
static BITMAPINFO bmpInfo;
const T_GRAPH_INFO *graph_setup(int width, int height,
int fullscreen, double aspect)
{
int win_width, win_height;
/* fullscreen, aspect は未使用 */
/* オフスクリーンバッファを確保する */
if (buffer) {
free(buffer);
}
buffer = malloc(width * height * sizeof(unsigned long));
if (buffer == FALSE) {
return NULL;
}
memset(&bmpInfo, 0, sizeof(bmpInfo));
bmpInfo.bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
bmpInfo.bmiHeader.biWidth = width;
bmpInfo.bmiHeader.biHeight = - height;
bmpInfo.bmiHeader.biPlanes = 1;
bmpInfo.bmiHeader.biBitCount = 32;
bmpInfo.bmiHeader.biCompression = BI_RGB;
/* ウインドウの生成、ないしリサイズ */
if (graph_exist == FALSE) { /* ウインドウが無ければ生成 */
if (create_window(width, height) == FALSE) {
free(buffer);
buffer = NULL;
return NULL;
}
} else { /* ウインドウが有ればリサイズ */
win_width = width;
win_height = height;
calc_window_size(&win_width, &win_height);
SetWindowPos(g_hWnd,
HWND_TOP, 0, 0, /* ダミー(無視される) */
win_width, win_height, /* ウィンドウの幅・高さ */
SWP_NOMOVE | SWP_NOZORDER);
}
/* graph_info に諸言をセットする */
graph_info.fullscreen = FALSE;
graph_info.width = width;
graph_info.height = height;
graph_info.byte_per_pixel = 4;
graph_info.byte_per_line = width * 4;
graph_info.buffer = buffer;
graph_info.nr_color = 255;
graph_info.write_only = FALSE;
graph_info.broken_mouse = FALSE;
graph_info.draw_start = NULL;
graph_info.draw_finish = NULL;
graph_info.dont_frameskip = FALSE;
graph_exist = TRUE;
return &graph_info;
}
/*
* ウインドウを生成する
*/
static int create_window(int width, int height)
{
WNDCLASSEX wc;
int win_width, win_height;
/* ウィンドウクラスの情報を設定 */
wc.cbSize = sizeof(wc); /* 構造体サイズ */
wc.style = 0; /* ウインドウスタイル */
wc.lpfnWndProc = WndProc; /* ウィンドウプロシージャ */
wc.cbClsExtra = 0; /* 拡張情報 */
wc.cbWndExtra = 0; /* 拡張情報 */
wc.hInstance = g_hInstance; /* インスタンスハンドル */
wc.hIcon = NULL; /* アイコン */
/*
wc.hIcon = (HICON)LoadImage(NULL, MAKEINTRESOURCE(IDI_APPLICATION),
IMAGE_ICON, 0, 0, LR_DEFAULTSIZE | LR_SHARED);
*/
wc.hIconSm = wc.hIcon; /* 小さいアイコン */
wc.hCursor = NULL; /* マウスカーソル */
/*
wc.hCursor = (HCURSOR)LoadImage(NULL, MAKEINTRESOURCE(IDC_ARROW),
IMAGE_CURSOR, 0, 0,
LR_DEFAULTSIZE | LR_SHARED);
*/
/* ウィンドウ背景 */
wc.hbrBackground = (HBRUSH)GetStockObject(BLACK_BRUSH);
/* wc.lpszMenuName = NULL;*/ /* メニュー名 */
wc.lpszMenuName = "QUASI88"; /* メニュー名 → quasi88.rc */
wc.lpszClassName = "Win32App"; /* ウィンドウクラス名 適当 */
/* ウィンドウクラスを登録する */
if (RegisterClassEx(&wc) == 0) { return FALSE; }
/* ウィンドウスタイルはこれ */
winStyle = WS_OVERLAPPED | WS_CAPTION | WS_SYSMENU | WS_MINIMIZEBOX;
/* ウィンドウサイズの計算 */
win_width = width;
win_height = height;
calc_window_size(&win_width, &win_height);
/* ウィンドウを作成する */
g_hWnd = CreateWindowEx(WS_EX_ACCEPTFILES, /* 拡張ウィンドウスタイル */
wc.lpszClassName, /* ウィンドウクラス名 */
"QUASI88 win32", /* タイトルバー文字列 */
winStyle, /* ウィンドウスタイル */
CW_USEDEFAULT, /* ウィンドウのx座標 */
CW_USEDEFAULT, /* ウィンドウのy座標 */
win_width, /* ウィンドウの幅 */
win_height, /* ウィンドウの高さ */
NULL, /* 親ウィンドウのハンドル */
NULL, /* メニューハンドル */
g_hInstance, /* インスタンスハンドル */
NULL); /* 付加情報 */
if (g_hWnd == NULL) { return FALSE; }
/* ウィンドウを表示する */
ShowWindow(g_hWnd, SW_SHOW);
UpdateWindow(g_hWnd);
/* メニューハンドル */
g_hMenu = GetMenu(g_hWnd);
/* Drug & Drop の許可 */
#if 0
/* ウインドウの作成時に、 WS_EX_ACCEPTFILES をつけているので、これは不要 */
DragAcceptFiles(g_hWnd, TRUE);
#endif
#if 0
if (verbose_proc) { /* ディスプレイ情報 */
HDC hdc;
hdc = GetDC(g_hWnd);
fprintf(debugfp, "Info: H-pixel %d\n", GetDeviceCaps(hdc, HORZRES));
fprintf(debugfp, "Info: V-pixel %d\n", GetDeviceCaps(hdc, VERTRES));
fprintf(debugfp, "Info: Depth %d\n", GetDeviceCaps(hdc, BITSPIXEL));
ReleaseDC(g_hWnd, hdc);
}
#endif
return TRUE;
}
/*
* 本当のウインドウサイズを計算する
*/
static void calc_window_size(int *width, int *height)
{
RECT rect;
rect.left = 0; rect.right = *width;
rect.top = 0; rect.bottom = *height;
AdjustWindowRectEx(&rect, /* クライアント矩形 */
winStyle, /* ウィンドウスタイル */
TRUE, /* メニューフラグ */
0); /* 拡張ウィンドウスタイル */
*width = rect.right - rect.left; /* 本当のウィンドウの幅 */
*height = rect.bottom - rect.top; /* 本当のウィンドウの高さ */
}
/************************************************************************/
void graph_exit(void)
{
if (buffer) {
free(buffer);
}
}
/************************************************************************
* 色の確保
* 色の解放
************************************************************************/
void graph_add_color(const PC88_PALETTE_T color[],
int nr_color, unsigned long pixel[])
{
int i;
for (i=0; i<nr_color; i++) {
pixel[i] = ((((unsigned long) color[i].red) << 16) |
(((unsigned long) color[i].green) << 8) |
(((unsigned long) color[i].blue)));
/* RGB()マクロは、順序が反転しているので使えない */
}
}
/************************************************************************/
void graph_remove_color(int nr_pixel, unsigned long pixel[])
{
/* 色に関しては何も管理しないので、ここでもなにもしない */
}
/************************************************************************
* グラフィックの更新
************************************************************************/
static int graph_update_counter = 0;
int graph_update_WM_PAINT(void)
{
int drawn;
HDC hdc;
PAINTSTRUCT ps;
hdc = BeginPaint(g_hWnd, &ps);
/* graph_update() により、 WM_PAINT イベントが発生した場合、描画する。
OS が勝手に発生させた WM_PAINT イベントの場合は、なにもしない。
(quasi88_expose() の処理により、 graph_update() が呼び出されるため) */
if (graph_update_counter > 0) {
#if 1 /* どちらの API でもよさげ。速度は? */
StretchDIBits(hdc,
0, 0, graph_info.width, graph_info.height,
0, 0, graph_info.width, graph_info.height,
buffer, &bmpInfo, DIB_RGB_COLORS, SRCCOPY);
#else /* こっちは、転送先の高さしか指定できない */
SetDIBitsToDevice(hdc,
0, 0, graph_info.width, graph_info.height,
0, 0, 0, graph_info.height,
buffer, &bmpInfo, DIB_RGB_COLORS);
#endif
graph_update_counter = 0;
drawn = TRUE;
} else {
drawn = FALSE;
}
/*
fprintf(debugfp,
"%s %d:(%3d,%3d)-(%3d,%3d)\n",
(drawn) ? "update" : "EXPOSE", graph_update_counter,
ps.rcPaint.left, ps.rcPaint.top,
ps.rcPaint.right, ps.rcPaint.bottom);
*/
EndPaint(g_hWnd, &ps);
return drawn;
}
void graph_update(int nr_rect, T_GRAPH_RECT rect[])
{
graph_update_counter = 1;
InvalidateRect(g_hWnd, NULL, FALSE);
UpdateWindow(g_hWnd);
/* ここで、直接ウインドウ描画をしようとしたのだが、なんかうまくいかない。
WndProc() の内部でしか、ウインドウ描画はできないのかな?
とりあえず、 InvalidateRect() をすると、 WM_PAINT イベントが発生する
ので、この後の WndProc() の WM_PAINT 処理にて描画させることにしよう。
ちなみに、 InvalidateRect() の直後に、 UpdateWindow() を呼び出すと、
この関数の内部で WndProc() が呼び出され、 WM_PAINT の処理が行われる
らしい。つまり UpdateWindow() が終わった時点で描画は終わっている。
本来ここは nr_rect 回、処理を繰り返すようにすべきなのだが、面倒なので
全画面を1回だけ描画させている。(速いマシンなら気にならない ^^;) */
}
/************************************************************************
* タイトルの設定
* 属性の設定
************************************************************************/
void graph_set_window_title(const char *title)
{
}
/************************************************************************/
void graph_set_attribute(int mouse_show, int grab, int keyrepeat_on)
{
g_keyrepeat = keyrepeat_on;
if (mouse_show) ShowCursor(TRUE);
else ShowCursor(FALSE);
}
|
cnlohr/bridgesim
|
src/cclient/util/linmath.c
|
<reponame>cnlohr/bridgesim<filename>src/cclient/util/linmath.c
#include "linmath.h"
#include <math.h>
void cross3d( float * out, const float * a, const float * b )
{
out[0] = a[1]*b[2] - a[2]*b[1];
out[1] = a[2]*b[0] - a[0]*b[2];
out[2] = a[0]*b[1] - a[1]*b[0];
}
void sub3d( float * out, const float * a, const float * b )
{
out[0] = a[0] - b[0];
out[1] = a[1] - b[1];
out[2] = a[2] - b[2];
}
void add3d( float * out, const float * a, const float * b )
{
out[0] = a[0] + b[0];
out[1] = a[1] + b[1];
out[2] = a[2] + b[2];
}
void scale3d( float * out, const float * a, float scalar )
{
out[0] = a[0] * scalar;
out[1] = a[1] * scalar;
out[2] = a[2] * scalar;
}
void normalize3d( float * out, const float * in )
{
float r = 1./sqrtf( in[0] * in[0] + in[1] * in[1] + in[2] * in[2] );
out[0] = in[0] * r;
out[1] = in[1] * r;
out[2] = in[2] * r;
}
float dot3d( const float * a, const float * b )
{
return a[0] * b[0] + a[1] * b[1] + a[2] * b[2];
}
int compare3d( const float * a, const float * b, float epsilon )
{
if( !a || !b ) return 0;
if( a[2] - b[2] > epsilon ) return 1;
if( b[2] - a[2] > epsilon ) return -1;
if( a[1] - b[1] > epsilon ) return 1;
if( b[1] - a[1] > epsilon ) return -1;
if( a[0] - b[0] > epsilon ) return 1;
if( b[0] - a[0] > epsilon ) return -1;
return 0;
}
void copy3d( float * out, const float * in )
{
out[0] = in[0];
out[1] = in[1];
out[2] = in[2];
}
/////////////////////////////////////QUATERNIONS//////////////////////////////////////////
//Originally from Mercury (Copyright (C) 2009 by <NAME>, <NAME>, <NAME>)
//Under the mit/X11 license.
void quatsetnone( float * q )
{
q[0] = 0; q[1] = 0; q[2] = 0; q[3] = 1;
}
void quatcopy( float * qout, const float * qin )
{
qout[0] = qin[0];
qout[1] = qin[1];
qout[2] = qin[2];
qout[3] = qin[3];
}
void quatfromeuler( float * q, const float * euler )
{
float X = euler[0]/2.0f; //roll
float Y = euler[1]/2.0f; //pitch
float Z = euler[2]/2.0f; //yaw
float cx = cosf(X);
float sx = cosf(X);
float cy = cosf(Y);
float sy = cosf(Y);
float cz = cosf(Z);
float sz = cosf(Z);
//Correct according to
//http://en.wikipedia.org/wiki/Conversion_between_MQuaternions_and_Euler_angles
q[0] = cx*cy*cz+sx*sy*sz;//q1
q[1] = sx*cy*cz-cx*sy*sz;//q2
q[2] = cx*sy*cz+sx*cy*sz;//q3
q[3] = cx*cy*sz-sx*sy*cz;//q4
quatnormalize( q, q );
}
void quattoeuler( float * euler, const float * q )
{
//According to http://en.wikipedia.org/wiki/Conversion_between_quaternions_and_Euler_angles (Oct 26, 2009)
euler[0] = atan2( 2 * (q[0]*q[1] + q[2]*q[3]), 1 - 2 * (q[1]*q[1] + q[2]*q[2] ) );
euler[1] = asin( 2 * (q[0] *q[2] - q[3]*q[1] ) );
euler[2] = atan2( 2 * (q[0]*q[3] + q[1]*q[2]), 1 - 2 * (q[2]*q[2] + q[3]*q[3] ) );
}
void quatfromaxisangle( float * q, const float * axis, float radians )
{
float v[3];
normalize3d( v, axis );
float sn = sin(radians/2.0f);
q[0] = cos(radians/2.0f);
q[1] = sn * v[0];
q[2] = sn * v[1];
q[3] = sn * v[2];
quatnormalize( q, q );
}
float quatmagnitude( const float * q )
{
return sqrt((q[0]*q[0])+(q[1]*q[1])+(q[2]*q[2])+(q[3]*q[3]));
}
float quatinvsqmagnitude( const float * q )
{
return 1./(q[0]*q[0])+(q[1]*q[1])+(q[2]*q[2])+(q[3]*q[3]);
}
void quatnormalize( float * qout, const float * qin )
{
float imag = quatinvsqmagnitude( qin );
quatscale( qout, qin, imag );
}
void quattomatrix( float * matrix44, const float * qin )
{
float q[4];
quatnormalize( q, qin );
//Reduced calulation for speed
float xx = 2*q[0]*q[0];
float xy = 2*q[0]*q[1];
float xz = 2*q[0]*q[2];
float xw = 2*q[0]*q[3];
float yy = 2*q[1]*q[1];
float yz = 2*q[1]*q[2];
float yw = 2*q[1]*q[3];
float zz = 2*q[2]*q[2];
float zw = 2*q[2]*q[3];
//opengl major
matrix44[0] = 1-yy-zz;
matrix44[1] = xy-zw;
matrix44[2] = xz+yw;
matrix44[3] = 0;
matrix44[4] = xy+zw;
matrix44[5] = 1-xx-zz;
matrix44[6] = yz-xw;
matrix44[7] = 0;
matrix44[8] = xz-yw;
matrix44[9] = yz+xw;
matrix44[10] = 1-xx-yy;
matrix44[11] = 0;
matrix44[12] = 0;
matrix44[13] = 0;
matrix44[14] = 0;
matrix44[15] = 1;
}
void quatgetconjugate( float * qout, const float * qin )
{
qout[0] = qin[0];
qout[1] = -qin[1];
qout[2] = -qin[2];
qout[3] = -qin[3];
}
void quatgetreciprocal( float * qout, const float * qin )
{
float m = quatinvsqmagnitude(qin);
quatgetconjugate( qout, qin );
quatscale( qout, qout, m );
}
void quatsub( float * qout, const float * a, const float * b )
{
qout[0] = a[0] - b[0];
qout[1] = a[1] - b[1];
qout[2] = a[2] - b[2];
qout[3] = a[3] - b[3];
}
void quatadd( float * qout, const float * a, const float * b )
{
qout[0] = a[0] + b[0];
qout[1] = a[1] + b[1];
qout[2] = a[2] + b[2];
qout[3] = a[3] + b[3];
}
void quatrotateabout( float * qout, const float * a, const float * b )
{
float q1[4];
float q2[4];
quatnormalize( q1, a );
quatnormalize( q2, b );
qout[0] = (q1[0]*q2[0])-(q1[1]*q2[1])-(q1[2]*q2[2])-(q1[3]*q2[3]);
qout[1] = (q1[0]*q2[1])+(q1[1]*q2[0])+(q1[2]*q2[3])-(q1[3]*q2[2]);
qout[2] = (q1[0]*q2[2])-(q1[1]*q2[3])+(q1[2]*q2[0])+(q1[3]*q2[1]);
qout[3] = (q1[0]*q2[3])+(q1[1]*q2[2])-(q1[2]*q2[1])+(q1[3]*q2[0]);
}
void quatscale( float * qout, const float * qin, float s )
{
qout[0] = qin[0] * s;
qout[1] = qin[1] * s;
qout[2] = qin[2] * s;
qout[3] = qin[3] * s;
}
float quatinnerproduct( const float * qa, const float * qb )
{
return (qa[0]*qb[0])+(qa[1]*qb[1])+(qa[2]*qb[2])+(qa[3]*qb[3]);
}
void quatouterproduct( float * outvec3, float * qa, float * qb )
{
outvec3[0] = (qa[0]*qb[1])-(qa[1]*qb[0])-(qa[2]*qb[3])+(qa[3]*qb[2]);
outvec3[1] = (qa[0]*qb[2])+(qa[1]*qb[3])-(qa[2]*qb[0])-(qa[3]*qb[1]);
outvec3[2] = (qa[0]*qb[3])-(qa[1]*qb[2])+(qa[2]*qb[1])-(qa[3]*qb[0]);
}
void quatevenproduct( float * q, float * qa, float * qb )
{
q[0] = (qa[0]*qb[0])-(qa[1]*qb[1])-(qa[2]*qb[2])-(qa[3]*qb[3]);
q[1] = (qa[0]*qb[1])+(qa[1]*qb[0]);
q[2] = (qa[0]*qb[2])+(qa[2]*qb[0]);
q[3] = (qa[0]*qb[3])+(qa[3]*qb[0]);
}
void quatoddproduct( float * outvec3, float * qa, float * qb )
{
outvec3[0] = (qa[2]*qb[3])-(qa[3]*qb[2]);
outvec3[1] = (qa[3]*qb[1])-(qa[1]*qb[3]);
outvec3[2] = (qa[1]*qb[2])-(qa[2]*qb[1]);
}
void quatslerp( float * q, const float * qa, const float * qb, float t )
{
float an[4];
float bn[4];
quatnormalize( an, qa );
quatnormalize( bn, qb );
float cosTheta = quatinnerproduct(an,bn);
float sinTheta;
//Careful: If cosTheta is exactly one, or even if it's infinitesimally over, it'll
// cause SQRT to produce not a number, and screw everything up.
if ( 1 - (cosTheta*cosTheta) <= 0 )
sinTheta = 0;
else
sinTheta = sqrt(1 - (cosTheta*cosTheta));
float Theta = acos(cosTheta); //Theta is half the angle between the 2 MQuaternions
if(fabs(Theta) < DEFAULT_EPSILON )
quatcopy( q, qa );
else if(fabs(sinTheta) < DEFAULT_EPSILON )
{
quatadd( q, qa, qb );
quatscale( q, q, 0.5 );
}
else
{
float aside[4];
float bside[4];
quatscale( bside, qb, sin( t * Theta ) );
quatscale( aside, qa, sin((1-t)*Theta) );
quatadd( q, aside, bside );
quatscale( q, q, 1./sinTheta );
}
}
void quatrotatevector( float * vec3out, const float * quat, const float * vec3in )
{
float tquat[4];
float vquat[4];
float qrecp[4];
vquat[0] = 0;
vquat[1] = vec3in[0];
vquat[2] = vec3in[1];
vquat[3] = vec3in[2];
quatrotateabout( tquat, quat, vquat );
quatgetreciprocal( qrecp, quat );
quatrotateabout( vquat, tquat, qrecp );
vec3out[0] = vquat[1];
vec3out[1] = vquat[2];
vec3out[2] = vquat[3];
}
|
cnlohr/bridgesim
|
src/cclient/util/linmath.h
|
#ifndef _LINMATH_H
#define _LINMATH_H
//Yes, I know it's kind of arbitrary.
#define DEFAULT_EPSILON 0.001
//NOTE: Inputs may never be output with cross product.
void cross3d( float * out, const float * a, const float * b );
void sub3d( float * out, const float * a, const float * b );
void add3d( float * out, const float * a, const float * b );
void scale3d( float * out, const float * a, float scalar );
void normalize3d( float * out, const float * in );
float dot3d( const float * a, const float * b );
//Returns 0 if equal. If either argument is null, 0 will ALWAYS be returned.
int compare3d( const float * a, const float * b, float epsilon );
void copy3d( float * out, const float * in );
//Quaternion things...
void quatsetnone( float * q );
void quatcopy( float * qout, const float * qin );
void quatfromeuler( float * q, const float * euler );
void quattoeuler( float * euler, const float * q );
void quatfromaxisangle( float * q, const float * axis, float radians );
float quatmagnitude( const float * q );
float quatinvsqmagnitude( const float * q );
void quatnormalize( float * qout, const float * qin ); //Safe for in to be same as out.
void quattomatrix( float * matrix44, const float * q );
void quatgetconjugate( float * qout, const float * qin );
void quatgetreciprocal( float * qout, const float * qin );
void quatsub( float * qout, const float * a, const float * b );
void quatadd( float * qout, const float * a, const float * b );
void quatrotateabout( float * qout, const float * a, const float * b ); //same as quat multiply, not piecewise multiply.
void quatscale( float * qout, const float * qin, float s );
float quatinnerproduct( const float * qa, const float * qb );
void quatouterproduct( float * outvec3, float * qa, float * qb );
void quatevenproduct( float * q, float * qa, float * qb );
void quatoddproduct( float * outvec3, float * qa, float * qb );
void quatslerp( float * q, const float * qa, const float * qb, float t );
void quatrotatevector( float * vec3out, const float * quat, const float * vec3in );
#endif
|
cnlohr/bridgesim
|
src/cclient/util/3dutils.h
|
<gh_stars>1-10
#ifndef _3DUTILS_H
#define _3DUTILS_H
//NOTE: Expects triples for all three.
//Returns quadruples
float * CalculateTangentSpace( int Triangles, int VertexCount, int * Indices, float * verts, float * normals, float * texs );
#endif
|
cnlohr/bridgesim
|
src/cclient/gui/button.c
|
<gh_stars>1-10
#include "button.h"
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
struct GUIBase * CreateButton( struct GUIWindow * parent, const char * text )
{
struct Button * ret = malloc( sizeof( struct Button ) );
ret->text = text?strdup(text):0;
ret->x = 100;
ret->y = 0;
ret->w = 100;
ret->h = 30;
ret->color[0] = 1;
ret->color[1] = 1;
ret->color[2] = 0;
ret->color[3] = 1;
ret->wp = parent;
ret->focused = 0;
ret->clicked = 0;
ret->depressed = 0;
ret->oldtext = 0;
ret->geotext = 0;
ret->Prerender = 0;
ret->Render = ButtonRender;
ret->CheckClick = GenericCheckClick;
ret->HandleMove = GenericHandleMove;
ret->HandleKeyboard = GenericHandleKeyboard;
ret->DestroyMe = ButtonDestroyMe;
ret->ProcessClick = ButtonProcessClick;
return (struct GUIBase*)ret;
}
void ButtonDestroyMe( struct Button * b )
{
WindowRemoveElement( b->wp, (struct GUIBase*)b );
if( b->text ) free( b->text );
if( b->oldtext ) free( b->oldtext );
if( b->geotext ) DestroyGPUGeometry( b->geotext );
free( b );
}
void ButtonProcessClick( struct Button * b )
{
printf( "I GOT CLICKED!\n" );
}
void ButtonRender( struct Button * b )
{
if( b->text != b->oldtext || !b->geotext )
{
if( b->oldtext)
free( b->oldtext );
if( b->geotext )
DestroyGPUGeometry( b->geotext );
b->geotext = EmitGeometryFromFontString( OldSansBlack, b->text, TEXTFLIPY );
b->oldtext = b->text;
}
// b->w = sin(TotalTime)*100+100;
// b->h = cos(TotalTime)*100+100;
ApplyShader( ButtonShader, OverallUniforms );
glColor4fv( b->color );
glBegin(GL_QUADS);
glTexCoord4f(0.0, 0.0, b->w, b->h);
glVertex3f(b->x, b->y, 0.0);
glTexCoord4f(b->w, 0.0, b->w, b->h);
glVertex3f(b->x+b->w, b->y, 0.0);
glTexCoord4f(b->w, b->h, b->w, b->h );
glVertex3f(b->x+b->w, b->y+b->h, 0.0);
glTexCoord4f(0.0, b->h, b->w, b->h );
glVertex3f(b->x, b->y+b->h, 0.0);
glEnd();
CancelShader( ButtonShader );
if( b->color[0] + b->color[1] + b->color[2] > 1.5 )
glColor4f( 0, 0, 0, 1 );
else
glColor4f( 1,1,1,1 );
if( b->geotext )
{
float mx = b->geotext->maxs[0]-b->geotext->mins[0];
float my = b->geotext->maxs[1]-b->geotext->mins[1];
float scaleby = b->h / OldSansBlack->fontsize;
glTranslatef( b->x+(b->w-mx*scaleby)/2, b->y+(b->h-(my+32)*scaleby)/2, 0 );
glScalef( scaleby, scaleby, 0.0 );
// ApplyShader( TextShader, OverallUniforms );
RenderGPUGeometry( b->geotext );
// CancelShader( TextShader );
}
glColor4f( 1,1,1,1 );
}
|
cnlohr/bridgesim
|
src/cclient/graphics/glutmain.h
|
<filename>src/cclient/graphics/glutmain.h
#ifndef _GLUTMAIN_H
#define _GLUTMAIN_H
extern int fpscount;
//Only in warp mode.
extern double absoluteMouseMotionX;
extern double absoluteMouseMotionY;
extern double currentMouseX;
extern double currentMouseY;
//This must be done in your main.
int StartGlutMain(int argc, char **argv, const char * title, int initsizeX, int initsizeY);
void DoGlutLoop();
//You can call these
void SetMouseWarpMode( int dowarp );
//You have to implement this:
void UpdateDisplay();
void MouseMotion( double x, double y, int mask );
void MouseClick( double x, double y, int button, int state );
void HandleKeyboard( int c, int down );
#endif
|
cnlohr/bridgesim
|
src/cclient/graphics/glutmain.c
|
<filename>src/cclient/graphics/glutmain.c<gh_stars>1-10
#include <stdio.h>
#include <GL/glew.h>
#include <GL/freeglut.h>
#include "graphicscore.h"
#include "bitmapfont.h"
#include <os_generic.h>
#include "objreader.h"
#include <math.h>
#include "commonassets.h"
#include "guibase.h"
#include "button.h"
#include <string.h>
double StartTime;
double LastFPSTime;
int framecountsincefps;
int fpscount;
int domousewarp;
double absoluteMouseMotionX = 0;
double absoluteMouseMotionY = 0;
double currentMouseX = 0;
double currentMouseY = 0;
struct GPUGeometry * helloworld;
struct GUIWindow * guiwindow;
void idle()
{
glutPostRedisplay();
}
void reshape(int w, int h)
{
ScreenW = w;
ScreenH = h;
glViewport(0, 0, w, h);
}
void display(void)
{
static double LastTime;
TotalTime = OGGetAbsoluteTime() - StartTime;
DeltaTime = TotalTime - LastTime;
LastTime = TotalTime;
if( ( ScreenW <= 0 || ScreenH <= 0 ) && TotalTime < 1.0 ) return;
if( LastFPSTime + 1 < TotalTime )
{
LastFPSTime += 1;
fpscount = framecountsincefps;
printf( "FPS: %d\n", fpscount );
framecountsincefps = 0;
}
framecountsincefps++;
RenderW = ScreenW;
RenderH = ScreenH;
UpdatedDisplay();
glFlush();
}
void myupfunc( unsigned char key, int x, int y )
{
HandleKeyboard( key, 0 );
}
void mykeyfunc( unsigned char key, int x, int y )
{
HandleKeyboard( key, 1 );
}
void myspecialfunc( int key, int x, int y )
{
HandleKeyboard( key, 1 );
}
void myspecialupfunc( int key, int x, int y )
{
HandleKeyboard( key, 0 );
}
static int mousebuttonmask = 0;
void mousepassive(int x, int y)
{
if( domousewarp )
{
absoluteMouseMotionX += x - (int)(RenderW/2);
absoluteMouseMotionY += y - (int)(RenderH/2);
glutWarpPointer( (int)(RenderW/2), (int)(RenderH/2) );
MouseMotion( x - (int)(RenderW/2), y - (int)(RenderH/2), mousebuttonmask );
}
else
{
currentMouseY = y;
currentMouseX = x;
MouseMotion( x, y, mousebuttonmask );
}
}
void mousemotion(int x, int y)
{
mousepassive( x, y );
}
void mousefunc( int button, int state, int x, int y )
{
if( state )
{
mousebuttonmask |= 1<<button;
}
else
{
mousebuttonmask &= ~(1<<button);
}
if( domousewarp )
{
MouseClick( absoluteMouseMotionX, absoluteMouseMotionY, button, state );
}
else
{
double dx = x;
double dy = y;
MouseClick( dx, dy, button, state );
}
}
int StartGlutMain(int argc, char **argv, const char * title, int initsizeX, int initsizeY)
{
int i;
glutInitWindowSize(initsizeX,initsizeY);
glutInit( &argc, argv );
glutCreateWindow( "Test" );
if( glewInit() != GLEW_OK )
{
fprintf( stderr, "Error: GLEW Fault.\n" );
return 0;
}
StartTime = OGGetAbsoluteTime();
glutSetKeyRepeat( GLUT_KEY_REPEAT_OFF );
glutDisplayFunc( display );
glutReshapeFunc( reshape );
glutIdleFunc( idle );
glutKeyboardFunc( mykeyfunc );
glutKeyboardUpFunc( myupfunc );
glutSpecialFunc( myspecialfunc );
glutSpecialUpFunc( myspecialupfunc );
glutMotionFunc( mousemotion );
glutPassiveMotionFunc( mousepassive );
glutMouseFunc( mousefunc );
}
void DoGlutLoop()
{
glutMainLoop();
}
void SetMouseWarpMode( int dowarp )
{
domousewarp = dowarp;
if( dowarp )
{
glutSetCursor( GLUT_CURSOR_NONE );
}
else
{
glutSetCursor( GLUT_CURSOR_INHERIT );
}
}
|
cnlohr/bridgesim
|
src/cclient/graphics/test.c
|
#include <stdio.h>
#include <GL/glew.h>
#include <GL/freeglut.h>
#include "graphicscore.h"
#include "bitmapfont.h"
#include <os_generic.h>
#include "objreader.h"
#include <math.h>
struct Shader * modelshader;
struct Shader * defshader;
struct Shader * texcoords;
struct Shader * textshader;
struct UniformMatch * shaderprops;
struct Texture * testtex;
float Ambient[4] = { .1, .1, .1, 1 };
float Emission[4] = { 0, 0, 0, 1 };
float TexSlot = 0;
float TexSlot1 = 0;
double StartTime;
struct RFBuffer * myrb;
struct Texture * torender;
struct BitmapFont * mbf;
struct BitmapFont * captureitfont;
struct GPUGeometry * helloworld = 0;
struct GPUGeometry * bridgesim = 0;
struct GPUGeometry * lottatext = 0;
struct GPUGeometry * modelgeo;
double ElapsedTime;
double DeltaTime;
double LastFPSTime;
int framecountsincefps;
int fpscount;
void SetupShaderProps()
{
shaderprops = UniformMatchMake( "AmbientColor", Ambient, 0, 4, 0 );
shaderprops = UniformMatchMake( "EmissionColor", Emission, 0, 4, shaderprops );
shaderprops = UniformMatchMake( "tex0", &TexSlot, 1, 0, shaderprops );
shaderprops = UniformMatchMake( "tex1", &TexSlot1, 1, 0, shaderprops );
}
void idle()
{
glutPostRedisplay();
}
void reshape(int w, int h)
{
ScreenW = w;
ScreenH = h;
glViewport(0, 0, w, h);
}
void display(void)
{
static double LastTime;
ElapsedTime = OGGetAbsoluteTime() - StartTime;
DeltaTime = ElapsedTime - LastTime;
LastTime = ElapsedTime;
if( LastFPSTime + 1 < ElapsedTime )
{
LastFPSTime += 1;
fpscount = framecountsincefps;
printf( "FPS: %d\n", fpscount );
framecountsincefps = 0;
}
framecountsincefps++;
glClearColor( .2, .2, .2, 0 );
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glEnable (GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glEnable( GL_DEPTH_TEST );
glDepthFunc(GL_LESS);
RFBufferGo( myrb, 100, 100, 1, &torender, 1 );
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluPerspective( 45.0, 1.0, 0.1f, 500.0 );
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glRotatef( ElapsedTime * 100, 0, 0, 1 );
glTranslatef( 0., 0., -10 );
glColor3f( 1,1,1 );
glRasterPos2f(1.5, .5);
glutBitmapString( GLUT_BITMAP_9_BY_15, "(15,51)" );
glutWireTeapot(1.0);
RFBufferDone( myrb );
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluPerspective( 45.0, (GLfloat)(ScreenW)/(GLfloat)(ScreenH), 0.1f, 500.0 );
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glTranslatef( 0., 0., -10 );
glRotatef( ElapsedTime * 100, 0, 1, 0 );
glColor3f( 1,1,1 );
glScalef(.2,.2,.2);
CheckForNewerShader( modelshader );
ApplyShader( modelshader, shaderprops );
RenderGPUGeometry( modelgeo );
CancelShader( modelshader );
glLoadIdentity();
glTranslatef( 0., -6., -30 );
glColor4f( 1,1,0,1 );
glScalef( .07, .07, .07 );
CheckForNewerShader( textshader );
ApplyShader( textshader, shaderprops );
RenderGPUGeometry( helloworld );
CancelShader( textshader );
glColor4f( 1,1,1,1 );
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(0, ScreenW, 0, ScreenH, -1, 1);
glDepthFunc(GL_ALWAYS);
glScalef(1, -1, 1);
glTranslatef(0, -ScreenH, 0);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
char st[15];
sprintf( st, "FPS: %d", fpscount );
glRasterPos2f(80, 50);
glutBitmapString( GLUT_BITMAP_9_BY_15, st );
CheckForNewerShader( defshader );
ApplyShader( defshader,shaderprops );
ActivateTexture( testtex );
glBegin(GL_QUADS);
glTexCoord2f(0.0, 0.0);
glVertex3f(0.0, 0.0, 0.0);
glTexCoord2f(1.0, 0.0);
glVertex3f(100.0, 0.0, 0.0);
glTexCoord2f(1.0, 1.0);
glVertex3f(100.0, 100.0, 0.0);
glTexCoord2f(0.0, 1.0);
glVertex3f(0.0, 100.0, 0.0);
glEnd();
DeactivateTexture( testtex);
CancelShader( defshader);
ActivateTexture( torender );
glScalef( 2, 2, 1 );
glBegin(GL_QUADS);
glTexCoord2f(0.0, 0.0);
glVertex3f(100.0, 0.0, 0.0);
glTexCoord2f(1.0, 0.0);
glVertex3f(200.0, 0.0, 0.0);
glTexCoord2f(1.0, 1.0);
glVertex3f(200.0, 100.0, 0.0);
glTexCoord2f(0.0, 1.0);
glVertex3f(100.0, 100.0, 0.0);
glEnd();
DeactivateTexture( torender);
glPushMatrix();
glTranslatef( 0, 100, 0 );
glScalef( 0.1*ScreenW/250.0, 0.1*ScreenH/250.0, 0.0 );
glScalef(1, -1, 1);
char stx[85];
sprintf( stx, "[BRIDGE SIM %4.2f]", ElapsedTime );
if( bridgesim ) DestroyGPUGeometry( bridgesim );
bridgesim = EmitGeometryFromFontString( captureitfont, stx, 0 );
CheckForNewerShader( textshader );
ApplyShader( textshader, shaderprops );
RenderGPUGeometry( bridgesim );
CancelShader( textshader );
glPopMatrix();
/*
glPushMatrix();
glTranslatef( 0, 20, 0 );
glScalef( 0.005*g_width/250.0, 0.005*g_width/250.0, 0.0 );
CheckForNewerShader( texcoords );
ApplyShader( texcoords, shaderprops );
RenderGPUGeometry( lottatext );
RenderGPUGeometry( lottatext );
CancelShader( texcoords );
glPopMatrix();
*/
glFlush();
}
int main(int argc, char **argv)
{
int i;
glutInit( &argc, argv );
glutCreateWindow( "Test" );
if( glewInit() != GLEW_OK )
{
fprintf( stderr, "Error: GLEW Fault.\n" );
return 0;
}
StartTime = OGGetAbsoluteTime();
defshader = CreateShader( "../../assets/shaders/default" );
texcoords = CreateShader( "../../assets/shaders/texcoords" );
textshader = CreateShader( "../../assets/shaders/text" );
modelshader = CreateShader( "../../assets/shaders/model" );
SetupShaderProps();
testtex = CreateTexture();
ReadTextureFromFile( testtex, "test.jpg" );
UpdateDataInOpenGL( testtex );
myrb = MakeRFBuffer( 1, TTRGBA );
torender = CreateTexture();
mbf = LoadBitmapFontByName( "../../assets/fonts/OldSansBlack.hgfont" );
captureitfont = LoadBitmapFontByName( "../../assets/fonts/CaptureIt.hgfont" );
helloworld = EmitGeometryFromFontString( mbf, "Hello, world.", 0 );
struct OBJFile * model = OpenOBJ( "../../assets/models/g1.obj", 1 );
modelgeo = model->Objects[0]->geometry;
char stx[65536];
for( i = 0; i < 65535; i++ )
{
if( (i % 350) == 0 )
stx[i] = '\n';
else
stx[i] = (rand()%95) + 32;
}
stx[i] = 0;
lottatext = EmitGeometryFromFontString( captureitfont, stx, 0 );
RenderGPUGeometry( lottatext );
glutDisplayFunc( display );
glutReshapeFunc( reshape );
glutIdleFunc( idle );
glutMainLoop();
return 0;
}
|
cnlohr/bridgesim
|
src/cclient/test.c
|
#include <stdio.h>
#include <GL/glew.h>
#include <GL/freeglut.h>
#include "graphicscore.h"
#include "bitmapfont.h"
#include <os_generic.h>
#include "objreader.h"
#include <math.h>
#include "commonassets.h"
#include "guibase.h"
#include "button.h"
#include "glutmain.h"
#include <string.h>
double StartTime;
double LastFPSTime;
int framecountsincefps;
int fpscount;
struct GPUGeometry * helloworld;
struct GUIWindow * guiwindow;
void MouseMotion( double x, double y, int mask )
{
WindowHandleMouseMove( guiwindow, x, y, mask );
}
void MouseClick( double x, double y, int button, int state )
{
WindowHandleMouseClick( guiwindow, x, y, button, state );
}
void HandleKeyboard( int c, int down )
{
WindowHandleKeyboard( guiwindow, c, down );
}
void UpdatedDisplay(void)
{
CheckCommonAssets();
glClearColor( .2, .2, .2, 0 );
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glEnable (GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glEnable( GL_DEPTH_TEST );
glDepthFunc(GL_LESS);
guiwindow->width = ScreenW;
guiwindow->height = ScreenH;
WindowRender( guiwindow );
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(0, ScreenW, 0, ScreenH, -1, 1);
glDepthFunc(GL_ALWAYS);
glScalef(1, -1, 1);
glTranslatef(0, -ScreenH, 0);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
char st[15];
sprintf( st, "FPS: %d", fpscount );
glRasterPos2f(80, 50);
glutBitmapString( GLUT_BITMAP_9_BY_15, st );
ActivateTexture( guiwindow->torender );
DrawSquare(0,0,ScreenW,ScreenH );
DeactivateTexture( guiwindow->torender );
glLoadIdentity();
glFlush();
}
int main(int argc, char **argv)
{
StartGlutMain( argc, argv, "test", 640, 480 );
SetupCommonAssets();
guiwindow = CreateGUIWindow( );
guiwindow->width = 300;
guiwindow->height = 300;
struct GUIBase * b;
WindowAddElement( guiwindow, b = CreateButton( guiwindow, "Hi!" ) );
SetMouseWarpMode( 0 );
DoGlutLoop();
}
|
cnlohr/bridgesim
|
src/cclient/gui/button.h
|
#ifndef _BUTTON_H
#define _BUTTON_H
#include "commonassets.h"
#include "guibase.h"
struct Button
{
float x, y;
float w, h;
float color[4];
int depressed;
int clicked;
int focused;
struct GUIWindow * wp;
void (*Prerender)( struct Button * b );
void (*Render)( struct Button * b );
int (*CheckClick)( struct GUIBase * b, float screenx, float screeny, int button, int down ); //Return 0 if received event.
void (*HandleMove)( struct GUIBase * b, float screenx, float screeny, int buttonmask ); //Return 0 if received event.
void (*HandleKeyboard)( struct GUIBase * b, char c, int down, int focused ); //If unfocused, treat as a hotkey only.
void (*DestroyMe)( struct Button * b );
void (*ProcessClick)( struct Button * b );
char * text;
char * oldtext;
struct GPUGeometry * geotext;
};
struct GUIBase * CreateButton( struct GUIWindow * parent, const char * text );
//Below here are kind of private-ish.
//Assumes you are in ortho or an orto-like mode.
void ButtonRender( struct Button * b );
void ButtonDestroyMe( struct Button * b );
void ButtonProcessClick( struct Button * b );
#endif
|
cnlohr/bridgesim
|
src/cclient/commonassets.h
|
#ifndef _COMMONASSETS_H
#define _COMMONASSETS_H
#include "graphicscore.h"
#include "bitmapfont.h"
#include <os_generic.h>
#include "objreader.h"
extern struct UniformMatch * OverallUniforms;
extern struct Shader * ButtonShader;
extern struct Shader * TextShader;
extern struct BitmapFont * OldSansBlack;
extern float Ambient[4];
extern float Emission[4];
void SetupCommonAssets();
void CheckCommonAssets();
#endif
|
cnlohr/bridgesim
|
src/cclient/graphics/objreader.c
|
//Copyright 2013 <>< <NAME>, Relicensed under the MIT/x11 License.
#include "objreader.h"
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include "3dutils.h"
#define TBUFFERSIZE 256
#define VBUFFERSIZE 524288
struct TempObject
{
char CNameBuffer[TBUFFERSIZE];
int CVertCount;
float CVerts[VBUFFERSIZE*3];
int CNormalCount;
float CNormals[VBUFFERSIZE*3];
int CTexCount;
float CTexs[VBUFFERSIZE*3];
int CTriCount;
int CFaces[VBUFFERSIZE*9];
};
void ResetTempObject( struct TempObject * o )
{
memset( o, 0, sizeof( struct TempObject ) );
}
void CommitObject( struct TempObject * o, struct OBJFile * f )
{
int i, j;
struct OBJObject * oo = malloc( sizeof( struct OBJObject ) );
f->Objects[f->NumObjects++] = oo;
oo->OName = strdup( o->CNameBuffer );
oo->VertCount = o->CVertCount;
oo->Vertices = malloc( oo->VertCount * sizeof( float ) * 3 );
memcpy( oo->Vertices, o->CVerts, oo->VertCount * sizeof( float ) * 3 );
oo->NormalCount = o->CNormalCount;
oo->Normals = malloc( oo->NormalCount * sizeof( float ) * 3 );
memcpy( oo->Normals, o->CNormals, oo->NormalCount * sizeof( float ) * 3 );
oo->TexCount = o->CTexCount;
oo->Textures = malloc(o->CTexCount * sizeof( float ) * 3 );
memcpy( oo->Textures, o->CTexs, o->CTexCount * sizeof( float ) * 3 );
oo->TriCount = o->CTriCount;
oo->Faces = malloc( o->CTriCount * sizeof( int ) * 9 );
memcpy( oo->Faces, o->CFaces, o->CTriCount * sizeof( int ) * 9 );
for( j = 0; j < 3; j++ )
{
oo->mins[j] = 1e20;
oo->maxs[j] = -1e20;
}
for( i = 0; i < oo->VertCount; i++ )
{
for( j = 0; j < 3; j++ )
{
float t = oo->Vertices[j + i*3];
if( t < oo->mins[j] ) oo->mins[j] = t;
if( t > oo->maxs[j] ) oo->maxs[j] = t;
}
}
for( j = 0; j < 3; j++ )
{
oo->center[j] = ( oo->maxs[j] + oo->mins[j] ) / 2.f;
}
//Make OPENGLized geometry.
//Technique: If vertex, texture and normal match, this is a valid index.
// If something doesn't match up, need to make a new entry.
float * OutputVerts = 0;
float * OutputTexs = 0;
float * OutputNorms = 0;
int * OutputIndices = malloc( oo->TriCount * 3 * sizeof( float ) );
if( oo->VertCount ) OutputVerts = malloc( oo->TriCount * 3 * sizeof( float ) * 3 );
if( oo->TexCount ) OutputTexs = malloc( oo->TriCount * 3 * sizeof( float ) * 3 );
if( oo->NormalCount) OutputNorms = malloc( oo->TriCount * 3 * sizeof( float ) * 3 );
int OutputVertCount = 0;
for( i = 0; i < oo->TriCount*3; i++ )
{
int match = -1;
int indexV = oo->Faces[i*3+0];
int indexT = oo->Faces[i*3+1];
int indexN = oo->Faces[i*3+2];
float * pos = &oo->Vertices[indexV*3];
float * tex = &oo->Textures[indexT*3];
float * nrm = &oo->Normals[indexN*3];
if( oo->VertCount == 0 ) pos = 0;
if( oo->TexCount == 0 ) tex = 0;
if( oo->NormalCount == 0 ) nrm = 0;
for( j = 0; j < OutputVertCount; j++ )
{
int m1 = compare3d( pos, &OutputVerts[j*3], DEFAULT_EPSILON );
m1 |= compare3d( tex, &OutputTexs[j*3], DEFAULT_EPSILON );
m1 |= compare3d( nrm, &OutputNorms[j*3], DEFAULT_EPSILON );
if( m1 ) continue;
}
if( j == OutputVertCount )
{
copy3d( &OutputVerts[j*3], pos );
if( tex )
copy3d( &OutputTexs[j*3], tex );
if( nrm )
copy3d( &OutputNorms[j*3], nrm );
OutputVertCount++;
}
OutputIndices[i] = j;
}
float * OutputTangents = 0;
if( OutputVerts && OutputNorms && OutputTexs )
OutputTangents = CalculateTangentSpace( o->CTriCount, OutputVertCount, OutputIndices, OutputVerts, OutputNorms, OutputTexs );
int vertentrycount = 1;
struct VertexData ** vertslist = malloc( sizeof( struct VertexData * ) * 4 );
char * names[4];
struct IndexData * indices = IndexDataCreate();
UpdateIndexData( indices, o->CTriCount * 3, OutputIndices );
struct VertexData * positions = VertexDataCreate();
UpdateVertexData( positions, OutputVerts, OutputVertCount, 3 );
names[0] = 0;
vertslist[0] = positions;
if( OutputTexs )
{
struct VertexData * texs = VertexDataCreate();
UpdateVertexData( texs, OutputTexs, OutputVertCount, 3 );
names[vertentrycount] = strdup( "texture" );
vertslist[vertentrycount] = texs;
vertentrycount++;
}
if( OutputNorms )
{
struct VertexData * norms = VertexDataCreate();
UpdateVertexData( norms, OutputNorms, OutputVertCount, 3 );
names[vertentrycount] = strdup( "normal" );
vertslist[vertentrycount] = norms;
vertentrycount++;
}
if( OutputTangents )
{
struct VertexData * tans = VertexDataCreate();
UpdateVertexData( tans, OutputTangents, OutputVertCount, 4 );
names[vertentrycount] = strdup( "tangent" );
vertslist[vertentrycount] = tans;
vertentrycount++;
}
free( OutputIndices );
if( OutputVerts ) free( OutputVerts );
if( OutputTexs ) free( OutputTexs );
if( OutputNorms ) free( OutputNorms );
if( OutputTangents ) free( OutputTangents );
oo->geometry = CreateGeometry( indices, vertentrycount, vertslist, names, 1, GL_TRIANGLES );
copy3d( oo->geometry->maxs, oo->maxs );
copy3d( oo->geometry->mins, oo->mins );
for( i = 1; i < vertentrycount; i++ )
{
free( names[i] );
}
}
int ReadOneLine( FILE * f, char * buffer )
{
int c;
int i = 0;
while( ( c = fgetc( f ) ) != EOF )
{
if( c == '\r' ) continue;
if( c == '\n' ) break;
buffer[i++] = c;
}
buffer[i] = 0;
return i;
}
struct OBJFile * OpenOBJ( const char * Filename, int flipv )
{
char LineBuffer[TBUFFERSIZE];
struct TempObject * t = malloc( sizeof( struct TempObject ) );;
int CurrentVertOffset = 0;
int CurrentNormOffset = 0;
int CurrentTexOffset = 0;
ResetTempObject( t );
FILE * f = fopen( Filename, "r" );
if( !f )
{
fprintf( stderr, "Error: cannot open file.\n" );
return 0;
}
struct OBJFile * ret = malloc( sizeof( struct OBJFile ) );
ret->Filename = strdup( Filename );
ret->NumObjects = 0;
while( !feof( f ) && !ferror( f ) )
{
int r = ReadOneLine( f, LineBuffer );
if( r < 2 ) continue;
if( tolower( LineBuffer[0] ) == 'v' )
{
if( tolower( LineBuffer[1] ) == 'n' )
{
int r = sscanf( LineBuffer + 3, "%f %f %f",
&t->CNormals[0 + t->CNormalCount * 3],
&t->CNormals[1 + t->CNormalCount * 3],
&t->CNormals[2 + t->CNormalCount * 3] );
if( r == 3 )
t->CNormalCount++;
}
else if( tolower( LineBuffer[1] ) == 't' )
{
int r = sscanf( LineBuffer + 3, "%f %f %f",
&t->CTexs[0 + t->CTexCount * 3],
&t->CTexs[1 + t->CTexCount * 3],
&t->CTexs[2 + t->CTexCount * 3] );
if( flipv )
t->CTexs[1 + t->CTexCount * 3] = 1. - t->CTexs[1 + t->CTexCount * 3];
if( r == 3 || r == 2 )
t->CTexCount++;
else
{
fprintf( stderr, "Error: Invalid Tex (%d) (%s)\n", r, LineBuffer + 3 );
}
}
else
{
int r = sscanf( LineBuffer + 2, "%f %f %f",
&t->CVerts[0 + t->CVertCount * 3],
&t->CVerts[1 + t->CVertCount * 3],
&t->CVerts[2 + t->CVertCount * 3] );
if( r == 3 )
t->CVertCount++;
else
{
fprintf( stderr, "Error: Invalid Vertex\n" );
}
}
}
else if( tolower( LineBuffer[0] ) == 'f' )
{
char buffer[3][TBUFFERSIZE];
int p = 0;
int facemark = t->CTriCount * 9;
int r = sscanf( LineBuffer + 1, "%30s %30s %30s",
buffer[0], buffer[1], buffer[2] );
if( r == 0 )
{
//Invalid line - continue.
continue;
}
else if( r == 1 )
{
memcpy( buffer[1], buffer[0], TBUFFERSIZE );
memcpy( buffer[2], buffer[0], TBUFFERSIZE );
}
else if( r == 2 )
{
memcpy( buffer[2], buffer[1], TBUFFERSIZE );
}
//Whatever... they're all populated with something now, even if it is largely useless.
for( p = 0; p < 3; p++ )
{
char buffer2[3][TBUFFERSIZE];
int mark = 0, markb = 0;
int i;
int sl = strlen( buffer[p] );
for( i = 0; i < sl; i++ )
{
if( buffer[p][i] == '/' )
{
buffer2[mark][markb] = 0;
mark++;
if( mark >= 3 ) break;
markb = 0;
}
else
buffer2[mark][markb++] = buffer[p][i];
}
buffer2[mark][markb] = 0;
for( i = mark+1; i < 3; i++ )
buffer2[i][0] = 0;
t->CFaces[facemark++] = atoi( buffer2[0] ) - 1 - CurrentVertOffset;
t->CFaces[facemark++] = atoi( buffer2[1] ) - 1 - CurrentTexOffset;
t->CFaces[facemark++] = atoi( buffer2[2] ) - 1 - CurrentNormOffset;
}
t->CTriCount++;
}
else if( tolower( LineBuffer[0] ) == 'o' )
{
if( t->CFaces && t->CTriCount)
{
CurrentVertOffset += t->CVertCount;
CurrentNormOffset += t->CNormalCount;
CurrentTexOffset += t->CTexCount;
CommitObject( t, ret );
ResetTempObject( t );
}
memcpy( t->CNameBuffer, &LineBuffer[2], strlen( &LineBuffer[2] ) );
}
else if( strncmp( LineBuffer, "usemtl", 6 ) == 0 )
{
//Not implemented.
}
else if( strncmp( LineBuffer, "mtllib", 6 ) == 0 )
{
//Not implemented.
}
else if( tolower( LineBuffer[0] ) == 's' )
{
//Not implemented.
}
}
if( t->CFaces )
{
CommitObject( t, ret );
}
fclose( f );
free( t );
return ret;
}
|
cnlohr/bridgesim
|
src/cclient/graphics/bitmapfont.c
|
#include "bitmapfont.h"
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
struct BitmapFont * LoadBitmapFontByName( const char * fontpath )
{
int line = 0;
struct BitmapFont * ret = 0;
char sfname[2048];
FILE * f = fopen( fontpath, "r" );
if( !f )
{
fprintf( stderr, "Error: could not open up path to: %s\n", fontpath );
}
if( strlen( fontpath ) > 1024 )
{
fprintf( stderr, "Error: pathname to font too long: %s\n", fontpath );
fclose( f );
return 0;
}
memcpy( sfname, fontpath, strlen( fontpath )+1 );
char * rr = strrchr( sfname, '/' );
if( !rr || fscanf( f, "%1000s\n", rr+1 ) != 1 )
{
fprintf( stderr, "Error: could not find font image in font: %s\n", fontpath );
return 0;
}
struct Texture * t = CreateTexture();
if( ReadTextureFromFile( t, sfname ) )
{
fprintf( stderr, "Error: could not load font image for: %s\n", fontpath );
goto cancel;
}
UpdateDataInOpenGL( t );
ret = malloc( sizeof( struct BitmapFont ) );
memset( ret, 0, sizeof( struct BitmapFont ) );
if( fscanf( f, "%f %f %f %f\n", &ret->fontsize, &ret->A, &ret->B, &ret->C ) != 4 )
{
fprintf( stderr, "Error: first line of font is corrupt: %s\n", fontpath );
goto cancel;
}
while( !feof( f ) && !ferror( f ) )
{
struct MChar m;
int actualchar;
int r = fscanf( f, "%d %f %f %f %f %d %d %d %d\n", &actualchar, &m.loffx, &m.loffy,
&m.loffxe, &m.loffye, &m.iW, &m.lbitrows, &m.bitmapleft, &m.bitmaptop );
if( r != 9 )
{
fgetc( f );
continue;
}
memcpy( &ret->chars[actualchar], &m, sizeof( struct MChar ) );
line++;
}
ChangeTextureFilter( t, 1 );
ret->fonttex = t;
return ret;
cancel:
fclose( f );
DestroyTexture( t );
if( ret )
free( ret );
return 0;
}
struct GPUGeometry * EmitGeometryFromFontString( struct BitmapFont * bf, const char * str, int flags )
{
if( !bf )
{
fprintf( stderr, "Error: Fault. Cannot find bitmapfont.\n ");
return 0;
}
struct GPUGeometry * ret;
struct VertexData * vd; //Places
struct VertexData * tc; //Texture coords.
struct IndexData * id;
int slen, i, actualchars;
int * indexdata;
float * verts;
float * tcs;
int line = 0;
float progressx = 0;
float gminx = 1e20;
float gminy = 1e20;
float gmaxx = -1e20;
float gmaxy = -1e20;
if( str == 0 || *str == 0 ) return 0;
slen = strlen( str );
indexdata = malloc( 6 * sizeof(int) * slen );
verts = malloc( 4 * 2 * sizeof( float ) * slen );
tcs = malloc( 4 * 2 * sizeof( float ) * slen );
actualchars = 0;
for( i = 0; i < slen; i++ )
{
if( str[i] == '\n' )
{
line++;
progressx = 0;
continue;
}
struct MChar * mc = &bf->chars[(unsigned char)str[i]];
indexdata[i*6+0] = i * 4;
indexdata[i*6+1] = i * 4 + 1;
indexdata[i*6+2] = i * 4 + 2;
indexdata[i*6+3] = i * 4 + 2;
indexdata[i*6+4] = i * 4 + 1;
indexdata[i*6+5] = i * 4 + 3;
tcs[i*2*4+0] = mc->loffx; tcs[i*2*4+1] = mc->loffy;
tcs[i*2*4+2] = mc->loffxe; tcs[i*2*4+3] = mc->loffy;
tcs[i*2*4+4] = mc->loffx; tcs[i*2*4+5] = mc->loffye;
tcs[i*2*4+6] = mc->loffxe; tcs[i*2*4+7] = mc->loffye;
float minx = progressx;// + mc->bitmapleft/3.0f;
float miny = mc->bitmaptop + line * bf->fontsize;
float maxx = minx + mc->iW;
float maxy = mc->bitmaptop - mc->lbitrows + line * bf->fontsize;
if( flags & TEXTFLIPY )
{
maxy = bf->fontsize - maxy;
miny = bf->fontsize - miny;
}
verts[i*2*4+0] = minx; verts[i*2*4+1] = miny;
verts[i*2*4+2] = maxx; verts[i*2*4+3] = miny;
verts[i*2*4+4] = minx; verts[i*2*4+5] = maxy;
verts[i*2*4+6] = maxx; verts[i*2*4+7] = maxy;
if( minx < gminx ) gminx = minx;
if( miny < gminy ) gminy = miny;
if( maxx > gmaxx ) gmaxx = maxx;
if( maxy > gmaxy ) gmaxy = maxy;
actualchars++;
progressx += mc->iW + bf->A;
}
id = IndexDataCreate();
vd = VertexDataCreate();
tc = VertexDataCreate();
UpdateIndexData( id, 6 * actualchars, indexdata );
UpdateVertexData( vd, verts, actualchars * 4, 2 );
UpdateVertexData( tc, tcs, actualchars * 4, 2 );
free( indexdata );
free( verts );
free( tcs );
struct VertexData ** vertslist = malloc( sizeof( struct VertexData * ) * 2 );
vertslist[0] = vd;
vertslist[1] = tc;
char ** names = malloc( sizeof( char * ) * 2 );
names[0] = 0;
names[1] = strdup( "texture" );
ret = CreateGeometry( id, 2, vertslist, names, 1, GL_TRIANGLES );
ret->mins[0] = gminx;
ret->mins[1] = gminy;
ret->mins[2] = 0;
ret->maxs[0] = gmaxx;
ret->maxs[1] = gmaxy;
ret->maxs[2] = 0;
AttachTextureToGeometry( ret, bf->fonttex, 0, 0 );
free( names[1] );
free( names );
return ret;
}
|
cnlohr/bridgesim
|
src/cclient/graphics/bitmapfont.h
|
<reponame>cnlohr/bridgesim<filename>src/cclient/graphics/bitmapfont.h
#ifndef _BITMAPFONT_H
#define _BITMAPFONT_H
#include "graphicscore.h"
struct MChar
{
float loffx; //(U,V Tex coord) (Upper left)
float loffy;
float loffxe; //(U,V Tex coord) (Lower right)
float loffye;
int iW; //Pixles Width
int lbitrows; //Pixels Height
int bitmapleft; //Position left
int bitmaptop; //Position up (from bottom)
};
struct BitmapFont
{
struct MChar chars[256];
struct Texture * fonttex;
float fontsize;
float A, B, C; //???????
};
struct BitmapFont * LoadBitmapFontByName( const char * fontpath );
#define TEXTFLIPY 1
struct GPUGeometry * EmitGeometryFromFontString( struct BitmapFont * bf, const char * str, int flags );
#endif
|
cnlohr/bridgesim
|
src/cclient/gui/guibase.c
|
#include "guibase.h"
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
void GenericHandleKeyboard( struct GUIBase * b, int c, int down, int focused )
{
if( b->focused )
{
if( c == '\n' || c == ' ' )
{
if( b->depressed && !down )
{
b->ProcessClick( b );
}
else if( down )
{
b->depressed = 1;
}
}
}
}
void GenericHandleMove( struct GUIBase * b, float screenx, float screeny, int buttonmask )
{
int inside = b->x <= screenx && b->y <= screeny && b->x + b->w >= screenx && b->y + b->h >= screeny;
if( (buttonmask & 1) && b->clicked )
{
if( inside )
b->depressed = 1;
else
b->depressed = 0;
}
}
int GenericCheckClick( struct GUIBase * b, float screenx, float screeny, int button, int down )
{
int inside = b->x <= screenx && b->y <= screeny && b->x + b->w >= screenx && b->y + b->h >= screeny;
if( button != 0 ) return;
if( down )
{
if( inside )
{
b->depressed = 1;
b->clicked = 1;
if( b->w )
{
WindowTakeFocus( b->wp, b );
}
return 0;
}
else
return -1;
}
else
{
if( b->clicked && inside )
{
b->ProcessClick( b );
}
b->clicked = 0;
b->depressed = 0;
}
}
struct GUIWindow * CreateGUIWindow()
{
struct GUIWindow * ret = malloc( sizeof( struct GUIWindow ) );
memset( ret->elements, 0, sizeof( ret->elements ) );
ret->renderbuffer = MakeRFBuffer( 0, TTRGBA );
ret->torender = CreateTexture();
return ret;
}
void WindowHandleMouseMove( struct GUIWindow * w, float x, float y, int mask )
{
int i;
for( i = 0; i < MAX_GUI_ELEMENTS; i++ )
{
struct GUIBase * g = w->elements[i];
if( g && g->HandleMove )
g->HandleMove( g, x, y, mask );
}
}
void WindowHandleMouseClick( struct GUIWindow * w, float x, float y, int button, int down )
{
int i;
for( i = 0; i < MAX_GUI_ELEMENTS; i++ )
{
struct GUIBase * g = w->elements[i];
if( g && g->CheckClick )
g->CheckClick( g, x, y, button, down );
}
}
void WindowHandleKeyboard( struct GUIWindow * w, int c, int down )
{
int i;
for( i = 0; i < MAX_GUI_ELEMENTS; i++ )
{
struct GUIBase * g = w->elements[i];
if( g && g->HandleKeyboard )
g->HandleKeyboard( g, c, down, i==w->focusid );
}
}
void DestroyGUIWindow( struct GUIWindow * w )
{
int i;
for( i = 0; i < MAX_GUI_ELEMENTS; i++ )
{
struct GUIBase * g = w->elements[i];
if( g && g->DestroyMe ) g->DestroyMe( g );
}
if( w->renderbuffer ) DestroyRFBuffer( w->renderbuffer );
if( w->torender ) DestroyTexture( w->torender );
}
void WindowTakeFocus( struct GUIWindow * w, struct GUIBase * g )
{
int i;
for( i = 0; i < MAX_GUI_ELEMENTS; i++ )
{
if( g == w->elements[i] )
{
if( w->focusid >= 0 )
w->elements[w->focusid]->focused = 0;
w->elements[i]->focused = 1;
w->focusid = i;
return;
}
}
}
void WindowRender( struct GUIWindow * w )
{
int i;
for( i = 0; i < MAX_GUI_ELEMENTS; i++ )
{
struct GUIBase * g = w->elements[i];
if( g && g->Prerender ) g->Prerender( g );
}
RFBufferGo( w->renderbuffer, w->width, w->height, 1, &w->torender, 1 );
glMatrixMode(GL_PROJECTION);
glPushMatrix();
glLoadIdentity();
glOrtho(0, w->width, 0, w->height, -1, 1);
glDepthFunc(GL_ALWAYS);
//Flip-y
// glScalef(1, -1, 1);
// glTranslatef(0, -w->height, 0);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glPushMatrix();
for( i = 0; i < MAX_GUI_ELEMENTS; i++ )
{
struct GUIBase * g = w->elements[i];
if( g && g->Render ) g->Render( g );
}
glMatrixMode(GL_PROJECTION);
glPopMatrix();
glMatrixMode(GL_MODELVIEW);
glPopMatrix();
RFBufferDone( w->renderbuffer );
}
void WindowAddElement( struct GUIWindow * w, struct GUIBase * g )
{
int i;
for( i = 0; i < MAX_GUI_ELEMENTS; i++ )
{
if( !w->elements[i] )
{
w->elements[i] = g;
return;
}
}
if( i == MAX_GUI_ELEMENTS )
{
fprintf( stderr, "Error: too many GUI Elements.\n" );
}
}
void WindowRemoveElement( struct GUIWindow * w, struct GUIBase * g )
{
int i;
for( i = 0; i < MAX_GUI_ELEMENTS; i++ )
{
if( w->elements[i] == g )
w->elements[i] = 0;
}
}
|
cnlohr/bridgesim
|
src/cclient/commonassets.c
|
#include "commonassets.h"
struct UniformMatch * OverallUniforms;
struct Shader * ButtonShader;
struct Shader * TextShader;
struct BitmapFont * OldSansBlack;
float Ambient[4];
float Emission[4];
float TexSlot0;
float TexSlot1;
void SetupCommonAssets()
{
ButtonShader = CreateShader( "../assets/shaders/button" );
TextShader = CreateShader( "../assets/shaders/text" );
OldSansBlack = LoadBitmapFontByName( "../assets/fonts/OldSansBlack.hgfont" );
OverallUniforms = UniformMatchMake( "AmbientColor", Ambient, 0, 4, 0 );
OverallUniforms = UniformMatchMake( "EmissionColor", Emission, 0, 4, OverallUniforms );
OverallUniforms = UniformMatchMake( "tex0", &TexSlot0, 1, 0, OverallUniforms );
OverallUniforms = UniformMatchMake( "tex1", &TexSlot1, 1, 0, OverallUniforms );
OverallUniforms = UniformMatchMake( "RenderW", &RenderW, 1, 0, OverallUniforms );
OverallUniforms = UniformMatchMake( "RenderH", &RenderH, 1, 0, OverallUniforms );
}
void CheckCommonAssets()
{
CheckForNewerShader( TextShader );
CheckForNewerShader( ButtonShader );
}
|
cnlohr/bridgesim
|
src/cclient/graphics/graphicscore.h
|
#ifndef _GARPHICSCORE_H
#define _GARPHICSCORE_H
#include <stdint.h>
#include <GL/gl.h>
#define USE_PNG
#define USE_JPG
#define USE_IBO
#define MAX_TEXTURES 16
extern double TotalTime;
extern double DeltaTime;
extern float RenderW;
extern float RenderH;
extern float ScreenW;
extern float ScreenH;
struct Shader
{
GLuint vertex;
GLuint fragment;
GLuint program;
char * VertexName;
char * FragmentName;
double LastFileTimeVertex;
double LastFileTimeFragment;
};
struct UniformMatch
{
const char * name;
float * data;
int intcount;
int floatcount;
struct UniformMatch * next;
};
//Shaders utilities
struct Shader * CreateShader( const char * file ); //Returns a shader even if compilation fails.
void ApplyShader( struct Shader * shader, struct UniformMatch * match );
struct UniformMatch * UniformMatchMake( const char* name, float * data, int intcount, int floatcount, struct UniformMatch * prev );
void CancelShader( struct Shader * s );
void DeleteShader( struct Shader * s );
void CheckForNewer( struct Shader * s );
enum TextureType
{
TTUNDEFINED = 0,
TTGRAYSCALE,
TTGRAYALPHA,
TTRGB,
TTRGBA,
TTRGBA16,
TTRGBA32,
};
struct Texture
{
enum TextureType format;
GLenum type; //Almost always GL_TEXTURE_2D (Could be GL_TEXTURE_3D)
GLuint texture; //Texture ID
int width, height;
int slot; //which texture slot (For multi-texturing)
uint8_t * rawdata; //May be other types, too!
};
struct Texture * CreateTexture();
//Zero return = OKAY! Nonzero = bad.
int ReadTextureFromFile( struct Texture * t, const char * filename );
void MakeDynamicTexture2D( struct Texture * t, int width, int height, enum TextureType tt );
void UpdateDataInOpenGL( struct Texture * t );
void ActivateTexture( struct Texture * t );
void DeactivateTexture( struct Texture * t );
void DestroyTexture( struct Texture * t );
void ChangeTextureFilter( struct Texture * t, int linear );
struct RFBuffer
{
int width, height;
int use_depth_buffer;
enum TextureType mtt;
GLuint renderbuffer;
GLuint outputbuffer;
int outextures;
};
struct RFBuffer * MakeRFBuffer( int use_depth_buffer, enum TextureType type );
int RFBufferGo( struct RFBuffer *rb, int width, int height, int texturecount, struct Texture ** textures, int do_clear );
void RFBufferDone( struct RFBuffer *rb );
void DestroyRFBuffer( struct RFBuffer *rb );
unsigned char * ReadDataFile( const char * name ); //Read a file and malloc
//VBOs
struct VertexData
{
int vertexcount;
int stride;
GLuint vbo;
};
struct IndexData
{
int indexcount;
#ifdef USE_IBO
GLuint ido;
#else
GLuint * indexdata;
#endif
};
struct GPUGeometry
{
struct Texture * textures[MAX_TEXTURES];
int todelete[MAX_TEXTURES]; //if 1, will delete texture
struct IndexData * indices;
int vertexcount;
struct VertexData ** vertexdatas;
char ** names;
//If 1, will cause indices, and vertexdatas to be deleted with names. If 0, only names will be deleted.
int uniquedata;
GLint mode;
float maxs[3];
float mins[3];
};
struct VertexData * VertexDataCreate();
//Call with verts=0 to make a strippable buffer (GPGPU only)
void UpdateVertexData( struct VertexData * vd, float * Verts, int iNumVerts, int iStride );
void DestroyVertexData( struct VertexData * vd );
struct IndexData * IndexDataCreate();
void UpdateIndexData( struct IndexData * id, int indexcount, int * data );
void DestroyIndexData( struct IndexData * id );
//Names[0] doesn't matter, but for all other names, it binds to a specific shader property.
//the 0th vd will ALWAYS be vertex position.
//
//if you say "texcoord" it will bind to that text coord.
//if you say "color" it will bind to the color.
struct GPUGeometry * CreateGeometry( struct IndexData * indices, int vertexcount, struct VertexData ** verts, char ** names, int unique, GLint mode );
void AttachTextureToGeometry( struct GPUGeometry * g, struct Texture * texture, int place, int take_ownership_of );
void RenderGPUGeometry( struct GPUGeometry * g );
void DestroyGPUGeometry( struct GPUGeometry * g );
//TODO: Shaders: Global parameters, i.e. for size-of-textures?
//TODO: Model loading
void DrawSquare( float x, float y, float w, float h );
#endif
|
cnlohr/bridgesim
|
src/cclient/util/3dutils.c
|
#include "3dutils.h"
#include <stdlib.h>
#include <string.h>
//WARNING: This function probably doesn't work AT ALL!
float * CalculateTangentSpace( int Triangles, int VertexCount, int * Indices, float * verts, float * normals, float * texs )
{
//Here is the place to calculate the Tangent values.
//It is a vector pointing in the direction of increasing u.
int i;
float * tans = 0;
if( normals && texs && verts )
{
//If we have both Texture coords and normals, we can calculate a tangent matrix.
tans = malloc( VertexCount * sizeof( float ) * 4 );
memset( tans, 0, VertexCount * sizeof( float ) * 4 );
//Process modeled after: http://www.terathon.com/code/tangent.html
float * tan1 = malloc( VertexCount * sizeof( float ) * 3 );
float * tan2 = malloc( VertexCount * sizeof( float ) * 3 );
memset( tan1, 0, VertexCount * sizeof( float ) * 3 );
memset( tan2, 0, VertexCount * sizeof( float ) * 3 );
for( i = 0; i < Triangles; i++ )
{
int v1 = Indices[i*3+0];
int v2 = Indices[i*3+1];
int v3 = Indices[i*3+2];
float * t1 = &texs[v1*3];
float * t2 = &texs[v2*3];
float * t3 = &texs[v3*3];
float * p1 = &verts[v1*3];
float * p2 = &verts[v2*3];
float * p3 = &verts[v3*3];
float vec1[3];
float vec2[3];
float tex1[3];
float tex2[3];
sub3d( vec1, p2, p1 ); //(x,y,z)
sub3d( vec2, p3, p1 );
sub3d( tex1, t2, t1 ); //(s,t,u)
sub3d( tex2, t3, t1 );
float r = 1.0f / ( tex1[0] * tex2[1] - tex2[0] * tex1[1] );
float sdir[3] = {
(tex2[1] * vec1[0] - tex1[1] * vec2[0]) * r,
(tex2[1] * vec1[1] - tex1[1] * vec2[1]) * r,
(tex2[1] * vec1[2] - tex1[1] * vec2[2]) * r };
float tdir[3] = {
(tex1[0] * vec2[0] - tex2[0] * vec1[0]) * r,
(tex1[0] * vec2[1] - tex2[0] * vec1[1]) * r,
(tex1[0] * vec2[2] - tex2[0] * vec1[2]) * r };
add3d( &tan1[v1*3], &tan1[v1*3], sdir );
add3d( &tan1[v2*3], &tan1[v2*3], sdir );
add3d( &tan1[v3*3], &tan1[v3*3], sdir );
add3d( &tan2[v1*3], &tan2[v1*3], sdir );
add3d( &tan2[v2*3], &tan2[v2*3], sdir );
add3d( &tan2[v3*3], &tan2[v3*3], sdir );
}
//Normalize and orthoganlize.
for (i = 0; i < VertexCount; i++)
{
const float * n = &normals[i*3];
const float * t = &tan1[i*3];
// Gram-Schmidt orthogonalize
float tmp[3];
float tdn[3];
float thisdot = dot3d( n, t );
scale3d( tdn, n, thisdot );
sub3d( tmp, t, tdn );
normalize3d( &tans[i*4], tmp );
cross3d( tmp, n, t );
tans[i*4+3] = (dot3d( tmp, &tan2[i*3] ) < 0)?-1:1; //set handedness
}
}
return tans;
}
|
cnlohr/bridgesim
|
src/cclient/gui/guibase.h
|
<filename>src/cclient/gui/guibase.h<gh_stars>1-10
#ifndef _GUIBASE_H
#define _GUIBASE_H
#define MAX_GUI_ELEMENTS 2048
#include "graphicscore.h"
struct GUIWindow;
struct GUIBase
{
float x, y;
float w, h;
float color[4];
int depressed;
int clicked;
int focused;
struct GUIWindow * wp;
void (*Prerender)( struct GUIBase * b );
void (*Render)( struct GUIBase * b );
int (*CheckClick)( struct GUIBase * b, float screenx, float screeny, int button, int down ); //Return 0 if received event.
void (*HandleMove)( struct GUIBase * b, float screenx, float screeny, int buttonmask ); //Return 0 if received event.
void (*HandleKeyboard)( struct GUIBase * b, char c, int down, int focused ); //If unfocused, treat as a hotkey only.
void (*DestroyMe)( struct GUIBase * b );
//High level functionality.
void (*ProcessClick)( struct GUIBase * b ); //High level: this gets called if the user actually CLICKs a button.
};
void GenericHandleKeyboard( struct GUIBase * b, int c, int down, int focused ); //If unfocused, treat as a hotkey only.
int GenericCheckClick( struct GUIBase * b, float screenx, float screeny, int button, int down );
void GenericHandleMove( struct GUIBase * b, float screenx, float screeny, int buttonmask ); //Return 0 if received event.
struct GUIWindow
{
int width;
int height;
int focusid; //-1 if no focus
struct RFBuffer * renderbuffer;
struct Texture * torender;
struct GUIBase * elements[MAX_GUI_ELEMENTS];
};
struct GUIWindow * CreateGUIWindow();
void WindowRemoveElement( struct GUIWindow * w, struct GUIBase * g ); //removes only, does not delete.
void WindowAddElement( struct GUIWindow * w, struct GUIBase * g );
void WindowTakeFocus( struct GUIWindow * w, struct GUIBase * g );
void WindowHandleMouseMove( struct GUIWindow * w, float x, float y, int mask );
void WindowHandleMouseClick( struct GUIWindow * w, float x, float y, int button, int down );
void WindowHandleKeyboard( struct GUIWindow * w, int c, int down );
void WindowRender( struct GUIWindow * w );
void DestroyGUIWindow( struct GUIWindow * w );
#endif
|
cnlohr/bridgesim
|
src/cclient/graphics/graphicscore.c
|
<gh_stars>1-10
#include <sys/types.h>
#include <stdint.h>
#include "os_generic.h"
#include <GL/glew.h>
#include "graphicscore.h"
#include <GL/glext.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
double TotalTime;
double DeltaTime;
float RenderW;
float RenderH;
float ScreenW;
float ScreenH;
#define MAX_STORAGE 8192
static struct Shader * CurrentShader;
static GLuint FreeBOs[MAX_STORAGE];
static int FreeBOHead = -1;
#ifdef WIN32
#include <windows.h>
//For graphics loading.
#include <gdiplus/gdiplus.h>
#include <gdiplus/gdiplusflat.h>
#else
#ifdef USE_PNG
#include <png.h>
#endif
#ifdef USE_JPG
#include <jpeglib.h>
#endif
#endif
unsigned char * ReadDataFile( const char * name )
{
int r;
FILE * f = fopen( name, "rb" );
if( !f )
{
return 0;
}
fseek( f, 0, SEEK_END );
long len = ftell( f );
fseek( f, 0, SEEK_SET );
unsigned char * ret = malloc( len + 1);
r = fread( ret, len, 1, f );
if( r < 1 )
{
free( ret );
fclose( f );
return 0;
}
fclose( f );
ret[len] = 0;
return ret;
}
static void ShaderErrorPrint( GLint shader )
{
int written = 0;
int loglen = 0;
GLchar * log;
glGetShaderiv( shader, GL_INFO_LOG_LENGTH, &loglen );
if (loglen > 0)
{
log = malloc(loglen);
glGetShaderInfoLog(shader, loglen, &written, log);
fprintf( stderr, "%s\n", log );
free( log );
}
}
static int LoadShaderInPlace( struct Shader * ret )
{
unsigned char * VertexText;
unsigned char * FragmentText;
GLint compiled;
VertexText = ReadDataFile( ret->VertexName );
if( !VertexText )
{
fprintf( stderr, "Error: Could not open vertex shader: %s\n", ret->VertexName );
return 1;
}
FragmentText = ReadDataFile( ret->FragmentName );
if( !FragmentText )
{
fprintf( stderr, "Error: Could not open fragment shader: %s\n", ret->FragmentName );
free( VertexText );
return 1;
}
ret->vertex = glCreateShader(GL_VERTEX_SHADER);
ret->fragment = glCreateShader(GL_FRAGMENT_SHADER);
GLint vl = strlen( VertexText );
GLint fl = strlen( FragmentText );
glShaderSource(ret->vertex, 1, (const GLchar **)&VertexText, &vl );
glShaderSource(ret->fragment, 1, (const GLchar **)&FragmentText, &fl );
glCompileShader(ret->vertex);
glGetShaderiv(ret->vertex, GL_COMPILE_STATUS, &compiled);
if(!compiled)
{
fprintf( stderr, "Error: Could not compile vertex shader: %s\n", ret->VertexName );
ShaderErrorPrint( ret->vertex );
goto cancel;
}
glCompileShader(ret->fragment);
glGetShaderiv(ret->fragment, GL_COMPILE_STATUS, &compiled);
if(!compiled)
{
fprintf( stderr, "Error: Could not compile fragment shader: %s\n", ret->FragmentName );
ShaderErrorPrint( ret->fragment );
goto cancel;
}
ret->program = glCreateProgram();
glAttachShader(ret->program, ret->vertex);
glAttachShader(ret->program, ret->fragment);
// glBindAttribLocation(shaderProgram, 0, "InVertex");
glLinkProgram(ret->program);
GLint IsLinked;
glGetProgramiv(ret->program, GL_LINK_STATUS, (GLint *)&IsLinked);
if(!IsLinked)
{
fprintf( stderr, "Error: Could not link shader: %s + %s\n", ret->VertexName, ret->FragmentName );
GLint maxlen;
glGetProgramiv(ret->program, GL_INFO_LOG_LENGTH, &maxlen);
if( maxlen > 0 )
{
char * log = malloc( maxlen );
glGetProgramInfoLog(ret->program, maxlen, &maxlen, log);
fprintf( stderr, "%s\n", log );
free( log );
}
goto cancel_with_program;
}
free( VertexText );
free( FragmentText );
return 0; //Happy!
cancel_with_program:
glDetachShader(ret->program, ret->vertex);
glDetachShader(ret->program, ret->fragment );
glDeleteShader(ret->program);
cancel:
free( VertexText );
free( FragmentText );
glDeleteShader( ret->vertex );
glDeleteShader( ret->fragment );
return 1;
}
struct Shader * CreateShader( const char * file )
{
struct Shader * ret;
int lnl = strlen( file );
char * lfv, *lff;
lfv = malloc( lnl + 8 );
sprintf( lfv, "%s.vert", file );
lff = malloc( lnl + 8 );
sprintf( lff, "%s.frag", file );
ret = malloc( sizeof( struct Shader ) );
ret->VertexName = lfv;
ret->FragmentName = lff;
ret->LastFileTimeVertex = OGGetFileTime( lfv );
ret->LastFileTimeFragment = OGGetFileTime( lff );
LoadShaderInPlace( ret );
return ret;
}
void DeleteShader( struct Shader * s )
{
glDetachShader(s->program, s->vertex);
glDetachShader(s->program, s->fragment );
glDeleteShader(s->program);
glDeleteShader(s->vertex );
glDeleteShader(s->fragment );
free(s->VertexName );
free(s->FragmentName );
free(s);
}
struct UniformMatch * UniformMatchMake( const char* name, float * data, int intcount, int floatcount, struct UniformMatch * prev )
{
int i;
struct UniformMatch * m = malloc( sizeof( struct UniformMatch ) );
m->next = prev;
m->name = name;
m->data = data;
m->intcount = intcount;
m->floatcount = floatcount;
return m;
}
void ApplyShader( struct Shader * shader, struct UniformMatch * m )
{
glUseProgramObjectARB( shader->program );
CurrentShader = shader;
while( m )
{
int place = glGetUniformLocationARB( shader->program, m->name );
if( m->intcount == 1 )
{
glUniform1i( place, m->data[0] );
}
else if( m->intcount == 2 )
{
glUniform2i( place, m->data[0], m->data[1] );
}
else if( m->intcount == 3 )
{
glUniform3i( place, m->data[0], m->data[1], m->data[2] );
}
else if( m->intcount == 4 )
{
glUniform4i( place, m->data[0], m->data[1], m->data[2], m->data[3] );
}
else if( m->floatcount == 1 )
{
glUniform1f( place, m->data[0] );
}
else if( m->floatcount == 2 )
{
glUniform2f( place, m->data[0], m->data[1] );
}
else if( m->floatcount == 3 )
{
glUniform3f( place, m->data[0], m->data[1], m->data[2] );
}
else if( m->floatcount == 4 )
{
glUniform4f( place, m->data[0], m->data[1], m->data[2], m->data[3] );
}
m = m->next;
}
//Need to bind things...
}
void CancelShader( struct Shader * s )
{
CurrentShader = 0;
glUseProgramObjectARB( 0 );
}
void CheckForNewerShader( struct Shader * s )
{
double VertTime = OGGetFileTime( s->VertexName );
double FragTime = OGGetFileTime( s->FragmentName );
if( s->LastFileTimeVertex != VertTime || s->LastFileTimeFragment != FragTime )
{
glDetachShader(s->program, s->vertex);
glDetachShader(s->program, s->fragment );
glDeleteShader(s->program);
glDeleteShader(s->vertex );
glDeleteShader(s->fragment );
LoadShaderInPlace( s );
}
s->LastFileTimeVertex = VertTime;
s->LastFileTimeFragment = FragTime;
}
//TEXTURE/////////////////////////////////////////////////////////////////////
//For things that require GL_RGBA when dealing with floating point data; usually when dealing with verticies or host data.
static GLuint imTypes[] = { 0, GL_LUMINANCE8, GL_LUMINANCE8_ALPHA8, GL_RGB, GL_RGBA, GL_RGBA16F_ARB, GL_RGBA32F_ARB, 0 };
static GLuint imXTypes[] ={ 0, GL_LUMINANCE, GL_LUMINANCE_ALPHA, GL_RGB, GL_RGBA, GL_RGBA, GL_RGBA, 0 };
static GLuint byTypes[] = { 0, GL_UNSIGNED_BYTE, GL_UNSIGNED_BYTE, GL_UNSIGNED_BYTE, GL_UNSIGNED_BYTE, GL_FLOAT, GL_FLOAT, 0 };
static int channels[] = { 0, 1, 2, 3, 4, 4, 4, 0 };
struct Texture * CreateTexture()
{
struct Texture * ret = malloc( sizeof( struct Texture ) );
ret->format = TTUNDEFINED;
ret->type = 0;
ret->texture = 0xaaaaaaaa;
glGenTextures( 1, &ret->texture );
ret->width = 0;
ret->rawdata = 0;
ret->height = 0;
ret->slot = 0;
return ret;
}
void MakeDynamicTexture2D( struct Texture * t, int width, int height, enum TextureType tt )
{
t->width = width;
t->height = height;
t->format = tt;
t->type = GL_TEXTURE_2D;
glBindTexture( t->type, t->texture );
glCopyTexImage2D( t->type, 0, imTypes[t->format], 0, 0, width, height, 0 );
glTexParameteri( t->type, GL_TEXTURE_MIN_FILTER, GL_NEAREST );
glTexParameteri( t->type, GL_TEXTURE_MAG_FILTER, GL_NEAREST );
glBindTexture( t->type, 0 );
}
#ifdef WIN32
int ReadTextureFromFile( struct Texture * t, const char * filename )
{
int i;
HGLOBAL hMem;
LPVOID pMemImage;
IStream *pStm;
struct GdiplusStartupInput gdiplusStartupInput;
ULONG_PTR gdiplusToken;
GpBitmap *pImg;
PixelFormat PixelFormat;
//Read in data
FILE * f = fopen( filename, "rb");
if( !f )
{
fprintf( stderr, "Error: Could not open %s\n", filename );
return -1;
}
fseek(f,0,SEEK_END);
int l = ftell( f );
unsigned char * buffer = malloc( l );
fseek(f,0,SEEK_SET);
fread(buffer, l, 1, f );
fclose( f );
//Prepare GDI+ imaging
hMem = GlobalAlloc( GMEM_MOVEABLE, l );
pMemImage = GlobalLock( hMem);
memcpy( pMemImage, buffer, l );
GlobalUnlock( hMem );
//XXX: This requries OLE32, do we really want it?
CreateStreamOnHGlobal( hMem, TRUE, &pStm );
gdiplusStartupInput.GdiplusVersion = 1;
gdiplusStartupInput.DebugEventCallback = NULL;
gdiplusStartupInput.SuppressBackgroundThread = FALSE;
gdiplusStartupInput.SuppressExternalCodecs = FALSE;
GdiplusStartup( &gdiplusToken, &gdiplusStartupInput, NULL );
if( GdipCreateBitmapFromStream( pStm, &pImg ) )
{
fprintf( stderr, "Error: cannot decode: %s\n", filename );
return -2;
}
GdipGetImagePixelFormat( (GpImage *)pImg, &PixelFormat );
UINT width;
UINT height;
GdipGetImageHeight( (GpImage *)pImg, &height );
GdipGetImageWidth( (GpImage *)pImg, &width );
GpRect r;
r.X = 0;
r.Y = 0;
r.Width = width;
r.Height = height;
BitmapData bd;
enum TextureType format;
GLenum type; //Almost always GL_TEXTURE_2D (Could be GL_TEXTURE_3D)
GLuint texture;
int slot; //which texture slot (For multi-texturing)
uint8_t * rawdata; //May be other types, too!
t->width = width;
t->height = height;
t->type = GL_TEXTURE_2D;
//Detect if has alpha or not...
int ps;
if( PixelFormat & PixelFormatAlpha )
{
GdipBitmapLockBits(pImg,&r,ImageLockModeRead,PixelFormat32bppARGB,&bd);
ps = 4;
t->format = TTRGBA;
}
else
{
GdipBitmapLockBits(pImg,&r,ImageLockModeRead,PixelFormat24bppRGB,&bd);
ps = 3;
t->format = TTRGB;
}
t->rawdata = malloc( ps * width * height );
int x, y;
if( ps == 3 )
{
for( y = 0; y < height; y++ )
for( x = 0; x < width; x++ )
{
t->rawdata[(x+y*width)*3+0] = ((unsigned char*)bd.Scan0)[x*3+y*bd.Stride+2];
t->rawdata[(x+y*width)*3+1] = ((unsigned char*)bd.Scan0)[x*3+y*bd.Stride+1];
t->rawdata[(x+y*width)*3+2] = ((unsigned char*)bd.Scan0)[x*3+y*bd.Stride+0];
}
}
else //ps = 4
{
for( y = 0; y < height; y++ )
for( x = 0; x < width; x++ )
{
t->rawdata[(x+y*width)*4+0] = ((unsigned char*)bd.Scan0)[x*4+y*bd.Stride+2];
t->rawdata[(x+y*width)*4+1] = ((unsigned char*)bd.Scan0)[x*4+y*bd.Stride+1];
t->rawdata[(x+y*width)*4+2] = ((unsigned char*)bd.Scan0)[x*4+y*bd.Stride+0];
t->rawdata[(x+y*width)*4+3] = ((unsigned char*)bd.Scan0)[x*4+y*bd.Stride+3];
}
}
GdipBitmapUnlockBits(pImg, &bd );
GdipDisposeImage( (GpImage *)pImg );
GdiplusShutdown( gdiplusToken );
return 0;
}
#else
#ifdef USE_PNG
static void mypngreadfn(png_struct *png, png_byte *p, png_size_t size )
{
int r = fread( p, size, 1, png_get_io_ptr(png));
}
#endif
#ifdef USE_JPG
struct my_error_mgr {
struct jpeg_error_mgr pub; /* "public" fields */
jmp_buf setjmp_buffer; /* for return to caller */
};
typedef struct my_error_mgr * my_error_ptr;
void my_error_exit (j_common_ptr cinfo)
{
my_error_ptr myerr = (my_error_ptr) cinfo->err;
(*cinfo->err->output_message) (cinfo);
longjmp(myerr->setjmp_buffer, 1);
}
#endif
int ReadTextureFromJPG( struct Texture * t, const char * filename )
{
#ifndef USE_JPG
fprintf( stderr, "Error. Cannot load: %s. JPG Support not included.\n" );
return -1;
#else
//from: https://github.com/LuaDist/libjpeg/blob/master/example.c
struct jpeg_decompress_struct cinfo;
struct my_error_mgr jerr;
FILE * infile;
JSAMPARRAY buffer;
int row_stride;
if ((infile = fopen(filename, "rb")) == NULL) {
fprintf(stderr, "can't open %s\n", filename);
return 0;
}
cinfo.err = jpeg_std_error(&jerr.pub);
jerr.pub.error_exit = my_error_exit;
if (setjmp(jerr.setjmp_buffer)) {
jpeg_destroy_decompress(&cinfo);
fclose(infile);
return 0;
}
jpeg_create_decompress(&cinfo);
jpeg_stdio_src(&cinfo, infile);
(void) jpeg_read_header(&cinfo, TRUE);
(void) jpeg_start_decompress(&cinfo);
row_stride = cinfo.output_width * cinfo.output_components;
buffer = (*cinfo.mem->alloc_sarray)
((j_common_ptr) &cinfo, JPOOL_IMAGE, row_stride, 1);
if( cinfo.output_components != 3 && cinfo.output_components != 1 )
{
jpeg_finish_decompress(&cinfo);
jpeg_destroy_decompress(&cinfo);
fclose(infile);
return -2;
}
t->format = (cinfo.output_components==3)?TTRGB:TTGRAYSCALE;
t->width = cinfo.output_width;
t->height = cinfo.output_height;
t->type = GL_TEXTURE_2D;
t->rawdata = malloc( t->width * t->height * cinfo.output_components );
int line = 0;
while (cinfo.output_scanline < cinfo.output_height)
{
int i;
jpeg_read_scanlines(&cinfo, buffer, 1);
memcpy( &t->rawdata[row_stride * line], buffer[0], row_stride );
line++;
}
fail:
jpeg_finish_decompress(&cinfo);
jpeg_destroy_decompress(&cinfo);
fclose(infile);
return 0;
#endif
}
int ReadTextureFromPNG( struct Texture * t, const char * filename )
{
#ifdef USE_PNG
png_structp png_ptr;
png_infop info_ptr;
int number_of_passes;
png_bytep* row_pointers;
png_byte color_type;
png_byte bit_depth;
unsigned x;
int r;
unsigned char header[8]; // 8 is the maximum size that can be checked
FILE * fp = fopen( filename, "rb" );
//open file and test for it being a png
if (!fp)
{
fprintf( stderr, "[read_png_file] File %s could not be opened for reading", filename );
goto quickexit;
}
r = fread(header, 8, 1, fp);
if (png_sig_cmp(header, 0, 8))
{
fprintf( stderr, "[read_png_file] File %s is not recognized as a PNG file", filename );
goto closeandquit;
}
//initialize stuff
png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
if (!png_ptr)
{
fprintf( stderr, "[read_png_file] png_create_read_struct failed");
goto closeandquit;
}
info_ptr = png_create_info_struct(png_ptr);
if (!info_ptr)
{
fprintf( stderr, "[read_png_file] png_create_info_struct failed");
goto closepngandquit;
}
if (setjmp(png_jmpbuf(png_ptr)))
{
fprintf( stderr, "[read_png_file] Error during init_io");
goto closepngandquit;
}
png_set_sig_bytes(png_ptr, 8);
png_set_read_fn( png_ptr, fp, mypngreadfn );
png_read_info(png_ptr, info_ptr);
t->width = png_get_image_width(png_ptr, info_ptr);
t->height = png_get_image_height(png_ptr, info_ptr);
color_type = png_get_color_type(png_ptr, info_ptr);
bit_depth = png_get_bit_depth(png_ptr, info_ptr);
if (color_type == PNG_COLOR_TYPE_PALETTE)
png_set_palette_to_rgb(png_ptr);
number_of_passes = png_set_interlace_handling(png_ptr);
png_read_update_info(png_ptr, info_ptr);
// read file
if (setjmp(png_jmpbuf(png_ptr)))
{
fprintf(stderr,"[read_png_file] Error during read_image");
goto closepngandquit;
}
row_pointers = (png_bytep*) malloc(sizeof(png_bytep) * t->height);
unsigned int y;
for ( y=0; y < (unsigned)t->height; y++)
row_pointers[y] = (png_byte*) malloc(png_get_rowbytes(png_ptr, info_ptr));
png_read_image(png_ptr, row_pointers);
png_read_end( png_ptr, info_ptr );
png_destroy_read_struct( &png_ptr, &info_ptr, NULL );
png_free_data(png_ptr, info_ptr, PNG_FREE_ALL, -1);
if (color_type & PNG_COLOR_MASK_COLOR )
if (color_type & PNG_COLOR_MASK_ALPHA)
t->format = TTRGBA;
else
t->format = TTRGB;
else
if (color_type & PNG_COLOR_MASK_ALPHA)
t->format = TTGRAYALPHA;
else
t->format = TTGRAYSCALE;
// SAFE_DELETE(texture->m_data);
t->rawdata = malloc( t->width * t->height * channels[t->format] );
switch (t->format)
{
case TTGRAYSCALE:
for ( y=0; y < (unsigned)t->height; ++y) {
png_byte* row = row_pointers[y];
for ( x = 0; x < t->width; ++x) {
png_byte* ptr = &(row[x]);
t->rawdata[(x + y * t->width)] = ptr[0];
}
}
break;
case TTGRAYALPHA:
for ( y=0; y < (unsigned)t->height; ++y) {
png_byte* row = row_pointers[y];
for ( x = 0; x < t->width; ++x) {
png_byte* ptr = &(row[x*2]);
t->rawdata[(x + y * t->width) * 2] = ptr[0];
t->rawdata[(x + y * t->width) * 2 + 1] = ptr[1];
}
}
break;
case TTRGBA:
for ( y=0; y < (unsigned)t->height; ++y) {
png_byte* row = row_pointers[y];
for ( x = 0; x < t->width; ++x) {
png_byte* ptr = &(row[x*4]);
t->rawdata[(x + y * t->width) * 4] = ptr[0];
t->rawdata[(x + y * t->width) * 4 + 1] = ptr[1];
t->rawdata[(x + y * t->width) * 4 + 2] = ptr[2];
t->rawdata[(x + y * t->width) * 4 + 3] = ptr[3];
}
}
break;
case TTRGB:
for ( y=0; y < (unsigned)t->height; y++) {
png_byte* row = row_pointers[y];
for (x=0; x<t->width; x++) {
png_byte* ptr = &(row[x * 3]);
t->rawdata[(x + y * t->width) * 3] = ptr[0];
t->rawdata[(x + y * t->width) * 3 + 1] = ptr[1];
t->rawdata[(x + y * t->width) * 3 + 2] = ptr[2];
}
}
break;
default:
fprintf( stderr, "Warning: Invalid color byte type for PNG.");
break;
}
for ( y=0; y < (unsigned)t->height; y++)
free(row_pointers[y]);
free(row_pointers);
t->type = GL_TEXTURE_2D;
return 0;
closepngandquit:
png_read_end( png_ptr, info_ptr );
png_destroy_read_struct( &png_ptr, &info_ptr, NULL );
png_free_data(png_ptr, info_ptr, PNG_FREE_ALL, -1);
closeandquit:
fclose( fp );
quickexit:
return -1;
#else
fprintf( stderr, "Error. Cannot load: %s. PNG Support not included.\n" );
return -1;
#endif
}
int ReadTextureFromFile( struct Texture * t, const char * filename )
{
const char * extension = strrchr( filename, '.' );
if( extension == 0 )
{
return -1;
}
if( *extension == 0 )
{
return -1;
}
extension++;
if( strcmp( extension, "png" ) == 0 )
{
return ReadTextureFromPNG( t, filename );
} else if( strcmp( extension, "jpg" ) == 0 || strcmp( extension, "jpeg" ) )
{
return ReadTextureFromJPG( t, filename );
}
return -1;
}
#endif
void UpdateDataInOpenGL( struct Texture * t )
{
glEnable( GL_TEXTURE_2D );
glBindTexture(GL_TEXTURE_2D, t->texture);
glTexImage2D(t->type, 0, imTypes[t->format], t->width, t->height, 0, imXTypes[t->format], byTypes[t->format], t->rawdata);
/*
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
*/
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
}
void ChangeTextureFilter( struct Texture * t, int linear )
{
if( linear )
{
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
}
else
{
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
}
}
void ActivateTexture( struct Texture * t )
{
glEnable( t->type );
glActiveTextureARB( GL_TEXTURE0_ARB + t->slot );
glBindTexture(t->type, t->texture );
}
void DeactivateTexture( struct Texture * t )
{
glActiveTextureARB( GL_TEXTURE0_ARB + t->slot );
glBindTexture(t->type, 0 );
}
void DestroyTexture( struct Texture * t )
{
glDeleteTextures( 1, &t->texture );
if( t->rawdata ) free( t->rawdata );
free( t->rawdata );
}
//RF BUFFERS
struct RFBuffer * MakeRFBuffer( int use_depth_buffer, enum TextureType type )
{
struct RFBuffer * ret = malloc( sizeof( struct RFBuffer ) );
ret->mtt = type;
ret->use_depth_buffer = use_depth_buffer;
if( use_depth_buffer )
glGenRenderbuffersEXT( 1, &ret->renderbuffer );
glGenFramebuffersEXT( 1, &ret->outputbuffer );
return ret;
}
int RFBufferGo( struct RFBuffer *rb, int width, int height, int texturecount, struct Texture ** textures, int do_clear )
{
int i;
static const GLenum buffers[8] = { GL_COLOR_ATTACHMENT0_EXT, GL_COLOR_ATTACHMENT1_EXT, GL_COLOR_ATTACHMENT2_EXT,
GL_COLOR_ATTACHMENT3_EXT, GL_COLOR_ATTACHMENT4_EXT, GL_COLOR_ATTACHMENT5_EXT,
GL_COLOR_ATTACHMENT6_EXT, GL_COLOR_ATTACHMENT7_EXT };
for( i = 0; i < texturecount; i++ )
{
struct Texture * t = textures[i];
if( t->width != width || t->height != height )
{
MakeDynamicTexture2D( t, width, height, rb->mtt );
}
}
RenderW = width;
RenderH = height;
rb->width = width;
rb->height = height;
rb->outextures = texturecount;
if( rb->use_depth_buffer )
{
glBindRenderbuffer( GL_RENDERBUFFER, rb->renderbuffer );
glRenderbufferStorage( GL_RENDERBUFFER, GL_DEPTH_COMPONENT24, width, height );
}
glBindFramebufferEXT( GL_FRAMEBUFFER_EXT, rb->outputbuffer );
for( i = 0; i < texturecount; i++ )
{
struct Texture * t = textures[i];
glFramebufferTexture2DEXT( GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT + i,
GL_TEXTURE_2D, t->texture, 0 );
}
if( rb->use_depth_buffer )
glFramebufferRenderbufferEXT( GL_FRAMEBUFFER_EXT,
GL_DEPTH_ATTACHMENT_EXT, GL_RENDERBUFFER_EXT, rb->renderbuffer );
glDrawBuffers( texturecount, buffers );
glViewport( 0, 0, width, height );
//Check to see if there were any errors with the framebuffer
switch( (GLenum)glCheckFramebufferStatusEXT(GL_FRAMEBUFFER_EXT) )
{
case GL_FRAMEBUFFER_COMPLETE_EXT: break; //GOOD!
case GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT_EXT:
fprintf( stderr, "OpenGL Framebuffer error: GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT_EXT\n");
return -1;
case GL_FRAMEBUFFER_UNSUPPORTED_EXT:
fprintf( stderr, "OpenGL Framebuffer error: GL_FRAMEBUFFER_UNSUPPORTED_EXT\n");
return -2;
case GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT_EXT:
fprintf( stderr, "OpenGL Framebuffer error: GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT_EXT\n");
return -3;
case GL_FRAMEBUFFER_INCOMPLETE_DIMENSIONS_EXT:
fprintf( stderr, "OpenGL Framebuffer error: GL_FRAMEBUFFER_INCOMPLETE_DIMENSIONS_EXT\n");
return -4;
case GL_FRAMEBUFFER_INCOMPLETE_FORMATS_EXT:
fprintf( stderr, "OpenGL Framebuffer error: GL_FRAMEBUFFER_INCOMPLETE_FORMATS_EXT\n");
return -5;
case GL_FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER_EXT:
fprintf( stderr, "OpenGL Framebuffer error: GL_FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER_EXT\n");
return -6;
case GL_FRAMEBUFFER_INCOMPLETE_READ_BUFFER_EXT:
fprintf( stderr, "OpenGL Framebuffer error: GL_FRAMEBUFFER_INCOMPLETE_READ_BUFFER_EXT\n");
return -7;
default:
fprintf( stderr, "UNKNWON error with OpenGL Framebuffer\n");
return -8;
}
if( do_clear )
glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );
return 0;
}
void RFBufferDone( struct RFBuffer *rb )
{
unsigned i;
for( i = 0; i < rb->outextures; i++ )
{
glFramebufferTexture2DEXT( GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT + i,
GL_TEXTURE_2D, 0, 0 );
glActiveTextureARB( GL_TEXTURE0_ARB + i );
glDisable( GL_TEXTURE_2D );
}
glBindFramebufferEXT( GL_FRAMEBUFFER_EXT, 0 );
glBindRenderbufferEXT( GL_RENDERBUFFER_EXT, 0 );
RenderW = ScreenW;
RenderH = ScreenH;
glViewport( 0, 0, ScreenW, ScreenH );
}
void DestroyRFBuffer( struct RFBuffer *rb )
{
if( rb->use_depth_buffer )
glDeleteRenderbuffersEXT( 1, &rb->renderbuffer );
glDeleteFramebuffersEXT( 1, &rb->outputbuffer );
}
//VBOs, etc.
struct VertexData * VertexDataCreate()
{
struct VertexData * vd = malloc( sizeof( struct VertexData ) );
vd->vertexcount = 0;
vd->stride = 1;
vd->vbo = 0;
return vd;
}
void UpdateVertexData( struct VertexData * vd, float * Verts, int iNumVerts, int iStride )
{
vd->stride = iStride;
if( !vd->vbo )
{
if( FreeBOHead != -1 )
vd->vbo = FreeBOs[FreeBOHead--];
else
glGenBuffersARB( 1, &vd->vbo );
}
if( !Verts )
{
glBindBufferARB( GL_PIXEL_PACK_BUFFER_ARB, vd->vbo );
glBufferDataARB( GL_PIXEL_PACK_BUFFER_ARB, iNumVerts*4 * sizeof( float ), 0, GL_STREAM_COPY );
glBindBufferARB( GL_PIXEL_PACK_BUFFER_ARB, 0 );
//glBufferDataARB( GL_ARRAY_BUFFER_ARB, iNumVerts * iStride*4, 0, GL_DYNAMIC_DRAW );
}
else
{
glBindBufferARB( GL_ARRAY_BUFFER_ARB, vd->vbo );
glBufferDataARB( GL_ARRAY_BUFFER_ARB, iNumVerts * iStride * sizeof( float ), Verts, GL_STATIC_DRAW_ARB );
glBindBufferARB( GL_ARRAY_BUFFER_ARB, 0 );
}
}
void DestroyVertexData( struct VertexData * vd )
{
if( FreeBOHead+1 < MAX_STORAGE )
FreeBOs[++FreeBOHead] = vd->vbo;
else
glDeleteBuffersARB( 1, &vd->vbo );
free( vd );
}
struct IndexData * IndexDataCreate()
{
struct IndexData * ret = malloc( sizeof( struct IndexData ) );
ret->indexcount = 0;
#ifdef USE_IBO
ret->ido = 0;
#else
ret->indexdata = 0;
#endif
}
void UpdateIndexData( struct IndexData * id, int indexcount, int * data )
{
int i;
id->indexcount = indexcount;
#ifdef USE_IBO
if( !id->ido )
{
if( FreeBOHead != -1 )
id->ido = FreeBOs[FreeBOHead--];
else
glGenBuffersARB( 1, &id->ido );
}
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, id->ido);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, indexcount*sizeof(int), data, GL_STATIC_DRAW);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
#else
if( id->indexdata ) free( id->indexdata );
id->indexdata = malloc( sizeof( GLuint ) * indexcount );
for( i = 0; i < indexcount; i++ )
id->indexdata[i] = data[i];
#endif
}
void DestroyIndexData( struct IndexData * id )
{
if( id )
{
#ifdef USE_IBO
if( id->ido )
{
if( FreeBOHead+1 < MAX_STORAGE )
FreeBOs[++FreeBOHead] = id->ido;
else
glDeleteBuffersARB( 1, &id->ido );
}
#else
if( id->indexdata )
free( id->indexdata );
#endif
free( id );
}
}
struct GPUGeometry * CreateGeometry( struct IndexData * indices, int vertexcount, struct VertexData ** verts, char ** names, int unique, GLint mode )
{
int i, j;
struct GPUGeometry * ret = malloc( sizeof( struct GPUGeometry ) );
ret->indices = indices;
ret->vertexcount = vertexcount;
ret->vertexdatas = verts;
ret->uniquedata = unique;
ret->names = malloc( sizeof( const char *) * vertexcount );
ret->names[0] = 0;
ret->mode = mode;
ret->maxs[0] = -10000;
ret->maxs[1] = -10000;
ret->maxs[2] = -10000;
ret->mins[0] = 10000;
ret->mins[1] = 10000;
ret->mins[2] = 10000;
memset( &ret->textures[0], 0, sizeof( ret->textures ) );
memset( &ret->todelete[0], 0, sizeof( ret->todelete ) );
for( i = 1; i < vertexcount; i++ )
{
ret->names[i] = strdup( names[i] );
}
return ret;
}
void RenderGPUGeometry( struct GPUGeometry * g )
{
struct VertexData ** vd = g->vertexdatas;
char ** names = g->names;
int NumVertexSets = g->vertexcount;
struct IndexData * id = g->indices;
int i;
int tcarrayset = 0;
int normalarrayset = 0;
int colorarrayset = 0;
//Can't render.
if( !vd[0] ) return;
if( !(vd[0]->vbo) ) return;
for( i = 0; i < MAX_TEXTURES; i++ )
{
if( g->textures[i] )
{
ActivateTexture( g->textures[i] );
}
}
for( i = 1; i < NumVertexSets; ++i )
{
const char * name = names[i];
if( !vd[i] ) continue;
if( !vd[i]->vbo ) continue;
glBindBufferARB( GL_ARRAY_BUFFER_ARB, vd[i]->vbo );
if( strcmp( name, "texture" ) == 0 )
{
glEnableClientState( GL_TEXTURE_COORD_ARRAY );
glTexCoordPointer( vd[i]->stride, GL_FLOAT, 0, 0 );
tcarrayset = 1;
}
else if( strcmp( name, "color" ) == 0 )
{
glEnableClientState( GL_COLOR_ARRAY );
glColorPointer( vd[i]->stride, GL_FLOAT, 0, 0 );
colorarrayset = 1;
}
else if( strcmp( name, "normal" ) == 0 )
{
glEnableClientState( GL_NORMAL_ARRAY );
glNormalPointer( GL_FLOAT, vd[i]->stride*4, 0 );
normalarrayset = 1;
}
else if( CurrentShader )
{
int iTexPosID = glGetAttribLocationARB( CurrentShader->program, name );
glEnableVertexAttribArrayARB( iTexPosID );
glVertexAttribPointerARB( iTexPosID, vd[i]->stride, GL_FLOAT, 0, 0, 0 );
}
}
glBindBufferARB( GL_ARRAY_BUFFER_ARB, vd[0]->vbo );
glVertexPointer( vd[0]->stride, GL_FLOAT, 0, 0 );
#ifdef USE_IBO
glEnableClientState( GL_VERTEX_ARRAY );
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, id->ido);
glDrawElements(GL_TRIANGLES, id->indexcount, GL_UNSIGNED_INT, 0);
glDisableClientState( GL_VERTEX_ARRAY );
#else
glEnableClientState( GL_VERTEX_ARRAY );
glDrawElements( g->mode, id->indexcount, GL_UNSIGNED_INT, id->indexdata );
glDisableClientState( GL_VERTEX_ARRAY );
#endif
if( tcarrayset )
{
glDisableClientState( GL_TEXTURE_COORD_ARRAY );
}
if( colorarrayset )
{
glDisableClientState( GL_COLOR_ARRAY );
}
if( normalarrayset )
{
glDisableClientState( GL_NORMAL_ARRAY );
}
for( i = 0; i < MAX_TEXTURES; i++ )
{
if( g->textures[i] )
{
DeactivateTexture( g->textures[i] );
}
}
}
void AttachTextureToGeometry( struct GPUGeometry * g, struct Texture * texture, int place, int take_ownership_of )
{
g->textures[place] = texture;
g->todelete[place] = take_ownership_of;
}
void DestroyGPUGeometry( struct GPUGeometry * g )
{
int i;
for( i = 1; i < g->vertexcount; i++ )
{
free( g->names[i] );
}
free( g->names );
if( g->uniquedata )
{
DestroyIndexData( g->indices );
for( i = 0; i < g->vertexcount; i++ )
{
DestroyVertexData( g->vertexdatas[i] );
}
}
for( i = 0; i < MAX_TEXTURES; i++ )
{
if( g->todelete[i] && g->textures[i] )
{
DestroyTexture( g->textures[i] );
}
}
free( g );
}
void DrawSquare( float x, float y, float w, float h )
{
glBegin(GL_QUADS);
glTexCoord2f(0.0, 0.0);
glVertex3f(0.0, 0.0, 0.0);
glTexCoord2f(1.0, 0.0);
glVertex3f(ScreenW, 0.0, 0.0);
glTexCoord2f(1.0, 1.0);
glVertex3f(ScreenW, ScreenH, 0.0);
glTexCoord2f(0.0, 1.0);
glVertex3f(0.0, ScreenH, 0.0);
glEnd();
}
|
cnlohr/bridgesim
|
src/cclient/graphics/objreader.h
|
<gh_stars>1-10
//Copyright 2013 <>< <NAME>, Relicensed under the MIT/x11 License.
#ifndef _OBJREADER_H
#define _OBJREADER_H
#define MAX_OBJECTS_PER_OBJ 128
#include "linmath.h"
#include "graphicscore.h"
struct OBJObject
{
const char * OName;
int VertCount; //3 floats per vert count
float * Vertices;
int NormalCount; //3 floats per normal count
float * Normals;
float * Tangents; //4 floats per.
int TexCount; //3 floats per tex
float * Textures;
int TriCount; //3 ints per face index, i.e. 9 per face... [vertex texture norm] [vertex texture norm]
int * Faces;
float mins[3];
float maxs[3];
float center[3];
unsigned int OGLList; //Optionally implemented by user, may have OpenGL List.
struct GPUGeometry * geometry;
};
struct OBJFile
{
const char * Filename;
int NumObjects;
struct OBJObject * Objects[MAX_OBJECTS_PER_OBJ];
};
struct OBJFile * OpenOBJ( const char * Filename, int flipv );
#endif
|
Civica-EE/DUTCHess
|
src/gpio.h
|
#ifndef __DUTCHESS_GPIO_H__
#define __DUTCHESS_GPIO_H__
void dutchess_gpio_init ();
void dutchess_gpio_configure (int pin);
void dutchess_gpio_set (int pin, int value);
int dutchess_gpio_get (int pin);
#endif // __DUTCHESS_GPIO_H__
|
Civica-EE/DUTCHess
|
src/fs.h
|
#ifndef __DUTCHESS_FS_H__
#define __DUTCHESS_FS_H__
void dutchess_fs_init ();
#endif // __DUTCHESS_FS_H__
|
Civica-EE/DUTCHess
|
src/web.c
|
<reponame>Civica-EE/DUTCHess
#include <posix/pthread.h>
#include <data/json.h>
#include "civetweb.h"
#include "relay.h"
#include "web.h"
#define HTTP_PORT 80
#define MAX_REQUEST_SIZE_BYTES 1024
#define HTTP_OK "HTTP/1.1 200 OK\r\n" \
"Content-Type: text/html\r\n" \
"Connection: close\r\n\r\n"
K_THREAD_STACK_DEFINE(stack, CONFIG_MAIN_STACK_SIZE);
static int home (struct mg_connection *conn, void *cbdata)
{
mg_printf(conn, HTTP_OK);
mg_printf(conn, "<html><body>\n");
mg_printf(conn, "<h1>DUTCHess</h1>\n");
mg_printf(conn, "Relay: %s\n", dutchess_relay_state() ? "ON":"OFF");
mg_printf(conn, "</body></html>\n");
return 200;
}
static int turn_relay_on (struct mg_connection *conn, void *cbdata)
{
dutchess_relay_set(1);
return home(conn,cbdata);
}
static int turn_relay_off (struct mg_connection *conn, void *cbdata)
{
dutchess_relay_set(0);
return home(conn,cbdata);
}
static void *server (void *arg)
{
static const char * const options[] = {
"listening_ports",
STRINGIFY(HTTP_PORT),
"num_threads",
"1",
"max_request_size",
STRINGIFY(MAX_REQUEST_SIZE_BYTES),
NULL
};
struct mg_callbacks callbacks;
struct mg_context *ctx;
memset(&callbacks, 0, sizeof(callbacks));
if ((ctx = mg_start(&callbacks, 0, (const char **)options)) == NULL)
{
printf("Unable to start the server.");
return 0;
}
mg_set_request_handler(ctx, "/$", home, 0);
mg_set_request_handler(ctx, "/on$", turn_relay_on, 0);
mg_set_request_handler(ctx, "/off$", turn_relay_off, 0);
return 0;
}
void dutchess_web_server_init ()
{
pthread_attr_t attr;
pthread_t thread;
pthread_attr_init(&attr);
pthread_attr_setstack(&attr,
&stack,
CONFIG_MAIN_STACK_SIZE);
pthread_create(&thread, &attr, server, 0);
}
|
Civica-EE/DUTCHess
|
src/net.h
|
#ifndef __DUTCHESS_NET_H__
#define __DUTCHESS_NET_H__
#include <net/net_ip.h>
void dutchess_net_init ();
void dutchess_net_address_set (struct in_addr address);
void dutchess_net_netmask_set (struct in_addr netmask);
void dutchess_net_gateway_set (struct in_addr gateway);
#endif // __DUTCHESS_NET_H__
|
Civica-EE/DUTCHess
|
src/shell.c
|
#include <shell/shell.h>
#include "relay.h"
#include "net.h"
#include "temperature.h"
static int dutchess_relay_cmd (const struct shell *shell, size_t argc, char **argv)
{
if (argc != 2)
{
shell_print(shell, "Usage: Please supply on/off as a parameter\n");
}
else
{
if (!strcmp(argv[1], "on"))
{
dutchess_relay_set(1);
shell_print(shell, "Power ON\n");
}
else if (!strcmp(argv[1], "off"))
{
dutchess_relay_set(0);
shell_print(shell, "Power OFF\n");
}
else
{
shell_print(shell, "Please supply on/off\n");
}
}
return 0;
}
static int dutchess_ip_address_cmd (const struct shell *shell, size_t argc, char **argv)
{
if (argc != 2)
{
shell_print(shell, "Usage: Please supply an IP address as a parameter\n");
}
else
{
struct in_addr addr;
if (net_addr_pton(AF_INET, argv[1], &addr))
{
shell_print(shell, "Invalid address: %s\n", argv[1]);
return -1;
}
dutchess_net_address_set(addr);
}
return 0;
}
static int dutchess_ip_netmask_cmd (const struct shell *shell, size_t argc, char **argv)
{
if (argc != 2)
{
shell_print(shell, "Usage: Please supply a dotted decimal netmask as a parameter\n");
}
else
{
struct in_addr addr;
if (net_addr_pton(AF_INET, argv[1], &addr))
{
shell_print(shell, "Invalid address: %s\n", argv[1]);
return -1;
}
dutchess_net_netmask_set(addr);
}
return 0;
}
static int dutchess_ip_gateway_cmd (const struct shell *shell, size_t argc, char **argv)
{
if (argc != 2)
{
shell_print(shell, "Usage: Please supply an IP address as a parameter\n");
}
else
{
struct in_addr addr;
if (net_addr_pton(AF_INET, argv[1], &addr))
{
shell_print(shell, "Invalid address: %s\n", argv[1]);
return -1;
}
dutchess_net_gateway_set(addr);
}
return 0;
}
static int dutchess_temperature_cmd (const struct shell *shell, size_t argc, char **argv)
{
shell_print(shell, "Temperature: %g C", dutchess_temperature_read());
return 0;
}
SHELL_STATIC_SUBCMD_SET_CREATE(sub_dutchess_ip,
SHELL_CMD(address, NULL, "IP address command.", dutchess_ip_address_cmd),
SHELL_CMD(netmask, NULL, "IP netmask command.", dutchess_ip_netmask_cmd),
SHELL_CMD(gateway, NULL, "IP gateway command.", dutchess_ip_gateway_cmd),
SHELL_SUBCMD_SET_END);
SHELL_STATIC_SUBCMD_SET_CREATE(sub_dutchess,
SHELL_CMD(relay, NULL, "Relay command.", dutchess_relay_cmd),
SHELL_CMD(ip, &sub_dutchess_ip, "IP command.", NULL),
SHELL_CMD(temperature, NULL, "Temperature command.", dutchess_temperature_cmd),
SHELL_SUBCMD_SET_END);
SHELL_CMD_REGISTER(dutchess, &sub_dutchess, "DUTCHess commands", NULL);
|
Civica-EE/DUTCHess
|
src/main.c
|
#include "gpio.h"
#include "fs.h"
#include "led.h"
#include "net.h"
#include "relay.h"
#include "settings.h"
#include "temperature.h"
#include "terminal_server.h"
#include "tftp.h"
#include "tftp_eeprom.h"
#include "web.h"
static struct dutchess_terminal_server_cfg dut_serial_cfg[] = {
{
.cfg = {
.baudrate = 115200,
.parity = UART_CFG_PARITY_NONE,
.stop_bits = 1,
.data_bits = 8,
.flow_ctrl = UART_CFG_FLOW_CTRL_NONE
},
.tcp_port = 21500
},
{
.cfg = {
.baudrate = 57600,
.parity = UART_CFG_PARITY_NONE,
.stop_bits = 1,
.data_bits = 8,
.flow_ctrl = UART_CFG_FLOW_CTRL_NONE
},
.tcp_port = 25700
},
};
void main (void)
{
dutchess_gpio_init();
dutchess_fs_init();
dutchess_led_init();
dutchess_net_init();
dutchess_relay_init();
dutchess_temperature_init();
dutchess_terminal_server_init();
dut_start_tftpServer();
dut_tftp_eeprom();
dutchess_web_server_init();
// Initialise the settings last as this will read the settings and call the
// relevant modules.
dutchess_settings_init();
for (int i = 0; i < 2; i++)
{
dutchess_terminal_server_add(&dut_serial_cfg[i]);
}
while (1)
{
int32_t durations_ms[] = {500, 500, 500, 1000, 1000, 1000, 500, 500, 500};
dutchess_led_blink(durations_ms, 9);
}
}
|
Civica-EE/DUTCHess
|
src/terminal_server.c
|
<reponame>Civica-EE/DUTCHess<filename>src/terminal_server.c
#include <fcntl.h>
#include <logging/log.h>
#include <poll.h>
#include <posix/pthread.h>
#include <settings/settings.h>
#include "terminal_server.h"
#ifndef CONFIG_UART_INTERRUPT_DRIVEN
#error "We must has interrupts"
#endif
#define DUTCHESS_TERMINAL_SERVER_MAX_PORTS 10
// Use D0 and D1 (UART 2 RX/TX)
#define DUTCHESS_TERMINAL_SERVER_UART_NAME "UART_2"
#define TELNET_IAC 255
LOG_MODULE_REGISTER(dutchess_terminal_server);
K_THREAD_STACK_DEFINE(dutchess_terminal_server_stack, CONFIG_MAIN_STACK_SIZE);
static struct dutchess_terminal_server_cfg servers[DUTCHESS_TERMINAL_SERVER_MAX_PORTS];
// Sockets to poll; one more than the number of servers to handle the client
// socket.
static struct pollfd fds[DUTCHESS_TERMINAL_SERVER_MAX_PORTS + 1];
static const struct device *dev;
static pthread_mutex_t lock;
static int dutchess_terminal_server_blocking_set (int fd,
bool val)
{
int fl;
int ret;
if ((fl = zsock_fcntl(fd, F_GETFL, 0)) < 0)
{
return fl;
}
if (val)
{
fl &= ~O_NONBLOCK;
}
else
{
fl |= O_NONBLOCK;
}
if ((ret = zsock_fcntl(fd, F_SETFL, fl)) < 0)
{
return ret;
}
return 0;
}
int dutchess_terminal_server_add (struct dutchess_terminal_server_cfg *cfg)
{
int ret = 0;
struct dutchess_terminal_server_cfg *server = NULL;
int *fd = NULL;
struct sockaddr_in baddr = {
.sin_family = AF_INET,
.sin_port = htons(cfg->tcp_port),
.sin_addr = {
.s_addr = htonl(INADDR_ANY),
},
};
if ((ret = pthread_mutex_lock(&lock)) != 0)
{
LOG_ERR("Could not lock!");
return ret;
}
// Find somewhere in the configuration to store this terminal server.
for (int i = 0; i < DUTCHESS_TERMINAL_SERVER_MAX_PORTS; i++)
{
if (fds[i].fd == -1)
{
server = &servers[i];
fd = &fds[i].fd;
break;
}
}
if (!server)
{
LOG_ERR("Terminal server port limit exceeded!");
return -ENOMEM;
}
// Open the socket, bind it to the configured port, and make it non-blocking.
if ((ret = zsock_socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0)
{
return ret;
}
*fd = ret;
if ((ret = zsock_bind(*fd, (const struct sockaddr*) &baddr, sizeof(baddr))) < 0)
{
zsock_close(*fd);
*fd = -1;
return ret;
}
if ((ret = dutchess_terminal_server_blocking_set(*fd, false)) < 0)
{
zsock_close(*fd);
*fd = -1;
return ret;
}
// Listen for connections on this socket; only one UART here so only accept
// a single connection at a time.
if ((ret = zsock_listen(*fd, 1)) < 0)
{
zsock_close(*fd);
*fd = -1;
return ret;
}
// Save the configuration.
memcpy(server, cfg, sizeof(*cfg));
settings_save_one("terminal_server/config", servers, sizeof(servers));
pthread_mutex_unlock(&lock);
return 0;
}
int dutchess_terminal_server_del (struct dutchess_terminal_server_cfg *cfg)
{
struct dutchess_terminal_server_cfg *server = NULL;
int *fd = NULL;
int ret = 0;
if ((ret = pthread_mutex_lock(&lock)) != 0)
{
LOG_ERR("Could not lock!");
return ret;
}
// Find the matching element in the servers array.
for (int i = 0; i < DUTCHESS_TERMINAL_SERVER_MAX_PORTS; i++)
{
if (fds[i].fd != -1 &&
memcmp(cfg, &servers[i], sizeof(*cfg)) == 0)
{
// Found.
server = &servers[i];
fd = &fds[i].fd;
}
}
if (!server)
{
LOG_ERR("Terminal server not found!");
return -EINVAL;
}
// Close the socket
zsock_close(*fd);
*fd = -1;
// Clear the configuration.
memset(server, 0, sizeof(*server));
settings_save_one("terminal_server/config", servers, sizeof(servers));
pthread_mutex_unlock(&lock);
return 0;
}
static void dutchess_terminal_server_uart_isr (const struct device *dev, void *user_data)
{
while (uart_irq_update(dev) &&
uart_irq_is_pending(dev))
{
char buf[128];
int len;
if (!uart_irq_rx_ready(dev))
continue;
len = uart_fifo_read(dev, buf, 128);
if (len < 0)
{
LOG_ERR("Failed UART read!");
break;
}
else if (len == 0)
{
break;
}
else if (fds[DUTCHESS_TERMINAL_SERVER_MAX_PORTS].fd != -1) // Note: this may have been closed in the mean time.
{
if (zsock_send(fds[DUTCHESS_TERMINAL_SERVER_MAX_PORTS].fd, buf, len, 0) < 0)
{
LOG_ERR("Failed to send data to the session!");
}
}
}
}
static int dutchess_terminal_server_uart_init (struct uart_config *cfg)
{
// Disable interrupts while we set things up.
uart_irq_rx_disable(dev);
uart_irq_tx_disable(dev);
// Set the baudrate, etc.
uart_configure(dev, cfg);
// Set our ISR.
uart_irq_callback_user_data_set(dev, dutchess_terminal_server_uart_isr, NULL);
// Drain the FIFO.
while (uart_irq_rx_ready(dev))
{
char c;
uart_fifo_read(dev, &c, 1);
}
// Bring everything up.
uart_irq_rx_enable(dev);
return 0;
}
static int dutchess_terminal_server_uart_write (const uint8_t *buf, size_t len)
{
for (int i = 0; i < len; ++i)
{
uart_poll_out(dev, buf[i]);
}
char ch;
if (uart_poll_in(dev, &ch) == 0)
{
LOG_INF("Got a char '%c' (%02x)", ch, ch);
}
return 0;
}
void *server (void *arg)
{
while (1)
{
int ret = 0;
if ((ret = pthread_mutex_lock(&lock)) != 0)
{
LOG_ERR("Error during lock (%d)!", ret);
continue;
}
if ((ret = zsock_poll(fds, DUTCHESS_TERMINAL_SERVER_MAX_PORTS + 1, -1)) < 0)
{
LOG_ERR("Error during poll (%d)!", ret);
continue;
}
// Check for new connections.
for (int i = 0; i < DUTCHESS_TERMINAL_SERVER_MAX_PORTS; i++)
{
if (fds[i].revents & POLLIN)
{
struct sockaddr_storage client_addr;
void *addr = &((struct sockaddr_in*) &client_addr)->sin_addr;
socklen_t client_addr_len = sizeof(client_addr);
char addr_str[32];
int client = -1;
if ((client = zsock_accept(fds[i].fd,
(struct sockaddr*) &client_addr,
&client_addr_len)) < 0)
{
LOG_ERR("Error accepting connection (%d)", client);
continue;
}
zsock_inet_ntop(client_addr.ss_family, addr, addr_str, sizeof(addr_str));
LOG_INF("New connection from %s", addr_str);
if (fds[DUTCHESS_TERMINAL_SERVER_MAX_PORTS].fd != -1)
{
char *msg = "Connection in use.\r\n";
zsock_send(client, msg, sizeof(msg), 0);
zsock_close(client);
}
else
{
unsigned char charmode[]={255, 251, 3, 255, 251, 1, 0, 0, 0};
dutchess_terminal_server_blocking_set(client, false);
fds[DUTCHESS_TERMINAL_SERVER_MAX_PORTS].fd = client;
zsock_send(client, charmode, sizeof(charmode), 0);
}
dutchess_terminal_server_uart_init(&servers[i].cfg);
}
}
// Check for data on the client socket.
if (fds[DUTCHESS_TERMINAL_SERVER_MAX_PORTS].fd != -1 &&
fds[DUTCHESS_TERMINAL_SERVER_MAX_PORTS].revents & POLLIN)
{
int *fd = &fds[DUTCHESS_TERMINAL_SERVER_MAX_PORTS].fd;
char buf[1];
int len = zsock_recv(*fd, buf, sizeof(buf), 0);
if (len < 0)
{
LOG_ERR("Error during receive (%d)", len);
}
else if (len == 0)
{
struct sockaddr_storage client_addr;
void *addr = &((struct sockaddr_in *)&client_addr)->sin_addr;
socklen_t client_addr_len = sizeof(client_addr);
char addr_str[32];
zsock_getsockname(*fd,
(struct sockaddr*) &client_addr,
&client_addr_len);
zsock_inet_ntop(client_addr.ss_family, addr,
addr_str, sizeof(addr_str));
LOG_INF("Closing connection from %s", addr_str);
*fd = -1;
}
else
{
if (buf[0] == TELNET_IAC)
{
zsock_recv(*fd, buf, sizeof(buf), 0);
}
else
{
dutchess_terminal_server_uart_write(buf, len);
}
}
}
pthread_mutex_unlock(&lock);
}
return NULL;
}
void dutchess_terminal_server_init ()
{
pthread_attr_t attr;
pthread_t thread;
dev = device_get_binding(DUTCHESS_TERMINAL_SERVER_UART_NAME);
for (int i = 0; i < DUTCHESS_TERMINAL_SERVER_MAX_PORTS + 1; i++)
{
fds[i].fd = -1;
fds[i].events = POLLIN;
}
if (pthread_mutex_init(&lock, NULL) != 0)
{
LOG_ERR("Could not create lock!");
return;
}
pthread_attr_init(&attr);
pthread_attr_setstack(&attr,
&dutchess_terminal_server_stack,
CONFIG_MAIN_STACK_SIZE);
pthread_create(&thread, &attr, server, 0);
}
|
Civica-EE/DUTCHess
|
src/temperature.c
|
<gh_stars>0
#include <drivers/sensor.h>
#include <logging/log.h>
#include "temperature.h"
LOG_MODULE_REGISTER(dutchess_temperature);
static const struct device *dev = NULL;
double dutchess_temperature_read ()
{
int rc = 0;
struct sensor_value temp;
if (!device_is_ready(dev))
{
LOG_ERR("Device not ready!");
return 0;
}
if ((rc = sensor_sample_fetch(dev)) != 0)
{
LOG_ERR("Error fetching sample!");
return 0;
}
if ((rc = sensor_channel_get(dev, SENSOR_CHAN_AMBIENT_TEMP, &temp)) != 0)
{
LOG_ERR("Error getting channel!");
return 0;
}
return sensor_value_to_double(&temp);
}
void dutchess_temperature_init ()
{
dev = DEVICE_DT_GET_ANY(nxp_pct2075);
}
|
Civica-EE/DUTCHess
|
src/led.c
|
#include <drivers/gpio.h>
#include "gpio.h"
#include "led.h"
#define BLINK_INTERVAL_MS 500
#define PIN 5
void dutchess_led_init ()
{
dutchess_gpio_configure(PIN);
}
void dutchess_led_blink (int32_t *durations_ms, int32_t blinks)
{
// Blink the LED for the specified durations and number of blinks.
for (int i = 0; i < blinks; i++)
{
// LED is active low, so pull the GPIO low for the duration.
dutchess_gpio_set(PIN, 0);
k_msleep(durations_ms[i]);
// Turn the LED off for the interval.
dutchess_gpio_set(PIN, 1);
k_msleep(BLINK_INTERVAL_MS);
}
// Sleep afterwards so that it is easy to distinguish between different
// sequences.
k_msleep(BLINK_INTERVAL_MS * 4);
}
|
Civica-EE/DUTCHess
|
src/led.h
|
#ifndef __DUTCHESS_LED_H__
#define __DUTCHESS_LED_H__
#include <stdint.h>
void dutchess_led_init ();
void dutchess_led_blink (int32_t *durations_ms, int32_t blinks);
#endif // __DUTCHESS_LED_H__
|
Civica-EE/DUTCHess
|
src/tftp_eeprom.c
|
<gh_stars>0
#include <zephyr.h>
#include <sys/printk.h>
#include <drivers/eeprom.h>
#include <device.h>
#include "tftp.h"
const struct device *dev = NULL;
size_t eeprom_size;
int eepromOpen(char *filename)
{
unsigned char buf[1];
return eeprom_read( dev, 0 , buf, 1);
}
int eepromRead(unsigned int *addr, unsigned char *buf, unsigned int len)
{
if ( *addr > eeprom_size )
return 0;
if (eeprom_read( dev, *addr, buf, len)<0 )
return 0;
*addr+=len;
return len;
}
int eepromWrite(unsigned int *addr, unsigned char *buf, unsigned int len)
{
if (eeprom_write( dev, *addr, buf, len)<0)
return 0;
*addr+=len;
return len;
}
tftpHandler eepromHandler=
{
.id="eeprom",
.open=eepromOpen,
.read=eepromRead,
.write=eepromWrite,
};
void dut_tftp_eeprom(void)
{
dev = DEVICE_DT_GET(DT_ALIAS(eeprom_0));
if (dev == NULL) {
printk("\nError: EEPROM with alias eeprom_0 not found.\n");
return ;
}
if (!device_is_ready(dev)) {
printk("\nError: Device \"%s\" is not ready; "
"check the driver initialization logs for errors.\n",
dev->name);
return ;
}
eeprom_size = eeprom_get_size( dev);
printk("Found EEPROM device \"%s\"\n", dev->name);
registerHandler(&eepromHandler);
}
|
Civica-EE/DUTCHess
|
pct2075/zephyr/pct2075.c
|
<gh_stars>0
#define DT_DRV_COMPAT nxp_pct2075
#include <errno.h>
#include <kernel.h>
#include <drivers/i2c.h>
#include <init.h>
#include <drivers/sensor.h>
#include <init.h>
#include <sys/byteorder.h>
#include <sys/__assert.h>
#include <logging/log.h>
LOG_MODULE_REGISTER(pct2075, CONFIG_SENSOR_LOG_LEVEL);
struct pct2075_data {
const struct device *i2c_master;
uint16_t reg_val;
};
struct pct2075_config {
const char *i2c_bus;
uint16_t i2c_addr;
};
#define PCT2075_TEMP_SCALE_CEL 8
#define PCT2075_TEMP_SIGN_BIT BIT(11)
#define PCT2075_TEMP_ABS_MASK ((uint16_t)(PCT2075_TEMP_SIGN_BIT - 1U))
int pct2075_reg_read(const struct device *dev, uint8_t reg, uint16_t *val)
{
struct pct2075_data *data = dev->data;
const struct pct2075_config *cfg = dev->config;
int rc = i2c_write_read(data->i2c_master, cfg->i2c_addr,
®, sizeof(reg),
val, sizeof(*val));
if (rc == 0) {
*val = sys_be16_to_cpu(*val);
}
// 16 bits are d10,d9,d..d0,0,0,0,0,0
*val >>=5; // shift down to lsb
return rc;
}
static int pct2075_sample_fetch(const struct device *dev,
enum sensor_channel chan)
{
struct pct2075_data *data = dev->data;
__ASSERT_NO_MSG(chan == SENSOR_CHAN_ALL || chan == SENSOR_CHAN_AMBIENT_TEMP);
return pct2075_reg_read(dev, 0, &data->reg_val);
}
static inline int pct2075_temp_signed_from_reg(uint16_t reg)
{
int rv = reg & PCT2075_TEMP_ABS_MASK;
if (reg & PCT2075_TEMP_SIGN_BIT) {
/* Convert 11-bit 2s complement to signed negative
* value.
*/
rv = -(1U + (rv ^ PCT2075_TEMP_ABS_MASK));
}
return rv;
}
static int pct2075_channel_get(const struct device *dev,
enum sensor_channel chan,
struct sensor_value *val)
{
const struct pct2075_data *data = dev->data;
int temp = pct2075_temp_signed_from_reg(data->reg_val);
__ASSERT_NO_MSG(chan == SENSOR_CHAN_AMBIENT_TEMP);
val->val1 = temp / PCT2075_TEMP_SCALE_CEL;
temp -= val->val1 * PCT2075_TEMP_SCALE_CEL;
val->val2 = (temp * 1000000) / PCT2075_TEMP_SCALE_CEL;
return 0;
}
static const struct sensor_driver_api pct2075_api_funcs = {
.sample_fetch = pct2075_sample_fetch,
.channel_get = pct2075_channel_get,
};
int pct2075_init(const struct device *dev)
{
struct pct2075_data *data = dev->data;
const struct pct2075_config *cfg = dev->config;
int rc = 0;
data->i2c_master = device_get_binding(cfg->i2c_bus);
if (!data->i2c_master) {
LOG_ERR("pct2075: i2c master not found: %s", cfg->i2c_bus);
return -EINVAL;
}
return rc;
}
static struct pct2075_data pct2075_data;
static const struct pct2075_config pct2075_cfg = {
.i2c_bus = DT_INST_BUS_LABEL(0),
.i2c_addr = DT_INST_REG_ADDR(0)
};
DEVICE_DT_INST_DEFINE(0, pct2075_init, NULL,
&pct2075_data, &pct2075_cfg, POST_KERNEL,
CONFIG_SENSOR_INIT_PRIORITY, &pct2075_api_funcs);
|
Civica-EE/DUTCHess
|
src/settings.c
|
<filename>src/settings.c<gh_stars>0
#include <logging/log.h>
#include <settings/settings.h>
#include "settings.h"
LOG_MODULE_REGISTER(dutchess_settings);
void dutchess_settings_init ()
{
if (settings_subsys_init())
{
LOG_ERR("Error during settings subsystem initialization\n");
return;
}
settings_load();
}
|
Civica-EE/DUTCHess
|
src/tftp_eeprom.h
|
<gh_stars>0
#ifndef __TFTP_EEPROM_H__
#define __TFTP_EEPROM_H__
void dut_tftp_eeprom(void);
#endif // __TFTP_EEPROM_H__
|
Civica-EE/DUTCHess
|
src/relay.h
|
<gh_stars>0
#ifndef __DUTCHESS_RELAY_H__
#define __DUTCHESS_RELAY_H__
void dutchess_relay_init ();
void dutchess_relay_set (int value);
int dutchess_relay_state ();
#endif // __DUTCHESS_RELAY_H__
|
Civica-EE/DUTCHess
|
src/fs.c
|
<filename>src/fs.c
#include <storage/disk_access.h>
#include <fs/fs.h>
#include <ff.h>
#include <logging/log.h>
#include "fs.h"
LOG_MODULE_REGISTER(dutchess_fs);
static FATFS fat_fs;
static struct fs_mount_t mp = {
.type = FS_FATFS,
.fs_data = &fat_fs,
};
static const char *disk_mount_pt = "/SD:";
void dutchess_fs_init ()
{
static const char *disk_pdrv = "SD";
uint64_t memory_size_mb;
uint32_t block_count;
uint32_t block_size;
if (disk_access_init(disk_pdrv) != 0)
{
LOG_ERR("Storage init ERROR!");
return;
}
if (disk_access_ioctl(disk_pdrv, DISK_IOCTL_GET_SECTOR_COUNT, &block_count))
{
LOG_ERR("Unable to get sector count");
return;
}
LOG_INF("Block count %u", block_count);
if (disk_access_ioctl(disk_pdrv, DISK_IOCTL_GET_SECTOR_SIZE, &block_size))
{
LOG_ERR("Unable to get sector size");
return;
}
LOG_INF("Sector size %u\n", block_size);
memory_size_mb = (uint64_t)block_count * block_size;
LOG_INF("Memory Size(MB) %u\n", (uint32_t)(memory_size_mb >> 20));
mp.mnt_point = disk_mount_pt;
if (fs_mount(&mp) == FR_OK)
{
LOG_INF("Disk mounted.\n");
}
else
{
LOG_ERR("Error mounting disk.\n");
}
}
|
Civica-EE/DUTCHess
|
src/temperature.h
|
#ifndef __DUTCHESS_TEMPERATURE_H__
#define __DUTCHESS_TEMPERATURE_H__
void dutchess_temperature_init ();
double dutchess_temperature_read ();
#endif // __DUTCHESS_TEMPERATURE_H__
|
Civica-EE/DUTCHess
|
src/tftp.h
|
#ifndef TFTP_H
#define TFTP_H
void dut_start_tftpServer(void);
typedef int (*openDataType)(char *filename);
typedef int (*readDataType)(unsigned int *addr, unsigned char *buf, unsigned int len);
typedef int (*writeDataType)(unsigned int *addr, unsigned char *buf, unsigned int len);
typedef struct
{
char *id; // first part of the filename up to a "/"
openDataType open;
readDataType read;
writeDataType write;
} tftpHandler;
void registerHandler(tftpHandler *client);
#endif
|
Civica-EE/DUTCHess
|
src/terminal_server.h
|
<reponame>Civica-EE/DUTCHess
#ifndef __DUTCHESS_TERMINAL_SERVER_H__
#define __DUTCHESS_TERMINAL_SERVER_H__
#include <drivers/uart.h>
struct dutchess_terminal_server_cfg {
struct uart_config cfg;
int tcp_port;
};
void dutchess_terminal_server_init ();
int dutchess_terminal_server_add (struct dutchess_terminal_server_cfg *sap);
int dutchess_terminal_server_del (struct dutchess_terminal_server_cfg *sap);
#endif /* __DUTCHESS_TERMINAL_SERVER_H__ */
|
Civica-EE/DUTCHess
|
src/settings.h
|
#ifndef __DUTCHESS_SETTINGS_H__
#define __DUTCHESS_SETTINGS_H__
void dutchess_settings_init ();
#endif // __DUTCHESS_SETTINGS_H__
|
Civica-EE/DUTCHess
|
src/gpio.c
|
#include <stdio.h>
#include <drivers/gpio.h>
#include "gpio.h"
static const struct device *dev = NULL;
void dutchess_gpio_init ()
{
#ifdef CONFIG_BOARD_MIMXRT1020_EVK
dev = device_get_binding("GPIO_1");
#endif
}
void dutchess_gpio_configure (int pin)
{
#ifdef CONFIG_BOARD_MIMXRT1020_EVK
gpio_pin_configure(dev, pin, GPIO_OUTPUT_ACTIVE);
#endif
}
void dutchess_gpio_set (int pin, int value)
{
#ifdef CONFIG_BOARD_MIMXRT1020_EVK
gpio_pin_set(dev, pin, value);
#endif
}
int dutchess_gpio_get (int pin)
{
int value = 0;
#ifdef CONFIG_BOARD_MIMXRT1020_EVK
value = gpio_pin_get(dev, pin);
#endif
return value;
}
|
Civica-EE/DUTCHess
|
src/net.c
|
<reponame>Civica-EE/DUTCHess
#include <net/net_if.h>
#include <settings/settings.h>
#include "net.h"
struct net_if *iface = NULL;
static struct in_addr address;
int network_settings_set (const char *name,
size_t len,
settings_read_cb read_cb,
void *cb_arg)
{
const char *next;
size_t name_len;
struct in_addr addr;
name_len = settings_name_next(name, &next);
if (!next)
{
if (!strncmp(name, "address", name_len))
{
read_cb(cb_arg, &addr, sizeof(addr));
dutchess_net_address_set(addr);
return 0;
}
else if (!strncmp(name, "netmask", name_len))
{
read_cb(cb_arg, &addr, sizeof(addr));
dutchess_net_netmask_set(addr);
return 0;
}
else if (!strncmp(name, "gateway", name_len))
{
read_cb(cb_arg, &addr, sizeof(addr));
dutchess_net_gateway_set(addr);
return 0;
}
}
return -ENOENT;
}
SETTINGS_STATIC_HANDLER_DEFINE(network,
"network",
NULL,
network_settings_set,
NULL,
NULL);
void dutchess_net_init ()
{
iface = net_if_get_default();
}
void dutchess_net_address_set (struct in_addr new_address)
{
if (iface)
{
if (address.s_addr != 0)
{
net_if_ipv4_addr_rm(iface, &address);
}
net_if_ipv4_addr_add(iface, &new_address, NET_ADDR_MANUAL, 0);
memcpy(&address, &new_address, sizeof(address));
settings_save_one("network/address", &address, sizeof(address));
}
}
void dutchess_net_netmask_set (struct in_addr netmask)
{
if (iface)
{
net_if_ipv4_set_netmask(iface, &netmask);
settings_save_one("network/netmask", &netmask, sizeof(netmask));
}
}
void dutchess_net_gateway_set (struct in_addr gateway)
{
if (iface)
{
net_if_ipv4_set_gw(iface, &gateway);
settings_save_one("network/gateway", &gateway, sizeof(gateway));
}
}
|
Civica-EE/DUTCHess
|
src/relay.c
|
#include <stdio.h>
#include <drivers/gpio.h>
#include "gpio.h"
#include "relay.h"
#define PIN 22 // D7 on the Arduino header.
void dutchess_relay_init ()
{
dutchess_gpio_configure(PIN);
}
void dutchess_relay_set (int value)
{
// Relay is active low so invert the value here to abstract that.
dutchess_gpio_set(PIN, !value);
}
int dutchess_relay_state ()
{
// As with the function above, need to invert the value so the rest of the
// application doesn't have to care that this device is active low.
return !dutchess_gpio_get(PIN);
}
|
Civica-EE/DUTCHess
|
src/web.h
|
<reponame>Civica-EE/DUTCHess
#ifndef __WEB_H__
#define __WEB_H__
void dutchess_web_server_init ();
#endif // __WEB_H__
|
Civica-EE/DUTCHess
|
src/tftp.c
|
<gh_stars>0
#include <logging/log.h>
LOG_MODULE_REGISTER(tftp_server, LOG_LEVEL_DBG);
#include <zephyr.h>
#include <errno.h>
#include <stdio.h>
#include <posix/sys/socket.h>
#include <net/net_core.h>
#include <net/net_mgmt.h>
#include <net/net_event.h>
#include <net/net_conn_mgr.h>
#include <net/socket.h>
#include "tftp.h"
// uncomment the next line to have a test/xxx handler
#define TEST_HANDLER 1
#if defined(CONFIG_USERSPACE)
#include <app_memory/app_memdomain.h>
extern struct k_mem_partition app_partition;
extern struct k_mem_domain app_domain;
#define APP_BMEM K_APP_BMEM(app_partition)
#define APP_DMEM K_APP_DMEM(app_partition)
#else
#define APP_BMEM
#define APP_DMEM
#endif
#if defined(CONFIG_NET_SOCKETS_SOCKOPT_TLS) || defined(CONFIG_NET_TCP2) || \
defined(CONFIG_COVERAGE)
#define STACK_SIZE 4096
#else
#define STACK_SIZE 2048
#endif
#if IS_ENABLED(CONFIG_NET_TC_THREAD_COOPERATIVE)
#define THREAD_PRIORITY K_PRIO_COOP(CONFIG_NUM_COOP_PRIORITIES - 1)
#else
#define THREAD_PRIORITY K_PRIO_PREEMPT(8)
#endif
#define RECV_BUFFER_SIZE 1280
#define STATS_TIMER 60 /* How often to print statistics (in seconds) */
struct data {
const char *proto;
struct {
int sock;
char recv_buffer[RECV_BUFFER_SIZE];
uint32_t counter;
atomic_t bytes_received;
struct k_work_delayable stats_print;
} udp;
};
struct configs {
struct data ipv4;
};
unsigned short int tftpServerPort = 69;
static void process_udp4(void);
APP_DMEM struct configs conf = {
.ipv4 = {
.proto = "IPv4",
},
};
K_THREAD_DEFINE(udp4_thread_id, STACK_SIZE,
process_udp4, NULL, NULL, NULL,
THREAD_PRIORITY,
IS_ENABLED(CONFIG_USERSPACE) ? K_USER : 0, -1);
#define TFTP_DATA_SIZE 512
#define TFTP_OPCODE_SIZE 2
#define TFTP_BLOCKNO_SIZE 2
#define TFTP_MAX_PAYLOAD 512
#define TFTP_ACK_SIZE TFTP_OPCODE_SIZE + TFTP_BLOCKNO_SIZE
#define TFTP_PACKET_MAX_SIZE TFTP_OPCODE_SIZE + TFTP_BLOCKNO_SIZE + TFTP_MAX_PAYLOAD
unsigned int localPort = 69; // local port to listen on
char packetBuffer[TFTP_PACKET_MAX_SIZE]; //buffer to hold incoming packet,
char ReplyBuffer[4];
char ErrorBuffer[37];
char filename[132];
int flagR = 0;
int flagW = 0;
unsigned short int no_block = 0;
int sendit = 0;
int timeout = 0;
unsigned char Block[TFTP_MAX_PAYLOAD];
unsigned char buffer[TFTP_MAX_PAYLOAD]; // line of srec bindary data
char mode[32];
tftpHandler *curHandler=NULL;
unsigned int readAddr;
unsigned int writeAddr;
#define MAX_HANDLERS 5
tftpHandler *handlers[MAX_HANDLERS];
unsigned int noHandlers=0;
void ack(unsigned char block0, unsigned char block1)
{
ReplyBuffer[0] = 0;
ReplyBuffer[1] = 4;
ReplyBuffer[2] = block0;
ReplyBuffer[3] = block1;
}
void error(int e)
{
memset(ErrorBuffer,0,sizeof(ErrorBuffer));
ErrorBuffer[0] = 0;
ErrorBuffer[1] = 5;
ErrorBuffer[2] = 0;
ErrorBuffer[3] = e;
char *message = "";
switch (e) {
case 0:
message = "Not defined error";
for (int i = 0; i < strlen(message); i++){
ErrorBuffer[i+4] = message[i];
}
break;
case 1:
message = "Only Octet mode supported";
for (int i = 0; i < strlen(message); i++){
ErrorBuffer[i+4] = message[i];
}
break;
case 2:
message = "Access violation";
for (int i = 0; i < strlen(message); i++){
ErrorBuffer[i+4] = message[i];
}
break;
case 3:
message = "Disk full or allocation exceeded";
for (int i = 0; i < strlen(message); i++){
ErrorBuffer[i+4] = message[i];
}
break;
case 4:
message = "Failed to verify write (power?)";
for (int i = 0; i < strlen(message); i++){
ErrorBuffer[i+4] = message[i];
}
break;
case 5:
message = "No I2C device";
for (int i = 0; i < strlen(message); i++){
ErrorBuffer[i+4] = message[i];
}
break;
case 6:
message = "Could not open file";
for (int i = 0; i < strlen(message); i++){
ErrorBuffer[i+4] = message[i];
}
break;
case 7:
message = "No such handler";
for (int i = 0; i < strlen(message); i++){
ErrorBuffer[i+4] = message[i];
}
break;
}
ErrorBuffer[36] = 0;
}
bool validblock(int b, int b1, int b2)
{
if ( b == ((b1<<8)+b2))
return true;
return false;
}
void sendBlock(unsigned short int no_block, unsigned char *packetBuffer, int sock, struct sockaddr *client_addr, socklen_t client_addr_len)
{
int len = 4 ;
timeout = 0;
packetBuffer[0] = 0;
packetBuffer[1] = 3;
packetBuffer[2] = no_block >> 8;
packetBuffer[3] = no_block & 0xff;
len+=curHandler->read(&readAddr, &packetBuffer[4], TFTP_PACKET_MAX_SIZE-len);
NET_INFO("sending packet %d", len);
sendto(sock,packetBuffer,len,0,client_addr, client_addr_len);
}
void registerHandler(tftpHandler *client)
{
if ( noHandlers < MAX_HANDLERS)
{
NET_INFO("Registered %s as %d", log_strdup(client->id), noHandlers);
handlers[noHandlers]=client;
noHandlers++;
}
else
{
NET_ERR("Cannot register %s\n", client->id);
}
}
tftpHandler *getHandler(char *filename)
{
// NB we alter filename in this function to split it up...
char *ptr=filename;
int i;
while ( *ptr != 0 )
{
if ( *ptr == '/')
break; //got it
ptr++;
}
if ( *ptr ==0 )
{
NET_INFO("Cannot find handler for %s\n", log_strdup(filename));
return NULL; // no need to look as there cant be a handler for this
}
*ptr=0;
ptr++; // this is the rest of the filename which we send to the handler...if we find one
for (i=0;i< noHandlers;i++)
{
if (strcmp(handlers[i]->id, filename) == 0 )
{
return handlers[i];
}
}
NET_INFO("Cannot find handler for %s\n", log_strdup(filename));
return NULL ; // we cant do this
}
void tftp_packet(int sock,unsigned char *packetBuffer,int packetSize, struct sockaddr *client_addr, socklen_t client_addr_len)
{
if(packetSize)
{
// was it a start read?
if (packetBuffer[1] == 1 ){
if (flagR == 0) {
*filename = 0;
timeout = 0;
}
NET_INFO("RRQ Start a read request");
strcpy(filename, &packetBuffer[2]);
NET_INFO("Filename : %s",log_strdup( filename));
curHandler=getHandler(filename);;
if ( curHandler == NULL )
{
error(7);
NET_INFO("No Handler detected");
sendto(sock,ErrorBuffer,TFTP_PACKET_MAX_SIZE,0,client_addr, client_addr_len);
return;
}
// ok we have a handler for this type of filename
no_block = 1;
packetBuffer[0] = 0;
packetBuffer[1] = 3;
packetBuffer[2] = 0;
packetBuffer[3] = no_block;
readAddr=0;
int len=4+curHandler->read(&readAddr, &packetBuffer[4], TFTP_PACKET_MAX_SIZE-4);
sendto(sock,packetBuffer,len,0,client_addr, client_addr_len);
// was it a start Write?
} else if (packetBuffer[1] == 2 ) {
NET_INFO("WRQ start a write request");
if (flagW == 0) {
timeout = 0;
}
strcpy(filename, &packetBuffer[2]);
strcpy(mode, &packetBuffer[2+strlen(filename)+1]);
NET_INFO("Filename : %s Mode %s", log_strdup(filename),log_strdup(mode));
curHandler=getHandler(filename);;
if ( curHandler == NULL )
{
error(7);
NET_INFO("No Handler detected");
sendto(sock,ErrorBuffer,TFTP_PACKET_MAX_SIZE,0,client_addr, client_addr_len);
return;
}
if ( curHandler->open(filename) < 0)
{
error(6);
NET_INFO("Could not open file");
sendto(sock,ErrorBuffer,TFTP_PACKET_MAX_SIZE,0,client_addr, client_addr_len);
return;
}
ack(0,0);
writeAddr=0;
if ( strcmp(mode,"octet")==0)
{
sendto(sock,ReplyBuffer,TFTP_ACK_SIZE,0,client_addr, client_addr_len);
flagW = 1;
no_block = 1;
}
else
{
error(1);
NET_INFO("Only support octet mode");
sendto(sock,ErrorBuffer,TFTP_PACKET_MAX_SIZE,0,client_addr, client_addr_len);
}
// was it a write data packet
} else if (packetBuffer[1] ==3 ) {
timeout = 0;
if (validblock(no_block, (int)packetBuffer[2], (int)packetBuffer[3])) {
ack(packetBuffer[2],packetBuffer[3]);
readAddr=writeAddr;
curHandler->write(&writeAddr,&packetBuffer[4],packetSize-4);
// now verify what we wrote (if indeed we did write it)
curHandler->read(&readAddr,&Block[4],packetSize-4);
int i;
for ( i=4;i < packetSize;i++)
{
if ( packetBuffer[i] != Block[i] )
{
NET_INFO("Failure in verification.Different %d",i);
error(4);
sendto(sock,ErrorBuffer,TFTP_PACKET_MAX_SIZE,0,client_addr, client_addr_len);
return;
}
}
if (packetSize < 516){
flagW = 0;
}
sendto(sock,ReplyBuffer,TFTP_ACK_SIZE,0,client_addr, client_addr_len);
no_block++;
} else {
NET_INFO("Wrong block %d %d %d",no_block,(int)packetBuffer[2],(int)packetBuffer[3]);
error(0);
sendto(sock,ErrorBuffer,TFTP_PACKET_MAX_SIZE,0,client_addr, client_addr_len);
}
// was it a read data packet?
} else if (packetBuffer[1] == 4 ) {
if (validblock(no_block, (int)packetBuffer[2], (int)packetBuffer[3])) {
no_block++;
sendBlock(no_block,packetBuffer,sock,client_addr, client_addr_len);
} else if ( !validblock(no_block, (int)packetBuffer[2], (int)packetBuffer[3]) ) {
NET_INFO("resending packet");
sendBlock(no_block,packetBuffer,sock,client_addr, client_addr_len);
} else if (timeout == 8000) {
error(0);
NET_INFO("timeout packet");
sendto(sock,ErrorBuffer,TFTP_PACKET_MAX_SIZE,0,client_addr, client_addr_len);
} else {
NET_INFO("error packet");
error(0);
sendto(sock,ErrorBuffer,TFTP_PACKET_MAX_SIZE,0,client_addr, client_addr_len);
}
} else {
error(2);
sendto(sock,ErrorBuffer,TFTP_PACKET_MAX_SIZE,0,client_addr, client_addr_len);
}
timeout++;
}
}
static int start_udp_proto(struct data *data, struct sockaddr *bind_addr,
socklen_t bind_addrlen)
{
int ret;
data->udp.sock = socket(bind_addr->sa_family, SOCK_DGRAM, IPPROTO_UDP);
if (data->udp.sock < 0) {
NET_ERR("Failed to create UDP socket (%s): %d", data->proto,
errno);
return -errno;
}
ret = bind(data->udp.sock, bind_addr, bind_addrlen);
if (ret < 0) {
NET_ERR("Failed to bind UDP socket (%s): %d", data->proto,
errno);
ret = -errno;
}
return ret;
}
static int process_udp(struct data *data)
{
int ret = 0;
int received;
struct sockaddr client_addr;
socklen_t client_addr_len;
NET_INFO("Waiting for UDP packets on port %d (%s)...",
tftpServerPort, data->proto);
do {
client_addr_len = sizeof(client_addr);
received = recvfrom(data->udp.sock, data->udp.recv_buffer,
sizeof(data->udp.recv_buffer), 0,
&client_addr, &client_addr_len);
NET_INFO("Received UDP packet %d bytes",received);
if (received < 0) {
/* Socket error */
NET_ERR("UDP (%s): Connection error %d", data->proto,
errno);
ret = -errno;
break;
} else if (received) {
atomic_add(&data->udp.bytes_received, received);
tftp_packet(data->udp.sock, data->udp.recv_buffer,received,&client_addr, client_addr_len);
}
} while (true);
return ret;
}
static void process_udp4(void)
{
int ret;
struct sockaddr_in addr4;
(void)memset(&addr4, 0, sizeof(addr4));
addr4.sin_family = AF_INET;
addr4.sin_port = htons(tftpServerPort);
ret = start_udp_proto(&conf.ipv4, (struct sockaddr *)&addr4,
sizeof(addr4));
if (ret < 0) {
return;
}
k_work_reschedule(&conf.ipv4.udp.stats_print, K_SECONDS(STATS_TIMER));
while (ret == 0) {
ret = process_udp(&conf.ipv4);
#if 0
// its unlikely that we got an error, but we must continue
// so dont check the error code
if (ret < 0) {
return;
}
#endif
}
}
static void print_stats(struct k_work *work)
{
struct data *data = CONTAINER_OF(work, struct data, udp.stats_print);
int total_received = atomic_get(&data->udp.bytes_received);
if (total_received) {
if ((total_received / STATS_TIMER) < 1024) {
LOG_INF("%s UDP: Received %d B/sec", data->proto,
total_received / STATS_TIMER);
} else {
LOG_INF("%s UDP: Received %d KiB/sec", data->proto,
total_received / 1024 / STATS_TIMER);
}
atomic_set(&data->udp.bytes_received, 0);
}
k_work_reschedule(&data->udp.stats_print, K_SECONDS(STATS_TIMER));
}
#ifdef TEST_HANDLER
unsigned char mybuf[ TFTP_MAX_PAYLOAD];
int testOpen(char *filename)
{
int i;
NET_INFO("Test Handler asked for %s\n", log_strdup(filename));
for (i=0;i<TFTP_MAX_PAYLOAD;i++)
mybuf[i]=i;
return 0;
}
int testRead(unsigned int *addr, unsigned char *buf, unsigned int len)
{
NET_INFO("read %x", *addr);
if ( *addr >= 0x8000)
return 0;
memcpy(buf,mybuf,len);
*addr+=len;
return len;
}
int testWrite(unsigned int *addr, unsigned char *buf, unsigned int len)
{
NET_INFO("write %x", *addr);
memcpy(mybuf,buf,len);
*addr+=len;
return len;
}
tftpHandler testHandler=
{
.id="test",
.open=testOpen,
.read=testRead,
.write=testWrite,
};
#endif
void dut_start_tftpServer(void)
{
if (IS_ENABLED(CONFIG_NET_IPV4)) {
#if defined(CONFIG_USERSPACE)
k_mem_domain_add_thread(&app_domain, udp4_thread_id);
#endif
k_work_init_delayable(&conf.ipv4.udp.stats_print, print_stats);
k_thread_name_set(udp4_thread_id, "udp4");
k_thread_start(udp4_thread_id);
}
#ifdef TEST_HANDLER
registerHandler(&testHandler);
#endif
}
void dut_stop_tftpServer(void)
{
/* Not very graceful way to close a thread, but as we may be blocked
* in recvfrom call it seems to be necessary
*/
if (IS_ENABLED(CONFIG_NET_IPV4)) {
k_thread_abort(udp4_thread_id);
if (conf.ipv4.udp.sock >= 0) {
zsock_close(conf.ipv4.udp.sock);
}
}
}
|
harryji168/dart-samples
|
ffi/structs/structs_library/structs.c
|
// Copyright (c) 2019, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
#include <stdio.h>
#include <stdlib.h>
#include "structs.h"
int main()
{
printf("%s\n", hello_world());
char* backwards = "backwards";
printf("%s reversed is %s\n", backwards, reverse(backwards, 9));
struct Coordinate coord = create_coordinate(3.5, 4.6);
printf("Coordinate is lat %.2f, long %.2f\n", coord.latitude, coord.longitude);
struct Place place = create_place("My Home", 42.0, 24.0);
printf("The name of my place is %s at %.2f, %.2f\n", place.name, place.coordinate.latitude, place.coordinate.longitude);
return 0;
}
char *hello_world()
{
return "Hello World";
}
char *reverse(char *str, int length)
{
// Allocates native memory in C.
char *reversed_str = (char *)malloc((length + 1) * sizeof(char));
for (int i = 0; i < length; i++)
{
reversed_str[length - i - 1] = str[i];
}
reversed_str[length] = '\0';
return reversed_str;
}
void free_string(char *str)
{
// Free native memory in C which was allocated in C.
free(str);
}
struct Coordinate create_coordinate(double latitude, double longitude)
{
struct Coordinate coordinate;
coordinate.latitude = latitude;
coordinate.longitude = longitude;
return coordinate;
}
struct Place create_place(char *name, double latitude, double longitude)
{
struct Place place;
place.name = name;
place.coordinate = create_coordinate(latitude, longitude);
return place;
}
|
samuelgr/Spindle
|
source/barrier.c
|
/*****************************************************************************
* Spindle
* Multi-platform topology-aware thread control library.
* Distributes a set of synchronized tasks over cores in the system.
*****************************************************************************
* Authored by <NAME>
* Department of Electrical Engineering, Stanford University
* Copyright (c) 2016-2017
*************************************************************************//**
* @file barrier.c
* Implementation of internal thread barrier functionality.
*****************************************************************************/
#include "align.h"
#include "barrier.h"
#include <malloc.h>
#include <stdlib.h>
#include <string.h>
// -------- FUNCTIONS ------------------------------------------------------ //
// See "barrier.h" for documentation.
void* spindleAllocateLocalThreadBarriers(uint32_t taskCount)
{
if (NULL == spindleLocalBarrierBase)
{
// Create a single memory region of size 2x the number of tasks, so that each task gets a counter and a flag.
spindleLocalBarrierBase = (SSpindleBarrierData*)aligned_malloc(sizeof(SSpindleBarrierData) * taskCount * 2, sizeof(SSpindleBarrierData));
}
return spindleLocalBarrierBase;
}
// --------
void spindleFreeLocalThreadBarriers(void)
{
if (NULL != spindleLocalBarrierBase)
{
aligned_free((void*)spindleLocalBarrierBase);
spindleLocalBarrierBase = NULL;
}
}
|
samuelgr/Spindle
|
include/spindle/init.h
|
<reponame>samuelgr/Spindle
/*****************************************************************************
* Spindle
* Multi-platform topology-aware thread control library.
* Distributes a set of synchronized tasks over cores in the system.
*****************************************************************************
* Authored by <NAME>
* Department of Electrical Engineering, Stanford University
* Copyright (c) 2016-2017
*************************************************************************//**
* @file init.h
* Declaration of internal functions for initializing thread information.
* Not intended for external use.
*****************************************************************************/
#pragma once
#include <stdint.h>
// -------- FUNCTIONS ------------------------------------------------------ //
/// Initializes the calling thread with its local ID, global ID, and thread group ID.
/// Intended to be called internally before passing control to user-supplied code.
/// @param [in] localThreadID Current thread's local ID.
/// @param [in] globalThreadID Current thread's global ID.
/// @param [in] taskID Current thread's task ID.
void spindleSetThreadID(uint32_t localThreadID, uint32_t globalThreadID, uint32_t taskID);
/// Initializes the calling thread with information about the number of other threads.
/// Intended to be called internally before passing control to user-supplied code.
/// @param [in] localThreadCount Number of threads in the current thread's group.
/// @param [in] globalThreadCount Number of threads globally.
/// @param [in] taskCount Number of tasks globally.
void spindleSetThreadCounts(uint32_t localThreadCount, uint32_t globalThreadCount, uint32_t taskCount);
/// Initializes the calling thread's per-thread local variable to 0.
/// Intended to be called internally before passing control to user-supplied code.
void spindleInitializeLocalVariable(void);
|
samuelgr/Spindle
|
include/spindle/osthread.h
|
/*****************************************************************************
* Spindle
* Multi-platform topology-aware thread control library.
* Distributes a set of synchronized tasks over cores in the system.
*****************************************************************************
* Authored by <NAME>
* Department of Electrical Engineering, Stanford University
* Copyright (c) 2016-2017
*************************************************************************//**
* @file osthread.h
* Declaration of functions for creating and managing OS threads.
* Not intended for external use.
*****************************************************************************/
#pragma once
#include "types.h"
#include <hwloc.h>
#include <stdbool.h>
#include <stdint.h>
// -------- FUNCTIONS ------------------------------------------------------ //
/// Affinitizes the calling OS thread to the specified hwloc affinity object within the specified hwloc topology.
/// @param [in] topology `hwloc` system topology.
/// @param [in] affinityObject `hwloc` object within the topology object that represents the PU to which to affinitize.
void spindleAffinitizeCurrentOSThread(hwloc_topology_t topology, hwloc_obj_t affinityObject);
/// Creates a single OS thread per the thread specification.
/// This is a platform-specific operation.
/// @param [in] threadSpec Thread specification.
/// @return OS-specific handle that identifies the newly-created thread.
hwloc_thread_t spindleCreateOSThread(SSpindleThreadInfo* threadSpec);
/// Creates the threads specified by the thread specifications and thread count.
/// Returns once all created threads have terminated or an error occurs.
/// @param [in, out] threadSpec Array of thread assignment specifications. The threadHandle members are filled with thread identification information during this function.
/// @param [in] threadCount Number of threads to create.
/// @param [in] useCurrentThread `true` to use calling thread as a worker, `false` otherwise.
/// @return 0 once all threads terminate successfully, or nonzero in the event of an error.
uint32_t spindleCreateThreads(SSpindleThreadInfo* threadSpec, uint32_t threadCount, bool useCurrentThread);
/// Retrieves the OS-specific handle that identifes the calling thread.
/// This is a platform-specific operation.
/// @return OS-specific handle identifying the calling thread.
hwloc_thread_t spindleIdentifyCurrentOSThread(void);
/// Joins the specified threads, returning only once they have all terminated or an error occurs.
/// This is a platform-specific operation.
/// @param [in] threadSpec Array of thread assignment specifications. Only the threadHandle member is used, and it must be filled for all elements.
/// @param [in] threadCount Number of threads in the threadSpec array.
/// @return 0 once all threads terminate successfully, or nonzero in the event of an error.
uint32_t spindleJoinThreads(SSpindleThreadInfo* threadSpec, uint32_t threadCount);
/// Affinitizes and runs the thread routine on the calling thread according to the provided specification.
/// Encapsulates common thread-starting functionality.
void spindleRunThreadSpec(SSpindleThreadInfo* threadSpec);
/// Applies the thread specification to the current thread and executes its user-specified function.
/// This is a platform-specific operation.
/// @param [in] threadSpec Thread specification.
/// @return 0 once the user-supplied function returns.
uint32_t spindleStartCurrentThread(SSpindleThreadInfo* threadSpec);
|
samuelgr/Spindle
|
include/spindle/datashare.h
|
/*****************************************************************************
* Spindle
* Multi-platform topology-aware thread control library.
* Distributes a set of synchronized tasks over cores in the system.
*****************************************************************************
* Authored by <NAME>
* Department of Electrical Engineering, Stanford University
* Copyright (c) 2016-2017
*************************************************************************//**
* @file datashare.h
* Interface to internal data sharing functionality.
* Not intended for external use.
*****************************************************************************/
#pragma once
#include <stdint.h>
// -------- FUNCTIONS ------------------------------------------------------ //
/// Allocates space for all data sharing buffers.
/// Intended to be called during the spawning process.
/// @param [in] taskCount Number of tasks.
/// @return Pointer to the start of the memory region on success, or `NULL` on failure.
void* spindleAllocateDataShareBuffers(uint32_t taskCount);
/// Frees all previously-allocated space for data sharing buffers.
/// Intended to be called after all spawned threads have terminated.
void spindleFreeDataShareBuffers(void);
|
samuelgr/Spindle
|
include/spindle/barrier.h
|
/*****************************************************************************
* Spindle
* Multi-platform topology-aware thread control library.
* Distributes a set of synchronized tasks over cores in the system.
*****************************************************************************
* Authored by <NAME>
* Department of Electrical Engineering, Stanford University
* Copyright (c) 2016-2017
*************************************************************************//**
* @file barrier.h
* Interface to internal thread barrier functionality.
* Not intended for external use.
*****************************************************************************/
#pragma once
#include <stdint.h>
// -------- TYPE DEFINITIONS ----------------------------------------------- //
/// Represents the layout of storage space used to hold barrier-related quantities.
/// A single 32-bit value is accompanied by padding, to align on a two-cache-line (128-byte) boundary.
typedef struct SSpindleBarrierData
{
uint32_t value; ///< Data value.
uint8_t padding[128 - sizeof(uint32_t)]; ///< Unused, cache-line alignment padding.
} SSpindleBarrierData;
// -------- GLOBALS -------------------------------------------------------- //
/// Storage area for the counter of threads that have reached the global barrier, plus cache-line padding.
extern SSpindleBarrierData spindleGlobalBarrierCounter;
/// Storage area for the global barrier flag, on which threads spin while waiting for the global barrier, plus cache-line padding.
extern SSpindleBarrierData spindleGlobalBarrierFlag;
/// Base address for all local barrier counters and flags.
extern SSpindleBarrierData* spindleLocalBarrierBase;
// -------- FUNCTIONS ------------------------------------------------------ //
/// Allocates space for all local thread barriers.
/// Intended to be called during the spawning process.
/// @param [in] taskCount Number of tasks.
/// @return Pointer to the start of the memory region on success, or `NULL` on failure.
void* spindleAllocateLocalThreadBarriers(uint32_t taskCount);
/// Provides a barrier that no thread can pass until all threads have reached this point in the execution.
/// For internal use only. This is the same as the external version, except it uses a different area of memory to help catch end-user bugs.
/// If a user specifies tasks with different numbers of global barriers, Spindle needs a separate internal barrier to help avoid allowing the program to proceed past thread spawning.
void spindleBarrierInternalGlobal(void);
/// Frees all previously-allocated space for local thread barriers.
/// Intended to be called after all spawned threads have terminated.
void spindleFreeLocalThreadBarriers(void);
/// Initializes the local thread barrier memory regions for the specified thread group.
/// Intended to be called during the thread spawning process but before actual thread creation.
/// @param [in] taskID Target thread group ID.
/// @param [in] localThreadCount Number of threads being spawned in the target thread group.
void spindleInitializeLocalThreadBarrier(uint32_t taskID, uint32_t localThreadCount);
/// Initializes the global thread barrier memory regions.
/// Intended to be called during the thread spawning process but before actual thread creation.
/// @param [in] globalThreadCount Number of threads being spawned globally.
void spindleInitializeGlobalThreadBarrier(uint32_t globalThreadCount);
|
samuelgr/Spindle
|
include/spindle/align.h
|
/*****************************************************************************
* Spindle
* Multi-platform topology-aware thread control library.
* Distributes a set of synchronized tasks over cores in the system.
*****************************************************************************
* Authored by <NAME>
* Department of Electrical Engineering, Stanford University
* Copyright (c) 2016-2017
*************************************************************************//**
* @file align.h
* Platform-specific memory alignment macros.
* Not intended for external use.
*****************************************************************************/
#pragma once
// -------- PLATFORM-SPECIFIC MACROS --------------------------------------- //
/// Allocates a memory region of size `size` bytes aligned to an `align`-byte boundary.
/// Implementation is platform-specific.
#ifdef SPINDLE_WINDOWS
#define aligned_malloc(size, align) _aligned_malloc(size, align)
#else
#define aligned_malloc(size, align) memalign(align, size)
#endif
/// Frees an aligned memory region.
/// Implementation is platform-specific.
#ifdef SPINDLE_WINDOWS
#define aligned_free(ptr) _aligned_free(ptr)
#else
#define aligned_free(ptr) free(ptr)
#endif
|
samuelgr/Spindle
|
include/spindle.h
|
<reponame>samuelgr/Spindle<gh_stars>1-10
/*****************************************************************************
* Spindle
* Multi-platform topology-aware thread control library.
* Distributes a set of synchronized tasks over cores in the system.
*****************************************************************************
* Authored by <NAME>
* Department of Electrical Engineering, Stanford University
* Copyright (c) 2016-2017
*************************************************************************//**
* @file spindle.h
* Declaration of external API functions.
* Top-level header file for this library, to be included externally.
*****************************************************************************/
#pragma once
#include <stdbool.h>
#include <stdint.h>
// -------- CONSTANTS ------------------------------------------------------ //
/// In the `numThreads` field of #SSpindleTaskSpec, specifies to use all available threads on a NUMA node.
#define kSpindleTaskSpecAllAvailableThreads 0
/// In the `numThreads` field of #SSpindleTaskSpec, specifies to use the same number of threads for the current task as for the previous task.
/// When spawning threads, Spindle processes task specifications in index order (0 to `taskCount - 1`).
/// If `taskSpec[i].numThreads` is equal to this value, then the number of threads will be set to whatever Spindle used or calculated for `taskSpec[i-1]`.
/// If there are insufficient threads left on the current NUMA node, then this will result in an error.
#define kSpindleTaskSpecThreadsSameAsPrevious UINT32_MAX
// -------- TYPE DEFINITIONS ----------------------------------------------- //
/// Signature of the starting function of each thread.
/// Must return nothing and accept a single parameter.
typedef void (* TSpindleFunc)(void* arg);
/// Enumerates supported SMT thread assignment policies.
/// Each policy specifies how Spindle should order its assignment of threads to cores, where each core may have multiple logical threads (by means of simultaneous multithreading, or SMT).
/// As an example, consider a task with 7 threads to be assigned to 4 physical cores, each supporting 2 logical cores (hardware threads).
/// Preferring physical cores would assign threads in the order P0L0, P1L0, P2L0, P3L0, P0L1, P1L1, and finally P2L1.
/// Preferring logical cores would assign threads in the order P0L0, P0L1, P1L0, P1L1, P2L0, P2L1, and finally P3L0.
/// The correct policy depends largely on the tasks themselves and how each thread shares data with other threads.
/// Regardless of the SMT policy, separate tasks are always affinitized to different physical cores.
typedef enum ESpindleSMTPolicy
{
SpindleSMTPolicyDisableSMT, ///< Disable SMT completely. Reserve one physical core per thread and affinitize each thread to a different physical core.
SpindleSMTPolicyPreferPhysical, ///< When assigning threads to cores, assign consecutive threads to different physical cores.
SpindleSMTPolicyPreferLogical ///< When assigning threads to cores, saturate each physical core (by assigning a thread to all logical cores) before moving onto the next one.
} ESpindleSMTPolicy;
/// Specifies a Spindle task that can be created and assigned to threads.
typedef struct SSpindleTaskSpec
{
TSpindleFunc func; ///< Starting function to call for each thread.
void* arg; ///< Argument to pass to the starting function.
uint32_t numaNode; ///< Zero-based index of the NUMA node on which to create the threads.
uint32_t numThreads; ///< Number of threads to create, or 0 to use all remaining threads available.
ESpindleSMTPolicy smtPolicy; ///< Specifies the policy for distributing threads among cores that may each have multiple hardware threads.
} SSpindleTaskSpec;
// -------- FUNCTIONS ------------------------------------------------------ //
#ifdef __cplusplus
extern "C" {
#endif
/// Checks whether execution is happening within a Spindle parallelized region.
/// Only one such region can exist at any time.
/// @return `true` if so, `false` otherwise.
bool spindleIsInParallelRegion(void);
/// Spawns threads according to the provided task specification.
/// NUMA node indices must appear in monotonically increasing order in the array, and only the last entry per NUMA node may specify 0 (automatically-determined) threads.
/// @param [in] taskSpec Task specifications, as an array.
/// @param [in] taskCount Number of tasks specified.
/// @param [in] useCurrentThread `true` if the calling thread should be used as a worker (can improve performance), `false` otherwise.
/// @return 0 once all spawned threads have terminated, or nonzero in the event of an error.
uint32_t spindleThreadsSpawn(SSpindleTaskSpec* taskSpec, uint32_t taskCount, bool useCurrentThread);
/// Retrieves the current thread's local ID within its task.
/// Undefined return value if called outside the context of a code region parallelized by this library.
/// @return Current thread's local ID.
uint32_t spindleGetLocalThreadID(void);
/// Retrieves the current thread's global ID, unique among all spawned threads.
/// Undefined return value if called outside the context of a code region parallelized by this library.
/// @return Current thread's global ID.
uint32_t spindleGetGlobalThreadID(void);
/// Retrieves the current thread's logical task number.
/// Undefined return value if called outside the context of a code region parallelized by this library.
/// @return Current thread's task ID.
uint32_t spindleGetTaskID(void);
/// Retrieves the number of threads in the current thread's logical task.
/// Undefined return value if called outside the context of a code region parallelized by this library.
/// @return Number of threads in the current thread's task.
uint32_t spindleGetLocalThreadCount(void);
/// Retrieves the total number of threads spawned globally.
/// Undefined return value if called outside the context of a code region parallelized by this library.
/// @return Total number of threads spawned globally.
uint32_t spindleGetGlobalThreadCount(void);
/// Retrieves the total number of tasks.
/// Undefined return value if called outside the context of a code region parallelized by this library.
/// @return Total number of tasks.
uint32_t spindleGetTaskCount(void);
/// Sets the value of the current thread's 64-bit per-thread variable.
/// This variable can be used for any purpose and is valid only within the context of a code region parallelized by this library.
/// @param [in] value Value to set.
void spindleSetLocalVariable(uint64_t value);
/// Retrieves the value of the current thread's 64-bit per-thread variable.
/// This variable can be used for any purpose and is valid only within the context of a code region parallelized by this library.
/// @return Value of the current thread's per-thread variable.
uint64_t spindleGetLocalVariable(void);
/// Provides a barrier that no thread can pass until all threads in the current task have reached this point in the execution.
/// Useful for synchronization.
void spindleBarrierLocal(void);
/// Provides a barrier that no thread can pass until all threads have reached this point in the execution.
/// Useful for synchronization.
void spindleBarrierGlobal(void);
/// Provides a barrier that no thread can pass until all threads in the current task have reached this point in the execution.
/// Useful for synchronization, but this version measures the time a thread spends waiting.
/// @return Number of cycles the calling thread spent waiting, captured using the `rdtsc` instruction.
uint64_t spindleTimedBarrierLocal(void);
/// Provides a barrier that no thread can pass until all threads have reached this point in the execution.
/// Useful for synchronization, but this version measures the time a thread spends waiting.
/// @return Number of cycles the calling thread spent waiting, captured using the `rdtsc` instruction.
uint64_t spindleTimedBarrierGlobal(void);
/// Shares a 64-bit data item with other threads in the same Spindle task.
/// Only one thread in the task should call this function.
/// @param [in] data Quantity that is to be shared.
void spindleDataShareSendLocal(uint64_t data);
/// Shares a 64-bit data item with all other Spindle-created threads.
/// Only one thread should call this function.
/// @param [in] data Quantity that is to be shared.
void spindleDataShareSendGlobal(uint64_t data);
/// Receives a 64-bit data item shared by another thread in the same Spindle task.
/// All threads in the same task except the sender should call this function.
/// @return [out] Shared data item.
uint64_t spindleDataShareReceiveLocal(void);
/// Receives a 64-bit data item shared by another Spindle-created thread.
/// All threads except the sender should call this function.
/// @return [out] Shared data item.
uint64_t spindleDataShareReceiveGlobal(void);
#ifdef __cplusplus
}
#endif
|
samuelgr/Spindle
|
source/osthread.c
|
/*****************************************************************************
* Spindle
* Multi-platform topology-aware thread control library.
* Distributes a set of synchronized tasks over cores in the system.
*****************************************************************************
* Authored by <NAME>
* Department of Electrical Engineering, Stanford University
* Copyright (c) 2016-2017
*************************************************************************//**
* @file osthread.c
* Implementation of functions for creating and managing OS threads.
* This file contains platform-independent functions.
*****************************************************************************/
#include "barrier.h"
#include "init.h"
#include "osthread.h"
#include "types.h"
#include <hwloc.h>
#include <stdbool.h>
#include <stdint.h>
// -------- FUNCTIONS ------------------------------------------------------ //
// See "osthread.h" for documentation.
void spindleAffinitizeCurrentOSThread(hwloc_topology_t topology, hwloc_obj_t affinityObject)
{
hwloc_set_thread_cpubind(topology, spindleIdentifyCurrentOSThread(), affinityObject->cpuset, HWLOC_CPUBIND_THREAD | HWLOC_CPUBIND_STRICT);
}
// --------
uint32_t spindleCreateThreads(SSpindleThreadInfo* threadSpec, uint32_t threadCount, bool useCurrentThread)
{
if (useCurrentThread)
{
for (uint32_t i = 1; i < threadCount; ++i)
{
threadSpec[i].threadHandle = spindleCreateOSThread(&threadSpec[i]);
if ((hwloc_thread_t)NULL == threadSpec[i].threadHandle)
return __LINE__;
}
threadSpec[0].threadHandle = spindleIdentifyCurrentOSThread();
return spindleStartCurrentThread(&threadSpec[0]);
}
else
{
for (uint32_t i = 0; i < threadCount; ++i)
{
threadSpec[i].threadHandle = spindleCreateOSThread(&threadSpec[i]);
if ((hwloc_thread_t)NULL == threadSpec[i].threadHandle)
return __LINE__;
}
return spindleJoinThreads(threadSpec, threadCount);
}
}
// --------
void spindleRunThreadSpec(SSpindleThreadInfo* threadSpec)
{
// Affinitize the thread as required by the thread specification.
spindleAffinitizeCurrentOSThread(threadSpec->topology, threadSpec->affinityObject);
// Initialize thread identification information.
spindleSetThreadID(threadSpec->localThreadID, threadSpec->globalThreadID, threadSpec->taskID);
spindleSetThreadCounts(threadSpec->localThreadCount, threadSpec->globalThreadCount, threadSpec->taskCount);
spindleInitializeLocalVariable();
// Wait for all threads, then call the real thread starting function.
spindleBarrierInternalGlobal();
threadSpec->func(threadSpec->arg);
spindleBarrierInternalGlobal();
}
|
samuelgr/Spindle
|
source/osthread-windows.c
|
/*****************************************************************************
* Spindle
* Multi-platform topology-aware thread control library.
* Distributes a set of synchronized tasks over cores in the system.
*****************************************************************************
* Authored by <NAME>
* Department of Electrical Engineering, Stanford University
* Copyright (c) 2016-2017
*************************************************************************//**
* @file osthread-windows.c
* Implementation of functions for creating and managing OS threads.
* This file contains Windows-specific functions.
*****************************************************************************/
#include "osthread.h"
#include "types.h"
#include <hwloc.h>
#include <malloc.h>
#include <stdint.h>
#include <windows.h>
// -------- INTERNAL FUNCTIONS --------------------------------------------- //
/// Internal thread start function for Windows.
/// Affinitizes the thread to the required logical core, initializes thread information, and invokes the user-supplied function.
/// @param [arg] Thread specificaion, cast as a typeless pointer.
/// @return 0 upon completion of the user-supplied code.
static DWORD WINAPI spindleInternalThreadStartFuncWindows(LPVOID arg)
{
spindleRunThreadSpec((SSpindleThreadInfo*)arg);
return 0;
}
// -------- FUNCTIONS ------------------------------------------------------ //
// See "osthread.h" for documentation.
hwloc_thread_t spindleCreateOSThread(SSpindleThreadInfo* threadSpec)
{
return CreateThread(NULL, 0, &spindleInternalThreadStartFuncWindows, (LPVOID)threadSpec, 0, NULL);
}
// --------
hwloc_thread_t spindleIdentifyCurrentOSThread(void)
{
return (hwloc_thread_t)GetCurrentThread();
}
// --------
uint32_t spindleJoinThreads(SSpindleThreadInfo* threadSpec, uint32_t threadCount)
{
DWORD waitResult = 0;
HANDLE* threadHandles = (HANDLE*)malloc(sizeof(HANDLE) * threadCount);
if (NULL == threadHandles)
return __LINE__;
for (uint32_t i = 0; i < threadCount; ++i)
threadHandles[i] = threadSpec[i].threadHandle;
waitResult = WaitForMultipleObjects((DWORD)threadCount, threadHandles, TRUE, INFINITE);
free((void*)threadHandles);
return (uint32_t)waitResult;
}
// --------
uint32_t spindleStartCurrentThread(SSpindleThreadInfo* threadSpec)
{
spindleInternalThreadStartFuncWindows((LPVOID)threadSpec);
return 0;
}
|
samuelgr/Spindle
|
source/osthread-linux.c
|
/*****************************************************************************
* Spindle
* Multi-platform topology-aware thread control library.
* Distributes a set of synchronized tasks over cores in the system.
*****************************************************************************
* Authored by <NAME>
* Department of Electrical Engineering, Stanford University
* Copyright (c) 2016-2017
*************************************************************************//**
* @file osthread-linux.c
* Implementation of functions for creating and managing OS threads.
* This file contains Linux-specific functions.
*****************************************************************************/
#include "osthread.h"
#include "types.h"
#include <hwloc.h>
#include <pthread.h>
#include <stdint.h>
// -------- INTERNAL FUNCTIONS --------------------------------------------- //
/// Internal thread start function for Linux.
/// Affinitizes the thread to the required logical core, initializes thread information, and invokes the user-supplied function.
/// @param [arg] Thread specificaion, cast as a typeless pointer.
/// @return `NULL` upon completion of the user-supplied code.
static void* spindleInternalThreadStartFuncLinux(void* arg)
{
spindleRunThreadSpec((SSpindleThreadInfo*)arg);
return NULL;
}
// -------- FUNCTIONS ------------------------------------------------------ //
// See "osthread.h" for documentation.
hwloc_thread_t spindleCreateOSThread(SSpindleThreadInfo* threadSpec)
{
pthread_t threadHandle;
if (0 != pthread_create(&threadHandle, NULL, &spindleInternalThreadStartFuncLinux, (void*)threadSpec))
return (hwloc_thread_t)NULL;
return threadHandle;
}
// --------
hwloc_thread_t spindleIdentifyCurrentOSThread(void)
{
return (hwloc_thread_t)pthread_self();
}
// --------
uint32_t spindleJoinThreads(SSpindleThreadInfo* threadSpec, uint32_t threadCount)
{
for (uint32_t i = 0; i < threadCount; ++i)
{
if (0 != pthread_join((pthread_t)threadSpec[i].threadHandle, NULL))
return __LINE__;
}
return 0;
}
// --------
uint32_t spindleStartCurrentThread(SSpindleThreadInfo* threadSpec)
{
spindleInternalThreadStartFuncLinux((void*)threadSpec);
return 0;
}
|
samuelgr/Spindle
|
source/spawn.c
|
/*****************************************************************************
* Spindle
* Multi-platform topology-aware thread control library.
* Distributes a set of synchronized tasks over cores in the system.
*****************************************************************************
* Authored by <NAME>
* Department of Electrical Engineering, Stanford University
* Copyright (c) 2016-2017
*************************************************************************//**
* @file spawn.c
* Implementation of all thread-spawning logic.
*****************************************************************************/
#include "../spindle.h"
#include "barrier.h"
#include "datashare.h"
#include "osthread.h"
#include "types.h"
#include <hwloc.h>
#include <malloc.h>
#include <stdbool.h>
#include <stdint.h>
#include <topo.h>
// -------- LOCALS --------------------------------------------------------- //
/// Specifies whether execution is taking place within a Spindle parallel region.
/// Only one such region can exist at a time.
static bool inParallelRegion = false;
// -------- HELPERS -------------------------------------------------------- //
/// Retrieves the `hwloc` processing unit object to which the specified thread should be affinitized.
/// Parameters specify the `hwloc` system topology, the task definition, and the SMT policy, all of which are used to identify the processing unit.
/// Performs minimal, if any, error-checking and assumes a correct assignment of physical cores to tasks.
/// @param [in] topology System topology object, from `hwloc`.
/// @param [in] startPhysCore Starting physical core, part of the task specification.
/// @param [in] endPhysCore Ending physical core, part of the task specification.
/// @param [in] threadIndex Zero-based index of the thread within the task (in other words, the thread's local ID).
/// @param [in] smtPolicy SMT policy, part of the task specification.
/// @return Object representing the `hwloc` processing unit to which the specified thread should be affinitized.
static hwloc_obj_t spindleHelperGetThreadAffinityObject(hwloc_topology_t topology, uint32_t startPhysCore, uint32_t endPhysCore, uint32_t threadIndex, ESpindleSMTPolicy smtPolicy)
{
const uint32_t numPhysCoresAvailable = endPhysCore - startPhysCore + 1;
hwloc_obj_t affinityObject = NULL;
switch (smtPolicy)
{
case SpindleSMTPolicyDisableSMT:
// Each thread consumes a whole physical core, so verify that the index is within bounds.
if (threadIndex < numPhysCoresAvailable)
{
// First, get the physical core at the specified index.
hwloc_obj_t physicalCoreObject = hwloc_get_obj_by_type(topology, HWLOC_OBJ_CORE, startPhysCore + threadIndex);
// Next, get the first logical core of the corresponding physical core.
if (NULL != physicalCoreObject)
affinityObject = hwloc_get_obj_inside_cpuset_by_type(topology, physicalCoreObject->cpuset, HWLOC_OBJ_PU, 0);
}
break;
case SpindleSMTPolicyPreferPhysical:
if (1)
{
// Calculate physical and logical core indices.
// The current implementation assumes all physical cores per task have the same number of logical cores.
const uint32_t physicalCoreIndex = startPhysCore + (threadIndex % numPhysCoresAvailable);
const uint32_t logicalCoreIndex = threadIndex / numPhysCoresAvailable;
// Obtain the correct physical core.
hwloc_obj_t physicalCoreObject = hwloc_get_obj_by_type(topology, HWLOC_OBJ_CORE, physicalCoreIndex);
// Obtain the correct logical core as the affinity object.
if (NULL != physicalCoreObject)
affinityObject = hwloc_get_obj_inside_cpuset_by_type(topology, physicalCoreObject->cpuset, HWLOC_OBJ_PU, logicalCoreIndex);
}
break;
case SpindleSMTPolicyPreferLogical:
if (1)
{
// First, get the physical core at the starting physical core index and, from this, obtain the number of logical cores per physical core.
// The current implementation assumes all physical cores per task have the same number of logical cores.
hwloc_obj_t physicalCoreObject = hwloc_get_obj_by_type(topology, HWLOC_OBJ_CORE, startPhysCore);
if (NULL == physicalCoreObject)
break;
const uint32_t logicalCoresPerPhysicalCore = hwloc_get_nbobjs_inside_cpuset_by_type(topology, physicalCoreObject->cpuset, HWLOC_OBJ_PU);
// Next, calculate physical and logical core indices.
const uint32_t physicalCoreIndex = startPhysCore + (threadIndex / logicalCoresPerPhysicalCore);
const uint32_t logicalCoreIndex = threadIndex % logicalCoresPerPhysicalCore;
// Obtain the correct physical core.
physicalCoreObject = hwloc_get_obj_by_type(topology, HWLOC_OBJ_CORE, physicalCoreIndex);
// Obtain the correct logical core as the affinity object.
if (NULL != physicalCoreObject)
affinityObject = hwloc_get_obj_inside_cpuset_by_type(topology, physicalCoreObject->cpuset, HWLOC_OBJ_PU, logicalCoreIndex);
}
break;
default:
break;
}
return affinityObject;
}
// -------- FUNCTIONS ------------------------------------------------------ //
// See "spindle.h" for documentation.
bool spindleIsInParallelRegion(void)
{
return inParallelRegion;
}
// --------
uint32_t spindleThreadsSpawn(SSpindleTaskSpec* taskSpec, uint32_t taskCount, bool useCurrentThread)
{
SSpindleThreadInfo* threadAssignments = NULL;
uint32_t nextThreadAssignmentIndex = 0;
uint32_t threadResult = 0;
hwloc_topology_t topology;
hwloc_obj_t numaNodeObject = NULL;
hwloc_obj_t physicalCoreObject = NULL;
uint32_t* taskStartPhysCore;
uint32_t* taskEndPhysCore;
uint32_t* taskNumThreads;
uint32_t currentNumaNode = 0;
uint32_t threadsLeftOnCurrentNumaNode = 0;
uint32_t coresLeftOnCurrentNumaNode = 0;
uint32_t numThreadsRequested = 0;
uint32_t numNumaNodes = 0;
uint32_t totalNumThreads = 0;
// Verify that a Spindle parallel region does not already exist.
if (false != spindleIsInParallelRegion())
return __LINE__;
// It is trivially a success case if the number of tasks is zero.
if (0 == taskCount)
return 0;
// Obtain the hardware topology object for the current system.
topology = topoGetSystemTopologyObject();
if (NULL == topology)
return __LINE__;
// Figure out the highest possible NUMA node index, for error-checking purposes.
numNumaNodes = topoGetSystemNUMANodeCount();
if (1 > numNumaNodes)
return __LINE__;
// Initialize data structures to assign from the first NUMA node in the system.
numaNodeObject = topoGetNUMANodeObjectAtIndex(currentNumaNode);
if (NULL == numaNodeObject)
return __LINE__;
threadsLeftOnCurrentNumaNode = hwloc_get_nbobjs_inside_cpuset_by_type(topology, numaNodeObject->cpuset, HWLOC_OBJ_PU);
coresLeftOnCurrentNumaNode = hwloc_get_nbobjs_inside_cpuset_by_type(topology, numaNodeObject->cpuset, HWLOC_OBJ_CORE);
physicalCoreObject = hwloc_get_obj_inside_cpuset_by_type(topology, numaNodeObject->cpuset, HWLOC_OBJ_CORE, 0);
if (NULL == physicalCoreObject)
return __LINE__;
// Allocate memory for assignment arrays.
taskStartPhysCore = (uint32_t*)malloc(sizeof(uint32_t) * taskCount);
if (NULL == taskStartPhysCore)
return __LINE__;
taskEndPhysCore = (uint32_t*)malloc(sizeof(uint32_t) * taskCount);
if (NULL == taskEndPhysCore)
{
free((void*)taskStartPhysCore);
return __LINE__;
}
taskNumThreads = (uint32_t*)malloc(sizeof(uint32_t) * taskCount);
if (NULL == taskNumThreads)
{
free((void*)taskStartPhysCore);
free((void*)taskEndPhysCore);
return __LINE__;
}
// Assign ranges of physical cores to tasks, based on the task specifications.
for (uint32_t taskIndex = 0; taskIndex < taskCount; ++taskIndex)
{
// Verify the task specification's NUMA node.
if (taskSpec[taskIndex].numaNode < currentNumaNode || taskSpec[taskIndex].numaNode >= numNumaNodes)
{
free((void*)taskStartPhysCore);
free((void*)taskEndPhysCore);
free((void*)taskNumThreads);
return __LINE__;
}
// Reinitialize to a different NUMA node if the specified NUMA node is different.
if (taskSpec[taskIndex].numaNode != currentNumaNode)
{
currentNumaNode = taskSpec[taskIndex].numaNode;
numaNodeObject = topoGetNUMANodeObjectAtIndex(currentNumaNode);
if (NULL == numaNodeObject)
{
free((void*)taskStartPhysCore);
free((void*)taskEndPhysCore);
free((void*)taskNumThreads);
return __LINE__;
}
threadsLeftOnCurrentNumaNode = hwloc_get_nbobjs_inside_cpuset_by_type(topology, numaNodeObject->cpuset, HWLOC_OBJ_PU);
coresLeftOnCurrentNumaNode = hwloc_get_nbobjs_inside_cpuset_by_type(topology, numaNodeObject->cpuset, HWLOC_OBJ_CORE);
physicalCoreObject = hwloc_get_obj_inside_cpuset_by_type(topology, numaNodeObject->cpuset, HWLOC_OBJ_CORE, 0);
if (NULL == physicalCoreObject)
{
free((void*)taskStartPhysCore);
free((void*)taskEndPhysCore);
free((void*)taskNumThreads);
return __LINE__;
}
}
// Figure out the requested number of threads, based on any special constants passed.
switch (taskSpec[taskIndex].numThreads)
{
case kSpindleTaskSpecThreadsSameAsPrevious:
// Use the same number of threads as was ultimately used for the previous task.
if (0 == taskIndex)
{
// Cannot assign same as previous number of threads if the current task is the first one specified.
free((void*)taskStartPhysCore);
free((void*)taskEndPhysCore);
free((void*)taskNumThreads);
return __LINE__;
}
numThreadsRequested = taskNumThreads[taskIndex - 1];
break;
default:
// Use whatever number of threads as was specified directly in the input.
numThreadsRequested = taskSpec[taskIndex].numThreads;
break;
}
// Find the ending physical core for the current task, based on the number of threads specified.
if (kSpindleTaskSpecAllAvailableThreads == numThreadsRequested)
{
// Verify that at least one core remains available on the current NUMA node.
if (1 > coresLeftOnCurrentNumaNode)
{
free((void*)taskStartPhysCore);
free((void*)taskEndPhysCore);
free((void*)taskNumThreads);
return __LINE__;
}
// Assign the starting physical core for the current task.
taskStartPhysCore[taskIndex] = physicalCoreObject->logical_index;
// Initialize the counter for the number of threads assigned to the present task.
taskNumThreads[taskIndex] = 0;
// Consume all the remaining physical cores on the present node.
while (NULL != physicalCoreObject)
{
// Update the end physical core assignment.
taskEndPhysCore[taskIndex] = physicalCoreObject->logical_index;
// Update the number of threads assigned to the present task.
if (SpindleSMTPolicyDisableSMT == taskSpec[taskIndex].smtPolicy)
taskNumThreads[taskIndex] += 1;
else
taskNumThreads[taskIndex] += hwloc_get_nbobjs_inside_cpuset_by_type(topology, physicalCoreObject->cpuset, HWLOC_OBJ_PU);
// Move to the next physical core.
physicalCoreObject = hwloc_get_next_obj_inside_cpuset_by_type(topology, numaNodeObject->cpuset, HWLOC_OBJ_CORE, physicalCoreObject);
}
// Update the numbers of available cores and threads on the present NUMA node.
coresLeftOnCurrentNumaNode = 0;
threadsLeftOnCurrentNumaNode = 0;
}
else
{
uint32_t numThreadsAssignedForTask = 0;
// Verify a sufficient number of cores and threads left on the current NUMA node.
if (threadsLeftOnCurrentNumaNode < numThreadsRequested || (SpindleSMTPolicyDisableSMT == taskSpec[taskIndex].smtPolicy && coresLeftOnCurrentNumaNode < numThreadsRequested))
{
free((void*)taskStartPhysCore);
free((void*)taskEndPhysCore);
free((void*)taskNumThreads);
return __LINE__;
}
// Assign the starting physical core for the current task.
taskStartPhysCore[taskIndex] = physicalCoreObject->logical_index;
// Specify the number of threads for the current task.
taskNumThreads[taskIndex] = numThreadsRequested;
// Assign one physical core at a time to the present task,
while (numThreadsAssignedForTask < numThreadsRequested)
{
// Calculate the number of threads consumed by the present physical core.
const uint32_t numThreadsConsumed = hwloc_get_nbobjs_inside_cpuset_by_type(topology, physicalCoreObject->cpuset, HWLOC_OBJ_PU);
// Check for errors: there needs to be a valid physical core object at this point.
if (NULL == physicalCoreObject)
{
free((void*)taskStartPhysCore);
free((void*)taskEndPhysCore);
free((void*)taskNumThreads);
return __LINE__;
}
// Update the end physical core assignment.
taskEndPhysCore[taskIndex] = physicalCoreObject->logical_index;
// Add to the total number of threads assigned to the present task.
if (SpindleSMTPolicyDisableSMT == taskSpec[taskIndex].smtPolicy)
numThreadsAssignedForTask += 1;
else
numThreadsAssignedForTask += numThreadsConsumed;
// Deduct from the number of available cores and threads on the present NUMA node.
coresLeftOnCurrentNumaNode -= 1;
threadsLeftOnCurrentNumaNode -= numThreadsConsumed;
// Move to the next physical core.
physicalCoreObject = hwloc_get_next_obj_inside_cpuset_by_type(topology, numaNodeObject->cpuset, HWLOC_OBJ_CORE, physicalCoreObject);
}
}
// Update the total number of threads created globally.
totalNumThreads += taskNumThreads[taskIndex];
}
// Allocate memory for thread assignments.
threadAssignments = (SSpindleThreadInfo*)malloc(sizeof(SSpindleThreadInfo) * totalNumThreads);
if (NULL == threadAssignments)
{
free((void*)taskStartPhysCore);
free((void*)taskEndPhysCore);
free((void*)taskNumThreads);
return __LINE__;
}
// Create thread information for each task.
for (uint32_t taskIndex = 0; taskIndex < taskCount; ++taskIndex)
{
for (uint32_t threadIndex = 0; threadIndex < taskNumThreads[taskIndex]; ++threadIndex)
{
threadAssignments[nextThreadAssignmentIndex].func = taskSpec[taskIndex].func;
threadAssignments[nextThreadAssignmentIndex].arg = taskSpec[taskIndex].arg;
threadAssignments[nextThreadAssignmentIndex].topology = topology;
threadAssignments[nextThreadAssignmentIndex].affinityObject = spindleHelperGetThreadAffinityObject(topology, taskStartPhysCore[taskIndex], taskEndPhysCore[taskIndex], threadIndex, taskSpec[taskIndex].smtPolicy);
threadAssignments[nextThreadAssignmentIndex].localThreadID = threadIndex;
threadAssignments[nextThreadAssignmentIndex].globalThreadID = nextThreadAssignmentIndex;
threadAssignments[nextThreadAssignmentIndex].taskID = taskIndex;
threadAssignments[nextThreadAssignmentIndex].localThreadCount = taskNumThreads[taskIndex];
threadAssignments[nextThreadAssignmentIndex].globalThreadCount = totalNumThreads;
threadAssignments[nextThreadAssignmentIndex].taskCount = taskCount;
nextThreadAssignmentIndex += 1;
}
}
// Allocate and initialize all thread barrier and data sharing memory regions.
spindleInitializeGlobalThreadBarrier(totalNumThreads);
if (NULL == spindleAllocateDataShareBuffers(taskCount))
{
free((void*)taskStartPhysCore);
free((void*)taskEndPhysCore);
free((void*)taskNumThreads);
free((void*)threadAssignments);
return __LINE__;
}
if (NULL == spindleAllocateLocalThreadBarriers(taskCount))
{
spindleFreeDataShareBuffers();
free((void*)taskStartPhysCore);
free((void*)taskEndPhysCore);
free((void*)taskNumThreads);
free((void*)threadAssignments);
return __LINE__;
}
for (uint32_t taskIndex = 0; taskIndex < taskCount; ++taskIndex)
spindleInitializeLocalThreadBarrier(taskIndex, taskNumThreads[taskIndex]);
// Free buffers no longer needed.
free((void*)taskStartPhysCore);
free((void*)taskEndPhysCore);
free((void*)taskNumThreads);
// Entering a Spindle parallel region.
inParallelRegion = true;
// Create the threads and wait for the result.
threadResult = spindleCreateThreads(threadAssignments, totalNumThreads, useCurrentThread);
// Exiting a Spindle parallel region.
inParallelRegion = false;
// Free allocated memory and return.
spindleFreeDataShareBuffers();
spindleFreeLocalThreadBarriers();
free((void*)threadAssignments);
return threadResult;
}
|
samuelgr/Spindle
|
source/datashare.c
|
<reponame>samuelgr/Spindle<gh_stars>1-10
/*****************************************************************************
* Spindle
* Multi-platform topology-aware thread control library.
* Distributes a set of synchronized tasks over cores in the system.
*****************************************************************************
* Authored by <NAME>
* Department of Electrical Engineering, Stanford University
* Copyright (c) 2016-2017
*************************************************************************//**
* @file datashare.c
* Implementation of internal data sharing functionality.
*****************************************************************************/
#include "../spindle.h"
#include "align.h"
#include "datashare.h"
#include <malloc.h>
#include <stdlib.h>
#include <string.h>
// -------- TYPE DEFINITIONS ----------------------------------------------- //
/// Represents the layout of storage space used to hold data to be shared between threads.
/// A single 64-bit value is accompanied by padding, to align on a two-cache-line (128-byte) boundary.
typedef struct SSpindleDataShareBuffer
{
uint64_t data; ///< Shared data value.
uint8_t padding[128 - sizeof(uint64_t)]; ///< Unused, cache-line alignment padding.
} SSpindleDataShareBuffer;
// -------- LOCALS --------------------------------------------------------- //
/// Storage area for all data sharing buffers.
/// The last position is to be used for the global data sharing buffer, others are for local sharing within each task.
static SSpindleDataShareBuffer* spindleDataShareBufferBase;
// -------- FUNCTIONS ------------------------------------------------------ //
// See "datashare.h" for documentation.
void* spindleAllocateDataShareBuffers(uint32_t taskCount)
{
if (NULL == spindleDataShareBufferBase)
{
// Create a single memory region with one data sharing buffer per task, plus one for the global data sharing buffer.
spindleDataShareBufferBase = (SSpindleDataShareBuffer*)aligned_malloc(sizeof(SSpindleDataShareBuffer) * (1 + taskCount), sizeof(SSpindleDataShareBuffer));
}
return spindleDataShareBufferBase;
}
// --------
void spindleFreeDataShareBuffers(void)
{
if (NULL != spindleDataShareBufferBase)
{
aligned_free((void*)spindleDataShareBufferBase);
spindleDataShareBufferBase = NULL;
}
}
// -------- FUNCTIONS ------------------------------------------------------ //
// See "spindle.h" for documentation.
void spindleDataShareSendLocal(uint64_t data)
{
spindleDataShareBufferBase[spindleGetTaskID()].data = data;
spindleBarrierLocal();
}
// --------
void spindleDataShareSendGlobal(uint64_t data)
{
spindleDataShareBufferBase[spindleGetTaskCount()].data = data;
spindleBarrierGlobal();
}
// --------
uint64_t spindleDataShareReceiveLocal(void)
{
spindleBarrierLocal();
return spindleDataShareBufferBase[spindleGetTaskID()].data;
}
// --------
uint64_t spindleDataShareReceiveGlobal(void)
{
spindleBarrierGlobal();
return spindleDataShareBufferBase[spindleGetTaskCount()].data;
}
|
samuelgr/Spindle
|
include/spindle/types.h
|
<filename>include/spindle/types.h
/*****************************************************************************
* Spindle
* Multi-platform topology-aware thread control library.
* Distributes a set of synchronized tasks over cores in the system.
*****************************************************************************
* Authored by <NAME>
* Department of Electrical Engineering, Stanford University
* Copyright (c) 2016-2017
*************************************************************************//**
* @file types.h
* Declaration of internal types.
* Not intended for external use.
*****************************************************************************/
#pragma once
#include "../spindle.h"
#include <hwloc.h>
#include <stdint.h>
// -------- TYPE DEFINITIONS ----------------------------------------------- //
/// Internal data structure, used to provide each spawned thread with control and identification information.
/// One such data structure exists per thread created during the spawning process.
/// Each instance uniquely identifies and supplies sufficient information for each thread.
/// These data structures are created as threads are assigned to logical cores and read by each thread's internal starting function.
typedef struct SSpindleThreadInfo
{
TSpindleFunc func; ///< Starting function to call.
void* arg; ///< Argument to pass to the starting function.
hwloc_topology_t topology; ///< System topology object from `hwloc`.
hwloc_obj_t affinityObject; ///< Object from `hwloc` that identifies the PU to which the present thread should be affinitized.
uint32_t localThreadID; ///< Local thread ID.
uint32_t globalThreadID; ///< Global thread ID.
uint32_t taskID; ///< Task ID.
uint32_t localThreadCount; ///< Number of threads in the current task.
uint32_t globalThreadCount; ///< Total number of threads spawned.
uint32_t taskCount; ///< Total number of tasks created.
hwloc_thread_t threadHandle; ///< Thread handle, used to identify and wait for threads once they are created.
} SSpindleThreadInfo;
|
heshanlk/InterstitialAdControllerCocos2d
|
Example/Pods/Target Support Files/Pods-InterstitialAdControllerCocos2d_Tests/Pods-InterstitialAdControllerCocos2d_Tests-umbrella.h
|
#import <UIKit/UIKit.h>
FOUNDATION_EXPORT double Pods_InterstitialAdControllerCocos2d_TestsVersionNumber;
FOUNDATION_EXPORT const unsigned char Pods_InterstitialAdControllerCocos2d_TestsVersionString[];
|
heshanlk/InterstitialAdControllerCocos2d
|
Pod/Classes/InterstitialAdControllerCocos2d.h
|
<filename>Pod/Classes/InterstitialAdControllerCocos2d.h
//
// SimpleAdControllerCocos2d.h
// JigsawHero
//
// Created by <NAME> on 12/9/15.
// Copyright © 2015 Apportable. All rights reserved.
//
#import <iAd/iAd.h>
@import GoogleMobileAds;
@interface InterstitialAdControllerCocos2d : NSObject <ADInterstitialAdDelegate, GADInterstitialDelegate>{
ADInterstitialAd *iAdInterstitial;
GADInterstitial *gAdInterstitial;
}
+(instancetype)sharedInstance;
-(void)showInterstitial;
@end
|
heshanlk/InterstitialAdControllerCocos2d
|
Example/Pods/Target Support Files/InterstitialAdControllerCocos2d/InterstitialAdControllerCocos2d-umbrella.h
|
<gh_stars>0
#import <UIKit/UIKit.h>
FOUNDATION_EXPORT double InterstitialAdControllerCocos2dVersionNumber;
FOUNDATION_EXPORT const unsigned char InterstitialAdControllerCocos2dVersionString[];
|
Ratheshprabakar/Top-Interview-Questions
|
Array/Two_sum.c
|
<reponame>Ratheshprabakar/Top-Interview-Questions
/*Given an array of integers, return indices of the two numbers such that they add up to a specific target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
Given nums=[2,7,11,15], target=9,
Because nums[0] + nums [1]=2+7=9,
return [0,1]
*/
#include<stdio.h>
int main()
{
int *input_array,target,size,i,j,first=0,second=0,diff;
printf("Enter number of elements\t");
scanf("%d",&size);
input_array=(int *)malloc(size * sizeof(int));
printf("Enter the elements\n");
for(i=0;i<size;i++)
{
scanf("%d",&input_array[i]);
}
printf("Enter the target sum\t");
scanf("%d",&target);
for(i=0;i<size;i++)
{
diff=abs(target-input_array[i]);
for(j=i+1;j<size;j++)
{
if(input_array[j]==diff)
{
first=i;
second =j;
break;
}
}
if(input_array[second]+input_array[first]==target)
{
break;
}
}
(first==0 && second ==0)?printf("\nNo sum occurs"):printf("[%d,%d]",first,second);
free(input_array);
}
|
Ratheshprabakar/Top-Interview-Questions
|
Strings/Reverse_integer.c
|
<reponame>Ratheshprabakar/Top-Interview-Questions
/*Given a 32-bit signed integer, reverse digits of an integer.
Example 1:
Input: 123
Output: 321
Example 2:
Input: -123
Output: -321
Example 3:
Input: 120
Output: 21
Note:
Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−231, 231 − 1]. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.
*/
#include<stdio.h>
int main()
{
long int num,temp;
int rem,count=0,flag=0;
printf("Enter the number\t");
scanf("%ld",&num);
if(num<0)
{
num*=-1;
flag=1;
}
temp=num;
while(num>0)
{
rem=num%10;
count++;
num=num/10;
}
num=0;
while(temp>0)
{
rem=temp%10;
num+=rem * pow(10,count-1);
count--;
temp=temp/10;
}
(flag==1)?printf("The Reverse Integer is \t%ld",num*-1):printf("The Reverse Integer is\t%ld",num*1);
}
|
Ratheshprabakar/Top-Interview-Questions
|
Array/Remove_Duplicates_from_sorted_array.c
|
<gh_stars>0
/*Given a sorted array nums, remove the duplicates in-place such that each element appear only once and return the new length.
Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory.
Example 1:
Given nums = [1,1,2],
Your function should return length = 2, with the first two elements of nums being 1 and 2 respectively.
It doesn't matter what you leave beyond the returned length.
Example 2:
Given nums = [0,0,1,1,1,2,2,3,3,4],
Your function should return length = 5, with the first five elements of nums being modified to 0, 1, 2, 3, and 4 respectively.
It doesn't matter what values are set beyond the returned length.*/
#include<stdio.h>
int main()
{
int *input_array;
int n,i,temp,count=0;
input_array=(int *)calloc(100,sizeof(int));
printf("Enter the length of the array\t");
scanf("%d",&n);
printf("Enter the input array\n");
for(i=0;i<n;i++)
{
scanf("%d",&temp);
if(input_array[temp]==0)
{
input_array[temp]++;
count++;
}
}
printf("No. of unique elements\t%d",count);
free(input_array);
}
|
Ratheshprabakar/Top-Interview-Questions
|
Strings/First_unique_character.c
|
/*Given a string, find the first non-repeating character in it and return it's index. If it doesn't exist, return -1.
Examples:
s = "leetcode"
return 0.
s = "loveleetcode",
return 2.
Note: You may assume the string contain only lowercase letters.
*/
#include<stdio.h>
int main()
{
char input_array[100];
static int temp_array[27];
int i,j,flag=0;
printf("Enter the string\n");
gets(input_array);
for(i=0;input_array[i]!='\0';i++)
{
temp_array[input_array[i]-'a'+1]++;
}
for(i=0;input_array[i]!='\0';i++)
{
if(temp_array[input_array[i]-'a'+1]==1)
{
flag=1;
printf("%d",i);
break;
}
}
if(flag==0)
{
printf("-1");
}
}
|
Ratheshprabakar/Top-Interview-Questions
|
Strings/Valid_anagram.c
|
<reponame>Ratheshprabakar/Top-Interview-Questions
/*Given two strings s and t , write a function to determine if t is an anagram of s.
Example 1:
Input: s = "anagram", t = "nagaram"
Output: true
Example 2:
Input: s = "rat", t = "car"
Output: false
Note:
You may assume the string contains only lowercase alphabets.
*/
#include<stdio.h>
int main()
{
char s[100],t[100];
static int hash1[27],hash2[27];
int i,flag=1;
printf("Enter the string s\t");
gets(s);
printf("Enter the string t\t");
gets(t);
for(i=0;i<strlen(s);i++)
{
hash1[s[i]-'a'+1]++;
}
for(i=0;i<strlen(t);i++)
{
hash2[t[i]-'a'+1]++;
}
for(i=0;i<strlen(t);i++)
{
if(hash2[t[i]-'a'+1]!=hash1[t[i]-'a'+1])
{
printf("false");
flag=0;
break;
}
}
if(flag==1)
{
printf("true");
}
}
|
Ratheshprabakar/Top-Interview-Questions
|
Array/Move_zeros.c
|
/*Given an array nums, write a function to move all 0's to the end of it while maintaining the relative order of the non-zero elements.
Example:
Input: [0,1,0,3,12]
Output: [1,3,12,0,0]
Note:
1.You must do this in-place without making a copy of the array.
2.Minimize the total number of operations.*/
#include<stdio.h>
int main()
{
int n,i,s,temp,k=0;
int *input_array;
printf("Enter the array size\t");
scanf("%d",&n);
s=n-1;
input_array=(int *)malloc(n*sizeof(int));
for(i=0;i<n;i++)
{
scanf("%d",&temp);
if(temp==0)
{
input_array[s]=temp;
s--;
}
else
{
input_array[k]=temp;
k++;
}
}
printf("The Resultant Array is\n[");
for(i=0;i<n;i++)
{
printf("%d,",input_array[i]);
}
printf("]");
free(input_array);
}
|
Ratheshprabakar/Top-Interview-Questions
|
Array/Plus_one.c
|
/*Given a non-empty array of digits representing a non-negative integer, plus one to the integer.
The digits are stored such that the most significant digit is at the head of the list, and each element in the array contain a single digit.
You may assume the integer does not contain any leading zero, except the number 0 itself.
Example 1:
Input: [1,2,3]
Output: [1,2,4]
Explanation: The array represents the integer 123.
Example 2:
Input: [4,3,2,1]
Output: [4,3,2,2]
Explanation: The array represents the integer 4321.
*/
#include<stdio.h>
int main()
{
int size,i;
int *input_array;
printf("Enter the size of the array\t");
scanf("%d",&size);
input_array=(int *)malloc(size * sizeof(int));
for(i=0;i<size;i++)
{
scanf("%d",&input_array[i]);
}
if(input_array[size-1]>=0 &&input_array[size-1]<=8)
{
input_array[size-1]++;
}
else
{
input_array[size-1]=0;
for(i=(size-1)-1;i>=0;i--)
{
if(input_array[i]>=0 && input_array[i]<=8)
{
input_array[i]++;
break;
}
else
{
input_array[i]=0;
}
}
}
if(input_array[0]==0)
{
size=size+1;
input_array = (int *)realloc(input_array, sizeof(int)*size);
input_array[0]=1;
input_array[size-1]=0;
}
printf("The Plus one array is\n");
for(i=0;i<size;i++)
{
printf("%d",input_array[i]);
}
}
|
Ratheshprabakar/Top-Interview-Questions
|
Strings/Reverse_string.c
|
<filename>Strings/Reverse_string.c
/*Write a function that reverses a string. The input string is given as an array of characters char[].
Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory.
You may assume all the characters consist of printable ascii characters.
Example 1:
Input: ["h","e","l","l","o"]
Output: ["o","l","l","e","h"]
Example 2:
Input: ["H","a","n","n","a","h"]
Output: ["h","a","n","n","a","H"]
*/
#include<stdio.h>
int main()
{
int size,c,i;
char temp;
char input_array[100];
printf("Enter the number of characters\t");
scanf("%d",&size);
printf("Enter the characters\n");
for(i=0;i<size;i++)
{
scanf(" %c",&input_array[i]);
}
input_array[size]='\0';
c=size-1;
printf("The Reverse string is\n");
for(i=0;i<c;i++)
{
temp=input_array[i];
input_array[i]=input_array[c];
input_array[c]=temp;
c--;
}
for(i=0;i<size;i++)
{
printf("%c\n",input_array[i]);
}
}
|
Ratheshprabakar/Top-Interview-Questions
|
Array/Contains_duplicates.c
|
<filename>Array/Contains_duplicates.c
/*Given an array of integers, find if the array contains any duplicates.
Your function should return true if any value appears at least twice in the array, and it should return false if every element is distinct.
Example 1:
Input: [1,2,3,1]
Output: true
Example 2:
Input: [1,2,3,4]
Output: false
Example 3:
Input: [1,1,1,3,3,4,3,2,4,2]
Output : true*/
#include<stdio.h>
int main()
{
int n,flag=0,i,temp;
int *input_array;
input_array=(int *)calloc(100,sizeof(int));
printf("Enter the size of the array\t");
scanf("%d",&n);
for(i=0;i<n;i++)
{
scanf("%d",&temp);
if(input_array[temp]!=0)
{
input_array[temp]++;
flag=1;
}
else
{
input_array[temp]++;
flag=0;
}
}
(flag==1)?printf("true"):printf("false");
free(input_array);
}
|
Ratheshprabakar/Top-Interview-Questions
|
Array/Single_number.c
|
<reponame>Ratheshprabakar/Top-Interview-Questions
/*Given a non-empty array of integers, every element appears twice except for one. Find that single one.
Note:
Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?
Example 1:
Input: [2,2,1]
Output: 1
Example 2:
Input: [4,1,2,1,2]
Output: 4*/
#include<stdio.h>
int main()
{
int n,i,temp,max=0;
int *input_array;
printf("Enter the size of the array\t");
scanf("%d",&n);
input_array=(int *)calloc(100,sizeof(int));
for(i=0;i<n;i++)
{
scanf("%d",&temp);
input_array[temp]++;
if(temp>max)
max=temp;
}
for(i=0;i<=max;i++)
{
if(input_array[i]==1)
{
printf("%d",i);
break;
}
}
free(input_array);
}
|
Ratheshprabakar/Top-Interview-Questions
|
Array/Intersection_of_two_arraysII.c
|
/*Given two arrays, write a function to compute their intersection.
Example 1:
Input: nums1 = [1,2,2,1], nums2 = [2,2]
Output: [2,2]
Example 2:
Input: nums1 = [4,9,5], nums2 = [9,4,9,8,4]
Output: [4,9]
Note:
Each element in the result should appear as many times as it shows in both arrays.
The result can be in any order.
Follow up:
What if the given array is already sorted? How would you optimize your algorithm?
What if nums1's size is small compared to nums2's size? Which algorithm is better?
What if elements of nums2 are stored on disk, and the memory is limited such that you cannot load all elements into the memory at once?
*/
#include<stdio.h>
int main()
{
int size1,size2,i,j=0,temp,max1=0,max2=0,min1=999,min2=999,k;
int *input_array1,*input_array2,*temp_array;
printf("Enter the size of the array 1\t");
scanf("%d",&size1);
printf("Enter the size of the array 2\t");
scanf("%d",&size2);
input_array1=calloc(100,sizeof(int));
input_array2=calloc(100,sizeof(int));
printf("Enter the nums1 elements\n");
for(i=0;i<size1;i++)
{
scanf("%d",&temp);
input_array1[temp]++;
if(max1<temp)
{
max1=temp;
}
if(min1>temp)
{
min1=temp;
}
}
printf("\nEnter the nums2 elements\n");
for(i=0;i<size2;i++)
{
scanf("%d",&temp);
input_array2[temp]++;
if(max2<temp)
{
max2=temp;
}
if(min2>temp)
{
min2=temp;
}
}
if(size1<=size2)
{
j=0;
temp_array=(int *)malloc(size2*sizeof(int));
for(i=min1;i<=max1;i++)
{
if(input_array1[i]!=0 && input_array2[i]!=0)
{
if(input_array1[i]<=input_array2[i])
{
for(k=0;k<input_array1[i];k++)
{
temp_array[j]=i;
j++;
}
}
else
{
for(k=0;k<input_array2[i];k++)
{
temp_array[j]=i;
j++;
}
}
}
}
}
else
{
j=0;
temp_array=(int *)malloc(size1*sizeof(int));
for(i=min2;i<=max2;i++)
{
if(input_array1[i]!=0 && input_array2[i]!=0)
{
if(input_array1[i]<=input_array2[i])
{
for(k=0;k<input_array1[i];k++)
{
temp_array[j]=i;
j++;
}
}
else
{
for(k=0;k<input_array2[i];k++)
{
temp_array[j]=i;
j++;
}
}
}
}
}
printf("The RESULTANT ARRAY is\n[");
for(i=0;i<j;i++)
{
printf("%d,",temp_array[i]);
}
printf("]");
free(input_array1);
free(input_array2);
free(temp_array);
}
|
salass00/png16_lib
|
include/interfaces/png16.h
|
<gh_stars>0
#ifndef PNG16_INTERFACE_DEF_H
#define PNG16_INTERFACE_DEF_H
#ifndef EXEC_TYPES_H
#include <exec/types.h>
#endif
#ifndef EXEC_EXEC_H
#include <exec/exec.h>
#endif
#ifndef EXEC_INTERFACES_H
#include <exec/interfaces.h>
#endif
#ifndef LIBRARIES_PNG16_H
#include <libraries/png16.h>
#endif
#ifdef __cplusplus
#ifdef __USE_AMIGAOS_NAMESPACE__
namespace AmigaOS {
#endif
extern "C" {
#endif
struct PNG16IFace
{
struct InterfaceData Data;
uint32 APICALL (*Obtain)(struct PNG16IFace *Self);
uint32 APICALL (*Release)(struct PNG16IFace *Self);
void APICALL (*Expunge)(struct PNG16IFace *Self);
struct Interface * APICALL (*Clone)(struct PNG16IFace *Self);
png_uint_32 (*png_access_version_number)(void);
void (*png_set_sig_bytes)(png_structrp png_ptr, int num_bytes);
int (*png_sig_cmp)(png_const_bytep sig, png_size_t start, png_size_t num_to_check);
png_structp (*png_create_read_struct)(png_const_charp user_png_ver, png_voidp error_ptr, png_error_ptr error_fn, png_error_ptr warn_fn);
png_structp (*png_create_write_struct)(png_const_charp user_png_ver, png_voidp error_ptr, png_error_ptr error_fn, png_error_ptr warn_fn);
png_size_t (*png_get_compression_buffer_size)(png_const_structrp png_ptr);
void (*png_set_compression_buffer_size)(png_structrp png_ptr, png_size_t size);
jmp_buf *(*png_set_longjmp_fn)(png_structrp png_ptr, png_longjmp_ptr longjmp_fn, size_t jmp_buf_size);
void (*png_longjmp)(png_const_structrp png_ptr, int val);
png_structp (*png_create_read_struct_2)(png_const_charp user_png_ver, png_voidp error_ptr, png_error_ptr error_fn, png_error_ptr warn_fn, png_voidp mem_ptr, png_malloc_ptr malloc_fn, png_free_ptr free_fn);
png_structp (*png_create_write_struct_2)(png_const_charp user_png_ver, png_voidp error_ptr, png_error_ptr error_fn, png_error_ptr warn_fn, png_voidp mem_ptr, png_malloc_ptr malloc_fn, png_free_ptr free_fn);
void (*png_write_sig)(png_structrp png_ptr);
void (*png_write_chunk)(png_structrp png_ptr, png_const_bytep chunk_name, png_const_bytep data, png_size_t length);
void (*png_write_chunk_start)(png_structrp png_ptr, png_const_bytep chunk_name, png_uint_32 length);
void (*png_write_chunk_data)(png_structrp png_ptr, png_const_bytep data, png_size_t length);
void (*png_write_chunk_end)(png_structrp png_ptr);
png_infop (*png_create_info_struct)(png_const_structrp png_ptr);
void (*png_write_info_before_PLTE)(png_structrp png_ptr, png_const_inforp info_ptr);
void (*png_write_info)(png_structrp png_ptr, png_const_inforp info_ptr);
void (*png_read_info)(png_structrp png_ptr, png_inforp info_ptr);
int (*png_convert_to_rfc1123_buffer)(char out[29], png_const_timep ptime);
void (*png_convert_from_struct_tm)(png_timep ptime, const struct tm * ttime);
void (*png_convert_from_time_t)(png_timep ptime, time_t ttime);
void (*png_set_expand)(png_structrp png_ptr);
void (*png_set_expand_gray_1_2_4_to_8)(png_structrp png_ptr);
void (*png_set_palette_to_rgb)(png_structrp png_ptr);
void (*png_set_tRNS_to_alpha)(png_structrp png_ptr);
void (*png_set_expand_16)(png_structrp png_ptr);
void (*png_set_bgr)(png_structrp png_ptr);
void (*png_set_gray_to_rgb)(png_structrp png_ptr);
void (*png_set_rgb_to_gray)(png_structrp png_ptr, int error_action, double red, double green);
void (*png_set_rgb_to_gray_fixed)(png_structrp png_ptr, int error_action, png_fixed_point red, png_fixed_point green);
png_byte (*png_get_rgb_to_gray_status)(png_const_structrp png_ptr);
void (*png_build_grayscale_palette)(int bit_depth, png_colorp palette);
void (*png_set_alpha_mode)(png_structrp png_ptr, int mode, double output_gamma);
void (*png_set_alpha_mode_fixed)(png_structrp png_ptr, int mode, png_fixed_point output_gamma);
void (*png_set_strip_alpha)(png_structrp png_ptr);
void (*png_set_swap_alpha)(png_structrp png_ptr);
void (*png_set_invert_alpha)(png_structrp png_ptr);
void (*png_set_filler)(png_structrp png_ptr, png_uint_32 filler, int flags);
void (*png_set_add_alpha)(png_structrp png_ptr, png_uint_32 filler, int flags);
void (*png_set_swap)(png_structrp png_ptr);
void (*png_set_packing)(png_structrp png_ptr);
void (*png_set_packswap)(png_structrp png_ptr);
void (*png_set_shift)(png_structrp png_ptr, png_const_color_8p true_bits);
int (*png_set_interlace_handling)(png_structrp png_ptr);
void (*png_set_invert_mono)(png_structrp png_ptr);
void (*png_set_background)(png_structrp png_ptr, png_const_color_16p background_color, int background_gamma_code, int need_expand, double background_gamma);
void (*png_set_background_fixed)(png_structrp png_ptr, png_const_color_16p background_color, int background_gamma_code, int need_expand, png_fixed_point background_gamma);
void (*png_set_scale_16)(png_structrp png_ptr);
void (*png_set_strip_16)(png_structrp png_ptr);
void (*png_set_quantize)(png_structrp png_ptr, png_colorp palette, int num_palette, int maximum_colors, png_const_uint_16p histogram, int full_quantize);
void (*png_set_gamma)(png_structrp png_ptr, double screen_gamma, double override_file_gamma);
void (*png_set_gamma_fixed)(png_structrp png_ptr, png_fixed_point screen_gamma, png_fixed_point override_file_gamma);
void (*png_set_flush)(png_structrp png_ptr, int nrows);
void (*png_write_flush)(png_structrp png_ptr);
void (*png_start_read_image)(png_structrp png_ptr);
void (*png_read_update_info)(png_structrp png_ptr, png_inforp info_ptr);
void (*png_read_rows)(png_structrp png_ptr, png_bytepp row, png_bytepp display_row, png_uint_32 num_rows);
void (*png_read_row)(png_structrp png_ptr, png_bytep row, png_bytep display_row);
void (*png_write_row)(png_structrp png_ptr, png_const_bytep row);
void (*png_write_rows)(png_structrp png_ptr, png_bytepp row, png_uint_32 num_rows);
void (*png_write_image)(png_structrp png_ptr, png_bytepp image);
void (*png_write_end)(png_structrp png_ptr, png_inforp info_ptr);
void (*png_read_end)(png_structrp png_ptr, png_inforp info_ptr);
void (*png_destroy_info_struct)(png_const_structrp png_ptr, png_infopp info_ptr_ptr);
void (*png_destroy_read_struct)(png_structpp png_ptr_ptr, png_infopp info_ptr_ptr, png_infopp end_info_ptr_ptr);
void (*png_destroy_write_struct)(png_structpp png_ptr_ptr, png_infopp info_ptr_ptr);
void (*png_set_crc_action)(png_structrp png_ptr, int crit_action, int ancil_action);
void (*png_set_filter)(png_structrp png_ptr, int method, int filters);
void (*png_set_filter_heuristics)(png_structrp png_ptr, int heuristic_method, int num_weights, png_const_doublep filter_weights, png_const_doublep filter_costs);
void (*png_set_filter_heuristics_fixed)(png_structrp png_ptr, int heuristic_method, int num_weights, png_const_fixed_point_p filter_weights, png_const_fixed_point_p filter_costs);
void (*png_set_compression_level)(png_structrp png_ptr, int level);
void (*png_set_compression_mem_level)(png_structrp png_ptr, int mem_level);
void (*png_set_compression_strategy)(png_structrp png_ptr, int strategy);
void (*png_set_compression_window_bits)(png_structrp png_ptr, int window_bits);
void (*png_set_compression_method)(png_structrp png_ptr, int method);
void (*png_set_text_compression_level)(png_structrp png_ptr, int level);
void (*png_set_text_compression_mem_level)(png_structrp png_ptr, int mem_level);
void (*png_set_text_compression_strategy)(png_structrp png_ptr, int strategy);
void (*png_set_text_compression_window_bits)(png_structrp png_ptr, int window_bits);
void (*png_set_text_compression_method)(png_structrp png_ptr, int method);
void (*png_init_io)(png_structrp png_ptr, png_FILE_p fp);
void (*png_set_error_fn)(png_structrp png_ptr, png_voidp error_ptr, png_error_ptr error_fn, png_error_ptr warning_fn);
png_voidp (*png_get_error_ptr)(png_const_structrp png_ptr);
void (*png_set_write_fn)(png_structrp png_ptr, png_voidp io_ptr, png_rw_ptr write_data_fn, png_flush_ptr output_flush_fn);
void (*png_set_read_fn)(png_structrp png_ptr, png_voidp io_ptr, png_rw_ptr read_data_fn);
png_voidp (*png_get_io_ptr)(png_const_structrp png_ptr);
void (*png_set_read_status_fn)(png_structrp png_ptr, png_read_status_ptr read_row_fn);
void (*png_set_write_status_fn)(png_structrp png_ptr, png_write_status_ptr write_row_fn);
void (*png_set_mem_fn)(png_structrp png_ptr, png_voidp mem_ptr, png_malloc_ptr malloc_fn, png_free_ptr free_fn);
void (*png_get_mem_ptr)(png_const_structrp png_ptr);
void (*png_set_read_user_transform_fn)(png_structrp png_ptr, png_user_transform_ptr read_user_transform_fn);
void (*png_set_write_user_transform_fn)(png_structrp png_ptr, png_user_transform_ptr write_user_transform_fn);
void (*png_set_user_transform_info)(png_structrp png_ptr, png_voidp user_transform_ptr, int user_transform_depth, int user_transform_channels);
png_voidp (*png_get_user_transform_ptr)(png_const_structrp png_ptr);
png_uint_32 (*png_get_current_row_number)(png_const_structrp);
png_byte (*png_get_current_pass_number)(png_const_structrp);
void (*png_set_read_user_chunk_fn)(png_structrp png_ptr, png_voidp user_chunk_ptr, png_user_chunk_ptr read_user_chunk_fn);
png_voidp (*png_get_user_chunk_ptr)(png_const_structrp png_ptr);
void (*png_set_progressive_read_fn)(png_structrp png_ptr, png_voidp progressive_ptr, png_progressive_info_ptr info_fn, png_progressive_row_ptr row_fn, png_progressive_end_ptr end_fn);
png_voidp (*png_get_progressive_ptr)(png_const_structrp png_ptr);
void (*png_process_data)(png_structrp png_ptr, png_inforp info_ptr, png_bytep buffer, png_size_t buffer_size);
png_size_t (*png_process_data_pause)(png_structrp, int save);
png_uint_32 (*png_process_data_skip)(png_structrp);
void (*png_progressive_combine_row)(png_const_structrp png_ptr, png_bytep old_row, png_const_bytep new_row);
png_voidp (*png_malloc)(png_const_structrp png_ptr, png_alloc_size_t size);
png_voidp (*png_calloc)(png_const_structrp png_ptr, png_alloc_size_t size);
png_voidp (*png_malloc_warn)(png_const_structrp png_ptr, png_alloc_size_t size);
void (*png_free)(png_const_structrp png_ptr, png_voidp ptr);
void (*png_free_data)(png_const_structrp png_ptr, png_inforp info_ptr, png_uint_32 free_me, int num);
void (*png_data_freer)(png_const_structrp png_ptr, png_inforp info_ptr, int freer, png_uint_32 mask);
void (*png_error)(png_const_structrp png_ptr, png_const_charp error_message);
void (*png_chunk_error)(png_const_structrp png_ptr, png_const_charp error_message);
void (*png_warning)(png_const_structrp png_ptr, png_const_charp warning_message);
void (*png_chunk_warning)(png_const_structrp png_ptr, png_const_charp warning_message);
void (*png_benign_error)(png_const_structrp png_ptr, png_const_charp warning_message);
void (*png_chunk_benign_error)(png_const_structrp png_ptr, png_const_charp warning_message);
void (*png_set_benign_errors)(png_const_structrp png_ptr, png_const_charp warning_message);
png_uint_32 (*png_get_valid)(png_const_structrp png_ptr, png_const_inforp info_ptr, png_uint_32 flag);
png_size_t (*png_get_rowbytes)(png_const_structrp png_ptr, png_const_inforp info_ptr);
png_bytepp (*png_get_rows)(png_const_structrp png_ptr, png_const_inforp info_ptr);
void (*png_set_rows)(png_const_structrp png_ptr, png_inforp info_ptr, png_bytepp row_pointers);
png_byte (*png_get_channels)(png_const_structrp png_ptr, png_const_inforp info_ptr);
png_uint_32 (*png_get_image_width)(png_const_structrp png_ptr, png_const_inforp info_ptr);
png_uint_32 (*png_get_image_height)(png_const_structrp png_ptr, png_const_inforp info_ptr);
png_byte (*png_get_bit_depth)(png_const_structrp png_ptr, png_const_inforp info_ptr);
png_byte (*png_get_color_type)(png_const_structrp png_ptr, png_const_inforp info_ptr);
png_byte (*png_get_filter_type)(png_const_structrp png_ptr, png_const_inforp info_ptr);
png_byte (*png_get_interlace_type)(png_const_structrp png_ptr, png_const_inforp info_ptr);
png_byte (*png_get_compression_type)(png_const_structrp png_ptr, png_const_inforp info_ptr);
png_uint_32 (*png_get_pixels_per_meter)(png_const_structrp png_ptr, png_const_inforp info_ptr);
png_uint_32 (*png_get_x_pixels_per_meter)(png_const_structrp png_ptr, png_const_inforp info_ptr);
png_uint_32 (*png_get_y_pixels_per_meter)(png_const_structrp png_ptr, png_const_inforp info_ptr);
float (*png_get_pixel_aspect_ratio)(png_const_structrp png_ptr, png_const_inforp info_ptr);
png_fixed_point (*png_get_pixel_aspect_ratio_fixed)(png_const_structrp png_ptr, png_const_inforp info_ptr);
png_int_32 (*png_get_x_offset_pixels)(png_const_structrp png_ptr, png_const_inforp info_ptr);
png_int_32 (*png_get_y_offset_pixels)(png_const_structrp png_ptr, png_const_inforp info_ptr);
png_int_32 (*png_get_x_offset_microns)(png_const_structrp png_ptr, png_const_inforp info_ptr);
png_int_32 (*png_get_y_offset_microns)(png_const_structrp png_ptr, png_const_inforp info_ptr);
png_const_bytep (*png_get_signature)(png_const_structrp png_ptr, png_const_inforp info_ptr);
png_uint_32 (*png_get_bKGD)(png_const_structrp png_ptr, png_inforp info_ptr, png_color_16p *background);
void (*png_set_bKGD)(png_const_structrp png_ptr, png_inforp info_ptr, png_const_color_16p background);
png_uint_32 (*png_get_cHRM)(png_const_structrp png_ptr, png_const_inforp info_ptr, double *white_x, double *white_y, double *red_x, double *red_y, double *green_x, double *green_y, double *blue_x, double *blue_y);
png_uint_32 (*png_get_cHRM_XYZ)(png_const_structrp png_ptr, png_const_inforp info_ptr, double *red_X, double *red_Y, double *red_Z, double *green_X, double *green_Y, double *green_Z, double *blue_X, double *blue_Y, double *blue_Z);
png_uint_32 (*png_get_cHRM_fixed)(png_const_structrp png_ptr, png_const_inforp info_ptr, png_fixed_point *int_white_x, png_fixed_point *int_white_y, png_fixed_point *int_red_x, png_fixed_point *int_red_y, png_fixed_point *int_green_x, png_fixed_point *int_green_y, png_fixed_point *int_blue_x, png_fixed_point *int_blue_y);
png_uint_32 (*png_get_cHRM_XYZ_fixed)(png_const_structrp png_ptr, png_const_inforp info_ptr, png_fixed_point *int_red_X, png_fixed_point *int_red_Y, png_fixed_point *int_red_Z, png_fixed_point *int_green_X, png_fixed_point *int_green_Y, png_fixed_point *int_green_Z, png_fixed_point *int_blue_X, png_fixed_point *int_blue_Y, png_fixed_point *int_blue_Z);
void (*png_set_cHRM)(png_const_structrp png_ptr, png_inforp info_ptr, double white_x, double white_y, double red_x, double red_y, double green_x, double green_y, double blue_x, double blue_y);
void (*png_set_cHRM_XYZ)(png_const_structrp png_ptr, png_inforp info_ptr, double red_X, double red_Y, double red_Z, double green_X, double green_Y, double green_Z, double blue_X, double blue_Y, double blue_Z);
void (*png_set_cHRM_fixed)(png_const_structrp png_ptr, png_inforp info_ptr, png_fixed_point int_white_x, png_fixed_point int_white_y, png_fixed_point int_red_x, png_fixed_point int_red_y, png_fixed_point int_green_x, png_fixed_point int_green_y, png_fixed_point int_blue_x, png_fixed_point int_blue_y);
void (*png_set_cHRM_XYZ_fixed)(png_const_structrp png_ptr, png_inforp info_ptr, png_fixed_point int_red_X, png_fixed_point int_red_Y, png_fixed_point int_red_Z, png_fixed_point int_green_X, png_fixed_point int_green_Y, png_fixed_point int_green_Z, png_fixed_point int_blue_X, png_fixed_point int_blue_Y, png_fixed_point int_blue_Z);
png_uint_32 (*png_get_eXIf)(png_const_structrp png_ptr, png_inforp info_ptr, png_bytep *exif);
void (*png_set_eXIf)(png_const_structrp png_ptr, png_inforp info_ptr, const png_bytep exif);
png_uint_32 (*png_get_eXIf_1)(png_const_structrp png_ptr, png_const_inforp info_ptr, png_uint_32 *num_exif, png_bytep *exif);
void (*png_set_eXIf_1)(png_const_structrp png_ptr, png_inforp info_ptr, const png_uint_32 num_exif, const png_bytep exif);
png_uint_32 (*png_get_gAMA)(png_const_structrp png_ptr, png_const_inforp info_ptr, double *file_gamma);
png_uint_32 (*png_get_gAMA_fixed)(png_const_structrp png_ptr, png_const_inforp info_ptr, png_fixed_point *int_file_gamma);
void (*png_set_gAMA)(png_const_structrp png_ptr, png_inforp info_ptr, double file_gamma);
void (*png_set_gAMA_fixed)(png_const_structrp png_ptr, png_inforp info_ptr, png_fixed_point int_file_gamma);
png_uint_32 (*png_get_hIST)(png_const_structrp png_ptr, png_inforp info_ptr, png_uint_16p *hist);
void (*png_set_hIST)(png_const_structrp png_ptr, png_inforp info_ptr, png_const_uint_16p hist);
png_uint_32 (*png_get_IHDR)(png_const_structrp png_ptr, png_const_inforp info_ptr, png_uint_32 *width, png_uint_32 *height, int *bit_depth, int *color_type, int *interlace_method, int *compression_method, int *filter_method);
void (*png_set_IHDR)(png_const_structrp png_ptr, png_inforp info_ptr, png_uint_32 width, png_uint_32 height, int bit_depth, int color_type, int interlace_method, int compression_method, int filter_method);
png_uint_32 (*png_get_oFFs)(png_const_structrp png_ptr, png_const_inforp info_ptr, png_int_32 *offset_x, png_int_32 *offset_y, int *unit_type);
void (*png_set_oFFs)(png_const_structrp png_ptr, png_inforp info_ptr, png_int_32 offset_x, png_int_32 offset_y, int unit_type);
png_uint_32 (*png_get_pCAL)(png_const_structrp png_ptr, png_inforp info_ptr, png_charp *purpose, png_int_32 *X0, png_int_32 *X1, int *type, int *nparams, png_charp *units, png_charpp *params);
void (*png_set_pCAL)(png_const_structrp png_ptr, png_inforp info_ptr, png_const_charp purpose, png_int_32 X0, png_int_32 X1, int type, int nparams, png_const_charp units, png_charpp params);
png_uint_32 (*png_get_pHYs)(png_const_structrp png_ptr, png_const_inforp info_ptr, png_uint_32 *res_x, png_uint_32 *res_y, int *unit_type);
void (*png_set_pHYs)(png_const_structrp png_ptr, png_inforp info_ptr, png_uint_32 res_x, png_uint_32 res_y, int unit_type);
png_uint_32 (*png_get_PLTE)(png_const_structrp png_ptr, png_inforp info_ptr, png_colorp *palette, int *num_palette);
void (*png_set_PLTE)(png_structrp png_ptr, png_inforp info_ptr, png_const_colorp palette, int num_palette);
png_uint_32 (*png_get_sBIT)(png_const_structrp png_ptr, png_inforp info_ptr, png_color_8p *sig_bit);
void (*png_set_sBIT)(png_const_structrp png_ptr, png_inforp info_ptr, png_const_color_8p sig_bit);
png_uint_32 (*png_get_sRGB)(png_const_structrp png_ptr, png_const_inforp info_ptr, int *file_srgb_intent);
void (*png_set_sRGB)(png_const_structrp png_ptr, png_inforp info_ptr, int srgb_intent);
void (*png_set_sRGB_gAMA_and_cHRM)(png_const_structrp png_ptr, png_inforp info_ptr, int srgb_intent);
png_uint_32 (*png_get_iCCP)(png_const_structrp png_ptr, png_inforp info_ptr, png_charpp name, int *compression_type, png_bytepp profile, png_uint_32 *proflen);
void (*png_set_iCCP)(png_const_structrp png_ptr, png_inforp info_ptr, png_const_charp name, int compression_type, png_const_bytep profile, png_uint_32 proflen);
int (*png_get_sPLT)(png_const_structrp png_ptr, png_inforp info_ptr, png_sPLT_tpp entries);
void (*png_set_sPLT)(png_const_structrp png_ptr, png_inforp info_ptr, png_const_sPLT_tp entries, int nentries);
int (*png_get_text)(png_const_structrp png_ptr, png_inforp info_ptr, png_textp *text_ptr, int *num_text);
void (*png_set_text)(png_const_structrp png_ptr, png_inforp info_ptr, png_const_textp text_ptr, int num_text);
png_uint_32 (*png_get_tIME)(png_const_structrp png_ptr, png_inforp info_ptr, png_timep *mod_time);
void (*png_set_tIME)(png_const_structrp png_ptr, png_inforp info_ptr, png_const_timep mod_time);
png_uint_32 (*png_get_tRNS)(png_const_structrp png_ptr, png_inforp info_ptr, png_bytep *trans_alpha, int *num_trans, png_color_16p *trans_color);
void (*png_set_tRNS)(png_structrp png_ptr, png_inforp info_ptr, png_const_bytep trans_alpha, int num_trans, png_const_color_16p trans_color);
png_uint_32 (*png_get_sCAL)(png_const_structrp png_ptr, png_const_inforp info_ptr, int *unit, double *width, double *height);
png_uint_32 (*png_get_sCAL_fixed)(png_const_structrp png_ptr, png_const_inforp info_ptr, int *unit, png_fixed_point *width, png_fixed_point *height);
png_uint_32 (*png_get_sCAL_s)(png_const_structrp png_ptr, png_const_inforp info_ptr, int *unit, png_charpp swidth, png_charpp sheight);
void (*png_set_sCAL)(png_const_structrp png_ptr, png_inforp info_ptr, int unit, double width, double height);
void (*png_set_sCAL_fixed)(png_const_structrp png_ptr, png_inforp info_ptr, int unit, png_fixed_point width, png_fixed_point height);
void (*png_set_sCAL_s)(png_const_structrp png_ptr, png_inforp info_ptr, int unit, png_const_charp swidth, png_const_charp sheight);
void (*png_set_keep_unknown_chunks)(png_structrp png_ptr, int keep, png_const_bytep chunk_list, int num_chunks);
int (*png_handle_as_unknown)(png_const_structrp png_ptr, png_const_bytep chunk_name);
void (*png_set_unknown_chunks)(png_const_structrp png_ptr, png_inforp info_ptr, png_const_unknown_chunkp unknowns, int num_unknowns);
void (*png_set_unknown_chunk_location)(png_const_structrp png_ptr, png_inforp info_ptr, int chunk, int location);
int (*png_get_unknown_chunks)(png_const_structrp png_ptr, png_inforp info_ptr, png_unknown_chunkpp entries);
void (*png_set_invalid)(png_const_structrp png_ptr, png_inforp info_ptr, int mask);
void (*png_read_png)(png_structrp png_ptr, png_inforp info_ptr, int transforms, png_voidp params);
void (*png_write_png)(png_structrp png_ptr, png_inforp info_ptr, int transforms, png_voidp params);
png_const_charp (*png_get_copyright)(png_const_structrp png_ptr);
png_const_charp (*png_get_header_ver)(png_const_structrp png_ptr);
png_const_charp (*png_get_header_version)(png_const_structrp png_ptr);
png_const_charp (*png_get_libpng_ver)(png_const_structrp png_ptr);
png_uint_32 (*png_permit_mng_features)(png_structrp png_ptr, png_uint_32 mng_features_permitted);
void (*png_set_user_limits)(png_structrp png_ptr, png_uint_32 user_width_max, png_uint_32 user_height_max);
png_uint_32 (*png_get_user_width_max)(png_const_structrp png_ptr);
png_uint_32 (*png_get_user_height_max)(png_const_structrp png_ptr);
void (*png_set_chunk_cache_max)(png_structrp png_ptr, png_uint_32 user_chunk_cache_max);
png_uint_32 (*png_get_chunk_cache_max)(png_const_structrp png_ptr);
void (*png_set_chunk_malloc_max)(png_structrp png_ptr, png_alloc_size_t user_chunk_cache_max);
png_alloc_size_t (*png_get_chunk_malloc_max)(png_const_structrp png_ptr);
png_uint_32 (*png_get_pixels_per_inch)(png_const_structrp png_ptr, png_const_inforp info_ptr);
png_uint_32 (*png_get_x_pixels_per_inch)(png_const_structrp png_ptr, png_const_inforp info_ptr);
png_uint_32 (*png_get_y_pixels_per_inch)(png_const_structrp png_ptr, png_const_inforp info_ptr);
float (*png_get_x_offset_inches)(png_const_structrp png_ptr, png_const_inforp info_ptr);
png_fixed_point (*png_get_x_offset_inches_fixed)(png_const_structrp png_ptr, png_const_inforp info_ptr);
float (*png_get_y_offset_inches)(png_const_structrp png_ptr, png_const_inforp info_ptr);
png_fixed_point (*png_get_y_offset_inches_fixed)(png_const_structrp png_ptr, png_const_inforp info_ptr);
png_uint_32 (*png_get_pHYs_dpi)(png_const_structrp png_ptr, png_const_inforp info_ptr, png_uint_32 *res_x, png_uint_32 *res_y, int *unit_type);
png_uint_32 (*png_get_io_state)(png_const_structrp png_ptr);
png_uint_32 (*png_get_io_chunk_type)(png_const_structrp png_ptr);
png_uint_32 (*png_get_uint_32)(png_const_bytep buf);
png_uint_16 (*png_get_uint_16)(png_const_bytep buf);
png_int_32 (*png_get_int_32)(png_const_bytep buf);
png_uint_32 (*png_get_uint_31)(png_const_structrp png_ptr, png_const_bytep buf);
void (*png_save_uint_32)(png_bytep buf, png_uint_32 i);
void (*png_save_int_32)(png_bytep buf, png_int_32 i);
void (*png_save_uint_16)(png_bytep buf, unsigned int i);
void (*png_set_check_for_invalid_index)(png_structrp png_ptr, int allowed);
int (*png_get_palette_max)(png_const_structp png_ptr, png_const_infop info_ptr);
int (*png_image_begin_read_from_file)(png_imagep image, const char *file_name);
int (*png_image_begin_read_from_stdio)(png_imagep image, FILE* file);
int (*png_image_begin_read_from_memory)(png_imagep image, png_const_voidp memory, png_size_t size);
int (*png_image_finish_read)(png_imagep image, png_const_colorp background, void *buffer, png_int_32 row_stride, void *colormap);
void (*png_image_free)(png_imagep image);
int (*png_image_write_to_file)(png_imagep image, const char *file, int convert_to_8bit, const void *buffer, png_int_32 row_stride, const void *colormap);
int (*png_image_write_to_stdio)(png_imagep image, FILE *file, int convert_to_8_bit, const void *buffer, png_int_32 row_stride, const void *colormap);
int (*png_image_write_to_memory)(png_imagep image, void *memory, png_alloc_size_t * PNG_RESTRICT memory_bytes, int convert_to_8_bit, const void *buffer, png_int_32 row_stride, const void *colormap);
int (*png_set_option)(png_structrp png_ptr, int option, int onoff);
};
#ifdef __cplusplus
}
#ifdef __USE_AMIGAOS_NAMESPACE__
}
#endif
#endif
#endif /* PNG16_INTERFACE_DEF_H */
|
salass00/png16_lib
|
init.c
|
/*
* AmigaOS shared library implementation of libpng 1.6.x
*
* Copyright (C) 2017 <NAME> <<EMAIL>>
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS'
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#include <proto/exec.h>
#include <proto/dos.h>
#include <interfaces/png16.h>
#include "png16.library_rev.h"
#define LIBNAME "png16.library"
static const USED TEXT verstag[] = VERSTAG;
static const USED TEXT extversion[] = "\0$EXTVER: libpng " PNG_LIBPNG_VER_STRING " (" DATE ")";
struct PNG16Base {
struct Library libNode;
BPTR segList;
/* If you need more data fields, add them here */
};
struct ExecIFace *IExec;
struct DOSIFace *IDOS;
struct NewlibIFace *INewlib;
struct ZIFace *IZ;
int32 _start(void) {
/* If you feel like it, open DOS and print something to the user */
return RETURN_FAIL;
}
static struct Interface *OpenInterface(CONST_STRPTR name, ULONG version) {
struct Library *library;
struct Interface *interface;
library = IExec->OpenLibrary(name, version);
if (library == NULL)
return NULL;
interface = IExec->GetInterface(library, "main", 1, NULL);
if (interface == NULL) {
IExec->CloseLibrary(library);
return NULL;
}
return interface;
}
static void CloseInterface(struct Interface *interface) {
struct Library *library;
if (interface == NULL)
return;
library = interface->Data.LibBase;
IExec->DropInterface(interface);
IExec->CloseLibrary(library);
}
static BOOL CheckInterface(struct Interface *interface, CONST_STRPTR name, int32 version, int32 revision) {
CONST_STRPTR bodytext;
ULONG args[5];
bodytext = "Failed to open %s V%ld\n\n";
args[0] = (ULONG)name;
args[1] = version;
if (interface != NULL) {
if (LIB_IS_AT_LEAST(interface->Data.LibBase, version, revision))
return TRUE;
bodytext = "You need %s V%ld.%ld+\nYou only have V%ld.%ld\n\n";
args[2] = revision;
args[3] = interface->Data.LibBase->lib_Version;
args[4] = interface->Data.LibBase->lib_Revision;
}
IDOS->TimedDosRequesterTags(
TDR_Timeout, 30,
TDR_NonBlocking, TRUE,
TDR_TitleString, VERS,
TDR_FormatString, bodytext,
TDR_GadgetString, "OK",
TDR_ImageType, TDRIMAGE_ERROR,
TDR_ArgArray, args,
TAG_END);
return FALSE;
}
/* Open the library */
STATIC struct Library *libOpen(struct LibraryManagerInterface *Self, ULONG version) {
struct Library *libBase = Self->Data.LibBase;
if (version > VERSION) {
return NULL;
}
/* Add any specific open code here
Return 0 before incrementing OpenCnt to fail opening */
/* Add up the open count */
libBase->lib_OpenCnt++;
return libBase;
}
/* Close the library */
STATIC BPTR libClose(struct LibraryManagerInterface *Self) {
struct Library *libBase = Self->Data.LibBase;
/* Make sure to undo what open did */
/* Make the close count */
libBase->lib_OpenCnt--;
return ZERO;
}
/* Expunge the library */
STATIC BPTR libExpunge(struct LibraryManagerInterface *Self) {
struct PNG16Base *libBase = (struct PNG16Base *)Self->Data.LibBase;
BPTR result;
if (libBase->libNode.lib_OpenCnt == 0) {
result = libBase->segList;
/* Undo what the init code did */
CloseInterface((struct Interface *)IZ);
CloseInterface((struct Interface *)INewlib);
CloseInterface((struct Interface *)IDOS);
IExec->Remove((struct Node *)libBase);
IExec->DeleteLibrary((struct Library *)libBase);
} else {
/* If your library cannot be expunged, return ZERO */
result = ZERO;
libBase->libNode.lib_Flags |= LIBF_DELEXP;
}
return result;
}
/* The ROMTAG Init Function */
STATIC struct PNG16Base *libInit(struct PNG16Base *libBase, BPTR seglist, struct ExecIFace *exec) {
libBase->libNode.lib_Node.ln_Type = NT_LIBRARY;
libBase->libNode.lib_Node.ln_Pri = 0;
libBase->libNode.lib_Node.ln_Name = (STRPTR)LIBNAME;
libBase->libNode.lib_Flags = LIBF_SUMUSED|LIBF_CHANGED;
libBase->libNode.lib_Version = VERSION;
libBase->libNode.lib_Revision = REVISION;
libBase->libNode.lib_IdString = (STRPTR)VSTRING;
libBase->segList = seglist;
IExec = exec;
IDOS = (struct DOSIFace *)OpenInterface("dos.library", 52);
if (IDOS == NULL) {
IExec->Alert(AG_OpenLib | AO_DOSLib);
goto error;
}
INewlib = (struct NewlibIFace *)OpenInterface("newlib.library", 53);
if (INewlib == NULL) {
IExec->Alert(AG_OpenLib | AO_NewlibLib);
goto error;
}
IZ = (struct ZIFace *)OpenInterface("z.library", 53);
if (!CheckInterface((struct Interface *)IZ, "z.library", 53, 9)) {
goto error;
}
return libBase;
error:
CloseInterface((struct Interface *)IZ);
CloseInterface((struct Interface *)INewlib);
CloseInterface((struct Interface *)IDOS);
IExec->DeleteLibrary((struct Library *)libBase);
return NULL;
}
/* ------------------- Manager Interface ------------------------ */
/* These are generic. Replace if you need more fancy stuff */
STATIC uint32 _manager_Obtain(struct LibraryManagerInterface *Self) {
uint32 res;
__asm__ __volatile__(
"1: lwarx %0,0,%1\n"
"addic %0,%0,1\n"
"stwcx. %0,0,%1\n"
"bne- 1b"
: "=&r" (res)
: "r" (&Self->Data.RefCount)
: "cc", "memory");
return res;
}
STATIC uint32 _manager_Release(struct LibraryManagerInterface *Self) {
uint32 res;
__asm__ __volatile__(
"1: lwarx %0,0,%1\n"
"addic %0,%0,-1\n"
"stwcx. %0,0,%1\n"
"bne- 1b"
: "=&r" (res)
: "r" (&Self->Data.RefCount)
: "cc", "memory");
return res;
}
/* Manager interface vectors */
STATIC CONST APTR lib_manager_vectors[] = {
_manager_Obtain,
_manager_Release,
NULL,
NULL,
libOpen,
libClose,
libExpunge,
NULL,
(APTR)-1
};
//* "__library" interface tag list */
STATIC CONST struct TagItem lib_managerTags[] = {
{ MIT_Name, (Tag)"__library" },
{ MIT_VectorTable, (Tag)lib_manager_vectors },
{ MIT_Version, 1 },
{ TAG_DONE, 0 }
};
/* ------------------- Library Interface(s) ------------------------ */
#include "png16_vectors.c"
/* Uncomment this line (and see below) if your library has a 68k jump table */
/* extern APTR VecTable68K[]; */
STATIC CONST struct TagItem main_v1_Tags[] = {
{ MIT_Name, (Tag)"main" },
{ MIT_VectorTable, (Tag)main_v1_vectors },
{ MIT_Version, 1 },
{ TAG_DONE, 0 }
};
STATIC CONST CONST_APTR libInterfaces[] = {
lib_managerTags,
main_v1_Tags,
NULL
};
STATIC CONST struct TagItem libCreateTags[] = {
{ CLT_DataSize, sizeof(struct PNG16Base) },
{ CLT_InitFunc, (Tag)libInit },
{ CLT_Interfaces, (Tag)libInterfaces },
/* Uncomment the following line if you have a 68k jump table */
/* { CLT_Vector68K, (Tag)VecTable68K }, */
{ TAG_DONE, 0 }
};
/* ------------------- ROM Tag ------------------------ */
STATIC CONST struct Resident USED lib_res = {
RTC_MATCHWORD,
(struct Resident *)&lib_res,
(APTR)(&lib_res + 1),
RTF_NATIVE|RTF_AUTOINIT, /* Add RTF_COLDSTART if you want to be resident */
VERSION,
NT_LIBRARY, /* Make this NT_DEVICE if needed */
0, /* PRI, usually not needed unless you're resident */
LIBNAME,
VSTRING,
(APTR)libCreateTags
};
|
salass00/png16_lib
|
png16_vectors.c
|
/*
* AmigaOS shared library implementation of libpng 1.6.x
*
* Copyright (C) 2017 <NAME> <<EMAIL>>
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS'
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#include "png16_vectors.h"
static const APTR main_v1_vectors[] =
{
_main_Obtain,
_main_Release,
NULL,
NULL,
png_access_version_number,
png_set_sig_bytes,
png_sig_cmp,
png_create_read_struct,
png_create_write_struct,
png_get_compression_buffer_size,
png_set_compression_buffer_size,
png_set_longjmp_fn,
png_longjmp,
png_create_read_struct_2,
png_create_write_struct_2,
png_write_sig,
png_write_chunk,
png_write_chunk_start,
png_write_chunk_data,
png_write_chunk_end,
png_create_info_struct,
png_write_info_before_PLTE,
png_write_info,
png_read_info,
png_convert_to_rfc1123_buffer,
png_convert_from_struct_tm,
png_convert_from_time_t,
png_set_expand,
png_set_expand_gray_1_2_4_to_8,
png_set_palette_to_rgb,
png_set_tRNS_to_alpha,
png_set_expand_16,
png_set_bgr,
png_set_gray_to_rgb,
png_set_rgb_to_gray,
png_set_rgb_to_gray_fixed,
png_get_rgb_to_gray_status,
png_build_grayscale_palette,
png_set_alpha_mode,
png_set_alpha_mode_fixed,
png_set_strip_alpha,
png_set_swap_alpha,
png_set_invert_alpha,
png_set_filler,
png_set_add_alpha,
png_set_swap,
png_set_packing,
png_set_packswap,
png_set_shift,
png_set_interlace_handling,
png_set_invert_mono,
png_set_background,
png_set_background_fixed,
png_set_scale_16,
png_set_strip_16,
png_set_quantize,
png_set_gamma,
png_set_gamma_fixed,
png_set_flush,
png_write_flush,
png_start_read_image,
png_read_update_info,
png_read_rows,
png_read_row,
png_write_row,
png_write_rows,
png_write_image,
png_write_end,
png_read_end,
png_destroy_info_struct,
png_destroy_read_struct,
png_destroy_write_struct,
png_set_crc_action,
png_set_filter,
png_set_filter_heuristics,
png_set_filter_heuristics_fixed,
png_set_compression_level,
png_set_compression_mem_level,
png_set_compression_strategy,
png_set_compression_window_bits,
png_set_compression_method,
png_set_text_compression_level,
png_set_text_compression_mem_level,
png_set_text_compression_strategy,
png_set_text_compression_window_bits,
png_set_text_compression_method,
png_init_io,
png_set_error_fn,
png_get_error_ptr,
png_set_write_fn,
png_set_read_fn,
png_get_io_ptr,
png_set_read_status_fn,
png_set_write_status_fn,
png_set_mem_fn,
png_get_mem_ptr,
png_set_read_user_transform_fn,
png_set_write_user_transform_fn,
png_set_user_transform_info,
png_get_user_transform_ptr,
png_get_current_row_number,
png_get_current_pass_number,
png_set_read_user_chunk_fn,
png_get_user_chunk_ptr,
png_set_progressive_read_fn,
png_get_progressive_ptr,
png_process_data,
png_process_data_pause,
png_process_data_skip,
png_progressive_combine_row,
png_malloc,
png_calloc,
png_malloc_warn,
png_free,
png_free_data,
png_data_freer,
png_error,
png_chunk_error,
png_warning,
png_chunk_warning,
png_benign_error,
png_chunk_benign_error,
png_set_benign_errors,
png_get_valid,
png_get_rowbytes,
png_get_rows,
png_set_rows,
png_get_channels,
png_get_image_width,
png_get_image_height,
png_get_bit_depth,
png_get_color_type,
png_get_filter_type,
png_get_interlace_type,
png_get_compression_type,
png_get_pixels_per_meter,
png_get_x_pixels_per_meter,
png_get_y_pixels_per_meter,
png_get_pixel_aspect_ratio,
png_get_pixel_aspect_ratio_fixed,
png_get_x_offset_pixels,
png_get_y_offset_pixels,
png_get_x_offset_microns,
png_get_y_offset_microns,
png_get_signature,
png_get_bKGD,
png_set_bKGD,
png_get_cHRM,
png_get_cHRM_XYZ,
png_get_cHRM_fixed,
png_get_cHRM_XYZ_fixed,
png_set_cHRM,
png_set_cHRM_XYZ,
png_set_cHRM_fixed,
png_set_cHRM_XYZ_fixed,
png_get_eXIf,
png_set_eXIf,
png_get_eXIf_1,
png_set_eXIf_1,
png_get_gAMA,
png_get_gAMA_fixed,
png_set_gAMA,
png_set_gAMA_fixed,
png_get_hIST,
png_set_hIST,
png_get_IHDR,
png_set_IHDR,
png_get_oFFs,
png_set_oFFs,
png_get_pCAL,
png_set_pCAL,
png_get_pHYs,
png_set_pHYs,
png_get_PLTE,
png_set_PLTE,
png_get_sBIT,
png_set_sBIT,
png_get_sRGB,
png_set_sRGB,
png_set_sRGB_gAMA_and_cHRM,
png_get_iCCP,
png_set_iCCP,
png_get_sPLT,
png_set_sPLT,
png_get_text,
png_set_text,
png_get_tIME,
png_set_tIME,
png_get_tRNS,
png_set_tRNS,
png_get_sCAL,
png_get_sCAL_fixed,
png_get_sCAL_s,
png_set_sCAL,
png_set_sCAL_fixed,
png_set_sCAL_s,
png_set_keep_unknown_chunks,
png_handle_as_unknown,
png_set_unknown_chunks,
png_set_unknown_chunk_location,
png_get_unknown_chunks,
png_set_invalid,
png_read_png,
png_write_png,
png_get_copyright,
png_get_header_ver,
png_get_header_version,
png_get_libpng_ver,
png_permit_mng_features,
png_set_user_limits,
png_get_user_width_max,
png_get_user_height_max,
png_set_chunk_cache_max,
png_get_chunk_cache_max,
png_set_chunk_malloc_max,
png_get_chunk_malloc_max,
png_get_pixels_per_inch,
png_get_x_pixels_per_inch,
png_get_y_pixels_per_inch,
png_get_x_offset_inches,
png_get_x_offset_inches_fixed,
png_get_y_offset_inches,
png_get_y_offset_inches_fixed,
png_get_pHYs_dpi,
png_get_io_state,
png_get_io_chunk_type,
png_get_uint_32,
png_get_uint_16,
png_get_int_32,
png_get_uint_31,
png_save_uint_32,
png_save_int_32,
png_save_uint_16,
png_set_check_for_invalid_index,
png_get_palette_max,
png_image_begin_read_from_file,
png_image_begin_read_from_stdio,
png_image_begin_read_from_memory,
png_image_finish_read,
png_image_free,
png_image_write_to_file,
png_image_write_to_stdio,
png_image_write_to_memory,
png_set_option,
(APTR)-1
};
|
salass00/png16_lib
|
zlib/stubs.c
|
<gh_stars>0
/*
* AmigaOS shared library implementation of libpng 1.6.x
*
* Copyright (C) 2017 <NAME> <<EMAIL>>
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS'
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#define LIBRARIES_Z_H
#include <zlib.h>
#include <interfaces/z.h>
extern struct ZIFace *IZ;
const char *zlibVersion(void) {
return IZ->ZlibVersion();
}
int deflateInit_(z_streamp strm, int level, const char *version, int stream_size) {
const char *my_version = IZ->ZlibVersion();
if (version == Z_NULL || version[0] != my_version[0] || stream_size != sizeof(z_stream)) {
return Z_VERSION_ERROR;
}
return IZ->DeflateInit(strm, level);
}
int deflateInit2_(z_streamp strm, int level, int method, int windowBits, int memLevel,
int strategy, const char *version, int stream_size)
{
const char *my_version = IZ->ZlibVersion();
if (version == Z_NULL || version[0] != my_version[0] || stream_size != sizeof(z_stream)) {
return Z_VERSION_ERROR;
}
return IZ->DeflateInit2(strm, level, method, windowBits, memLevel, strategy);
}
int deflateSetDictionary(z_streamp strm, const Bytef *dictionary, uInt dictLength) {
return IZ->DeflateSetDictionary(strm, dictionary, dictLength);
}
int deflate (z_streamp strm, int flush) {
return IZ->Deflate(strm, flush);
}
int deflateCopy(z_streamp dest, z_streamp source) {
return IZ->DeflateCopy(dest, source);
}
int deflateReset(z_streamp strm) {
return IZ->DeflateReset(strm);
}
int deflateParams(z_streamp strm, int level, int strategy) {
return IZ->DeflateParams(strm, level, strategy);
}
int deflateTune(z_streamp strm, int good_length, int max_lazy, int nice_length,
int max_chain)
{
return IZ->DeflateTune(strm, good_length, max_lazy, nice_length, max_chain);
}
uLong deflateBound(z_streamp strm, uLong sourceLen) {
return IZ->DeflateBound(strm, sourceLen);
}
int deflatePrime(z_streamp strm, int bits, int value) {
return IZ->DeflatePrime(strm, bits, value);
}
int deflateSetHeader(z_streamp strm, gz_headerp head) {
return IZ->DeflateSetHeader(strm, head);
}
int deflateEnd(z_streamp strm) {
return IZ->DeflateEnd(strm);
}
int inflateInit_(z_streamp strm, const char *version, int stream_size) {
const char *my_version = IZ->ZlibVersion();
if (version == Z_NULL || version[0] != my_version[0] || stream_size != sizeof(z_stream)) {
return Z_VERSION_ERROR;
}
return IZ->InflateInit(strm);
}
int inflateInit2_(z_streamp strm, int windowBits, const char *version, int stream_size) {
const char *my_version = IZ->ZlibVersion();
if (version == Z_NULL || version[0] != my_version[0] || stream_size != sizeof(z_stream)) {
return Z_VERSION_ERROR;
}
return IZ->InflateInit2(strm, windowBits);
}
int inflateGetDictionary(z_streamp strm, Bytef *dictionary, uInt *dictLength) {
return IZ->InflateGetDictionary(strm, dictionary, (uint32 *)dictLength);
}
int inflateSetDictionary(z_streamp strm, const Bytef *dictionary, uInt dictLength) {
return IZ->InflateSetDictionary(strm, dictionary, dictLength);
}
int inflate(z_streamp strm, int flush) {
return IZ->Inflate(strm, flush);
}
int inflateSync (z_streamp strm) {
return IZ->InflateSync(strm);
}
int inflateCopy(z_streamp dest, z_streamp source) {
return IZ->InflateCopy(dest, source);
}
int inflateReset(z_streamp strm) {
return IZ->InflateReset(strm);
}
int inflatePrime(z_streamp strm, int bits, int value) {
return IZ->InflatePrime(strm, bits, value);
}
int inflateGetHeader(z_streamp strm, gz_headerp head) {
return IZ->InflateGetHeader(strm, head);
}
int inflateEnd(z_streamp strm) {
return IZ->InflateEnd(strm);
}
int inflateBackInit_(z_streamp strm, int windowBits, unsigned char *window,
const char *version, int stream_size)
{
const char *my_version = IZ->ZlibVersion();
if (version == Z_NULL || version[0] != my_version[0] || stream_size != sizeof(z_stream)) {
return Z_VERSION_ERROR;
}
return IZ->InflateBackInit(strm, windowBits, window);
}
int inflateBack(z_streamp strm, in_func in, void *in_desc, out_func out, void *out_desc) {
return IZ->InflateBack(strm, in, in_desc, out, out_desc);
}
int inflateBackEnd(z_streamp strm) {
return IZ->InflateBackEnd(strm);
}
int compress(Bytef *dest, uLongf *destLen, const Bytef *source, uLong sourceLen) {
return IZ->Compress(dest, destLen, source, sourceLen);
}
int compress2(Bytef *dest, uLongf *destLen, const Bytef *source, uLong sourceLen, int level) {
return IZ->Compress2(dest, destLen, source, sourceLen, level);
}
uLong compressBound(uLong sourceLen) {
return IZ->CompressBound(sourceLen);
}
int uncompress(Bytef *dest, uLongf *destLen, const Bytef *source, uLong sourceLen) {
return IZ->Uncompress(dest, destLen, source, sourceLen);
}
uLong adler32(uLong adler, const Bytef *buf, uInt len) {
return IZ->Adler32(adler, buf, len);
}
uLong adler32_combine(uLong adler1, uLong adler2, z_off_t len2) {
return IZ->Adler32Combine(adler1, adler2, len2);
}
uLong crc32(uLong crc, const Bytef *buf, uInt len) {
return IZ->CRC32(crc, buf, len);
}
uLong crc32_combine(uLong crc1, uLong crc2, z_off_t len2) {
return IZ->CRC32Combine(crc1, crc2, len2);
}
const char *zError(int err) {
return IZ->ZError(err);
}
int uncompress2(Bytef *dest, uLongf *destLen, const Bytef *source, uLong *sourceLen) {
return IZ->Uncompress2(dest, destLen, source, sourceLen);
}
uLong adler32_z(uLong adler, const Bytef *buf, z_size_t len) {
return IZ->Adler32(adler, buf, len);
}
uLong crc32_z(uLong crc, const Bytef *buf, z_size_t len) {
return IZ->CRC32(crc, buf, len);
}
int inflateReset2(z_streamp strm, int windowBits) {
return IZ->InflateReset2(strm, windowBits);
}
int inflateValidate(z_streamp strm, int check) {
return IZ->InflateValidate(strm, check);
}
|
salass00/png16_lib
|
include/proto/png16.h
|
<filename>include/proto/png16.h
#ifndef PROTO_PNG16_H
#define PROTO_PNG16_H
/****************************************************************************/
#ifndef __NOLIBBASE__
extern struct Library * PNG16Base;
#endif
/****************************************************************************/
#ifdef __amigaos4__
#include <interfaces/png16.h>
#ifdef __USE_INLINE__
#include <inline4/png16.h>
#endif /* __USE_INLINE__ */
#ifndef CLIB_PNG16_PROTOS_H
#define CLIB_PNG16_PROTOS_H 1
#endif /* CLIB_PNG16_PROTOS_H */
#ifndef __NOGLOBALIFACE__
extern struct PNG16IFace *IPNG16;
#endif /* __NOGLOBALIFACE__ */
#else /* __amigaos4__ */
#ifndef CLIB_PNG16_PROTOS_H
#include <clib/png16_protos.h>
#endif /* CLIB_PNG16_PROTOS_H */
#if defined(__GNUC__)
#ifndef __PPC__
#include <inline/png16.h>
#else
#include <ppcinline/png16.h>
#endif /* __PPC__ */
#elif defined(__VBCC__)
#ifndef __PPC__
#include <inline/png16_protos.h>
#endif /* __PPC__ */
#else
#include <pragmas/png16_pragmas.h>
#endif /* __GNUC__ */
#endif /* __amigaos4__ */
/****************************************************************************/
#endif /* PROTO_PNG16_H */
|
salass00/png16_lib
|
png16.library_rev.h
|
#define VERSION 53
#define REVISION 1
#define DATE "25.12.2017"
#define VERS "png16.library 53.1"
#define VSTRING "png16.library 53.1 (25.12.2017)\r\n"
#define VERSTAG "\0$VER: png16.library 53.1 (25.12.2017)"
|
salass00/png16_lib
|
pngcrush-1.8.13/pngcrush.c
|
/* pngcrush.c - recompresses png files
* Copyright (C) 1998-2002, 2006-2017 <NAME>
* (glennrp at users.sf.net)
* Portions Copyright (C) 2005 <NAME>
*/
#define PNGCRUSH_VERSION "1.8.13"
#undef BLOCKY_DEINTERLACE
/* This software is released under a license derived from the libpng
* license (see LICENSE, below).
*
* The most recent version of pngcrush can be found at SourceForge in
* http://pmt.sf.net/pngcrush/
*
* This program reads in a PNG image, and writes it out again, with the
* optimum filter_method and zlib_level. It uses brute force (trying
* filter_method none, and libpng adaptive filtering, with compression
* levels 3 and 9).
*
* Optionally, it can remove unwanted chunks or add gAMA, sRGB, bKGD,
* tEXt/zTXt, and tRNS chunks. It will remove some chunks such as gAMA,
* cHRM, pHYs, and oFFs when their data fields contain all zero, which is a
* mistake.
*
* Uses libpng and zlib. This program was based upon libpng's pngtest.c.
*
* NOTICES:
*
* If you have modified this source, you may insert additional notices
* immediately after this sentence.
*
* COPYRIGHT:
*
* Copyright (C) 1998-2002, 2006-2017 <NAME>
* (glennrp at users.sf.net)
* Portions Copyright (C) 2005 <NAME>
*
* LICENSE:
*
* Permission is hereby irrevocably granted to everyone to use, copy, modify,
* and distribute this source code, or portions hereof, or executable programs
* compiled from it, for any purpose, without payment of any fee, subject to
* the following restrictions:
*
* 1. The origin of this source code must not be misrepresented.
*
* 2. Altered versions must be plainly marked as such and must not be
* misrepresented as being the original source.
*
* 3. This Copyright notice, disclaimers, and license may not be removed
* or altered from any source or altered source distribution.
*
* DISCLAIMERS:
*
* The pngcrush computer program is supplied "AS IS". The Author disclaims all
* warranties, expressed or implied, including, without limitation, the
* warranties of merchantability and of fitness for any purpose. The
* Author assumes no liability for direct, indirect, incidental, special,
* exemplary, or consequential damages, which may result from the use of
* the computer program, even if advised of the possibility of such damage.
* There is no warranty against interference with your enjoyment of the
* computer program or against infringement. There is no warranty that my
* efforts or the computer program will fulfill any of your particular purposes
* or needs. This computer program is provided with all faults, and the entire
* risk of satisfactory quality, performance, accuracy, and effort is with
* the user.
*
* EXPORT CONTROL
*
* I am not a lawyer, but I believe that the Export Control Classification
* Number (ECCN) for pngcrush is EAR99, which means not subject to export
* controls or International Traffic in Arms Regulations (ITAR) because it
* and cexcept.c, libpng, and zlib, which may be bundled with pngcrush, are
* all open source, publicly available software, that do not contain any
* encryption software. See the EAR, paragraphs 734.3(b)(3) and 734.7(b).
*
* TRADEMARK:
*
* The name "pngcrush" has not been registered by the Copyright owner
* as a trademark in any jurisdiction. However, because pngcrush has
* been distributed and maintained world-wide, continually since 1998,
* the Copyright owner claims "common-law trademark protection" in any
* jurisdiction where common-law trademark is recognized.
*
* CEXCEPT COPYRIGHT, DISCLAIMER, and LICENSE:
*
* The cexcept.h header file which is bundled with this software
* is conveyed under the license and disclaimer described in lines 10
* through 18 of cexcept.h.
*
* LIBPNG COPYRIGHT, DISCLAIMER, and LICENSE:
*
* If libpng is bundled with this software, it is conveyed under the
* libpng license (see COPYRIGHT NOTICE, DISCLAIMER, and LICENSE, in png.h).
*
* If intel_init.c and filter_sse2_intrinsics.c are bundled with this
* software, they are conveyed under the libpng license (see the
* copyright notices within those files and the COPYRIGHT NOTICE, DISCLAIMER,
* and LICENSE in png.h).
*
* ZLIB COPYRIGHT, DISCLAIMER, and LICENSE:
*
* If zlib is bundled with this software, it is conveyed under the
* zlib license (see the copyright notice, disclaimer, and license
* appearing in zlib.h).
*
* ACKNOWLEDGMENTS:
*
* Thanks to <NAME> for various bug fixes, suggestions, and
* occasionally creating Linux executables.
*
* Thanks to <NAME> for some helpful suggestions about gcc compiler
* options and for a suggestion to increase the Z_MEM_LEVEL from default.
*
* Thanks to others who have made bug reports and suggestions mentioned
* in the change log.
*
* CAUTION:
*
* There is another version of pngcrush that has been distributed by
* Apple since mid-2008 as a part of the Xcode SDK. Although it claims
* to be pngcrush by <NAME>, it has additional options
* "-iPhone", "-speed", "-revert-iphone-optimizations", and perhaps others.
* It is an "altered version". I've seen output from a 2006 version that
* says on its help screen, "and modified by Apple as indicated in the
* sources".
*
* It writes files that have the PNG 8-byte signature but are not valid PNG
* files (instead they are "IOS-optimized PNG files"), due to at least
*
* 1. the presence of the CgBI chunk ahead of the IHDR chunk;
* 2. nonstandard deflate compression in IDAT, iCCP, and perhaps zTXt chunks
* (I believe this only amounts to the omission of the zlib header from
* the IDAT and perhaps other compressed chunks);
* 3. Omission of the CRC bytes from the IDAT chunk and perhaps other chunks;
* 4. the use of premultiplied alpha in color_type 6 files; and
* 5. the sample order, which is ARGB instead of RGBA in color_type 6 files.
*
* See http://iphonedevwiki.net/index.php/CgBI_file_format for more info.
*
* Although there is no loss in converting a CgBI PNG back to a regular
* PNG file, the original PNG file cannot be losslessly recovered from such
* files because of the losses that occurred during the conversion to
* premultiplied alpha.
*
* Most PNG decoders will recognize the fact that an unknown critical
* chunk "CgBI" is present and will immediately reject the file.
*
* It is said that the Xcode version of pngcrush is automatically applied
* when PNG files are prepared for downloading to the iPhone unless the
* user takes special measures to prevent it.
*
* It is said that the Xcode pngcrush does have a command to undo the
* premultiplied alpha. It's not theoretically possible, however, to recover
* the original file without loss. The underlying color data will either be
* reduced in precision, or, in the case of fully-transparent pixels,
* completely lost.
*
* I have not seen the source for the Xcode version of pngcrush. All I
* know, for now, is from running "strings -a" on an old copy of the
* executable, looking at two Xcode-PNG files, and reading Apple's patent
* application <http://www.freepatentsonline.com/y2008/0177769.html>. Anyone
* who does have access to the revised pngcrush code cannot show it to me
* anyhow because of their Non-Disclosure Agreement with Apple.
*/
/* To do (TODO, TO DO):
*
* (As noted below, some of the features that aren't yet implemented
* in pngcrush are already available in ImageMagick; you can try a
* workflow that makes a first pass over the image with ImageMagick
* to select the bit depth, color type, interlacing, etc., and then makes
* another pass with pngcrush to optimize the compression, and finally
* makes a pass with libpng's "pngfix" app to optimize the zlib CMF
* bytes.)
*
* 0. Make pngcrush optionally operate as a filter, writing the crushed PNG
* to standard output, if an output file is not given, and reading
* the source file from standard input if no input file is given.
*
* 1. Reset CINFO to reflect decoder's required window size (instead of
* libz-1.1.3 encoder's required window size, which is 262 bytes larger).
* See discussion about zlib in png-list archives for April 2001.
* libpng-1.2.9 does some of this and libpng-1.5.4 does better.
* But neither has access to the entire datastream, so pngcrush could
* do even better.
*
* This has no effect on the "crushed" filesize. The reason for setting
* CINFO properly is to provide the *decoder* with information that will
* allow it to request only the minimum amount of memory required to decode
* the image (note that libpng-based decoders don't make use of this
* hint, because of the large number of files found in the wild that have
* incorrect CMF bytes).
*
* In the meantime, one can just run
*
* pc input.png crushed.png
*
* where the "pc" script is the following:
*
* #!/bin/sh
* cp $1 temp-$$.png
* for w in 512 1 2 4 8 16 32
* do
* pngcrush -ow -w $w -brute temp-$$.png
* done
* mv temp-$$.png $2
*
* It turns out that sometimes this finds a smaller compressed PNG
* than plain "pngcrush -brute input.png crushed.png" finds.
*
* There are several ways that pngcrush could implement this.
*
* a. Revise the bundled zlib to report the maximum window size that
* it actually used, then rewrite CINFO to contain the next power-of-two
* size equal or larger than the size. This method would of course
* only work when pngcrush is built with the bundled zlib, and won't
* work with zopfli compression.
*
* b. Do additional trials after the best filter method, strategy,
* and compression level have been determined, using those settings
* and reducing the window size until the measured filesize increases,
* then choosing the smallest size which did not cause the filesize
* to increase. This is expensive.
*
* c. After the trials are complete, replace CINFO with smaller
* settings, then attempt to decode the zlib datastream, and choose
* the smallest setting whose datastream can still be decoded
* successfully. This is likely to be the simplest and fastest
* solution; however, it will only work with a version of libpng
* in which the decoder actually uses the CINFO hint.
* This seems to be the only method that would work with zopfli
* compression which always writes "7" (i.e., a 32k window) in CINFO.
*
* d. The simplest is to use pngfix, which comes with libpng16 and
* later, as a final step:
*
* pngcrush input.png temp.png
* pngfix --optimize --out=output.png temp.png
* # To do: find out if this works with zopfli output
*
* 2. Check for the possiblity of using the tRNS chunk instead of
* the full alpha channel. If all of the transparent pixels are
* fully transparent, and they all have the same underlying color,
* and no opaque pixel has that same color, then write a tRNS
* chunk and reduce the color-type to 0 or 2. This is a lossless
* operation. ImageMagick already does this, as of version 6.7.0.
* If the lossy "-blacken" option is present, do that operation first.
*
* 3. Add choice of interlaced or non-interlaced output. Currently you
* can change interlaced to non-interlaced and vice versa by using
* ImageMagick before running pngcrush. Note, when implementing this,
* disallow changing interlacing if APNG chunks are being copied.
*
* 4. Use a better compression algorithm for "deflating" (result must
* still be readable with zlib!) e.g., http://en.wikipedia.org/wiki/7-Zip
* says that the 7-zip deflate compressor achieves better compression
* (smaller files) than zlib. If tests show that this would be worth
* while, incorporate the 7-zip compressor as an optional alternative
* or additional method of pngcrush compression. See the GPL-licensed code
* at http://en.wikipedia.org/wiki/AdvanceCOMP and note that if this
* is incorporated in pngcrush, then pngcrush would have to be re-licensed,
* or released in two versions, one libpng-licensed and one GPL-licensed!
*
* Also consider Google's "zopfli" compressor, which is said to slow but
* achieves better compression. It is Apache-2.0 licensed and available from
* a GIT repository at SourceForge (see https://code.google.com/p/zopfli/).
* See also the "pngzop" directory under the pmt.sourceforge.net project.
* Note paragraph 1.c above; zopfli always writes "7" in CINFO. See
* my "pmt/pngzop" project at SourceForge and GitHub.
*
* 5. Optionally recognize any sRGB iCCP profile and replace it with the
* sRGB chunk. Turn this option on if the "-reduce" option is on. Also,
* if "-reduce" is on, delete any gAMA and cHRM chunks if the sRGB chunk
* is being written.
*
* 6. Accept "--long-option". For starters, just accept -long_option
* and --long_option equally.
*
* 7. Implement a "copy_idat" option that simply copies the IDAT data,
* implemented as "-m 176". This will still repackage the IDAT chunks
* in a possibly different IDAT chunk size.
*
* 8. Implement palette-building (from ImageMagick-6.7.0 or later, minus
* the "PNG8" part) -- actually ImageMagick puts the transparent colors
* first, then the semitransparent colors, and finally the opaque colors,
* and does not sort colors by frequency of use but just adds them
* to the palette/colormap as it encounters them, so it might be improved.
* Also it might be made faster by using a hash table as was partially
* implemented in pngcrush-1.6.x. If the latter is done, also port that
* back to ImageMagick/GraphicsMagick. See also ppmhist from the NetPBM
* package which counts RGB pixels in an image; this and its supporting
* lib/libppmcmap.c would need to be revised to count RGBA pixels instead.
*
* 9. Improve the -help output and/or write a good man page.
*
* 10. Finish pplt (MNG partial palette) feature.
*
* 11. Remove text-handling and color-handling features and put
* those in a separate program or programs, to avoid unnecessary
* recompressing. Note that in pngcrush-1.7.34, pngcrush began doing
* this extra work only once instead of for every trial, so the potential
* benefit in CPU savings is much smaller now.
*
* 12. Add a "pcRu" ancillary chunk that keeps track of the best method,
* methods already tried, and whether "loco crushing" was effective.
*
* 13. Try both transformed and untransformed colors when "-loco" is used.
*
* 14. Move the Photoshop-fixing stuff into a separate program.
*
* 15. GRR: More generally (superset of previous 3 items): split into
* separate "edit" and "crush" programs (or functions). Former is fully
* libpng-aware, much like current pngcrush; latter makes little or no use of
* libpng (maybe IDAT-compression parts only?), instead handling virtually
* all chunks as opaque binary blocks that are copied to output file _once_,
* with IDATs alone replaced (either by best in-memory result or by original
* _data_ resplit into bigger IDATs, if pngcrush cannot match/beat). "edit"
* version should be similar to current code but more efficient: make
* _one_ pass through args list, creating table of PNG_UINTs for removal;
* then make initial pass through PNG image, creating (in-order) table of
* all chunks (and byte offsets?) and marking each as "keep" or "remove"
* according to args table. Could start with static table of 16 or 32 slots,
* then double size & copy if run out of room: still O(n) algorithm.
*
* 16. With libpng17, png_write throws an "affirm()" with tc.format=256
* when attempting to write a sub-8-bit grayscale image.
*
* 17. Figure out why we aren't calling png_read_update_info() and fix.
*
* 18. Fix ADLER32 checksum handling in conjunction with iCCP chunk
* reading.
*
* 19. Fix Coverity "TOCTOU" warning about our "stat()" usage.
*
* 20. Warn about removing copyright and license info appearing in
* PNG text chunks.
*
* 21. Implement the "eXIf" chunk if it is approved by the PNG
* Development Group. Optionally, remove preview and thumbnail
* images from the Exif profile contained in the eXIf chunk.
*
*/
#if 0 /* changelog */
Change log:
Version 1.8.13 (built with libpng-1.6.32 and zlib-1.2.11)
Add "exit(0)" after processing "-version" argument, to avoid
displaying the Usage information (bug report by <NAME>,
Issue #76).
Fix problem with MacOS prior to Sierra; it uses CLOCK_MONOTONIC
for some other purpose (bug report and help developing patch by
Github user "ilovezfs", Homebrew/homebrew-core PR#16391).
Version 1.8.12 (built with libpng-1.6.31 and zlib-1.2.11)
Added POWERPC-VSX support.
Report whether using optimizations.
Added filter_method 6 (same as filter 5 with -speed).
Added "methods" 149-176 (that use filter_method 6).
Changed default verbosity from 1 (normal) to 0 (quiet). Use "-v" to get
the previous default behavior and "-v -v" to get the previous "verbose"
behavior. The "-s" (silent) and "-q" (quiet) options behave as before.
Version 1.8.11 (built with libpng-1.6.28 and zlib-1.2.11)
Use png_set_option(PNG_IGNORE_ADLER32) to control ADLER32 handling.
Changed LD=gcc to LD=$(CC) in Makefile and Makefile-nolib (suggested
by <NAME> in Bug#850927 of some GIT project)
Version 1.8.10 (built with libpng-1.6.26 and zlib-1.2.8.1)
Changed ADLER32 checksum handling to only use inflateValidate()
during IDAT chunk handling; it broke iCCP chunk handling.
Version 1.8.9 (built with libpng-1.6.26 and zlib-1.2.8.1)
Added "-warn" option, to show only warnings.
Enabled method 149. For now it writes uncompressed IDAT but in
a future version of pngcrush it will just copy the IDAT data.
Version 1.8.8 (built with libpng-1.6.26beta06 and zlib-1.2.8.1)
Fixed "nolib" build (bug report by <NAME>).
Make sure we use system-png.h, and not the local file. It is now
possible to build either the regular pngcrush or the "nolib"
pngcrush in the complete pngcrush source directory (use
"make clean" before rebuilding!)
Fixed timing when using "clock()". Sometimes an additional second
was added when the timer crossed a one-second boundary, since
version 1.8.5.
Upgrade libpng to version 1.6.26beta06 and zlib to 1.2.8.1.
Use zlib-1.2.8.1 new "inflateValidate()" function to avoid checking
ADLER32 checksums. Version 1.8.7 did not work when the "-fix"
option was used.
Version 1.8.7 (built with libpng-1.6.25 and zlib-1.2.8)
Do not check the ADLER32 CRC while reading except during the final write
pass (requires libpng-1.6.26 or later and zlib-1.2.4 or later).
This saves some CPU time, around five to ten percent, in decoding.
Do not calculate the ADLER32 CRC while writing except during the final
write pass (writing raw deflate streams instead of zlib streams to
the IDAT chunks; these are invalid PNGs but since all we do is count
the bytes that does not matter). This saves some CPU time in encoding
but it is barely perceptible. Requires zlib 1.2.4 or later and modified
pngwutil.c.
Version 1.8.6 (built with libpng-1.6.25 and zlib-1.2.8)
Enabled ARM_NEON support.
Fixed error in handling of timer wraparound when interval exceeds one
second.
Disable high resolution timers by default in Makefile. To enable them,
you must enable/disable relevant CPPFLAGS and LIBS in Makefile.
Version 1.8.5 (built with libpng-1.6.24 and zlib-1.2.8)
Added "-benchmark n" option. It runs the main loop "n" times, and
records the minimum value for each timer.
After checking for CLOCK_ID, use clock() if none is found.
Avoid some timing when verbose<0 ("-s" or "--silent")
Added PNGCRUSH_CHECK_CRC (off by default) to use libpng default
CRC checking. Otherwise, CRC are only computed and checked during
the first read pass and while writing.
Accept "--option" (for now, by simply skipping the first "-").
Version 1.8.4 (built with libpng-1.6.24 and zlib-1.2.8)
Fixed handling of CLOCK_ID, removed some "//"-delimited comments.
Revised intel_init.c to always optimize 4bpp images, because the
poor optimization noted previously has been fixed.
Version 1.8.3 (built with libpng-1.6.24 and zlib-1.2.8)
Fixed bug introduced in 1.8.2 that causes trial 10 to be skipped when
using the default heuristic method.
Fixed incorrect typecast in call to png_create_write_struct_2() (Bug
report by <NAME>).
Added intel_init.c, filter_sse2_intrinsics.c, and Makefile-sse,
to enable INTEL SSE optimization. Revised intel_init.c to optionally
only optimize 4bpp images, because the optimization appears to slow
down reading of 3bpp images.
Added PNGCRUSH_TIMERS (nanosecond resolution using clock_gettime), to
measure defiltering time in png_read_filter_row(). For now, this only
works with a modified libpng, on platforms that provide "clock_gettime()".
To enable all timers, define PNGCRUSH_TIMERS=11.
Revised "-q" to show a short summary of results (final size and timing)
To do: Add ZLIB_AMALGAMATED configuration; currently produces different output
https://blog.forrestthewoods.com/
improving-open-source-with-amalgamation-cf293592c5f4#.g9fb2tyhs
(added #ifndef NO_GZ / #endif to skip the gz* code in zlib_amalg.[ch]).
Added LIBPNG_UNIFIED configuration.
Version 1.8.2 (built with libpng-1.6.23 and zlib-1.2.8)
Fixed filesize reduction report when "-ow" option is used (Bug report #68).
When a single method is specified, turn -reduce off by default and skip
trial 0.
Version 1.8.1 (built with libpng-1.6.21 and zlib-1.2.8)
Added the LICENSE file to the tar and zip distributions.
Made "-force" force output even when the IDAT is larger, and added
"-noforce" option; "-noforce" is now the default behavior (Bug
report #68 at SourceForge by "wintakeall")
Use right filename in filesize reduction report (overwrite?inname:outname)
(bug report #69 by "wintakeall").
Removed some superfluous spaces from the Copyright statement.
Added "-speed" option; it avoids using the AVG or PAETH filters which
are slower to decode.
Version 1.8.0 (built with libpng-1.6.21 and zlib-1.2.8)
Made "-reduce" and "-force" the default behavior. Removed obsolete
options "-plte_len", "-cc", "-nocc", "-double_gamma", "-already_crushed",
and "-bit_depth". Removed "things_have_changed" code.
Version 1.7.92 (built with libpng-1.6.20 and zlib-1.2.8)
Deleted png_read_update_info() statement that was mistakenly added to
version 1.7.89. It caused "bad adaptive filter value" errors.
Version 1.7.91 (built with libpng-1.6.20 and zlib-1.2.8)
Suppress warning about "damaged LZ stream" when bailing out and building
with libpng-1.7.0beta.
Added a LICENSE file to the distribution. It points to the actual
license appearing in the NOTICES section near the top of pngcrush.c
Show if pngcrush is built with bundled or system libpng and zlib.
Fixed segfault while writing a -loco MNG (bug found with AFL, reported
by <NAME>). Bug was introduced in pngcrush-1.7.35.
Version 1.7.88 (built with libpng-1.6.19 and zlib-1.2.8)
Eliminated a potential overflow while adding iTXt chunk (over-length
text_lang or text_lang_key), reported by Coverity.
Version 1.7.87 (built with libpng-1.6.18 and zlib-1.2.8)
Fixed a double-free bug (CVE-2015-7700). There was a "free" of the
sPLT chunk structure in pngcrush and then again in png.c (Bug report
by <NAME>).
Added common-law trademark notice and export control information.
Rearranged some paragraphs in the comments at the beginning of pngcrush.c
Increased some buffer sizes in an attempt to prevent possible overflows.
Version 1.7.86 (built with libpng-1.6.18 and zlib-1.2.8)
Increased maximum size of a text chunk input from 260 to 2048
(STR_BUF_SIZE) bytes, to agree with the help screen (bug report by
<NAME>).
Fixed bug that caused text chunks after IDAT to be written only when
the "-save" option is used.
Version 1.7.85 (built with libpng-1.6.16 and zlib-1.2.8)
Improved reporting of invalid chunk names. Does not try to put
non-printable characters in STDERR; displays hex numbers instead.
Fixed include path for utime.h on MSVC (Louis McLaughlin).
Eliminated "FAR" memory support (it was removed from libpng at version
1.6.0).
Disabled the "-already_crushed" option which does not really work well.
Version 1.7.84 (built with libpng-1.6.16 and zlib-1.2.8)
Cleaned up more Coverity-scan warnings. Fixing those also fixed
CVE-2015-2158.
Version 1.7.83 (built with libpng-1.6.16 and zlib-1.2.8)
Cleaned up some Coverity-scan warnings. Unfortunately one of these
changes introduced the vulnerability reported in CVE-2015-2158.
Version 1.7.82 (built with libpng-1.6.16 and zlib-1.2.8)
Version 1.7.81 (built with libpng-1.6.15 and zlib-1.2.8)
Fixed off-by-one error in calculation of plte_len. Bug reports by
<NAME> and <NAME>.
Version 1.7.80 (built with libpng-1.6.14 and zlib-1.2.8)
Added "-reduce_palette" and "-noreduce_palette" options. Enable
reduce_palette when the "-new" or "-reduce" option is used.
Version 1.7.79 (built with libpng-1.6.14 and zlib-1.2.8)
Fixed bug in -plte_len N option.
Version 1.7.78 (built with libpng-1.6.14 and zlib-1.2.8)
Made "-s" and "-silent" options suppress libpng warnings.
Version 1.7.77 (built with libpng-1.6.13 and zlib-1.2.8)
Updated libpng to version 1.6.13.
Version 1.7.76 (built with libpng-1.6.12 and zlib-1.2.8)
Updated libpng to version 1.6.12.
Version 1.7.75 (built with libpng-1.6.10 and zlib-1.2.8)
Reverted libpng to version 1.6.10 due to a misplaced statement in png.c
Version 1.7.74 (built with libpng-1.6.11 and zlib-1.2.8)
Fixed "-zmem" option (only "-zm" would work since version 1.7.62).
Version 1.7.73 (built with libpng-1.6.10 and zlib-1.2.8)
Restored calls to png_set_crc_action() which had been removed from
version 1.7.72 for some testing and inadvertently not restored.
Changed "fix" internal variable name to "salvage" (still set with "-fix")
Added code to fix/salvage PNG with "bad adaptive filter value" error.
Avoid calculating CRC during compression trials except for the last trial,
when the output is actually written.
Fixed a bug with reducing 16-bit images to 8-bit using "-reduce" option.
Version 1.7.72 (built with libpng-1.6.10 and zlib-1.2.8)
Version 1.7.71 (built with libpng-1.6.9 and zlib-1.2.8)
Built the Windows binaries using -DTOO_FAR=32767; neglected to do this
in versions 1.7.42 through 1.7.70, which caused the Windows binaries
to produce different (usually a few bytes larger) results than Linux.
Thanks to <NAME> for reporting the discrepancy.
Version 1.7.70 (built with libpng-1.6.8 and zlib-1.2.8)
Version 1.7.69 (built with libpng-1.6.6 and zlib-1.2.8)
Updated libpng to version 1.6.6.
Version 1.7.68 (built with libpng-1.6.4 and zlib-1.2.8)
Check for NULL return from malloc().
Undefine CLOCKS_PER_SECOND "1000" found in some version of MinGW.
Replaced most "atoi(argv[++i])" with "pngcrush_get_long" which does
"BUMP_I; strtol(argv[i],ptr,10)" and added pngcrush_check_long macro
to detect malformed or missing parameters (debian bug 716149).
Added global_things_have_changed=1 when reading -bkgd.
The "-bit_depth N" option did not work reliably and has been removed.
Version 1.7.67 (built with libpng-1.5.17 and zlib-1.2.8)
Fixed handling of "-text" and "-ztext" options for text input. They had been
reduced to "-t" and "-z" with an incorrect argument (3 instead of 2) in
version 1.7.62. Bug report and patch from Tsukasa Oi.
Version 1.7.66 (built with libpng-1.5.17 and zlib-1.2.8)
Revised pngcrush_examine_pixels_fn() to fix some incorrect reductions.
Version 1.7.65 (built with libpng-1.5.17 and zlib-1.2.8)
Do not allow any colortype or depth reductions if acTL is present.
Added warnings to explain why any requested reductions were not allowed.
Version 1.7.64 (built with libpng-1.5.17 and zlib-1.2.8)
Version 1.7.63 (built with libpng-1.5.16 and zlib-1.2.8)
Add "int dowildcard=-1;" in an attempt to get wildcard arguments working
in the cross-compiled MinGW executables.
Version 1.7.62 (built with libpng-1.5.16 and zlib-1.2.8)
Remove old filename before renaming, when using the "-ow" option on
any Windows platform, not just CYGWIN (see log entry for pngcrush-1.7.43).
Reverted error with handling single-character options like "-v", introduced
in 1.7.61.
Version 1.7.61 (built with libpng-1.5.16 and zlib-1.2.8)
Check sBIT chunk data to see if reduction to gray or to 8-bit is permitted,
i.e., the RGB sBIT values are equal to each other or the sBIT values are
not greater than 8, respectively.
Do not try to make_opaque if the tRNS chunk is found.
Added warning when ignoring an invalid commandline option.
Improved brute_force handling with specified level, filter, or strategy.
Version 1.7.60 (built with libpng-1.5.16 and zlib-1.2.8)
Revise -reduce so reducing from color-type 6 to grayscale works.
Issue a warning if reducing bit depth or color type would violate various
chunk dependencies, and do not perform the action:
Do not reduce to grayscale if a color bKGD chunk, sBIT or iCCP chunk
is present.
Do not reduce bit depth if bKGD or sBIT chunk is present.
Do not reduce palette length if the hIST chunk is present.
Set "found_iCCP" flag to zero to avoid re-reading a bad iCCP chunk.
Version 1.7.59 (built with libpng-1.5.16 and zlib-1.2.8)
Show the acTL chunk in the chunk list in verbose output.
Fixed several bugs reported by pornel at users.sf.net:
Do not call png_set_benign_errors when PNG_BENIGN_ERRORS_SUPPORTED
is not defined
Renamed PNG_UNUSED() macro PNGCRUSH_UNUSED().
Moved a closing bracket inside the PNGCRUSH_LOCO block.
Moved the declaration of "new_mng" outside a PNGCRUSH_LOCO block.
Put reference to "input_format" inside a PNGCRUSH_LOCO block.
Moved declarations of mng_out and mngname inside a PNGCRUSH_LOCO block.
Version 1.7.58 (built with libpng-1.5.15 and zlib-1.2.7-1)
Do not enable reduce_palette by default for "-reduce", "-new", or "-old".
It still is failing for some files.
Version 1.7.57 (built with libpng-1.5.15 and zlib-1.2.7-1)
Added "-new" option that turns on "-reduce" which will be
the default setting for version 1.8.0 and beyond.
Added "-old" option that turns off "-reduce" which is the
current default setting.
Updated copyright year for zlib-1.2.7-1.
Reverted to libpng-1.5.15 to be able to read old PNG files with TOO FAR
errors. This will of course only work with the embedded libpng.
Version 1.7.56 (built with libpng-1.6.1 and zlib-1.2.7-1)
Only use pngcrush_debug_malloc() and pngcrush_debug_free() if the result
is going to be shown.
Added PNG_PASS_ROWS, PNG_UNUSED, and other macro definitions, when building
with libpng-1.4.x and older libpng versions.
Multiplied rowbytes by 8/bit_depth when using the system library because
we do not call png_read_transform_info(). This prevents a crash when
reading sub-8-bit input files.
Version 1.7.55 (built with libpng-1.6.1 and zlib-1.2.7-1)
Version 1.7.54 (built with libpng-1.6.1rc01 and zlib-1.2.7-1)
Version 1.7.53 (built with libpng-1.6.1rc01 and zlib-1.2.7)
Removed plte_len stuff from the "To do" list because it is done.
Shorten the indexed-PNG tRNS chunk length if it has more entries than the PLTE chunk.
Version 1.7.52 (built with libpng-1.6.1beta06 and zlib-1.2.7)
Added license info for cexcept.h, libpng, and zlib.
Added consideration of "zopfli" compression to the "To do" list.
Fixed a typo that caused a cHRM chunk to be "found" if an iCCP chunk
were present.
Reset best_byte_count before trial loop.
Revise global png_set_keep_unknown_chunks() calls to avoid a libpng16
warning.
Reset "intent" to "specified_intent" before trial loop.
Reset "plte_len" to "specified_plte_len" before trial loop.
Initialize length of each trial to 0x7fffffff so any untried method
is not the "best method".
Version 1.7.51 (built with libpng-1.6.0 and zlib-1.2.7)
Added "-noreduce" option, in preparation for "-reduce" becoming the
default behaviour in version 1.8.0. This turns off lossless bit depth,
color type, palette reduction, and opaque alpha channel removal.
Zero out the high byte of transparent color for color-type 0 and 2,
when reducing from 16 bits to 8.
Undefined a bunch of stuff in pngcrush.h that we do not use, saves about
100 kbytes of executable file size in addition to about 50k saved by
undefining the simplified API.
Fixed double-underscore typo in an #ifdef in png.c
If "-reduce" is on and the background index is larger than the reduced
palette_length+1, reduce it to the palette_length+1.
Increased required_window_size if necessary to account for slightly larger
size of interlaced files due to additional filter bytes and padding.
Version 1.7.50 (built with libpng-1.6.0 and zlib-1.2.7)
Removed completed items from the "To do" list.
Ignore the argument of the "plte_len" argument and just set the
"reduce_palette" flag.
Version 1.7.49 (built with libpng-1.5.14 and zlib-1.2.7)
Use png_set_benign_errors() to allow certain errors in the input file
to be handled as warnings.
Skip PNG_ABORT redefinition when using libpng-1.4.0 and later.
Implemented "-reduce" option to identify and reduce all-gray images,
all-opaque images, unused PLTE entries, and 16-bit images that can be
reduced losslessly to 8-bit.
Version 1.7.48 (built with libpng-1.5.14 and zlib-1.2.7)
Reserved method==0 for examining the pixels during trial 0, if necessary.
Changed blacken_fn() to separate pngcrush_examine_pixels_fn() and
pngcrush_transform_pixels_fn() callback functions. The "examine"
function is only done during trial 0; it sets a flag whether
any fully transparent pixels were found, and pngcrush only runs
pngcrush_transform_pixels_fn() if necessary.
This is in preparation for future versions, which will examine other
conditions such as if the image is opaque or gray or can be losslessly
reduced in bit depth, set flags in trial 0 and accomplish the
transformations in the remaining trials (see the To do list starting
about line 200 in the pngcrush.c source).
Removed "PNGCRUSH_COUNT_COLORS" blocks again.
Version 1.7.47 (built with libpng-1.5.13 and zlib-1.2.7)
Do not do the heuristic trials of the first 10 methods when -brute is
specified, because it did not save time as I hoped.
Fixed a mistake in 1.7.45 and 1.7.46 that caused the output file to
not be written.
Version 1.7.46 (built with libpng-1.5.13 and zlib-1.2.7)
Moved the new level 0 methods to the end of the trial list (methods 137-148)
Version 1.7.45 (built with libpng-1.5.13 and zlib-1.2.7)
Added method 0 (uncompressed). "-m 0" now simply turns on method 0.
Added "-try10" option that has the same effect that "-m 0" previously did,
namely to try only the first ten methods.
Inserted new methods 17 through 21 with zlib level 0.
Do the heuristic trials of the first 10 methods when -brute is specified,
to get quickly to a small solution, so we can bail out of most of the
remaining trials early. Previously these 10 methods were skipped during
a -brute run.
Removed the "-reduce" line from the help screen when PNGCRUSH_COUNT_COLORS
is disabled.
Version 1.7.44 (built with libpng-1.5.14 and zlib-1.2.7)
Version 1.7.43 (built with libpng-1.5.13 and zlib-1.2.7)
Added "remove(inname)" before "rename(outname, inname)" when using the "-ow"
option on CYGWIN/MinGW because "rename()" does not work if the target file
exists.
Use the bundled "zlib.h" when PNGCRUSH_H is defined, otherwise use the
system <zlib.h>.
Version 1.7.42 (built with libpng-1.5.13 and zlib-1.2.7)
Use malloc() and free() instead of png_malloc_default() and
png_free_default(). This will be required to run with libpng-1.7.x.
Revised the PNG_ABORT definition in pngcrush.h to work with libpng-1.7.x.
Revised zutil.h to avoid redefining ptrdiff_t on MinGW/CYGWIN platforms.
Version 1.7.41 (built with libpng-1.5.13 and zlib-1.2.7)
Reverted to version 1.7.38. Versions 1.7.39 and 1.7.40 failed to
open an output file.
Version 1.7.40 (built with libpng-1.5.13 and zlib-1.2.7)
Revised the "To do" list.
Version 1.7.39 (built with libpng-1.5.13 and zlib-1.2.7)
Removed "PNGCRUSH_COUNT_COLORS" blocks which I no longer intend to
implement because that feature is already available in ImageMagick. Kept
"reduce_to_gray" and "it_is_opaque" flags which I do hope to implement
soon.
Changed NULL to pngcrush_default_read_data in png_set_read_fn() calls, to fix
an insignificant error introduced in pngcrush-1.7.14, that caused most
reads to not go through the alternate read function. Also always set this
function, instead of depending on STDIO_SUPPORTED.
Version 1.7.38 (built with libpng-1.5.13 and zlib-1.2.7)
Bail out of a trial if byte count exceeds best byte count so far. This
avoids wasting CPU time on trial compressions of trials that exceed the
best compression found so far.
Added -bail and -nobail options. Use -nobail to get a complete report
of filesizes; otherwise the report just says ">N" for any trial
that exceeds size N where N is the best size achieved so far.
Added -blacken option, to enable changing the color samples of any
fully-transparent pixels to zero in PNG files with color-type 4 or 6,
potentially improving their compressibility. Note that this is an
irreversible lossy change: the underlying colors of all fully transparent
pixels are lost, if they were not already black.
Version 1.7.37 (built with libpng-1.5.12 and zlib-1.2.7)
Reverted pngcrush.c back to 1.7.35 and fixed the bug with PLTE handling.
Version 1.7.36 (built with libpng-1.5.12 and zlib-1.2.7)
Reverted pngcrush.c to version 1.7.34 because pngcrush is failing with
some paletted PNGs.
Separated CFLAGS and CPPFLAGS in the makefile (with "-I" and "-DZ_SOLO"
in CPPFLAGS)
Version 1.7.35 (built with libpng-1.5.12 and zlib-1.2.7)
Removed FOPEN of fpout except for the last trial. The open files caused
"pngcrush -brute -e _ext.png *.png" to fail on the 10th file (about the
1024th compression trial) due to being unable to open the output file.
Version 1.7.34 (built with libpng-1.5.12 and zlib-1.2.7)
Compute and report sum of critical chunk lengths IHDR, PLTE, IDAT, and IEND,
plus the 8-byte PNG signature instead of just the total IDAT data length.
Simplify finding the lengths from the trial compressions, by replacing
the write function with one that simply counts the bytes that would have
been written to a trial PNG, instead of actually writing a PNG, reading it
back, and counting the IDAT bytes.
Removed comments about the system library having to be libpng14 or earlier.
This restriction was fixed in version 1.7.20.
Version 1.7.33 (built with libpng-1.5.12 and zlib-1.2.7)
Ignore all ancillary chunks except during the final trial. This can be
significantly faster when large ancillary chunks such as iCCP and zTXt
are present.
Version 1.7.32 (built with libpng-1.5.12 and zlib-1.2.7)
Fixed bug introduced in 1.7.30: Do not call png_set_check_for_invalid_index()
when nosave != 0 (otherwise pngcrush crashes with the "-n" option).
Version 1.7.31 (built with libpng-1.5.11 and zlib-1.2.7)
Dropped *.tar.bz2 from distribution.
Added a comma that was missing from one of the "usage" strings (error
introduced in version 1.7.29).
Version 1.7.30 (built with libpng-1.5.11 and zlib-1.2.7)
Only run the new (in libpng-1.5.10) test of palette indexes during the
first trial.
Version 1.7.29 (built with libpng-1.5.10 and zlib-1.2.7)
Set "things_have_changed" flag when adding text chunks, so the "-force"
option is no longer necessary when adding text to an already-compressed
file.
Direct usage message and error messages to stderr instead of stdout. If
anyone is still using DOS they may have to change the "if 0" at line
990 to "if 1". If you need to have the messages on standard output
as in the past, use 2>&1 to redirect them.
Added "pngcrush -n -v files.png" to the usage message.
Version 1.7.28 (built with libpng-1.5.10 and zlib-1.2.7)
Write proper copyright year for zlib, depending upon ZLIB_VERNUM
Version 1.7.27 (built with libpng-1.5.10 and zlib-1.2.6)
Increased row_buf malloc to row_bytes+64 instead of row_bytes+16, to
match the size of big_row_buf in pngrutil.c (it is 48 in libpng14, 15, 16,
and 64 in libpng10, 12. Otherwise there is a double-free crash when the
row_buf is destroyed.
Version 1.7.26 (built with libpng-1.5.10 and zlib-1.2.6)
Increased the text_text buffer from 2048 to 10*2048 (<NAME>), and
changed an incorrect test for keyword length "< 180" to "< 80". The
text_text buffer was inadvertently reduced from 20480 to 2048 in
pngcrush-1.7.9.
Added -DZ_SOLO to CFLAGS, needed to compile zlib-1.2.6.
Changed user limits to width and height max 500000, malloc max 2MB,
cache max 500.
Added -nolimits option which sets the user limits to the default
unlimited values.
Version 1.7.25 (built with libpng-1.5.9 and zlib-1.2.5)
Version 1.7.24 (built with libpng-1.5.7 and zlib-1.2.5)
Do not append a slash to the directory name if it already has one.
Version 1.7.23 (built with libpng-1.5.7 and zlib-1.2.5)
Ignore any attempt to use "-ow" with the "-d" or "-e" options, with warning.
Include zlib.h if ZLIB_H is not defined (instead of checking the libpng
version; see entry below for pngcrush-1.7.14), and include string.h
if _STRING_H_ is not defined (because libpng-1.6 does not include string.h)
Define SLASH = backslash on Windows platforms so the "-d" option will work..
Version 1.7.22 (built with libpng-1.5.6 and zlib-1.2.5)
Added "-ow" (overwrite) option. The input file is overwritten and the
output file is just used temporarily and removed after it is copied
over the input file.. If you do not specify an output file, "pngout.png"
is used as the temporary file. Caution: the temporary file must be on
the same filesystem as the input file. Contributed by a group of students
of the University of Paris who were taking the "Understanding of Programs"
course and wished to gain familiarity with an open-source program.
Version 1.7.21 (built with libpng-1.5.6 and zlib-1.2.5)
Defined TOO_FAR=32767 in Makefile (instead of in pngcrush.h)
Version 1.7.20 (built with libpng-1.5.5 and zlib-1.2.5)
Removed the call to png_read_transform_info() when the system libpng
is being used, so it can be built with a system libpng.
Version 1.7.19 (built with libpng-1.5.5 and zlib-1.2.5)
pngcrush-1.7.18 failed to read interlaced PNGs. Reverted the change
from calling png_read_transform_info() to png_read_update_info().
Since png_read_transform_info() is not exported we again cannot build
with the system libpng15.
Version 1.7.18 (built with libpng-1.5.5 and zlib-1.2.5)
This version will work with either a "system" libpng14 or libpng15, or with
the embedded libpng15. The deprecated usage of libpng png_struct members
and unexported functions has been removed.
Fixing "too far back" errors does not work with libpng15.
Revised the format of the time report (all on one line so you can get
a nice compact report by piping the output to "grep coding").
Version 1.7.17 (built with libpng-1.5.5beta08 and zlib-1.2.5)
Changed "#if !defined(PNG_NO_STDIO)" to "#ifdef PNG_STDIO_SUPPORTED"
as recommended in the libpng documentation.
Added PNG_UINT_32_NAME macro and used it to simplify chunk_type integer
definitions.
Version 1.7.16 (built with libpng-1.5.4 and zlib-1.2.5)
Only report best method==0 if pngcrush cannot match the input filesize.
Otherwise, if there is no improvement, report the first matching method.
Version 1.7.15 (built with libpng-1.5.2rc02 and zlib-1.2.5)
Force bit_depth to 1, 2, or 4 when -plte_len is <=2, <=4, or <=16 and
the -bit_depth option is not present, to avoid writing invalid palette
indexes.
Version 1.7.14 (built with libpng-1.5.1beta08 and zlib-1.2.5)
Removed WIN32_WCE support (libpng has dropped it already)
Include zlib.h and define png_memcpy, etc., and revise the
png_get_iCCP() and png_set_iCCP() calls to be able to build
with bundled libpng-1.5.x. Pngcrush cannot be built yet with
a system libpng-1.5.x.
Dropped most of pngcrush.h, that eliminates various parts of libpng.
Version 1.7.13 (built with libpng-1.4.5 and zlib-1.2.5)
Version 1.7.12 (built with libpng-1.4.4beta05 and zlib-1.2.5)
Version 1.7.11 (built with libpng-1.4.2 and zlib-1.2.5)
Version 1.7.10 (built with libpng-1.4.1 and zlib-1.2.3.9)
Added missing "(...)" in png_get_uint_32().
Only compile png_get_uint_32(), etc., when PNG_LIBPNG_VER < 1.2.9
Revised help info for "-zitxt".
Version 1.7.9 (built with libpng-1.4.1 and zlib-1.2.3.9)
Defined TOO_FAR == 32767 in pngcrush.h (instead of in deflate.c)
Revised the "nolib" Makefiles to remove reference to gzio.c and
pnggccrd.c
Imposed user limits of chunk_malloc_max=4000000 and chunk_cache_max=500.
Version 1.7.8 (built with libpng-1.4.0 and zlib-1.2.3.5)
Removed gzio.c
Version 1.7.7 (built with libpng-1.4.0 and zlib-1.2.3.4)
Updated bundled libpng to version 1.4.0.
Check the "-plte_len n" option for out-of-range value of n.
Changed local variable "write" to "z_write" in inffast.c (zlib-1.2.3.4)
to avoid shadowed declaration warning.
Version 1.7.6 (built with libpng-1.4.0rc02 and zlib-1.2.3.2)
Change some "#if defined(X)" to "#ifdef X" according to libpng coding style.
Added some defines to suppress pedantic warnings from libpng-1.2.41beta15
and later. A warning about deprecated access to png_ptr->zstream is
otherwise unavoidable. When building the embedded libpng, a warning
about png_default_error() returning is also otherwise unavoidable.
Write premultiplied alpha if output extension is .ppng and
PNG_READ_PREMULTIPLIED_ALPHA_SUPPORTED is set (needs libpng-1.5.0).
Check the "-m method" option for out-of-range method value.
Version 1.7.5 (built with libpng-1.2.41beta14 and zlib-1.2.3.2)
Version 1.7.4 (built with libpng-1.2.40rc01 and zlib-1.2.3.2)
Use unmodified pngconf.h from libpng-1.2.41beta05 or later.
Version 1.7.3 (built with libpng-1.2.40 and zlib-1.2.3.2)
Print contents of text chunks after IDAT, even when the -n option
is used. This requires a slight modification of pngconf.h,
when libpng-1.2.x is used.
Version 1.7.2 (built with libpng-1.2.40 and zlib-1.2.3.2)
Added check for "verbose" on some printf statements.
Version 1.7.1 (built with libpng-1.2.39 and zlib-1.2.3.2)
Revised some prototypes to eliminate "Shadowed Declaration" warnings.
Moved warning about discarding APNG chunks to the end.
Replaced *.tar.lzma with *.tar.xz in the distribution.
Version 1.7.0 (built with libpng-1.2.38 and zlib-1.2.3.2)
Save (but do not recompress) APNG chunks if the output file has the
".apng" extension and the color_type and bit_depth are not changed.
Version 1.6.20 (built with libpng-1.2.38 and zlib-1.2.3.2)
Changed local variable "write" to "wwrite" in inffast.c (zlib) to avoid
shadowed declaration warning.
Version 1.6.19 (built with libpng-1.2.37 and zlib-1.2.3.2)
Added missing braces that cause an incorrect png_error() to be issued.
Version 1.6.18 (built with libpng-1.2.37 and zlib-1.2.3.2)
Removed extra FCLOSE(fpin) and FCLOSE(fpout) in the first Catch{} block,
since they get removed anyway right after that (<NAME>).
Define PNG_NO_READ|WRITE_cHRM and PNG_NO_READ_|WRITEiCCP in pngcrush.h
and reordered pngcrush.h
Version 1.6.17 (built with libpng-1.2.36 and zlib-1.2.3.2)
Defined TOO_FAR == 32767 in deflate.c (again). The definition
has continually been inadvertently omitted during zlib updates
since pngcrush version 1.6.4.
Revised handling of xcode files so at least we can get printout
of IHDR values with "pngcrush -fix -n -v xcode.png".
Moved ChangeLog.txt back into pngcrush.c so it does not get lost.
Removed single quotes from the ChangeLog.
Version 1.6.16 (built with libpng-1.2.35 and zlib-1.2.3.2)
Added -newtimestamp and -oldtimestamp options and changed
default condition to timestamping the output file with
the current time (i.e., -newtimestamp is default)
If the -oldtimestamp option is used then the output file
has the same timestamp as the input file.
Added CgBI chunk detection.
Version 1.6.15 (built with libpng-1.2.35 and zlib-1.2.3.2)
Fixes some missing typecasts on png_malloc() calls, patch from
an anonymous reporter to the SourceForge bug tracker.
Added -time_stamp option to change time stamping from default
condition.
Version 1.6.14 (built with libpng-1.2.35 and zlib-1.2.3.2)
Avoids CVE-2009-0040.
Version 1.6.12 (built with libpng-1.2.34 and zlib-1.2.3.2)
Version 1.6.11 (built with libpng-1.2.33 and zlib-1.2.3.2)
Eliminated a memory leak in libpng with writing bad tEXt chunks.
Version 1.6.10 (built with libpng-1.2.31 and zlib-1.2.3.2)
Add sTER chunk support.
Version 1.6.9 (built with libpng-1.2.31 and zlib-1.2.3.2)
Updated cexcept.h to version 2.0.1
Add missing curly brackets.
Version 1.6.8 (built with libpng-1.2.29 and zlib-1.2.3.2)
Fixed bug with handling of -z and -zi options.
Version 1.6.7 (built with libpng-1.2.29 and zlib-1.2.3.2)
Moved PNG_UINT_CHNK and some other defines from pngcrush.h to pngcrush.c
Reject invalid color_type or bit_depth.
Version 1.6.6 (built with libpng-1.2.29 and zlib-1.2.3.2)
Added dSIG support. Pngcrush will not rewrite an image containing
a dSIG chunk immediately following the IHDR chunk, unless the
dSIG is explicitly removed with "-rem dSIG" or explicitly kept
with "-keep dSIG". In the latter case the saved dSIG chunks will
become invalid if any changes are made to the datastream.
Fixed bug in writing unknown chunks from the end_info_ptr.
Version 1.6.5 (built with libpng-1.2.29 and zlib-1.2.3.2)
Discontinued adding a new gAMA chunk when writing sRGB chunk.
Version 1.6.4 (built with libpng-1.2.9rc1 and zlib-1.2.3)
Fixed bug in handling of undocumented -trns_a option (<NAME>).
Fixed bug with "nosave" handling of unknown chunks.
Version 1.6.3 (built with libpng-1.2.9beta11 and zlib-1.2.3)
Fixed documentation of iTXt input (<NAME>).
Removed #define PNG_INTERNAL and provided prototypes for some
internal libpng functions that are duplicated in pngcrush.c
Version 1.6.2 (built with libpng-1.2.8 and zlib-1.2.3)
Fixed bug with "PNG_ROWBYTES" usage, introduced in version 1.6.0.
The bug could cause a crash and only affects the "nolib" builds.
Converted C++ style (// ...) comments to C style (/* ... */).
Defined TOO_FAR == 32767 in deflate.c (again). The definition was
omitted from version 1.6.0 when zlib was upgraded to version 1.2.3.
Version 1.6.1 (distributed as 1.6.0, built with libpng-1.2.8 and zlib-1.2.3)
Copied non-exported libpng functions from libpng into pngcrush, to make
pngcrush play more nicely with shared libpng. These are not compiled
when a static library is being built with the bundled libpng and
pngcrush.h is included.
Version 1.6.0-grr (built with libpng-1.2.4 and zlib-1.1.4pc or zlib-1.2.2)
Moved ChangeLog out of pngcrush.c comments and into a separate file.
Filtered pngcrush.c through "indent -kr" and "expand" for readability.
Moved 550 lines of usage/help/copyright/license/version info to separate
function(s) and cleaned up significantly.
Added some comments for ease of navigation and readability.
Stripped out a bunch of ancient-libpng compatibility stuff.
Defined PNG_UINT_* macros (pngcrush.h for now).
Fixed unknown-chunk handling ("-rem alla" and "-rem gifx" now work).
Created modified version of makefile that supports external zlib.
Added support for methods using Z_RLE zlib strategy (zlib 1.2.x only).
Documented -huffman option in usage screen.
Added IDAT statistics to final per-file summary.
Added utime() support to give output files same timestamps as input files.
Version 1.5.10 (built with libpng-1.2.4 and zlib-1.1.4pc)
Fixed bug, introduced in 1.5.9, that caused defaults for method 0 to
be used instead of copying the original image, when the original was
already smallest.
Version 1.5.9 (built with libpng-1.2.4beta3 and zlib-1.1.4pc)
Work around CPU timer wraparound at 2G microseconds.
Upgraded zlib from 1.1.3 to 1.1.4. Pngcrush is believed not to
be vulnerable to the zlib-1.1.3 buffer-overflow bug.
Choose the first instance of smallest IDAT instead of the last,
for faster final recompression, suggested by TSamuel.
Version 1.5.8 (built with libpng-1.2.1)
Added -trns_a option for entering a tRNS array.
Version 1.5.7 (built with libpng-1.2.0)
Added setargv.obj to Makefile.msc to expand wildcards, e.g., *.png
Use constant string "pngcrush" instead of argv[0] when appropriate.
Only check stats for infile==outfile once per input file, or not at all
if "-nofilecheck" option is present or if a directory was created.
Fixed bugs with changing bit_depth of grayscale images.
Version 1.5.6 (built with libpng-1.0.12)
Eliminated extra "Removed the cHNK chunk" messages generated by version
1.5.5 when "-rem alla" or "-rem allb" is used.
All unknown chunks including safe-to-copy chunks are now removed in
response to the "-rem alla" or "-rem allb" options.
Issue a warning if the user tries "-cc" option when it is not supported.
Version 1.5.5 (built with libpng-1.0.12)
Reset reduce_to_gray and it_is_opaque flags prior to processing each
image.
Enable removal of safe-to-copy chunks that are being handled as unknown
e.g., "-rem time".
Version 1.5.4 (built with libpng-1.0.11)
Added 262 to the length of uncompressed data when calculating
required_window_size, to account for zlib/deflate implementation.
Added "-bit_depth n" to the help screen.
Call png_set_packing() when increasing bit_depth to 2 or 4.
Added warning about not overwriting an existing tRNS chunk.
Reduced the memory usage
Write 500K IDAT chunks even when system libpng is being used.
Ignore all-zero cHRM chunks, with a warning.
Version 1.5.3 (built with libpng-1.0.9beta5)
Added "-loco" option (writes MNG files with filter_method 64)
"-dir" and "-ext" options are no longer mutually exclusive, e.g.:
pngcrush -loco -dir Crushed -ext .mng *.png
Version 1.5.2 (built with libpng-1.0.9beta1)
Added "-iccp" option.
Increased the zlib memory level, which improves compression (typically
about 1.3 percent for photos) at the expense of increased memory usage.
Enabled the "-max max_idat_size" option, even when max_idat_size
exceeds the default 1/2 megabyte size.
Added missing "png_ptr" argument to png_error() call
Added "-loco" option, to enable the LOCO color transformation
(R->R-G, G, B->B-G) while writing a MNG with filter_method 64. Undo
the transformation and write the regular PNG filter_method (0) if the
MNG filter_method 64 is detected.
Revised the "-help" output slightly and improved the "-version" output.
The "-already[_crushed]" option is now ignored if the "-force" option
is present or if chunks are being added, deleted, or modified.
Improved "things_have_changed" behavior (now, when set in a particular
file, it is not set for all remaining files)
Version 1.5.1 (built with libpng-1.0.8)
Disabled color counting by default and made it controllable with new
-cc and -no_cc commandline arguments.
Added some #ifdef PNGCRUSH_COUNT_COLORS around code that needs it.
Revised count_colors() attempting to avoid stack corruption that has
been observed on RedHat 6.2
Added the word "irrevocably" to the license and changed "without fee"
to "without payment of any fee".
Version 1.5.0 (built with libpng-1.0.8)
After encountering an image with a bad Photoshop iCCP chunk, pngcrush
1.4.5 through 1.4.8 write sRGB and gAMA=45455 chunks in all
remaining PNG files on the command line. This has been fixed so the
correction is only applied to the particular bad input file.
Version 1.4.8 (built with libpng-1.0.8rc1)
Detect and remove all-opaque alpha channel.
Detect and reduce all-gray truecolor images to grayscale.
Version 1.4.7 (built with libpng-1.0.8rc1)
Restored the "-ext" option that was inadvertently overridden with
a new "-exit" option in version 1.4.6 ("-exit" is used to force an
"exit" instead of a "return" from the main program).
Version 1.4.6 (built with libpng-1.0.8rc1)
Fixed bug in color-counting of noninterlaced images.
Added capability of processing multiple rows at a time (disabled by
default because it turns out to be no faster).
Replaced "return" statements in main() with "exit" statements.
Force exit instead of return with "-exit" argument.
Added the UCITA disclaimers to the help output.
Version 1.4.5 (built with libpng-1.0.7rc2 and cexcept-1.0.0)
Added color-counting and palette-building capability (enable by
defining PNGCRUSH_COUNT_COLORS). In a future version, this will
give pngcrush the ability to reduce RGBA images to indexed-color
or grayscale when fewer than 257 RGBA combinations are present,
and no color is present that requires 16-bit precision. For now,
it only reports the frequencies.
Added "-fix" option, for fixing bad CRCs and other correctable
conditions.
Write sBIT.alpha=1 when adding an opaque alpha channel and sBIT
is present.
Identify the erroneous 2615-byte sRGB monitor profile being written
by Photoshop 5.5, which causes many apps to crash, and replace it with
an sRGB chunk.
Added a check for input and output on different devices before rejecting
the output file as being the same as the input file based on inode.
Added some UCITA language to the disclaimer.
Version 1.4.4 (built with libpng-1.0.6i and cexcept-0.6.3)
Can be built on RISC OS platforms, thanks to <NAME>.
Version 1.4.3 (built with libpng-1.0.6h and cexcept-0.6.3)
Reduced scope of Try/Catch blocks to avoid nesting them, and
removed returns from within the Try blocks, where they are not
allowed.
Removed direct access to the png structure when possible, and isolated
the remaining direct accesses to the png structure into new
png_get_compression_buffer_size(), png_set_compression_buffer_size(),
and png_set_unknown_chunk_location() functions that were installed
in libpng version 1.0.6g.
Version 1.4.2 (built with libpng-1.0.6f and cexcept-0.6.0)
Removes extra IDAT chunks (such as found in some POV-ray PNGs) with
a warning instead of bailing out (this feature requires libpng-1.0.6f
or later, compiled with "#define PNG_ABORT()").
Removed old setjmp interface entirely.
Version 1.4.1 (built with libpng-1.0.6e and cexcept-0.6.0)
Uses cexcept.h for error handling instead of the libpng built-in
setjmp/longjmp mechanism. See http://cexcept.sf.net/
Pngcrush.c will now run when compiled with old versions of libpng back
to version 0.96, although some features will not be available.
Version 1.4.0 (built with libpng-1.0.6 + libpng-1.0.6-patch-a)
Version 1.3.6 (built with libpng-1.0.5v)
RGB to Grayscale conversion is more accurate (15-bit instead of 8-bit)
and now uses only integer arithmetic.
"#ifdefed" out PNG_READ_DITHER
Changed "Compressed" to "Uncompressed" in help for -itxt.
Stifled some compiler warnings
Version 1.3.5 (built with libpng-1.0.5s)
Add test on stat_buf.st_size to verify fpin==fpout, because stat in
MSVC++6.0 standard version returns stat_buf.st_ino=0 for all files.
Revised pngcrush.h to make it easier to control PNG_ZBUF_SIZE and
PNG_NO_FLOATING_POINT_SUPPORTED from a makefile.
Restored ability to enter "replace_gamma" value as a float even when
floating point arithmetic is not enabled.
Enabled removing tEXt, zTXt, or iTXt chunks by chunk type, i.e.,
"-rem tEXt" only removes tEXt chunks, while "-rem text" removes all
three types of text chunk.
Removed definition of TOO_FAR from pngcrush.h
Uses new libpng error handler; if a file has errors, pngcrush now will
continue on and compress the remaining files instead of bailing out.
Version 1.3.4 (built with libpng-1.0.5m)
Do not allow pngcrush to overwrite the input file.
Version 1.3.3 (built with libpng-1.0.5m)
Restored ability to enter gamma as a float even when floating point
arithmetic is not enabled.
Version 1.3.2 (built with libpng-1.0.5k)
Renamed "dirname" to "directory_name" to avoid conflict with "dirname"
that appears in string.h on some platforms.
Fixed "PNG_NO_FLOAING_POINT" typo in pngcrush.h
"#ifdefed" out parts of the help screen for options that are unsupported.
Version 1.3.1 (built with libpng-1.0.5k): Eliminated some spurious warnings
that were being issued by libpng-1.0.5j. Added -itxt, -ztxt, and
-zitxt descriptions to the help screen.
Dropped explicit support for pCAL, hIST, sCAL, sPLT, iCCP, tIME, and
cHRM chunks and handle them as unknown but safe-to-copy instead, using
new png_handle_as_unknown function available in libpng-1.0.5k.
Version 1.3.0 (built with libpng-1.0.5j): Added support for handling
unknown chunks.
pngcrush is now fixed-point only, unless PNG_NO_FLOATING_POINT_SUPPORTED
is undefined in pngcrush.h.
Added support for the iCCP, iTXt, sCAL, and sPLT chunks, which
are now supported by libpng (since libpng-1.0.5j). None of these have
been adequately tested.
"#ifdefed" out more unused code (weighted filters and progressive read;
this saves about 15k in the size of the executable).
Moved the special definitions from pngconf.h into a new pngcrush.h
Disallow 256-byte compression window size when writing, to work around
an apparent zlib bug. Either deflate was producing incorrect results in a
21x21 4-bit image or inflate was decoding it incorrectly; the uncompressed
stream is 252 bytes, which is uncomfortably close to the resulting
256-byte compression window. This workaround can be removed when zlib
is fixed.
The "-m method" can be used any of the 124 methods, without having to
specify the filter, level, and strategy, instead of just the first 10.
Version 1.2.1 (built with libpng-1.0.5f): Fixed -srgb parameter so it
really does take an argument, and so it continues to use "0" if an
integer does not follow the -srgb.
Added "-plte_len n" argument for truncating the PLTE. Be sure not to
truncate it to less than the greatest index actually appearing in IDAT.
Version 1.2.0: Removed registration requirement. Added open source
license. Redefined TOO_FAR=32k in deflate.c.
Changes prior to going "open source":
Version 1.1.8: built with libpng-1.0.5a. Runs OK with pngvcrd.c.
Version 1.1.7: added ability to add tEXt/zTXt chunks. Fixed bug with
closing a file that was not opened when using "pngcrush -n". Fixed
bug with tEXt/zTXt chunks after IDAT not being copied.
Added alpha to the displayed palette table. Rebuilt with libpng-1.0.5.
Version 1.1.6: fixed bug with one file left open after each image is
processed
Version 1.1.5: Shorten or remove tRNS chunks that are all opaque or have
opaque entries at the end. Added timing report.
Version 1.1.4: added ability to restrict brute_force to one or more filter
types, compression levels, or compression strategies.
#endif /* end of changelog */
static int verbose = 0;
static int show_warnings = 0; /* =1 to show warnings even with verbose < 0 */
static int copy_idat = 0; /* = 1 to simply copy the IDAT chunk data */
/* Experimental: define these if you wish, but, good luck.
#define PNGCRUSH_COUNT_COLORS
#define PNGCRUSH_MULTIPLE_ROWS
*/
#define PNGCRUSH_LARGE
#define PNGCRUSH_ROWBYTES(pixel_bits, width) \
((pixel_bits) >= 8 ? \
((png_size_t)(width) * (((png_size_t)(pixel_bits)) >> 3)) : \
(( ((png_size_t)(width) * ((png_size_t)(pixel_bits))) + 7) >> 3) )
/* Suppress libpng pedantic warnings */
#if 0
#define PNG_DEPSTRUCT /* Access to this struct member is deprecated */
#endif
#ifndef PNGCRUSH_TIMERS
# define PNGCRUSH_TIMERS 4
#endif
#if PNGCRUSH_TIMERS > 0
/* TIMER function
===== ======================
set in pngcrush.c:
0 total time
1 total decode
2 total encode
3 total other
set in pngread.c:
4 decode deinterlace
5 decode filter 0 (none)
6 decode filter 1 (sub)
7 decode filter 2 (up)
8 decode filter 3 (avg)
9 decode filter 4 (paeth)
set in pngwutil.c:
10 encode filter setup
*/
#undef _POSIX_C_SOURCE
#define _POSIX_C_SOURCE 199309L /* for clock_gettime */
#include <time.h>
#ifdef CLOCKS_PER_SECOND
# if CLOCKS_PER_SECOND == '"1000"'
# undef CLOCKS_PER_SEC
# endif
#endif
#ifndef CLOCKS_PER_SEC
# define CLOCKS_PER_SEC 1000
#endif
#ifdef __STDC__
# define TIME_T clock_t
#else
# if CLOCKS_PER_SEC <= 100
# define TIME_T long
# else
# define TIME_T float
# endif
#endif
#ifdef __APPLE__
# include <AvailabilityMacros.h>
#endif
/* As in GraphicsMagick */
# if PNGCRUSH_USE_CLOCK_GETTIME == 0
# define PNGCRUSH_USING_CLOCK "clock()"
# elif defined(CLOCK_HIGHRES) /* Solaris */
# define PNGCRUSH_CLOCK_ID CLOCK_HIGHRES
# define PNGCRUSH_USING_CLOCK "clock_gettime(CLOCK_HIGHRES,&t)"
# define PNGCRUSH_USE_CLOCK_GETTIME 1
# elif defined(CLOCK_MONOTONIC_RAW) /* Linux */
# define PNGCRUSH_CLOCK_ID CLOCK_MONOTONIC_RAW
# define PNGCRUSH_USING_CLOCK "clock_gettime(CLOCK_MONOTONIC_RAW,&t)"
# define PNGCRUSH_USE_CLOCK_GETTIME 1
# elif defined(CLOCK_MONOTONIC_PRECISE) /* FreeBSD */
# define PNGCRUSH_CLOCK_ID CLOCK_MONOTONIC_PRECISE
# define PNGCRUSH_USING_CLOCK "clock_gettime(CLOCK_MONOTONIC_PRECISE,&t)"
# define PNGCRUSH_USE_CLOCK_GETTIME 1
# elif defined(CLOCK_MONOTONIC) /* Linux, FreeBSD & macOS Sierra & up */ && \
!(defined(__APPLE__) && MAC_OS_X_VERSION_MIN_REQUIRED < 101200)
# define PNGCRUSH_CLOCK_ID CLOCK_MONOTONIC
# define PNGCRUSH_USING_CLOCK "clock_gettime(CLOCK_MONOTONIC,&t)"
# define PNGCRUSH_USE_CLOCK_GETTIME 1
# else
# define PNGCRUSH_USING_CLOCK "clock()"
# undef PNGCRUSH_USE_CLOCK_GETTIME
# define PNGCRUSH_USE_CLOCK_GETTIME 0
# endif
#else /* PNGCRUSH_TIMERS */
# define PNGCRUSH_USING_CLOCK "clock()"
# define PNGCRUSH_USE_CLOCK_GETTIME 0
#endif
#ifndef LIBPNG_UNIFIED
#include <png.h>
#define PNGCRUSH_TIMER_UINT_API extern unsigned int PNGAPI
#define PNGCRUSH_TIMER_VOID_API extern void PNGAPI
#else
#define PNGCRUSH_TIMER_UINT_API unsigned int
#define PNGCRUSH_TIMER_VOID_API void
#endif
#define PNGCRUSH_TIMER_DECODE 1
#define PNGCRUSH_TIMER_ENCODE 2
#define PNGCRUSH_TIMER_MISC 3
#define PNGCRUSH_TIMER_TOTAL 0
static unsigned int pngcrush_timer_hits[PNGCRUSH_TIMERS];
static unsigned int pngcrush_timer_secs[PNGCRUSH_TIMERS];
static unsigned int pngcrush_timer_nsec[PNGCRUSH_TIMERS];
static unsigned int pngcrush_clock_secs[PNGCRUSH_TIMERS];
static unsigned int pngcrush_clock_nsec[PNGCRUSH_TIMERS];
PNGCRUSH_TIMER_UINT_API
pngcrush_timer_get_seconds(unsigned int n);
PNGCRUSH_TIMER_UINT_API
pngcrush_timer_get_hits(unsigned int n);
PNGCRUSH_TIMER_UINT_API
pngcrush_timer_get_nanoseconds(unsigned int n);
PNGCRUSH_TIMER_VOID_API
pngcrush_timer_reset(unsigned int n);
PNGCRUSH_TIMER_VOID_API
pngcrush_timer_start(unsigned int n);
PNGCRUSH_TIMER_VOID_API
pngcrush_timer_stop(unsigned int n);
#if PNGCRUSH_TIMERS > 0
PNGCRUSH_TIMER_UINT_API
pngcrush_timer_get_hits(unsigned int n)
{
if (n < PNGCRUSH_TIMERS)
{
return pngcrush_timer_hits[n];
}
return 0;
}
PNGCRUSH_TIMER_UINT_API
pngcrush_timer_get_seconds(unsigned int n)
{
if (n < PNGCRUSH_TIMERS)
{
return pngcrush_timer_secs[n];
}
return 0;
}
PNGCRUSH_TIMER_UINT_API
pngcrush_timer_get_nanoseconds(unsigned int n)
{
if (n < PNGCRUSH_TIMERS)
{
return pngcrush_timer_nsec[n];
}
return 0;
}
PNGCRUSH_TIMER_VOID_API
pngcrush_timer_reset(unsigned int n)
{
if (n < PNGCRUSH_TIMERS)
{
pngcrush_timer_secs[n] = 0;
pngcrush_timer_nsec[n] = 0;
pngcrush_timer_hits[n] = 0;
}
}
PNGCRUSH_TIMER_VOID_API
pngcrush_timer_start(unsigned int n)
{
if (verbose >= 0 && n < PNGCRUSH_TIMERS)
{
#if PNGCRUSH_USE_CLOCK_GETTIME
struct timespec t;
clock_gettime(PNGCRUSH_CLOCK_ID, &t);
pngcrush_clock_secs[n] = t.tv_sec;
pngcrush_clock_nsec[n] = t.tv_nsec;
#else
TIME_T t = clock();
pngcrush_clock_secs[n] = t/CLOCKS_PER_SEC;
pngcrush_clock_nsec[n] = (t*1000000000/CLOCKS_PER_SEC) -
pngcrush_clock_secs[n]*1000000000;
#endif
}
}
PNGCRUSH_TIMER_VOID_API
pngcrush_timer_stop(unsigned int n)
{
if (verbose >= 0 && n < PNGCRUSH_TIMERS)
{
unsigned long seconds;
unsigned long nseconds;
unsigned long delta_secs;
unsigned long delta_nsec;
#if PNGCRUSH_USE_CLOCK_GETTIME
struct timespec t;
clock_gettime(PNGCRUSH_CLOCK_ID, &t);
seconds = t.tv_sec;
nseconds = t.tv_nsec;
#else
TIME_T t = clock();
seconds = t/CLOCKS_PER_SEC;
nseconds = (t*1000000000/CLOCKS_PER_SEC) - seconds*1000000000;
#endif
delta_secs = (unsigned int)seconds - pngcrush_clock_secs[n];
if ((unsigned long)nseconds < pngcrush_clock_nsec[n])
{
delta_nsec = 1000000000;
delta_secs--;
}
else
{
delta_nsec = 0;
}
delta_nsec += (unsigned long)nseconds - pngcrush_clock_nsec[n];
pngcrush_timer_secs[n] += delta_secs;
pngcrush_timer_nsec[n] += delta_nsec;
if (pngcrush_timer_nsec[n] >= 1000000000)
{
pngcrush_timer_nsec[n] -= 1000000000;
pngcrush_timer_secs[n]++;
}
pngcrush_clock_secs[n] = (unsigned long)seconds;
pngcrush_clock_nsec[n] = (unsigned long)nseconds;
pngcrush_timer_hits[n]++;
}
}
static unsigned long pngcrush_timer_min_secs[PNGCRUSH_TIMERS];
static unsigned long pngcrush_timer_min_nsec[PNGCRUSH_TIMERS];
#endif /* PNGCRUSH_TIMERS */
#ifdef ZLIB_AMALGAMATED
/* See
https://blog.forrestthewoods.com/
improving-open-source-with-amalgamation-cf293592c5f4#.g9fb2tyhs
*/
#include "zlib_amalg.c"
#define ZLIB_H
#endif /* ZLIB_AMALGAMATED */
#ifdef ZLIB_UNIFIED /* Not working */
#include "zutil.h"
#include "adler32.c"
#undef DO1
#undef DO8
#include "compress.c"
#include "crc32.c"
#include "deflate.c"
#include "infback.c"
#undef PULLBYTE
#include "inffast.c"
#undef CHECK
#undef CODES
#undef DISTS
#undef DONE
#undef LENGTH
#undef LENS
#include "inflate.c"
#undef CHECK
#undef CODES
#undef DISTS
#undef DONE
#undef LENGTH
#undef LENS
#undef PULLBYTE
#include "inftrees.c"
#undef CHECK
#undef CODES
#undef DISTS
#undef DONE
#undef LENGTH
#undef LENS
#include "trees.c"
#include "uncompr.c"
#include "zutil.c"
#endif /* ZLIB_UNIFIED */
#ifdef LIBPNG_UNIFIED
#include "pngcrush.h"
#include "png.c"
#include "pngerror.c"
#include "pngget.c"
#include "pngmem.c"
#include "pngpread.c"
#include "pngread.c"
#include "pngrio.c"
#include "pngrtran.c"
#include "pngrutil.c"
#include "pngset.c"
#include "pngtrans.c"
#include "pngwio.c"
#include "pngwrite.c"
#include "pngwtran.c"
#include "pngwutil.c"
#ifdef PNGCRUSH_USE_ARM_NEON
# include "arm_init.c"
# include "filter_neon_intrinsics.c"
#endif
#ifdef PNGCRUSH_USE_MIPS_NSA
# include "mips_init.c"
# include "filter_msa_intrinsics.c"
#endif
#ifdef PNGCRUSH_USE_INTEL_SSE
# include "intel_init.c"
# include "filter_sse2_intrinsics.c"
#endif
#ifdef PNGCRUSH_USE_POWERPC_VSX
# include "powerpc_init.c"
# include "filter_vsx_intrinsics.c"
#endif
#endif /* LIBPNG_UNIFIED */
#include "png.h"
#ifndef PNGCBAPI /* Needed when building with libpng-1.4.x and earlier */
# define PNGCBAPI PNGAPI
#endif
/* internal libpng macros */
#ifdef PNG_LIBPNG_VER
#define PNGCRUSH_LIBPNG_VER PNG_LIBPNG_VER
#else
/*
* This must agree with PNG_LIBPNG_VER; you have to define it manually
* here if you are using libpng-1.0.6h or earlier
*/
#define PNGCRUSH_LIBPNG_VER 10007
#endif
#define PNGCRUSH_UNUSED(param) (void)param;
#define pngcrush_get_uint_31 png_get_uint_31
#define pngcrush_get_uint_32 png_get_uint_32
#define pngcrush_save_uint_32 png_save_uint_32
#undef PNG_ABORT
#if (PNGCRUSH_LIBPNG_VER < 10400)
/* This allows png_default_error() to return, when it is called after our
* own exception handling, which only returns after "Too many IDAT's",
* or anything else that we might want to handle as a warning instead of
* an error. Doesn't work in libpng-1.4.0 and later; there we use
* png_benign_error() instead.
*/
# define PNG_ABORT() (void)0
#elif (PNGCRUSH_LIBPNG_VER < 10700)
# define PNG_ABORT() abort()
#else
# define PNG_ABORT abort();
#endif
#if (PNGCRUSH_LIBPNG_VER < 10500)
/* Two macros to return the first row and first column of the original,
* full, image which appears in a given pass. 'pass' is in the range 0
* to 6 and the result is in the range 0 to 7.
*/
#define PNG_PASS_START_ROW(pass) (((1&~(pass))<<(3-((pass)>>1)))&7)
#define PNG_PASS_START_COL(pass) (((1& (pass))<<(3-(((pass)+1)>>1)))&7)
/* A macro to return the offset between pixels in the output row for a pair of
* pixels in the input - effectively the inverse of the 'COL_SHIFT' macro that
* follows. Note that ROW_OFFSET is the offset from one row to the next whereas
* COL_OFFSET is from one column to the next, within a row.
*/
#define PNG_PASS_ROW_OFFSET(pass) ((pass)>2?(8>>(((pass)-1)>>1)):8)
#define PNG_PASS_COL_OFFSET(pass) (1<<((7-(pass))>>1))
/* Two macros to help evaluate the number of rows or columns in each
* pass. This is expressed as a shift - effectively log2 of the number or
* rows or columns in each 8x8 tile of the original image.
*/
#define PNG_PASS_ROW_SHIFT(pass) ((pass)>2?(8-(pass))>>1:3)
#define PNG_PASS_COL_SHIFT(pass) ((pass)>1?(7-(pass))>>1:3)
/* Hence two macros to determine the number of rows or columns in a given
* pass of an image given its height or width. In fact these macros may
* return non-zero even though the sub-image is empty, because the other
* dimension may be empty for a small image.
*/
#define PNG_PASS_ROWS(height, pass) (((height)+(((1<<PNG_PASS_ROW_SHIFT(pass))\
-1)-PNG_PASS_START_ROW(pass)))>>PNG_PASS_ROW_SHIFT(pass))
#define PNG_PASS_COLS(width, pass) (((width)+(((1<<PNG_PASS_COL_SHIFT(pass))\
-1)-PNG_PASS_START_COL(pass)))>>PNG_PASS_COL_SHIFT(pass))
#endif /* PNGCRUSH_LIBPNG_VER < 10500 */
#if PNGCRUSH_LIBPNG_VER >= 10500
#if !defined(ZLIB_AMALGAMATED) && !defined(ZLIB_UNIFIED)
/* "#include <zlib.h>" is not provided by libpng15 */
#ifdef PNGCRUSH_H
/* Use the bundled zlib */
# include "zlib.h"
#else
/* Use the system zlib */
# include <zlib.h>
#endif
#endif /* ZLIB_AMALGAMATED || ZLIB_UNIFIED */
/* Not provided by libpng16 */
# include <string.h>
/* The following became unavailable in libpng16 (and were
* deprecated in libpng14 and 15)
*/
# ifdef _WINDOWS_ /* Favor Windows over C runtime fns */
# define png_memcmp memcmp
# define png_memcpy CopyMemory
# define png_memset memset
# else
# define png_memcmp memcmp /* SJT: added */
# define png_memcpy memcpy
# define png_memset memset
# endif
#endif /* PNGCRUSH_LIBPNG_VER >= 10500 */
#if PNGCRUSH_LIBPNG_VER < 10800 || defined(PNGCRUSH_H)
/* Changed in version 0.99 */
#if PNGCRUSH_LIBPNG_VER < 99
# undef PNG_CONST
# ifndef PNG_NO_CONST
# define PNG_CONST const
# else
# define PNG_CONST
# endif
#endif
#ifndef LIBPNG_UNIFIED
#define PNG_IDAT const png_byte png_IDAT[5] = { 73, 68, 65, 84, '\0'}
#define PNG_IHDR const png_byte png_IHDR[5] = { 73, 72, 68, 82, '\0'}
#define PNG_acTL const png_byte png_acTL[5] = { 97, 99, 84, 76, '\0'}
#define PNG_dSIG const png_byte png_dSIG[5] = {100, 83, 73, 71, '\0'}
#define PNG_fcTL const png_byte png_fcTL[5] = {102, 99, 84, 76, '\0'}
#define PNG_fdAT const png_byte png_fdAT[5] = {102, 100, 65, 84, '\0'}
#define PNG_iCCP const png_byte png_iCCP[5] = {105, 67, 67, 80, '\0'}
#define PNG_IEND const png_byte png_IEND[5] = { 73, 69, 78, 68, '\0'}
#endif
/* GRR 20050220: added these, which apparently aren't defined anywhere else */
/* GRP 20110714: define PNG_UINT_32_NAME macro and used that instead */
#define PNG_UINT_32_NAME(a,b,c,d) \
((png_uint_32) ((a) & 0xff) << 24 | \
((png_uint_32) (b) << 16) | \
((png_uint_32) (c) << 8) | \
((png_uint_32) (d) ))
#ifndef PNG_UINT_IHDR
# define PNG_UINT_IHDR PNG_UINT_32_NAME(73, 72, 68, 82)
#endif
#ifndef PNG_UINT_IDAT
# define PNG_UINT_IDAT PNG_UINT_32_NAME(73, 68, 65, 84)
#endif
#ifndef PNG_UINT_IEND
# define PNG_UINT_IEND PNG_UINT_32_NAME(73, 69, 78, 68)
#endif
#ifndef PNG_UINT_PLTE
# define PNG_UINT_PLTE PNG_UINT_32_NAME(80, 76, 84, 69)
#endif
#ifndef PNG_UINT_bKGD
# define PNG_UINT_bKGD PNG_UINT_32_NAME(98, 75, 71, 68)
#endif
/* glennrp added CgBI at pngcrush-1.6.16 */
#ifndef PNG_UINT_CgBI
# define PNG_UINT_CgBI PNG_UINT_32_NAME(67,103, 66, 73)
#endif
/* glennrp added acTL, fcTL, and fdAT at pngcrush-1.7.0 */
# define PNG_UINT_acTL PNG_UINT_32_NAME(97, 99, 84, 76)
# define PNG_UINT_fcTL PNG_UINT_32_NAME(102, 99, 84, 76)
# define PNG_UINT_fdAT PNG_UINT_32_NAME(102,100, 65, 84)
#ifndef PNG_UINT_cHRM
# define PNG_UINT_cHRM PNG_UINT_32_NAME(99, 72, 82, 77)
#endif
#ifndef PNG_UINT_dSIG
# define PNG_UINT_dSIG PNG_UINT_32_NAME(100, 83, 73, 71)
#endif
#ifndef PNG_UINT_gAMA
# define PNG_UINT_gAMA PNG_UINT_32_NAME(103, 65, 77, 65)
#endif
#ifndef PNG_UINT_hIST
# define PNG_UINT_hIST PNG_UINT_32_NAME(104, 73, 83, 84)
#endif
#ifndef PNG_UINT_iCCP
# define PNG_UINT_iCCP PNG_UINT_32_NAME(105, 67, 67, 80)
#endif
#ifndef PNG_UINT_iTXt
# define PNG_UINT_iTXt PNG_UINT_32_NAME(105, 84, 88, 116)
#endif
#ifndef PNG_UINT_oFFs
# define PNG_UINT_oFFs PNG_UINT_32_NAME(111, 70, 70, 115)
#endif
#ifndef PNG_UINT_pCAL
# define PNG_UINT_pCAL PNG_UINT_32_NAME(112, 67, 65, 76)
#endif
#ifndef PNG_UINT_pHYs
# define PNG_UINT_pHYs PNG_UINT_32_NAME(112, 72, 89, 115)
#endif
#ifndef PNG_UINT_sBIT
# define PNG_UINT_sBIT PNG_UINT_32_NAME(115, 66, 73, 84)
#endif
#ifndef PNG_UINT_sCAL
# define PNG_UINT_sCAL PNG_UINT_32_NAME(115, 67, 65, 76)
#endif
#ifndef PNG_UINT_sPLT
# define PNG_UINT_sPLT PNG_UINT_32_NAME(115, 80, 76, 84)
#endif
#ifndef PNG_UINT_sRGB
# define PNG_UINT_sRGB PNG_UINT_32_NAME(115, 82, 71, 66)
#endif
/* glennrp added sTER at pngcrush-1.6.10 */
#ifndef PNG_UINT_sTER
# define PNG_UINT_sTER PNG_UINT_32_NAME(115, 84, 69, 82)
#endif
#ifndef PNG_UINT_tEXt
# define PNG_UINT_tEXt PNG_UINT_32_NAME(116, 69, 88, 116)
#endif
#ifndef PNG_UINT_tIME
# define PNG_UINT_tIME PNG_UINT_32_NAME(116, 73, 77, 69)
#endif
#ifndef PNG_UINT_tRNS
# define PNG_UINT_tRNS PNG_UINT_32_NAME(116, 82, 78, 83)
#endif
#ifndef PNG_UINT_zTXt
# define PNG_UINT_zTXt PNG_UINT_32_NAME(122, 84, 88, 116)
#endif
#ifndef LIBPNG_UNIFIED
#define PNG_FLAG_CRC_ANCILLARY_USE 0x0100
#define PNG_FLAG_CRC_ANCILLARY_NOWARN 0x0200
#define PNG_FLAG_CRC_CRITICAL_USE 0x0400
#define PNG_FLAG_CRC_CRITICAL_IGNORE 0x0800
#define PNG_FLAG_CRC_ANCILLARY_MASK (PNG_FLAG_CRC_ANCILLARY_USE | \
PNG_FLAG_CRC_ANCILLARY_NOWARN)
#define PNG_PACK 0x0004
#define PNG_DITHER 0x0040
#define PNG_BACKGROUND 0x0080
#define PNG_16_TO_8 0x0400
#define PNG_RGBA 0x0800
#define PNG_EXPAND 0x1000
#define PNG_GAMMA 0x2000
#define PNG_GRAY_TO_RGB 0x4000
#define PNG_FILLER 0x8000L
#define PNG_USER_TRANSFORM 0x100000L
#define PNG_RGB_TO_GRAY 0x600000L /* two bits, RGB_TO_GRAY_ERR|WARN */
#endif /* LIBPNG_UNIFIED */
/*
* We don't need some of the extra libpng transformations
* so they are ifdef'ed out in pngcrush.h, which is included by
* pngcrush's local copy of libpng's pngconf.h which is included
* by png.h
*
*/
/* Defined so I can write to a file on gui/windowing platforms */
#if 0 /* Change this to "#if 1" if you need to. */
# define STDERR stdout /* for DOS */
#else
# define STDERR stderr
#endif
#ifdef PNG_MNG_FEATURES_SUPPORTED
# define PNGCRUSH_LOCO
#endif
#ifdef PNGCRUSH_H
int png_ignore_crc = 0;
#else
png_uint_32 pngcrush_crc;
#endif
#ifndef PNG_UINT_31_MAX
#define PNG_UINT_31_MAX ((png_uint_32)0x7fffffffL)
#endif
/* These macros were renamed in libpng-1.2.6 */
#ifndef PNG_HANDLE_CHUNK_ALWAYS
#define PNG_HANDLE_CHUNK_ALWAYS HANDLE_CHUNK_ALWAYS
#define PNG_HANDLE_CHUNK_NEVER HANDLE_CHUNK_NEVER
#define PNG_HANDLE_CHUNK_IF_SAFE HANDLE_CHUNK_IF_SAFE
#endif
#if defined(__DJGPP__) && ((__DJGPP__ == 2) && (__DJGPP_MINOR__ == 0))
# include <libc/dosio.h> /* for _USE_LFN, djgpp 2.0 only */
#endif
#if ( defined(_Windows) || defined(_WINDOWS) || defined(WIN32) || \
defined(_WIN32) || defined(__WIN32__) || defined(__CYGWIN__) || \
defined(__DJGPP__) )
# define SLASH "\\"
# define DOT "."
#else
# ifdef __riscos
# define SLASH "."
# define DOT "/"
# else
# define SLASH "/"
# define DOT "."
# endif
#endif
#define BACK_SLASH "\\"
#define FWD_SLASH "/"
#ifndef GAS_VERSION
# define GAS_VERSION "2.9.5(?)" /* used only in help/usage screen */
#endif
#if !defined(__TURBOC__) && !defined(_MSC_VER) && !defined(_MBCS) && \
!defined(__riscos)
# include <unistd.h>
#endif
#ifndef __riscos
# include <sys/types.h>
# include <sys/stat.h>
# ifndef _MSC_VER
# include <utime.h>
# else
# include <sys/utime.h>
# endif
#endif
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <assert.h>
#include <errno.h>
#if defined(_MBCS) || defined(WIN32) || defined(__WIN32__)
# include <direct.h>
#endif
#define DEFAULT_MODE 0
#define DIRECTORY_MODE 1
#define EXTENSION_MODE 2
#define DIREX_MODE 3
#define OVERWRITE_MODE 4
#define FOPEN(file, how) fopen(file, how)
#define FCLOSE(file) {fclose(file); file=NULL;--number_of_open_files;};
#define P0 if(last_trial && verbose > 0)printf
#define P1 if(verbose > 1)printf
#define P2 if(verbose > 2)printf
#define STRNGIFY_STAGE1(x) #x
#define STRNGIFY(x) STRNGIFY_STAGE1(x)
#define STR_BUF_SIZE 2048
#define MAX_IDAT_SIZE 524288L
#define MAX_METHODS 177
#define MAX_METHODSP1 (MAX_METHODS+1)
#define DEFAULT_METHODS 10
#define FAKE_PAUSE_STRING "P"
#ifdef Z_RLE
# define NUM_STRATEGIES 4
#else
# define NUM_STRATEGIES 3
#endif
#ifdef __TURBOC__
# include <mem.h>
#endif
struct options_help
{
int verbosity; /* if verbose >= this value, then print line */
const char *textline; /* static string with newline chopped off */
};
#ifdef MINGW32
/* enable commandline wildcard interpretation (doesn't necessarily work!) */
int _dowildcard = 1;
#endif
/* Input and output filenames */
static PNG_CONST char *progname;
static PNG_CONST char *inname = "pngtest" DOT "png";
static PNG_CONST char *outname = "pngout" DOT "png";
#ifdef PNGCRUSH_LOCO
static PNG_CONST char *mngname = "mngout" DOT "mng";
#endif
static PNG_CONST char *directory_name = "pngcrush" DOT "bak";
static PNG_CONST char *extension = "_C" DOT "png";
static png_uint_32 width, height;
static png_uint_32 measured_idat_length;
static int found_bKGD = 0;
static int found_color_bKGD = 0;
#ifdef PNG_cHRM_SUPPORTED
static int found_cHRM = 0;
#endif
static int found_gAMA = 0;
static int found_hIST = 0;
static int found_iCCP = 0;
static int found_IDAT = 0;
static int found_sBIT = 0;
static int found_sBIT_max = 0;
static int found_sBIT_different_RGB_bits = 0;
static int found_sRGB = 0;
static int found_tRNS = 0;
static int premultiply = 0;
static int printed_version_info = 0;
static int interlace_method = 0;
#if (PNGCRUSH_LIBPNG_VER < 10400)
png_size_t max_bytes;
#else
png_alloc_size_t max_bytes;
#endif
/* 0: not premultipled
* 1: premultiplied input (input has .ppng suffix)
* 2: premultiplied output (output has .ppng suffix)
* 3: premultiplied input and output (both have .ppng suffix)
*
* .png -> .ppng is OK, do premultiplication.
* .ppng -> .ppng is OK, simply copy data.
* .ppng -> .ppng is not OK because colors are irretrievably lost.
* .ppng -> no output (pngcrush -n) is OK.
*
* To do: Implement this stuff!
*/
static int found_CgBI = 0;
static int found_any_chunk = 0;
static int save_apng_chunks = 0; /* 0: output not .apng 1: .apng 2: rejected */
static int found_acTL_chunk = 0; /* 0: not found, 1: found, 2: rejected */
static int image_is_immutable = 0;
static int pngcrush_must_exit = 0;
static int all_chunks_are_safe = 0;
static int number_of_open_files;
static int do_pplt = 0;
#ifdef PNGCRUSH_MULTIPLE_ROWS
static png_uint_32 max_rows_at_a_time = 1;
static png_uint_32 rows_at_a_time;
#endif
char pplt_string[STR_BUF_SIZE];
char *ip, *op, *dot;
char in_string[STR_BUF_SIZE];
char prog_string[STR_BUF_SIZE];
char out_string[STR_BUF_SIZE];
char in_extension[STR_BUF_SIZE];
static int text_inputs = 0;
int text_where[10]; /* 0: no text; 1: before PLTE; 2: after PLTE */
int text_compression[10]; /* -1: uncompressed tEXt; 0: compressed zTXt
1: uncompressed iTXt; 2: compressed iTXt */
char text_text[11*STR_BUF_SIZE+1]; /* It would be nice to png_malloc this but we
don't have a png_ptr yet when we need it. */
char text_keyword[11*80+1];
/* PNG_iTXt_SUPPORTED */
char text_lang[881];
char text_lang_key[881];
/* PNG_iCCP_SUPPORTED */
int iccp_length = 0;
char *iccp_text;
char *iccp_file;
char iccp_name[80];
int best;
char buffer[256];
/* Set up the "cexcept" Try/Throw/Catch exception handler. */
#include "cexcept.h"
define_exception_type(const char *);
extern struct exception_context the_exception_context[1];
struct exception_context the_exception_context[1];
png_const_charp msg;
static png_uint_32 input_length;
static png_uint_32 total_input_length = 0;
static png_uint_32 total_output_length = 0;
static int pngcrush_mode = DEFAULT_MODE;
static int resolution = 0;
static int remove_chunks = 0;
static int output_color_type;
static int output_bit_depth;
static int force_output_color_type = 8;
static int force_output_bit_depth = 0;
static int input_color_type;
static int input_bit_depth;
static int trial;
static int last_trial = 0;
static png_uint_32 pngcrush_write_byte_count;
static png_uint_32 pngcrush_best_byte_count=0xffffffff;
static int salvage = 0;
static int bail = 0; /* if 0, bail out of trials early */
static int check_crc = 0; /* if 0, skip CRC and ADLER32 checks */
/* otherwise check both */
static int force = 1; /* if 1, force output even if IDAT is larger */
static unsigned int benchmark_iterations = 0;
static int blacken = 0; /* if 0, or 2 after the first trial,
do not blacken color samples */
/* Delete these in pngcrush-1.8.0 */
#if 0
static int make_gray = 0; /* if 0, 2, or 3 after the first trial,
do not change color_type to gray */
static int make_opaque = 0; /* if 0, 2, or 3 after the first trial,
do not change color_type to opaque */
static int make_8_bit = 0; /* if 0, 2, or 3 after the first trial,
do not reduce bit_depth from 16 */
static int reduce_palette = 0;
#endif
/* Activate these in pngcrush-1.8.0 */
#if 1
static int noreduce = 1; /* if 0, "-reduce" was specified */
static int make_gray = 1; /* if 0, 2, or 3 after the first trial,
do not change color_type to gray */
static int make_opaque = 1; /* if 0, 2, or 3 after the first trial,
do not change color_type to opaque */
static int make_8_bit = 1; /* if 0, 2, or 3 after the first trial,
do not reduce bit_depth from 16 */
static int reduce_palette = 1;
#endif
static int compression_window;
static int default_compression_window = 15;
static int force_compression_window = 0;
static int compression_mem_level = 9;
static int final_method = 0;
static int brute_force = 0;
static int brute_force_level = 0;
static int brute_force_filter = 0;
static int brute_force_strategy = 0;
static int brute_force_levels[10] = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 };
static int brute_force_filters[6] = { 1, 1, 1, 1, 1, 1 };
#ifdef Z_RLE
static int brute_force_strategies[NUM_STRATEGIES] = { 1, 1, 1, 1 };
#else
static int brute_force_strategies[NUM_STRATEGIES] = { 1, 1, 1 };
#endif
static int speed = 0;
static int method = 10;
static int pauses = 0;
static int nosave = 0; /* 0: save; 1: do not save */
static int overwrite = 0; /* 1: overwrite the input file instead of
creating a new output file */
static int nofilecheck = 0;
static int no_limits = 0;
static int new_mng = 0;
static png_bytep row_buf;
#ifdef PNGCRUSH_MULTIPLE_ROWS
static png_bytepp row_pointers;
#endif
static int z_strategy;
static int best_of_three;
static int methods_specified = 0;
static int specified_intent = -1;
static int intent = -1;
static int ster_mode = -1;
static int new_time_stamp = 1;
static int plte_len = -1;
#ifdef PNG_FIXED_POINT_SUPPORTED
static int specified_gamma = 0;
static int image_specified_gamma = 0;
static int force_specified_gamma = 0;
#else
static double specified_gamma = 0.0;
static double image_specified_gamma = 0;
static double force_specified_gamma = 0.0;
#endif
static int double_gamma = 0;
static int names;
static int first_name;
static int have_trns = 0;
static png_uint_16 trns_index = 0;
static png_uint_16 trns_red = 0;
static png_uint_16 trns_green = 0;
static png_uint_16 trns_blue = 0;
static png_uint_16 trns_gray = 0;
static png_byte trns_array[256];
static png_byte trans_in[256];
static png_uint_16 num_trans_in;
#if defined(PNG_READ_tRNS_SUPPORTED) && defined(PNG_WRITE_tRNS_SUPPORTED)
png_bytep trans;
int num_trans;
png_color_16p trans_values;
#endif
static int have_bkgd = 0;
static png_uint_16 bkgd_red = 0;
static png_uint_16 bkgd_green = 0;
static png_uint_16 bkgd_blue = 0;
static png_byte bkgd_index = 0;
static png_colorp palette;
static int num_palette;
#ifdef REORDER_PALETTE
static png_byte palette_reorder[256];
#endif
static png_structp read_ptr, write_ptr, mng_ptr;
static png_infop read_info_ptr, write_info_ptr;
static png_infop end_info_ptr;
static png_infop write_end_info_ptr;
static FILE *fpin, *fpout;
png_uint_32 measure_idats(FILE * fp);
#ifdef PNGCRUSH_LOCO
static FILE *mng_out;
static int do_loco = 0;
static int input_format = 0; /* 0: PNG 1: MNG */
static int output_format = 0;
#endif
static int do_color_count;
png_uint_32 pngcrush_measure_idat(png_structp png_ptr);
static png_uint_32 idat_length[MAX_METHODSP1];
static int filter_type, zlib_level;
static png_bytep png_row_filters = NULL;
#if PNGCRUSH_TIMERS > 0
unsigned int pc_timer;
static float t_filter[PNGCRUSH_TIMERS] = {0};
static png_uint_32 filter_count[PNGCRUSH_TIMERS] = {0};
png_uint_32 t_sec;
png_uint_32 t_nsec;
#endif
static png_uint_32 max_idat_size = MAX_IDAT_SIZE; /* increases the IDAT size */
#if 0 /* disabled */
static png_uint_32 crushed_idat_size = 0x3ffffffL;
static int already_crushed = 0;
#endif
int ia;
#if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
static /* const */ png_byte chunks_to_ignore[] = {
98, 75, 71 , 68, '\0', /* bKGD */
99, 72, 82, 77, '\0', /* cHRM */
103, 65, 77, 65, '\0', /* gAMA */
104, 73, 83, 84, '\0', /* hIST */
105, 67, 67, 80, '\0', /* iCCP */
105, 84, 88, 116, '\0', /* iTXt */
111, 70, 70, 115, '\0', /* oFFs */
112, 67, 65, 76, '\0', /* pCAL */
112, 72, 89, 115, '\0', /* pHYs */
115, 66, 73, 84, '\0', /* sBIT */
115, 67, 65, 76, '\0', /* sCAL */
115, 80, 76, 84, '\0', /* sPLT */
115, 82, 71, 66, '\0', /* sRGB */
115, 84, 69, 82, '\0', /* sTER */
116, 69, 88, 116, '\0', /* tEXt */
116, 73, 77, 69, '\0', /* tIME */
116, 82, 78, 83, '\0', /* tRNS */
122, 84, 88, 116, '\0' /* zTXt */
};
#endif
/* Prototypes */
static void pngcrush_cexcept_error(png_structp png_ptr,
png_const_charp message);
static void pngcrush_warning(png_structp png_ptr,
png_const_charp message);
void PNGCBAPI pngcrush_default_read_data(png_structp png_ptr, png_bytep data,
png_size_t length);
#ifdef PNGCRUSH_H
void png_read_transform_info(png_structp png_ptr, png_infop info_ptr);
#endif
void PNGCBAPI pngcrush_default_write_data(png_structp png_ptr, png_bytep data,
png_size_t length);
void pngcrush_write_png(png_structp write_pointer, png_bytep data,
png_size_t length);
#ifdef PNG_USER_MEM_SUPPORTED
png_voidp pngcrush_debug_malloc(png_structp png_ptr, png_uint_32 size);
void pngcrush_debug_free(png_structp png_ptr, png_voidp ptr);
#endif
void pngcrush_pause(void);
#ifdef __riscos
static int fileexists(const char *name)
static int filesize(const char *name)
static int mkdir(const char *name, int ignored)
static void setfiletype(const char *name)
#endif
int keep_unknown_chunk(png_const_charp name, char *argv[]);
int keep_chunk(png_const_charp name, char *argv[]);
void show_result(void);
png_uint_32 measure_idats(FILE * fp);
png_uint_32 pngcrush_measure_idat(png_structp png_ptr);
void print_version_info(void);
void print_usage(int retval);
#ifdef PNGCRUSH_H
/* Use unexported functions in the embedded libpng */
# define pngcrush_reset_crc(png_ptr) png_reset_crc(png_ptr)
# define pngcrush_calculate_crc(png_ptr, ptr, length) \
png_calculate_crc(png_ptr, ptr, length)
# define pngcrush_crc_read(png_ptr, buf, length) \
png_crc_read(png_ptr, buf, length)
# define pngcrush_crc_error(png_ptr) png_crc_error(png_ptr)
# define pngcrush_crc_finish(png_ptr, skip) png_crc_finish(png_ptr, skip)
#else
/*
* ============================================================
* We aren't using the bundled libpng functions, so we must
* reproduce the libpng routines that aren't exported by libpng
* ============================================================
*/
# if (PNGCRUSH_LIBPNG_VER >= 10209)
# ifndef PNG_READ_BIG_ENDIAN_SUPPORTED
# undef pngcrush_get_uint_32
png_uint_32 pngcrush_get_uint_32(png_bytep buf);
/* Grab an unsigned 32-bit integer from a buffer in big-endian format. */
png_uint_32 /* PRIVATE */
pngcrush_get_uint_32(png_bytep buf)
{
png_uint_32 i = ((png_uint_32) (*buf & 0xff) << 24) +
(*(buf + 1) << 16) + (*(buf + 2) << 8) + (*(buf + 3)) ;
return (i);
}
# else /*! BIG_ENDIAN */
# define pngcrush_get_uint_32(buf) ( *((png_uint_32p) (buf)))
# endif /* BIG_ENDIAN */
# undef pngcrush_get_uint_31
png_uint_32 pngcrush_get_uint_31(png_structp png_ptr, png_bytep buf);
png_uint_32 /* PRIVATE */
pngcrush_get_uint_31(png_structp png_ptr, png_bytep buf)
{
png_uint_32 i = pngcrush_get_uint_32(buf);
if (i > PNG_UINT_31_MAX)
{
i=0;
png_error(png_ptr, "PNG unsigned integer out of range.\n");
}
return (i);
}
# undef pngcrush_save_uint_32
void pngcrush_save_uint_32(png_bytep buf, png_uint_32 i);
void /* PRIVATE */
pngcrush_save_uint_32(png_bytep buf, png_uint_32 i)
{
buf[0] = (png_byte)((i >> 24) & 0xff);
buf[1] = (png_byte)((i >> 16) & 0xff);
buf[2] = (png_byte)((i >> 8) & 0xff);
buf[3] = (png_byte)(i & 0xff);
}
# endif /* PNGCRUSH_LIBPNG_VER < 10209 */
/*
* Reset the CRC variable to 32 bits of 1's. Care must be taken
* in case CRC is > 32 bits to leave the top bits 0.
*/
void PNGAPI
pngcrush_reset_crc(png_structp png_ptr)
{
pngcrush_crc = crc32(0, Z_NULL, 0);
}
/*
* Calculate the CRC over a section of data. We can only pass as
* much data to this routine as the largest single buffer size. We
* also check that this data will actually be used before going to the
* trouble of calculating it.
*/
void PNGAPI
pngcrush_calculate_crc(png_structp png_ptr, png_bytep ptr, png_size_t length)
{
pngcrush_crc = crc32(pngcrush_crc, ptr, (uInt)length);
}
/* Read data, and (optionally) run it through the CRC. */
void PNGAPI
pngcrush_crc_read(png_structp png_ptr, png_bytep buf, png_size_t length)
{
pngcrush_default_read_data(png_ptr, buf, length);
pngcrush_calculate_crc(png_ptr, buf, length);
}
/* Compare the CRC stored in the PNG file with that calculated by libpng from
* the data it has read thus far.
*/
int PNGAPI
pngcrush_crc_error(png_structp png_ptr)
{
png_byte crc_bytes[4];
png_uint_32 crc;
pngcrush_default_read_data(png_ptr, crc_bytes, 4);
crc = pngcrush_get_uint_32(crc_bytes);
return ((int)(crc != pngcrush_crc));
}
/*
* Optionally skip data and then check the CRC. Depending on whether we
* are reading a ancillary or critical chunk, and how the program has set
* things up, we may calculate the CRC on the data and print a message.
* Returns '1' if there was a CRC error, '0' otherwise.
*/
int PNGAPI
pngcrush_crc_finish(png_structp png_ptr, png_uint_32 skip)
{
png_size_t i;
png_byte bytes[1024];
png_size_t istop = 1024;
for (i = (png_size_t)skip; i > istop; i -= istop)
{
pngcrush_crc_read(png_ptr, bytes, (png_size_t)1024);
}
if (i)
{
pngcrush_crc_read(png_ptr, bytes, i);
}
if (pngcrush_crc_error(png_ptr))
{
{
png_chunk_error(png_ptr, "CRC error");
}
return (1);
}
return (0);
}
#endif /* PNGCRUSH_H */
#ifdef PNG_STDIO_SUPPORTED
/*
* This is the function that does the actual reading of data. If you are
* not reading from a standard C stream, you should create a replacement
* read_data function and use it at run time with png_set_read_fn(), rather
* than changing the library.
*/
void PNGCBAPI pngcrush_default_read_data(png_structp png_ptr, png_bytep data,
png_size_t length)
{
png_FILE_p io_ptr;
if (length == 0)
png_error(png_ptr, "Read Error: invalid length requested");
io_ptr = png_get_io_ptr(png_ptr);
if (fileno(io_ptr) == -1)
png_error(png_ptr, "Read Error: invalid io_ptr");
/*
* fread() returns 0 on error, so it is OK to store this in a png_size_t
* instead of an int, which is what fread() actually returns.
*/
if ((png_size_t)fread((void *)data, sizeof (png_byte), length,
io_ptr) != length)
{
png_error(png_ptr, "Read Error: invalid length returned");
#if PNGCRUSH_LIBPNG_VER >= 10700
PNG_ABORT
#else
PNG_ABORT();
#endif
}
clearerr(io_ptr);
if (ferror(io_ptr))
{
clearerr(io_ptr);
png_error(png_ptr, "Read Error: error returned by fread()");
}
if (feof(io_ptr))
{
clearerr(io_ptr);
png_error(png_ptr, "Read Error: unexpected end of file");
}
clearerr(io_ptr);
}
#endif /* PNG_STDIO_SUPPORTED */
#ifdef PNG_STDIO_SUPPORTED
/*
* This is the function that does the actual writing of data. If you are
* not writing to a standard C stream, you should create a replacement
* write_data function and use it at run time with png_set_write_fn(), rather
* than changing the library.
*/
void PNGCBAPI pngcrush_default_write_data(png_structp png_ptr, png_bytep data,
png_size_t length)
{
png_uint_32 check;
png_FILE_p io_ptr;
io_ptr = png_get_io_ptr(png_ptr);
check = fwrite(data, 1, length, io_ptr);
if (check != length)
png_error(png_ptr, "Write Error");
}
#endif /* PNG_STDIO_SUPPORTED */
static void pngcrush_warning(png_structp png_ptr,
png_const_charp warning_msg)
{
#if (PNGCRUSH_LIBPNG_VER >= 10700)
/* don't warn about damaged LZ stream due to bailing */
if (bail == 0 && !strcmp(warning_msg, "damaged LZ stream"))
return;
#endif
if (verbose >= 0)
fprintf(stderr, "pngcrush: %s\n", warning_msg);
else
{
if (show_warnings)
fprintf(stderr, "%s: %s\n", inname, warning_msg);
}
return;
}
/* cexcept interface */
static void pngcrush_cexcept_error(png_structp png_ptr,
png_const_charp err_msg)
{
#if 0
/* Handle "bad adaptive filter value" error. */
if (!strcmp(err_msg, "bad adaptive filter value")) {
#ifdef PNG_CONSOLE_IO_SUPPORTED
fprintf(stderr, "\nIn %s, correcting %s\n", inname,err_msg);
#else
pngcrush_warning(png_ptr, err_msg);
#endif
return;
}
#if PNGCRUSH_LIBPNG_VER < 10400
/* Handle "Too many IDAT's found" error. In libpng-1.4.x this became
* a benign error, "Too many IDATs found". This scheme will not work
* in libpng-1.5.0 and later.
*/
# ifdef PNGCRUSH_H /* Why would this not work with the system library? */
if (!strcmp(err_msg, "Too many IDAT's found")) {
# ifdef PNG_CONSOLE_IO_SUPPORTED
fprintf(stderr, "\nIn %s, correcting %s\n", inname,err_msg);
# else
pngcrush_warning(png_ptr, err_msg);
# endif
return;
}
# endif /* PNGCRUSH_H */
#endif /* PNGCRUSH_LIBPNG_VER */
#endif /* 0 */
{
Throw err_msg;
}
}
/* START of code to validate memory allocation and deallocation */
#ifdef PNG_USER_MEM_SUPPORTED
/*
* Allocate memory. For reasonable files, size should never exceed
* 64K. However, zlib may allocate more then 64K if you don't tell
* it not to. See zconf.h and png.h for more information. zlib does
* need to allocate exactly 64K, so whatever you call here must
* have the ability to do that.
*
* This piece of code can be compiled to validate max 64K allocations
* by setting MAXSEG_64K in zlib zconf.h *or* PNG_MAX_MALLOC_64K.
*/
typedef struct memory_information {
png_uint_32 size;
png_voidp pointer;
struct memory_information *next;
} memory_information;
typedef memory_information *memory_infop;
static memory_infop pinformation = NULL;
static int current_allocation = 0;
static int maximum_allocation = 0;
png_voidp pngcrush_debug_malloc(png_structp png_ptr, png_uint_32 size)
{
/*
* png_malloc has already tested for NULL; png_create_struct calls
* pngcrush_debug_malloc directly (with png_ptr == NULL prior to
* libpng-1.2.0 which is OK since we are not using a user mem_ptr)
*/
if (size == 0)
return (png_voidp) (NULL);
/*
* This calls the library allocator twice, once to get the requested
* buffer and once to get a new free list entry.
*/
{
memory_infop pinfo = (memory_infop)malloc(sizeof *pinfo);
if (pinfo == NULL)
return (png_voidp) (NULL);
pinfo->size = size;
current_allocation += size;
if (current_allocation > maximum_allocation)
maximum_allocation = current_allocation;
pinfo->pointer = malloc(size);
pinfo->next = pinformation;
pinformation = pinfo;
/* Make sure the caller isn't assuming zeroed memory. */
png_memset(pinfo->pointer, 0xdd, pinfo->size);
if (verbose > 2)
fprintf(STDERR, "Pointer %p allocated %lu bytes\n",
(png_voidp) pinfo->pointer, (unsigned long)size);
return (png_voidp) (pinfo->pointer);
}
}
/* Free a pointer. It is removed from the list at the same time. */
void pngcrush_debug_free(png_structp png_ptr, png_voidp ptr)
{
if (png_ptr == NULL)
fprintf(STDERR, "NULL pointer to pngcrush_debug_free.\n");
if (ptr == 0) {
#if 0 /* This happens all the time. */
fprintf(STDERR, "WARNING: freeing NULL pointer\n");
#endif /* 0 */
return;
}
/* Unlink the element from the list. */
{
memory_infop *ppinfo = &pinformation;
for (;;) {
memory_infop pinfo = *ppinfo;
if (pinfo->pointer == ptr) {
*ppinfo = pinfo->next;
current_allocation -= pinfo->size;
if (current_allocation < 0)
fprintf(STDERR, "Duplicate free of memory\n");
/* We must free the list element too, but first kill
the memory that is to be freed. */
memset(ptr, 0x55, pinfo->size);
if (verbose > 2)
fprintf(STDERR, "Pointer %p freed %lu bytes\n",
(png_voidp) ptr, (unsigned long)pinfo->size);
free(pinfo);
break;
}
if (pinfo->next == NULL) {
fprintf(STDERR, "Pointer %p not found\n",
(png_voidp) ptr);
break;
}
ppinfo = &pinfo->next;
}
}
/* Finally free the data. */
free(ptr);
}
#endif /* PNG_USER_MEM_SUPPORTED */
/* END of code to test memory allocation/deallocation */
void pngcrush_pause(void)
{
if (pauses > 0) {
char keystroke;
fprintf(STDERR, "Press [ENTER] key to continue.\n");
keystroke = (char) getc(stdin);
keystroke = keystroke; /* stifle compiler warning */
}
}
void png_skip_chunk(png_structp png_ptr)
{
png_byte buff[4] = { 0, 0, 0, 0 };
int ib;
unsigned long length;
/* read the length field */
pngcrush_default_read_data(png_ptr, buff, 4);
length = pngcrush_get_uint_31(png_ptr,buff);
/* read the chunk name */
pngcrush_default_read_data(png_ptr, buff, 4);
if (verbose > 0)
printf("Skipping %c%c%c%c chunk.\n",buff[0],buff[1],
buff[2],buff[3]);
/* skip the data and CRC */
for (ib=0; ib<length+4; ib++)
{
png_byte junk[1] = { 0 };
pngcrush_default_read_data(png_ptr, junk, 1);
}
}
#ifndef __riscos
# define setfiletype(x)
#else /* defined(__riscos) */
# include <kernel.h>
/* The riscos/acorn support was contributed by <NAME>. */
static int fileexists(const char *name)
{
# ifdef __acorn
int ret;
return _swix(8, 3 | 1 << 31, 17, name, &ret) ? 0 : ret;
# else
_kernel_swi_regs r;
r.r[0] = 17;
r.r[1] = (int) name;
return _kernel_swi(8, &r, &r) ? 0 : r.r[0];
# endif
}
static int filesize(const char *name)
{
# ifdef __acorn
int ret;
return _swix(8, 3 | 1 << 27, 17, name, &ret) ? 0 : ret;
# else
_kernel_swi_regs r;
r.r[0] = 17;
r.r[1] = (int) name;
return _kernel_swi(8, &r, &r) ? 0 : r.r[4];
# endif
}
static int mkdir(const char *name, int ignored)
{
# ifdef __acorn
_swi(8, 0x13, 8, name, 0);
return 0;
# else
_kernel_swi_regs r;
r.r[0] = 8;
r.r[1] = (int) name;
r.r[4] = r.r[3] = r.r[2] = 0;
return (int) _kernel_swi(8 | 1 << 31, &r, &r);
# endif
}
static void setfiletype(const char *name)
{
# ifdef __acorn
_swi(8, 7, 18, name, 0xB60);
# else
_kernel_swi_regs r;
r.r[0] = 18;
r.r[1] = (int) name;
r.r[2] = 0xB60;
_kernel_swi(8 | 1 << 31, &r, &r);
# endif
}
#endif /* defined(__riscos) */
/*
* GRR: basically boolean; first arg is chunk name-string (e.g., "tIME" or
* "alla"); second is always full argv[] command line
* - remove_chunks is argv index of *last* -rem arg on command line
* (would be more efficient to build table at time of cmdline processing!)
* (i.e., build removal_list with names or unique IDs or whatever--skip
* excessive string-processing on every single one)
* - reprocesses command line _every_ time called, looking for -rem opts...
* - just like keep_chunk() except that latter sets things_have_changed
* variable and debug stmts say "Removed chunk" (but caller actually does
* so, by choosing not to copy chunk to new file)
* - for any given chunk name, "name" must either match exact command-line
* arg (e.g., -rem fOOb), OR it must match one of the official PNG chunk
* names explicitly listed below AND command-line arg either used all-
* lowercase form or one of "all[ab]" options
*/
int keep_unknown_chunk(png_const_charp name, char *argv[])
{
int i;
if (remove_chunks == 0)
return 1; /* no -rem options, so always keeping */
for (i = 1; i <= remove_chunks; i++) {
if (!strncmp(argv[i], "-rem", 4)) {
int allb = 0;
i++;
if (!strncmp(argv[i], "all", 3)) {
allb++; /* all but gamma, but not doing gamma here */
}
if (!strncmp(argv[i], name, 4) /* exact chunk-name match in args */
/* ...or exact match for one of known set, plus args included
* either "alla", "allb", or all-lowercase form of "name" */
|| (!strncmp(name, "cHRM", 4)
&& (!strncmp(argv[i], "chrm", 4) || allb))
|| (!strncmp(name, "dSIG", 4)
&& (!strncmp(argv[i], "dsig", 4) || allb))
|| (!strncmp(name, "gIFg", 4)
&& (!strncmp(argv[i], "gifg", 4) || allb))
|| (!strncmp(name, "gIFt", 4)
&& (!strncmp(argv[i], "gift", 4) || allb))
|| (!strncmp(name, "gIFx", 4)
&& (!strncmp(argv[i], "gifx", 4) || allb))
|| (!strncmp(name, "hIST", 4)
&& (!strncmp(argv[i], "hist", 4) || allb))
|| (!strncmp(name, "iCCP", 4)
&& (!strncmp(argv[i], "iccp", 4) || allb))
|| (!strncmp(name, "pCAL", 4)
&& (!strncmp(argv[i], "pcal", 4) || allb))
|| (!strncmp(name, "sCAL", 4)
&& (!strncmp(argv[i], "scal", 4) || allb))
|| (!strncmp(name, "sPLT", 4)
&& (!strncmp(argv[i], "splt", 4) || allb))
|| (!strncmp(name, "tIME", 4)
&& (!strncmp(argv[i], "time", 4) || allb)))
{
return 0;
}
}
}
return 1;
}
int keep_chunk(png_const_charp name, char *argv[])
{
int i;
if (verbose > 2 && last_trial)
fprintf(STDERR, " Read the %s chunk.\n", name);
if (remove_chunks == 0)
return 1;
if (verbose > 1 && last_trial)
fprintf(STDERR, " Check for removal of the %s chunk.\n", name);
for (i = 1; i <= remove_chunks; i++) {
if (!strncmp(argv[i], "-rem", 4)) {
int alla = 0;
int allb = 0;
int allt = 0;
i++;
if (!strncmp(argv[i], "all", 3)) {
allt++; /* all forms of text chunk are ancillary */
allb++; /* all ancillaries but gamma... */
if (!strncmp(argv[i], "alla", 4))
alla++; /* ...no, all ancillaries, period */
} else if (!strncmp(argv[i], "text", 4)) {
allt++; /* all forms of text chunk */
}
if (!strncmp(argv[i], name, 4) /* exact chunk-name match in args
* ...or exact match for one of known set, plus args included
* either "alla", "allb", or all-lowercase form of "name": */
|| (!strncmp(name, "PLTE", 4)
&& (!strncmp(argv[i], "plte", 4) ))
|| (!strncmp(name, "bKGD", 4)
&& (!strncmp(argv[i], "bkgd", 4) || allb))
|| (!strncmp(name, "cHRM", 4)
&& (!strncmp(argv[i], "chrm", 4) || allb))
|| (!strncmp(name, "dSIG", 4)
&& (!strncmp(argv[i], "dsig", 4) || allb))
|| (!strncmp(name, "gAMA", 4)
&& (!strncmp(argv[i], "gama", 4) || alla))
|| (!strncmp(name, "gIFg", 4)
&& (!strncmp(argv[i], "gifg", 4) || allb))
|| (!strncmp(name, "gIFt", 4)
&& (!strncmp(argv[i], "gift", 4) || allb))
|| (!strncmp(name, "gIFx", 4)
&& (!strncmp(argv[i], "gifx", 4) || allb))
|| (!strncmp(name, "hIST", 4)
&& (!strncmp(argv[i], "hist", 4) || allb))
|| (!strncmp(name, "iCCP", 4)
&& (!strncmp(argv[i], "iccp", 4) || allb))
|| (!strncmp(name, "iTXt", 4)
&& (!strncmp(argv[i], "itxt", 4) || allt))
|| (!strncmp(name, "oFFs", 4)
&& (!strncmp(argv[i], "offs", 4) || allb))
|| (!strncmp(name, "pHYs", 4)
&& (!strncmp(argv[i], "phys", 4) || allb))
|| (!strncmp(name, "pCAL", 4)
&& (!strncmp(argv[i], "pcal", 4) || allb))
|| (!strncmp(name, "sBIT", 4)
&& (!strncmp(argv[i], "sbit", 4) || allb))
|| (!strncmp(name, "sCAL", 4)
&& (!strncmp(argv[i], "scal", 4) || allb))
|| (!strncmp(name, "sRGB", 4)
&& (!strncmp(argv[i], "srgb", 4) || allb))
|| (!strncmp(name, "sTER", 4)
&& (!strncmp(argv[i], "ster", 4) || allb))
|| (!strncmp(name, "sPLT", 4)
&& (!strncmp(argv[i], "splt", 4) || allb))
|| (!strncmp(name, "tEXt", 4)
&& ( allt))
|| (!strncmp(name, "tIME", 4)
&& (!strncmp(argv[i], "time", 4) || allb))
|| (!strncmp(name, "tRNS", 4)
&& (!strncmp(argv[i], "trns", 4) ))
|| (!strncmp(name, "zTXt", 4)
&& (!strncmp(argv[i], "ztxt", 4) || allt)) )
{
/* (caller actually does the removal--by failing to create
* copy) */
if (verbose > 0 && last_trial)
fprintf(STDERR, " Removed the %s chunk.\n", name);
return 0;
}
}
}
if (verbose > 1 && last_trial)
fprintf(STDERR, " Preserving the %s chunk.\n", name);
return 1;
}
void show_result(void)
{
if (total_output_length) {
if (total_input_length == total_output_length)
fprintf(STDERR, " Overall result: no change\n");
else if (total_input_length > total_output_length)
fprintf(STDERR,
" Overall result: %4.2f%% reduction, %lu bytes\n",
(100.0 -
(100.0 * total_output_length) / total_input_length),
(unsigned long)(total_input_length-total_output_length));
else
fprintf(STDERR,
" Overall result: %4.2f%% increase, %lu bytes\n",
-(100.0 -
(100.0 * total_output_length) / total_input_length),
(unsigned long)(total_output_length - total_input_length));
}
#if PNGCRUSH_TIMERS > 0
for (pc_timer=0;pc_timer < PNGCRUSH_TIMERS; pc_timer++)
{
filter_count[pc_timer]+=pngcrush_timer_get_hits(pc_timer);
t_sec=pngcrush_timer_get_seconds(pc_timer);
t_nsec=pngcrush_timer_get_nanoseconds(pc_timer);
t_filter[pc_timer] = (float)t_nsec/1000000000.;
if (t_sec)
t_filter[pc_timer] += (float)t_sec;
}
# if PNGCRUSH_TIMERS >= 3
if (benchmark_iterations > 0 && verbose >= 0)
{
fprintf(STDERR, " CPU time decode %.4f,", t_filter[1]);
fprintf(STDERR, " encode %.4f,", t_filter[2]);
fprintf(STDERR, " other %.4f,", t_filter[3]);
fprintf(STDERR, " total %.4f sec\n", t_filter[0]);
}
#endif
if (verbose <= 0)
return;
# if PNGCRUSH_TIMERS > 9
{
float total_t_filter=0;
float total_filter_count=0;
for (pc_timer = 5; pc_timer < 10; pc_timer++)
{
total_t_filter+=t_filter[pc_timer];
total_filter_count+=filter_count[pc_timer];
}
if (total_filter_count > 0)
{
for (pc_timer = 5; pc_timer < 10; pc_timer++)
{
fprintf(STDERR, " filter[%u] defilter time = %15.9f, count = %lu\n",
pc_timer-5, t_filter[pc_timer],
(unsigned long)filter_count[pc_timer]);
}
fprintf(STDERR, " total defilter time = %15.9f, count = %lu\n",
total_t_filter, (unsigned long) total_filter_count);
}
}
# endif
# if PNGCRUSH_TIMERS > 4
{
if (filter_count[4] > 0)
fprintf(STDERR, " deinterlace time = %15.9f, count = %lu\n",
t_filter[4], (unsigned long)filter_count[4]);
}
# endif
# if PNGCRUSH_USE_CLOCK_GETTIME != 0
# if PNGCRUSH_TIMERS > 1
{
fprintf(STDERR, " total decode time = %15.9f, count = %lu\n",
t_filter[1], (unsigned long)filter_count[1]);
}
# endif
# if PNGCRUSH_TIMERS > 10
{
if (filter_count[10] > 0)
fprintf(STDERR, " filter setup time = %15.9f, count = %lu\n",
t_filter[10], (unsigned long)filter_count[10]);
}
# endif
# if PNGCRUSH_TIMERS > 2
{
fprintf(STDERR, " total encode time = %15.9f, count = %lu\n",
t_filter[2], (unsigned long)filter_count[2]);
}
# endif
# if PNGCRUSH_TIMERS > 3
{
fprintf(STDERR, " total misc time = %15.9f, count = %lu\n",
t_filter[3], (unsigned long)filter_count[3]);
}
# endif
# if PNGCRUSH_TIMERS > 0
{
fprintf(STDERR, " total time = %15.9f, count = %lu\n",
t_filter[0], (unsigned long)filter_count[0]);
}
# endif
# endif
#else
# ifdef PNGCRUSH_TIMERS
fprintf(STDERR, " CPU time defilter = 0.000000\n");
fprintf(STDERR, " (PNGCRUSH_TIMERS=%d)\n\n", (int)PNGCRUSH_TIMERS);
# endif
#endif
#ifdef PNG_USER_MEM_SUPPORTED
if (current_allocation) {
memory_infop pinfo = pinformation;
fprintf(STDERR, "MEMORY ERROR: %d bytes still allocated\n",
current_allocation);
while (pinfo != NULL) {
fprintf(STDERR, "%10lu bytes at %p\n", (unsigned long)pinfo->size,
(png_voidp) pinfo->pointer);
free(pinfo->pointer);
pinfo = pinfo->next;
}
}
#endif /* PNG_USER_MEM_SUPPORTED */
if (found_acTL_chunk == 2)
fprintf(STDERR,
" **** Discarded APNG chunks. ****\n");
}
void pngcrush_write_png(png_structp write_pointer, png_bytep data,
png_size_t length)
{
pngcrush_write_byte_count += (int) length;
if (nosave == 0 && last_trial == 1)
pngcrush_default_write_data(write_pointer, data, length);
}
static void pngcrush_flush(png_structp png_ptr)
{
/* Do nothing. */
PNGCRUSH_UNUSED(png_ptr)
}
void pngcrush_examine_pixels_fn(png_structp png_ptr, png_row_infop
row_info, png_bytep data)
{
if (blacken == 1 || make_gray == 1 || make_opaque == 1)
{
/* Check if there are any fully transparent pixels. If one is found,
* without the underlying color already black, set blacken==2. If the
* PNG colortype does not support an alpha channel, set blacken==3.
*
* Check if there are any transparent pixels. If one is found,
* set make_opaque==2. If the PNG colortype does not support an alpha
* channel, set make_opaque==3.
*
* Check if there are any non-gray pixels. If one is found,
* set make_gray == 2. If the PNG colortype is already gray, set
* make_gray = 3.
*
* Check if any 16-bit pixels do not have identical high and low
* bytes. If one is found, set make_8_bit == 2. If the PNG bit_depth
* is not 16-bits, set make_8_bit = 3.
*
* Find the maximum palette entry present in the IDAT chunks of
* an indexed PNG.
*
*/
int i;
if (row_info->color_type < 4)
{
blacken = 3; /* It doesn't have an alpha channel */
/* To do: check if tRNS chunk can be removed from color type 0 or 2 */
make_opaque = 3;
}
if (row_info->color_type == 0 || row_info->color_type == 4)
make_gray = 3; /* It's already gray! */
if (row_info->color_type == 3)
make_gray = 3; /* Don't change indexed PNG */
if (row_info->bit_depth < 16)
make_8_bit = 3;
i = (int) row_info->rowbytes-1;
if ((row_info->color_type == 2 || row_info->color_type == 6) &&
make_gray == 1) /* RGB */
{
if (row_info->bit_depth == 8)
{
int incr=3;
if (row_info->color_type == 6)
{
incr=4;
i--;
}
for ( ; i > 0 ; )
{
if (data[i] != data[i-1] || data[i] != data[i-2])
{
make_gray = 2;
}
i-=incr;
}
}
else /* bit depth == 16 */
{
int incr = 6;
if (row_info->color_type == 6)
{
incr = 8;
i-=2;
}
for ( ; i > 0 ; )
{
if (data[i] != data[i-2] || data[i] != data[i-4] ||
data[i-1] != data[i-3] || data[i-1] != data[i-5])
{
make_gray = 2;
}
i-=incr;
}
}
}
else if (row_info->color_type == 4 && (blacken == 1 ||
make_opaque == 1)) /* GA */
{
i = (int) row_info->rowbytes-1;
if (row_info->bit_depth == 8)
{
for ( ; i > 0 ; )
{
if (blacken == 1 && data[i] == 0 && data[i-1] != 0)
{
blacken = 2;
}
if (make_opaque == 1 && data[i] != 255)
{
make_opaque = 2;
}
i-=2;
}
}
else /* bit depth == 16 */
{
for ( ; i > 0 ; )
{
if (blacken == 1 && (data[i] == 0 && data[i-1] == 0) &&
(data[i-2] != 0 || data[i-3] != 0))
{
blacken = 2;
}
if (make_opaque == 1 && (data[i] != 255 || data[i-1] != 255))
{
make_opaque = 2;
}
i-=4;
}
}
}
/* color_type == 6, RGBA */
if (row_info->color_type == 6 && (blacken == 1 || make_gray == 1 ||
make_opaque == 1))
{
i = (int) row_info->rowbytes-1;
if (row_info->bit_depth == 8)
{
for ( ; i > 0 ; )
{
if (blacken == 1 && data[i] == 0 &&
(data[i-1] != 0 || data[i-2] != 0 || data[i-3] != 0))
{
blacken = 2;
}
if (make_gray == 1 &&
(data[i-1] != data[i-2] || data[i-1] != data[i-3]))
{
make_gray = 2;
}
if (make_opaque == 1 && data[i] != 255)
{
make_opaque = 2;
}
i-=4;
}
}
else /* bit depth == 16 */
{
for ( ; i > 0 ; )
{
if (blacken == 1 && (data[i] == 0 && data[i-1]== 0) &&
(data[i-2] != 0 || data[i-3] != 0 || data[i-4] != 0 ||
data[i-5] != 0 || data[i-6] != 0 || data[i-7] != 0))
{
blacken = 2;
}
if (make_gray == 1 &&
(data[i-2] != data[i-4] || data[i-2] != data[i-6] ||
data[i-3] != data[i-5] || data[i-3] != data[i-7]))
{
make_gray = 2;
}
if (make_opaque == 1 && (data[i] != 255 || data[i-1] != 255))
{
make_opaque = 2;
}
i-=8;
}
}
}
}
if (make_8_bit == 1)
{
int i;
i = (int) row_info->rowbytes-1;
if (row_info->color_type == 0)
{
for ( ; i > 0 ; )
{
if (data[i] != data[i-1])
make_8_bit = 2;
i-=2;
}
}
if (row_info->color_type == 2)
{
for ( ; i > 0 ; )
{
if (data[i] != data[i-1] || data[i-2] != data[i-3] ||
data[i-4] != data [i-5])
make_8_bit = 2;
i-=6;
}
}
if (row_info->color_type == 4)
{
for ( ; i > 0 ; )
{
if (data[i] != data[i-1] || data[i-2] != data[i-3])
make_8_bit = 2;
i-=4;
}
}
if (row_info->color_type == 6)
{
for ( ; i > 0 ; )
{
if (data[i] != data[i-1] || data[i-2] != data[i-3] ||
data[i-4] != data [i-5] || data[i-6] != data[i-7])
make_8_bit = 2;
i-=8;
}
}
}
if (reduce_palette == 1 && row_info->color_type == 3)
{
int i;
i = (int) row_info->rowbytes-1;
for ( ; i > 0 ; i--)
{
if (data[i] >= plte_len)
plte_len = data[i] + 1;
}
}
}
void pngcrush_transform_pixels_fn(png_structp png_ptr, png_row_infop row_info,
png_bytep data)
{
int i;
if (blacken == 2)
{
/* change the underlying color of any fully transparent pixels to black */
i=(int) row_info->rowbytes-1;
if (row_info->color_type == 4) /* GA */
{
if (row_info->bit_depth == 8)
{
for ( ; i > 0 ; )
{
if (data[i] == 0 && data[i-1] != 0)
{
data[i-1]=0;
}
i-=2;
}
}
else /* bit depth == 16 */
{
for ( ; i > 0 ; )
{
if (data[i] == 0 && data[i-1] == 0)
{
data[i-2]=0;
data[i-3]=0;
}
i-=4;
}
}
}
else /* color_type == 6, RGBA */
{
if (row_info->bit_depth == 8)
{
for ( ; i > 0 ; )
{
if (data[i] == 0)
{
data[i-1]=0;
data[i-2]=0;
data[i-3]=0;
}
i-=4;
}
}
else /* bit depth == 16 */
{
for ( ; i > 0 ; )
{
if (data[i] == 0 && data[i-1] == 0)
{
data[i-2]=0;
data[i-3]=0;
data[i-4]=0;
data[i-5]=0;
data[i-6]=0;
data[i-7]=0;
}
i-=8;
}
}
}
}
}
int main(int argc, char *argv[])
{
unsigned int bench = 0;
png_uint_32 y;
int bit_depth = 0;
int color_type = 0;
int num_pass, pass;
int num_methods;
int try10 = 0;
char *endptr = NULL;
/* try_method[n]: 0 means try this method;
*
* : 1 means do not try this method.
*/
int try_method[MAX_METHODSP1];
int methods_enabled = 0;
int last_method = MAX_METHODS;
int fm[MAX_METHODSP1];
int lv[MAX_METHODSP1];
int zs[MAX_METHODSP1];
int lev, strat, filt;
#ifdef PNG_gAMA_SUPPORTED
# ifdef PNG_FIXED_POINT_SUPPORTED
png_fixed_point file_gamma = 0;
# else
double file_gamma = 0.;
# endif
#endif
char *cp;
int i;
#if PNGCRUSH_TIMERS >= 0
for (pc_timer=0;pc_timer< PNGCRUSH_TIMERS; pc_timer++)
{
pngcrush_timer_reset(pc_timer);
pngcrush_timer_min_secs[pc_timer]=0xffffffff;
pngcrush_timer_min_nsec[pc_timer]=0xffffffff;
}
pngcrush_timer_start(PNGCRUSH_TIMER_TOTAL);
pngcrush_timer_start(PNGCRUSH_TIMER_MISC);
#endif
if (strcmp(png_libpng_ver, PNG_LIBPNG_VER_STRING))
{
fprintf(STDERR,
"Warning: versions are different between png.h and png.c\n");
fprintf(STDERR, " png.h version: %s\n", PNG_LIBPNG_VER_STRING);
fprintf(STDERR, " png.c version: %s\n\n", png_libpng_ver);
}
row_buf = (png_bytep) NULL;
P2(" row_buf = %p\n",row_buf);
number_of_open_files = 0;
do_color_count = 0;
PNGCRUSH_UNUSED(do_color_count) /* silence compiler warning */
strncpy(prog_string, argv[0], STR_BUF_SIZE);
prog_string[STR_BUF_SIZE-1] = '\0';
progname = prog_string;
for (i = 0, cp = prog_string; *cp != '\0'; i++, cp++)
{
#ifdef __riscos
if (*cp == '.' || *cp == ':')
progname = ++cp;
#else
if (*cp == '\\' || *cp == '/')
progname = ++cp;
#endif
}
/*
* Definition of methods ("canonical list" is methods 11 and up)
*/
for (i = 0; i <= MAX_METHODS; i++)
{
try_method[i] = 1; /* 1 means do not try this method */
fm[i] = 6; lv[i] = 9; zs[i] = 1; /* default: method 136 */
}
fm[0] = 0; lv[0] = 0; zs[0] = 0; /* method 0 == uncompressed */
fm[1] = 0; lv[1] = 4; zs[1] = 0; /* method 1 == method 53 */
fm[2] = 1; lv[2] = 4; zs[2] = 0; /* method 2 == method 54 */
/* fm[3] = 6;*/ lv[3] = 4;/* zs[3] = 1;*/ /* method 3 == method 161 */
fm[4] = 0;/* lv[4] = 9; zs[4] = 1;*/ /* method 4 == method 119 */
fm[5] = 1;/* lv[5] = 9; zs[5] = 0;*/ /* method 5 == method 114 */
/* fm[6] = 6; lv[6] = 9;*/ zs[6] = 0; /* method 6 == method 157 */
fm[7] = 0;/* lv[7] = 9;*/ zs[7] = 0; /* method 7 == method 113 */
fm[8] = 1;/* lv[8] = 9; zs[8] = 1;*/ /* method 8 == method 120 */
/* fm[9] = 6;*/ lv[9] = 2; zs[9] = 2; /* method 9 == method xxx */
/* fm[10]= 6; lv[10]= 9; zs[10]= 1;*/ /* method 10 == method 166 */
/* methods 11 through 16
*
* [strategy 2 (Z_HUFFMAN_ONLY) is independent of zlib compression level]
*/
method = 11;
for (filt = 0; filt <= 5; filt++)
{
fm[method] = filt;
lv[method] = 2;
zs[method] = 2;
method++;
}
/*
* methods 17 through 136 (10*2*6 = 120)
*/
for (lev = 1; lev <= 9; lev++)
{
for (strat = 0; strat <= 1; strat++)
{
for (filt = 0; filt <= 5; filt++)
{
fm[method] = filt;
lv[method] = lev;
zs[method] = strat;
method++;
}
}
}
#ifdef Z_RLE
/* methods 125 through 136
*
* [strategy 3 (Z_RLE) is mostly independent of level; 1-3 and 4-9 are
* same]
*/
for (filt = 0; filt <= 5; filt++)
{
fm[method] = filt;
lv[method] = 1;
zs[method] = 3;
method++;
}
for (filt = 0; filt <= 5; filt++)
{
fm[method] = filt;
lv[method] = 4;
zs[method] = 3;
method++;
}
#endif /* Z_RLE */
/* methods 137 through 148 (12*1*1 = 12), level 0 */
for (strat = 0; strat <= 1; strat++)
{
for (filt = 0; filt <= 5; filt++)
{
fm[method] = filt;
lv[method] = 0;
zs[method] = strat;
method++;
}
}
/*
* methods 149 through 176 (9*3*1 + 1 = 28), speedy
*/
for (strat = 0; strat <= 3; strat++)
{
for (lev = 1; lev <= 9; lev++)
{
lv[method] = lev;
zs[method] = strat;
fm[method] = 6;
method++;
if (strat == 2)
break; /* HUFFMAN ONLY is independent of level */
}
}
num_methods = method; /* GRR */
/* method 177 */
fm[method] = 0; lv[method] = 0; zs[method] = 0; /* copy_idat */
method++;
#define pngcrush_get_long strtol(argv[i],&endptr,10)
#define pngcrush_check_long \
{if (errno || endptr == argv[i] || *endptr != '\0') \
{ fprintf(STDERR, "pngcrush: malformed or missing argument\n"); \
exit(1); \
} \
}
#define BUMP_I \
{ i++; \
if(i >= argc) {fprintf(STDERR,"pngcrush: insufficient parameters\n");\
exit(1);} }
names = 1;
/* ===================================================================== */
/* FIXME: move args-processing block into separate function (470 lines) */
for (i = 1; i < argc; i++)
{
errno=0;
if (!strncmp(argv[i], "--", 2))
argv[i]++;
if (!strncmp(argv[i], "-", 1))
names++;
/* GRR: start of giant else-if block */
if (!strncmp(argv[i], "-bail", 5))
bail=0;
if (!strncmp(argv[i], "-bench", 6))
{
names++;
BUMP_I;
benchmark_iterations = (unsigned int) pngcrush_get_long;
pngcrush_check_long;
}
else if (!strncmp(argv[i], "-bkgd", 5) ||
!strncmp(argv[i], "-bKGD", 5))
{
names += 3;
have_bkgd = 1;
BUMP_I;
bkgd_red = (png_uint_16) pngcrush_get_long;
pngcrush_check_long;
BUMP_I;
bkgd_green = (png_uint_16) pngcrush_get_long;
pngcrush_check_long;
BUMP_I;
bkgd_blue = (png_uint_16) pngcrush_get_long;
pngcrush_check_long;
bkgd_index = 0;
}
else if (!strncmp(argv[i], "-blacken", 8))
blacken=1;
else if (!strncmp(argv[i], "-brute", 6))
/* brute force: try everything */
{
methods_specified = 1;
brute_force++;
for (method = 1; method < num_methods; method++)
try_method[method] = 0;
if (brute_force_filter == 0)
for (filt = 0; filt < 6; filt++)
brute_force_filters[filt] = 0;
if (brute_force_level == 0)
for (lev = 0; lev < 10; lev++)
brute_force_levels[lev] = 0;
if (brute_force_strategy == 0)
for (strat = 0; strat < NUM_STRATEGIES; strat++)
brute_force_strategies[strat] = 0;
}
else if (!strncmp(argv[i], "-check", 6))
{
check_crc = 1;
}
else if (!strncmp(argv[i], "-c", 3) || !strncmp(argv[i], "-col", 4))
{
names++;
BUMP_I;
force_output_color_type = pngcrush_get_long;
pngcrush_check_long;
}
else if (!strncmp(argv[i], "-d", 3) || !strncmp(argv[i], "-dir", 4))
{
BUMP_I;
if (pngcrush_mode == EXTENSION_MODE)
pngcrush_mode = DIREX_MODE;
else
pngcrush_mode = DIRECTORY_MODE;
directory_name = argv[names++];
}
else if (!strncmp(argv[i], "-exit", 5))
{
pngcrush_must_exit = 1;
}
else if (!strncmp(argv[i], "-e", 3) || !strncmp(argv[i], "-ext", 4))
{
BUMP_I;
if (pngcrush_mode == DIRECTORY_MODE)
pngcrush_mode = DIREX_MODE;
else
pngcrush_mode = EXTENSION_MODE;
extension = argv[names++];
}
else if (!strncmp(argv[i], "-fast", 5))
{
/* try two fast filters */
methods_specified = 1;
try_method[16] = 0;
try_method[53] = 0;
}
else if (!strncmp(argv[i], "-force", 6))
{
force = 1;
}
else if (!strncmp(argv[i], "-fix", 4))
{
salvage++;
}
else if (!strncmp(argv[i], "-f", 3) || !strncmp(argv[i], "-fil", 4))
{
int specified_filter;
BUMP_I;
specified_filter = pngcrush_get_long;
pngcrush_check_long;
if (specified_filter > 5 || specified_filter < 0)
specified_filter = 5;
names++;
if (brute_force == 0)
fm[method] = specified_filter;
else
{
if (brute_force_filter == 0)
for (filt = 0; filt < 6; filt++)
brute_force_filters[filt] = 1;
brute_force_filters[specified_filter] = 0;
brute_force_filter++;
}
}
#ifdef PNG_gAMA_SUPPORTED
else if (!strncmp(argv[i], "-g", 3) || !strncmp(argv[i], "-gam", 4))
{
names++;
BUMP_I;
found_gAMA=1;
if (specified_intent < 0)
{
#ifdef PNG_FIXED_POINT_SUPPORTED
int c;
char number[16];
char *n = number;
int nzeroes = -1;
int length = strlen(argv[i]);
for (c = 0; c < length; c++)
{
if (*(argv[i] + c) == '.')
{
nzeroes = 5;
}
else if (nzeroes)
{
*n++ = *(argv[i] + c);
nzeroes--;
}
}
for (c = 0; c < nzeroes; c++)
*n++ = '0';
*n = '\0';
specified_gamma = strtol(number,&endptr,10);
#else
specified_gamma = strtof(argv[i],&endptr);
#endif
pngcrush_check_long;
}
}
#endif /* PNG_gAMA_SUPPORTED */
else if (!strncmp(argv[i], "-h", 3) || !strncmp(argv[i], "-hel", 4))
{
++verbose;
print_version_info();
printed_version_info++;
print_usage(0); /* this exits */
}
else if (!strncmp(argv[i], "-huffman", 8))
{
/* try all filters with huffman */
methods_specified = 1;
for (method = 11; method <= 16; method++)
{
try_method[method] = 0;
}
}
#ifdef PNG_iCCP_SUPPORTED
else if (!strncmp(argv[i], "-iccp", 5))
{
FILE *iccp_fn;
if (iccp_length)
free(iccp_text);
BUMP_I;
iccp_length = pngcrush_get_long;
pngcrush_check_long;
names += 3;
BUMP_I;
strncpy(iccp_name, argv[i], 80);
iccp_name[79] = '\0';
BUMP_I;
iccp_file = argv[i];
if ((iccp_fn = FOPEN(iccp_file, "rb")) == NULL) {
fprintf(STDERR, "Could not find file: %s\n", iccp_file);
iccp_length = 0;
}
else
{
int ic;
number_of_open_files++;
iccp_text = (char*)malloc(iccp_length);
if (iccp_text == NULL)
{
fprintf(STDERR, "malloc of iccp_text failed\n");
iccp_length = 0;
}
for (ic = 0; ic < iccp_length; ic++)
{
png_size_t num_in;
num_in = fread((void *)buffer, 1, 1, iccp_fn);
if (!num_in)
break;
iccp_text[ic] = buffer[0];
}
FCLOSE(iccp_fn);
}
}
#endif /* PNG_iCCP_SUPPORTED */
else if (!strncmp(argv[i], "-keep", 5))
{
names++;
BUMP_I;
if (!strncmp(argv[i], "-dSIG", 5)
&& (!strncmp(argv[i], "-dsig", 5) ))
found_any_chunk=1;
}
else if (!strncmp(argv[i], "-l", 3) || !strncmp(argv[i], "-lev", 4))
{
int specified_level;
BUMP_I;
specified_level = pngcrush_get_long;
pngcrush_check_long;
if (specified_level > 9 || specified_level < 0)
specified_level = 9;
names++;
if (brute_force == 0)
lv[method] = specified_level;
else
{
if (brute_force_level == 0)
for (lev = 0; lev < 10; lev++)
brute_force_levels[lev] = 1;
brute_force_levels[specified_level] = 0;
brute_force_level++;
}
}
else if (!strncmp(argv[i], "-loco", 5))
{
#ifdef PNGCRUSH_LOCO
do_loco = 1;
#else
fprintf
(STDERR,"Cannot do -loco because libpng was compiled"
" without MNG features");
#endif
}
else if (!strncmp(argv[i], "-max", 4))
{
names++;
BUMP_I;
max_idat_size = (png_uint_32) pngcrush_get_long;
pngcrush_check_long;
if (max_idat_size == 0 || max_idat_size > PNG_UINT_31_MAX)
max_idat_size = PNG_ZBUF_SIZE;
}
else if (!strncmp(argv[i], "-m", 3) || !strncmp(argv[i], "-met", 4))
{
names++;
BUMP_I;
method = pngcrush_get_long;
pngcrush_check_long;
if (method >= 1 && method <= MAX_METHODS)
{
methods_specified = 1;
brute_force = 0;
try_method[method] = 0;
}
else
{
fprintf(STDERR, "\n Ignoring invalid method: %d\n",
method);
method = MAX_METHODS;
}
}
#ifdef PNGCRUSH_LOCO
else if (!strncmp(argv[i], "-mng", 4))
{
names++;
BUMP_I;
mngname = argv[i];
new_mng++;
}
#endif
else if (!strncmp(argv[i], "-new", 4))
{
make_opaque = 1; /* -reduce */
make_gray = 1; /* -reduce */
make_8_bit = 1; /* -reduce */
reduce_palette = 1; /* -reduce */
}
else if (!strncmp(argv[i], "-nobail", 7))
bail=1;
else if (!strncmp(argv[i], "-nocheck", 8))
{
check_crc = 0;
}
else if (!strncmp(argv[i], "-nofilecheck", 5))
{
nofilecheck++;
}
else if (!strncmp(argv[i], "-noforce", 6))
{
force = 0;
}
else if (!strncmp(argv[i], "-nolimits", 5))
{
no_limits++;
}
else if (!strncmp(argv[i], "-noreduce_pal", 13))
{
reduce_palette = 0;
}
else if (!strncmp(argv[i], "-noreduce", 9))
{
make_opaque = 0;
make_gray = 0;
make_8_bit = 0;
reduce_palette = 0;
}
else if (!strncmp(argv[i], "-n", 3) || !strncmp(argv[i], "-nos", 4))
{
/* no save; I just use this for testing decode speed */
/* also to avoid saving if a CgBI chunk was found */
nosave++;
pngcrush_mode = EXTENSION_MODE;
}
else if (!strncmp(argv[i], "-oldtimestamp", 5))
{
new_time_stamp=0;
}
else if (!strncmp(argv[i], "-old", 4))
{
make_opaque = 0; /* no -reduce */
make_gray = 0; /* no -reduce */
make_8_bit = 0; /* no -reduce */
reduce_palette = 0; /* no -reduce */
}
else if(!strncmp(argv[i], "-ow",3))
{
overwrite = 1;
}
else if (!strncmp(argv[i], "-pplt", 3))
{
names++;
do_pplt++;
BUMP_I;
strncpy(pplt_string, argv[i], STR_BUF_SIZE);
pplt_string[STR_BUF_SIZE-1] = '\0';
}
else if (!strncmp(argv[i], "-premultiply", 5))
{
premultiply=2;
}
else if (!strncmp(argv[i], "-p", 3) || !strncmp(argv[i], "-pau", 4))
{
pauses++;
}
else if (!strncmp(argv[i], "-q", 3) || !strncmp(argv[i], "-qui", 4))
{
/* quiet, does not suppress warnings or timing */
verbose = 0;
}
else if (!strncmp(argv[i], "-reduce_pal", 11))
{
reduce_palette = 1;
}
else if (!strncmp(argv[i], "-reduce", 7))
{
noreduce = 0;
make_opaque = 1;
make_gray = 1;
make_8_bit = 1;
reduce_palette = 1;
}
#ifdef PNG_gAMA_SUPPORTED
else if (!strncmp(argv[i], "-replace_gamma", 4))
{
names++;
BUMP_I;
found_gAMA=1;
{
#ifdef PNG_FIXED_POINT_SUPPORTED
int c;
char number[16];
char *n = number;
int nzeroes = -1;
int length = strlen(argv[i]);
for (c = 0; c < length; c++)
{
if (*(argv[i] + c) == '.')
{
nzeroes = 5;
}
else if (nzeroes)
{
*n++ = *(argv[i] + c);
nzeroes--;
}
}
for (c = 0; c < nzeroes; c++)
*n++ = '0';
*n = '\0';
force_specified_gamma = strtol(number,&endptr,10);
#else
force_specified_gamma = strtof(argv[i],&endptr);
#endif
pngcrush_check_long;
}
}
#endif /* PNG_gAMA_SUPPORTED */
#ifdef PNG_pHYs_SUPPORTED
else if (!strncmp(argv[i], "-res", 4))
{
names++;
BUMP_I;
resolution = pngcrush_get_long;
pngcrush_check_long;
}
#endif
#ifdef Z_RLE
else if (!strncmp(argv[i], "-rle", 4))
{
/* try all filters with RLE */
methods_specified = 1;
for (method = 125; method <= 136; method++)
{
try_method[method] = 0;
}
}
#endif
#ifdef PNGCRUSH_MULTIPLE_ROWS
else if (!strncmp(argv[i], "-rows", 5))
{
names++;
BUMP_I;
max_rows_at_a_time = pngcrush_get_long;
pngcrush_check_long;
}
#endif
else if (!strncmp(argv[i], "-r", 3) || !strncmp(argv[i], "-rem", 4))
{
remove_chunks = i;
names++;
BUMP_I;
if (!strncmp(argv[i], "-dSIG", 5)
&& (!strncmp(argv[i], "-dsig", 5)))
image_is_immutable=0;
}
else if (!strncmp(argv[i], "-save", 5))
{
all_chunks_are_safe++;
}
else if (!strncmp(argv[i], "-speed", 6))
{
speed = 1;
}
else if (!strncmp(argv[i], "-srgb", 5) ||
!strncmp(argv[i], "-sRGB", 5))
{
#ifdef PNG_gAMA_SUPPORTED
# ifdef PNG_FIXED_POINT_SUPPORTED
specified_gamma = 45455L;
# else
specified_gamma = 0.45455;
# endif
#endif
specified_intent = 0;
BUMP_I;
if (!strncmp(argv[i], "0", 1) ||
!strncmp(argv[i], "1", 1) ||
!strncmp(argv[i], "2", 1) ||
!strncmp(argv[i], "3", 1))
{
names++;
specified_intent = (int) pngcrush_get_long;
pngcrush_check_long;
} else
i--;
}
else if (!strncmp(argv[i], "-ster", 5) ||
!strncmp(argv[i], "-sTER", 5))
{
BUMP_I;
ster_mode = -1;
if (!strncmp(argv[i], "0", 1) ||
!strncmp(argv[i], "1", 1))
{
names++;
ster_mode = (int) pngcrush_get_long;
pngcrush_check_long;
}
else
i--;
}
else if (!strncmp(argv[i], "-s", 3) || !strncmp(argv[i], "-sil", 4))
{
/* silent, suppresses warnings, timing, and results */
verbose = -1;
}
else if (!strncmp(argv[i], "-text", 5)
|| !strncmp(argv[i], "-tEXt", 5) ||
#ifdef PNG_iTXt_SUPPORTED
!strncmp(argv[i], "-itxt", 5)
|| !strncmp(argv[i], "-iTXt", 5)
|| !strncmp(argv[i], "-zitxt", 6)
|| !strncmp(argv[i], "-ziTXt", 6) ||
#endif
!strncmp(argv[i], "-ztxt", 5)
|| !strncmp(argv[i], "-zTXt", 5))
{
i += 2;
BUMP_I;
i -= 3;
if (strlen(argv[i + 2]) < 80 &&
strlen(argv[i + 3]) < STR_BUF_SIZE &&
text_inputs < 10)
{
#ifdef PNG_iTXt_SUPPORTED
if (!strncmp(argv[i], "-zi", 3))
{
text_compression[text_inputs] =
PNG_ITXT_COMPRESSION_zTXt;
/* names += 2; */
}
else
#endif
if (!strncmp(argv[i], "-z", 2))
text_compression[text_inputs] =
PNG_TEXT_COMPRESSION_zTXt;
else if (!strncmp(argv[i], "-t", 2))
text_compression[text_inputs] =
PNG_TEXT_COMPRESSION_NONE;
#ifdef PNG_iTXt_SUPPORTED
else
{
text_compression[text_inputs] =
PNG_ITXT_COMPRESSION_NONE;
/* names += 2; */
}
#endif
names += 3;
if (!strncmp(argv[++i], "b", 1))
text_where[text_inputs] = 1;
if (!strncmp(argv[i], "a", 1))
text_where[text_inputs] = 2;
strncpy(&text_keyword[text_inputs * 80], argv[++i],
80);
text_keyword[text_inputs * 80 + 79] = '\0';
#ifdef PNG_iTXt_SUPPORTED
if (text_compression[text_inputs] <= 0)
{
text_lang[text_inputs * 80] = '\0';
text_lang_key[text_inputs * 80] = '\0';
}
else
{
i += 2;
BUMP_I;
i -= 3;
names += 2;
strncpy(&text_lang[text_inputs * 80], argv[++i], 80);
text_lang[text_inputs * 80 + 79] = '\0';
/* libpng-1.0.5j and later */
strncpy(&text_lang_key[text_inputs * 80], argv[++i], 80);
text_lang_key[text_inputs * 80 + 79] = '\0';
}
#endif
strncpy(&text_text[text_inputs * STR_BUF_SIZE], argv[++i],
STR_BUF_SIZE);
text_text[(text_inputs + 1) * STR_BUF_SIZE - 1] = '\0';
text_inputs++;
} else {
if (text_inputs > 9)
fprintf(STDERR,
"too many text/zTXt inputs; only 10 allowed\n");
else
fprintf(STDERR,
"keyword exceeds 79 characters or text"
" exceeds 2047 characters\n");
i += 3;
names += 3;
#ifdef PNG_iTXt_SUPPORTED
if (!strncmp(argv[i], "-i", 3) || !strncmp(argv[i], "-itx", 4))
{
i++;
BUMP_I;
names += 2;
}
#endif
}
}
else if (!strncmp(argv[i], "-time_stamp", 5) || /* legacy */
!strncmp(argv[i], "-newtimestamp", 5))
new_time_stamp=1;
#ifdef PNG_tRNS_SUPPORTED
else if (!strncmp(argv[i], "-trns_a", 7) ||
!strncmp(argv[i], "-tRNS_a", 7))
{
num_trans_in = (png_uint_16) pngcrush_get_long;
pngcrush_check_long;
if (num_trans_in > 256)
num_trans_in = 256;
trns_index=num_trans_in-1;
have_trns = 1;
for (ia = 0; ia < num_trans_in; ia++)
{
BUMP_I;
trans_in[ia] = (png_byte) pngcrush_get_long;
pngcrush_check_long;
}
names += 1 + num_trans_in;
}
else if (!strncmp(argv[i], "-trns", 5) ||
!strncmp(argv[i], "-tRNS", 5))
{
names += 5;
have_trns = 1;
BUMP_I;
trns_index = (png_uint_16) pngcrush_get_long;
pngcrush_check_long;
BUMP_I;
trns_red = (png_uint_16) pngcrush_get_long;
pngcrush_check_long;
BUMP_I;
trns_green = (png_uint_16) pngcrush_get_long;
pngcrush_check_long;
BUMP_I;
trns_blue = (png_uint_16) pngcrush_get_long;
pngcrush_check_long;
BUMP_I;
trns_gray = (png_uint_16) pngcrush_get_long;
pngcrush_check_long;
}
#endif /* tRNS */
else if(!strncmp(argv[i], "-try10",6))
{
try10 = 1;
}
else if (!strncmp(argv[i], "-version", 8))
{
fprintf(STDERR, " pngcrush ");
fprintf(STDERR, PNGCRUSH_VERSION);
fprintf(STDERR, ", uses libpng ");
fprintf(STDERR, PNG_LIBPNG_VER_STRING);
fprintf(STDERR, " and zlib ");
fprintf(STDERR, ZLIB_VERSION);
fprintf(STDERR, "\n Check http://pmt.sf.net/\n");
fprintf(STDERR, " for the most recent version.\n");
verbose = 0;
exit(0);
}
else if (!strncmp(argv[i], "-v", 3) || !strncmp(argv[i], "-ver", 4))
{
verbose++;
}
else if (!strncmp(argv[i], "-warn", 5))
{
show_warnings++;
verbose = -1;
}
else if (!strncmp(argv[i], "-w", 3) || !strncmp(argv[i], "-win", 4))
{
BUMP_I;
default_compression_window = pngcrush_get_long;
pngcrush_check_long;
force_compression_window++;
names++;
}
else if (!strncmp(argv[i], "-zm", 4) || !strncmp(argv[i], "-zmem", 5))
{
BUMP_I;
compression_mem_level = pngcrush_get_long;
pngcrush_check_long;
names++;
}
else if (!strncmp(argv[i], "-z", 3))
{
int specified_strategy;
BUMP_I;
specified_strategy = pngcrush_get_long;
pngcrush_check_long;
if (specified_strategy > 2 || specified_strategy < 0)
specified_strategy = 0;
names++;
if (brute_force == 0)
zs[method] = specified_strategy;
else
{
if (brute_force_strategy == 0)
for (strat = 0; strat < 2; strat++)
brute_force_strategies[strat] = 1;
brute_force_strategies[specified_strategy] = 0;
brute_force_strategy++;
}
}
else if (!strncmp(argv[i], "-", 1))
{
if (verbose > 0 && printed_version_info == 0)
{
print_version_info();
printed_version_info++;
}
fprintf(STDERR, "\n Ignoring invalid option: %s\n",
argv[i]);
} /* GRR: end of giant if-else block */
} /* end of loop over args ============================================ */
if (verbose > 0 && printed_version_info == 0)
print_version_info();
if (default_compression_window == 32)
default_compression_window = 15;
else if (default_compression_window == 16)
default_compression_window = 14;
else if (default_compression_window == 8)
default_compression_window = 13;
else if (default_compression_window == 4)
default_compression_window = 12;
else if (default_compression_window == 2)
default_compression_window = 11;
else if (default_compression_window == 1)
default_compression_window = 10;
else if (default_compression_window == 512)
default_compression_window = 9;
/* Use of compression window size 256 is not recommended. */
else if (default_compression_window == 256)
default_compression_window = 8;
else if (default_compression_window == 0)
/* do nothing */;
else if (default_compression_window != 15) {
fprintf(STDERR, "Invalid window size (%d); using window size=4\n",
default_compression_window);
default_compression_window = 12;
}
if (pngcrush_mode == DEFAULT_MODE)
{
if (argc - names == 2)
{
inname = argv[names];
outname = argv[names + 1];
}
else if (overwrite)
{
inname = argv[names];
}
else
{
if ((argc - names == 1 || nosave))
{
inname = argv[names];
}
if (verbose > 0 && !nosave)
{
print_usage(1); /* this exits */
}
}
}
first_name = names;
if (benchmark_iterations)
bench=1;
else
bench=0;
for (; bench <= benchmark_iterations; bench++)
{
if (benchmark_iterations > 0)
{
P1(" Pngcrush benchmark iteration %d\n",bench);
names = first_name;
}
#if PNGCRUSH_TIMERS > 0
for (pc_timer = 0; pc_timer < PNGCRUSH_TIMERS; pc_timer++)
{
pngcrush_timer_reset(pc_timer);
filter_count[pc_timer]=0;
}
pngcrush_timer_start(PNGCRUSH_TIMER_TOTAL);
pngcrush_timer_start(PNGCRUSH_TIMER_MISC);
#endif
for (ia = 0; ia < 256; ia++)
trns_array[ia]=255;
for (;;) /* loop on input files */
{
methods_enabled = 0;
last_trial = 0;
if (png_row_filters != NULL)
{
free(png_row_filters);
png_row_filters = NULL;
}
image_specified_gamma = 0;
intent=specified_intent;
inname = argv[names++];
if (inname == NULL)
{
#if PNGCRUSH_TIMERS > 0
pngcrush_timer_stop(PNGCRUSH_TIMER_MISC);
pngcrush_timer_stop(PNGCRUSH_TIMER_TOTAL);
#endif
if (verbose >= 0)
{
show_result();
}
break;
}
if (pngcrush_mode == DIRECTORY_MODE || pngcrush_mode == DIREX_MODE) {
int inlen, outlen;
#ifndef __riscos
struct stat stat_buf;
if (stat(directory_name, &stat_buf))
#else
if (fileexists(directory_name) & 2)
#endif
{
#if defined(_MBCS) || defined(WIN32) || defined(__WIN32__)
if (_mkdir(directory_name))
#else
if (mkdir(directory_name, 0755))
#endif
{
fprintf(STDERR,
"pngcrush: could not create directory %s\n",
directory_name);
exit(1);
}
nofilecheck = 1;
}
outlen = strlen(directory_name);
if (outlen >= STR_BUF_SIZE-1)
{
fprintf(STDERR,
"pngcrush: directory %s is too long for buffer\n",
directory_name);
exit(1);
}
strcpy(out_string, directory_name);
/* Append a slash if it hasn't already got one at the end. */
if (out_string[outlen-1] != SLASH[0] &&
out_string[outlen-1] != FWD_SLASH[0] &&
out_string[outlen-1] != BACK_SLASH[0])
out_string[outlen++] = SLASH[0]; /* (assume SLASH is 1 byte) */
out_string[outlen] = '\0';
inlen = strlen(inname);
if (inlen >= STR_BUF_SIZE)
{
fprintf(STDERR,
"pngcrush: filename %s is too long for buffer\n", inname);
exit(1);
}
strcpy(in_string, inname);
in_string[inlen] = '\0';
#ifdef __riscos
op = strrchr(in_string, '.');
if (!op)
op = in_string;
else
op++;
#else
op = in_string;
ip = in_string + inlen - 1; /* start at last char in string */
while (ip > in_string)
{
if (*ip == '\\' || *ip == '/')
{
op = ip + 1;
break;
}
--ip;
}
#endif
if (outlen + (inlen - (op - in_string)) >= STR_BUF_SIZE)
{
fprintf(STDERR,
"pngcrush: full path is too long for buffer\n");
exit(1);
}
strcpy(out_string+outlen, op);
/*outlen += inlen - (op - in_string); */
outname = out_string;
}
if (overwrite && (pngcrush_mode == EXTENSION_MODE ||
pngcrush_mode == DIRECTORY_MODE ||
pngcrush_mode == DIREX_MODE))
{
if (overwrite > 0)
{
P1( "Ignoring \"-ow\"; cannot use it with \"-d\" or \"-e\"");
overwrite=0;
}
}
/*
* FIXME: need same input-validation fixes (as above) here, too
*
* FIXME: what was the point of setting in_string and out_string in
* DIREX_MODE above if going to do all over again here?
*/
if (pngcrush_mode == EXTENSION_MODE || pngcrush_mode == DIREX_MODE)
{
ip = in_string;
in_string[0] = '\0';
if (pngcrush_mode == EXTENSION_MODE)
strncat(in_string, inname, STR_BUF_SIZE-1);
else
strncat(in_string, outname, STR_BUF_SIZE-1);
ip = in_string;
op = dot = out_string;
while (*ip != '\0')
{
*op++ = *ip++;
#ifdef __riscos
if (*ip == '/')
dot = op;
#else
if (*ip == '.')
dot = op;
#endif
}
*op = '\0';
if (dot != out_string)
*dot = '\0';
in_extension[0] = '\0';
if (dot != out_string)
{
strncat(in_extension, ++dot, STR_BUF_SIZE - 1);
}
strncat(out_string, extension, STR_BUF_SIZE - 1);
outname = out_string;
}
if ((outname[strlen(outname) - 4] == 'p') &&
(outname[strlen(outname) - 3] == 'p') &&
(outname[strlen(outname) - 2] == 'n') &&
(outname[strlen(outname) - 1] == 'g'))
{
/* Writing a *.ppng (png with premultiplied alpha) */
premultiply=2;
#ifndef PNG_READ_PREMULTIPLY_ALPHA_SUPPORTED
png_error(read_ptr, "Premultiplied alpha is not supported");
#endif
}
if ((outname[strlen(outname) - 4] == 'a') &&
(outname[strlen(outname) - 3] == 'p') &&
(outname[strlen(outname) - 2] == 'n') &&
(outname[strlen(outname) - 1] == 'g'))
{
/* Writing an APNG */
save_apng_chunks=1;
}
if (nosave < 2)
{
P1( "Opening file %s for length measurement\n",
inname);
if ((fpin = FOPEN(inname, "rb")) == NULL)
{
fprintf(STDERR, "Could not find file: %s\n", inname);
continue;
}
number_of_open_files++;
#ifdef PNGCRUSH_LOCO
if (new_mng)
{
# ifdef PNG_USER_MEM_SUPPORTED
if (verbose > 0)
mng_ptr = png_create_write_struct_2(PNG_LIBPNG_VER_STRING,
(png_voidp) NULL, (png_error_ptr) pngcrush_cexcept_error,
(png_error_ptr) pngcrush_warning, (png_voidp) NULL,
(png_malloc_ptr) pngcrush_debug_malloc,
(png_free_ptr) pngcrush_debug_free);
else
# endif
mng_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING,
(png_voidp) NULL,
(png_error_ptr) pngcrush_cexcept_error,
(png_error_ptr) pngcrush_warning);
if (mng_ptr == NULL)
fprintf(STDERR, "pngcrush could not create mng_ptr");
if ((mng_out = FOPEN(mngname, "wb")) == NULL)
{
fprintf(STDERR,
"pngcrush: could not open output file %s\n",
mngname);
FCLOSE(fpin);
exit(1);
}
number_of_open_files++;
png_init_io(mng_ptr, mng_out);
png_set_write_fn(mng_ptr, (png_voidp) mng_out,
(png_rw_ptr) pngcrush_write_png,
pngcrush_flush);
}
#endif /* PNGCRUSH_LOCO */
idat_length[0] = measure_idats(fpin);
#ifdef PNGCRUSH_LOCO
if (new_mng)
{
png_destroy_write_struct(&mng_ptr, NULL);
FCLOSE(mng_out);
}
#endif
FCLOSE(fpin);
if (verbose >= 0 && bench < 2)
{
if (nosave)
{
fprintf(STDERR, " %s:\n", inname);
}
else if (overwrite)
{
fprintf(STDERR,
" Recompressing IDAT chunks in %s\n", inname);
}
else
{
fprintf(STDERR,
" Recompressing IDAT chunks in %s to %s\n",
inname, outname);
}
fprintf(STDERR,
" Total length of data found in critical chunks "
" =%10lu\n", (unsigned long)idat_length[0]);
fflush(STDERR);
}
if (idat_length[0] == 0)
continue;
}
else
idat_length[0] = 1;
if (image_is_immutable)
{
fprintf(STDERR,
" Image %s has a dSIG chunk and is immutable.\n", inname);
}
if (!image_is_immutable)
{
if (force_output_color_type != 8 &&
force_output_color_type != 0 &&
force_output_color_type != 2 &&
force_output_color_type != 3 &&
force_output_color_type != 4 &&
force_output_color_type != 6)
{
fprintf(STDERR, "\n Ignoring invalid color_type: %d\n",
force_output_color_type);
force_output_color_type=8;
}
output_color_type = force_output_color_type;
output_bit_depth = force_output_bit_depth;
best_of_three = 1;
pngcrush_best_byte_count=0xffffffff;
if (blacken == 1 || make_gray == 1 || make_opaque == 1 ||
reduce_palette == 1)
{
try_method[0] = 0;
}
/*
* From the PNG spec, various dependencies among chunk types
* must be accounted for during any reduction of color type
* or bit depth:
*
* IHDR valid bit depth depends on color type
* valid filter type depends on color type (for MNG extensions)
* tRNS depends on color type
* depends on num_palette for color type 3 (palette)
* iCCP valid profile depends on color type
* sBIT depends on color type and bit depth
* bKGD depends on color type and bit depth
* hIST depends on num_palette
*
* Chunk types present have been detected in the first pass over
* the file, in the measure_idat() function.
*/
if (make_gray)
{
if ((found_iCCP && keep_unknown_chunk("iCCP", argv)) ||
(found_color_bKGD && keep_unknown_chunk("bKGD", argv)) ||
found_acTL_chunk == 1 ||
(found_sBIT_different_RGB_bits &&
keep_unknown_chunk("sBIT", argv)))
{
P1 ("Cannot change colortype to gray when iCCP,"
" acTL, bKGD with color, or sBIT chunk is present\n");
make_gray = 0;
}
else
{
make_gray = 1;
try_method[0] = 0;
}
}
if (make_opaque)
{
if (found_tRNS || found_acTL_chunk == 1)
{
P1("Cannot remove the alpha channel when tRNS"
" or acTL chunk is present\n");
make_opaque = 0;
}
else
{
make_opaque = 1;
try_method[0] = 0;
}
}
if (make_8_bit)
{
if ((found_bKGD && keep_unknown_chunk("bKGD", argv)) ||
found_acTL_chunk == 1 ||
(found_sBIT_max > 8 && keep_unknown_chunk("sBIT", argv)))
{
P1 ("Cannot reduce bit depth to 8 when bKGD,"
" sBIT or acTL chunk is present\n");
make_8_bit = 0;
}
else
{
make_8_bit = 1;
try_method[0] = 0;
}
}
if (input_color_type == 3 && reduce_palette)
{
if ((found_hIST && keep_unknown_chunk("hIST", argv)) ||
found_acTL_chunk == 1)
{
P1("Cannot reduce palette length when hIST"
" or acTL chunk is present\n");
reduce_palette = 0;
plte_len = -1;
}
else
{
try_method[0] = 0;
plte_len = 0;
}
}
/* Handle specified brute_force options */
if (brute_force_level || brute_force_filter || brute_force_strategy)
{
for (method = 1; method < num_methods; method++)
{
int option;
try_method[method]=1;
if (brute_force_level)
{
for (option = 0; option < 10; option++)
if (option == lv[method])
try_method[method]=brute_force_levels[option];
}
if ((try_method[method] == 0) && brute_force_filter)
{
for (option = 0; option < 6; option++)
if (option == fm[method])
try_method[method]=brute_force_filters[option];
}
if ((try_method[method] == 0) && brute_force_strategy)
{
for (option = 0; option < NUM_STRATEGIES; option++)
if (option == zs[method])
try_method[method]=brute_force_strategies[option];
}
if (method && method < 11)
try_method[method] = 1;
}
if (speed)
{
/* Do not try AVG or PAETH */
for (method = 1; method < num_methods; method++)
{
if (try_method[method] == 0 && (fm[method] == 3 ||
fm[method] == 4 || fm[method] == 5))
try_method[method] = 1;
}
}
}
if (methods_specified == 0 || try10 != 0)
{
for (i = 0; i <= DEFAULT_METHODS; i++)
try_method[i] = 0;
try_method[6] = try10;
}
for (i = 1; i <= MAX_METHODS; i++)
{
methods_enabled += (1 - try_method[i]);
}
P1("%d methods enabled\n",methods_enabled);
/* Skip trial 0 when a single method was specified and -reduce was not */
if (methods_specified != 0 && noreduce != 0)
{
if (methods_enabled == 1)
{
try_method[0] = 1;
make_opaque = 0;
make_gray = 0;
make_8_bit = 0;
reduce_palette = 0;
}
}
last_method = 0;
for (i = 1; i <= MAX_METHODS; i++)
{
if (try_method[i] == 0)
last_method = i;
}
if (methods_enabled > 1)
last_method++;
P1(" pngcrush: methods = %d\n",methods_enabled);
P1(" pngcrush: last_method = %d\n",last_method);
if (methods_enabled == 1 && last_method == 176)
copy_idat = 1;
best_of_three = 1;
#ifndef __riscos
{
/* COVERITY complains about TOCTOU when inname is used later */
struct stat stat_buf;
stat(inname, &stat_buf);
input_length = (unsigned long) stat_buf.st_size;
}
#else
input_length = (unsigned long) filesize(inname);
#endif
/* ////////////////////////////////////////////////////////////////////
//////////////// ////////////////////
//////////////// START OF MAIN LOOP OVER METHODS ////////////////////
//////////////// ////////////////////
//////////////////////////////////////////////////////////////////// */
/* MAX_METHODS is 177 */
P1("\n\nENTERING MAIN LOOP OVER %d METHODS\n", MAX_METHODS);
for (trial = 0; trial <= last_method; trial++)
{
if (nosave || trial == last_method)
last_trial = 1;
if (verbose > 1)
fprintf(STDERR, "pngcrush: trial = %d\n",trial);
pngcrush_write_byte_count=0;
#ifdef PNGCRUSH_H
# if ZLIB_VERNUM > 0x1240
if (last_trial == 0)
pngcrush_write_byte_count=6; /* zlib header that isn't written */
# endif
#endif
found_IDAT = 0;
if (trial != 0)
idat_length[trial] = (png_uint_32) 0xffffffff;
/* this part of if-block is for final write-the-best-file
iteration */
if (trial == last_method)
{
png_uint_32 best_length;
if (methods_enabled == 1)
{
best = trial;
best_length = idat_length[trial];
}
else
{
int j;
/* check lengths */
best = 0; /* i.e., input file */
best_length = (png_uint_32) 0xffffffff;
for (j = 0; j <= last_method; j++)
{
if (best == 0 && best_length == idat_length[j])
{
/* If no change, report the first match */
best = j;
}
if ((force == 0 || j != 0) &&
best_length > idat_length[j])
{
best_length = idat_length[j];
best = j;
}
if (j > 148 && j < 176 && best_length == idat_length[j])
{
/* break ties in favor of method 6 */
best = j;
}
}
}
if (image_is_immutable ||
(idat_length[best] == idat_length[0] &&
force == 0 && nosave == 0))
{
/* just copy input to output */
P2("prepare to copy input to output\n");
pngcrush_pause();
if ((fpin = FOPEN(inname, "rb")) == NULL)
{
fprintf(STDERR, "Could not find input file %s\n",
inname);
continue;
}
number_of_open_files++;
if ((fpout = FOPEN(outname, "wb")) == NULL)
{
fprintf(STDERR,
"pngcrush: could not open output file %s\n",
outname);
FCLOSE(fpin);
exit(1);
}
number_of_open_files++;
P2("copying input to output...");
for (;;)
{
png_size_t num_in, num_out;
num_in = fread((void *)buffer, 1, 1, fpin);
if (!num_in)
break;
num_out = fwrite(buffer, 1, 1, fpout);
if (num_out != num_in)
P2("copy error.\n");
}
P2("copy complete.\n");
pngcrush_pause();
FCLOSE(fpin);
FCLOSE(fpout);
setfiletype(outname);
break;
}
filter_type = fm[best];
zlib_level = lv[best];
if (zs[best] == 1)
z_strategy = Z_FILTERED;
else if (zs[best] == 2)
z_strategy = Z_HUFFMAN_ONLY;
#ifdef Z_RLE
else if (zs[best] == 3)
z_strategy = Z_RLE;
#endif
else /* if (zs[best] == 0) */
z_strategy = Z_DEFAULT_STRATEGY;
}
else /* Trial < last_method */
{
if (trial > 2 && trial < 5 && idat_length[trial - 1]
< idat_length[best_of_three])
best_of_three = trial - 1;
if (try_method[trial])
{
P2("skipping \"late\" trial %d\n", trial);
continue;
}
/* default behavior is to do the heuristics (6 of the first
* 10 methods). try10 means try all of 1-10.
*/
if (!methods_specified && try10 == 0)
{
if ((trial == 4 || trial == 7) && best_of_three != 1)
{
P2("skipping \"early\" trial %d\n", trial);
continue;
}
if ((trial == 5 || trial == 8) && best_of_three != 2)
{
P2("skipping \"early\" trial %d\n", trial);
continue;
}
if ((trial == 6 || trial == 9 || trial == 10)
&& best_of_three != 3)
{
P2("skipping \"early\" trial %d\n", trial);
continue;
}
}
filter_type = fm[trial];
zlib_level = lv[trial];
if (zs[trial] == 1)
z_strategy = Z_FILTERED;
else if (zs[trial] == 2)
z_strategy = Z_HUFFMAN_ONLY;
#ifdef Z_RLE
else if (zs[trial] == 3)
z_strategy = Z_RLE;
#endif
else /* if (zs[trial] == 0) */
z_strategy = Z_DEFAULT_STRATEGY;
final_method = trial;
if (!nosave)
{
P2("\n\n------------------------------------------------\n"
"Begin trial %d, filter %d, strategy %d, level %d\n",
trial, filter_type, z_strategy, zlib_level);
}
}
P2("prepare to open files.\n");
pngcrush_pause();
if ((fpin = FOPEN(inname, "rb")) == NULL)
{
fprintf(STDERR, "Could not find input file %s\n", inname);
continue;
}
number_of_open_files++;
if (last_trial && nosave == 0)
{
#ifndef __riscos
/* Can't sensibly check this on RISC OS without opening a file
for update or output
*/
struct stat stat_in, stat_out;
if (last_trial && !nofilecheck
&& (stat(inname, &stat_in) == 0)
&& (stat(outname, &stat_out) == 0) &&
#if defined(_MSC_VER) || defined(__MINGW32__) /* maybe others? */
/* MSVC++6.0 will erroneously return 0 for both files, so
we simply check the size instead. It is possible that
we will erroneously reject the attempt when inputsize
and outputsize are equal, for different files
*/
(stat_in.st_size == stat_out.st_size) &&
#else
(stat_in.st_ino == stat_out.st_ino) &&
#endif
(stat_in.st_dev == stat_out.st_dev))
{
fprintf(STDERR,
"\n pngcrush: cannot overwrite input file %s\n",
outname);
P1(" st_ino=%d, st_size=%d\n\n",
(int) stat_in.st_ino, (int) stat_in.st_size);
FCLOSE(fpin);
exit(1);
}
#endif
if ((fpout = FOPEN(outname, "wb")) == NULL)
{
fprintf(STDERR,
"pngcrush: could not open output file %s\n",
outname);
FCLOSE(fpin);
exit(1);
}
number_of_open_files++;
}
P2("files are opened.\n");
pngcrush_pause();
/* OK to ignore any warning about the address of exception__prev in "Try" */
Try {
png_uint_32 row_length;
P1( "Allocating read and write structures\n");
#ifdef PNG_USER_MEM_SUPPORTED
if (verbose > 0)
read_ptr = png_create_read_struct_2(PNG_LIBPNG_VER_STRING,
(png_voidp) NULL,
(png_error_ptr) pngcrush_cexcept_error,
(png_error_ptr) pngcrush_warning,
(png_voidp) NULL,
(png_malloc_ptr) pngcrush_debug_malloc,
(png_free_ptr) pngcrush_debug_free);
else
#endif /* PNG_USER_MEM_SUPPORTED */
read_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING,
(png_voidp) NULL,
(png_error_ptr) pngcrush_cexcept_error,
(png_error_ptr) pngcrush_warning);
if (read_ptr == NULL)
Throw "pngcrush could not create read_ptr";
#ifdef PNG_BENIGN_ERRORS_SUPPORTED
# if PNGCRUSH_LIBPNG_VER >= 10400
/* Allow certain errors in the input file to be handled
* as warnings.
*/
png_set_benign_errors(read_ptr, 1);
# endif
#endif
#ifdef PNG_SET_USER_LIMITS_SUPPORTED
if (no_limits == 0)
{
# if PNGCRUSH_LIBPNG_VER >= 10400
png_set_user_limits(read_ptr, 500000L, 500000L);
png_set_chunk_cache_max(read_ptr, 500);
# endif
# if PNGCRUSH_LIBPNG_VER >= 10401
png_set_chunk_malloc_max(read_ptr, 2000000L);
# endif
}
#endif /* PNG_SET_USER_LIMITS_SUPPORTED */
#if defined(PNG_MAXIMUM_INFLATE_WINDOW) && defined(PNG_OPTION_ON)
if (salvage)
{
P1(" Setting MAXIMUM_INFLATE_WINDOW\n");
png_set_option(read_ptr, PNG_MAXIMUM_INFLATE_WINDOW,
PNG_OPTION_ON);
}
#endif
#if 0
/* Use a smaller decompression buffer for speed */
png_set_compression_buffer_size(read_ptr,
(png_size_t)256);
#endif /* 0 */
/* Change the underlying color of any fully transparent pixel to black.
* Remove the alpha channel from any fully-opaque image.
* Change any all-gray image to a gray colortype.
* Reduce 16-bit image to 8-bit if possible without loss.
*/
if (trial == 0 &&
(blacken == 1 || make_gray == 1 || make_opaque == 1 ||
make_8_bit == 1 || reduce_palette == 1))
{
P1(" Examine image for possible lossless reductions\n");
png_set_read_user_transform_fn(read_ptr, pngcrush_examine_pixels_fn);
}
#ifdef PNG_READ_UNKNOWN_CHUNKS_SUPPORTED
if (last_trial == 0)
{
png_set_keep_unknown_chunks(read_ptr,
PNG_HANDLE_CHUNK_NEVER, (png_bytep) NULL, 0);
png_set_keep_unknown_chunks(read_ptr,
PNG_HANDLE_CHUNK_NEVER, chunks_to_ignore,
sizeof (chunks_to_ignore)/5);
}
#endif
if (nosave == 0)
{
#ifdef PNG_USER_MEM_SUPPORTED
if (verbose > 0)
write_ptr = png_create_write_struct_2(
PNG_LIBPNG_VER_STRING,
(png_voidp) NULL,
(png_error_ptr) pngcrush_cexcept_error,
(png_error_ptr) pngcrush_warning,
(png_voidp) NULL,
(png_malloc_ptr) pngcrush_debug_malloc,
(png_free_ptr) pngcrush_debug_free);
else
#endif
write_ptr = png_create_write_struct(
PNG_LIBPNG_VER_STRING,
(png_voidp) NULL,
(png_error_ptr) pngcrush_cexcept_error,
(png_error_ptr) NULL);
if (write_ptr == NULL)
Throw "pngcrush could not create write_ptr";
}
P1("Allocating read_info, write_info, end_info structures\n");
read_info_ptr = png_create_info_struct(read_ptr);
if (read_info_ptr == NULL)
Throw "pngcrush could not create read_info_ptr";
end_info_ptr = png_create_info_struct(read_ptr);
if (end_info_ptr == NULL)
Throw "pngcrush could not create end_info_ptr";
if (nosave == 0)
{
write_info_ptr = png_create_info_struct(write_ptr);
if (write_info_ptr == NULL)
Throw "pngcrush could not create write_info_ptr";
write_end_info_ptr = png_create_info_struct(write_ptr);
if (write_end_info_ptr == NULL)
Throw
"pngcrush could not create write_end_info_ptr";
}
P2("structures created.\n");
pngcrush_pause();
P1( "Initializing input and output streams\n");
#ifdef PNG_STDIO_SUPPORTED
png_init_io(read_ptr, fpin);
#else
png_set_read_fn(read_ptr, (png_voidp) fpin,
(png_rw_ptr) NULL);
#endif /* PNG_STDIO_SUPPORTED */
if (nosave == 0)
png_set_write_fn(write_ptr, (png_voidp) fpout,
(png_rw_ptr) pngcrush_write_png, pngcrush_flush);
P2("io has been initialized.\n");
pngcrush_pause();
#ifdef PNG_CRC_QUIET_USE
if (check_crc == 0)
{
/* We don't need to check IDAT CRC's and ADLER32 because
* they were already checked in the pngcrush_measure_idat
* function
*/
png_set_option(read_ptr, PNG_IGNORE_ADLER32,
PNG_OPTION_ON);
png_set_crc_action(read_ptr, PNG_CRC_QUIET_USE,
PNG_CRC_QUIET_USE);
}
#endif
#ifndef PNGCRUSH_CHECK_ADLER32
# ifdef PNG_IGNORE_ADLER32
if (last_trial == 0)
{
/* During trials other than the final output, avoid
* calculating CRC and ADLER32 checksums (just write
* a DEFLATE datastream)
*/
png_set_option(write_ptr, PNG_IGNORE_ADLER32,
PNG_OPTION_ON);
}
# endif
#endif
#ifdef PNG_READ_CHECK_FOR_INVALID_INDEX_SUPPORTED
/* Only run this test (new in libpng-1.5.10) during the
* 0th and last trial
*/
if ((input_color_type == 3) &&
((last_trial && reduce_palette == 0) ||
(trial == 0 && reduce_palette == 1)))
{
P1(" Check the read palette\n");
png_set_check_for_invalid_index (read_ptr, 1);
}
#endif
#ifdef PNG_WRITE_CHECK_FOR_INVALID_INDEX_SUPPORTED
if (last_trial && nosave == 0 && output_color_type == 3)
{
P1(" Check the written palette\n");
png_set_check_for_invalid_index (write_ptr, 1);
}
#endif
if (last_trial == 1)
{
#ifdef PNG_READ_UNKNOWN_CHUNKS_SUPPORTED
png_set_keep_unknown_chunks(read_ptr, PNG_HANDLE_CHUNK_ALWAYS,
(png_bytep) NULL, 0);
#endif
#ifdef PNG_WRITE_UNKNOWN_CHUNKS_SUPPORTED
if (nosave == 0)
{
if (save_apng_chunks == 1)
{
/* To do: Why use write_ptr not read_ptr here? */
png_set_keep_unknown_chunks(write_ptr,
PNG_HANDLE_CHUNK_ALWAYS,
(png_bytep) "acTL", 1);
png_set_keep_unknown_chunks(write_ptr,
PNG_HANDLE_CHUNK_ALWAYS,
(png_bytep) "fcTL", 1);
png_set_keep_unknown_chunks(write_ptr,
PNG_HANDLE_CHUNK_ALWAYS,
(png_bytep) "fdAT", 1);
}
if (found_any_chunk == 1)
png_set_keep_unknown_chunks(write_ptr,
PNG_HANDLE_CHUNK_ALWAYS,
(png_bytep) "dSIG", 1);
if (all_chunks_are_safe)
{
png_set_keep_unknown_chunks(write_ptr,
PNG_HANDLE_CHUNK_ALWAYS,
(png_bytep) NULL, 0);
printf("while saving, all_chunks_are_safe=\n");
if (save_apng_chunks == 0)
{
png_set_keep_unknown_chunks(write_ptr,
PNG_HANDLE_CHUNK_ALWAYS,
(png_bytep) "acTL", 1);
png_set_keep_unknown_chunks(write_ptr,
PNG_HANDLE_CHUNK_ALWAYS,
(png_bytep) "fcTL", 1);
png_set_keep_unknown_chunks(write_ptr,
PNG_HANDLE_CHUNK_ALWAYS,
(png_bytep) "fdAT", 1);
}
}
else
{
#if !defined(PNG_cHRM_SUPPORTED) || !defined(PNG_hIST_SUPPORTED) || \
!defined(PNG_iCCP_SUPPORTED) || !defined(PNG_sCAL_SUPPORTED) || \
!defined(PNG_pCAL_SUPPORTED) || !defined(PNG_sPLT_SUPPORTED) || \
!defined(PNG_sTER_SUPPORTED) || !defined(PNG_tIME_SUPPORTED)
png_byte chunk_name[5];
chunk_name[4] = '\0';
#endif
/* To do: Why use write_ptr not read_ptr here? */
if (keep_unknown_chunk("alla", argv) &&
keep_unknown_chunk("allb", argv))
png_set_keep_unknown_chunks(write_ptr,
PNG_HANDLE_CHUNK_IF_SAFE,
(png_bytep) NULL,
0);
else
png_set_keep_unknown_chunks(write_ptr,
PNG_HANDLE_CHUNK_NEVER,
(png_bytep) NULL,
0);
#ifndef PNG_cHRM_SUPPORTED
if (keep_unknown_chunk("cHRM", argv))
{
pngcrush_save_uint_32(chunk_name, PNG_UINT_cHRM);
png_set_keep_unknown_chunks(write_ptr,
PNG_HANDLE_CHUNK_ALWAYS,
chunk_name, 1);
}
#endif
#ifndef PNG_hIST_SUPPORTED
if (keep_unknown_chunk("hIST", argv))
{
pngcrush_save_uint_32(chunk_name, PNG_UINT_hIST);
png_set_keep_unknown_chunks(write_ptr,
PNG_HANDLE_CHUNK_ALWAYS,
chunk_name, 1);
}
#endif
#ifndef PNG_iCCP_SUPPORTED
if (keep_unknown_chunk("iCCP", argv))
{
pngcrush_save_uint_32(chunk_name, PNG_UINT_iCCP);
png_set_keep_unknown_chunks(write_ptr,
PNG_HANDLE_CHUNK_ALWAYS,
chunk_name, 1);
}
#endif
#ifndef PNG_iTXt_SUPPORTED
if (keep_unknown_chunk("iTXt", argv))
{
pngcrush_save_uint_32(chunk_name, PNG_UINT_iTXt);
png_set_keep_unknown_chunks(write_ptr,
PNG_HANDLE_CHUNK_ALWAYS,
chunk_name, 1);
}
#endif
#ifndef PNG_sCAL_SUPPORTED
if (keep_unknown_chunk("sCAL", argv))
{
pngcrush_save_uint_32(chunk_name, PNG_UINT_sCAL);
png_set_keep_unknown_chunks(write_ptr,
PNG_HANDLE_CHUNK_ALWAYS,
chunk_name, 1);
}
#endif
#ifndef PNG_pCAL_SUPPORTED
if (keep_unknown_chunk("pCAL", argv))
{
pngcrush_save_uint_32(chunk_name, PNG_UINT_pCAL);
png_set_keep_unknown_chunks(write_ptr,
PNG_HANDLE_CHUNK_ALWAYS,
chunk_name, 1);
}
#endif
#ifndef PNG_sPLT_SUPPORTED
if (keep_unknown_chunk("sPLT", argv))
{
pngcrush_save_uint_32(chunk_name, PNG_UINT_sPLT);
png_set_keep_unknown_chunks(write_ptr,
PNG_HANDLE_CHUNK_ALWAYS,
chunk_name, 1);
}
#endif
#ifndef PNG_sTER_SUPPORTED
if (keep_unknown_chunk("sTER", argv))
{
pngcrush_save_uint_32(chunk_name, PNG_UINT_sTER);
png_set_keep_unknown_chunks(write_ptr,
PNG_HANDLE_CHUNK_ALWAYS,
chunk_name, 1);
}
#endif
#ifndef PNG_tIME_SUPPORTED
if (keep_unknown_chunk("tIME", argv))
{
pngcrush_save_uint_32(chunk_name, PNG_UINT_tIME);
png_set_keep_unknown_chunks(write_ptr,
PNG_HANDLE_CHUNK_ALWAYS,
chunk_name, 1);
}
#endif
}
} /* nosave == 0 */
#endif /* PNG_WRITE_UNKNOWN_CHUNKS_SUPPORTED */
} /* last trial */
/* To do: Remove this? We already did this in measure_idats */
P1(" Reading signature bytes\n");
{
#ifdef PNGCRUSH_LOCO
png_byte mng_signature[8] =
{ 138, 77, 78, 71, 13, 10, 26, 10 };
#endif
png_byte png_signature[8] =
{ 137, 80, 78, 71, 13, 10, 26, 10 };
pngcrush_default_read_data(read_ptr, png_signature, 8);
png_set_sig_bytes(read_ptr, 8);
#ifdef PNGCRUSH_LOCO
if (!(int)(png_memcmp(mng_signature, png_signature, 8)))
{
/* Skip the MHDR */
png_permit_mng_features(read_ptr,
PNG_FLAG_MNG_FILTER_64);
png_skip_chunk(read_ptr);
input_format = 1;
}
else
#endif
if (png_sig_cmp(png_signature, 0, 8))
{
if (png_sig_cmp(png_signature, 0, 4))
png_error(read_ptr, "Not a PNG file!");
else
png_error(read_ptr,
"PNG file corrupted by ASCII conversion");
}
if (salvage && found_CgBI)
{
/* Skip the CgBI chunk */
png_skip_chunk(read_ptr);
/* iCCP and zTXt are probably unreadable
* because of the nonstandard deflate */
#ifdef PNG_WRITE_UNKNOWN_CHUNKS_SUPPORTED
png_set_keep_unknown_chunks(read_ptr,
PNG_HANDLE_CHUNK_NEVER,
(png_bytep)"iCCP", 1);
png_set_keep_unknown_chunks(read_ptr,
PNG_HANDLE_CHUNK_NEVER,
(png_bytep)"zTXt", 1);
#endif
}
}
#ifndef PNG_READ_PREMULTIPLY_ALPHA_SUPPORTED
if (premultiply)
png_error(read_ptr, "Premultiplied alpha is not supported");
#endif
P1( " Reading info struct\n");
png_read_info(read_ptr, read_info_ptr);
if (trial != 0)
{
if (make_opaque == 1)
{
P1(" Remove all-opaque alpha channel\n");
if (output_color_type == 4)
output_color_type = 0;
if (output_color_type == 6)
output_color_type = 2;
}
P1(" make_opaque= %d\n",make_opaque);
if (make_gray == 1)
{
/* Note: Take care that iCCP, sBIT, and bKGD data are not
* lost or become invalid when reducing images from
* truecolor to grayscale or when reducing the bit depth.
* (To do: test this; it's probably OK)
*/
/* To do: check bKGD color */
P1(" Encode all-gray image with a gray colortype\n");
if (output_color_type == 6)
output_color_type = 4;
if (output_color_type == 2)
output_color_type = 0;
}
P1(" make_gray= %d\n",make_gray);
if (make_8_bit == 1)
{
/* Note: Take care that sBIT and bKGD data are not
* lost or become invalid when reducing the bit depth.
* (To do: test this; it's probably OK)
*/
P1(" Reduce 16-bit image losslessly to 8-bit\n");
}
P1(" make_8_bit= %d\n",make_8_bit);
if (make_opaque != 1 && blacken == 2)
{
P1(" Blacken the fully transparent pixels\n");
png_set_read_user_transform_fn(read_ptr,
pngcrush_transform_pixels_fn);
}
P1(" make_opaque= %d\n",make_opaque);
P1(" blacken= %d\n",blacken);
if (reduce_palette == 1)
{
/* Note: Take care that sBIT and bKGD data are not
* lost or become invalid when reducing the bit depth.
* (To do: test this; it's probably OK)
*/
P1(" Reduce palette by truncating unused entries\n");
}
P1(" reduce_palette= %d\n",reduce_palette);
P1(" new plte_len = %d\n",plte_len);
}
/* { GRR added for quick %-navigation (1) */
/* Start of chunk-copying/removal code, in order:
* - IHDR
* - bKGD
* - cHRM
* - gAMA
* - sRGB
* - iCCP
* - oFFs
* - pCAL
* - pHYs
* - hIST
* - tRNS
* - PLTE
* - sBIT
* - sCAL
* - sPLT
* - sTER
* - tEXt/zTXt/iTXt
* - tIME
* - unknown chunks
*/
{
int compression_method,
filter_method;
P1( "Transferring info struct\n");
if (png_get_IHDR(read_ptr, read_info_ptr, &width, &height,
&bit_depth, &color_type, &interlace_method,
&compression_method, &filter_method))
{
int need_expand = 0;
input_color_type = color_type;
input_bit_depth = bit_depth;
if (output_color_type > 7)
{
output_color_type = input_color_type;
}
/* if (verbose > 1 && last_trial) */
if (verbose > 1 && trial == 0)
{
fprintf(STDERR, " IHDR chunk data:\n");
fprintf(STDERR,
" Width=%lu, height=%lu\n",
(unsigned long)width,
(unsigned long)height);
fprintf(STDERR, " Bit depth =%d\n",
bit_depth);
fprintf(STDERR, " Color type=%d\n",
color_type);
if (output_color_type != color_type)
fprintf(STDERR,
" Output color type=%d\n",
output_color_type);
fprintf(STDERR, " Interlace =%d\n",
interlace_method);
}
output_bit_depth = input_bit_depth;
if ((output_color_type != 3 || output_bit_depth > 8)
&& output_bit_depth >= 8
&& output_bit_depth > input_bit_depth)
need_expand = 1;
#ifdef PNG_READ_RGB_TO_GRAY_SUPPORTED
if ((color_type == 2 ||
color_type == 6 ||
color_type == 3) &&
(output_color_type == 0 ||
output_color_type == 4))
{
if (verbose > 0 && last_trial)
{
fprintf(STDERR, " Reducing truecolor "
"image to grayscale.\n");
}
#ifdef PNG_FIXED_POINT_SUPPORTED
png_set_rgb_to_gray_fixed(read_ptr, 1,
21260, 71520);
#else
png_set_rgb_to_gray(read_ptr, 1,
0.21260, 0.71520);
#endif
if (output_bit_depth < 8)
output_bit_depth = 8;
if (color_type == 3)
need_expand = 1;
}
#endif /* PNG_READ_RGB_TO_GRAY_SUPPORTED */
if (color_type != 3 && output_color_type == 3)
{
fprintf(STDERR," Cannot change to indexed color "
"(color_type 3)\n");
output_color_type = input_color_type;
}
if ((color_type == 0 || color_type == 4) &&
(output_color_type == 2
|| output_color_type == 6))
{
png_set_gray_to_rgb(read_ptr);
}
if ((color_type == 4 || color_type == 6) &&
(output_color_type != 4
&& output_color_type != 6))
{
if (verbose > 0 && last_trial)
{
fprintf(STDERR,
" Stripping existing alpha channel.\n");
}
#ifdef PNG_READ_STRIP_ALPHA_SUPPORTED
png_set_strip_alpha(read_ptr);
#endif
}
if ((output_color_type == 4
|| output_color_type == 6) && (color_type != 4
&& color_type != 6))
{
if (verbose > 0 && last_trial)
fprintf(STDERR,
" Adding an opaque alpha channel.\n");
#ifdef PNG_READ_FILLER_SUPPORTED
png_set_filler(read_ptr, (png_uint_32) 65535L,
PNG_FILLER_AFTER);
#endif
need_expand = 1;
}
if (output_color_type != 0 && output_color_type != 3 &&
output_bit_depth < 8)
output_bit_depth = 8;
if ((output_color_type == 2
|| output_color_type == 6)
&& color_type == 3)
{
if (verbose > 0 && last_trial)
fprintf(STDERR,
" Expanding indexed color file.\n");
need_expand = 1;
}
#ifdef PNG_READ_EXPAND_SUPPORTED
if (need_expand == 1)
png_set_expand(read_ptr);
#endif
#ifdef PNG_READ_PACK_SUPPORTED
if (input_bit_depth < 8)
{
png_set_packing(read_ptr);
}
if (output_color_type == 0 && output_bit_depth < 8)
{
png_color_8 true_bits;
true_bits.gray = (png_byte) (output_bit_depth);
png_set_shift(read_ptr, &true_bits);
}
#endif
if (trial > 0)
{
/* To do: have we got the right plte_len now? */
if (plte_len > 0 && output_color_type == 3 &&
force_output_bit_depth == 0)
{
if (plte_len <= 2)
force_output_bit_depth = 1;
else if (plte_len <= 4)
force_output_bit_depth = 2;
else if (plte_len <= 16)
force_output_bit_depth = 4;
else
force_output_bit_depth = 8;
}
if (make_8_bit == 1)
{
#if defined(PNG_READ_SCALE_16_TO_8_SUPPORTED) || \
defined(PNG_READ_STRIP_16_TO_8_SUPPORTED)
output_bit_depth = 8;
force_output_bit_depth = 8;
if (verbose > 0 && last_trial)
fprintf(STDERR,
" Stripping 16-bit depth to 8, trial = %d\n",
trial);
#ifdef PNG_READ_STRIP_16_TO_8_SUPPORTED
png_set_strip_16(read_ptr);
#else
#ifdef PNG_READ_SCALE_16_TO_8_SUPPORTED
png_set_scale_16(read_ptr);
#else
fprintf(STDERR,
" PNG_READ_STRIP_16_TO_8 NOT SUPPORTED\n");
#endif
#endif
#endif
}
P1("force_output_bit_depth=%d\n",force_output_bit_depth);
}
if (last_trial == 1)
{
if (save_apng_chunks == 1 || found_acTL_chunk == 1)
{
if (save_apng_chunks == 0)
{
if (verbose > 0) fprintf(STDERR,
" pngcrush will only save APNG chunks in an\n");
if (verbose > 0) fprintf(STDERR,
" output file with the \".apng\" extension\n");
}
if (input_color_type != output_color_type)
{
if (verbose > 0) fprintf(STDERR,
" Cannot save APNG chunks with a color_type\n");
if (verbose > 0) fprintf(STDERR,
" different from that of the main image.\n");
save_apng_chunks = 2;
}
if (input_bit_depth != output_bit_depth)
{
if (verbose > 0) fprintf(STDERR,
" Cannot save APNG chunks with a bit_depth\n");
if (verbose > 0) fprintf(STDERR,
" different from that of the main image.\n");
save_apng_chunks = 2;
}
if (save_apng_chunks != 1 && found_acTL_chunk == 1)
found_acTL_chunk = 2;
}
}
if (verbose > 1)
fprintf(STDERR, " Setting IHDR\n");
#ifdef PNGCRUSH_LOCO
output_format = 0;
if (do_loco)
{
if (output_color_type == 2
|| output_color_type == 6)
{
output_format = 1;
filter_method = 64;
if (nosave == 0 && last_trial == 1)
png_permit_mng_features(write_ptr,
PNG_FLAG_MNG_FILTER_64);
}
} else
filter_method = 0;
#endif
png_set_IHDR(write_ptr, write_info_ptr, width,
height, output_bit_depth,
output_color_type, interlace_method,
compression_method, filter_method);
} /* IHDR */
}
if (premultiply == 1 || premultiply == 2)
{
#ifdef PNG_READ_PREMULTIPLY_ALPHA_SUPPORTED
/* 0: not premultipled
* 1: premultiplied input (input has .pngp suffix and the
* PNGP chunk is present)
* 2: premultiplied output (output has .pngp suffix and the
* -premultiply option is present; PNGP chunk is added)
* 3: premultiplied input and output (both have .pngp suffix)
*/
P1("Calling png_set_premultiply_alpha\n");
png_set_premultiply_alpha(read_ptr,output_bit_depth);
#endif
}
/* Handle ancillary chunks */
if (last_trial == 1)
{
#if defined(PNG_READ_bKGD_SUPPORTED) && defined(PNG_WRITE_bKGD_SUPPORTED)
{
png_color_16p background;
if (!have_bkgd
&& png_get_bKGD(read_ptr, read_info_ptr,
&background))
{
if (keep_chunk("bKGD", argv))
{
if ((input_color_type == 2 ||
input_color_type == 6) &&
(output_color_type == 0 ||
output_color_type == 4))
background->gray = background->green;
png_set_bKGD(write_ptr, write_info_ptr,
background);
}
}
if (have_bkgd)
{
/* If we are reducing an RGB image to grayscale, but
* the background color isn't gray, the green channel
* is written. That's not spec-compliant. We should
* really check for a non-gray bKGD and refuse to do
* the reduction if one is present.
*/
png_color_16 backgd;
png_color_16p backgrnd = &backgd;
backgrnd->red = bkgd_red;
backgrnd->green = bkgd_green;
backgrnd->blue = bkgd_blue;
backgrnd->gray = backgrnd->green;
backgrnd->index = bkgd_index;
png_set_bKGD(write_ptr, write_info_ptr,
backgrnd);
}
}
#endif /* PNG_READ_bKGD_SUPPORTED && PNG_WRITE_bKGD_SUPPORTED */
#if defined(PNG_READ_cHRM_SUPPORTED) && defined(PNG_WRITE_cHRM_SUPPORTED)
#ifdef PNG_FIXED_POINT_SUPPORTED
{
png_fixed_point white_x, white_y, red_x, red_y,
green_x, green_y, blue_x, blue_y;
if (found_cHRM && png_get_cHRM_fixed
(read_ptr, read_info_ptr, &white_x, &white_y,
&red_x, &red_y, &green_x, &green_y, &blue_x,
&blue_y))
{
if (keep_chunk("cHRM", argv))
{
png_set_cHRM_fixed(write_ptr,
write_info_ptr, white_x,
white_y, red_x, red_y,
green_x, green_y,
blue_x, blue_y);
}
}
}
#else
{
double white_x, white_y, red_x, red_y, green_x,
green_y, blue_x, blue_y;
if (found_cHRM && png_get_cHRM
(read_ptr, read_info_ptr, &white_x, &white_y,
&red_x, &red_y, &green_x, &green_y, &blue_x,
&blue_y)) {
if (keep_chunk("cHRM", argv))
{
png_set_cHRM(write_ptr, write_info_ptr,
white_x, white_y, red_x,
red_y, green_x, green_y,
blue_x, blue_y);
}
}
}
#endif /* PNG_FIXED_POINT_SUPPORTED */
#endif /* PNG_READ_cHRM_SUPPORTED && PNG_WRITE_cHRM_SUPPORTED */
#if defined(PNG_READ_gAMA_SUPPORTED) && defined(PNG_WRITE_gAMA_SUPPORTED)
{
if (force_specified_gamma)
{
if (last_trial)
{
if (verbose > 0)
fprintf(STDERR, " Inserting gAMA chunk with "
#ifdef PNG_FIXED_POINT_SUPPORTED
"gamma=(%d/100000)\n",
#else
"gamma=%f\n",
#endif
force_specified_gamma);
}
#ifdef PNG_FIXED_POINT_SUPPORTED
png_set_gAMA_fixed(write_ptr, write_info_ptr,
(png_fixed_point)
force_specified_gamma);
file_gamma =
(png_fixed_point) force_specified_gamma;
#else
png_set_gAMA(write_ptr, write_info_ptr,
force_specified_gamma);
file_gamma = force_specified_gamma;
#endif
}
#ifdef PNG_FIXED_POINT_SUPPORTED
else if (found_gAMA && png_get_gAMA_fixed
(read_ptr, read_info_ptr, &file_gamma))
#else
else if (found_gAMA && png_get_gAMA
(read_ptr, read_info_ptr, &file_gamma))
#endif
{
if (keep_chunk("gAMA", argv))
{
if (image_specified_gamma)
file_gamma = image_specified_gamma;
if (verbose > 1 && last_trial)
#ifdef PNG_FIXED_POINT_SUPPORTED
fprintf(STDERR, " gamma=(%d/100000)\n",
(int) file_gamma);
if (double_gamma)
file_gamma += file_gamma;
png_set_gAMA_fixed(write_ptr, write_info_ptr,
file_gamma);
#else
fprintf(STDERR, " gamma=%f\n",
file_gamma);
if (double_gamma)
file_gamma += file_gamma;
png_set_gAMA(write_ptr, write_info_ptr,
file_gamma);
#endif
}
}
else if (specified_gamma)
{
if (last_trial)
{
if (verbose > 0)
fprintf(STDERR, " Inserting gAMA chunk with "
#ifdef PNG_FIXED_POINT_SUPPORTED
"gamma=(%d/100000)\n",
#else
"gamma=%f\n",
#endif
specified_gamma);
}
#ifdef PNG_FIXED_POINT_SUPPORTED
png_set_gAMA_fixed(write_ptr, write_info_ptr,
specified_gamma);
file_gamma = (png_fixed_point) specified_gamma;
#else
png_set_gAMA(write_ptr, write_info_ptr,
specified_gamma);
file_gamma = specified_gamma;
#endif
}
}
#endif /* PNG_READ_gAMA_SUPPORTED && PNG_WRITE_gAMA_SUPPORTED */
#if defined(PNG_READ_sRGB_SUPPORTED) && defined(PNG_WRITE_sRGB_SUPPORTED)
{
int file_intent;
if (png_get_sRGB
(read_ptr, read_info_ptr, &file_intent))
{
if (keep_chunk("sRGB", argv))
{
png_set_sRGB(write_ptr, write_info_ptr,
file_intent);
intent = file_intent;
}
}
else if (found_sRGB)
{
#ifdef PNG_gAMA_SUPPORTED
# ifdef PNG_FIXED_POINT_SUPPORTED
if (file_gamma >= 45000L && file_gamma <= 46000L)
# else
if (file_gamma >= 0.45000 && file_gamma <= 0.46000)
# endif
{
if (verbose > 0 && last_trial)
fprintf(STDERR,
" Inserting sRGB chunk with intent=%d\n",
intent);
png_set_sRGB(write_ptr, write_info_ptr,
intent);
}
else if (file_gamma != 0)
{
if (verbose > 0 && last_trial)
{
fprintf(STDERR, " Ignoring sRGB request; "
# ifdef PNG_FIXED_POINT_SUPPORTED
"gamma=(%lu/100000)"
" is not approx. 0.455\n",
(unsigned long)file_gamma);
# else
"gamma=%f"
" is not approx. 0.455\n",
file_gamma);
# endif
}
}
#endif /* PNG_gAMA_SUPPORTED */
}
}
#endif /* PNG_READ_sRGB_SUPPORTED && PNG_WRITE_sRGB_SUPPORTED */
#if defined(PNG_READ_iCCP_SUPPORTED) && defined(PNG_WRITE_iCCP_SUPPORTED)
if (intent < 0) { /* ignore iCCP if sRGB is being written */
png_charp name;
#if PNGCRUSH_LIBPNG_VER < 10500
png_charp profile;
#else
png_bytep profile;
#endif
png_uint_32 proflen;
int compression_method;
if (found_iCCP && png_get_iCCP
(read_ptr, read_info_ptr, &name,
&compression_method, &profile, &proflen))
{
P1("Got iCCP chunk, proflen=%lu\n",
(unsigned long)proflen);
if (iccp_length)
P0("Will not replace existing iCCP chunk.\n");
if (keep_chunk("iCCP", argv))
png_set_iCCP(write_ptr, write_info_ptr,
#if PNGCRUSH_LIBPNG_VER < 10500
name,
#else
(png_const_charp) name,
#endif
compression_method, profile,
proflen);
}
#ifdef PNG_iCCP_SUPPORTED
else if (iccp_length)
{
png_set_iCCP(write_ptr, write_info_ptr, iccp_name,
0,
#if PNGCRUSH_LIBPNG_VER < 10500
iccp_text,
#else
(png_const_bytep) iccp_text,
#endif
iccp_length);
P1("Wrote iCCP chunk, proflen=%d\n", iccp_length);
}
#endif /* PNG_iCCP_SUPPORTED */
}
#endif /* PNG_READ_iCCP_SUPPORTED && PNG_WRITE_iCCP_SUPPORTED */
#if defined(PNG_READ_oFFs_SUPPORTED) && defined(PNG_WRITE_oFFs_SUPPORTED)
{
png_int_32 offset_x, offset_y;
int unit_type;
if (png_get_oFFs
(read_ptr, read_info_ptr, &offset_x, &offset_y,
&unit_type)) {
if (offset_x == 0 && offset_y == 0)
{
if (verbose > 0 && last_trial)
fprintf(STDERR,
" Deleting useless oFFs 0 0 chunk\n");
}
else
{
if (keep_chunk("oFFs", argv))
png_set_oFFs(write_ptr, write_info_ptr,
offset_x, offset_y,
unit_type);
}
}
}
#endif /* PNG_READ_oFFs_SUPPORTED && PNG_WRITE_oFFs_SUPPORTED */
#if defined(PNG_READ_pCAL_SUPPORTED) && defined(PNG_WRITE_pCAL_SUPPORTED)
{
png_charp purpose, units;
png_charpp params;
png_int_32 X0, X1;
int type, nparams;
if (png_get_pCAL
(read_ptr, read_info_ptr, &purpose, &X0, &X1,
&type, &nparams, &units, ¶ms))
{
if (keep_chunk("pCAL", argv))
png_set_pCAL(write_ptr, write_info_ptr,
purpose, X0, X1, type, nparams,
units, params);
}
}
#endif /* pCAL_SUPPORTED */
#if defined(PNG_READ_pHYs_SUPPORTED) && defined(PNG_WRITE_pHYs_SUPPORTED)
{
png_uint_32 res_x, res_y;
int unit_type;
if (resolution == 0)
{
if (png_get_pHYs
(read_ptr, read_info_ptr, &res_x, &res_y,
&unit_type))
{
if (res_x == 0 && res_y == 0)
{
if (verbose > 0 && last_trial)
fprintf(STDERR,
" Deleting useless pHYs 0 0 chunk\n");
}
else
{
if (keep_chunk("pHYs", argv))
png_set_pHYs(write_ptr, write_info_ptr,
res_x, res_y, unit_type);
}
}
} else {
unit_type = 1;
res_x = res_y =
(png_uint_32) ((resolution / .0254 + 0.5));
png_set_pHYs(write_ptr, write_info_ptr, res_x,
res_y, unit_type);
if (verbose > 0 && last_trial)
fprintf(STDERR, " Added pHYs %lu %lu 1 chunk\n",
(unsigned long)res_x,
(unsigned long)res_y);
}
}
#endif
#if defined(PNG_READ_hIST_SUPPORTED) && defined(PNG_WRITE_hIST_SUPPORTED)
{
png_uint_16p hist;
if (png_get_hIST(read_ptr, read_info_ptr, &hist))
{
if (keep_chunk("hIST", argv))
png_set_hIST(write_ptr, write_info_ptr, hist);
}
}
#endif /* hIST_SUPPORTED */
#if defined(PNG_READ_tRNS_SUPPORTED) && defined(PNG_WRITE_tRNS_SUPPORTED)
{
if (png_get_tRNS
(read_ptr, read_info_ptr, &trans, &num_trans,
&trans_values))
{
if (verbose > 1 && last_trial)
fprintf(STDERR,
" Found tRNS chunk in input file.\n");
if (have_trns == 1)
{
P0(" Will not overwrite existing tRNS chunk.\n");
}
if (keep_chunk("tRNS", argv))
{
int last_nonmax = -1;
trns_red = trans_values->red;
trns_green = trans_values->green;
trns_blue = trans_values->blue;
trns_gray = trans_values->gray;
if (output_color_type == 3)
{
for (ia = 0; ia < num_trans; ia++)
trns_array[ia] = trans[ia];
for (; ia < 256; ia++)
trns_array[ia] = 255;
for (ia = 0; ia < 256; ia++)
{
if (trns_array[ia] != 255)
last_nonmax = ia;
}
if (last_trial && verbose > 0)
{
if (last_nonmax < 0)
fprintf(STDERR, " Deleting "
"all-opaque tRNS chunk.\n");
else if (last_nonmax + 1 < num_trans)
fprintf(STDERR,
" Truncating trailing opaque "
"entries from tRNS chunk.\n");
}
num_trans = last_nonmax + 1;
}
else
{
/* color type is 0 or 2 */
if (input_bit_depth == 16 &&
output_bit_depth == 8)
{
/* zero out the high byte */
trans_values->red &= 0x00ff;
trans_values->green &= 0x00ff;
trans_values->blue &= 0x00ff;
trans_values->gray &= 0x00ff;
}
}
if (verbose > 1)
fprintf(STDERR,
" png_set_tRNS, num_trans=%d\n",
num_trans);
if (output_color_type < 3 || num_trans)
png_set_tRNS(write_ptr, write_info_ptr,
trans, num_trans,
trans_values);
}
}
else if (have_trns == 1)
{
/* will not overwrite existing trns data */
png_color_16 trans_data;
png_byte index_data = (png_byte) trns_index;
num_trans = index_data + 1;
if (verbose > 1)
fprintf(STDERR, "Have_tRNS, num_trans=%d\n",
num_trans);
if (output_color_type == 3)
{
trans_values = NULL;
for (ia = 0; ia < num_trans; ia++)
trns_array[ia] = trans_in[ia];
for (; ia < 256; ia++)
trns_array[ia] = 255;
} else {
for (ia = 0; ia < 256; ia++)
trns_array[ia] = 255;
trns_array[index_data] = 0;
trans_data.index = index_data;
trans_data.red = trns_red;
trans_data.green = trns_green;
trans_data.blue = trns_blue;
trans_data.gray = trns_gray;
trans_values = &trans_data;
}
P0(" Adding a tRNS chunk\n");
png_set_tRNS(write_ptr, write_info_ptr, trns_array,
num_trans, trans_values);
}
else
{
for (ia = 0; ia < 256; ia++)
trns_array[ia] = 255;
}
if (verbose > 1 && last_trial)
{
int last = -1;
for (ia = 0; ia < num_palette; ia++)
if (trns_array[ia] != 255)
last = ia;
if (last >= 0) {
fprintf(STDERR, " Transparency:\n");
if (output_color_type == 3)
for (ia = 0; ia < num_palette; ia++)
fprintf(STDERR, " %4d %4d\n", ia,
trns_array[ia]);
else if (output_color_type == 0)
fprintf(STDERR, " %d\n", trns_gray);
else if (output_color_type == 2)
fprintf(STDERR, " %d %d %d\n",
trns_red, trns_green, trns_blue);
}
}
}
#endif /* PNG_READ_tRNS_SUPPORTED && PNG_WRITE_tRNS_SUPPORTED */
} /* End of ancillary chunk handling */
if (png_get_PLTE
(read_ptr, read_info_ptr, &palette, &num_palette))
{
if (plte_len > 0)
num_palette = plte_len;
if (do_pplt)
{
fprintf(STDERR,"PPLT: %s\n", pplt_string);
fprintf(STDERR,"Sorry, PPLT is not implemented yet.\n");
}
if (nosave == 0)
{
if (output_color_type == 3)
png_set_PLTE(write_ptr, write_info_ptr, palette,
num_palette);
else if (keep_chunk("PLTE", argv))
png_set_PLTE(write_ptr, write_info_ptr, palette,
num_palette);
}
if (verbose > 1 && last_trial)
{
png_colorp p = palette;
fprintf(STDERR, " Palette:\n");
fprintf(STDERR,
" I R G B ( color ) A\n");
for (i = 0; i < num_palette; i++)
{
fprintf(STDERR,
" %4d %4d %4d %4d (#%2.2x%2.2x%2.2x) %4d\n",
i, p->red, p->green, p->blue, p->red,
p->green, p->blue, trns_array[i]);
p++;
}
}
}
/* Handle ancillary chunks */
if (last_trial == 1)
{
#if defined(PNG_READ_sBIT_SUPPORTED) && defined(PNG_WRITE_sBIT_SUPPORTED)
{
png_color_8p sig_bit;
/* If we are reducing a truecolor PNG to grayscale, and the
* RGB sBIT values aren't identical, we'll lose sBIT info.
*/
if (png_get_sBIT(read_ptr, read_info_ptr, &sig_bit))
{
if (keep_chunk("sBIT", argv))
{
if ((input_color_type == 0
|| input_color_type == 4)
&& (output_color_type == 2
|| output_color_type == 6
|| output_color_type == 3))
sig_bit->red = sig_bit->green =
sig_bit->blue = sig_bit->gray;
if ((input_color_type == 2
|| input_color_type == 6
|| output_color_type == 3)
&& (output_color_type == 0
|| output_color_type == 4))
sig_bit->gray = sig_bit->green;
if ((input_color_type == 0
|| input_color_type == 2)
&& (output_color_type == 4
|| output_color_type == 6))
sig_bit->alpha = 1;
if (nosave == 0)
png_set_sBIT(write_ptr, write_info_ptr,
sig_bit);
}
}
}
#endif /* PNG_READ_sBIT_SUPPORTED)&& PNG_WRITE_sBIT_SUPPORTED */
#ifdef PNG_sCAL_SUPPORTED
# ifdef PNG_FLOATING_POINT_SUPPORTED
{
int unit;
double scal_width, scal_height;
if (png_get_sCAL
(read_ptr, read_info_ptr, &unit, &scal_width,
&scal_height))
{
png_set_sCAL(write_ptr, write_info_ptr, unit,
scal_width, scal_height);
}
}
# else
# ifdef PNG_FIXED_POINT_SUPPORTED
{
int unit;
png_charp scal_width, scal_height;
if (png_get_sCAL_s
(read_ptr, read_info_ptr, &unit, &scal_width,
&scal_height))
{
if (keep_chunk("sCAL", argv))
png_set_sCAL_s(write_ptr, write_info_ptr, unit,
scal_width, scal_height);
}
}
# endif
# endif /* PNG_FLOATING_POINT_SUPPORTED */
#endif /* PNG_sCAL_SUPPORTED */
#ifdef PNG_sPLT_SUPPORTED
{
png_sPLT_tp entries;
int num_entries;
num_entries =
(int) png_get_sPLT(read_ptr, read_info_ptr,
&entries);
if (num_entries)
{
if (keep_chunk("sPLT", argv))
png_set_sPLT(write_ptr, write_info_ptr,
entries, num_entries);
}
}
#endif
#ifdef PNG_TEXT_SUPPORTED
{
png_textp text_ptr;
int num_text = 0;
if (png_get_text
(read_ptr, read_info_ptr, &text_ptr, &num_text) > 0
|| text_inputs)
{
int ntext;
P1( "Handling %d tEXt/zTXt chunks before IDAT\n",
num_text);
if (verbose > 1 && last_trial && num_text > 0)
{
for (ntext = 0; ntext < num_text; ntext++)
{
fprintf(STDERR, "%d %s", ntext,
text_ptr[ntext].key);
if (text_ptr[ntext].text_length)
fprintf(STDERR, ": %s\n",
text_ptr[ntext].text);
#ifdef PNG_iTXt_SUPPORTED
else if (text_ptr[ntext].itxt_length)
{
fprintf(STDERR, " (%s: %s): \n",
text_ptr[ntext].lang,
text_ptr[ntext].lang_key);
fprintf(STDERR, "%s\n",
text_ptr[ntext].text);
}
#endif
else
fprintf(STDERR, "\n");
}
}
if (num_text > 0)
{
if (keep_chunk("text", argv))
{
int num_to_write = num_text;
for (ntext = 0; ntext < num_text; ntext++)
{
if (last_trial)
P2("Text chunk before IDAT, "
"compression=%d\n",
text_ptr[ntext].compression);
if (text_ptr[ntext].compression ==
PNG_TEXT_COMPRESSION_NONE) {
if (!keep_chunk("tEXt", argv))
{
text_ptr[ntext].key[0] = '\0';
num_to_write--;
}
}
if (text_ptr[ntext].compression ==
PNG_TEXT_COMPRESSION_zTXt)
{
if (!keep_chunk("zTXt", argv))
{
text_ptr[ntext].key[0] = '\0';
num_to_write--;
}
}
#ifdef PNG_iTXt_SUPPORTED
if (text_ptr[ntext].compression ==
PNG_ITXT_COMPRESSION_NONE
|| text_ptr[ntext].compression ==
PNG_ITXT_COMPRESSION_zTXt)
{
if (!keep_chunk("iTXt", argv))
{
text_ptr[ntext].key[0] = '\0';
num_to_write--;
}
}
#endif
}
if (num_to_write > 0)
png_set_text(write_ptr, write_info_ptr,
text_ptr, num_text);
}
}
for (ntext = 0; ntext < text_inputs; ntext++)
{
if (text_where[ntext] == 1)
{
png_textp added_text;
added_text = (png_textp) png_malloc(write_ptr,
(png_uint_32) sizeof(png_text));
added_text[0].key = &text_keyword[ntext * 80];
#ifdef PNG_iTXt_SUPPORTED
added_text[0].lang = &text_lang[ntext * 80];
added_text[0].lang_key =
&text_lang_key[ntext * 80];
#endif
added_text[0].text =
&text_text[ntext * STR_BUF_SIZE];
added_text[0].compression =
text_compression[ntext];
png_set_text(write_ptr, write_info_ptr,
added_text, 1);
if (verbose > 0 && last_trial)
{
if (added_text[0].compression < 0)
fprintf(STDERR,
" Added a tEXt chunk.\n");
else if (added_text[0].compression == 0)
fprintf(STDERR,
" Added a zTXt chunk.\n");
#ifdef PNG_iTXt_SUPPORTED
else
fprintf(STDERR,
" Added a%scompressed iTXt chunk"
".\n", (added_text[0].compression == 1)?
"n un" : " ");
#endif
}
png_free(write_ptr, added_text);
added_text = (png_textp) NULL;
}
}
}
}
#endif /* defined(PNG_TEXT_SUPPORTED) */
#if defined(PNG_READ_tIME_SUPPORTED) && defined(PNG_WRITE_tIME_SUPPORTED)
{
png_timep mod_time;
if (png_get_tIME(read_ptr, read_info_ptr, &mod_time))
{
if (keep_chunk("tIME", argv))
png_set_tIME(write_ptr, write_info_ptr, mod_time);
}
}
#endif
#ifdef PNG_WRITE_UNKNOWN_CHUNKS_SUPPORTED
/* This section handles pCAL and tIME (at least, in default
* build), gIFx/gIFg/gIFt, private Fireworks chunks, etc. */
{
png_unknown_chunkp unknowns; /* allocated by libpng */
int num_unknowns;
num_unknowns = (int)png_get_unknown_chunks(read_ptr,
read_info_ptr, &unknowns);
if (nosave == 0 && ster_mode >= 0)
{
/* Add sTER chunk */
png_unknown_chunkp ster;
P1("Handling sTER as unknown chunk %d\n", num_unknowns);
ster = (png_unknown_chunk*)png_malloc(read_ptr,
(png_uint_32) sizeof(png_unknown_chunk));
png_memcpy((char *)ster[0].name, "sTER",5);
ster[0].size = 1;
ster[0].data = (png_byte*)png_malloc(read_ptr, 1);
ster[0].data[0] = (png_byte)ster_mode;
png_set_unknown_chunks(read_ptr, read_info_ptr,
ster, 1);
png_free(read_ptr,ster[0].data);
png_free(read_ptr,ster);
num_unknowns++;
}
#ifndef PNG_HAVE_IHDR
#define PNG_HAVE_IHDR 0x01
#endif
if (ster_mode >= 0)
png_set_unknown_chunk_location(read_ptr, read_info_ptr,
num_unknowns - 1, (int)PNG_HAVE_IHDR);
P1("Found %d unknown chunks\n", num_unknowns);
if (nosave == 0 && num_unknowns)
{
png_unknown_chunkp unknowns_keep; /* allocated by us */
int num_unknowns_keep;
unknowns_keep = (png_unknown_chunk*)png_malloc(
write_ptr, (png_uint_32) num_unknowns
*sizeof(png_unknown_chunk));
P1("malloc for %d unknown chunks\n", num_unknowns);
num_unknowns_keep = 0;
/* make an array of only those chunks we want to keep */
for (i = 0; i < num_unknowns; i++)
{
P1("Handling unknown chunk %d %s\n", i,
(char *)unknowns[i].name);
/* not EBCDIC-safe, but neither is keep_chunks(): */
P2(" unknown[%d] = %s (%lu bytes, location %d)\n",
i, unknowns[i].name,
(unsigned long)unknowns[i].size,
unknowns[i].location);
if (keep_chunk((char *)unknowns[i].name, argv))
{
png_memcpy(&unknowns_keep[num_unknowns_keep],
&unknowns[i], sizeof(png_unknown_chunk));
++num_unknowns_keep;
}
}
P1("Keeping %d unknown chunks\n", num_unknowns_keep);
png_set_unknown_chunks(write_ptr, write_info_ptr,
unknowns_keep, num_unknowns_keep);
/* relevant location bits:
* (1) !PNG_HAVE_PLTE && !PNG_HAVE_IDAT (before PLTE)
* (2) PNG_HAVE_PLTE && !PNG_HAVE_IDAT (between)
* (3) PNG_AFTER_IDAT (after IDAT)
* PNG_HAVE_PLTE = 0x02
* PNG_HAVE_IDAT = 0x04
* PNG_AFTER_IDAT = 0x08
*/
for (i = 0; i < num_unknowns_keep; i++)
{
png_set_unknown_chunk_location(write_ptr,
write_info_ptr, i,
(int)unknowns_keep[i].location);
}
/* png_set_unknown_chunks() makes own copy, so nuke
* ours */
png_free(write_ptr, unknowns_keep);
}
}
P1( "Finished handling ancillary chunks after IDAT\n");
#endif /* PNG_WRITE_UNKNOWN_CHUNKS_SUPPORTED */
} /* End of ancillary chunk handling */
/* } GRR added for quick %-navigation (1) */
/*
* Would be useful to have a libpng fix, that either exports
* png_read_transform_info() or provides a generic API that
* can set any png_ptr->flag, or, simpler, provides an API
* to set the PNG_FLAG_ROW_INIT flag.
*
* Starting in libpng-1.5.6beta06, png_read_update_info()
* does not check the PNG_FLAG_ROW_INIT flag and does not
* initialize the row or issue a warning.
*
*/
#ifdef PNGCRUSH_H
png_read_transform_info(read_ptr, read_info_ptr);
#else
/* Some pngcrush capabilities are lacking when the system
* libpng is used instead of the one bundled with pngcrush
*
* To do: list those capabilities here
*/
/* pngcrush fails to read interlaced PNGs properly
* when png_read_update_info() is called here.
*/
/* png_read_update_info(read_ptr, read_info_ptr); */
/* Workaround is to multiply rowbytes by 8/bit_depth
* to allow for unpacking, wherever we allocate a
* row buffer. This results in too large a value for
* rowbytes under some conditions, e.g., when increasing
* a sub-8-bit file to RGBA, but this is rare and harmless.
*/
#endif
/* This is the default case (nosave == 1 -> perf-testing
only) */
if (nosave == 0)
{
if (filter_type == 0)
png_set_filter(write_ptr, 0, PNG_FILTER_NONE);
else if (filter_type == 1)
png_set_filter(write_ptr, 0, PNG_FILTER_SUB);
else if (filter_type == 2)
png_set_filter(write_ptr, 0, PNG_FILTER_UP);
else if (filter_type == 3)
png_set_filter(write_ptr, 0, PNG_FILTER_AVG);
else if (filter_type == 4)
png_set_filter(write_ptr, 0, PNG_FILTER_PAETH);
else if (filter_type == 5)
png_set_filter(write_ptr, 0, PNG_ALL_FILTERS);
else if (filter_type == 6) /* speedy */
png_set_filter(write_ptr, 0, PNG_FILTER_NONE |
PNG_FILTER_SUB | PNG_FILTER_UP);
else
png_set_filter(write_ptr, 0, PNG_FILTER_NONE);
#ifdef PNGCRUSH_LOCO
if (do_loco) {
png_byte buff[30];
const png_byte png_MHDR[5] = { 77, 72, 68, 82, '\0' };
png_byte mng_signature[8] =
{ 138, 77, 78, 71, 13, 10, 26, 10 };
/* write the MNG 8-byte signature */
if (outname[strlen(outname) - 3] == 'p')
pngcrush_warning(read_ptr,
" Writing a MNG file with a .png extension");
pngcrush_write_png(write_ptr, &mng_signature[0],
(png_size_t) 8);
png_set_sig_bytes(write_ptr, 8);
/* Write a MHDR chunk */
buff[0] = (png_byte) ((width >> 24) & 0xff);
buff[1] = (png_byte) ((width >> 16) & 0xff);
buff[2] = (png_byte) ((width >> 8) & 0xff);
buff[3] = (png_byte) ((width) & 0xff);
buff[4] = (png_byte) ((height >> 24) & 0xff);
buff[5] = (png_byte) ((height >> 16) & 0xff);
buff[6] = (png_byte) ((height >> 8) & 0xff);
buff[7] = (png_byte) ((height) & 0xff);
for (i = 8; i < 27; i++)
buff[i] = 0x00;
buff[15] = 2; /* layer count */
buff[19] = 1; /* frame count */
if (output_color_type == 6)
buff[27] = 0x09; /* profile: MNG-VLC with trans. */
else
buff[27] = 0x01; /* profile: MNG-VLC */
png_write_chunk(write_ptr, (png_bytep) png_MHDR,
buff, (png_size_t) 28);
}
#endif /* PNGCRUSH_LOCO */
pngcrush_pause();
if (found_CgBI)
{
pngcrush_warning(read_ptr,
"Cannot read Xcode CgBI PNG");
}
P1( "\nWriting info struct\n");
if (copy_idat == 0)
{
#if 0 /* doesn't work; compression level has to be the same as in IDAT */
/* if zTXt other compressed chunk */
png_set_compression_level(write_ptr, 9);
png_set_compression_window_bits(write_ptr, 15);
#endif /* 0 */
pngcrush_pause();
{
png_uint_32 zbuf_size;
png_uint_32 required_window;
int channels = 0;
png_set_compression_strategy(write_ptr,
z_strategy);
png_set_compression_mem_level(write_ptr,
compression_mem_level);
if (output_color_type == 0)
channels = 1;
if (output_color_type == 2)
channels = 3;
if (output_color_type == 3)
channels = 1;
if (output_color_type == 4)
channels = 2;
if (output_color_type == 6)
channels = 4;
/* This method was copied from libpng to find maximum
* data size. Only return sizes up to the maximum of
* a png_uint_32, by limiting the width and height used
* to 15 bits.
*/
png_uint_32 rowbytes;
png_uint_32 h = height;
/* FIX THIS, does not work with libpng-1.7.0
* because info_ptr->bit_depth has not been
* updated yet.
*/
rowbytes = png_get_rowbytes(read_ptr, read_info_ptr);
#ifndef PNGCRUSH_H
/* We must do this because we could not call
* png_read_update_info().
*/
if (input_bit_depth < 8)
rowbytes *= 8/input_bit_depth;
#endif
if (rowbytes < 16384 && h < 16384)
{
if (rowbytes * h < 16384)
{
if (interlace_method)
{
/* Interlacing makes the uncompressed data
* larger because of the replication of both
* the filter byte and the padding to a byte
* boundary.
*/
png_uint_32 w = width;
unsigned int pd = channels * output_bit_depth;
#if (PNGCRUSH_LIBPNG_VER < 10400)
png_size_t cb_base;
#else
png_alloc_size_t cb_base;
#endif
int interlace_pass;
for (cb_base=0, interlace_pass=0;
interlace_pass<=6; ++interlace_pass)
{
png_uint_32 pw = PNG_PASS_COLS(w,
interlace_pass);
if (pw > 0)
cb_base += (PNGCRUSH_ROWBYTES(pd, pw)+1) *
PNG_PASS_ROWS(h, interlace_pass);
}
max_bytes = cb_base;
}
else
max_bytes = (rowbytes+1) * h;
}
else
max_bytes = 0x3fffffffU;
}
else
max_bytes = 0x3fffffffU;
required_window = (png_uint_32) (max_bytes + 262);
zbuf_size =
png_get_compression_buffer_size(write_ptr);
/* reinitialize zbuf - compression buffer */
if (zbuf_size != max_idat_size)
{
png_uint_32 max_possible_size =
required_window;
if (max_possible_size > max_idat_size)
max_possible_size = max_idat_size;
P2("reinitializing write zbuf to %lu.\n",
(unsigned long)max_possible_size);
png_set_compression_buffer_size(write_ptr,
max_possible_size);
}
if (required_window <= 512)
compression_window = 9;
else if (required_window <= 1024)
compression_window = 10;
else if (required_window <= 2048)
compression_window = 11;
else if (required_window <= 4096)
compression_window = 12;
else if (required_window <= 8192)
compression_window = 13;
else if (required_window <= 16384)
compression_window = 14;
else
compression_window = 15;
if (compression_window > default_compression_window
|| force_compression_window)
compression_window =
default_compression_window;
if (verbose > 1 && last_trial
&& (compression_window != 15
|| force_compression_window))
fprintf(STDERR,
" Compression window for output= %d\n",
1 << compression_window);
png_set_compression_window_bits(write_ptr,
compression_window);
}
png_set_compression_level(write_ptr, zlib_level);
} /* copy_idat */
png_write_info(write_ptr, write_info_ptr);
P1( "\nWrote info struct\n");
if (copy_idat == 1)
{
/* No recompress, just copy IDATs. */
png_set_compression_buffer_size(write_ptr,
MAX_IDAT_SIZE);
}
#ifdef PNG_WRITE_PACK_SUPPORTED
if (output_bit_depth < 8)
{
if (output_color_type == 0)
{
png_color_8 true_bits;
true_bits.gray = (png_byte) (output_bit_depth);
png_set_shift(write_ptr, &true_bits);
}
png_set_packing(write_ptr);
}
#endif
} /* no save */
#ifdef PNGCRUSH_MULTIPLE_ROWS
rows_at_a_time = max_rows_at_a_time;
if (rows_at_a_time == 0 || rows_at_a_time < height)
rows_at_a_time = height;
#endif
#ifndef PNGCRUSH_LARGE
{
png_uint_32 rowbytes_s;
png_uint_32 rowbytes;
rowbytes = png_get_rowbytes(read_ptr, read_info_ptr);
#ifndef PNGCRUSH_H
if (input_bit_depth < 8)
rowbytes *= 8/input_bit_depth;
#endif
P2("rowbytes = %lud\n",rowbytes;
rowbytes_s = (png_size_t) rowbytes;
if (rowbytes == (png_uint_32) rowbytes_s)
# ifdef PNGCRUSH_MULTIPLE_ROWS
row_buf =
png_malloc(read_ptr,
rows_at_a_time * rowbytes + 64);
# else
row_buf = png_malloc(read_ptr, rowbytes + 64);
# endif
else
row_buf = NULL;
}
#else /* PNGCRUSH_LARGE */
{
png_uint_32 read_row_length, write_row_length;
read_row_length =
(png_uint_32) (png_get_rowbytes
(read_ptr, read_info_ptr));
write_row_length =
(png_uint_32) (png_get_rowbytes
(write_ptr, write_info_ptr));
row_length =
read_row_length >
write_row_length ? read_row_length :
write_row_length;
#ifndef PNGCRUSH_H
/* We must do this because we could not call
* png_read_update_info().
*/
if (input_bit_depth < 8)
row_length *= 8/input_bit_depth;
#endif
# ifdef PNGCRUSH_MULTIPLE_ROWS
row_buf =
(png_bytep) png_malloc(read_ptr,
rows_at_a_time *
row_length + 64);
# else
row_buf =
(png_bytep) png_malloc(read_ptr, row_length + 64);
# endif
}
#endif /* PNGCRUSH_LARGE */
P2(" row_buf = %p\n",row_buf);
if (row_buf == NULL)
png_error(read_ptr,
"Insufficient memory to allocate row buffer");
{
/* Check for sufficient memory: we need 2*zlib_window and,
* if filter_type == 5, 4*rowbytes in separate allocations.
* If it's not enough we can drop the "average" filter and
* we can reduce the zlib_window for writing. We can't
* change the input zlib_window because the input file
* might have used the full 32K sliding window. (To do)
*/
}
P2("allocated rowbuf.\n");
#ifdef PNGCRUSH_MULTIPLE_ROWS
row_pointers = (png_bytepp) png_malloc(read_ptr,
rows_at_a_time *
sizeof(png_bytepp));
P2("allocated row_pointers.\n");
for (i = 0; i < rows_at_a_time; i++)
row_pointers[i] = row_buf + i * row_length;
#endif
pngcrush_pause();
num_pass = png_set_interlace_handling(read_ptr);
if (nosave == 0)
png_set_interlace_handling(write_ptr);
/* START_STOP */
for (pass = 0; pass < num_pass; pass++)
{
#ifdef PNGCRUSH_MULTIPLE_ROWS
png_uint_32 num_rows;
#endif
P1( "\nBegin interlace pass %d\n", pass);
#ifdef PNGCRUSH_MULTIPLE_ROWS
num_rows = rows_at_a_time;
for (y = 0; y < height; y += rows_at_a_time)
#else
for (y = 0; y < height; y++)
#endif
{
#if PNGCRUSH_TIMERS > 0
if (verbose >= 0)
{
pngcrush_timer_stop(PNGCRUSH_TIMER_MISC);
pngcrush_timer_start(PNGCRUSH_TIMER_DECODE);
}
#endif
#ifdef PNGCRUSH_MULTIPLE_ROWS
if (y + num_rows > height)
num_rows = height - y;
# ifdef BLOCKY_DEINTERLACE
png_read_rows(read_ptr, (png_bytepp) NULL,
row_pointers, num_rows);
# else /* SPARKLE */
png_read_rows(read_ptr, row_pointers,
(png_bytepp) NULL, num_rows);
# endif
#else
# ifdef BLOCKY_DEINTERLACE
png_read_row(read_ptr, row_buf, (png_bytep) NULL);
# else /* SPARKLE */
png_read_row(read_ptr, (png_bytep) NULL, row_buf);
# endif
#endif
if (nosave == 0)
{
#if PNGCRUSH_TIMERS > 0
if (verbose >= 0)
{
pngcrush_timer_stop(PNGCRUSH_TIMER_DECODE);
pngcrush_timer_start(PNGCRUSH_TIMER_ENCODE);
}
#endif
#ifdef PNGCRUSH_MULTIPLE_ROWS
/* To do: zero the padding bits */
png_write_rows(write_ptr, row_pointers,
num_rows);
#else
/* To do: zero the padding bits */
png_write_row(write_ptr, row_buf);
#endif
}
#if PNGCRUSH_TIMERS > 0
if (verbose >= 0)
{
if (nosave == 0)
pngcrush_timer_stop(PNGCRUSH_TIMER_ENCODE);
else
pngcrush_timer_stop(PNGCRUSH_TIMER_DECODE);
pngcrush_timer_start(PNGCRUSH_TIMER_MISC);
}
#endif
/* Bail if byte count exceeds best so far */
if (bail == 0 && trial != last_method &&
pngcrush_write_byte_count >
pngcrush_best_byte_count)
{
png_write_flush(write_ptr);
break;
}
}
P2( "End interlace pass %d\n\n", pass);
if (bail == 0 && trial != last_method &&
pngcrush_write_byte_count >
pngcrush_best_byte_count)
break;
}
if (color_type == 3)
{
if (trial == 0 && reduce_palette == 1)
{
int palette_length;
palette_length = plte_len;
P1("Measured palette length = %d\n", palette_length);
#ifdef PNG_READ_bKGD_SUPPORTED
{
png_color_16p bkgd;
if (png_get_bKGD(read_ptr, read_info_ptr, &bkgd))
{
bkgd_index = bkgd->index;
P1("bKGD index = %d\n", bkgd_index);
#if 1
if (bkgd_index > palette_length)
{
bkgd_index = palette_length;
have_bkgd = 1;
fprintf(STDERR,
" New bKGD index = %d\n", bkgd_index);
}
#endif
if (bkgd->index >= palette_length)
palette_length = (int) bkgd_index+1;
P1("Total palette length = %d\n", palette_length);
}
}
#endif
plte_len = palette_length;
if (num_trans > plte_len)
{
num_trans = plte_len;
png_set_tRNS(write_ptr, write_info_ptr, trns_array,
num_trans, trans_values);
}
}
}
#if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED) && \
defined(PNG_FLOATING_POINT_SUPPORTED)
if ((color_type == 2 || color_type == 6 || color_type == 3)
&& (output_color_type == 0 || output_color_type == 4))
{
png_byte rgb_error =
png_get_rgb_to_gray_status(read_ptr);
if (last_trial && verbose > 0 && rgb_error)
fprintf(STDERR,
" **** Converted non-gray image to gray. **** \n");
}
#endif
#ifdef PNG_FREE_UNKN
# if defined(PNG_READ_UNKNOWN_CHUNKS_SUPPORTED)
png_free_data(read_ptr, read_info_ptr, PNG_FREE_UNKN, -1);
# endif
# if defined(PNG_WRITE_UNKNOWN_CHUNKS_SUPPORTED)
png_free_data(write_ptr, write_info_ptr, PNG_FREE_UNKN, -1);
# endif
#else
# if defined(PNG_READ_UNKNOWN_CHUNKS_SUPPORTED)
png_free_unknown_chunks(read_ptr, read_info_ptr, -1);
# endif
# if defined(PNG_WRITE_UNKNOWN_CHUNKS_SUPPORTED)
png_free_unknown_chunks(write_ptr, write_info_ptr, -1);
# endif
#endif /* PNG_FREE_UNKN */
/* { GRR: added for %-navigation (2) */
if (!(bail == 0 && trial != last_method &&
pngcrush_write_byte_count >
pngcrush_best_byte_count))
{
P1(" Reading and writing end_info data\n");
png_read_end(read_ptr, end_info_ptr);
/* Handle ancillary chunks */
if (last_trial == 1)
{
#if (defined(PNG_READ_tEXt_SUPPORTED) && defined(PNG_WRITE_tEXt_SUPPORTED)) \
|| (defined(PNG_READ_iTXt_SUPPORTED) && defined(PNG_WRITE_iTXt_SUPPORTED)) \
|| (defined(PNG_READ_zTXt_SUPPORTED) && defined(PNG_WRITE_zTXt_SUPPORTED))
P1( "Check for iTXt/tEXt/zTXt chunks after IDAT\n");
{
png_textp text_ptr;
int num_text = 0;
if (png_get_text (read_ptr,
end_info_ptr, &text_ptr, &num_text) > 0
|| text_inputs)
{
int ntext;
#ifdef PNG_iTXt_SUPPORTED
P1( "Handling %d tEXt/zTXt/iTXt chunks after IDAT\n",
#else
P1( "Handling %d tEXt/zTXt chunks after IDAT\n",
#endif
num_text);
if (verbose > 1 && last_trial && num_text > 0)
{
for (ntext = 0; ntext < num_text; ntext++)
{
fprintf(STDERR, "%d %s", ntext,
text_ptr[ntext].key);
if (text_ptr[ntext].text_length)
fprintf(STDERR, ": %s\n",
text_ptr[ntext].text);
#ifdef PNG_iTXt_SUPPORTED
else if (text_ptr[ntext].itxt_length)
{
fprintf(STDERR, " (%s: %s): \n",
text_ptr[ntext].lang,
text_ptr[ntext].lang_key);
fprintf(STDERR, "%s\n",
text_ptr[ntext].text);
}
#endif
else
fprintf(STDERR, "\n");
}
}
if (last_trial)
{
if (num_text > 0)
{
if (keep_chunk("text", argv))
{
int num_to_write = num_text;
for (ntext = 0; ntext < num_text; ntext++)
{
if (verbose > 1)
P2("Text chunk after IDAT, "
"compression=%d\n",
text_ptr[ntext].compression);
if (text_ptr[ntext].compression ==
PNG_TEXT_COMPRESSION_NONE)
{
if (!keep_chunk("tEXt", argv))
{
text_ptr[ntext].key[0] = '\0';
num_to_write--;
}
}
if (text_ptr[ntext].compression ==
PNG_TEXT_COMPRESSION_zTXt)
{
if (!keep_chunk("zTXt", argv))
{
text_ptr[ntext].key[0] = '\0';
num_to_write--;
}
}
#ifdef PNG_iTXt_SUPPORTED
if (text_ptr[ntext].compression ==
PNG_ITXT_COMPRESSION_NONE
|| text_ptr[ntext].compression ==
PNG_ITXT_COMPRESSION_zTXt)
{
if (!keep_chunk("iTXt", argv))
{
text_ptr[ntext].key[0] = '\0';
num_to_write--;
}
}
#endif
}
if (num_to_write > 0)
png_set_text(write_ptr,
write_end_info_ptr,
text_ptr, num_text);
}
}
P1( "text_inputs=%d\n",text_inputs);
for (ntext = 0; ntext < text_inputs; ntext++)
{
P1( " ntext=%d\n",ntext);
if (text_where[ntext] == 2)
{
png_textp added_text;
added_text = (png_textp)
png_malloc(write_ptr,
(png_uint_32)
sizeof(png_text));
added_text[0].key =
&text_keyword[ntext * 80];
#ifdef PNG_iTXt_SUPPORTED
added_text[0].lang =
&text_lang[ntext * 80];
added_text[0].lang_key =
&text_lang_key[ntext * 80];
#endif
added_text[0].text =
&text_text[ntext * STR_BUF_SIZE];
added_text[0].compression =
text_compression[ntext];
png_set_text(write_ptr, write_end_info_ptr,
added_text, 1);
if (verbose > 0 && last_trial)
{
if (added_text[0].compression < 0)
fprintf(STDERR,
" Added a tEXt chunk.\n");
else if (added_text[0].compression == 0)
fprintf(STDERR,
" Added a zTXt chunk.\n");
#ifdef PNG_iTXt_SUPPORTED
else if (added_text[0].compression == 1)
fprintf(STDERR,
" Added an uncompressed iTXt "
"chunk.\n");
else
fprintf(STDERR,
" Added a compressed iTXt "
"chunk.\n");
#endif
}
png_free(write_ptr, added_text);
added_text = (png_textp) NULL;
}
}
} /* end of nosave block */
}
}
#endif /* (PNG_READ_tEXt_SUPPORTED and PNG_WRITE_tEXt_SUPPORTED) or */
/* (PNG_READ_iTXt_SUPPORTED and PNG_WRITE_iTXt_SUPPORTED) or */
/* (PNG_READ_zTXt_SUPPORTED and PNG_WRITE_zTXt_SUPPORTED) */
#if defined(PNG_READ_tIME_SUPPORTED) && defined(PNG_WRITE_tIME_SUPPORTED)
{
png_timep mod_time;
if (png_get_tIME(read_ptr, end_info_ptr, &mod_time))
{
P1( "Handling tIME chunk after IDAT\n");
if (keep_chunk("tIME", argv))
png_set_tIME(write_ptr, write_end_info_ptr,
mod_time);
}
}
#endif
#ifdef PNG_WRITE_UNKNOWN_CHUNKS_SUPPORTED
/* GRR FIXME? this block may need same fix as above */
{
png_unknown_chunkp unknowns;
int num_unknowns =
(int) png_get_unknown_chunks(read_ptr,
end_info_ptr,
&unknowns);
if (num_unknowns && nosave == 0)
{
fprintf(STDERR,
"Handling %d unknown chunks after IDAT\n",
num_unknowns);
png_set_unknown_chunks(write_ptr,
write_end_info_ptr,
unknowns, num_unknowns);
for (i = 0; i < num_unknowns; i++)
png_set_unknown_chunk_location(write_ptr,
write_end_info_ptr,
i,
(int)
unknowns[i].
location);
}
}
#endif
} /* End of ancillary chunk handling */
if (nosave == 0) {
#if 0 /* doesn't work; compression level has to be the same as in IDAT */
/* if zTXt other compressed chunk */
png_set_compression_level(write_ptr, 9);
png_set_compression_window_bits(write_ptr, 15);
png_set_compression_buffer_size(write_ptr,
PNG_ZBUF_SIZE);
png_set_compression_strategy(write_ptr, 0);
#endif /* 0 */
png_write_end(write_ptr, write_end_info_ptr);
}
}
/* } GRR: added for %-navigation (2) */
P1( "Destroying read data structs\n");
if (row_buf != (png_bytep) NULL)
{
P2(" row_buf = %p\n",row_buf);
P2( "Destroying row_buf\n");
/* Crash has been observed here when using the
* system libpng instead of the bundled one.
* It seems to have to do with the workaround for
* png_read_transform_info() not being exported
* in libpng-1.5.6 and later.
*/
png_free(read_ptr, row_buf);
row_buf = (png_bytep) NULL;
}
P2( "Destroyed data row_buf\n");
#ifdef PNGCRUSH_MULTIPLE_ROWS
if (row_pointers != (png_bytepp) NULL)
{
P1( "Destroying row_pointers\n");
png_free(read_ptr, row_pointers);
row_pointers = (png_bytepp) NULL;
}
P2( "Destroyed data row_pointers\n");
#endif
png_destroy_read_struct(&read_ptr, &read_info_ptr,
&end_info_ptr);
P2( "Destroyed data structs\n");
if (nosave == 0)
{
#ifdef PNGCRUSH_LOCO
if (do_loco)
{
const png_byte png_MEND[5] =
{ 77, 69, 78, 68, '\0' };
/* write the MNG MEND chunk */
png_write_chunk(write_ptr, (png_bytep) png_MEND,
NULL, (png_size_t) 0);
}
#endif
png_destroy_info_struct(write_ptr,
&write_end_info_ptr);
png_destroy_write_struct(&write_ptr, &write_info_ptr);
}
}
Catch(msg) {
if (nosave == 0)
fprintf(stderr, "While converting %s to %s:\n", inname,
outname);
else
fprintf(stderr, "While reading %s:\n", inname);
fprintf(stderr,
" pngcrush caught libpng error:\n %s\n\n", msg);
if (row_buf)
{
png_free(read_ptr, row_buf);
row_buf = (png_bytep) NULL;
}
#ifdef PNGCRUSH_MULTIPLE_ROWS
if (row_pointers != (png_bytepp) NULL)
{
png_free(read_ptr, row_pointers);
row_pointers = (png_bytepp) NULL;
}
#endif
if (nosave == 0)
{
png_destroy_info_struct(write_ptr,
&write_end_info_ptr);
png_destroy_write_struct(&write_ptr, &write_info_ptr);
setfiletype(outname);
}
png_destroy_read_struct(&read_ptr, &read_info_ptr,
&end_info_ptr);
if (verbose > 1)
fprintf(stderr, "returning after cleanup\n");
trial = last_method + 1;
}
read_ptr = NULL;
write_ptr = NULL;
FCLOSE(fpin);
if (last_trial && nosave == 0)
{
FCLOSE(fpout);
setfiletype(outname);
}
if (nosave)
break;
if (trial == 0)
continue;
idat_length[trial] = pngcrush_write_byte_count;
if (pngcrush_write_byte_count < pngcrush_best_byte_count)
pngcrush_best_byte_count = pngcrush_write_byte_count;
if (verbose > 0 && trial != last_method)
{
if (bail == 0 &&
pngcrush_write_byte_count > pngcrush_best_byte_count)
fprintf(STDERR,
" Critical chunk length, method %3d"
" (ws %d fm %d zl %d zs %d) >%10lu\n",
trial, compression_window,
filter_type, zlib_level, z_strategy,
(unsigned long)pngcrush_best_byte_count);
else
fprintf(STDERR,
" Critical chunk length, method %3d"
" (ws %d fm %d zl %d zs %d) =%10lu\n",
trial, compression_window,
filter_type, zlib_level, z_strategy,
(unsigned long)idat_length[trial]);
fflush(STDERR);
}
} /* end of trial-loop */
P1("\n\nFINISHED MAIN LOOP OVER %d METHODS\n\n\n", last_method);
/* ////////////////////////////////////////////////////////////////////
////////////////// ////////////////////
////////////////// END OF MAIN LOOP OVER METHODS ////////////////////
////////////////// ////////////////////
//////////////////////////////////////////////////////////////////// */
}
if (fpin)
{
FCLOSE(fpin);
}
if (last_trial && nosave == 0 && fpout)
{
FCLOSE(fpout);
setfiletype(outname);
}
if (last_trial && nosave == 0 && overwrite != 0)
{
/* rename the new file , outname = inname */
if (
#if (defined(_Windows) || defined(_WINDOWS) || defined(WIN32) || \
defined(_WIN32) || defined(__WIN32__) || defined(__CYGWIN__) || \
defined(__DJGPP__) || defined(CYGWIN))
remove(inname) != 0 ||
#endif
rename(outname, inname) != 0 )
{
fprintf(STDERR,
"error while renaming \"%s\" to \"%s\" \n",outname,inname);
exit (1);
}
else
P2("rename %s to %s complete.\n",outname,inname);
}
if (last_trial && nosave == 0)
{
png_uint_32 output_length;
#ifndef __riscos
struct stat stat_buf;
struct utimbuf utim;
stat(inname, &stat_buf);
utim.actime = stat_buf.st_atime;
utim.modtime = stat_buf.st_mtime;
stat(outname, &stat_buf);
output_length = (unsigned long) stat_buf.st_size;
if (new_time_stamp == 0)
{
/* set file timestamp (no big deal if fails) */
utime(outname, &utim);
}
#else
output_length = (unsigned long) filesize(outname);
#endif
if (verbose >= 0 && bench < 2)
{
total_input_length += input_length + output_length;
if (best == 0)
{
fprintf(STDERR,
" Best pngcrush method = 0 (settings undetermined)\n");
}
#if 0 /* disabled */
else if (!already_crushed && !image_is_immutable)
#else
else if (!image_is_immutable)
#endif
{
fprintf(STDERR,
" Best pngcrush method = %3d "
"(ws %d fm %d zl %d zs %d) =%10lu\n",
best, compression_window, fm[best], lv[best], zs[best],
(unsigned long)idat_length[best]);
}
if (verbose > 0)
{
if (idat_length[0] == idat_length[best])
fprintf(STDERR, " (no critical chunk change)\n");
else if (idat_length[0] > idat_length[best])
fprintf(STDERR, " (%4.2f%% critical chunk reduction)\n",
(100.0 - (100.0 * idat_length[best]) / idat_length[0]));
else
fprintf(STDERR, " (%4.2f%% critical chunk increase)\n",
-(100.0 - (100.0 * idat_length[best]) / idat_length[0]));
if (input_length == output_length)
fprintf(STDERR, " (no filesize change)\n\n");
else if (input_length > output_length)
fprintf(STDERR, " (%4.2f%% filesize reduction)\n\n",
(100.0 - (100.0 * output_length) / input_length));
else
fprintf(STDERR, " (%4.2f%% filesize increase)\n\n",
-(100.0 - (100.0 * output_length) / input_length));
if (verbose > 2)
fprintf(STDERR, " Number of open files=%d\n",
number_of_open_files);
}
}
}
if (pngcrush_mode == DEFAULT_MODE || pngcrush_mode == OVERWRITE_MODE)
{
if (png_row_filters != NULL)
{
free(png_row_filters);
png_row_filters = NULL;
}
#if PNGCRUSH_TIMERS > 0
pngcrush_timer_stop(PNGCRUSH_TIMER_MISC);
pngcrush_timer_stop(PNGCRUSH_TIMER_TOTAL);
#endif
if (verbose >= 0)
{
show_result();
}
#ifdef PNG_iCCP_SUPPORTED
if (iccp_length)
{
free(iccp_text);
iccp_text = NULL;
iccp_length = 0;
}
#endif
break;
}
} /* end of loop on input files */
#if PNGCRUSH_TIMERS > 0
for (pc_timer = 0; pc_timer < PNGCRUSH_TIMERS; pc_timer++)
{
unsigned long ts,tn;
ts=pngcrush_timer_get_seconds(pc_timer);
tn=pngcrush_timer_get_nanoseconds(pc_timer);
if (ts < pngcrush_timer_min_secs[pc_timer])
{
pngcrush_timer_min_secs[pc_timer] = ts;
pngcrush_timer_min_nsec[pc_timer] = tn;
}
else
{
if (tn < pngcrush_timer_min_nsec[pc_timer])
pngcrush_timer_min_nsec[pc_timer] = tn;
}
pngcrush_timer_reset(pc_timer);
}
#endif
} /* end of benchmark_iteration loop */
if (verbose >= 0)
{
#if (PNGCRUSH_TIMERS > 0)
for (pc_timer=0;pc_timer < PNGCRUSH_TIMERS; pc_timer++)
{
filter_count[pc_timer]+=pngcrush_timer_get_hits(pc_timer);
t_sec=pngcrush_timer_min_secs[pc_timer];
t_nsec=pngcrush_timer_min_nsec[pc_timer];
t_filter[pc_timer] = (float)t_nsec/1000000000.;
if (t_sec)
t_filter[pc_timer] += (float)t_sec;
}
# if PNGCRUSH_TIMERS >= 3
fprintf(STDERR, "CPU time decode %.6f,", t_filter[1]);
fprintf(STDERR, " encode %.6f,", t_filter[2]);
fprintf(STDERR, " other %.6f,", t_filter[3]);
fprintf(STDERR, " total %.6f sec\n", t_filter[0]);
# endif
# if PNGCRUSH_USE_CLOCK_GETTIME != 0
if (benchmark_iterations > 0)
{
# if PNGCRUSH_TIMERS > 9
{
float total_t_filter=0;
float total_filter_count=0;
for (pc_timer = 5; pc_timer < 10; pc_timer++)
{
total_t_filter+=t_filter[pc_timer];
total_filter_count+=filter_count[pc_timer];
}
if (total_filter_count > 0)
{
for (pc_timer = 5; pc_timer < 10; pc_timer++)
{
fprintf(STDERR, " filter[%u] defilter time = %15.9f, count = %lu\n",
pc_timer-5, t_filter[pc_timer],
(unsigned long)filter_count[pc_timer]);
}
fprintf(STDERR, " total defilter time = %15.9f, count = %lu\n",
total_t_filter, (unsigned long) total_filter_count);
}
}
# endif
# if PNGCRUSH_TIMERS > 4
{
if (filter_count[4] > 0)
fprintf(STDERR, " deinterlace time = %15.9f, count = %lu\n",
t_filter[4], (unsigned long)filter_count[4]);
}
# endif
# if PNGCRUSH_TIMERS > 1
{
fprintf(STDERR, " total decode time = %15.9f, count = %lu\n",
t_filter[1], (unsigned long)filter_count[1]);
}
# endif
# if PNGCRUSH_TIMERS > 10
{
if (filter_count[10] > 0)
fprintf(STDERR, " filter setup time = %15.9f, count = %lu\n",
t_filter[10], (unsigned long)filter_count[10]);
}
# endif
# if PNGCRUSH_TIMERS > 2
{
fprintf(STDERR, " total encode time = %15.9f, count = %lu\n",
t_filter[2], (unsigned long)filter_count[2]);
}
# endif
# if PNGCRUSH_TIMERS > 3
{
fprintf(STDERR, " total misc time = %15.9f, count = %lu\n",
t_filter[3], (unsigned long)filter_count[3]);
}
# endif
# if PNGCRUSH_TIMERS > 0
{
fprintf(STDERR, " total time = %15.9f, count = %lu\n",
t_filter[0], (unsigned long)filter_count[0]);
}
# endif
}
#endif
#endif
}
if (pngcrush_must_exit)
exit(0);
return 0; /* just in case */
} /* end of main() */
png_uint_32 measure_idats(FILE * fp_in)
{
/* Copyright (C) 1999-2002, 2006-2015 <NAME>
(glennrp at users.sf.net). See notice in pngcrush.c for conditions of
use and distribution */
P2("\nmeasure_idats:\n");
P1( "Allocating read structure\n");
/* OK to ignore any warning about the address of exception__prev in "Try" */
Try {
read_ptr =
png_create_read_struct(PNG_LIBPNG_VER_STRING, (png_voidp) NULL,
(png_error_ptr) pngcrush_cexcept_error,
(png_error_ptr) NULL);
P1( "Allocating read_info, end_info structures\n");
read_info_ptr = png_create_info_struct(read_ptr);
end_info_ptr = png_create_info_struct(read_ptr);
#ifdef PNG_STDIO_SUPPORTED
png_init_io(read_ptr, fp_in);
#else
png_set_read_fn(read_ptr, (png_voidp) fp_in, (png_rw_ptr) NULL);
#endif
png_set_sig_bytes(read_ptr, 0);
measured_idat_length = pngcrush_measure_idat(read_ptr);
P2("measure_idats: IDAT length=%lu\n",
(unsigned long)measured_idat_length);
P1( "Destroying data structs\n");
png_destroy_read_struct(&read_ptr, &read_info_ptr, &end_info_ptr);
}
Catch(msg) {
fprintf(STDERR, "\nWhile measuring IDATs in %s ", inname);
fprintf(STDERR, "pngcrush caught libpng error:\n %s\n\n", msg);
png_destroy_read_struct(&read_ptr, &read_info_ptr, &end_info_ptr);
P1( "Destroyed data structs\n");
measured_idat_length = 0;
}
return measured_idat_length;
}
#define PNGCRUSH_a 97
#define PNGCRUSH_z 122
#define PNGCRUSH_A 65
#define PNGCRUSH_Z 90
png_uint_32 pngcrush_measure_idat(png_structp png_ptr)
{
/* Copyright (C) 1999-2002, 2006-2015 <NAME>
(glennrp at users.sf.net)
See notice in pngcrush.c for conditions of use and distribution */
/* Signature + IHDR + IEND; we'll add PLTE + IDAT lengths */
png_uint_32 sum_idat_length = 45;
png_byte *bb = NULL;
png_uint_32 malloced_length=0;
{
png_byte png_signature[8] = { 137, 80, 78, 71, 13, 10, 26, 10 };
#ifdef PNGCRUSH_LOCO
png_byte mng_signature[8] = { 138, 77, 78, 71, 13, 10, 26, 10 };
#endif
pngcrush_default_read_data(png_ptr, png_signature, 8);
png_set_sig_bytes(png_ptr, 8);
#ifdef PNGCRUSH_LOCO
if (!(int) (png_memcmp(mng_signature, png_signature, 8)))
{
const png_byte png_MHDR[5] = { 77, 72, 68, 82, '\0' };
int ib;
png_byte buff[28] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0 };
unsigned long length;
/* read the MHDR */
pngcrush_default_read_data(png_ptr, buff, 4);
length = pngcrush_get_uint_31(png_ptr,buff);
if (length > 28)
png_error(png_ptr, "MHDR length too long");
pngcrush_default_read_data(png_ptr, buff, 4);
/* To do: combine with checking for valid PNG chunk_name, below */
/* Check for valid chunk name [A-Za-z][A-Za-z][A-Z][A-Za-z] */
if (!(((buff[0] >= PNGCRUSH_a && buff[0] <= PNGCRUSH_z) ||
(buff[0] >= PNGCRUSH_A && buff[0] <= PNGCRUSH_Z)) &&
((buff[1] >= PNGCRUSH_a && buff[1] <= PNGCRUSH_z) ||
(buff[1] >= PNGCRUSH_A && buff[1] <= PNGCRUSH_Z)) &&
((buff[2] >= PNGCRUSH_A && buff[2] <= PNGCRUSH_Z)) &&
((buff[3] >= PNGCRUSH_a && buff[3] <= PNGCRUSH_z) ||
(buff[3] >= PNGCRUSH_A && buff[3] <= PNGCRUSH_Z))))
{
int i;
fprintf (STDERR,"Invalid MNG chunk name: \"");
for (i=0; i<4; i++)
{
if ((buff[i] >= PNGCRUSH_a && buff[i] <= PNGCRUSH_z) ||
(buff[i] >= PNGCRUSH_A && buff[i] <= PNGCRUSH_Z) ||
(buff[i] >= '0' && buff[i] <= '9'))
fprintf(STDERR,"%c",buff[i]);
else
fprintf(STDERR,"?");
}
fprintf(STDERR,"\" (0x%2x 0x%2x 0x%2x 0x%2x)\n",
buff[0],buff[1],buff[2],buff[3]);
}
else
if (verbose > 1)
printf(" Reading %c%c%c%c chunk.\n",buff[0],buff[1],buff[2],
buff[3]);
pngcrush_default_read_data(png_ptr, buff, length);
if (length < 28)
for (ib=27; ib >= length; ib--)
buff[ib] = 0;
if (verbose > 0) {
printf(" width=%lu\n",
(unsigned long) pngcrush_get_uint_31(png_ptr,buff));
printf(" height=%lu\n",
(unsigned long) pngcrush_get_uint_31(png_ptr,&buff[4]));
printf(" ticksps=%lu\n",
(unsigned long) pngcrush_get_uint_31(png_ptr,&buff[8]));
printf(" nomlayc=%lu\n",
(unsigned long) pngcrush_get_uint_31(png_ptr,&buff[12]));
printf(" nomfram=%lu\n",
(unsigned long) pngcrush_get_uint_31(png_ptr,&buff[16]));
printf(" nomplay=%lu\n",
(unsigned long) pngcrush_get_uint_31(png_ptr,&buff[20]));
printf(" profile=%lu\n",
(unsigned long) pngcrush_get_uint_31(png_ptr,&buff[24]));
}
if (new_mng)
{
/* write the MNG 8-byte signature */
pngcrush_write_png(mng_ptr, &mng_signature[0],
(png_size_t) 8);
/* Write a MHDR chunk */
png_write_chunk(mng_ptr, (png_bytep) png_MHDR,
buff, (png_size_t) 28);
}
pngcrush_default_read_data(png_ptr, buff, 4);
input_format = 1;
}
else
#endif
if (png_sig_cmp(png_signature, 0, 8))
{
if (png_sig_cmp(png_signature, 0, 4))
png_error(png_ptr, "Not a PNG file..");
else
png_error(png_ptr,
"PNG file corrupted by ASCII conversion");
}
}
if (salvage)
{
#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
/* The warning here about deprecated access to png_ptr->zstream
* is unavoidable. This will not work with libpng-1.5.x and later.
*/
inflateUndermine(&png_ptr->zstream, 1);
#endif
}
for (;;)
{
#ifndef PNG_UINT_IDAT
# ifdef PNG_USE_LOCAL_ARRAYS
PNG_IDAT;
PNG_IEND;
PNG_IHDR;
PNG_acTL;
# ifdef PNG_iCCP_SUPPORTED
PNG_iCCP;
# endif
# else
# ifdef PNG_iCCP_SUPPORTED
const png_byte png_iCCP[5] = { 105, 67, 67, 80, '\0' };
# endif
const png_byte png_acTL[5] = { 97, 99, 84, 76, '\0' };
# endif
#endif
png_byte chunk_name[5];
png_byte chunk_length[4];
png_byte buff[32];
png_uint_32 length;
pngcrush_default_read_data(png_ptr, chunk_length, 4);
length = pngcrush_get_uint_31(png_ptr,chunk_length);
pngcrush_reset_crc(png_ptr);
pngcrush_crc_read(png_ptr, chunk_name, 4);
chunk_name[4]='\0';
/* Check for valid chunk name [A-Za-z][A-Za-z][A-Z][A-Za-z] */
if (!(((chunk_name[0] >= PNGCRUSH_a && chunk_name[0] <= PNGCRUSH_z) ||
(chunk_name[0] >= PNGCRUSH_A && chunk_name[0] <= PNGCRUSH_Z)) &&
((chunk_name[1] >= PNGCRUSH_a && chunk_name[1] <= PNGCRUSH_z) ||
(chunk_name[2] >= PNGCRUSH_A && chunk_name[2] <= PNGCRUSH_Z)) &&
((chunk_name[2] >= PNGCRUSH_A && chunk_name[2] <= PNGCRUSH_Z)) &&
((chunk_name[3] >= PNGCRUSH_a && chunk_name[3] <= PNGCRUSH_z) ||
(chunk_name[3] >= PNGCRUSH_A && chunk_name[3] <= PNGCRUSH_Z))))
{
int i;
fprintf (STDERR,"Invalid chunk name: \"");
for (i=0; i<4; i++)
{
if ((chunk_name[i] >= PNGCRUSH_a &&
chunk_name[i] <= PNGCRUSH_z) ||
(chunk_name[i] >= PNGCRUSH_A &&
chunk_name[i] <= PNGCRUSH_Z)||
(chunk_name[i] >= '0' &&
chunk_name[i] <= '9'))
fprintf(STDERR,"%c",chunk_name[i]);
else
fprintf(STDERR,"?");
}
fprintf(STDERR,"\" (0x%2x 0x%2x 0x%2x 0x%2x)\n",
chunk_name[0],chunk_name[1],chunk_name[2],chunk_name[3]);
}
else
if (verbose > 1)
printf(" Reading %c%c%c%c chunk.\n",
chunk_name[0],chunk_name[1],chunk_name[2],chunk_name[3]);
if (new_mng)
{
const png_byte png_DHDR[5] = { 68, 72, 68, 82, '\0' };
const png_byte png_DEFI[5] = { 68, 69, 70, 73, '\0' };
const png_byte png_FRAM[5] = { 70, 82, 65, 77, '\0' };
const png_byte png_nEED[5] = { 110, 69, 69, 68, '\0' };
if (!png_memcmp(chunk_name, png_nEED, 4))
{
/* Skip the nEED chunk */
if (verbose > 0)
printf (" skipping MNG %c%c%c%c chunk, %lu bytes\n",
chunk_name[0],
chunk_name[1],chunk_name[2],chunk_name[3],
(unsigned long)length);
}
else
{
/* copy the chunk. */
if (verbose > 0)
printf (" reading MNG %c%c%c%c chunk, %lu bytes\n",
chunk_name[0],
chunk_name[1],chunk_name[2],chunk_name[3],
(unsigned long)length);
if (length+1 > malloced_length)
{
png_free(mng_ptr,bb);
if (verbose > 0)
printf (" png_malloc %lu bytes.\n",(unsigned long)length);
bb=(png_byte*)png_malloc(mng_ptr, length+1);
malloced_length=length+1;
}
pngcrush_crc_read(png_ptr, bb, length);
bb[length]='\0';
png_write_chunk(mng_ptr, chunk_name,
bb, (png_size_t) length);
if (verbose > 1 && !png_memcmp(chunk_name, png_DHDR, 4))
{
if (length > 19)
{
printf(" objid=%lu\n",(unsigned long)(bb[1]+(bb[0]<<8)));
printf(" itype=%lu\n",(unsigned long)(bb[2]));
printf(" dtype=%lu\n",(unsigned long)(bb[3]));
printf(" width=%lu\n",
(unsigned long) pngcrush_get_uint_31(png_ptr,&bb[4]));
printf(" height=%lu\n",
(unsigned long) pngcrush_get_uint_31(png_ptr,&bb[8]));
printf(" xloc=%lu\n",
(unsigned long) pngcrush_get_uint_31(png_ptr,&bb[12]));
printf(" yloc=%lu\n",
(unsigned long) pngcrush_get_uint_31(png_ptr,&bb[16]));
}
}
if (verbose > 1 && !png_memcmp(chunk_name, png_DEFI, 4))
{
if (length > 3)
{
printf(" objid=%lu\n",(unsigned long)(bb[1]+(bb[0]<<8)));
printf(" do_not_show=%lu\n",(unsigned long)(bb[2]));
printf(" concrete=%lu\n",(unsigned long)(bb[3]));
}
if (length > 19)
{
printf(" xloc=%lu\n",
(unsigned long) pngcrush_get_uint_31(png_ptr,&bb[12]));
printf(" yloc=%lu\n",
(unsigned long) pngcrush_get_uint_31(png_ptr,&bb[16]));
if (length > 28)
{
printf(" l_cb=%lu\n",
(unsigned long) pngcrush_get_uint_31(png_ptr,&bb[20]));
printf(" r_cb=%lu\n",
(unsigned long) pngcrush_get_uint_31(png_ptr,&bb[24]));
}
}
}
if (verbose > 1 && !png_memcmp(chunk_name, png_FRAM, 4))
{
printf(" mode=%lu\n",(unsigned long)bb[0]);
if (length > 1)
{
int ib;
printf(" name = ");
bb[length]='\0';
for (ib=0; bb[ib]; ib++)
{
printf ("%c", bb[ib]);
}
printf ("\n");
}
length=0;
}
}
}
#ifdef PNG_UINT_acTL
else if (pngcrush_get_uint_32(chunk_name) == PNG_UINT_acTL)
#else
else if (!png_memcmp(chunk_name, png_acTL, 4))
#endif
{
found_acTL_chunk = 1;
}
#ifdef PNG_UINT_IDAT
if ((pngcrush_get_uint_32(chunk_name) == PNG_UINT_IDAT) ||
#endif
#ifndef PNG_UINT_IDAT
if ((!png_memcmp(chunk_name, png_IDAT, 4)) ||
#endif
#ifdef PNG_UINT_PLTE
(pngcrush_get_uint_32(chunk_name) == PNG_UINT_PLTE))
#endif
#ifndef PNG_UINT_PLTE
(!png_memcmp(chunk_name, png_PLTE, 4)))
#endif
{
sum_idat_length += (length + 12);
#if 0 /* disabled */
if (length > crushed_idat_size)
already_crushed++;
#endif
}
if (verbose > 1)
{
chunk_name[4] = '\0';
fprintf(STDERR, " Reading %s chunk, length = %lu.\n",
chunk_name, (unsigned long)length);
}
if (pngcrush_get_uint_32(chunk_name) == PNG_UINT_CgBI)
{
fprintf(STDERR,
" This is an Xcode CgBI file, not a PNG file.\n");
if (salvage)
{
fprintf (STDERR, " Removing the CgBI chunk.\n");
}
else
{
fprintf (STDERR,
" Try \"pngcrush -fix ...\" to attempt to read it.\n");
}
found_CgBI++;
nosave++;
}
#ifdef PNG_UINT_IHDR
if (pngcrush_get_uint_32(chunk_name) == PNG_UINT_IHDR)
#else
if (!png_memcmp(chunk_name, png_IHDR, 4))
#endif
{
/* get the color type */
pngcrush_crc_read(png_ptr, buff, 13);
length -= 13;
input_color_type = buff[9];
}
else if (pngcrush_get_uint_32(chunk_name) == PNG_UINT_dSIG)
{
if (found_any_chunk == 0 && !all_chunks_are_safe)
{
image_is_immutable=1;
}
}
else
found_any_chunk=1;
#ifdef PNG_gAMA_SUPPORTED
#ifdef PNG_UINT_gAMA
if (pngcrush_get_uint_32(chunk_name) == PNG_UINT_gAMA)
#else
if (!png_memcmp(chunk_name, png_gAMA, 4))
#endif
found_gAMA=1;
#endif /* PNG_gAMA_SUPPORTED */
#ifdef PNG_bKGD_SUPPORTED
#ifdef PNG_UINT_bKGD
if (pngcrush_get_uint_32(chunk_name) == PNG_UINT_bKGD)
#else
if (!png_memcmp(chunk_name, png_bKGD, 4))
#endif
if (length == 6)
{
/* Set found_color_bKGD if the components are different,
* so we do not do reduction of color-type from color to gray
*/
pngcrush_crc_read(png_ptr, buff, 6);
length -= 6;
if ((buff[0] != buff[2]) && (buff[0] != buff[4]) &&
(buff[1] != buff[3]) && (buff[0] != buff[5]))
found_color_bKGD=1;
}
#endif /* PNG_bKGD_SUPPORTED */
#ifdef PNG_cHRM_SUPPORTED
#ifdef PNG_UINT_cHRM
if (pngcrush_get_uint_32(chunk_name) == PNG_UINT_cHRM)
#else
if (!png_memcmp(chunk_name, png_cHRM, 4))
#endif
found_cHRM=1;
#endif /* PNG_cHRM_SUPPORTED */
#ifdef PNG_hIST_SUPPORTED
#ifdef PNG_UINT_hIST
if (pngcrush_get_uint_32(chunk_name) == PNG_UINT_hIST)
#else
if (!png_memcmp(chunk_name, png_hIST, 4))
#endif
found_hIST=1;
#endif /* PNG_hIST_SUPPORTED */
#ifdef PNG_iCCP_SUPPORTED
/* check for bad Photoshop iCCP chunk */
#ifdef PNG_UINT_iCCP
if (pngcrush_get_uint_32(chunk_name) == PNG_UINT_iCCP)
#else
if (!png_memcmp(chunk_name, png_iCCP, 4))
#endif
{
found_iCCP = 1;
/* Check for bad Photoshop iCCP chunk. Libpng will reject the
* bad chunk because the Adler-32 bytes are missing, but we check
* here to see if it's really the sRGB profile, and if so, set the
* "intent" flag and gamma so pngcrush will write an sRGB chunk
* and a gamma chunk.
*/
if (length == 2615)
{
pngcrush_crc_read(png_ptr, buff, 22);
length -= 22;
buff[23] = 0;
if (!strncmp((png_const_charp) buff, "Photoshop ICC profile",
21))
{
fprintf(STDERR,
" Replacing bad Photoshop iCCP chunk with an "
"sRGB chunk\n");
#ifdef PNG_gAMA_SUPPORTED
# ifdef PNG_FIXED_POINT_SUPPORTED
image_specified_gamma = 45455L;
# else
image_specified_gamma = 0.45455;
# endif
#endif /* PNG_gAMA_SUPPORTED */
found_iCCP = 0;
found_sRGB = 1;
intent = 0;
}
}
/* To do: recognize other sRGB iCCP chunks and replace them with
* sRGB chunk
*/
}
#endif /* PNG_iCCP_SUPPORTED */
#ifdef PNG_sBIT_SUPPORTED
#ifdef PNG_UINT_sBIT
if (pngcrush_get_uint_32(chunk_name) == PNG_UINT_sBIT)
#else
if (!png_memcmp(chunk_name, png_sBIT, 4))
#endif
{
if (length <= 4)
{
int i;
pngcrush_crc_read(png_ptr, buff, length);
found_sBIT_max=0;
for (i=length; i; i--)
if (buff[i] > found_sBIT_max)
found_sBIT_max=buff[i];
if (length > 2)
if (buff[0] != buff[1] || buff[0] != buff[2])
found_sBIT_different_RGB_bits = 1;
found_sBIT = 1;
length = 0;
}
}
#endif /* PNG_sBIT_SUPPORTED */
#ifdef PNG_tRNS_SUPPORTED
#ifdef PNG_UINT_tRNS
if (pngcrush_get_uint_32(chunk_name) == PNG_UINT_tRNS)
#else
if (!png_memcmp(chunk_name, png_tRNS, 4))
#endif
found_tRNS=1;
#endif /* PNG_tRNS_SUPPORTED */
pngcrush_crc_finish(png_ptr, length);
#ifdef PNGCRUSH_LOCO
# ifdef PNG_UINT_MEND
if (pngcrush_get_uint_32(chunk_name) == PNG_UINT_MEND)
return sum_idat_length;
# else
{
const png_byte png_MEND[5] =
{ 77, 69, 78, 68, '\0' };
if (!png_memcmp(chunk_name, png_MEND, 4))
{
if (new_mng)
{
png_free(mng_ptr,bb);
return (0);
}
return sum_idat_length;
}
}
# endif
#endif
#ifdef PNGCRUSH_LOCO
if (input_format == 0)
#endif
{
#ifdef PNG_UINT_IEND
if (pngcrush_get_uint_32(chunk_name) == PNG_UINT_IEND)
#else
if (!png_memcmp(chunk_name, png_IEND, 4))
#endif
{
if (!salvage && found_CgBI)
return 0;
else
return sum_idat_length;
}
}
}
}
void print_version_info(void)
{
const char *zlib_copyright;
#ifndef ZLIB_VERNUM /* This became available in zlib-1.2 */
zlib_copyright=" (or later)";
#else
switch (ZLIB_VERNUM)
{
case 0x1220:
zlib_copyright="-2004";
break;
case 0x1230:
zlib_copyright="-2005";
break;
case 0x1240:
case 0x1250:
zlib_copyright="-2010";
break;
case 0x1260:
case 0x1270:
zlib_copyright="-2012";
break;
case 0x1271:
case 0x1280:
zlib_copyright="-2013";
break;
case 0x1290:
case 0x12a0:
case 0x12b0:
zlib_copyright="-2017";
break;
default:
zlib_copyright=" (or later)";
break;
}
#endif
#ifdef PNGCRUSH_H
# define BUNDLED_LIB "bundled"
#else
# define BUNDLED_LIB "system"
#endif
fprintf(STDERR,
"\n"
" | pngcrush-%s\n"
/* If you have modified this source, you may insert additional notices
* immediately after this sentence: */
" | Copyright (C) 1998-2002, 2006-2017 <NAME>\n"
" | Portions Copyright (C) 2005 <NAME>\n"
" | This is a free, open-source program. Permission is irrevocably\n"
" | granted to everyone to use this version of pngcrush without\n"
" | payment of any fee.\n"
" | Executable name is %s\n"
" | It was built with %s libpng-%s\n"
" | and is running with %s libpng-%s\n"
" | Copyright (C) 1998-2004, 2006-2017 <NAME>,\n"
" | Copyright (C) 1996, 1997 <NAME>,\n"
" | Copyright (C) 1995, <NAME>, Group 42 Inc.,\n"
" | and %s zlib-%s, Copyright (C) 1995%s,\n"
" | <NAME> and <NAME>",
PNGCRUSH_VERSION, progname,
BUNDLED_LIB,PNG_LIBPNG_VER_STRING,
BUNDLED_LIB,png_get_header_ver(NULL),
BUNDLED_LIB,ZLIB_VERSION,
zlib_copyright);
#if PNGCRUSH_TIMERS > 0
fprintf(STDERR,
",\n | and using \"%s\".\n",PNGCRUSH_USING_CLOCK);
#else
fprintf(STDERR,"\n");
#endif
#if defined(__GNUC__)
fprintf(STDERR,
" | It was compiled with gcc version %s", __VERSION__);
# if defined(__DJGPP__)
fprintf(STDERR,
"\n"
" | under DJGPP %d.%d, Copyright (C) 1995, DJ Delorie\n"
" | and loaded with PMODE/DJ, by <NAME> and <NAME>\n"
" | Copyright (C) 1996, <NAME>.\n",
__DJGPP__, __DJGPP_MINOR__);
# else
fprintf(STDERR, "\n");
# endif
#endif
#if PNG_ARM_NEON_OPT > 0
fprintf(STDERR," | using ARM_NEON optimizations.\n");
#endif
#if PNG_MIPS_MSA_OPT > 0
fprintf(STDERR," | using MIPS_MSA optimizations.\n");
#endif
#if PNG_POWERPC_VSX_OPT > 0
fprintf(STDERR," | using POWERPC_VSX optimizations.\n");
#endif
#if PNG_INTEL_SSE_OPT > 0
fprintf(STDERR," | using INTEL_SSE optimizations.\n");
#endif
fprintf(STDERR, "\n");
}
static const char *pngcrush_legal[] = {
"",
"If you have modified this source, you may insert additional notices",
"immediately after this sentence.",
"Copyright (C) 1998-2002, 2006-2017 <NAME>",
"Portions Copyright (C) 2005 <NAME>",
"",
"DISCLAIMER: The pngcrush computer program is supplied \"AS IS\".",
"The Author disclaims all warranties, expressed or implied, including,",
"without limitation, the warranties of merchantability and of fitness",
"for any purpose. The Author assumes no liability for direct, indirect,",
"incidental, special, exemplary, or consequential damages, which may",
"result from the use of the computer program, even if advised of the",
"possibility of such damage. There is no warranty against interference",
"with your enjoyment of the computer program or against infringement.",
"There is no warranty that my efforts or the computer program will",
"fulfill any of your particular purposes or needs. This computer",
"program is provided with all faults, and the entire risk of satisfactory",
"quality, performance, accuracy, and effort is with the user.",
"",
"LICENSE: Permission is hereby irrevocably granted to everyone to use,",
"copy, modify, and distribute this computer program, or portions hereof,",
"purpose, without payment of any fee, subject to the following",
"restrictions:",
"",
"1. The origin of this binary or source code must not be misrepresented.",
"",
"2. Altered versions must be plainly marked as such and must not be",
"misrepresented as being the original binary or source.",
"",
"3. The Copyright notice, disclaimer, and license may not be removed",
"or altered from any source, binary, or altered source distribution.",
""
};
static const char *pngcrush_usage[] = {
"\nusage: %s [options except for -e -d] infile.png outfile.png\n",
" %s -e ext [other options] file.png ...\n",
" %s -d dir/ [other options] file.png ...\n",
" %s -ow [other options] file.png [tempfile.png]\n",
" %s -n -v file.png ...\n"
};
struct options_help pngcrush_options[] = {
{0, " -bail (bail out of trial when size exceeds best size found"},
{2, ""},
{2, " Default is to bail out and simply report that the"},
{2, " filesize for the trial would be greater than the"},
{2, " best filesize achieved so far. Use the \"-nobail\""},
{2, " option to prevent that."},
{2, ""},
{0, " -blacken (zero samples underlying fully-transparent pixels)"},
{2, ""},
{2, " Changing the color samples to zero can improve the"},
{2, " compressibility. Since this is a lossy operation,"},
{2, " blackening is off by default."},
{2, ""},
#ifdef Z_RLE
{0, " -brute (use brute-force: try 176 different methods)"},
#else
{0, " -brute (use brute-force: try 166 different methods)"},
#endif
{2, ""},
{2, " Very time-consuming and generally not worthwhile."},
{2, " You can restrict this option to certain filter types,"},
{2, " compression levels, or strategies by following it"},
{2, " with \"-f filter\", \"-l level\", or \"-z strategy\"."},
{2, ""},
{0, FAKE_PAUSE_STRING},
{0, " -c color_type of output file [0, 2, 4, or 6]"},
{2, ""},
{2, " Color type for the output file. Future versions"},
{2, " will also allow color_type 3, if there are 256 or"},
{2, " fewer colors present in the input file. Color types"},
{2, " 4 and 6 are padded with an opaque alpha channel if"},
{2, " the input file does not have alpha information."},
{2, " You can use 0 or 4 to convert color to grayscale."},
{2, " Use 0 or 2 to delete an unwanted alpha channel."},
{2, " Default is to use same color type as the input file."},
{2, ""},
{0, " -check (check CRC and ADLER32 checksums)"},
{2, ""},
{2, " Use \"-nocheck\" (default) to skip checking them"},
{2, ""},
{0, " -d directory_name/ (where output files will go)"},
{2, ""},
{2, " If a directory name is given, then the output"},
{2, " files are placed in it, with the same filenames as"},
{2, " those of the original files. For example,"},
{2, " you would type 'pngcrush -directory CRUSHED/ *.png'"},
{2, " to get *.png => CRUSHED/*.png. The trailing slash is"},
{2, " optional, but if pngcrush appends the wrong kind of"},
{2, " slash or backslash, please include the correct one"},
{2, " at the end of the directory_name, as shown."},
{2, ""},
{0, FAKE_PAUSE_STRING},
{0, " -e extension (used for creating output filename)"},
{2, ""},
{2, " e.g., -ext .new means *.png => *.new"},
{2, " and -e _pc.png means *.png => *_pc.png"},
{2, ""},
{0, " -f user_filter [0-5] for specified method"},
{2, ""},
{2, " filter to use with the method specified in the"},
{2, " preceding '-m method' or '-brute_force' argument."},
{2, " 0: none; 1-4: use specified filter; 5: adaptive."},
{2, ""},
{0, FAKE_PAUSE_STRING},
{0, " -fix (salvage PNG with otherwise fatal conditions)"},
{2, ""},
{2, " Fixes bad CRCs, bad adaptive filter bytes,"},
{2, " or bad CMF bytes in the IDAT chunk that cause"},
{2, " the \"Too far back\" error"},
{2, ""},
{0, " -force (write output even if IDAT is larger)"},
{2, ""},
#ifdef PNG_FIXED_POINT_SUPPORTED
{0, " -g gamma (float or fixed*100000, e.g., 0.45455 or 45455)"},
#else
{0, " -g gamma (float, e.g., 0.45455)"},
#endif
{2, ""},
{2, " Value to insert in gAMA chunk, only if the input"},
{2, " file has no gAMA chunk. To replace an existing"},
{2, " gAMA chunk, use the '-replace_gamma' option."},
{2, ""},
{0, FAKE_PAUSE_STRING},
{0, " -huffman (use only zlib strategy 2, Huffman-only)"},
{2, ""},
{2, " Fast, but almost never very effective except for"},
{2, " certain rare image types."},
{2, ""},
#ifdef PNG_iCCP_SUPPORTED
{0, " -iccp length \"Profile Name\" iccp_file"},
{2, ""},
{2, " file with ICC profile to insert in an iCCP chunk."},
{2, ""},
#endif
#ifdef PNG_iTXt_SUPPORTED
{0, " -itxt b[efore_IDAT]|a[fter_IDAT] \"keyword\""},
{2, " \"language_code\" \"translated_keyword\" \"text\""},
{2, ""},
{2, " Uncompressed iTXt chunk to insert (see -text)."},
{2, ""},
#endif
{0, " -keep chunk_name"},
{2, ""},
{2, " keep named chunk even when pngcrush makes"},
{2, " changes to the PNG datastream that cause it"},
{2, " to become invalid. Currently only dSIG is"},
{2, " recognized as a chunk to be kept."},
{2, ""},
{0, " -l zlib_compression_level [0-9] for specified method"},
{2, ""},
{2, " zlib compression level to use with method specified"},
{2, " with the preceding '-m method' or '-brute_force'"},
{2, " argument."},
{2, ""},
#ifdef PNGCRUSH_LOCO
{0, FAKE_PAUSE_STRING},
{0, " -loco (\"loco crush\" truecolor PNGs)"},
{2, ""},
{2, " Make the file more compressible by performing a"},
{2, " lossless, reversible, color transformation."},
{2, " The resulting file is a MNG, not a PNG, and should"},
{2, " be given the \".mng\" file extension. The"},
{2, " \"loco\" option has no effect on grayscale or"},
{2, " indexed-color PNG files."},
{2, ""},
#endif
{0, " -m method [1 through " STRNGIFY(MAX_METHODS) "]"},
{2, ""},
{2, " pngcrush method to try. Can be repeated as in"},
{2, " '-m 1 -m 4 -m 7'. This can be useful if pngcrush"},
{2, " runs out of memory when it tries methods 2, 3, 5,"},
{2, " 6, 8, 9, or 10 which use filtering and are memory-"},
{2, " intensive. Methods 1, 4, and 7 use no filtering;"},
{2, " methods 11 and up use a specified filter,"},
{2, " compression level, and strategy."},
{2, ""},
{2, FAKE_PAUSE_STRING},
{0, " -max maximum_IDAT_size [default "STRNGIFY(MAX_IDAT_SIZE)"]"},
{2, ""},
#ifdef PNGCRUSH_LOCO
{0, " -mng (write a new MNG, do not crush embedded PNGs)"},
{2, ""},
#endif
{0, " -n (no save; doesn't do compression or write output PNG)"},
{2, ""},
{2, " Useful in conjunction with -v option to get info."},
{2, ""},
{0, " -new (Use new default settings (-reduce))"},
{2, ""},
{0, " -newtimestamp (Reset file modification time [default])"},
{2, ""},
{0, " -nobail (do not bail out early from trial -- see \"-bail\")"},
{2, ""},
{2, " Use this if you want to get a report of the"},
{2, " exact filesize achieved by each trial."},
{2, ""},
{0, " -nocheck (do not check CRC and ADLER32 checksums)"},
{2, ""},
{2, " Use \"-check\" to check them"},
{2, ""},
{0, FAKE_PAUSE_STRING},
{0, " -nofilecheck (do not check for infile.png == outfile.png)"},
{2, ""},
{2, " To avoid false hits from MSVC-compiled code. Note"},
{2, " that if you use this option, you are responsible for"},
{2, " ensuring that the input file is not the output file."},
{2, ""},
{0, " -noforce (default; do not write output when IDAT is larger)"},
{2, ""},
{0, " -nolimits (turns off limits on width, height, cache, malloc)"},
{2, ""},
{2, " Instead, the user limits are inherited from libpng."},
{2, ""},
{0, " -noreduce (turns off all \"-reduce\" operations)"},
{2, ""},
{0, "-noreduce_palette (turns off \"-reduce_palette\" operation)"},
{2, ""},
{0, " -old (Use old default settings (no -reduce))"},
{2, ""},
{0, " -oldtimestamp (Do not reset file modification time)"},
{2, ""},
{0, " -ow (Overwrite)"},
{2, ""},
{2, " Overwrite the input file. The input file is removed"},
{2, " and the temporary file (default \"pngout.png\")"},
{2, " is renamed to the input file after recompression"},
{2, " and therefore they must reside on the same"},
{2, " filesystem."},
{2, ""},
{2, " CAUTION: If you are running multiple instances"},
{2, " of pngcrush in parallel, you must specify a"},
{2, " different temporary filename for each instance,"},
{2, " to avoid collisions."},
{2, ""},
{0, " -q (quiet) suppresses console output except for warnings"},
{2, ""},
{2, " and summary of results."},
{2, ""},
{0, " -reduce (do lossless color-type or bit-depth reduction)"},
{2, ""},
{2, " (if possible). Also reduces palette length if"},
{2, " possible. Currently only attempts to reduce the"},
{2, " bit depth from 16 to 8. Reduces all-gray RGB"},
{2, " or RGBA image to gray or gray-alpha. Reduces"},
{2, " all-opaque RGBA or GA image to RGB or grayscale."},
{2, " Since pngcrush version 1.8.0, -reduce is on by"},
{2, " default, and you can disable it with -noreduce."},
{2, ""},
{0, " -rem chunkname (or \"alla\" or \"allb\")"},
{2, ""},
{2, " Name of an ancillary chunk or optional PLTE to be"},
{2, " removed. Be careful with this. Don't use this"},
{2, " feature to remove transparency, gamma, copyright,"},
{2, " or other valuable information. To remove several"},
{2, " different chunks, repeat: -rem tEXt -rem pHYs."},
{2, " Known chunks (those in the PNG 1.1 spec or extensions"},
{2, " document) can be named with all lower-case letters,"},
{2, " so \"-rem bkgd\" is equivalent to \"-rem bKGD\". But"},
{2, " note: \"-rem text\" removes all forms of text chunks;"},
{2, " Exact case is required to remove unknown chunks."},
{2, " To do surgery with a chain-saw, \"-rem alla\" removes"},
{2, " all known ancillary chunks except for tRNS, and"},
{2, " \"-rem allb\" removes all but tRNS and gAMA."},
{2, ""},
{0, FAKE_PAUSE_STRING},
#ifdef PNG_FIXED_POINT_SUPPORTED
{0, "-replace_gamma gamma (float or fixed*100000) even if it is present."},
#else
{0, "-replace_gamma gamma (float, e.g. 0.45455) even if it is present."},
#endif
{2, ""},
{0, " -res resolution in dpi"},
{2, ""},
{2, " Write a pHYs chunk with the given resolution in dpi"},
{2, " written as pixels per meter in x and y directions."},
{2, ""},
#ifdef Z_RLE
{0, " -rle (use only zlib strategy 3, RLE-only)"},
{2, ""},
{2, " A relatively fast subset of the \"-brute\" methods,"},
{2, " generally more effective than \"-huffman\" on PNG,"},
{2, " images (and quite effective on black-and-white"},
{2, " images) but not necessarily worth the bother"},
{2, " otherwise."},
{2, ""},
#endif
{0, " -s (silent) suppresses console output including warnings"},
{2, ""},
{2, " benchmark timing, and summary of results."},
{2, " (Use \"-warn\" to show only warnings"},
{2, ""},
{0, " -save (keep all copy-unsafe PNG chunks)"},
{2, ""},
{2, " Save otherwise unknown ancillary chunks that would"},
{2, " be considered copy-unsafe. This option makes"},
{2, " chunks 'known' to pngcrush, so they can be copied."},
{2, " It also causes the dSIG chunk to be saved, even when"},
{2, " it becomes invalid due to datastream changes."},
{2, " This option does not affect APNG chunks. These"},
{2, " chunks (acTL, fcTL, and fdAT) will be saved only"},
{2, " if the output file has the \".apng\" extension"},
{2, " and the color_type and bit_depth are not changed."},
{2, ""},
{0, FAKE_PAUSE_STRING},
{0, " -speed Avoid the AVG and PAETH filters, for decoding speed"},
{2, ""},
{2, " Useful for compressing PNG files that are expected"},
{2, " to be cached or otherwise to exist on the computer"},
{2, " where they will be used rather than being downloaded,"},
{2, " so filesize is therefore less important than CPU"},
{2, " time expended in defiltering."},
{2, ""},
{0, " -srgb [0, 1, 2, or 3]"},
{2, ""},
{2, " Value of 'rendering intent' for sRGB chunk."},
{2, ""},
{0, " -ster [0 or 1]"},
{2, ""},
{2, " Value of 'stereo mode' for sTER chunk."},
{2, " 0: cross-fused; 1: divergent-fused"},
{2, ""},
{0, " -text b[efore_IDAT]|a[fter_IDAT] \"keyword\" \"text\""},
{2, ""},
{2, " tEXt chunk to insert. keyword < 80 chars,"},
{2, " text < 2048 chars. For now, you can add no more than"},
{2, " ten tEXt, iTXt, or zTXt chunks per pngcrush run."},
{2, ""},
#ifdef PNG_tRNS_SUPPORTED
{0, " -trns_array n trns[0] trns[1] .. trns[n-1]"},
{2, ""},
{2, " Insert a tRNS chunk, if no tRNS chunk found in file."},
{2, " Values are for the tRNS array in indexed-color PNG."},
{2, ""},
{0, " -trns index red green blue gray"},
{2, ""},
{2, " Insert a tRNS chunk, if no tRNS chunk found in file."},
{2, " You must give all five parameters regardless of the"},
{2, " color type, scaled to the output bit depth."},
{2, ""},
#endif
{0, FAKE_PAUSE_STRING},
{0, " -v (display more detailed information)"},
{2, ""},
{2, " Repeat the option (use \"-v -v\") for even more."},
{2, ""},
{0, " -version (display the pngcrush version)"},
{2, ""},
{2, " Look for the most recent version of pngcrush at"},
{2, " http://pmt.sf.net"},
{2, ""},
{0, " -warn (only show warnings)"},
{2, ""},
{0, " -w compression_window_size [32, 16, 8, 4, 2, 1, 512]"},
{2, ""},
{2, " Size of the sliding compression window, in kbytes"},
{2, " (or bytes, in case of 512). It's best to"},
{2, " use the default (32) unless you run out of memory."},
{2, " The program will use a smaller window anyway when"},
{2, " the uncompressed file is smaller than 16k."},
{2, ""},
#ifdef Z_RLE
{0, " -z zlib_strategy [0, 1, 2, or 3] for specified method"},
#else
{0, " -z zlib_strategy [0, 1, or 2] for specified method"},
#endif
{2, ""},
{2, " zlib compression strategy to use with the preceding"},
{2, " '-m method' argument."},
{2, ""},
{0, " -zmem zlib_compression_mem_level [1-9, default 9]"},
{2, ""},
#ifdef PNG_iTXt_SUPPORTED
{0, " -zitxt b|a \"keyword\" \"lcode\" \"tkey\" \"text\""},
{2, ""},
{2, " (where \"lcode\"==language_code and"},
{2, " \"tkey\"==translated_keyword)\""},
{2, " Compressed iTXt chunk to insert (see -text)."},
{2, ""},
#endif
{0, " -ztxt b[efore_IDAT]|a[fter_IDAT] \"keyword\" \"text\""},
{2, ""},
{2, " zTXt chunk to insert (see -text)."},
{2, ""},
{2, FAKE_PAUSE_STRING},
{0, " -h (help and legal notices)"},
{2, ""},
{2, " Display this information."},
{2, ""},
{0, " -p (pause)"}
};
void print_usage(int retval)
{
int j, jmax;
if (verbose > 0)
{
jmax = sizeof(pngcrush_legal) / sizeof(char *);
for (j = 0; j < jmax; ++j)
fprintf(STDERR, "%s\n", pngcrush_legal[j]);
jmax = sizeof(pngcrush_usage) / sizeof(char *);
for (j = 0; j < jmax; ++j)
fprintf(STDERR, pngcrush_usage[j], progname); /* special case */
}
/* This block is also handled specially due to the "else" clause... */
if (verbose > 1)
{
pngcrush_pause();
fprintf(STDERR,
"\n"
"options (Note: any option can be spelled out for clarity, e.g.,\n"
" \"pngcrush -dir New -method 7 -remove bkgd *.png\"\n"
" is the same as \"pngcrush -d New/ -m 7 -rem bkgd *.png\"):"
"\n\n");
}
else
fprintf(STDERR, "options:\n");
/* This is the main part of the help screen; it is more complex than the
* other blocks due to the mix of verbose and non-verbose lines
*/
jmax = sizeof(pngcrush_options) / sizeof(struct options_help);
for (j = 0; j < jmax; ++j)
{
if (verbose >= pngcrush_options[j].verbosity)
{
if (pngcrush_options[j].textline[0] == FAKE_PAUSE_STRING[0])
pngcrush_pause();
else
fprintf(STDERR, "%s\n", pngcrush_options[j].textline);
}
}
/* due to progname, the verbose part of the -p option is handled explicitly
* (fortunately, it's the very last option anyway)
*/
if (verbose > 1)
{
fprintf(STDERR, "\n"
" Wait for [enter] key before continuing display.\n"
" e.g., type '%s -pause -help', if the help\n"
" screen scrolls out of sight.\n\n", progname);
}
exit(retval);
}
#endif /* PNGCRUSH_LIBPNG_VER < 10800 || defined(PNGCRUSH_H) */
|
salass00/png16_lib
|
static/autoinit_png16_base.c
|
/*
* AmigaOS shared library implementation of libpng 1.6.x
*
* Copyright (C) 2017 <NAME> <<EMAIL>>
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS'
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#include <interfaces/png16.h>
#include <proto/exec.h>
#include <assert.h>
/****************************************************************************/
struct Library * PNG16Base = NULL;
static struct Library * __PNG16Base;
/****************************************************************************/
void _INIT_5_PNG16Base(void)
{
if (PNG16Base != NULL)
{
return; /* Someone was quicker, e.g. an interface constructor */
}
__PNG16Base = PNG16Base = IExec->OpenLibrary("png16.library", 53L);
assert(PNG16Base != NULL);
}
__attribute__((section(".ctors.zzzz"))) static void
(*png16_base_constructor_ptr)(void) USED = _INIT_5_PNG16Base;
/****************************************************************************/
void _EXIT_5_PNG16Base(void)
{
if (__PNG16Base)
{
IExec->CloseLibrary(__PNG16Base);
}
}
__attribute__((section(".dtors.zzzz"))) static void
(*png16_base_destructor_ptr)(void) USED = _EXIT_5_PNG16Base;
/****************************************************************************/
|
salass00/png16_lib
|
static/stubs.c
|
<gh_stars>0
/*
* AmigaOS shared library implementation of libpng 1.6.x
*
* Copyright (C) 2017 <NAME> <<EMAIL>>
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS'
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#include <interfaces/png16.h>
asm("\t.section\t\".text\"\n"
"\t.align\t2\n"
"\t.globl\t__CallPNG16\n"
"\t.type\t__CallPNG16, @function\n"
"__CallPNG16:\n"
"\tlis\t%r11,IPNG16@ha\n"
"\tlwz\t%r0,IPNG16@l(%r11)\n"
"\tlwzx\t%r11,%r12,%r0\n"
"\tmtctr\t%r11\n"
"\tbctr\n"
"\t.size\t__CallPNG16, .-__CallPNG16");
#define PNG16Call(function, offset) \
asm("\t.section\t\".text\"\n" \
"\t.align\t2\n" \
"\t.globl\t" #function "\n" \
"\t.type\t" #function ", @function\n" \
#function ":\n" \
"\tli\t%r12," #offset "\n" \
"\tb\t__CallPNG16\n" \
"\t.size\t" #function ", .-" #function);
PNG16Call(png_access_version_number, 76)
PNG16Call(png_set_sig_bytes, 80)
PNG16Call(png_sig_cmp, 84)
PNG16Call(png_create_read_struct, 88)
PNG16Call(png_create_write_struct, 92)
PNG16Call(png_get_compression_buffer_size, 96)
PNG16Call(png_set_compression_buffer_size, 100)
PNG16Call(png_set_longjmp_fn, 104)
PNG16Call(png_longjmp, 108)
PNG16Call(png_create_read_struct_2, 112)
PNG16Call(png_create_write_struct_2, 116)
PNG16Call(png_write_sig, 120)
PNG16Call(png_write_chunk, 124)
PNG16Call(png_write_chunk_start, 128)
PNG16Call(png_write_chunk_data, 132)
PNG16Call(png_write_chunk_end, 136)
PNG16Call(png_create_info_struct, 140)
PNG16Call(png_write_info_before_PLTE, 144)
PNG16Call(png_write_info, 148)
PNG16Call(png_read_info, 152)
PNG16Call(png_convert_to_rfc1123_buffer, 156)
PNG16Call(png_convert_from_struct_tm, 160)
PNG16Call(png_convert_from_time_t, 164)
PNG16Call(png_set_expand, 168)
PNG16Call(png_set_expand_gray_1_2_4_to_8, 172)
PNG16Call(png_set_palette_to_rgb, 176)
PNG16Call(png_set_tRNS_to_alpha, 180)
PNG16Call(png_set_expand_16, 184)
PNG16Call(png_set_bgr, 188)
PNG16Call(png_set_gray_to_rgb, 192)
PNG16Call(png_set_rgb_to_gray, 196)
PNG16Call(png_set_rgb_to_gray_fixed, 200)
PNG16Call(png_get_rgb_to_gray_status, 204)
PNG16Call(png_build_grayscale_palette, 208)
PNG16Call(png_set_alpha_mode, 212)
PNG16Call(png_set_alpha_mode_fixed, 216)
PNG16Call(png_set_strip_alpha, 220)
PNG16Call(png_set_swap_alpha, 224)
PNG16Call(png_set_invert_alpha, 228)
PNG16Call(png_set_filler, 232)
PNG16Call(png_set_add_alpha, 236)
PNG16Call(png_set_swap, 240)
PNG16Call(png_set_packing, 244)
PNG16Call(png_set_packswap, 248)
PNG16Call(png_set_shift, 252)
PNG16Call(png_set_interlace_handling, 256)
PNG16Call(png_set_invert_mono, 260)
PNG16Call(png_set_background, 264)
PNG16Call(png_set_background_fixed, 268)
PNG16Call(png_set_scale_16, 272)
PNG16Call(png_set_strip_16, 276)
PNG16Call(png_set_quantize, 280)
PNG16Call(png_set_gamma, 284)
PNG16Call(png_set_gamma_fixed, 288)
PNG16Call(png_set_flush, 292)
PNG16Call(png_write_flush, 296)
PNG16Call(png_start_read_image, 300)
PNG16Call(png_read_update_info, 304)
PNG16Call(png_read_rows, 308)
PNG16Call(png_read_row, 312)
PNG16Call(png_write_row, 316)
PNG16Call(png_write_rows, 320)
PNG16Call(png_write_image, 324)
PNG16Call(png_write_end, 328)
PNG16Call(png_read_end, 332)
PNG16Call(png_destroy_info_struct, 336)
PNG16Call(png_destroy_read_struct, 340)
PNG16Call(png_destroy_write_struct, 344)
PNG16Call(png_set_crc_action, 348)
PNG16Call(png_set_filter, 352)
PNG16Call(png_set_filter_heuristics, 356)
PNG16Call(png_set_filter_heuristics_fixed, 360)
PNG16Call(png_set_compression_level, 364)
PNG16Call(png_set_compression_mem_level, 368)
PNG16Call(png_set_compression_strategy, 372)
PNG16Call(png_set_compression_window_bits, 376)
PNG16Call(png_set_compression_method, 380)
PNG16Call(png_set_text_compression_level, 384)
PNG16Call(png_set_text_compression_mem_level, 388)
PNG16Call(png_set_text_compression_strategy, 392)
PNG16Call(png_set_text_compression_window_bits, 396)
PNG16Call(png_set_text_compression_method, 400)
PNG16Call(png_init_io, 404)
PNG16Call(png_set_error_fn, 408)
PNG16Call(png_get_error_ptr, 412)
PNG16Call(png_set_write_fn, 416)
PNG16Call(png_set_read_fn, 420)
PNG16Call(png_get_io_ptr, 424)
PNG16Call(png_set_read_status_fn, 428)
PNG16Call(png_set_write_status_fn, 432)
PNG16Call(png_set_mem_fn, 436)
PNG16Call(png_get_mem_ptr, 440)
PNG16Call(png_set_read_user_transform_fn, 444)
PNG16Call(png_set_write_user_transform_fn, 448)
PNG16Call(png_set_user_transform_info, 452)
PNG16Call(png_get_user_transform_ptr, 456)
PNG16Call(png_get_current_row_number, 460)
PNG16Call(png_get_current_pass_number, 464)
PNG16Call(png_set_read_user_chunk_fn, 468)
PNG16Call(png_get_user_chunk_ptr, 472)
PNG16Call(png_set_progressive_read_fn, 476)
PNG16Call(png_get_progressive_ptr, 480)
PNG16Call(png_process_data, 484)
PNG16Call(png_process_data_pause, 488)
PNG16Call(png_process_data_skip, 492)
PNG16Call(png_progressive_combine_row, 496)
PNG16Call(png_malloc, 500)
PNG16Call(png_calloc, 504)
PNG16Call(png_malloc_warn, 508)
PNG16Call(png_free, 512)
PNG16Call(png_free_data, 516)
PNG16Call(png_data_freer, 520)
PNG16Call(png_error, 524)
PNG16Call(png_chunk_error, 528)
PNG16Call(png_warning, 532)
PNG16Call(png_chunk_warning, 536)
PNG16Call(png_benign_error, 540)
PNG16Call(png_chunk_benign_error, 544)
PNG16Call(png_set_benign_errors, 548)
PNG16Call(png_get_valid, 552)
PNG16Call(png_get_rowbytes, 556)
PNG16Call(png_get_rows, 560)
PNG16Call(png_set_rows, 564)
PNG16Call(png_get_channels, 568)
PNG16Call(png_get_image_width, 572)
PNG16Call(png_get_image_height, 576)
PNG16Call(png_get_bit_depth, 580)
PNG16Call(png_get_color_type, 584)
PNG16Call(png_get_filter_type, 588)
PNG16Call(png_get_interlace_type, 592)
PNG16Call(png_get_compression_type, 596)
PNG16Call(png_get_pixels_per_meter, 600)
PNG16Call(png_get_x_pixels_per_meter, 604)
PNG16Call(png_get_y_pixels_per_meter, 608)
PNG16Call(png_get_pixel_aspect_ratio, 612)
PNG16Call(png_get_pixel_aspect_ratio_fixed, 616)
PNG16Call(png_get_x_offset_pixels, 620)
PNG16Call(png_get_y_offset_pixels, 624)
PNG16Call(png_get_x_offset_microns, 628)
PNG16Call(png_get_y_offset_microns, 632)
PNG16Call(png_get_signature, 636)
PNG16Call(png_get_bKGD, 640)
PNG16Call(png_set_bKGD, 644)
PNG16Call(png_get_cHRM, 648)
PNG16Call(png_get_cHRM_XYZ, 652)
PNG16Call(png_get_cHRM_fixed, 656)
PNG16Call(png_get_cHRM_XYZ_fixed, 660)
PNG16Call(png_set_cHRM, 664)
PNG16Call(png_set_cHRM_XYZ, 668)
PNG16Call(png_set_cHRM_fixed, 672)
PNG16Call(png_set_cHRM_XYZ_fixed, 676)
PNG16Call(png_get_eXIf, 680)
PNG16Call(png_set_eXIf, 684)
PNG16Call(png_get_eXIf_1, 688)
PNG16Call(png_set_eXIf_1, 692)
PNG16Call(png_get_gAMA, 696)
PNG16Call(png_get_gAMA_fixed, 700)
PNG16Call(png_set_gAMA, 704)
PNG16Call(png_set_gAMA_fixed, 708)
PNG16Call(png_get_hIST, 712)
PNG16Call(png_set_hIST, 716)
PNG16Call(png_get_IHDR, 720)
PNG16Call(png_set_IHDR, 724)
PNG16Call(png_get_oFFs, 728)
PNG16Call(png_set_oFFs, 732)
PNG16Call(png_get_pCAL, 736)
PNG16Call(png_set_pCAL, 740)
PNG16Call(png_get_pHYs, 744)
PNG16Call(png_set_pHYs, 748)
PNG16Call(png_get_PLTE, 752)
PNG16Call(png_set_PLTE, 756)
PNG16Call(png_get_sBIT, 760)
PNG16Call(png_set_sBIT, 764)
PNG16Call(png_get_sRGB, 768)
PNG16Call(png_set_sRGB, 772)
PNG16Call(png_set_sRGB_gAMA_and_cHRM, 776)
PNG16Call(png_get_iCCP, 780)
PNG16Call(png_set_iCCP, 784)
PNG16Call(png_get_sPLT, 788)
PNG16Call(png_set_sPLT, 792)
PNG16Call(png_get_text, 796)
PNG16Call(png_set_text, 800)
PNG16Call(png_get_tIME, 804)
PNG16Call(png_set_tIME, 808)
PNG16Call(png_get_tRNS, 812)
PNG16Call(png_set_tRNS, 816)
PNG16Call(png_get_sCAL, 820)
PNG16Call(png_get_sCAL_fixed, 824)
PNG16Call(png_get_sCAL_s, 828)
PNG16Call(png_set_sCAL, 832)
PNG16Call(png_set_sCAL_fixed, 836)
PNG16Call(png_set_sCAL_s, 840)
PNG16Call(png_set_keep_unknown_chunks, 844)
PNG16Call(png_handle_as_unknown, 848)
PNG16Call(png_set_unknown_chunks, 852)
PNG16Call(png_set_unknown_chunk_location, 856)
PNG16Call(png_get_unknown_chunks, 860)
PNG16Call(png_set_invalid, 864)
PNG16Call(png_read_png, 868)
PNG16Call(png_write_png, 872)
PNG16Call(png_get_copyright, 876)
PNG16Call(png_get_header_ver, 880)
PNG16Call(png_get_header_version, 884)
PNG16Call(png_get_libpng_ver, 888)
PNG16Call(png_permit_mng_features, 892)
PNG16Call(png_set_user_limits, 896)
PNG16Call(png_get_user_width_max, 900)
PNG16Call(png_get_user_height_max, 904)
PNG16Call(png_set_chunk_cache_max, 908)
PNG16Call(png_get_chunk_cache_max, 912)
PNG16Call(png_set_chunk_malloc_max, 916)
PNG16Call(png_get_chunk_malloc_max, 920)
PNG16Call(png_get_pixels_per_inch, 924)
PNG16Call(png_get_x_pixels_per_inch, 928)
PNG16Call(png_get_y_pixels_per_inch, 932)
PNG16Call(png_get_x_offset_inches, 936)
PNG16Call(png_get_x_offset_inches_fixed, 940)
PNG16Call(png_get_y_offset_inches, 944)
PNG16Call(png_get_y_offset_inches_fixed, 948)
PNG16Call(png_get_pHYs_dpi, 952)
PNG16Call(png_get_io_state, 956)
PNG16Call(png_get_io_chunk_type, 960)
PNG16Call(png_get_uint_32, 964)
PNG16Call(png_get_uint_16, 968)
PNG16Call(png_get_int_32, 972)
PNG16Call(png_get_uint_31, 976)
PNG16Call(png_save_uint_32, 980)
PNG16Call(png_save_int_32, 984)
PNG16Call(png_save_uint_16, 988)
PNG16Call(png_set_check_for_invalid_index, 992)
PNG16Call(png_get_palette_max, 996)
PNG16Call(png_image_begin_read_from_file, 1000)
PNG16Call(png_image_begin_read_from_stdio, 1004)
PNG16Call(png_image_begin_read_from_memory, 1008)
PNG16Call(png_image_finish_read, 1012)
PNG16Call(png_image_free, 1016)
PNG16Call(png_image_write_to_file, 1020)
PNG16Call(png_image_write_to_stdio, 1024)
PNG16Call(png_image_write_to_memory, 1028)
PNG16Call(png_set_option, 1032)
|
ncantelmo/testbed
|
src/test.c
|
<gh_stars>0
#include <stdio.h>
int add(int, int);
int main() {
printf("Hello, world!\n");
int added = add(3, 5);
printf("add(3,5) result: %d\n", added);
return 0;
}
int add(int x, int y) {
return x + y;
}
|
BlueberryMC/NativeUtil
|
src/main/c/net_blueberrymc_native_util_NativeAccessor.h
|
/* DO NOT EDIT THIS FILE - it is machine generated */
#include <jni.h>
/* Header for class net_blueberrymc_native_util_NativeAccessor */
#ifndef _Included_net_blueberrymc_native_util_NativeAccessor
#define _Included_net_blueberrymc_native_util_NativeAccessor
#ifdef __cplusplus
extern "C" {
#endif
/*
* Class: net_blueberrymc_native_util_NativeAccessor
* Method: init
* Signature: ()V
*/
JNIEXPORT void JNICALL Java_net_blueberrymc_native_1util_NativeAccessor_init
(JNIEnv *, jclass);
/*
* Class: net_blueberrymc_native_util_NativeAccessor
* Method: appendToBootstrapClassLoaderSearch
* Signature: (Ljava/lang/String;)V
*/
JNIEXPORT void JNICALL Java_net_blueberrymc_native_1util_NativeAccessor_appendToBootstrapClassLoaderSearch
(JNIEnv *, jclass, jstring);
/*
* Class: net_blueberrymc_native_util_NativeAccessor
* Method: appendToSystemClassLoaderSearch
* Signature: (Ljava/lang/String;)V
*/
JNIEXPORT void JNICALL Java_net_blueberrymc_native_1util_NativeAccessor_appendToSystemClassLoaderSearch
(JNIEnv *, jclass, jstring);
/*
* Class: net_blueberrymc_native_util_NativeAccessor
* Method: allocateInstance
* Signature: (Ljava/lang/Class;)Ljava/lang/Object;
*/
JNIEXPORT jobject JNICALL Java_net_blueberrymc_native_1util_NativeAccessor_allocateInstance
(JNIEnv *, jclass, jclass);
/*
* Class: net_blueberrymc_native_util_NativeAccessor
* Method: setBoolean
* Signature: (Ljava/lang/reflect/Field;Ljava/lang/Object;Z)V
*/
JNIEXPORT void JNICALL Java_net_blueberrymc_native_1util_NativeAccessor_setBoolean
(JNIEnv *, jclass, jobject, jobject, jboolean);
/*
* Class: net_blueberrymc_native_util_NativeAccessor
* Method: setByte
* Signature: (Ljava/lang/reflect/Field;Ljava/lang/Object;B)V
*/
JNIEXPORT void JNICALL Java_net_blueberrymc_native_1util_NativeAccessor_setByte
(JNIEnv *, jclass, jobject, jobject, jbyte);
/*
* Class: net_blueberrymc_native_util_NativeAccessor
* Method: setChar
* Signature: (Ljava/lang/reflect/Field;Ljava/lang/Object;C)V
*/
JNIEXPORT void JNICALL Java_net_blueberrymc_native_1util_NativeAccessor_setChar
(JNIEnv *, jclass, jobject, jobject, jchar);
/*
* Class: net_blueberrymc_native_util_NativeAccessor
* Method: setDouble
* Signature: (Ljava/lang/reflect/Field;Ljava/lang/Object;D)V
*/
JNIEXPORT void JNICALL Java_net_blueberrymc_native_1util_NativeAccessor_setDouble
(JNIEnv *, jclass, jobject, jobject, jdouble);
/*
* Class: net_blueberrymc_native_util_NativeAccessor
* Method: setFloat
* Signature: (Ljava/lang/reflect/Field;Ljava/lang/Object;F)V
*/
JNIEXPORT void JNICALL Java_net_blueberrymc_native_1util_NativeAccessor_setFloat
(JNIEnv *, jclass, jobject, jobject, jfloat);
/*
* Class: net_blueberrymc_native_util_NativeAccessor
* Method: setInt
* Signature: (Ljava/lang/reflect/Field;Ljava/lang/Object;I)V
*/
JNIEXPORT void JNICALL Java_net_blueberrymc_native_1util_NativeAccessor_setInt
(JNIEnv *, jclass, jobject, jobject, jint);
/*
* Class: net_blueberrymc_native_util_NativeAccessor
* Method: setLong
* Signature: (Ljava/lang/reflect/Field;Ljava/lang/Object;J)V
*/
JNIEXPORT void JNICALL Java_net_blueberrymc_native_1util_NativeAccessor_setLong
(JNIEnv *, jclass, jobject, jobject, jlong);
/*
* Class: net_blueberrymc_native_util_NativeAccessor
* Method: setShort
* Signature: (Ljava/lang/reflect/Field;Ljava/lang/Object;S)V
*/
JNIEXPORT void JNICALL Java_net_blueberrymc_native_1util_NativeAccessor_setShort
(JNIEnv *, jclass, jobject, jobject, jshort);
/*
* Class: net_blueberrymc_native_util_NativeAccessor
* Method: setObject
* Signature: (Ljava/lang/reflect/Field;Ljava/lang/Object;Ljava/lang/Object;)V
*/
JNIEXPORT void JNICALL Java_net_blueberrymc_native_1util_NativeAccessor_setObject
(JNIEnv *, jclass, jobject, jobject, jobject);
/*
* Class: net_blueberrymc_native_util_NativeAccessor
* Method: getBoolean
* Signature: (Ljava/lang/reflect/Field;Ljava/lang/Object;)Z
*/
JNIEXPORT jboolean JNICALL Java_net_blueberrymc_native_1util_NativeAccessor_getBoolean
(JNIEnv *, jclass, jobject, jobject);
/*
* Class: net_blueberrymc_native_util_NativeAccessor
* Method: getByte
* Signature: (Ljava/lang/reflect/Field;Ljava/lang/Object;)B
*/
JNIEXPORT jbyte JNICALL Java_net_blueberrymc_native_1util_NativeAccessor_getByte
(JNIEnv *, jclass, jobject, jobject);
/*
* Class: net_blueberrymc_native_util_NativeAccessor
* Method: getChar
* Signature: (Ljava/lang/reflect/Field;Ljava/lang/Object;)C
*/
JNIEXPORT jchar JNICALL Java_net_blueberrymc_native_1util_NativeAccessor_getChar
(JNIEnv *, jclass, jobject, jobject);
/*
* Class: net_blueberrymc_native_util_NativeAccessor
* Method: getDouble
* Signature: (Ljava/lang/reflect/Field;Ljava/lang/Object;)D
*/
JNIEXPORT jdouble JNICALL Java_net_blueberrymc_native_1util_NativeAccessor_getDouble
(JNIEnv *, jclass, jobject, jobject);
/*
* Class: net_blueberrymc_native_util_NativeAccessor
* Method: getFloat
* Signature: (Ljava/lang/reflect/Field;Ljava/lang/Object;)F
*/
JNIEXPORT jfloat JNICALL Java_net_blueberrymc_native_1util_NativeAccessor_getFloat
(JNIEnv *, jclass, jobject, jobject);
/*
* Class: net_blueberrymc_native_util_NativeAccessor
* Method: getInt
* Signature: (Ljava/lang/reflect/Field;Ljava/lang/Object;)I
*/
JNIEXPORT jint JNICALL Java_net_blueberrymc_native_1util_NativeAccessor_getInt
(JNIEnv *, jclass, jobject, jobject);
/*
* Class: net_blueberrymc_native_util_NativeAccessor
* Method: getLong
* Signature: (Ljava/lang/reflect/Field;Ljava/lang/Object;)J
*/
JNIEXPORT jlong JNICALL Java_net_blueberrymc_native_1util_NativeAccessor_getLong
(JNIEnv *, jclass, jobject, jobject);
/*
* Class: net_blueberrymc_native_util_NativeAccessor
* Method: getShort
* Signature: (Ljava/lang/reflect/Field;Ljava/lang/Object;)S
*/
JNIEXPORT jshort JNICALL Java_net_blueberrymc_native_1util_NativeAccessor_getShort
(JNIEnv *, jclass, jobject, jobject);
/*
* Class: net_blueberrymc_native_util_NativeAccessor
* Method: getObject
* Signature: (Ljava/lang/reflect/Field;Ljava/lang/Object;)Ljava/lang/Object;
*/
JNIEXPORT jobject JNICALL Java_net_blueberrymc_native_1util_NativeAccessor_getObject
(JNIEnv *, jclass, jobject, jobject);
/*
* Class: net_blueberrymc_native_util_NativeAccessor
* Method: invokeVoid
* Signature: (Ljava/lang/reflect/Method;Ljava/lang/Object;[Ljava/lang/Object;)V
*/
JNIEXPORT void JNICALL Java_net_blueberrymc_native_1util_NativeAccessor_invokeVoid
(JNIEnv *, jclass, jobject, jobject, jobjectArray);
/*
* Class: net_blueberrymc_native_util_NativeAccessor
* Method: invokeBoolean
* Signature: (Ljava/lang/reflect/Method;Ljava/lang/Object;[Ljava/lang/Object;)Z
*/
JNIEXPORT jboolean JNICALL Java_net_blueberrymc_native_1util_NativeAccessor_invokeBoolean
(JNIEnv *, jclass, jobject, jobject, jobjectArray);
/*
* Class: net_blueberrymc_native_util_NativeAccessor
* Method: invokeByte
* Signature: (Ljava/lang/reflect/Method;Ljava/lang/Object;[Ljava/lang/Object;)B
*/
JNIEXPORT jbyte JNICALL Java_net_blueberrymc_native_1util_NativeAccessor_invokeByte
(JNIEnv *, jclass, jobject, jobject, jobjectArray);
/*
* Class: net_blueberrymc_native_util_NativeAccessor
* Method: invokeChar
* Signature: (Ljava/lang/reflect/Method;Ljava/lang/Object;[Ljava/lang/Object;)C
*/
JNIEXPORT jchar JNICALL Java_net_blueberrymc_native_1util_NativeAccessor_invokeChar
(JNIEnv *, jclass, jobject, jobject, jobjectArray);
/*
* Class: net_blueberrymc_native_util_NativeAccessor
* Method: invokeDouble
* Signature: (Ljava/lang/reflect/Method;Ljava/lang/Object;[Ljava/lang/Object;)D
*/
JNIEXPORT jdouble JNICALL Java_net_blueberrymc_native_1util_NativeAccessor_invokeDouble
(JNIEnv *, jclass, jobject, jobject, jobjectArray);
/*
* Class: net_blueberrymc_native_util_NativeAccessor
* Method: invokeFloat
* Signature: (Ljava/lang/reflect/Method;Ljava/lang/Object;[Ljava/lang/Object;)F
*/
JNIEXPORT jfloat JNICALL Java_net_blueberrymc_native_1util_NativeAccessor_invokeFloat
(JNIEnv *, jclass, jobject, jobject, jobjectArray);
/*
* Class: net_blueberrymc_native_util_NativeAccessor
* Method: invokeInt
* Signature: (Ljava/lang/reflect/Method;Ljava/lang/Object;[Ljava/lang/Object;)I
*/
JNIEXPORT jint JNICALL Java_net_blueberrymc_native_1util_NativeAccessor_invokeInt
(JNIEnv *, jclass, jobject, jobject, jobjectArray);
/*
* Class: net_blueberrymc_native_util_NativeAccessor
* Method: invokeLong
* Signature: (Ljava/lang/reflect/Method;Ljava/lang/Object;[Ljava/lang/Object;)J
*/
JNIEXPORT jlong JNICALL Java_net_blueberrymc_native_1util_NativeAccessor_invokeLong
(JNIEnv *, jclass, jobject, jobject, jobjectArray);
/*
* Class: net_blueberrymc_native_util_NativeAccessor
* Method: invokeShort
* Signature: (Ljava/lang/reflect/Method;Ljava/lang/Object;[Ljava/lang/Object;)S
*/
JNIEXPORT jshort JNICALL Java_net_blueberrymc_native_1util_NativeAccessor_invokeShort
(JNIEnv *, jclass, jobject, jobject, jobjectArray);
/*
* Class: net_blueberrymc_native_util_NativeAccessor
* Method: invokeObject
* Signature: (Ljava/lang/reflect/Method;Ljava/lang/Object;[Ljava/lang/Object;)Ljava/lang/Object;
*/
JNIEXPORT jobject JNICALL Java_net_blueberrymc_native_1util_NativeAccessor_invokeObject
(JNIEnv *, jclass, jobject, jobject, jobjectArray);
/*
* Class: net_blueberrymc_native_util_NativeAccessor
* Method: invokeNonvirtualVoid
* Signature: (Ljava/lang/reflect/Method;Ljava/lang/Object;[Ljava/lang/Object;)V
*/
JNIEXPORT void JNICALL Java_net_blueberrymc_native_1util_NativeAccessor_invokeNonvirtualVoid
(JNIEnv *, jclass, jobject, jobject, jobjectArray);
/*
* Class: net_blueberrymc_native_util_NativeAccessor
* Method: invokeNonvirtualBoolean
* Signature: (Ljava/lang/reflect/Method;Ljava/lang/Object;[Ljava/lang/Object;)Z
*/
JNIEXPORT jboolean JNICALL Java_net_blueberrymc_native_1util_NativeAccessor_invokeNonvirtualBoolean
(JNIEnv *, jclass, jobject, jobject, jobjectArray);
/*
* Class: net_blueberrymc_native_util_NativeAccessor
* Method: invokeNonvirtualByte
* Signature: (Ljava/lang/reflect/Method;Ljava/lang/Object;[Ljava/lang/Object;)B
*/
JNIEXPORT jbyte JNICALL Java_net_blueberrymc_native_1util_NativeAccessor_invokeNonvirtualByte
(JNIEnv *, jclass, jobject, jobject, jobjectArray);
/*
* Class: net_blueberrymc_native_util_NativeAccessor
* Method: invokeNonvirtualChar
* Signature: (Ljava/lang/reflect/Method;Ljava/lang/Object;[Ljava/lang/Object;)C
*/
JNIEXPORT jchar JNICALL Java_net_blueberrymc_native_1util_NativeAccessor_invokeNonvirtualChar
(JNIEnv *, jclass, jobject, jobject, jobjectArray);
/*
* Class: net_blueberrymc_native_util_NativeAccessor
* Method: invokeNonvirtualDouble
* Signature: (Ljava/lang/reflect/Method;Ljava/lang/Object;[Ljava/lang/Object;)D
*/
JNIEXPORT jdouble JNICALL Java_net_blueberrymc_native_1util_NativeAccessor_invokeNonvirtualDouble
(JNIEnv *, jclass, jobject, jobject, jobjectArray);
/*
* Class: net_blueberrymc_native_util_NativeAccessor
* Method: invokeNonvirtualFloat
* Signature: (Ljava/lang/reflect/Method;Ljava/lang/Object;[Ljava/lang/Object;)F
*/
JNIEXPORT jfloat JNICALL Java_net_blueberrymc_native_1util_NativeAccessor_invokeNonvirtualFloat
(JNIEnv *, jclass, jobject, jobject, jobjectArray);
/*
* Class: net_blueberrymc_native_util_NativeAccessor
* Method: invokeNonvirtualInt
* Signature: (Ljava/lang/reflect/Method;Ljava/lang/Object;[Ljava/lang/Object;)I
*/
JNIEXPORT jint JNICALL Java_net_blueberrymc_native_1util_NativeAccessor_invokeNonvirtualInt
(JNIEnv *, jclass, jobject, jobject, jobjectArray);
/*
* Class: net_blueberrymc_native_util_NativeAccessor
* Method: invokeNonvirtualLong
* Signature: (Ljava/lang/reflect/Method;Ljava/lang/Object;[Ljava/lang/Object;)J
*/
JNIEXPORT jlong JNICALL Java_net_blueberrymc_native_1util_NativeAccessor_invokeNonvirtualLong
(JNIEnv *, jclass, jobject, jobject, jobjectArray);
/*
* Class: net_blueberrymc_native_util_NativeAccessor
* Method: invokeNonvirtualShort
* Signature: (Ljava/lang/reflect/Method;Ljava/lang/Object;[Ljava/lang/Object;)S
*/
JNIEXPORT jshort JNICALL Java_net_blueberrymc_native_1util_NativeAccessor_invokeNonvirtualShort
(JNIEnv *, jclass, jobject, jobject, jobjectArray);
/*
* Class: net_blueberrymc_native_util_NativeAccessor
* Method: invokeNonvirtualObject
* Signature: (Ljava/lang/reflect/Method;Ljava/lang/Object;[Ljava/lang/Object;)Ljava/lang/Object;
*/
JNIEXPORT jobject JNICALL Java_net_blueberrymc_native_1util_NativeAccessor_invokeNonvirtualObject
(JNIEnv *, jclass, jobject, jobject, jobjectArray);
/*
* Class: net_blueberrymc_native_util_NativeAccessor
* Method: newInstance
* Signature: (Ljava/lang/reflect/Constructor;[Ljava/lang/Object;)Ljava/lang/Object;
*/
JNIEXPORT jobject JNICALL Java_net_blueberrymc_native_1util_NativeAccessor_newInstance
(JNIEnv *, jclass, jobject, jobjectArray);
/*
* Class: net_blueberrymc_native_util_NativeAccessor
* Method: getStaticMethod
* Signature: (Ljava/lang/Class;Ljava/lang/String;Ljava/lang/String;)Ljava/lang/reflect/Method;
*/
JNIEXPORT jobject JNICALL Java_net_blueberrymc_native_1util_NativeAccessor_getStaticMethod
(JNIEnv *, jclass, jclass, jstring, jstring);
/*
* Class: net_blueberrymc_native_util_NativeAccessor
* Method: getNonstaticMethod
* Signature: (Ljava/lang/Class;Ljava/lang/String;Ljava/lang/String;)Ljava/lang/reflect/Method;
*/
JNIEXPORT jobject JNICALL Java_net_blueberrymc_native_1util_NativeAccessor_getNonstaticMethod
(JNIEnv *, jclass, jclass, jstring, jstring);
/*
* Class: net_blueberrymc_native_util_NativeAccessor
* Method: getStaticField
* Signature: (Ljava/lang/Class;Ljava/lang/String;Ljava/lang/String;)Ljava/lang/reflect/Field;
*/
JNIEXPORT jobject JNICALL Java_net_blueberrymc_native_1util_NativeAccessor_getStaticField
(JNIEnv *, jclass, jclass, jstring, jstring);
/*
* Class: net_blueberrymc_native_util_NativeAccessor
* Method: getNonstaticField
* Signature: (Ljava/lang/Class;Ljava/lang/String;Ljava/lang/String;)Ljava/lang/reflect/Field;
*/
JNIEXPORT jobject JNICALL Java_net_blueberrymc_native_1util_NativeAccessor_getNonstaticField
(JNIEnv *, jclass, jclass, jstring, jstring);
/*
* Class: net_blueberrymc_native_util_NativeAccessor
* Method: defineClass
* Signature: (Ljava/lang/String;Ljava/lang/ClassLoader;[BI)Ljava/lang/Class;
*/
JNIEXPORT jclass JNICALL Java_net_blueberrymc_native_1util_NativeAccessor_defineClass
(JNIEnv *, jclass, jstring, jobject, jbyteArray, jint);
/*
* Class: net_blueberrymc_native_util_NativeAccessor
* Method: forceGarbageCollection
* Signature: ()V
*/
JNIEXPORT void JNICALL Java_net_blueberrymc_native_1util_NativeAccessor_forceGarbageCollection
(JNIEnv *, jclass);
/*
* Class: net_blueberrymc_native_util_NativeAccessor
* Method: getLoadedClasses
* Signature: ()[Ljava/lang/Class;
*/
JNIEXPORT jobjectArray JNICALL Java_net_blueberrymc_native_1util_NativeAccessor_getLoadedClasses
(JNIEnv *, jclass);
/*
* Class: net_blueberrymc_native_util_NativeAccessor
* Method: getClassLoaderClasses
* Signature: (Ljava/lang/ClassLoader;)[Ljava/lang/Class;
*/
JNIEXPORT jobjectArray JNICALL Java_net_blueberrymc_native_1util_NativeAccessor_getClassLoaderClasses
(JNIEnv *, jclass, jobject);
/*
* Class: net_blueberrymc_native_util_NativeAccessor
* Method: retransformClasses
* Signature: ([Ljava/lang/Class;)V
*/
JNIEXPORT void JNICALL Java_net_blueberrymc_native_1util_NativeAccessor_retransformClasses
(JNIEnv *, jclass, jobjectArray);
/*
* Class: net_blueberrymc_native_util_NativeAccessor
* Method: getObjectSize
* Signature: (Ljava/lang/Object;)J
*/
JNIEXPORT jlong JNICALL Java_net_blueberrymc_native_1util_NativeAccessor_getObjectSize
(JNIEnv *, jclass, jobject);
/*
* Class: net_blueberrymc_native_util_NativeAccessor
* Method: getObjectHashcode
* Signature: (Ljava/lang/Object;)I
*/
JNIEXPORT jint JNICALL Java_net_blueberrymc_native_1util_NativeAccessor_getObjectHashcode
(JNIEnv *, jclass, jobject);
/*
* Class: net_blueberrymc_native_util_NativeAccessor
* Method: registerClassLoadHook
* Signature: (Lnet/blueberrymc/native_util/ClassLoadHook;)V
*/
JNIEXPORT void JNICALL Java_net_blueberrymc_native_1util_NativeAccessor_registerClassLoadHook
(JNIEnv *, jclass, jobject);
/*
* Class: net_blueberrymc_native_util_NativeAccessor
* Method: isModifiableClass
* Signature: (Ljava/lang/Class;)Z
*/
JNIEXPORT jboolean JNICALL Java_net_blueberrymc_native_1util_NativeAccessor_isModifiableClass
(JNIEnv *, jclass, jclass);
/*
* Class: net_blueberrymc_native_util_NativeAccessor
* Method: canRedefineClasses
* Signature: ()Z
*/
JNIEXPORT jboolean JNICALL Java_net_blueberrymc_native_1util_NativeAccessor_canRedefineClasses
(JNIEnv *, jclass);
/*
* Class: net_blueberrymc_native_util_NativeAccessor
* Method: redefineClasses
* Signature: ([Lnet/blueberrymc/native_util/ClassDefinition;)V
*/
JNIEXPORT void JNICALL Java_net_blueberrymc_native_1util_NativeAccessor_redefineClasses
(JNIEnv *, jclass, jobjectArray);
#ifdef __cplusplus
}
#endif
#endif
|
ljnferreira/TP1ED1-2021
|
dataTypes.h
|
#ifndef _DATA_TYPES_H_
#define _DATA_TYPES_H_
typedef struct {
unsigned long id;
char nome[100];
char cpf[12];
char email[50];
char telefone[15];
} Cliente;
typedef struct {
unsigned long id;
unsigned long idCliente;
unsigned long idVendedor;
char dataCompra[11];
float valorTotal;
} NotaFiscal;
typedef struct{
unsigned long id;
unsigned long idNotaFiscal;
unsigned long idProduto;
float valorVenda;
unsigned int quantidade;
} ItemNotaFiscal;
typedef struct{
unsigned long id;
char nome[100];
unsigned int quantidadeEstoque;
float precoUnitario;
} Produto;
typedef struct{
unsigned long id;
char nome[100];
char cpf[12];
char email[50];
char telefone[15];
char password[20];
} Vendedor;
typedef struct{
unsigned long id;
char CNPJ[15];
char nome[100];
char email[50];
char telefone[15];
} Fornecedor;
typedef struct{
unsigned long id;
unsigned long idFornecedor;
char dataCompra[11];
float valorTotal;
} NotaCompra;
typedef struct{
unsigned long id;
unsigned long idProduto;
unsigned long idNotaCompra;
unsigned int quantidade;
float valorUnitario;
} ItemNotaCompra;
typedef struct{
unsigned long idProduto;
char data[11];
float valor;
}HistoricoPreco;
typedef struct{
unsigned long idProduto;
int quantidade;
float valorUnitario;
}ItemCarrinho;
#endif
|
ljnferreira/TP1ED1-2021
|
main.c
|
<reponame>ljnferreira/TP1ED1-2021
#include <stdio.h>
#include <string.h>
#include <locale.h>
#include <stdlib.h>
#include "dataTypes.h"
#include "files.h"
#include "userInteraction.h"
#include "utils.h"
int iniciar(){
setlocale(LC_ALL, "Portuguese_Brasil");
setlocale (LC_CTYPE, "pt_BR.UTF-8");
menuPrincipal();
return 0;
}
int main(){
return iniciar();
}
|
ljnferreira/TP1ED1-2021
|
memoryManagement.h
|
#ifndef _MEMORY_MANAGEMENT_
#define _MEMORY_MANAGEMENT_
#include "dataTypes.h"
int *alocaVetorInteiros(int tamanho);
int *realocaVetorInteiros(int *vetor, int *tamanho, int acrescimo);
/**
Aloca um vetor do tipo item carrinho de tamanho definido pelo usuario,
retornando um ponteiro para o mesmo.
*/
ItemCarrinho *alocaCarrinho(int tamanho);
/**
Realoca um vetor do tipo item carrinho recebendo o mesmo como parametro, alem de um ponteiro
do tipo inteiro para que o usuario da função saiba o atual tamanho do vetor.
Retorna o vetor com os mesmo valores do antigo acrescido de uma posiçao vazia ao final.
*/
ItemCarrinho *aumentaCarrinho(ItemCarrinho *carrinho, int *tamanho);
/**
Realoca um vetor do tipo item carrinho recebendo o mesmo como parametro, alem de um ponteiro
do tipo inteiro para que o usuario da função saiba o atual tamanho do vetor.
Retorna o vetor com os mesmo valores do antigo diminuido em uma posiçao ao final, da qual se perde os dados.
*/
ItemCarrinho *diminuiCarrinho(ItemCarrinho *carrinho, int *tamanho);
#endif
|
ljnferreira/TP1ED1-2021
|
userInteraction.h
|
#ifndef _INTERATION_H_
#define _INTERATION_H_
void bemVindo();
void menuPrincipal();
void limparTela();
void creditos();
void pause();
#endif
#ifndef WIN32
#define PAUSE 1
#endif
|
ljnferreira/TP1ED1-2021
|
files.h
|
#ifndef _FILES_H_
#define _FILES_H_
#include <stdio.h>
#include "dataTypes.h"
#define CLIENTE "data/Clientes.dat"
#define VENDEDOR "data/Vendedores.dat"
#define FORNECEDOR "data/Fornecedores.dat"
#define PRODUTO "data/Produtos.dat"
#define NOTA_FISCAL "data/NotasFiscais.dat"
#define ITEM_NOTA_FISCAL "data/ItensNotaFiscal.dat"
#define NOTA_COMPRA "data/NotasCompra.dat"
#define ITEM_NOTA_COMPRA "data/ItensNotaCompra.dat"
#define HISTORICO_PRECOS "data/HistoricoPrecos.dat"
FILE *abrirArquivo(char location[]);
int fecharArquivo(FILE *file);
int gravarRegistroFinalArquivo(void *data, FILE *file, unsigned long size);
int gravarRegistroEmArquivo(void *data, FILE *file, int posicao,unsigned long size);
void lerRegistroEmArquivo(void *data, FILE *file, int position, unsigned int size);
unsigned long getNewUniqueId(FILE *file, unsigned long sizeOfRegister);
int findClienteById(FILE *file, unsigned long id);
int findClienteByCPF(FILE *file, char *cpf);
int *findClientesByName(FILE *file, char *name, int *tamanho);
int findVendedorById(FILE *file, unsigned long id);
int findVendedorByCPF(FILE *file, char *cpf);
int *findVendedoresByName(FILE *file, char *name, int *tamanho);
int isEmailCadastradoVendedor(FILE *file, char *email);
int findFornecedorById(FILE *file, unsigned long id);
int findFornecedorByCNPJ(FILE *file, char *cnpj);
int findFornecedorByName(FILE *file, char *name);
int isNomeFornecedorCadastrado(FILE *file, char * nome);
int findProdutoById(FILE *file, unsigned long id);
int findNotaFiscalById(FILE *file, unsigned long id);
int findNotaCompraById(FILE *file, unsigned long id);
int findItemNotaCompraById(FILE *file, unsigned long id);
#endif
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.