root / pykota / trunk / pykota / pdlanalyzer.py @ 1573

Revision 1573, 23.0 kB (checked in by jalet, 20 years ago)

Additionnal speedup for GhostScript? generated PCL5 files

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
Line 
1# PyKota
2# -*- coding: ISO-8859-15 -*-
3#
4# PyKota - Print Quotas for CUPS and LPRng
5#
6# (c) 2003-2004 Jerome Alet <alet@librelogiciel.com>
7# This program is free software; you can redistribute it and/or modify
8# it under the terms of the GNU General Public License as published by
9# the Free Software Foundation; either version 2 of the License, or
10# (at your option) any later version.
11#
12# This program is distributed in the hope that it will be useful,
13# but WITHOUT ANY WARRANTY; without even the implied warranty of
14# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15# GNU General Public License for more details.
16#
17# You should have received a copy of the GNU General Public License
18# along with this program; if not, write to the Free Software
19# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
20#
21# $Id$
22#
23# $Log$
24# Revision 1.17  2004/06/26 23:20:01  jalet
25# Additionnal speedup for GhostScript generated PCL5 files
26#
27# Revision 1.16  2004/06/26 15:31:00  jalet
28# mmap reintroduced in PCL5 parser
29#
30# Revision 1.15  2004/06/26 14:14:31  jalet
31# Now uses Psyco if it is available
32#
33# Revision 1.14  2004/06/25 09:50:28  jalet
34# More debug info in PCLXL parser
35#
36# Revision 1.13  2004/06/25 08:10:08  jalet
37# Another fix for PCL5 parser
38#
39# Revision 1.12  2004/06/24 23:09:53  jalet
40# Fix for number of copies in PCL5 parser
41#
42# Revision 1.11  2004/06/23 22:07:50  jalet
43# Fixed PCL5 parser according to the sources of rastertohp
44#
45# Revision 1.10  2004/06/18 22:24:03  jalet
46# Removed old comments
47#
48# Revision 1.9  2004/06/18 22:21:27  jalet
49# Native PDF parser greatly improved.
50# GhostScript based PDF parser completely removed because native code
51# is now portable across Python versions.
52#
53# Revision 1.8  2004/06/18 20:49:46  jalet
54# "ERROR:" prefix added
55#
56# Revision 1.7  2004/06/18 17:48:04  jalet
57# Added native fast PDF parsing method
58#
59# Revision 1.6  2004/06/18 14:00:16  jalet
60# Added PDF support in smart PDL analyzer (through GhostScript for now)
61#
62# Revision 1.5  2004/06/18 10:09:05  jalet
63# Resets file pointer to start of file in all cases
64#
65# Revision 1.4  2004/06/18 06:16:14  jalet
66# Fixes PostScript detection code for incorrect drivers
67#
68# Revision 1.3  2004/05/21 20:40:08  jalet
69# All the code for pkpgcounter is now in pdlanalyzer.py
70#
71# Revision 1.2  2004/05/19 19:09:36  jalet
72# Speed improvement
73#
74# Revision 1.1  2004/05/18 09:59:54  jalet
75# pkpgcounter is now just a wrapper around the PDLAnalyzer class
76#
77#
78#
79
80import sys
81import os
82import re
83import struct
84import tempfile
85import mmap
86   
87KILOBYTE = 1024   
88MEGABYTE = 1024 * KILOBYTE   
89
90class PDLAnalyzerError(Exception):
91    """An exception for PDL Analyzer related stuff."""
92    def __init__(self, message = ""):
93        self.message = message
94        Exception.__init__(self, message)
95    def __repr__(self):
96        return self.message
97    __str__ = __repr__
98   
99class PostScriptAnalyzer :
100    def __init__(self, infile) :
101        """Initialize PostScript Analyzer."""
102        self.infile = infile
103       
104    def getJobSize(self) :   
105        """Count pages in a DSC compliant PostScript document."""
106        pagecount = 0
107        for line in self.infile.xreadlines() : 
108            if line.startswith("%%Page: ") :
109                pagecount += 1
110        return pagecount
111       
112class PDFAnalyzer :
113    def __init__(self, infile) :
114        """Initialize PDF Analyzer."""
115        self.infile = infile
116               
117    def getJobSize(self) :   
118        """Counts pages in a PDF document."""
119        regexp = re.compile(r"(/Type) ?(/Page)[/ \t\r\n]")
120        pagecount = 0
121        for line in self.infile.xreadlines() : 
122            pagecount += len(regexp.findall(line))
123        return pagecount   
124       
125class PCLAnalyzer :
126    def __init__(self, infile) :
127        """Initialize PCL Analyzer."""
128        self.infile = infile
129       
130    def getJobSize(self) :     
131        """Count pages in a PCL5 document."""
132        #
133        # Algorithm from pclcount
134        # (c) 2003, by Eduardo Gielamo Oliveira & Rodolfo Broco Manin
135        # published under the terms of the GNU General Public Licence v2.
136        #
137        # Backported from C to Python by Jerome Alet, then enhanced
138        # with more PCL tags detected. I think all the necessary PCL tags
139        # are recognized to correctly handle PCL5 files wrt their number
140        # of pages. The documentation used for this was :
141        #
142        # HP PCL/PJL Reference Set
143        # PCL5 Printer Language Technical Quick Reference Guide
144        # http://h20000.www2.hp.com/bc/docs/support/SupportManual/bpl13205/bpl13205.pdf
145        #
146        infileno = self.infile.fileno()
147        minfile = mmap.mmap(infileno, os.fstat(infileno).st_size, access=mmap.ACCESS_READ)
148        tagsends = { "&n" : "W", 
149                     "&b" : "W", 
150                     "*i" : "W", 
151                     "*l" : "W", 
152                     "*m" : "W", 
153                     "*v" : "W", 
154                     "*c" : "W", 
155                     "(f" : "W", 
156                     "(s" : "W", 
157                     ")s" : "W", 
158                     "&p" : "X", 
159                     "&l" : "XH",
160                     "&a" : "G",
161                     # "*b" : "VW", # treated specially because it occurs very often
162                   } 
163        pagecount = resets = ejects = backsides = 0
164        tag = None
165        copies = {}
166        pos = 0
167        try :
168            while 1 :
169                char = minfile[pos] ; pos += 1
170                if char == "\014" :   
171                    pagecount += 1
172                elif char == "\033" :   
173                    #
174                    #     <ESC>*b###W -> Start of a raster data row/block
175                    #     <ESC>*b###V -> Start of a raster data plane
176                    #     <ESC>*c###W -> Start of a user defined pattern
177                    #     <ESC>*i###W -> Start of a viewing illuminant block
178                    #     <ESC>*l###W -> Start of a color lookup table
179                    #     <ESC>*m###W -> Start of a download dither matrix block
180                    #     <ESC>*v###W -> Start of a configure image data block
181                    #     <ESC>(s###W -> Start of a characters description block
182                    #     <ESC>)s###W -> Start of a fonts description block
183                    #     <ESC>(f###W -> Start of a symbol set block
184                    #     <ESC>&b###W -> Start of configuration data block
185                    #     <ESC>&l###X -> Number of copies for current page
186                    #     <ESC>&n###W -> Starts an alphanumeric string ID block
187                    #     <ESC>&p###X -> Start of a non printable characters block
188                    #     <ESC>&a2G -> Back side when duplex mode as generated by rastertohp
189                    #     <ESC>&l0H -> Eject if NumPlanes > 1, as generated by rastertohp
190                    #
191                    tagstart = minfile[pos] ; pos += 1
192                    if tagstart in "E9=YZ" : # one byte PCL tag
193                        if tagstart == "E" :
194                            resets += 1
195                        continue             # skip to next tag
196                    tag = tagstart + minfile[pos] ; pos += 1
197                    if tag == "*b" : 
198                        tagend = "VW"
199                    else :   
200                        try :
201                            tagend = tagsends[tag]
202                        except KeyError :   
203                            continue # Unsupported PCL tag
204                    # Now read the numeric argument
205                    size = 0
206                    while 1 :
207                        char = minfile[pos] ; pos += 1
208                        if not char.isdigit() :
209                            break
210                        size = (size * 10) + int(char)   
211                    if char in tagend :   
212                        if (tag == "&l") and (char == "X") : # copies for current page
213                            copies[pagecount] = size
214                        elif (tag == "&l") and (char == "H") and (size == 0) :   
215                            ejects += 1         # Eject
216                        elif (tag == "&a") and (size == 2) :
217                            backsides += 1      # Back side in duplex mode
218                        else :   
219                            # we just ignore the block.
220                            if tag == "&n" : 
221                                # we have to take care of the operation id byte
222                                # which is before the string itself
223                                size += 1
224                            pos += size   
225        except IndexError : # EOF ?
226            minfile.close() # reached EOF
227                           
228        # if pagecount is still 0, we will use the number
229        # of resets instead of the number of form feed characters.
230        # but the number of resets is always at least 2 with a valid
231        # pcl file : one at the very start and one at the very end
232        # of the job's data. So we substract 2 from the number of
233        # resets. And since on our test data we needed to substract
234        # 1 more, we finally substract 3, and will test several
235        # PCL files with this. If resets < 2, then the file is
236        # probably not a valid PCL file, so we use 0
237        if not pagecount :
238            pagecount = (pagecount or ((resets - 3) * (resets > 2)))
239        else :   
240            # here we add counters for other ways new pages may have
241            # been printed and ejected by the printer
242            pagecount += ejects + backsides
243       
244        # now handle number of copies for each page (may differ).
245        # in duplex mode, number of copies may be sent only once.
246        for pnum in range(pagecount) :
247            # if no number of copies defined, take the preceding one else 1.
248            nb = copies.get(pnum, copies.get(pnum-1, 1))
249            pagecount += (nb - 1)
250        return pagecount
251       
252class PCLXLAnalyzer :
253    def __init__(self, infile) :
254        """Initialize PCLXL Analyzer."""
255        raise PDLAnalyzerError, "PCLXL (aka PCL6) is not supported yet."
256        self.infile = infile
257        self.islittleendian = None
258        found = 0
259        while not found :
260            line = self.infile.readline()
261            if not line :
262                break
263            if line[1:12] == " HP-PCL XL;" :
264                found = 1
265                if line[0] == ")" :
266                    self.littleendian()
267                elif line[0] == "(" :   
268                    self.bigendian()
269        if not found :
270            raise PDLAnalyzerError, "This file doesn't seem to be PCLXL (aka PCL6)"
271        else :   
272            self.tags = [ self.skipped ] * 256   
273            self.tags[0x28] = self.bigendian    # big endian
274            self.tags[0x29] = self.littleendian # big endian
275            self.tags[0x43] = self.beginPage    # BeginPage
276            self.tags[0x44] = self.endPage      # EndPage
277           
278            self.tags[0xc0] = lambda: self.debug("%08x : ubyte" % self.infile.tell()) or 1 # ubyte
279            self.tags[0xc1] = lambda: self.debug("%08x : uint16" % self.infile.tell()) or 2 # uint16
280            self.tags[0xc2] = lambda: self.debug("%08x : uint32" % self.infile.tell()) or 4 # uint32
281            self.tags[0xc3] = lambda: self.debug("%08x : sint16" % self.infile.tell()) or 2 # sint16
282            self.tags[0xc4] = lambda: self.debug("%08x : sint32" % self.infile.tell()) or 4 # sint32
283            self.tags[0xc5] = lambda: self.debug("%08x : real32" % self.infile.tell()) or 4 # real32
284           
285            self.tags[0xc8] = self.array_8  # ubyte_array
286            self.tags[0xc9] = self.array_16 # uint16_array
287            self.tags[0xca] = self.array_32 # uint32_array
288            self.tags[0xcb] = self.array_16 # sint16_array
289            self.tags[0xcc] = self.array_32 # sint32_array
290            self.tags[0xcd] = self.array_32 # real32_array
291           
292            self.tags[0xd0] = lambda: self.debug("%08x : ubyte_xy" % self.infile.tell()) or 2 # ubyte_xy
293            self.tags[0xd1] = lambda: self.debug("%08x : uint16_xy" % self.infile.tell()) or 4 # uint16_xy
294            self.tags[0xd2] = lambda: self.debug("%08x : uint32_xy" % self.infile.tell()) or 8 # uint32_xy
295            self.tags[0xd3] = lambda: self.debug("%08x : sint16_xy" % self.infile.tell()) or 4 # sint16_xy
296            self.tags[0xd4] = lambda: self.debug("%08x : sint32_xy" % self.infile.tell()) or 8 # sint32_xy
297            self.tags[0xd5] = lambda: self.debug("%08x : real32_xy" % self.infile.tell()) or 8 # real32_xy
298           
299            self.tags[0xd0] = lambda: self.debug("%08x : ubyte_box" % self.infile.tell()) or 4  # ubyte_box
300            self.tags[0xd1] = lambda: self.debug("%08x : uint16_box" % self.infile.tell()) or 8  # uint16_box
301            self.tags[0xd2] = lambda: self.debug("%08x : uint32_box" % self.infile.tell()) or 16 # uint32_box
302            self.tags[0xd3] = lambda: self.debug("%08x : sint16_box" % self.infile.tell()) or 8  # sint16_box
303            self.tags[0xd4] = lambda: self.debug("%08x : sint32_box" % self.infile.tell()) or 16 # sint32_box
304            self.tags[0xd5] = lambda: self.debug("%08x : real32_box" % self.infile.tell()) or 16 # real32_box
305           
306            self.tags[0xf8] = lambda: self.debug("%08x : attr_ubyte" % self.infile.tell()) or 1 # attr_ubyte
307            self.tags[0xf9] = lambda: self.debug("%08x : attr_uint16" % self.infile.tell()) or 2 # attr_uint16
308           
309            self.tags[0xfa] = self.embeddedData      # dataLength
310            self.tags[0xfb] = self.embeddedDataSmall # dataLengthByte
311           
312    def debug(self, msg) :
313        """Outputs a debug message on stderr."""
314        sys.stderr.write("%s\n" % msg)
315        sys.stderr.flush()
316       
317    def skipped(self) :   
318        """Skips a byte."""
319        self.debug("%08x : skip" % self.infile.tell())
320       
321    def beginPage(self) :
322        """Indicates the beginning of a new page."""
323        self.pagecount += 1
324        self.debug("%08x : beginPage (%i)" % (self.infile.tell(), self.pagecount))
325       
326    def endPage(self) :
327        """Indicates the end of a page."""
328        self.debug("%08x : endPage (%i)" % (self.infile.tell(), self.pagecount))
329       
330    def handleArray(self, itemsize) :       
331        """Handles arrays."""
332        pos = self.infile.tell()
333        datatype = self.infile.read(1)
334        self.debug("%08x : Array of datatype 0x%02x" % (pos, ord(datatype)))
335        length = self.tags[ord(datatype)]()
336        if length is None :
337            self.debug("Bogus array length at %s" % pos)
338        else :   
339            sarraysize = self.infile.read(length)
340            if self.islittleendian :
341                fmt = "<"
342            else :   
343                fmt = ">"
344            if length == 1 :   
345                fmt += "B"
346            elif length == 2 :   
347                fmt += "H"
348            elif length == 4 :   
349                fmt += "I"
350            else :   
351                raise PDLAnalyzerError, "Error on array size at %s" % self.infile.tell()
352            arraysize = struct.unpack(fmt, sarraysize)[0]
353            self.debug("itemsize %s * size %s = %s" % (itemsize, arraysize, itemsize*arraysize))
354            return arraysize * itemsize
355       
356    def array_8(self) :   
357        """Handles byte arrays."""
358        self.debug("%08x : array_8" % self.infile.tell())
359        return self.handleArray(1)
360       
361    def array_16(self) :   
362        """Handles byte arrays."""
363        self.debug("%08x : array_16" % self.infile.tell())
364        return self.handleArray(2)
365       
366    def array_32(self) :   
367        """Handles byte arrays."""
368        self.debug("%08x : array_32" % self.infile.tell())
369        return self.handleArray(4)
370       
371    def embeddedDataSmall(self) :
372        """Handle small amounts of data."""
373        self.debug("%08x : small_datablock" % self.infile.tell())
374        pos = self.infile.tell()
375        val = ord(self.infile.read(1))
376        self.debug("%08x : Small datablock length : 0x%02x" % (self.infile.tell()-1, val))
377        return val
378       
379    def embeddedData(self) :
380        """Handle normal amounts of data."""
381        self.debug("%08x : large_datablock" % self.infile.tell())
382        if self.islittleendian :
383            fmt = "<I"
384        else :   
385            fmt = ">I"
386        pos = self.infile.tell()
387        val = struct.unpack(fmt, self.infile.read(4))[0]
388        self.debug("%08x : Large datablock length : 0x%04x" % (self.infile.tell()-4, val))
389        return val
390       
391    def littleendian(self) :       
392        """Toggles to little endianness."""
393        self.debug("%08x : littleendian" % self.infile.tell())
394        self.islittleendian = 1 # little endian
395       
396    def bigendian(self) :   
397        """Toggles to big endianness."""
398        self.debug("%08x : bigendian" % self.infile.tell())
399        self.islittleendian = 0 # big endian
400   
401    def getJobSize(self) :
402        """Counts pages in a PCLXL (PCL6) document."""
403        self.pagecount = 0
404        while 1 :
405            char = self.infile.read(1)
406            if not char :
407                break
408            index = ord(char)   
409            length = self.tags[index]()
410            if length :   
411                self.infile.read(length)   
412        return self.pagecount
413       
414class PDLAnalyzer :   
415    """Generic PDL Analyzer class."""
416    def __init__(self, filename) :
417        """Initializes the PDL analyzer.
418       
419           filename is the name of the file or '-' for stdin.
420           filename can also be a file-like object which
421           supports read() and seek().
422        """
423        self.filename = filename
424        try :
425            import psyco 
426        except ImportError :   
427            pass # Psyco is not installed
428        else :   
429            # Psyco is installed, tell it to compile
430            # the CPU intensive methods : PCL and PCLXL
431            # parsing will greatly benefit from this,
432            # for PostScript and PDF the difference is
433            # barely noticeable since they are already
434            # almost optimal, and much more speedy anyway.
435            psyco.bind(PostScriptAnalyzer.getJobSize)
436            psyco.bind(PDFAnalyzer.getJobSize)
437            psyco.bind(PCLAnalyzer.getJobSize)
438            psyco.bind(PCLXLAnalyzer.getJobSize)
439       
440    def getJobSize(self) :   
441        """Returns the job's size."""
442        self.openFile()
443        try :
444            pdlhandler = self.detectPDLHandler()
445        except PDLAnalyzerError, msg :   
446            self.closeFile()
447            raise PDLAnalyzerError, "ERROR : Unknown file format for %s (%s)" % (self.filename, msg)
448        else :
449            try :
450                size = pdlhandler(self.infile).getJobSize()
451            finally :   
452                self.closeFile()
453            return size
454       
455    def openFile(self) :   
456        """Opens the job's data stream for reading."""
457        self.mustclose = 0  # by default we don't want to close the file when finished
458        if hasattr(self.filename, "read") and hasattr(self.filename, "seek") :
459            # filename is in fact a file-like object
460            infile = self.filename
461        elif self.filename == "-" :
462            # we must read from stdin
463            infile = sys.stdin
464        else :   
465            # normal file
466            self.infile = open(self.filename, "rb")
467            self.mustclose = 1
468            return
469           
470        # Use a temporary file, always seekable contrary to standard input.
471        self.infile = tempfile.TemporaryFile(mode="w+b")
472        while 1 :
473            data = infile.read(MEGABYTE) 
474            if not data :
475                break
476            self.infile.write(data)
477        self.infile.flush()   
478        self.infile.seek(0)
479           
480    def closeFile(self) :       
481        """Closes the job's data stream if we can close it."""
482        if self.mustclose :
483            self.infile.close()   
484        else :   
485            # if we don't have to close the file, then
486            # ensure the file pointer is reset to the
487            # start of the file in case the process wants
488            # to read the file again.
489            try :
490                self.infile.seek(0)
491            except :   
492                pass    # probably stdin, which is not seekable
493       
494    def isPostScript(self, data) :   
495        """Returns 1 if data is PostScript, else 0."""
496        if data.startswith("%!") or \
497           data.startswith("\004%!") or \
498           data.startswith("\033%-12345X%!PS") or \
499           ((data[:128].find("\033%-12345X") != -1) and \
500             ((data.find("LANGUAGE=POSTSCRIPT") != -1) or \
501              (data.find("LANGUAGE = POSTSCRIPT") != -1) or \
502              (data.find("LANGUAGE = Postscript") != -1))) or \
503              (data.find("%!PS-Adobe") != -1) :
504            return 1
505        else :   
506            return 0
507       
508    def isPDF(self, data) :   
509        """Returns 1 if data is PDF, else 0."""
510        if data.startswith("%PDF-") or \
511           data.startswith("\033%-12345X%PDF-") or \
512           ((data[:128].find("\033%-12345X") != -1) and (data.upper().find("LANGUAGE=PDF") != -1)) or \
513           (data.find("%PDF-") != -1) :
514            return 1
515        else :   
516            return 0
517       
518    def isPCL(self, data) :   
519        """Returns 1 if data is PCL, else 0."""
520        if data.startswith("\033E\033") or \
521           ((data[:128].find("\033%-12345X") != -1) and \
522             ((data.find("LANGUAGE=PCL") != -1) or \
523              (data.find("LANGUAGE = PCL") != -1) or \
524              (data.find("LANGUAGE = Pcl") != -1))) :
525            return 1
526        else :   
527            return 0
528       
529    def isPCLXL(self, data) :   
530        """Returns 1 if data is PCLXL aka PCL6, else 0."""
531        if ((data[:128].find("\033%-12345X") != -1) and \
532             (data.find(" HP-PCL XL;") != -1) and \
533             ((data.find("LANGUAGE=PCLXL") != -1) or \
534              (data.find("LANGUAGE = PCLXL") != -1))) :
535            return 1
536        else :   
537            return 0
538           
539    def detectPDLHandler(self) :   
540        """Tries to autodetect the document format.
541       
542           Returns the correct PDL handler class or None if format is unknown
543        """   
544        # Try to detect file type by reading first block of datas   
545        self.infile.seek(0)
546        firstblock = self.infile.read(KILOBYTE)
547        self.infile.seek(0)
548        if self.isPostScript(firstblock) :
549            return PostScriptAnalyzer
550        elif self.isPCLXL(firstblock) :   
551            return PCLXLAnalyzer
552        elif self.isPCL(firstblock) :   
553            return PCLAnalyzer
554        elif self.isPDF(firstblock) :   
555            return PDFAnalyzer
556        else :   
557            raise PDLAnalyzerError, "Analysis of first data block failed."
558           
559def main() :   
560    """Entry point for PDL Analyzer."""
561    if (len(sys.argv) < 2) or ((not sys.stdin.isatty()) and ("-" not in sys.argv[1:])) :
562        sys.argv.append("-")
563       
564    totalsize = 0   
565    for arg in sys.argv[1:] :
566        try :
567            parser = PDLAnalyzer(arg)
568            totalsize += parser.getJobSize()
569        except PDLAnalyzerError, msg :   
570            sys.stderr.write("ERROR: %s\n" % msg)
571            sys.stderr.flush()
572    print "%s" % totalsize
573   
574if __name__ == "__main__" :   
575    main()       
Note: See TracBrowser for help on using the browser.