Path: blob/21.2-virgl/src/intel/isl/gen_format_layout.py
4547 views
# encoding=utf-81# Copyright © 2016 Intel Corporation23# Permission is hereby granted, free of charge, to any person obtaining a copy4# of this software and associated documentation files (the "Software"), to deal5# in the Software without restriction, including without limitation the rights6# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell7# copies of the Software, and to permit persons to whom the Software is8# furnished to do so, subject to the following conditions:910# The above copyright notice and this permission notice shall be included in11# all copies or substantial portions of the Software.1213# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR14# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,15# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE16# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER17# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,18# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE19# SOFTWARE.2021"""Generates isl_format_layout.c."""2223from __future__ import absolute_import, division, print_function24import argparse25import csv26import re2728from mako import template2930# Load the template, ensure that __future__.division is imported, and set the31# bytes encoding to be utf-8. This last bit is important to getting simple32# consistent behavior for python 3 when we get there.33TEMPLATE = template.Template(future_imports=['division'],34output_encoding='utf-8',35text="""\36/* This file is autogenerated by gen_format_layout.py. DO NOT EDIT! */3738/*39* Copyright 2015 Intel Corporation40*41* Permission is hereby granted, free of charge, to any person obtaining a42* copy of this software and associated documentation files (the "Software"),43* to deal in the Software without restriction, including without limitation44* the rights to use, copy, modify, merge, publish, distribute, sublicense,45* and/or sell copies of the Software, and to permit persons to whom the46* Software is furnished to do so, subject to the following conditions:47*48* The above copyright notice and this permission notice (including the next49* paragraph) shall be included in all copies or substantial portions of the50* Software.51*52* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR53* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,54* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL55* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER56* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING57* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS58* IN THE SOFTWARE.59*/6061#include "isl/isl.h"6263const uint16_t isl_format_name_offsets[] = { <% offset = 0 %>64% for format in formats:65[ISL_FORMAT_${format.name}] = ${offset}, <% offset += 11 + len(format.name) + 1 %>66% endfor67};6869const char isl_format_names[] = {70% for format in formats:71"ISL_FORMAT_${format.name}\\0"72% endfor73};7475const struct isl_format_layout76isl_format_layouts[] = {77% for format in formats:78[ISL_FORMAT_${format.name}] = {79.format = ISL_FORMAT_${format.name},80.bpb = ${format.bpb},81.bw = ${format.bw},82.bh = ${format.bh},83.bd = ${format.bd},84.channels = {85% for mask in ['r', 'g', 'b', 'a', 'l', 'i', 'p']:86<% channel = getattr(format, mask, None) %>\\87% if channel.type is not None:88.${mask} = { ISL_${channel.type}, ${channel.start}, ${channel.size} },89% else:90.${mask} = {},91% endif92% endfor93},94.uniform_channel_type = ISL_${format.uniform_channel_type},95.colorspace = ISL_COLORSPACE_${format.colorspace},96.txc = ISL_TXC_${format.txc},97},9899% endfor100};101102bool103isl_format_is_valid(enum isl_format format)104{105if (format >= sizeof(isl_format_layouts) / sizeof(isl_format_layouts[0]))106return false;107108/* Only ISL_FORMAT_R32G32B32A32_FLOAT == 0 but that's a valid format.109* For all others, if this doesn't match then the entry in the table110* must not exist.111*/112return isl_format_layouts[format].format == format;113}114115enum isl_format116isl_format_srgb_to_linear(enum isl_format format)117{118switch (format) {119% for srgb, rgb in srgb_to_linear_map:120case ISL_FORMAT_${srgb}:121return ISL_FORMAT_${rgb};122%endfor123default:124return format;125}126}127""")128129130class Channel(object):131"""Class representing a Channel.132133Converts the csv encoded data into the format that the template (and thus134the consuming C code) expects.135136"""137# If the csv file grew very large this class could be put behind a factory138# to increase efficiency. Right now though it's fast enough that It didn't139# seem worthwhile to add all of the boilerplate140_types = {141'x': 'void',142'r': 'raw',143'un': 'unorm',144'sn': 'snorm',145'uf': 'ufloat',146'sf': 'sfloat',147'ux': 'ufixed',148'sx': 'sfixed',149'ui': 'uint',150'si': 'sint',151'us': 'uscaled',152'ss': 'sscaled',153}154_splitter = re.compile(r'\s*(?P<type>[a-z]+)(?P<size>[0-9]+)')155156def __init__(self, line):157# If the line is just whitespace then just set everything to None to158# save on the regex cost and let the template skip on None.159if line.isspace():160self.size = None161self.type = None162else:163grouped = self._splitter.match(line)164self.type = self._types[grouped.group('type')].upper()165self.size = int(grouped.group('size'))166167# Default the start bit to -1168self.start = -1169170171class Format(object):172"""Class taht contains all values needed by the template."""173def __init__(self, line):174# pylint: disable=invalid-name175self.name = line[0].strip()176177self.bpb = int(line[1])178self.bw = line[2].strip()179self.bh = line[3].strip()180self.bd = line[4].strip()181self.r = Channel(line[5])182self.g = Channel(line[6])183self.b = Channel(line[7])184self.a = Channel(line[8])185self.l = Channel(line[9])186self.i = Channel(line[10])187self.p = Channel(line[11])188189# Set the start bit value for each channel190self.order = line[12].strip()191bit = 0192for c in self.order:193chan = getattr(self, c)194chan.start = bit195bit = bit + chan.size196197# Set the uniform channel type, if the format has one.198#199# Iterate over all channels, not just those in self.order, because200# some formats have an empty 'order' field in the CSV (such as201# YCRCB_NORMAL).202self.uniform_channel_type = 'VOID'203for chan in self.channels:204if chan.type in (None, 'VOID'):205pass206elif self.uniform_channel_type == 'VOID':207self.uniform_channel_type = chan.type208elif self.uniform_channel_type == chan.type:209pass210else:211self.uniform_channel_type = 'VOID'212break213214# alpha doesn't have a colorspace of it's own.215self.colorspace = line[13].strip().upper()216if self.colorspace in ['']:217self.colorspace = 'NONE'218219# This sets it to the line value, or if it's an empty string 'NONE'220self.txc = line[14].strip().upper() or 'NONE'221222223@property224def channels(self):225yield self.r226yield self.g227yield self.b228yield self.a229yield self.l230yield self.i231yield self.p232233234def reader(csvfile):235"""Wrapper around csv.reader that skips comments and blanks."""236# csv.reader actually reads the file one line at a time (it was designed to237# open excel generated sheets), so hold the file until all of the lines are238# read.239with open(csvfile, 'r') as f:240for line in csv.reader(f):241if line and not line[0].startswith('#'):242yield line243244def get_srgb_to_linear_map(formats):245"""Compute a map from sRGB to linear formats.246247This function uses some probably somewhat fragile string munging to do248the conversion. However, we do assert that, if it's SRGB, the munging249succeeded so that gives some safety.250"""251names = {f.name for f in formats}252for fmt in formats:253if fmt.colorspace != 'SRGB':254continue255256replacements = [257('_SRGB', ''),258('SRGB', 'RGB'),259('U8SRGB', 'FLT16'),260]261262found = False263for rep in replacements:264rgb_name = fmt.name.replace(rep[0], rep[1])265if rgb_name in names:266found = True267yield fmt.name, rgb_name268break269270# We should have found a format name271assert found272273def main():274"""Main function."""275parser = argparse.ArgumentParser()276parser.add_argument('--csv', action='store', help='The CSV file to parse.')277parser.add_argument(278'--out',279action='store',280help='The location to put the generated C file.')281args = parser.parse_args()282283# This generator opens and writes the file itself, and it does so in bytes284# mode. This solves both python 2 vs 3 problems and solves the locale285# problem: Unicode can be rendered even if the shell calling this script286# doesn't.287with open(args.out, 'wb') as f:288formats = [Format(l) for l in reader(args.csv)]289try:290# This basically does lazy evaluation and initialization, which291# saves on memory and startup overhead.292f.write(TEMPLATE.render(293formats = formats,294srgb_to_linear_map = list(get_srgb_to_linear_map(formats)),295))296except Exception:297# In the even there's an error this imports some helpers from mako298# to print a useful stack trace and prints it, then exits with299# status 1, if python is run with debug; otherwise it just raises300# the exception301if __debug__:302import sys303from mako import exceptions304print(exceptions.text_error_template().render(),305file=sys.stderr)306sys.exit(1)307raise308309310if __name__ == '__main__':311main()312313314