summaryrefslogtreecommitdiff
path: root/fonts/utilities/fontools/bin/splitttc
blob: 1fa3e460e24f15c6cd76be74f93b69d4bd47e2f9 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
#! /usr/bin/env perl

=begin COPYRIGHT

----------------------------------------------------------------------------

    Copyright (C) 2020 Marc Penninga.

    This program is free software; you can redistribute it and/or
    modify it under the terms of the GNU General Public License
    as published by the Free Software Foundation, either version 2
    of the License, or (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program; if not, write to
        Free Software Foundation, Inc.,
        59 Temple Place,
        Suite 330,
        Boston, MA 02111-1307,
        USA

----------------------------------------------------------------------------

=end COPYRIGHT

=cut

use strict;
use warnings;

use Encode;
use File::Basename;
use Getopt::Long;
use Pod::Usage;

my $VERSION = "20200527";

parse_commandline();

use constant {
    SIZEOF_OFFSET_TABLE =>  12,
    SIZEOF_TABLE_RECORD =>  16,
};

my $filename_in = $ARGV[0];
my ($basename, undef, undef) = fileparse($filename_in, qw(.ttc .otc));

open my $fh, '<:raw', $filename_in
    or die "[ERROR] cannot open $filename_in: $!";
my $ttc = do { local $/; <$fh> };
close $fh
    or die "[ERROR] something went wrong when closing $filename_in: $!";

# unpack TTC header; we ignore the DSIG fields in version 2.0 headers
my ($ttc_tag, $major_version, $minor_version, $num_fonts)
    = unpack 'A4 nnN', $ttc;
my $ttc_header_version = sprintf "%d.%d", $major_version, $minor_version;
die "$ARGV[0] is not an OpenType Collection file" if $ttc_tag ne 'ttcf';
die "$ARGV[0]: unknown TTC Header Version $ttc_header_version"
    if $ttc_header_version !~ m/\A [12] [.] 0 \z/xms;

my $offsets_template = sprintf "\@%d N%d", SIZEOF_OFFSET_TABLE, $num_fonts;
my @offsets_of_offset_table = unpack $offsets_template, $ttc;

# collect the data for each font and write to separate file
for my $i_font (1..$num_fonts) {
    my $offset_of_offset_table = $offsets_of_offset_table[$i_font - 1];
    my $offset_table
        = substr $ttc, $offset_of_offset_table, SIZEOF_OFFSET_TABLE;

    # unpack relevant fields from Offset Table
    my ($sfnt_version, $num_tables) = unpack 'a4 n', $offset_table;
    my $file_ext = $sfnt_version eq 'OTTO'             ? 'otf'
                 : $sfnt_version eq "\x00\x01\x00\x00" ? 'ttf'
                 :                                       die
                 ;
    my $filename_out = sprintf "%s%d.%s", $basename, $i_font, $file_ext;

    # unpack Table Records and create list of tables
    my $table_records
        = substr $ttc,
                 $offset_of_offset_table + SIZEOF_OFFSET_TABLE,
                 $num_tables * SIZEOF_TABLE_RECORD,
                 ;
    my $table_records_template
        = sprintf "(a%d)%d", SIZEOF_TABLE_RECORD, $num_tables;
    my @table_records = unpack $table_records_template, $table_records;
    for my $table_record (@table_records) {
        my ($table_tag, $checksum, $offset, $length)
            = unpack 'a4 N3', $table_record;
        my $padding = "\x00" x ((4 - ($length % 4)) % 4);
        my $table = substr($ttc, $offset, $length) . $padding;
        $table_record = {
            table_tag   =>  $table_tag,
            checksum    =>  $checksum,
            offset      =>  $offset,
            length      =>  $length,
            table       =>  $table,
        };
    }

    my $file_pos = SIZEOF_OFFSET_TABLE + length $table_records;
    for my $table_record (@table_records) {
        $table_record->{offset} = $file_pos;
        $file_pos += length $table_record->{table};

        if ($table_record->{table_tag} eq 'name') {
            my $postscript_name = get_postscript_name($table_record->{table});
            if ($postscript_name) {
                $filename_out = $postscript_name . q(.) . $file_ext;
            }
        }
    }

    open my $filehandle_out, '>:raw', $filename_out
        or die "[ERROR] Cannot create $filename_out: $!";
    print {$filehandle_out} $offset_table;
    for my $table_record (@table_records) {
        print {$filehandle_out}
            pack 'a4 N3',
                 @{$table_record}{ qw(table_tag checksum offset length) }
            ;
    }
    for my $table_record (@table_records) {
        print {$filehandle_out} $table_record->{table};
    }
    close $filehandle_out
        or die "[ERROR] something went wrong when closing $filename_out: $!";
}


# --------------------------------------------------------------------------
#   Reads the command-line options.
# --------------------------------------------------------------------------
sub parse_commandline {
    Getopt::Long::GetOptions(
        'help|?'            =>  sub { pod2usage(-verbose => 1) },
        'version'           =>  sub { print "$VERSION\n"; exit },
        'output-prefix=s'   => \$ARGV{output_prefix},
    )
    or pod2usage(-verbose => 0);

    pod2usage(-verbose => 0) if @ARGV != 1;

    return;
}


# --------------------------------------------------------------------------
#   Parses the 'name' table and returns the font's PostScript name.
# --------------------------------------------------------------------------
sub get_postscript_name {
    my $name_table = shift;

    my ($version, $count, $string_offset) = unpack '@0n3', $name_table;
    if ($version > 1) {
        # Don't try to parse future versions
        return;
    }

    my @name_records = unpack "\@6(a12)$count", $name_table;
    for my $name_record (@name_records) {
        my ($platform_id, $encoding_id, $language_id,
            $name_id, $length, $offset) = unpack 'n6', $name_record;

        if ($name_id != 6) {
            next;
        }

        my $postscript_data
            = substr $name_table, $string_offset + $offset, $length;
        my $postscript_name;
        if ($platform_id == 3
                and $encoding_id == 1
                and $language_id == 0x409) {
            $postscript_name = Encode::decode('UTF-16BE', $postscript_data);
        }
        elsif ($platform_id == 1
                and $encoding_id == 0
                and $language_id == 0) {
            $postscript_name = Encode::decode('MacRoman', $postscript_data);
        }
        else {
            # According to the 'Recommendations' in the OpenType spec,
            # any PostScript names other than the above two may be ignored.
            next;
        }

        return $postscript_name;
    }

    return;
}


__END__


############################################################################

    To create the documentation:

    pod2man --center="Marc Penninga" --release="fontools" --section=1 \
        splitttc - | groff -Tps -man - | ps2pdf - splitttc.pdf

=pod

=head1 NAME

splitttc - split an OpenType Collection F<ttc> or F<otc> file

=head1 SYNOPSIS

=over 8

=item B<splitttc>
[B<-help>]
[B<-version>]
B<< <ttc-or-otc-file> >>

=back


=head1 DESCRIPTION

B<splitttc> splits an OpenType Collection file.

The OpenType specification allows for multiple fonts to be contained
in the same file. This might be advantageous if fonts share a lot of data,
as this then needs to be stored only once. Probably the best known
example of an OpenType Collection file is Microsoft's Cambria,
where the Regular weight shares a file with the Math font.

Unfortunately some tools (including Eddie Kohler's LCDF TypeTools)
cannot handle such OpenType Collections; they only work for individual fonts.
B<splitttc> takes an OpenType Collection file
and splits it into its constituent parts.


=head1 OPTIONS AND ARGUMENTS

=over 4

=item B<-help>

Print a short description of the syntax and exit.

=item B<-version>

Print version number and exit.

=item B<< <ttc-or-otc-file> >>

The F<ttc> or F<otc> file to be split.

=back

You may use either one or two dashes before options,
and option names may be shortened to a unique prefix.


=head1 OUTPUT

B<splitttc> tries to determine the 'PostScript name' of the resulting fonts
and uses this to name the output files.
If it cannot determine the PostScript name, it uses the basename of the input
font collection file plus a three-digit sequence number:
F<<< I<< <input> >> 001.otf >>>, F<<< I<< <input> >> 002.otf >>> etc.


=head1 AUTHOR

Marc Penninga <marcpenninga@gmail.com>


=head1 COPYRIGHT

Copyright (C) 2020 Marc Penninga.


=head1 LICENSE

This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published
by the Free Software Foundation, either version 2 of the License,
or (at your option) any later version.
A copy of the GNU General Public License is included with B<splitttc>;
see the file F<GPLv2.txt>.


=head1 DISCLAIMER

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU General Public License for more details.


=head1 VERSION

This document describes B<splitttc> version 20200527.


=head1 RECENT CHANGES

(See the source code for the rest of the story.)

=over 12

=item I<2020-05-11>

Use the 'PostScript name' to name the output fonts.

=item I<2019-06-25>

First release.

=back

=cut