File: kateenc.c

package info (click to toggle)
libkate 0.4.1-9
  • links: PTS, VCS
  • area: main
  • in suites: buster
  • size: 5,628 kB
  • sloc: ansic: 10,964; sh: 10,378; yacc: 2,358; python: 767; lex: 363; makefile: 239
file content (1132 lines) | stat: -rw-r--r-- 29,991 bytes parent folder | download | duplicates (4)
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
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
/* Copyright (C) 2008 Vincent Penquerc'h.
   This file is part of the Kate codec library.
   Written by Vincent Penquerc'h.

   Use, distribution and reproduction of this library is governed
   by a BSD style source license included with this source in the
   file 'COPYING'. Please read these terms before distributing. */


#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#ifdef HAVE_UNISTD_H
#include <unistd.h>
#endif
#if defined WIN32 || defined _WIN32 || defined MSDOS || defined __CYGWIN__ || defined __EMX__ || defined OS2
#include <io.h>
#include <fcntl.h>
#endif
#if defined WIN32 || defined _WIN32
#include <process.h>
#endif
#ifdef HAVE_TIME_H
#include <time.h>
#endif
#include <stdio.h>
#ifdef HAVE_STDLIB_H
#include <stdlib.h>
#endif
#ifdef HAVE_STRING_H
#include <string.h>
#endif
#include <errno.h>
#include <ogg/ogg.h>
#include "kate/oggkate.h"
#include "katedesc.h"

extern int katedesc_parse(void);
extern void katedesc_restart(FILE*);
extern FILE *katedesc_in;
extern FILE *katedesc_out;
extern int nerrors;

static ogg_stream_state os;
kate_state k;
kate_info ki;
kate_comment kc;
static ogg_int64_t packetno;
char base_path[4096]="";

static char str[4096];
static int headers_written=0;
#ifdef DEBUG
static int raw=0;
#endif
static kate_float repeat_threshold=(kate_float)0;
static kate_float keepalive_threshold=(kate_float)0;
static kate_int64_t last_stream_time=0;
static const unsigned char utf8bom[3]={0xef,0xbb,0xbf};
static const unsigned char utf16lebom[2]={0xff,0xfe};
static const unsigned char utf16bebom[2]={0xfe,0xff};
static const unsigned char utf32lebom[4]={0xff,0xfe,0x00,0x00};
static const unsigned char utf32bebom[4]={0x00,0x00,0xfe,0xff};

static const char *language=NULL;
static const char *category=NULL;

static int flush_page(FILE *f)
{
  ogg_page og;
  while (1) {
    int ret=ogg_stream_flush(&os,&og);
    if (ret==0) break;
    ret=fwrite(og.header,1,og.header_len,f);
    if (ret!=og.header_len) {
      fprintf(stderr,"Write failed (%s)\n",strerror(errno));
      return -1;
    }
    ret=fwrite(og.body,1,og.body_len,f);
    if (ret!=og.body_len) {
      fprintf(stderr,"Write failed (%s)\n",strerror(errno));
      return -1;
    }
    fflush(f);
  }
  return 0;
}

static int poll_page(FILE *f)
{
  /* discontinuous codec, so we want to flush pages every time,
     as Ogg keeps granules per page, not per packet */
  return flush_page(f);
}

int write_headers(FILE *f)
{
  ogg_packet op;

  /* command line overrides */
  if (language) {
    int ret=kate_info_set_language(&ki,language);
    if (ret<0) {
      fprintf(stderr,"Failed to set stream language to '%s': %d\n",language,ret);
      return ret;
    }
  }
  if (category) {
    int ret=kate_info_set_category(&ki,category);
    if (ret<0) {
      fprintf(stderr,"Failed to set stream category to '%s': %d\n",category,ret);
      return ret;
    }
  }

  /* warn if either language or category is missing */
  if (!ki.category || !*ki.category) {
    fprintf(stderr,"warning: no category defined\n");
  }
  if (!ki.language || !*ki.language) {
    fprintf(stderr,"warning: no language defined\n");
  }

  while (1) {
    int ret=kate_ogg_encode_headers(&k,&kc,&op);
    if (ret<0) {
      fprintf(stderr,"error encoding headers: %d\n",ret);
      return ret;
    }
    if (ret>0) break; /* we're done */

#ifdef DEBUG
    if (raw) {
      int ret=send_packet(f,&op,-1);
      if (ret<0) {
        fprintf(stderr,"error sending packet: %d\n",ret);
        return ret;
      }
    }
    else
#endif
    {
      ogg_stream_packetin(&os,&op);
      ogg_packet_clear(&op);
    }

    /* place all headers on the same page, it keeps oggmerge happy */
    /* poll_page(f); */
  }

  return flush_page(f);
}

int send_packet(FILE *f,ogg_packet *op,kate_int64_t t)
{
  if (t>last_stream_time)
    last_stream_time=t;

#ifdef DEBUG
  if (raw) {
    int ret;
    if (op->packetno>0) {
      ogg_int64_t bytes=op->bytes;
      ret=fwrite(&bytes,1,8,f);
      if (ret!=8) {
        fprintf(stderr,"Write failed (%s)\n",strerror(errno));
        return -1;
      }
    }
    ret=fwrite(op->packet,1,op->bytes,f);
    if (ret!=op->bytes) {
      fprintf(stderr,"Write failed (%s)\n",strerror(errno));
      return -1;
    }
    fflush(f);
    return 0;
  }
  else
#endif
  {
    ogg_stream_packetin(&os,op);
    ogg_packet_clear(op);
    return poll_page(f);
  }
}

void cancel_packet(ogg_packet *op)
{
  ogg_packet_clear(op);
}

static int flush_headers(FILE *f)
{
  int ret=0;
  if (!headers_written) {
    ret=write_headers(f);
    headers_written=1;
  }
  return ret;
}

static const char *eat_arg(int argc,char **argv,int *n)
{
  if (*n==argc-1) {
    fprintf(stderr,"%s needs an argument\n",argv[*n]);
    exit(-1);
  }
  return argv[++*n];
}

static kate_int64_t hmsms2ms(int h,int m,int s,int ms)
{
  return h*(kate_int64_t)3600000+m*60000+s*1000+ms;
}

static char *fgets2(char *s,size_t len,FILE *f,int ignore_hash)
{
  char *ret=fgets(s,len,f);
  if (ret) {
    char *ptr=strpbrk(s,"\r"); /* fix windows text files */
    if (ptr) strcpy(ptr,"\n");
    if (!ignore_hash) {
      ptr=strchr(s,'#');
      if (ptr) strcpy(ptr,"\n");
    }
  }
  else *s=0;
  return ret;
}

static int convert_kate(FILE *fin,FILE *fout)
{
  katedesc_in=fin;
  katedesc_out=fout;
  katedesc_restart(katedesc_in);
  nerrors=0;
  katedesc_parse();
  cleanup_lexer();
  if (nerrors>0) return -1;
  return 0;
}

static int is_line_empty(const char *s)
{
  while (*s) {
    if (!strchr(" \t\r\n",*s)) return 0;
    ++s;
  }
  return 1;
}

void update_stream_time(kate_state *k,FILE *fout,kate_int64_t endt)
{
  ogg_packet op;
  kate_int64_t t;
  int ret;
  kate_int64_t step;
  kate_int64_t raw_repeat_threshold=kate_duration_granule(k->ki,repeat_threshold);
  kate_int64_t raw_keepalive_threshold=kate_duration_granule(k->ki,keepalive_threshold);

  /* work out the best step to walk the time segment */
  step=0;
  if (step==0 || (raw_repeat_threshold>0 && raw_repeat_threshold<step))
    step=raw_repeat_threshold;
  if (step==0 || (raw_keepalive_threshold>0 && raw_keepalive_threshold<step))
    step=raw_keepalive_threshold;

  if (step<=0) return;

  for (t=last_stream_time;t<endt;t+=step) {
    /* try repeats first, no keepalives will be needed if we have one */
    if (raw_repeat_threshold>0) {
      while (1) {
        ret=kate_ogg_encode_repeat_raw_times(k,t,raw_repeat_threshold,&op);
        if (ret<0) {
          fprintf(stderr,"Failed encoding repeat at %"PRId64" (%d), continuing anyway\n",t,ret);
          return;
        }
        if (ret==0) break;
        ret=send_packet(fout,&op,t);
        if (ret<0) {
          fprintf(stderr,"Failed sending repeat packet, continuing anyway\n");
          return;
        }
      }
    }
    /* keepalives next */
    if (raw_keepalive_threshold>0 && t-last_stream_time>=raw_keepalive_threshold) {
      ret=kate_ogg_encode_keepalive_raw_times(k,t,&op);
      if (ret<0) {
        fprintf(stderr,"Failed encoding keepalive at %"PRId64" (%d), continuing anyway\n",t,ret);
        return;
      }
      ret=send_packet(fout,&op,t);
      if (ret<0) {
        fprintf(stderr,"Failed sending keepalive packet, continuing anyway\n");
        return;
      }
    }
  }
}

static void remove_last_newline(char *text)
{
  size_t len;

  len=strlen(text);
  if (len>0 && text[len-1]=='\n') text[--len]=0;
}

static int emit_srt_event(FILE *fout,kate_int64_t t0,kate_int64_t t1,const char *text,int allow_srt_markup,int x1,int y1,int x2,int y2)
{
  ogg_packet op;
  size_t len;
  int ret;

  update_stream_time(&k,fout,t0);

  len=strlen(text);
  ret=kate_text_validate(kate_utf8,text,len+1);
  if (ret<0) {
    if (ret==KATE_E_TEXT) {
      fprintf(stderr,"Text is not valid UTF-8: %s\n",text);
    }
    else {
      fprintf(stderr,"Failed to validate text: %d\n",ret);
    }
    return ret;
  }
  if (allow_srt_markup) kate_encode_set_markup_type(&k,kate_markup_simple);
  if (x1!=-INT_MAX && y1!=-INT_MAX && x2!=-INT_MAX && y2!=-INT_MAX) {
    kate_region kr;
    kate_region_init(&kr);
    kr.metric=kate_pixel;
    kr.x=x1;
    kr.y=y1;
    kr.w=x2-x1+1;
    kr.h=y2-y1+1;
    ret=kate_encode_set_region(&k,&kr);
    if (ret<0) {
      fprintf(stderr,"Error setting region: %d\n",ret);
      return ret;
    }
  }
  ret=kate_ogg_encode_text_raw_times(&k,t0,t1,text,len,&op);
  if (ret<0) {
    fprintf(stderr,"Error encoding text: %d\n",ret);
    return ret;
  }
  else {
    ret=send_packet(fout,&op,t0);
    if (ret<0) return ret;
  }
  return ret;
}

static int convert_srt(FILE *fin,FILE *fout,int allow_srt_markup)
{
  enum { need_id, need_timing, need_text };
  int need = need_id;
  int last_seen_id=0;
  int ret;
  int id;
  static char text[4096];
  int h0,m0,s0,ms0,h1,m1,s1,ms1;
  int x1,y1,x2,y2;
  kate_int64_t t0=0,t1=0;
  int line=0;

  ret=flush_headers(fout);
  if (ret<0) return ret;

  fgets2(str,sizeof(str),fin,1);

  if (!memcmp(str,utf16lebom,sizeof(utf16lebom)) || !memcmp(str,utf16bebom,sizeof(utf16bebom))) {
    fprintf(stderr,"This file seems to be encoded in UTF-16, Kate only supports UTF-8\n");
    fprintf(stderr,"You will need to convert it to UTF-8 first (eg, use iconv)\n");
    return -1;
  }

  if (!memcmp(str,utf32lebom,sizeof(utf32lebom)) || !memcmp(str,utf32bebom,sizeof(utf32bebom))) {
    fprintf(stderr,"This file seems to be encoded in UTF-32, Kate only supports UTF-8\n");
    fprintf(stderr,"You will need to convert it to UTF-8 first (eg, use iconv)\n");
    return -1;
  }

  /* kill any utf-8 BOM present */
  if (!memcmp(str,utf8bom,sizeof(utf8bom))) {
    /* printf("UTF-8 BOM found at start, skipped\n"); */
    memmove(str,str+3,strlen(str+3)+1);
  }

  while (!feof(fin) || *str) {
    ++line;
    switch (need) {
      case need_id:
        /* allow more than one blank line between events */
        if (is_line_empty(str)) {
          break;
        }
        ret=sscanf(str,"%d\n",&id);
        if (ret!=1) {
          fprintf(stderr,"Syntax error at line %d: %s\n",line,str);
          return -1;
        }
        if (id!=last_seen_id+1) {
          fprintf(stderr,"Warning at line %d: non consecutive ids: %s\n",line,str);
        }
        last_seen_id=id;
        need=need_timing;
        strcpy(text,"");
        break;
      case need_timing:
        ret=sscanf(str,"%d:%d:%d%*[,.]%d --> %d:%d:%d%*[,.]%d %*[xX]1: %d %*[xX]2: %d %*[yY]1: %d %*[yY]2: %d\n",&h0,&m0,&s0,&ms0,&h1,&m1,&s1,&ms1,&x1,&x2,&y1,&y2);
        if (ret!=12) {
          x1=y1=x2=y2=-INT_MAX;
          ret=sscanf(str,"%d:%d:%d%*[,.]%d --> %d:%d:%d%*[,.]%d\n",&h0,&m0,&s0,&ms0,&h1,&m1,&s1,&ms1);
          if (ret!=8) {
            fprintf(stderr,"Syntax error at line %d: %s\n",line,str);
            return -1;
          }
        }

        if ((h0|m0|s0|ms0)<0 || (h1|m1|s1|ms1)<0) {
          fprintf(stderr,"Bad time specification at line %d: %s\n",line,str);
          return -1;
        }
        t0=hmsms2ms(h0,m0,s0,ms0);
        t1=hmsms2ms(h1,m1,s1,ms1);
        if (t1<t0) {
          fprintf(stderr,"Error at line %d: end time must not be less than start time\n",line);
          return -1;
        }
        if (x2<x1 || y2<y1) {
          fprintf(stderr,"Invalid region coordinates at line %d\n",line);
          return -1;
        }
        need=need_text;
        break;
      case need_text:
        if (is_line_empty(str)) {
          remove_last_newline(text);
          ret=emit_srt_event(fout,t0,t1,text,allow_srt_markup,x1,y1,x2,y2);
          if (ret<0) return ret;
          need=need_id;
        }
        else {
          size_t len=strlen(text);
          strncpy(text+len,str,sizeof(text)-len);
          text[sizeof(text)-1]=0;
        }
        break;
    }
    fgets2(str,sizeof(str),fin,1);
  }

  /* add any text we've accumulated if there's no empty line at the end */
  if (need==need_text && text[0]) {
    fprintf(stderr, "Warning: last event is not followed by an empty line - input might be truncated\n");
    remove_last_newline(text);
    ret=emit_srt_event(fout,t0,t1,text,allow_srt_markup,x1,y1,x2,y2);
    if (ret<0) return ret;
  }

  return 0;
}

static void add_kate_karaoke_tag(kate_motion *km,kate_int64_t dt,const char *str,size_t len,int line)
{
  kate_curve *kc;
  kate_int64_t ptr=-500; /* minus half a second, in milliseconds */
  int ret;
  kate_curve **new_curves;
  kate_float *new_durations;

  if (dt<0) {
    fprintf(stderr, "Error: line %d: lyrics times must not be decreasing\n",line);
    return;
  }

  /* work out how many glyphs we have */
  while (len>0) {
    ret=kate_text_get_character(kate_utf8,&str,&len);
    if (ret<0) {
      fprintf(stderr, "Error: line %d: failed to get UTF-8 glyph from string\n",line);
      return;
    }
    ptr+=1000; /* a second, in milliseconds */
  }
  /* ptr now points to the middle of the glyph we're at */

  kc=(kate_curve*)kate_malloc(sizeof(kate_curve));
  if (kc) {
    kate_curve_init(kc);
    kc->type=kate_curve_static;
    kc->npts=1;
    kc->pts=(kate_float*)kate_malloc(2*sizeof(kate_float));
    if (kc->pts) {
      kc->pts[0]=ptr/(kate_float)1000;
      kc->pts[1]=(kate_float)0;

      new_curves=(kate_curve**)kate_realloc(km->curves,(km->ncurves+1)*sizeof(kate_curve*));
      if (new_curves) km->curves=new_curves;
      new_durations=(kate_float*)kate_realloc(km->durations,(km->ncurves+1)*sizeof(kate_float));
      if (new_durations) km->durations=new_durations;

      if (new_curves && new_durations) {
        km->ncurves++;
        km->curves[km->ncurves-1]=kc;
        km->durations[km->ncurves-1]=dt/(kate_float)1000;
      }
      else {
        fprintf(stderr,"Error: failed to allocate memory to store curve/duration");
        kate_free(kc->pts);
        kate_free(kc);
      }
    }
    else {
      fprintf(stderr,"Error: failed to allocate memory for curve points");
      kate_free(kc);
    }
  }
  else {
    fprintf(stderr,"Error: failed to allocate memory for a kate_curve");
  }
}

static int fraction_to_milliseconds(int fraction,int digits)
{
  while (digits<3) {
    fraction*=10;
    ++digits;
  }
  while (digits>3) {
    fraction/=10;
    --digits;
  }
  return fraction;
}

static kate_motion *process_enhanced_lrc_tags(char *str,kate_int64_t start_time,kate_int64_t end_time,int line)
{
  char *start,*end;
  int ret;
  int m,s,fs;
  kate_motion *km=NULL;
  kate_int64_t current_time=start_time;
  int f0,f1;

  if (!str) return NULL;

  start=str;
  while (1) {
    start=strchr(start,'<');
    if (!start) break;
    end=strchr(start+1,'>');
    if (!end) break;

    /* we found a <> pair, parse it */
    f0=f1=-1;
    ret=sscanf(start,"<%d:%d.%n%d%n>",&m,&s,&f0,&fs,&f1);

    /* remove the <> tag from input to get raw text */
    memmove(start,end+1,strlen(end+1)+1);

    if (ret<3 || (f0|f1)<0 || f1<=f0 || (m|s|fs)<0) {
      fprintf(stderr,"Error: failed to process enhanced LRC tag (%*.*s) - ignored\n",(int)(end-start+1),(int)(end-start+1),start);
    }
    else {
      kate_int64_t tag_time=hmsms2ms(0,m,s,fraction_to_milliseconds(fs,f1-f0));

      /* if this is the first tag in this line, create a kate motion */
      if (!km) {
        km=(kate_motion*)kate_malloc(sizeof(kate_motion));
        if (!km) {
          fprintf(stderr,"Error: failed to allocate memory - enhanced LRC tag will be ignored\n");
        }
        else {
          kate_motion_init(km);
          km->semantics=kate_motion_semantics_glyph_pointer_1;
        }
      }
      /* add to the kate motion */
      if (km) {
        add_kate_karaoke_tag(km,tag_time-current_time,str,start-str,line);
        current_time=tag_time;
      }
    }
  }

  /* if we've found karaoke info, extend the motion to the end time */
  if (km) {
    add_kate_karaoke_tag(km,end_time-current_time,str,strlen(str),line);
  }

  return km;
}

static void add_kate_karaoke_style(kate_info *ki,unsigned char r,unsigned char g,unsigned char b,unsigned char a)
{
    kate_style *ks;
    int ret;

    if (!ki) return;

    ks=(kate_style*)kate_malloc(sizeof(kate_style));
    if (ks) {
      kate_style_init(ks);
      ks->text_color.r = r;
      ks->text_color.g = g;
      ks->text_color.b = b;
      ks->text_color.a = a;
      ret=kate_info_add_style(ki,ks);
      if (ret<0) {
        fprintf(stderr,"WARNING - failed to add Kate karaoke style\n");
      }
    }
    else {
      fprintf(stderr,"WARNING - failed to allocate memory for Kate karaoke style\n");
    }
}

static int convert_lrc(FILE *fin,FILE *fout)
{
  int ret;
  static char text[4096];
  int m,s,fs;
  kate_int64_t t;
  kate_int64_t start_time=-1;
  int offset;
  int line=0;
  fpos_t start;
  int has_karaoke;
  kate_motion *km;
  int f0,f1;
  size_t len;

  fgets2(str,sizeof(str),fin,1);
  ++line;

  if (!memcmp(str,utf16lebom,sizeof(utf16lebom)) || !memcmp(str,utf16bebom,sizeof(utf16bebom))) {
    fprintf(stderr,"This file seems to be encoded in UTF-16, Kate only supports UTF-8\n");
    fprintf(stderr,"You will need to convert it to UTF-8 first (eg, use iconv)\n");
    return -1;
  }

  if (!memcmp(str,utf32lebom,sizeof(utf32lebom)) || !memcmp(str,utf32bebom,sizeof(utf32bebom))) {
    fprintf(stderr,"This file seems to be encoded in UTF-32, Kate only supports UTF-8\n");
    fprintf(stderr,"You will need to convert it to UTF-8 first (eg, use iconv)\n");
    return -1;
  }

  /* kill any utf-8 BOM present */
  if (!memcmp(str,utf8bom,sizeof(utf8bom))) {
    /* printf("UTF-8 BOM found at start, skipped\n"); */
    memmove(str,str+3,strlen(str+3)+1);
  }

  /* skip headers */
  while (!feof(fin)) {
    ret=sscanf(str,"[%d:%d.%d]",&m,&s,&fs);
    if (ret==3) break;
    fgets2(str,sizeof(str),fin,1);
    ++line;
  }

  /* there might be 'enhanced lrc' timing tags - if so, we'll include
     a timing motion for the appropriate events, as well as two styles
     in the headers, but we need to know beforehand if we'll need to
     add those styles, so they can go into headers  */
  if (fgetpos(fin,&start)<0) {
    fprintf(stderr,"Failed to get current file position\n");
    return -1;
  }
  has_karaoke=0;
  strcpy(text,str); /* we'll need to restore str after peeking */
  while (!feof(fin)) {
    ret=sscanf(str,"[%d:%d.%d]%n",&m,&s,&fs,&offset);
    if (ret==3) {
      const char *start=strchr(str+offset,'<');
      if (start) {
        const char *end=strchr(start,'>');
        if (end) {
          /* heuristics say we have enhanced lrc karaoke tags */
          has_karaoke=1;
          break;
        }
      }
    }
    fgets2(str,sizeof(str),fin,1);
  }
  if (fsetpos(fin,&start)<0) {
    fprintf(stderr,"Failed to reset file position\n");
    return -1;
  }
  strcpy(str,text);
  if (has_karaoke) {
    add_kate_karaoke_style(&ki, 255, 255, 255, 255);
    add_kate_karaoke_style(&ki, 255, 128, 128, 255);
  }

  ret=flush_headers(fout);
  if (ret<0) return ret;

  while (!feof(fin) || *str) {
    if (!is_line_empty(str)) {
      f0=f1=-1;
      ret=sscanf(str,"[%d:%d.%n%d%n]%n",&m,&s,&f0,&fs,&f1,&offset);
      if (ret<3 || (f0|f1)<0 || f1<=f0 || (m|s|fs)<0) {
        fprintf(stderr,"Syntax error at line %d: %s\n",line,str);
        return -1;
      }
      t=hmsms2ms(0,m,s,fraction_to_milliseconds(fs,f1-f0));
      if (start_time>=0 && !is_line_empty(text)) {
        ogg_packet op;

        update_stream_time(&k,fout,start_time);

        if (text[strlen(text)-1]=='\n') text[strlen(text)-1]=0;
        km=process_enhanced_lrc_tags(text,start_time,t,line);
        if (km) {
          ret=kate_encode_set_style_index(&k, 0);
          if (ret < 0) {
            fprintf(stderr,"Failed encoding karaoke style - continuing anyway\n");
          }
          ret=kate_encode_set_secondary_style_index(&k, 1);
          if (ret < 0) {
            fprintf(stderr,"Failed encoding karaoke style - continuing anyway\n");
          }
          ret=kate_encode_add_motion(&k,km,1);
          if (ret<0) {
            fprintf(stderr,"Failed to add karaoke motion (%d)\n",ret);
            return ret;
          }
        }
        len=strlen(text);
        ret=kate_text_validate(kate_utf8,text,len+1);
        if (ret<0) {
          if (ret==KATE_E_TEXT) {
            fprintf(stderr,"Text is not valid UTF-8: %s\n",text);
          }
          else {
            fprintf(stderr,"Failed to validate text: %d\n",ret);
          }
          return ret;
        }
        ret=kate_ogg_encode_text_raw_times(&k,start_time,t,text,len,&op);
        if (ret<0) {
          fprintf(stderr,"Failed to add lyrics (%d)\n",ret);
          return ret;
        }
        ret=send_packet(fout,&op,start_time);
        if (ret<0) return ret;
      }
      start_time=t;
      strcpy(text,str+offset);
    }
    fgets2(str,sizeof(str),fin,1);
    ++line;
  }
  return 0;
}

static void print_version(void)
{
  printf("Kate reference encoder - %s\n",kate_get_version_string());
}

static void print_help(const char *argv0)
{
  printf("usage: %s [options] [filename]\n",argv0);
  printf("   -V                  version\n");
  printf("   -h                  help\n");
  printf("   -o <filename>       set output filename\n");
  printf("   -t <type>           set input file type\n");
  printf("       types can be: kate, srt, lrc\n");
  printf("   -l <language>       set stream language\n");
  printf("   -c <category>       set stream category\n");
  printf("   -s <hex number>     set serial number of output stream\n");
  printf("   -R <threshold>      Use repeat packets with given threshold (seconds)\n");
  printf("   -K <threshold>      Use keepalive packets with given threshold (seconds)\n");
  printf("   -C <tag>=<value>    Add comment to the Kate stream\n");
  printf("   -M                  Allow simple markup in SRT files\n");
#ifdef DEBUG
  printf("   -r                  write raw Kate stream (experimental)\n");
#endif
}

#ifdef DEBUG
static void print_rle_stats(void)
{
  int n,total=0;
  extern int kate_rle_stats_overall[8];
  static const char *kate_rle_type_names[8]={
    "empty",
    "basic",
    "delta",
    "stop",
    "start/end",
    "delta/stop",
    "basic/zero",
    "",
  };
  for (n=0;n<8;++n) total+=kate_rle_stats_overall[n];
  if (total) {
    for (n=0;n<8;++n) {
      printf("%s: %d (%.2f%%)\n",kate_rle_type_names[n],kate_rle_stats_overall[n],100.0f*kate_rle_stats_overall[n]/total);
    }
  }
}
#endif

static void set_encoder_comment(kate_comment *kc)
{
  int ret;
  const char *base="kateenc - ";
  const char *version=kate_get_version_string();
  size_t len=strlen(base)+strlen(version)+1;
  char *value=(char*)kate_malloc(len);
  if (!value) {
    fprintf(stderr,"Failed to allocate %lu bytes\n",(unsigned long)len);
    exit(-1);
  }
  sprintf(value,"%s%s",base,version);
  ret=kate_comment_add_tag(kc,"ENCODER",value);
  kate_free(value);
  if (ret<0) {
    fprintf(stderr,"kate_comment_add_tag failed: %d\n",ret);
    exit(-1);
  }
}

int main(int argc,char **argv)
{
  int n,ret,failed=0;
  const char *input_filename=NULL;
  const char *output_filename=NULL;
  const char *input_file_type=NULL;
  uint32_t serial;
  const char *comment;
  const char *arg;
  char *endptr;
  FILE *fin,*fout;
  int allow_srt_markup=0;

  srand(time(NULL)^getpid());
  serial=rand();

  packetno=0;

  ret=kate_comment_init(&kc);
  if (ret<0) {
    fprintf(stderr,"kate_comment_init failed: %d\n",ret);
    exit(-1);
  }
  set_encoder_comment(&kc);
  if (ret<0) {
    fprintf(stderr,"Failed to set encoder tag: %d\n",ret);
    exit(-1);
  }
  ret=kate_info_init(&ki);
  if (ret<0) {
    fprintf(stderr,"kate_comment_init failed: %d\n",ret);
    exit(-1);
  }

  for (n=1;n<argc;++n) {
    if (argv[n][0]=='-') {
      switch (argv[n][1]) {
        case '-':
          if (!strcmp(argv[n],"--version")) {
            print_version();
            exit(0);
          }
          else if (!strcmp(argv[n],"--help")) {
            print_help(argv[0]);
            exit(0);
          }
          else {
            fprintf(stderr,"Invalid option: %s\n",argv[n]);
            exit(-1);
          }
          break;
        case 'V':
          print_version();
          exit(0);
        case 'h':
          print_help(argv[0]);
          exit(0);
        case 'o':
          if (!output_filename) {
            output_filename=eat_arg(argc,argv,&n);
          }
          else {
            fprintf(stderr,"Only one output filename may be given\n");
            exit(-1);
          }
          break;
        case 't':
          if (!input_file_type) {
            input_file_type=eat_arg(argc,argv,&n);
          }
          else {
            fprintf(stderr,"Only one input file type may be given\n");
            exit(-1);
          }
          break;
        case 'l':
          if (!language) {
            language=eat_arg(argc,argv,&n);
          }
          else {
            fprintf(stderr,"Only one language may be given\n");
            exit(-1);
          }
          break;
        case 'c':
          if (!category) {
            category=eat_arg(argc,argv,&n);
          }
          else {
            fprintf(stderr,"Only one category may be given\n");
            exit(-1);
          }
          break;
        case 's':
          serial=strtoul(eat_arg(argc,argv,&n),NULL,16);
          break;
        case 'C':
          comment=eat_arg(argc,argv,&n);
          /* check there's a = sign though */
          if (!strchr(comment,'=')) {
            fprintf(stderr,"comments must be of the form tag=value\n");
            exit(-1);
          }
          ret=kate_comment_add(&kc,comment);
          if (ret<0) {
            fprintf(stderr,"error adding comment \"%s\": %d\n",comment,ret);
            exit(-1);
          }
          break;
        case 'R':
          arg=eat_arg(argc,argv,&n);
          endptr=NULL;
          repeat_threshold=(kate_float)strtod(arg,&endptr);
          if (endptr==arg || *endptr) {
            fprintf(stderr,"error in repeat threshold: %s: should be a floating point value\n",arg);
            exit(-1);
          }
          break;
        case 'K':
          arg=eat_arg(argc,argv,&n);
          endptr=NULL;
          keepalive_threshold=(kate_float)strtod(arg,&endptr);
          if (endptr==arg || *endptr) {
            fprintf(stderr,"error in keepalive threshold: %s: should be a floating point value\n",arg);
            exit(-1);
          }
          break;
        case 'M':
          allow_srt_markup=1;
          break;
#ifdef DEBUG
        case 'r':
          raw=1;
          break;
#endif
        default:
          fprintf(stderr,"Invalid option: %s\n",argv[n]);
          exit(-1);
      }
    }
    else {
      if (!input_filename) {
        input_filename=argv[n];
      }
      else {
        fprintf(stderr,"Only one input filename may be given\n");
        exit(-1);
      }
    }
  }

  if (!input_file_type) {
    fprintf(stderr,"No input file type given\n");
    exit(-1);
  }

  if (!input_filename || !strcmp(input_filename,"-")) {
    fin=stdin;
  }
  else {
    const char *ptr,*end;
    fin=fopen(input_filename,"r");
    if (!fin) {
      fprintf(stderr,"%s: %s\n",input_filename,strerror(errno));
      exit(-1);
    }
    ptr=input_filename;
    end=NULL;
    while (*ptr) {
      if (*ptr=='/' || *ptr=='\\')
        end=ptr;
      ++ptr;
    }
    if (end) {
      /* we found a slash */
      if ((size_t)(end-input_filename+1)>=sizeof(base_path)) {
        fprintf(stderr,"%s too long\n",input_filename);
        exit(-1);
      }
      strncpy(base_path,input_filename,end-input_filename+1);
      base_path[end-input_filename+1]=0; /* just after the last slash */
    }
    else {
      /* we did not found a slash */
      strcpy(base_path,"");
    }
  }

  if (!output_filename || !strcmp(output_filename,"-")) {
#if defined WIN32 || defined _WIN32
    _setmode(_fileno(stdout),_O_BINARY);
#else
#if defined MSDOS || defined __CYGWIN__ || defined __EMX__ || defined OS2 || defined __BORLANDC__
    setmode(fileno(stdout),_O_BINARY);
#endif
#endif
    fout=stdout;
  }
  else {
    fout=fopen(output_filename,"wb");
    if (!fout) {
      fprintf(stderr,"%s: %s\n",output_filename,strerror(errno));
      exit(-1);
    }
  }

  ret=kate_encode_init(&k,&ki);
  if (ret<0) {
    fprintf(stderr,"kate_encode_init failed: %d\n",ret);
    exit(-1);
  }

#ifdef DEBUG
  if (!raw)
#endif
    ogg_stream_init(&os,serial);

  ret=0;
  if (!strcmp(input_file_type,"kate")) {
    ret=convert_kate(fin,fout);
  }
  else if (!strcmp(input_file_type,"srt")) {
    ret=convert_srt(fin,fout,allow_srt_markup);
  }
  else if (!strcmp(input_file_type,"lrc")) {
    ret=convert_lrc(fin,fout);
  }
  else {
    fprintf(stderr,"Invalid format type: %s\n",input_file_type);
    ret=-1;
  }
  if (ret<0) failed=ret;

  if (ret==0) {
    ogg_packet op;
    ret=kate_ogg_encode_finish(&k,-1,&op);
    if (ret<0) {
      fprintf(stderr,"error encoding end packet: %d\n",ret);
      failed=ret;
    }
    else {
      ret=send_packet(fout,&op,-1);
      if (ret<0) {
        fprintf(stderr,"error sending end packet: %d\n",ret);
        failed=ret;
      }
      else {
#ifdef DEBUG
        if (!raw)
#endif
        {
          ret=flush_page(fout);
          if (ret<0) {
            fprintf(stderr,"error flushing page: %d\n",ret);
            failed=ret;
          }
        }
      }
    }
  }

#ifdef DEBUG
  if (!raw)
#endif
    ogg_stream_clear(&os);

  ret=kate_clear(&k);
  if (ret<0) {
    fprintf(stderr,"kate_clear failed: %d\n",ret);
    /* continue anyway */
  }

  ret=kate_info_clear(&ki);
  if (ret<0) {
    fprintf(stderr,"kate_info_clear failed: %d\n",ret);
    /* continue anyway */
  }
  ret=kate_comment_clear(&kc);
  if (ret<0) {
    fprintf(stderr,"kate_comment_clear failed: %d\n",ret);
    /* continue anyway */
  }

  if (fout!=stdout) {
    fclose(fout);
    if (ret<0) {
      int unlink_ret=unlink(output_filename);
      if (unlink_ret<0) {
        fprintf(stderr,"unlink failed (%d) - corrupt file %s will not be deleted\n",ret,output_filename);
      }
    }
  }
  if (fin!=stdin) fclose(fin);

#ifdef DEBUG
  print_rle_stats();
#endif

  return failed?failed:ret;
}