1 /*
2  * ASF compatible encoder and decoder.
3  * Copyright (c) 2000, 2001 Fabrice Bellard.
4  *
5  * This library is free software; you can redistribute it and/or
6  * modify it under the terms of the GNU Lesser General Public
7  * License as published by the Free Software Foundation; either
8  * version 2 of the License, or (at your option) any later version.
9  *
10  * This library is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13  * Lesser General Public License for more details.
14  *
15  * You should have received a copy of the GNU Lesser General Public
16  * License along with this library; if not, write to the Free Software
17  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
18  */
19 
20 #if defined(USE_ICONV)
21 #include <iconv.h>
22 #endif /* USE_ICONV */
23 
24 #include "avformat.h"
25 #include "avi.h"
26 
27 #undef NDEBUG
28 #include <assert.h>
29 #define MPA_FRAME_SIZE 1152
30 #define PACKET_SIZE 3200
31 #define PACKET_HEADER_SIZE 12
32 #define FRAME_HEADER_SIZE 17
33 
34 typedef struct {
35     int num;
36     int seq;
37     /* use for reading */
38     AVPacket pkt;
39     int frag_offset;
40     int timestamp;
41     int64_t duration;
42 
43     int ds_span;		/* descrambling  */
44     int ds_packet_size;
45     int ds_chunk_size;
46     int ds_data_size;
47     int ds_silence_data;
48 
49     int packet_pos;
50 
51 } ASFStream;
52 
53 typedef struct {
54     uint32_t v1;
55     uint16_t v2;
56     uint16_t v3;
57     uint8_t v4[8];
58 } GUID;
59 
60 typedef struct {
61     GUID guid;			// generated by client computer
62     uint64_t file_size;		// in bytes
63                                 // invalid if broadcasting
64     uint64_t create_time;	// time of creation, in 100-nanosecond units since 1.1.1601
65                                 // invalid if broadcasting
66     uint64_t packets_count;	// how many packets are there in the file
67                                 // invalid if broadcasting
68     uint64_t play_time;		// play time, in 100-nanosecond units
69                                 // invalid if broadcasting
70     uint64_t send_time;		// time to send file, in 100-nanosecond units
71                                 // invalid if broadcasting (could be ignored)
72     uint32_t preroll;		// timestamp of the first packet, in milliseconds
73     				// if nonzero - substract from time
74     uint32_t ignore;            // preroll is 64bit - but let's just ignore it
75     uint32_t flags;		// 0x01 - broadcast
76     				// 0x02 - seekable
77                                 // rest is reserved should be 0
78     uint32_t min_pktsize;	// size of a data packet
79                                 // invalid if broadcasting
80     uint32_t max_pktsize;	// shall be the same as for min_pktsize
81                                 // invalid if broadcasting
82     uint32_t max_bitrate;	// bandwith of stream in bps
83     				// should be the sum of bitrates of the
84                                 // individual media streams
85 } ASFMainHeader;
86 
87 
88 typedef struct {
89     int seqno;
90     int packet_size;
91     int is_streamed;
92     int asfid2avid[128];        /* conversion table from asf ID 2 AVStream ID */
93     ASFStream streams[128];	/* it's max number and it's not that big */
94     /* non streamed additonnal info */
95     int64_t nb_packets;
96     int64_t duration; /* in 100ns units */
97     /* packet filling */
98     int packet_size_left;
99     int packet_timestamp_start;
100     int packet_timestamp_end;
101     int packet_nb_frames;
102     uint8_t packet_buf[PACKET_SIZE];
103     ByteIOContext pb;
104     /* only for reading */
105     uint64_t data_offset; /* begining of the first data packet */
106 
107     ASFMainHeader hdr;
108 
109     int packet_flags;
110     int packet_property;
111     int packet_timestamp;
112     int packet_segsizetype;
113     int packet_segments;
114     int packet_seq;
115     int packet_replic_size;
116     int packet_key_frame;
117     int packet_padsize;
118     int packet_frag_offset;
119     int packet_frag_size;
120     int packet_frag_timestamp;
121     int packet_multi_size;
122     int packet_obj_size;
123     int packet_time_delta;
124     int packet_time_start;
125     int packet_pos;
126 
127     int stream_index;
128     ASFStream* asf_st; /* currently decoded stream */
129 } ASFContext;
130 
131 static const GUID asf_header = {
132     0x75B22630, 0x668E, 0x11CF, { 0xA6, 0xD9, 0x00, 0xAA, 0x00, 0x62, 0xCE, 0x6C },
133 };
134 
135 static const GUID file_header = {
136     0x8CABDCA1, 0xA947, 0x11CF, { 0x8E, 0xE4, 0x00, 0xC0, 0x0C, 0x20, 0x53, 0x65 },
137 };
138 
139 static const GUID stream_header = {
140     0xB7DC0791, 0xA9B7, 0x11CF, { 0x8E, 0xE6, 0x00, 0xC0, 0x0C, 0x20, 0x53, 0x65 },
141 };
142 
143 static const GUID audio_stream = {
144     0xF8699E40, 0x5B4D, 0x11CF, { 0xA8, 0xFD, 0x00, 0x80, 0x5F, 0x5C, 0x44, 0x2B },
145 };
146 
147 static const GUID audio_conceal_none = {
148     // 0x49f1a440, 0x4ece, 0x11d0, { 0xa3, 0xac, 0x00, 0xa0, 0xc9, 0x03, 0x48, 0xf6 },
149     // New value lifted from avifile
150     0x20fb5700, 0x5b55, 0x11cf, { 0xa8, 0xfd, 0x00, 0x80, 0x5f, 0x5c, 0x44, 0x2b },
151 };
152 
153 static const GUID video_stream = {
154     0xBC19EFC0, 0x5B4D, 0x11CF, { 0xA8, 0xFD, 0x00, 0x80, 0x5F, 0x5C, 0x44, 0x2B },
155 };
156 
157 static const GUID video_conceal_none = {
158     0x20FB5700, 0x5B55, 0x11CF, { 0xA8, 0xFD, 0x00, 0x80, 0x5F, 0x5C, 0x44, 0x2B },
159 };
160 
161 
162 static const GUID comment_header = {
163     0x75b22633, 0x668e, 0x11cf, { 0xa6, 0xd9, 0x00, 0xaa, 0x00, 0x62, 0xce, 0x6c },
164 };
165 
166 static const GUID codec_comment_header = {
167     0x86D15240, 0x311D, 0x11D0, { 0xA3, 0xA4, 0x00, 0xA0, 0xC9, 0x03, 0x48, 0xF6 },
168 };
169 static const GUID codec_comment1_header = {
170     0x86d15241, 0x311d, 0x11d0, { 0xa3, 0xa4, 0x00, 0xa0, 0xc9, 0x03, 0x48, 0xf6 },
171 };
172 
173 static const GUID data_header = {
174     0x75b22636, 0x668e, 0x11cf, { 0xa6, 0xd9, 0x00, 0xaa, 0x00, 0x62, 0xce, 0x6c },
175 };
176 
177 static const GUID index_guid = {
178     0x33000890, 0xe5b1, 0x11cf, { 0x89, 0xf4, 0x00, 0xa0, 0xc9, 0x03, 0x49, 0xcb },
179 };
180 
181 static const GUID head1_guid = {
182     0x5fbf03b5, 0xa92e, 0x11cf, { 0x8e, 0xe3, 0x00, 0xc0, 0x0c, 0x20, 0x53, 0x65 },
183 };
184 
185 static const GUID head2_guid = {
186     0xabd3d211, 0xa9ba, 0x11cf, { 0x8e, 0xe6, 0x00, 0xc0, 0x0c, 0x20, 0x53, 0x65 },
187 };
188 
189 static const GUID extended_content_header = {
190         0xD2D0A440, 0xE307, 0x11D2, { 0x97, 0xF0, 0x00, 0xA0, 0xC9, 0x5E, 0xA8, 0x50 },
191 };
192 
193 /* I am not a number !!! This GUID is the one found on the PC used to
194    generate the stream */
195 static const GUID my_guid = {
196     0, 0, 0, { 0, 0, 0, 0, 0, 0, 0, 0 },
197 };
198 
199 const CodecTag codec_wav_tags[] = {
200     { CODEC_ID_MP2, 0x50 },
201     { CODEC_ID_MP3, 0x55 },
202     { CODEC_ID_AC3, 0x2000 },
203     { CODEC_ID_PCM_S16LE, 0x01 },
204     { CODEC_ID_PCM_U8, 0x01 }, /* must come after s16le in this list */
205     { CODEC_ID_PCM_ALAW, 0x06 },
206     { CODEC_ID_PCM_MULAW, 0x07 },
207     { CODEC_ID_ADPCM_MS, 0x02 },
208     { CODEC_ID_ADPCM_IMA_WAV, 0x11 },
209     { CODEC_ID_ADPCM_IMA_DK4, 0x61 },  /* rogue format number */
210     { CODEC_ID_ADPCM_IMA_DK3, 0x62 },  /* rogue format number */
211     { CODEC_ID_WMAV1, 0x160 },
212     { CODEC_ID_WMAV2, 0x161 },
213     { 0, 0 },
214 };
215 
codec_get_id(const CodecTag * tags,unsigned int tag)216 enum CodecID codec_get_id(const CodecTag *tags, unsigned int tag)
217 {
218     while (tags->id != 0) {
219         if(   toupper((tag >> 0)&0xFF) == toupper((tags->tag >> 0)&0xFF)
220            && toupper((tag >> 8)&0xFF) == toupper((tags->tag >> 8)&0xFF)
221            && toupper((tag >>16)&0xFF) == toupper((tags->tag >>16)&0xFF)
222            && toupper((tag >>24)&0xFF) == toupper((tags->tag >>24)&0xFF))
223             return tags->id;
224         tags++;
225     }
226     return CODEC_ID_NONE;
227 }
228 
wav_codec_get_id(unsigned int tag,int bps)229 int wav_codec_get_id(unsigned int tag, int bps)
230 {
231     int id;
232     id = codec_get_id(codec_wav_tags, tag);
233     if (id <= 0)
234         return id;
235     /* handle specific u8 codec */
236     if (id == CODEC_ID_PCM_S16LE && bps == 8)
237         id = CODEC_ID_PCM_U8;
238     return id;
239 }
240 
get_wav_header(ByteIOContext * pb,AVCodecContext * codec,int size)241 void get_wav_header(ByteIOContext *pb, AVCodecContext *codec, int size)
242 {
243     int id;
244 
245     id = get_le16(pb);
246     codec->codec_type = CODEC_TYPE_AUDIO;
247     codec->codec_tag = id;
248     codec->channels = get_le16(pb);
249     codec->sample_rate = get_le32(pb);
250     codec->bit_rate = get_le32(pb) * 8;
251     codec->block_align = get_le16(pb);
252     if (size == 14) {  /* We're dealing with plain vanilla WAVEFORMAT */
253         codec->bits_per_sample = 8;
254     }else
255         codec->bits_per_sample = get_le16(pb);
256     codec->codec_id = wav_codec_get_id(id, codec->bits_per_sample);
257 
258     if (size > 16) {  /* We're obviously dealing with WAVEFORMATEX */
259         codec->extradata_size = get_le16(pb);
260         if (codec->extradata_size > 0) {
261             if (codec->extradata_size > size - 18)
262                 codec->extradata_size = size - 18;
263             codec->extradata = av_mallocz(codec->extradata_size);
264             get_buffer(pb, codec->extradata, codec->extradata_size);
265         } else
266             codec->extradata_size = 0;
267 
268         /* It is possible for the chunk to contain garbage at the end */
269         if (size - codec->extradata_size - 18 > 0)
270             url_fskip(pb, size - codec->extradata_size - 18);
271     }
272 }
273 
274 #ifdef CONFIG_ENCODERS
put_guid(ByteIOContext * s,const GUID * g)275 static void put_guid(ByteIOContext *s, const GUID *g)
276 {
277     int i;
278 
279     put_le32(s, g->v1);
280     put_le16(s, g->v2);
281     put_le16(s, g->v3);
282     for(i=0;i<8;i++)
283         put_byte(s, g->v4[i]);
284 }
285 
put_str16(ByteIOContext * s,const char * tag)286 static void put_str16(ByteIOContext *s, const char *tag)
287 {
288     int c;
289 
290     put_le16(s,strlen(tag) + 1);
291     for(;;) {
292         c = (uint8_t)*tag++;
293         put_le16(s, c);
294         if (c == '\0')
295             break;
296     }
297 }
298 
put_str16_nolen(ByteIOContext * s,const char * tag)299 static void put_str16_nolen(ByteIOContext *s, const char *tag)
300 {
301     int c;
302 
303     for(;;) {
304         c = (uint8_t)*tag++;
305         put_le16(s, c);
306         if (c == '\0')
307             break;
308     }
309 }
310 
put_header(ByteIOContext * pb,const GUID * g)311 static int64_t put_header(ByteIOContext *pb, const GUID *g)
312 {
313     int64_t pos;
314 
315     pos = url_ftell(pb);
316     put_guid(pb, g);
317     put_le64(pb, 24);
318     return pos;
319 }
320 
321 /* update header size */
end_header(ByteIOContext * pb,int64_t pos)322 static void end_header(ByteIOContext *pb, int64_t pos)
323 {
324     int64_t pos1;
325 
326     pos1 = url_ftell(pb);
327     url_fseek(pb, pos + 16, SEEK_SET);
328     put_le64(pb, pos1 - pos);
329     url_fseek(pb, pos1, SEEK_SET);
330 }
331 
332 /* write an asf chunk (only used in streaming case) */
put_chunk(AVFormatContext * s,int type,int payload_length,int flags)333 static void put_chunk(AVFormatContext *s, int type, int payload_length, int flags)
334 {
335     ASFContext *asf = s->priv_data;
336     ByteIOContext *pb = &s->pb;
337     int length;
338 
339     length = payload_length + 8;
340     put_le16(pb, type);
341     put_le16(pb, length);
342     put_le32(pb, asf->seqno);
343     put_le16(pb, flags); /* unknown bytes */
344     put_le16(pb, length);
345     asf->seqno++;
346 }
347 
348 /* convert from unix to windows time */
unix_to_file_time(int ti)349 static int64_t unix_to_file_time(int ti)
350 {
351     int64_t t;
352 
353     t = ti * int64_t_C(10000000);
354     t += int64_t_C(116444736000000000);
355     return t;
356 }
357 
358 /* write the header (used two times if non streamed) */
asf_write_header1(AVFormatContext * s,int64_t file_size,int64_t data_chunk_size)359 static int asf_write_header1(AVFormatContext *s, int64_t file_size, int64_t data_chunk_size)
360 {
361     ASFContext *asf = s->priv_data;
362     ByteIOContext *pb = &s->pb;
363     int header_size, n, extra_size, extra_size2, wav_extra_size, file_time;
364     int has_title;
365     AVCodecContext *enc;
366     int64_t header_offset, cur_pos, hpos;
367     int bit_rate;
368 
369     has_title = (s->title[0] || s->author[0] || s->copyright[0] || s->comment[0]);
370 
371     bit_rate = 0;
372     for(n=0;n<s->nb_streams;n++) {
373         enc = &s->streams[n]->codec;
374 
375         bit_rate += enc->bit_rate;
376     }
377 
378     if (asf->is_streamed) {
379         put_chunk(s, 0x4824, 0, 0xc00); /* start of stream (length will be patched later) */
380     }
381 
382     put_guid(pb, &asf_header);
383     put_le64(pb, -1); /* header length, will be patched after */
384     put_le32(pb, 3 + has_title + s->nb_streams); /* number of chunks in header */
385     put_byte(pb, 1); /* ??? */
386     put_byte(pb, 2); /* ??? */
387 
388     /* file header */
389     header_offset = url_ftell(pb);
390     hpos = put_header(pb, &file_header);
391     put_guid(pb, &my_guid);
392     put_le64(pb, file_size);
393     file_time = 0;
394     put_le64(pb, unix_to_file_time(file_time));
395     put_le64(pb, asf->nb_packets); /* number of packets */
396     put_le64(pb, asf->duration); /* end time stamp (in 100ns units) */
397     put_le64(pb, asf->duration); /* duration (in 100ns units) */
398     put_le32(pb, 0); /* start time stamp */
399     put_le32(pb, 0); /* ??? */
400     put_le32(pb, asf->is_streamed ? 1 : 0); /* ??? */
401     put_le32(pb, asf->packet_size); /* packet size */
402     put_le32(pb, asf->packet_size); /* packet size */
403     put_le32(pb, bit_rate); /* Nominal data rate in bps */
404     end_header(pb, hpos);
405 
406     /* unknown headers */
407     hpos = put_header(pb, &head1_guid);
408     put_guid(pb, &head2_guid);
409     put_le32(pb, 6);
410     put_le16(pb, 0);
411     end_header(pb, hpos);
412 
413     /* title and other infos */
414     if (has_title) {
415         hpos = put_header(pb, &comment_header);
416         put_le16(pb, 2 * (strlen(s->title) + 1));
417         put_le16(pb, 2 * (strlen(s->author) + 1));
418         put_le16(pb, 2 * (strlen(s->copyright) + 1));
419         put_le16(pb, 2 * (strlen(s->comment) + 1));
420         put_le16(pb, 0);
421         put_str16_nolen(pb, s->title);
422         put_str16_nolen(pb, s->author);
423         put_str16_nolen(pb, s->copyright);
424         put_str16_nolen(pb, s->comment);
425         end_header(pb, hpos);
426     }
427 
428     /* stream headers */
429     for(n=0;n<s->nb_streams;n++) {
430         int64_t es_pos;
431         //        ASFStream *stream = &asf->streams[n];
432 
433         enc = &s->streams[n]->codec;
434         asf->streams[n].num = n + 1;
435         asf->streams[n].seq = 0;
436 
437         switch(enc->codec_type) {
438         case CODEC_TYPE_AUDIO:
439             wav_extra_size = 0;
440             extra_size = 18 + wav_extra_size;
441             extra_size2 = 0;
442             break;
443         default:
444         case CODEC_TYPE_VIDEO:
445             wav_extra_size = 0;
446             extra_size = 0x33;
447             extra_size2 = 0;
448             break;
449         }
450 
451         hpos = put_header(pb, &stream_header);
452         if (enc->codec_type == CODEC_TYPE_AUDIO) {
453             put_guid(pb, &audio_stream);
454             put_guid(pb, &audio_conceal_none);
455         } else {
456             put_guid(pb, &video_stream);
457             put_guid(pb, &video_conceal_none);
458         }
459         put_le64(pb, 0); /* ??? */
460         es_pos = url_ftell(pb);
461         put_le32(pb, extra_size); /* wav header len */
462         put_le32(pb, extra_size2); /* additional data len */
463         put_le16(pb, n + 1); /* stream number */
464         put_le32(pb, 0); /* ??? */
465 
466         if (enc->codec_type == CODEC_TYPE_AUDIO) {
467             /* WAVEFORMATEX header */
468             int wavsize = put_wav_header(pb, enc);
469 
470             if (wavsize < 0)
471                 return -1;
472             if (wavsize != extra_size) {
473                 cur_pos = url_ftell(pb);
474                 url_fseek(pb, es_pos, SEEK_SET);
475                 put_le32(pb, wavsize); /* wav header len */
476                 url_fseek(pb, cur_pos, SEEK_SET);
477             }
478         } else {
479             put_le32(pb, enc->width);
480             put_le32(pb, enc->height);
481             put_byte(pb, 2); /* ??? */
482             put_le16(pb, 40); /* size */
483 
484             /* BITMAPINFOHEADER header */
485             put_bmp_header(pb, enc, codec_bmp_tags, 1);
486         }
487         end_header(pb, hpos);
488     }
489 
490     /* media comments */
491 
492     hpos = put_header(pb, &codec_comment_header);
493     put_guid(pb, &codec_comment1_header);
494     put_le32(pb, s->nb_streams);
495     for(n=0;n<s->nb_streams;n++) {
496         AVCodec *p;
497 
498         enc = &s->streams[n]->codec;
499         p = avcodec_find_encoder(enc->codec_id);
500 
501         put_le16(pb, asf->streams[n].num);
502         put_str16(pb, p ? p->name : enc->codec_name);
503         put_le16(pb, 0); /* no parameters */
504 
505 
506         /* id */
507         if (enc->codec_type == CODEC_TYPE_AUDIO) {
508             put_le16(pb, 2);
509             if(!enc->codec_tag)
510                 enc->codec_tag = codec_get_tag(codec_wav_tags, enc->codec_id);
511             if(!enc->codec_tag)
512                 return -1;
513             put_le16(pb, enc->codec_tag);
514         } else {
515             put_le16(pb, 4);
516             if(!enc->codec_tag)
517                 enc->codec_tag = codec_get_tag(codec_bmp_tags, enc->codec_id);
518             if(!enc->codec_tag)
519                 return -1;
520             put_le32(pb, enc->codec_tag);
521         }
522     }
523     end_header(pb, hpos);
524 
525     /* patch the header size fields */
526 
527     cur_pos = url_ftell(pb);
528     header_size = cur_pos - header_offset;
529     if (asf->is_streamed) {
530         header_size += 8 + 30 + 50;
531 
532         url_fseek(pb, header_offset - 10 - 30, SEEK_SET);
533         put_le16(pb, header_size);
534         url_fseek(pb, header_offset - 2 - 30, SEEK_SET);
535         put_le16(pb, header_size);
536 
537         header_size -= 8 + 30 + 50;
538     }
539     header_size += 24 + 6;
540     url_fseek(pb, header_offset - 14, SEEK_SET);
541     put_le64(pb, header_size);
542     url_fseek(pb, cur_pos, SEEK_SET);
543 
544     /* movie chunk, followed by packets of packet_size */
545     asf->data_offset = cur_pos;
546     put_guid(pb, &data_header);
547     put_le64(pb, data_chunk_size);
548     put_guid(pb, &my_guid);
549     put_le64(pb, asf->nb_packets); /* nb packets */
550     put_byte(pb, 1); /* ??? */
551     put_byte(pb, 1); /* ??? */
552     return 0;
553 }
554 
asf_write_header(AVFormatContext * s)555 static int asf_write_header(AVFormatContext *s)
556 {
557     ASFContext *asf = s->priv_data;
558 
559     av_set_pts_info(s, 32, 1, 1000); /* 32 bit pts in ms */
560 
561     asf->packet_size = PACKET_SIZE;
562     asf->nb_packets = 0;
563 
564     if (asf_write_header1(s, 0, 50) < 0) {
565         //av_free(asf);
566         return -1;
567     }
568 
569     put_flush_packet(&s->pb);
570 
571     asf->packet_nb_frames = 0;
572     asf->packet_timestamp_start = -1;
573     asf->packet_timestamp_end = -1;
574     asf->packet_size_left = asf->packet_size - PACKET_HEADER_SIZE;
575     init_put_byte(&asf->pb, asf->packet_buf, asf->packet_size, 1,
576                   NULL, NULL, NULL, NULL);
577 
578     return 0;
579 }
580 
asf_write_stream_header(AVFormatContext * s)581 static int asf_write_stream_header(AVFormatContext *s)
582 {
583     ASFContext *asf = s->priv_data;
584 
585     asf->is_streamed = 1;
586 
587     return asf_write_header(s);
588 }
589 
590 /* write a fixed size packet */
put_packet(AVFormatContext * s,unsigned int timestamp,unsigned int duration,int nb_frames,int padsize)591 static int put_packet(AVFormatContext *s,
592                        unsigned int timestamp, unsigned int duration,
593                        int nb_frames, int padsize)
594 {
595     ASFContext *asf = s->priv_data;
596     ByteIOContext *pb = &s->pb;
597     int flags;
598 
599     if (asf->is_streamed) {
600         put_chunk(s, 0x4424, asf->packet_size, 0);
601     }
602 
603     put_byte(pb, 0x82);
604     put_le16(pb, 0);
605 
606     flags = 0x01; /* nb segments present */
607     if (padsize > 0) {
608         if (padsize < 256)
609             flags |= 0x08;
610         else
611             flags |= 0x10;
612     }
613     put_byte(pb, flags); /* flags */
614     put_byte(pb, 0x5d);
615     if (flags & 0x10)
616         put_le16(pb, padsize - 2);
617     if (flags & 0x08)
618         put_byte(pb, padsize - 1);
619     put_le32(pb, timestamp);
620     put_le16(pb, duration);
621     put_byte(pb, nb_frames | 0x80);
622 
623     return PACKET_HEADER_SIZE + ((flags & 0x18) >> 3);
624 }
625 
flush_packet(AVFormatContext * s)626 static void flush_packet(AVFormatContext *s)
627 {
628     ASFContext *asf = s->priv_data;
629     int hdr_size, ptr;
630 
631     hdr_size = put_packet(s, asf->packet_timestamp_start,
632                asf->packet_timestamp_end - asf->packet_timestamp_start,
633                asf->packet_nb_frames, asf->packet_size_left);
634 
635     /* Clear out the padding bytes */
636     ptr = asf->packet_size - hdr_size - asf->packet_size_left;
637     memset(asf->packet_buf + ptr, 0, asf->packet_size_left);
638 
639     put_buffer(&s->pb, asf->packet_buf, asf->packet_size - hdr_size);
640 
641     put_flush_packet(&s->pb);
642     asf->nb_packets++;
643     asf->packet_nb_frames = 0;
644     asf->packet_timestamp_start = -1;
645     asf->packet_timestamp_end = -1;
646     asf->packet_size_left = asf->packet_size - PACKET_HEADER_SIZE;
647     init_put_byte(&asf->pb, asf->packet_buf, asf->packet_size, 1,
648                   NULL, NULL, NULL, NULL);
649 }
650 
put_frame_header(AVFormatContext * s,ASFStream * stream,int timestamp,int payload_size,int frag_offset,int frag_len)651 static void put_frame_header(AVFormatContext *s, ASFStream *stream, int timestamp,
652                              int payload_size, int frag_offset, int frag_len)
653 {
654     ASFContext *asf = s->priv_data;
655     ByteIOContext *pb = &asf->pb;
656     int val;
657 
658     val = stream->num;
659     if (s->streams[val - 1]->codec.coded_frame->key_frame /* && frag_offset == 0 */)
660         val |= 0x80;
661     put_byte(pb, val);
662     put_byte(pb, stream->seq);
663     put_le32(pb, frag_offset); /* fragment offset */
664     put_byte(pb, 0x08); /* flags */
665     put_le32(pb, payload_size);
666     put_le32(pb, timestamp);
667     put_le16(pb, frag_len);
668 }
669 
670 
671 /* Output a frame. We suppose that payload_size <= PACKET_SIZE.
672 
673    It is there that you understand that the ASF format is really
674    crap. They have misread the MPEG Systems spec !
675  */
put_frame(AVFormatContext * s,ASFStream * stream,int timestamp,const uint8_t * buf,int payload_size)676 static void put_frame(AVFormatContext *s, ASFStream *stream, int timestamp,
677                       const uint8_t *buf, int payload_size)
678 {
679     ASFContext *asf = s->priv_data;
680     int frag_pos, frag_len, frag_len1;
681 
682     frag_pos = 0;
683     while (frag_pos < payload_size) {
684         frag_len = payload_size - frag_pos;
685         frag_len1 = asf->packet_size_left - FRAME_HEADER_SIZE;
686         if (frag_len1 > 0) {
687             if (frag_len > frag_len1)
688                 frag_len = frag_len1;
689             put_frame_header(s, stream, timestamp+1, payload_size, frag_pos, frag_len);
690             put_buffer(&asf->pb, buf, frag_len);
691             asf->packet_size_left -= (frag_len + FRAME_HEADER_SIZE);
692             asf->packet_timestamp_end = timestamp;
693             if (asf->packet_timestamp_start == -1)
694                 asf->packet_timestamp_start = timestamp;
695             asf->packet_nb_frames++;
696         } else {
697             frag_len = 0;
698         }
699         frag_pos += frag_len;
700         buf += frag_len;
701         /* output the frame if filled */
702         if (asf->packet_size_left <= FRAME_HEADER_SIZE)
703             flush_packet(s);
704     }
705     stream->seq++;
706 }
707 
708 
asf_write_packet(AVFormatContext * s,int stream_index,const uint8_t * buf,int size,int64_t timestamp)709 static int asf_write_packet(AVFormatContext *s, int stream_index,
710                             const uint8_t *buf, int size, int64_t timestamp)
711 {
712     ASFContext *asf = s->priv_data;
713     ASFStream *stream;
714     int64_t duration;
715     AVCodecContext *codec;
716 
717     codec = &s->streams[stream_index]->codec;
718     stream = &asf->streams[stream_index];
719 
720     if (codec->codec_type == CODEC_TYPE_AUDIO) {
721         duration = (codec->frame_number * codec->frame_size * int64_t_C(10000000)) /
722             codec->sample_rate;
723     } else {
724         duration = av_rescale(codec->frame_number * codec->frame_rate_base, 10000000, codec->frame_rate);
725     }
726     if (duration > asf->duration)
727         asf->duration = duration;
728 
729     put_frame(s, stream, timestamp, buf, size);
730     return 0;
731 }
732 
asf_write_trailer(AVFormatContext * s)733 static int asf_write_trailer(AVFormatContext *s)
734 {
735     ASFContext *asf = s->priv_data;
736     int64_t file_size;
737 
738     /* flush the current packet */
739     if (asf->pb.buf_ptr > asf->pb.buffer)
740         flush_packet(s);
741 
742     if (asf->is_streamed) {
743         put_chunk(s, 0x4524, 0, 0); /* end of stream */
744     } else {
745         /* rewrite an updated header */
746         file_size = url_ftell(&s->pb);
747         url_fseek(&s->pb, 0, SEEK_SET);
748         asf_write_header1(s, file_size, file_size - asf->data_offset);
749     }
750 
751     put_flush_packet(&s->pb);
752     return 0;
753 }
754 #endif //CONFIG_ENCODERS
755 
756 /**********************************/
757 /* decoding */
758 
759 //#define DEBUG
760 
761 #ifdef DEBUG
762 #define PRINT_IF_GUID(g,cmp) \
763 if (!memcmp(g, &cmp, sizeof(GUID))) \
764     printf("(GUID: %s) ", #cmp)
765 
print_guid(const GUID * g)766 static void print_guid(const GUID *g)
767 {
768     int i;
769     PRINT_IF_GUID(g, asf_header);
770     else PRINT_IF_GUID(g, file_header);
771     else PRINT_IF_GUID(g, stream_header);
772     else PRINT_IF_GUID(g, audio_stream);
773     else PRINT_IF_GUID(g, audio_conceal_none);
774     else PRINT_IF_GUID(g, video_stream);
775     else PRINT_IF_GUID(g, video_conceal_none);
776     else PRINT_IF_GUID(g, comment_header);
777     else PRINT_IF_GUID(g, codec_comment_header);
778     else PRINT_IF_GUID(g, codec_comment1_header);
779     else PRINT_IF_GUID(g, data_header);
780     else PRINT_IF_GUID(g, index_guid);
781     else PRINT_IF_GUID(g, head1_guid);
782     else PRINT_IF_GUID(g, head2_guid);
783     else PRINT_IF_GUID(g, my_guid);
784     else
785         printf("(GUID: unknown) ");
786     printf("0x%08x, 0x%04x, 0x%04x, {", g->v1, g->v2, g->v3);
787     for(i=0;i<8;i++)
788         printf(" 0x%02x,", g->v4[i]);
789     printf("}\n");
790 }
791 #undef PRINT_IF_GUID(g,cmp)
792 #endif
793 
get_guid(ByteIOContext * s,GUID * g)794 static void get_guid(ByteIOContext *s, GUID *g)
795 {
796     int i;
797 
798     g->v1 = get_le32(s);
799     g->v2 = get_le16(s);
800     g->v3 = get_le16(s);
801     for(i=0;i<8;i++)
802         g->v4[i] = get_byte(s);
803 }
804 
805 #if 0
806 static void get_str16(ByteIOContext *pb, char *buf, int buf_size)
807 {
808     int len, c;
809     char *q;
810 
811     len = get_le16(pb);
812     q = buf;
813     while (len > 0) {
814         c = get_le16(pb);
815         if ((q - buf) < buf_size - 1)
816             *q++ = c;
817         len--;
818     }
819     *q = '\0';
820 }
821 #endif
822 
823 /*
824 static char *getlocale()
825 {
826     char *str;
827 
828     str = strstr(getenv("LANG"), ".");
829     if(str)
830         *str++;
831     else
832         str = "US-ASCII";
833 
834     return str;
835 }
836 */
837 
838 #if defined(USE_ICONV)
tag_recode(char * before,unsigned int len)839 static void tag_recode(char *before, unsigned int len)
840 {
841        int result;
842        iconv_t frt;
843        char ansb[len];
844        char ansa[len];
845        char *ansbptr = ansb;
846        char *ansaptr = ansa;
847        unsigned int len1 = 2 * len;
848        unsigned int length = len;
849 
850        memcpy(ansb, before, len);
851        frt = iconv_open(getlocale(), "UTF-16LE");
852        if (frt == (iconv_t) - 1)
853        {
854            return;
855        }
856        result = iconv(frt, &ansbptr, &len, &ansaptr, &len1);
857        if (result == (size_t) - 1)
858        {
859            return;
860        }
861        else
862            memcpy(before, ansa, length);
863        if (iconv_close(frt) != 0)
864 	   if (iconv_close(frt) != 0)
865 		return;
866        return;
867 }
868 #endif /* USE_ICONV */
869 
get_str16_nolen(ByteIOContext * pb,int len,char * buf,int buf_size)870 static void get_str16_nolen(ByteIOContext *pb, int len, char *buf, int buf_size)
871 {
872     int c, lenz;
873     char *q;
874 
875     q = buf;
876     lenz = len;
877     while (len > 0) {
878         c = get_byte(pb);
879         if ((q - buf) < buf_size-1)
880             *q++ = c;
881         len--;
882     }
883 #if defined(USE_ICONV)
884     tag_recode(buf, lenz);
885 #endif /* USE_ICONV */
886 }
887 
asf_probe(AVProbeData * pd)888 static int asf_probe(AVProbeData *pd)
889 {
890     GUID g;
891     const unsigned char *p;
892     int i;
893 
894     /* check file header */
895     if (pd->buf_size <= 32)
896         return 0;
897     p = pd->buf;
898     g.v1 = p[0] | (p[1] << 8) | (p[2] << 16) | (p[3] << 24);
899     p += 4;
900     g.v2 = p[0] | (p[1] << 8);
901     p += 2;
902     g.v3 = p[0] | (p[1] << 8);
903     p += 2;
904     for(i=0;i<8;i++)
905         g.v4[i] = *p++;
906 
907     if (!memcmp(&g, &asf_header, sizeof(GUID)))
908         return AVPROBE_SCORE_MAX;
909     else
910         return 0;
911 }
912 
asf_read_header(AVFormatContext * s,AVFormatParameters * ap)913 static int asf_read_header(AVFormatContext *s, AVFormatParameters *ap)
914 {
915     ASFContext *asf = s->priv_data;
916     GUID g;
917     ByteIOContext *pb = &s->pb;
918     AVStream *st;
919     ASFStream *asf_st;
920     //int size, i;
921     int i;
922     int64_t gsize;
923 
924     av_set_pts_info(s, 32, 1, 1000); /* 32 bit pts in ms */
925 
926     get_guid(pb, &g);
927     if (memcmp(&g, &asf_header, sizeof(GUID)))
928         goto fail;
929     get_le64(pb);
930     get_le32(pb);
931     get_byte(pb);
932     get_byte(pb);
933     memset(&asf->asfid2avid, -1, sizeof(asf->asfid2avid));
934     for(;;) {
935         get_guid(pb, &g);
936         gsize = get_le64(pb);
937 #ifdef DEBUG
938         printf("%08Lx: ", url_ftell(pb) - 24);
939         print_guid(&g);
940         printf("  size=0x%Lx\n", gsize);
941 #endif
942         if (gsize < 24)
943             goto fail;
944         if (!memcmp(&g, &file_header, sizeof(GUID))) {
945             get_guid(pb, &asf->hdr.guid);
946 	    asf->hdr.file_size		= get_le64(pb);
947 	    asf->hdr.create_time	= get_le64(pb);
948 	    asf->hdr.packets_count	= get_le64(pb);
949 	    asf->hdr.play_time		= get_le64(pb);
950 	    asf->hdr.send_time		= get_le64(pb);
951 	    asf->hdr.preroll		= get_le32(pb);
952 	    asf->hdr.ignore		= get_le32(pb);
953 	    asf->hdr.flags		= get_le32(pb);
954 	    asf->hdr.min_pktsize	= get_le32(pb);
955 	    asf->hdr.max_pktsize	= get_le32(pb);
956 	    asf->hdr.max_bitrate	= get_le32(pb);
957 	    asf->packet_size = asf->hdr.max_pktsize;
958             asf->nb_packets = asf->hdr.packets_count;
959         } else if (!memcmp(&g, &stream_header, sizeof(GUID))) {
960             int type, total_size, type_specific_size;
961             //unsigned int tag1;
962             int64_t pos1, pos2;
963 
964             pos1 = url_ftell(pb);
965 
966             st = av_new_stream(s, 0);
967             if (!st)
968                 goto fail;
969             asf_st = av_mallocz(sizeof(ASFStream));
970             if (!asf_st)
971                 goto fail;
972             st->priv_data = asf_st;
973             st->start_time = asf->hdr.preroll / (10000000 / AV_TIME_BASE);
974 	    st->duration = (asf->hdr.send_time - asf->hdr.preroll) /
975                 (10000000 / AV_TIME_BASE);
976             get_guid(pb, &g);
977             if (!memcmp(&g, &audio_stream, sizeof(GUID))) {
978                 type = CODEC_TYPE_AUDIO;
979             } else if (!memcmp(&g, &video_stream, sizeof(GUID))) {
980                 type = CODEC_TYPE_VIDEO;
981             } else {
982                 goto fail;
983             }
984             get_guid(pb, &g);
985             total_size = get_le64(pb);
986             type_specific_size = get_le32(pb);
987             get_le32(pb);
988 	    st->id = get_le16(pb) & 0x7f; /* stream id */
989             // mapping of asf ID to AV stream ID;
990             asf->asfid2avid[st->id] = s->nb_streams - 1;
991 
992             get_le32(pb);
993 	    st->codec.codec_type = type;
994             /* 1 fps default (XXX: put 0 fps instead) */
995             st->codec.frame_rate = 1;
996             st->codec.frame_rate_base = 1;
997             if (type == CODEC_TYPE_AUDIO) {
998                 get_wav_header(pb, &st->codec, type_specific_size);
999                 st->need_parsing = 1;
1000 		/* We have to init the frame size at some point .... */
1001 		pos2 = url_ftell(pb);
1002 		if (gsize > (pos2 + 8 - pos1 + 24)) {
1003 		    asf_st->ds_span = get_byte(pb);
1004 		    asf_st->ds_packet_size = get_le16(pb);
1005 		    asf_st->ds_chunk_size = get_le16(pb);
1006 		    asf_st->ds_data_size = get_le16(pb);
1007 		    asf_st->ds_silence_data = get_byte(pb);
1008 		}
1009 		//printf("Descrambling: ps:%d cs:%d ds:%d s:%d  sd:%d\n",
1010 		//       asf_st->ds_packet_size, asf_st->ds_chunk_size,
1011 		//       asf_st->ds_data_size, asf_st->ds_span, asf_st->ds_silence_data);
1012 		if (asf_st->ds_span > 1) {
1013 		    if (!asf_st->ds_chunk_size
1014 			|| (asf_st->ds_packet_size/asf_st->ds_chunk_size <= 1))
1015 			asf_st->ds_span = 0; // disable descrambling
1016 		}
1017                 switch (st->codec.codec_id) {
1018                 case CODEC_ID_MP3:
1019                     st->codec.frame_size = MPA_FRAME_SIZE;
1020                     break;
1021                 case CODEC_ID_PCM_S16LE:
1022                 case CODEC_ID_PCM_S16BE:
1023                 case CODEC_ID_PCM_U16LE:
1024                 case CODEC_ID_PCM_U16BE:
1025                 case CODEC_ID_PCM_S8:
1026                 case CODEC_ID_PCM_U8:
1027                 case CODEC_ID_PCM_ALAW:
1028                 case CODEC_ID_PCM_MULAW:
1029                     st->codec.frame_size = 1;
1030                     break;
1031                 default:
1032                     /* This is probably wrong, but it prevents a crash later */
1033                     st->codec.frame_size = 1;
1034                     break;
1035                 }
1036 	    }
1037 #if 0
1038 	    } else {
1039 		get_le32(pb);
1040                 get_le32(pb);
1041                 get_byte(pb);
1042                 size = get_le16(pb); /* size */
1043                 get_le32(pb); /* size */
1044                 st->codec.width = get_le32(pb);
1045 		st->codec.height = get_le32(pb);
1046                 /* not available for asf */
1047                 get_le16(pb); /* panes */
1048 		st->codec.bits_per_sample = get_le16(pb); /* depth */
1049                 tag1 = get_le32(pb);
1050 		url_fskip(pb, 20);
1051 		if (size > 40) {
1052 		    st->codec.extradata_size = size - 40;
1053 		    st->codec.extradata = av_mallocz(st->codec.extradata_size);
1054 		    get_buffer(pb, st->codec.extradata, st->codec.extradata_size);
1055 		}
1056 
1057         /* Extract palette from extradata if bpp <= 8 */
1058         /* This code assumes that extradata contains only palette */
1059         /* This is true for all paletted codecs implemented in ffmpeg */
1060         if (st->codec.extradata_size && (st->codec.bits_per_sample <= 8)) {
1061             st->codec.palctrl = av_mallocz(sizeof(AVPaletteControl));
1062 #ifdef WORDS_BIGENDIAN
1063             for (i = 0; i < FFMIN(st->codec.extradata_size, AVPALETTE_SIZE)/4; i++)
1064                 st->codec.palctrl->palette[i] = bswap_32(((uint32_t*)st->codec.extradata)[i]);
1065 #else
1066             memcpy(st->codec.palctrl->palette, st->codec.extradata,
1067                    FFMIN(st->codec.extradata_size, AVPALETTE_SIZE));
1068 #endif
1069             st->codec.palctrl->palette_changed = 1;
1070         }
1071 
1072                 st->codec.codec_tag = tag1;
1073 		st->codec.codec_id = codec_get_id(codec_bmp_tags, tag1);
1074             }
1075 #endif
1076             pos2 = url_ftell(pb);
1077             url_fskip(pb, gsize - (pos2 - pos1 + 24));
1078         } else if (!memcmp(&g, &data_header, sizeof(GUID))) {
1079             break;
1080         } else if (!memcmp(&g, &comment_header, sizeof(GUID))) {
1081             int len1, len2, len3, len4, len5;
1082 
1083             len1 = get_le16(pb);
1084             len2 = get_le16(pb);
1085             len3 = get_le16(pb);
1086             len4 = get_le16(pb);
1087             len5 = get_le16(pb);
1088             get_str16_nolen(pb, len1, s->title, sizeof(s->title));
1089             get_str16_nolen(pb, len2, s->author, sizeof(s->author));
1090             get_str16_nolen(pb, len3, s->copyright, sizeof(s->copyright));
1091             get_str16_nolen(pb, len4, s->comment, sizeof(s->comment));
1092 	    url_fskip(pb, len5);
1093        } else if (!memcmp(&g, &extended_content_header, sizeof(GUID))) {
1094                 int desc_count, i;
1095 
1096                 desc_count = get_le16(pb);
1097                 for(i=0;i<desc_count;i++)
1098                 {
1099                         int name_len,value_type,value_len,value_num = 0;
1100                         char *name, *value;
1101 
1102                         name_len = get_le16(pb);
1103                         name = (char *)av_mallocz(name_len);
1104                         get_str16_nolen(pb, name_len, name, name_len);
1105                         value_type = get_le16(pb);
1106                         value_len = get_le16(pb);
1107                         if ((value_type == 0) || (value_type == 1)) // unicode or byte
1108                         {
1109                                 value = (char *)av_mallocz(value_len);
1110                                 get_str16_nolen(pb, value_len, value, value_len);
1111                                 if (strcmp(name,"WM/AlbumTitle")==0) { strcpy(s->album, value); }
1112                                 if (strcmp(name,"WM/Genre")==0) { strcpy(s->genre, value); }
1113                                 if (strcmp(name,"WM/Year")==0) s->year = atoi(value);
1114                                 av_free(value);
1115                         }
1116                         if ((value_type >= 2) || (value_type <= 5)) // boolean or DWORD or QWORD or WORD
1117                         {
1118                                 if (value_type==2) value_num = get_le32(pb);
1119                                 if (value_type==3) value_num = get_le32(pb);
1120                                 if (value_type==4) value_num = get_le64(pb);
1121                                 if (value_type==5) value_num = get_le16(pb);
1122                                 if (strcmp(name,"WM/Track")==0) s->track = value_num + 1;
1123                                 if (strcmp(name,"WM/TrackNumber")==0) s->track = value_num;
1124                         }
1125                         av_free(name);
1126                 }
1127 #if 0
1128         } else if (!memcmp(&g, &head1_guid, sizeof(GUID))) {
1129             int v1, v2;
1130             get_guid(pb, &g);
1131             v1 = get_le32(pb);
1132             v2 = get_le16(pb);
1133         } else if (!memcmp(&g, &codec_comment_header, sizeof(GUID))) {
1134             int len, v1, n, num;
1135             char str[256], *q;
1136             char tag[16];
1137 
1138             get_guid(pb, &g);
1139             print_guid(&g);
1140 
1141             n = get_le32(pb);
1142             for(i=0;i<n;i++) {
1143                 num = get_le16(pb); /* stream number */
1144                 get_str16(pb, str, sizeof(str));
1145                 get_str16(pb, str, sizeof(str));
1146                 len = get_le16(pb);
1147                 q = tag;
1148                 while (len > 0) {
1149                     v1 = get_byte(pb);
1150                     if ((q - tag) < sizeof(tag) - 1)
1151                         *q++ = v1;
1152                     len--;
1153                 }
1154                 *q = '\0';
1155             }
1156 #endif
1157         } else if (url_feof(pb)) {
1158             goto fail;
1159         } else {
1160             url_fseek(pb, gsize - 24, SEEK_CUR);
1161         }
1162     }
1163     get_guid(pb, &g);
1164     get_le64(pb);
1165     get_byte(pb);
1166     get_byte(pb);
1167     if (url_feof(pb))
1168         goto fail;
1169     asf->data_offset = url_ftell(pb);
1170     asf->packet_size_left = 0;
1171 
1172     return 0;
1173 
1174  fail:
1175      for(i=0;i<s->nb_streams;i++) {
1176         AVStream *st = s->streams[i];
1177 	if (st) {
1178 	    av_free(st->priv_data);
1179             av_free(st->codec.extradata);
1180 	}
1181         av_free(st);
1182     }
1183     return -1;
1184 }
1185 
1186 #define DO_2BITS(bits, var, defval) \
1187     switch (bits & 3) \
1188     { \
1189     case 3: var = get_le32(pb); rsize += 4; break; \
1190     case 2: var = get_le16(pb); rsize += 2; break; \
1191     case 1: var = get_byte(pb); rsize++; break; \
1192     default: var = defval; break; \
1193     }
1194 
asf_get_packet(AVFormatContext * s)1195 static int asf_get_packet(AVFormatContext *s)
1196 {
1197     ASFContext *asf = s->priv_data;
1198     ByteIOContext *pb = &s->pb;
1199     uint32_t packet_length, padsize;
1200     int rsize = 9;
1201     int c;
1202 
1203     assert((url_ftell(&s->pb) - s->data_offset) % asf->packet_size == 0);
1204 
1205     c = get_byte(pb);
1206     if (c != 0x82) {
1207         if (!url_feof(pb))
1208 	    printf("ff asf bad header %x  at:%lld\n", c, (long long)url_ftell(pb));
1209     }
1210     if ((c & 0x0f) == 2) { // always true for now
1211 	if (get_le16(pb) != 0) {
1212             if (!url_feof(pb))
1213 		printf("ff asf bad non zero\n");
1214 	    return -EIO;
1215 	}
1216         rsize+=2;
1217 /*    }else{
1218         if (!url_feof(pb))
1219 	    printf("ff asf bad header %x  at:%lld\n", c, url_ftell(pb));
1220 	return -EIO;*/
1221     }
1222 
1223     asf->packet_flags = get_byte(pb);
1224     asf->packet_property = get_byte(pb);
1225 
1226     DO_2BITS(asf->packet_flags >> 5, packet_length, asf->packet_size);
1227     DO_2BITS(asf->packet_flags >> 1, padsize, 0); // sequence ignored
1228     DO_2BITS(asf->packet_flags >> 3, padsize, 0); // padding length
1229 
1230     asf->packet_timestamp = get_le32(pb);
1231     get_le16(pb); /* duration */
1232     // rsize has at least 11 bytes which have to be present
1233 
1234     if (asf->packet_flags & 0x01) {
1235 	asf->packet_segsizetype = get_byte(pb); rsize++;
1236         asf->packet_segments = asf->packet_segsizetype & 0x3f;
1237     } else {
1238 	asf->packet_segments = 1;
1239         asf->packet_segsizetype = 0x80;
1240     }
1241     asf->packet_size_left = packet_length - padsize - rsize;
1242     if (packet_length < asf->hdr.min_pktsize)
1243         padsize += asf->hdr.min_pktsize - packet_length;
1244     asf->packet_padsize = padsize;
1245 #ifdef DEBUG
1246     printf("packet: size=%d padsize=%d  left=%d\n", asf->packet_size, asf->packet_padsize, asf->packet_size_left);
1247 #endif
1248     return 0;
1249 }
1250 
asf_read_packet(AVFormatContext * s,AVPacket * pkt)1251 static int asf_read_packet(AVFormatContext *s, AVPacket *pkt)
1252 {
1253     ASFContext *asf = s->priv_data;
1254     ASFStream *asf_st = 0;
1255     ByteIOContext *pb = &s->pb;
1256     //static int pc = 0;
1257     for (;;) {
1258 	int rsize = 0;
1259 	if (asf->packet_size_left < FRAME_HEADER_SIZE
1260 	    || asf->packet_segments < 1) {
1261 	    //asf->packet_size_left <= asf->packet_padsize) {
1262 	    int ret = asf->packet_size_left + asf->packet_padsize;
1263 	    //printf("PacketLeftSize:%d  Pad:%d Pos:%Ld\n", asf->packet_size_left, asf->packet_padsize, url_ftell(pb));
1264 	    /* fail safe */
1265 	    url_fskip(pb, ret);
1266             asf->packet_pos= url_ftell(&s->pb);
1267 	    ret = asf_get_packet(s);
1268 	    //printf("READ ASF PACKET  %d   r:%d   c:%d\n", ret, asf->packet_size_left, pc++);
1269 	    if (ret < 0 || url_feof(pb))
1270 		return -EIO;
1271             asf->packet_time_start = 0;
1272             continue;
1273 	}
1274 	if (asf->packet_time_start == 0) {
1275 	    /* read frame header */
1276             int num = get_byte(pb);
1277 	    asf->packet_segments--;
1278 	    rsize++;
1279 	    asf->packet_key_frame = (num & 0x80) >> 7;
1280 	    asf->stream_index = asf->asfid2avid[num & 0x7f];
1281 	    // sequence should be ignored!
1282 	    DO_2BITS(asf->packet_property >> 4, asf->packet_seq, 0);
1283 	    DO_2BITS(asf->packet_property >> 2, asf->packet_frag_offset, 0);
1284 	    DO_2BITS(asf->packet_property, asf->packet_replic_size, 0);
1285 //printf("key:%d stream:%d seq:%d offset:%d replic_size:%d\n", asf->packet_key_frame, asf->stream_index, asf->packet_seq, //asf->packet_frag_offset, asf->packet_replic_size);
1286 	    if (asf->packet_replic_size > 1) {
1287                 assert(asf->packet_replic_size >= 8);
1288                 // it should be always at least 8 bytes - FIXME validate
1289 		asf->packet_obj_size = get_le32(pb);
1290 		asf->packet_frag_timestamp = get_le32(pb); // timestamp
1291 		if (asf->packet_replic_size > 8)
1292 		    url_fskip(pb, asf->packet_replic_size - 8);
1293 		rsize += asf->packet_replic_size; // FIXME - check validity
1294 	    } else if (asf->packet_replic_size==1){
1295 		// multipacket - frag_offset is begining timestamp
1296 		asf->packet_time_start = asf->packet_frag_offset;
1297                 asf->packet_frag_offset = 0;
1298 		asf->packet_frag_timestamp = asf->packet_timestamp;
1299 
1300                 asf->packet_time_delta = get_byte(pb);
1301 		rsize++;
1302 	    }else{
1303                 assert(asf->packet_replic_size==0);
1304             }
1305 	    if (asf->packet_flags & 0x01) {
1306 		DO_2BITS(asf->packet_segsizetype >> 6, asf->packet_frag_size, 0); // 0 is illegal
1307 #undef DO_2BITS
1308 		//printf("Fragsize %d\n", asf->packet_frag_size);
1309 	    } else {
1310 		asf->packet_frag_size = asf->packet_size_left - rsize;
1311 		//printf("Using rest  %d %d %d\n", asf->packet_frag_size, asf->packet_size_left, rsize);
1312 	    }
1313 	    if (asf->packet_replic_size == 1) {
1314 		asf->packet_multi_size = asf->packet_frag_size;
1315 		if (asf->packet_multi_size > asf->packet_size_left) {
1316 		    asf->packet_segments = 0;
1317                     continue;
1318 		}
1319 	    }
1320 	    asf->packet_size_left -= rsize;
1321 	    //printf("___objsize____  %d   %d    rs:%d\n", asf->packet_obj_size, asf->packet_frag_offset, rsize);
1322 
1323 	    if (asf->stream_index < 0) {
1324                 asf->packet_time_start = 0;
1325 		/* unhandled packet (should not happen) */
1326 		url_fskip(pb, asf->packet_frag_size);
1327 		asf->packet_size_left -= asf->packet_frag_size;
1328 		printf("ff asf skip %d  %d\n", asf->packet_frag_size, num & 0x7f);
1329                 continue;
1330 	    }
1331 	    asf->asf_st = s->streams[asf->stream_index]->priv_data;
1332 	}
1333 	asf_st = asf->asf_st;
1334 
1335 	if ((asf->packet_frag_offset != asf_st->frag_offset
1336 	     || (asf->packet_frag_offset
1337 		 && asf->packet_seq != asf_st->seq)) // seq should be ignored
1338 	   ) {
1339 	    /* cannot continue current packet: free it */
1340 	    // FIXME better check if packet was already allocated
1341 	    printf("ff asf parser skips: %d - %d     o:%d - %d    %d %d   fl:%d\n",
1342 		   asf_st->pkt.size,
1343 		   asf->packet_obj_size,
1344 		   asf->packet_frag_offset, asf_st->frag_offset,
1345 		   asf->packet_seq, asf_st->seq, asf->packet_frag_size);
1346 	    if (asf_st->pkt.size)
1347 		av_free_packet(&asf_st->pkt);
1348 	    asf_st->frag_offset = 0;
1349 	    if (asf->packet_frag_offset != 0) {
1350 		url_fskip(pb, asf->packet_frag_size);
1351 		printf("ff asf parser skiping %db\n", asf->packet_frag_size);
1352 		asf->packet_size_left -= asf->packet_frag_size;
1353 		continue;
1354 	    }
1355 	}
1356 	if (asf->packet_replic_size == 1) {
1357 	    // frag_offset is here used as the begining timestamp
1358 	    asf->packet_frag_timestamp = asf->packet_time_start;
1359 	    asf->packet_time_start += asf->packet_time_delta;
1360 	    asf->packet_obj_size = asf->packet_frag_size = get_byte(pb);
1361 	    asf->packet_size_left--;
1362             asf->packet_multi_size--;
1363 	    if (asf->packet_multi_size < asf->packet_obj_size)
1364 	    {
1365 		asf->packet_time_start = 0;
1366 		url_fskip(pb, asf->packet_multi_size);
1367 		asf->packet_size_left -= asf->packet_multi_size;
1368                 continue;
1369 	    }
1370 	    asf->packet_multi_size -= asf->packet_obj_size;
1371 	    //printf("COMPRESS size  %d  %d  %d   ms:%d\n", asf->packet_obj_size, asf->packet_frag_timestamp, asf->packet_size_left, asf->packet_multi_size);
1372 	}
1373 	if (asf_st->frag_offset == 0) {
1374 	    /* new packet */
1375 	    av_new_packet(&asf_st->pkt, asf->packet_obj_size);
1376 	    asf_st->seq = asf->packet_seq;
1377 	    asf_st->pkt.pts = asf->packet_frag_timestamp - asf->hdr.preroll;
1378 	    asf_st->pkt.stream_index = asf->stream_index;
1379             asf_st->packet_pos= asf->packet_pos;
1380 //printf("new packet: stream:%d key:%d packet_key:%d audio:%d size:%d\n",
1381 //asf->stream_index, asf->packet_key_frame, asf_st->pkt.flags & PKT_FLAG_KEY,
1382 //s->streams[asf->stream_index]->codec.codec_type == CODEC_TYPE_AUDIO, asf->packet_obj_size);
1383 	    if (s->streams[asf->stream_index]->codec.codec_type == CODEC_TYPE_AUDIO)
1384 		asf->packet_key_frame = 1;
1385 	    if (asf->packet_key_frame)
1386 		asf_st->pkt.flags |= PKT_FLAG_KEY;
1387 	}
1388 
1389 	/* read data */
1390 	//printf("READ PACKET s:%d  os:%d  o:%d,%d  l:%d   DATA:%p\n",
1391 	//       asf->packet_size, asf_st->pkt.size, asf->packet_frag_offset,
1392 	//       asf_st->frag_offset, asf->packet_frag_size, asf_st->pkt.data);
1393 	asf->packet_size_left -= asf->packet_frag_size;
1394 	if (asf->packet_size_left < 0)
1395             continue;
1396 	get_buffer(pb, asf_st->pkt.data + asf->packet_frag_offset,
1397 		   asf->packet_frag_size);
1398 	asf_st->frag_offset += asf->packet_frag_size;
1399 	/* test if whole packet is read */
1400 	if (asf_st->frag_offset == asf_st->pkt.size) {
1401 	    /* return packet */
1402 	    if (asf_st->ds_span > 1) {
1403 		/* packet descrambling */
1404 		unsigned char* newdata = av_malloc(asf_st->pkt.size);
1405 		if (newdata) {
1406 		    int offset = 0;
1407 		    while (offset < asf_st->pkt.size) {
1408 			int off = offset / asf_st->ds_chunk_size;
1409 			int row = off / asf_st->ds_span;
1410 			int col = off % asf_st->ds_span;
1411 			int idx = row + col * asf_st->ds_packet_size / asf_st->ds_chunk_size;
1412 			//printf("off:%d  row:%d  col:%d  idx:%d\n", off, row, col, idx);
1413 			memcpy(newdata + offset,
1414 			       asf_st->pkt.data + idx * asf_st->ds_chunk_size,
1415 			       asf_st->ds_chunk_size);
1416 			offset += asf_st->ds_chunk_size;
1417 		    }
1418 		    av_free(asf_st->pkt.data);
1419 		    asf_st->pkt.data = newdata;
1420 		}
1421 	    }
1422 	    asf_st->frag_offset = 0;
1423 	    memcpy(pkt, &asf_st->pkt, sizeof(AVPacket));
1424 	    //printf("packet %d %d\n", asf_st->pkt.size, asf->packet_frag_size);
1425 	    asf_st->pkt.size = 0;
1426 	    asf_st->pkt.data = 0;
1427 	    break; // packet completed
1428 	}
1429     }
1430     return 0;
1431 }
1432 
asf_read_close(AVFormatContext * s)1433 static int asf_read_close(AVFormatContext *s)
1434 {
1435     int i;
1436 
1437     for(i=0;i<s->nb_streams;i++) {
1438 	AVStream *st = s->streams[i];
1439 	av_free(st->priv_data);
1440 	av_free(st->codec.extradata);
1441     av_free(st->codec.palctrl);
1442     }
1443     return 0;
1444 }
1445 
1446 // Added to support seeking after packets have been read
1447 // If information is not reset, read_packet fails due to
1448 // leftover information from previous reads
asf_reset_header(AVFormatContext * s)1449 static void asf_reset_header(AVFormatContext *s)
1450 {
1451     ASFContext *asf = s->priv_data;
1452     ASFStream *asf_st;
1453     int i;
1454 
1455     asf->packet_nb_frames = 0;
1456     asf->packet_timestamp_start = -1;
1457     asf->packet_timestamp_end = -1;
1458     asf->packet_size_left = 0;
1459     asf->packet_segments = 0;
1460     asf->packet_flags = 0;
1461     asf->packet_property = 0;
1462     asf->packet_timestamp = 0;
1463     asf->packet_segsizetype = 0;
1464     asf->packet_segments = 0;
1465     asf->packet_seq = 0;
1466     asf->packet_replic_size = 0;
1467     asf->packet_key_frame = 0;
1468     asf->packet_padsize = 0;
1469     asf->packet_frag_offset = 0;
1470     asf->packet_frag_size = 0;
1471     asf->packet_frag_timestamp = 0;
1472     asf->packet_multi_size = 0;
1473     asf->packet_obj_size = 0;
1474     asf->packet_time_delta = 0;
1475     asf->packet_time_start = 0;
1476 
1477     for(i=0; i<s->nb_streams; i++){
1478         asf_st= s->streams[i]->priv_data;
1479         av_free_packet(&asf_st->pkt);
1480         asf_st->frag_offset=0;
1481         asf_st->seq=0;
1482     }
1483     asf->asf_st= NULL;
1484 }
1485 
asf_read_pts(AVFormatContext * s,int64_t * ppos,int stream_index)1486 static int64_t asf_read_pts(AVFormatContext *s, int64_t *ppos, int stream_index)
1487 {
1488     ASFContext *asf = s->priv_data;
1489     AVPacket pkt1, *pkt = &pkt1;
1490     ASFStream *asf_st;
1491     int64_t pts;
1492     int64_t pos= *ppos;
1493     int i;
1494     int64_t start_pos[s->nb_streams];
1495 
1496     for(i=0; i<s->nb_streams; i++){
1497         start_pos[i]= pos;
1498     }
1499 
1500 //printf("asf_read_pts\n");
1501     url_fseek(&s->pb, pos*asf->packet_size + s->data_offset, SEEK_SET);
1502     asf_reset_header(s);
1503     for(;;){
1504         if (av_read_frame(s, pkt) < 0){
1505             printf("seek failed\n");
1506     	    return AV_NOPTS_VALUE;
1507         }
1508         pts= pkt->pts;
1509 
1510         av_free_packet(pkt);
1511         if(pkt->flags&PKT_FLAG_KEY){
1512             i= pkt->stream_index;
1513 
1514             asf_st= s->streams[i]->priv_data;
1515 
1516             assert((asf_st->packet_pos - s->data_offset) % asf->packet_size == 0);
1517             pos= (asf_st->packet_pos - s->data_offset) / asf->packet_size;
1518 
1519             av_add_index_entry(s->streams[i], pos, pts, pos - start_pos[i] + 1, AVINDEX_KEYFRAME);
1520             start_pos[i]= pos + 1;
1521 
1522             if(pkt->stream_index == stream_index)
1523                break;
1524         }
1525     }
1526 
1527     *ppos= pos;
1528 //printf("found keyframe at %Ld stream %d stamp:%Ld\n", *ppos, stream_index, pts);
1529 
1530     return pts;
1531 }
1532 
asf_read_seek(AVFormatContext * s,int stream_index,int64_t pts)1533 static int asf_read_seek(AVFormatContext *s, int stream_index, int64_t pts)
1534 {
1535     ASFContext *asf = s->priv_data;
1536     AVStream *st;
1537     int64_t pos;
1538     int64_t pos_min, pos_max, pts_min, pts_max, cur_pts, pos_limit;
1539     int no_change;
1540 
1541     if (stream_index == -1)
1542         stream_index= av_find_default_stream_index(s);
1543 
1544     if (asf->packet_size <= 0)
1545         return -1;
1546 
1547     pts_max=
1548     pts_min= AV_NOPTS_VALUE;
1549     pos_max= pos_limit= -1; // gcc thinks its uninitalized
1550 
1551     st= s->streams[stream_index];
1552     if(st->index_entries){
1553         AVIndexEntry *e;
1554         int index;
1555 
1556         index= av_index_search_timestamp(st, pts);
1557         e= &st->index_entries[index];
1558         if(e->timestamp <= pts){
1559             pos_min= e->pos;
1560             pts_min= e->timestamp;
1561 #ifdef DEBUG_SEEK
1562         printf("unsing cached pos_min=0x%llx dts_min=%0.3f\n",
1563                pos_min,pts_min / 90000.0);
1564 #endif
1565         }else{
1566             assert(index==0);
1567         }
1568         index++;
1569         if(index < st->nb_index_entries){
1570             e= &st->index_entries[index];
1571             assert(e->timestamp >= pts);
1572             pos_max= e->pos;
1573             pts_max= e->timestamp;
1574             pos_limit= pos_max - e->min_distance;
1575 #ifdef DEBUG_SEEK
1576         printf("unsing cached pos_max=0x%llx dts_max=%0.3f\n",
1577                pos_max,pts_max / 90000.0);
1578 #endif
1579         }
1580     }
1581 
1582     if(pts_min == AV_NOPTS_VALUE){
1583         pos_min = 0;
1584         pts_min = asf_read_pts(s, &pos_min, stream_index);
1585         if (pts_min == AV_NOPTS_VALUE) return -1;
1586     }
1587     if(pts_max == AV_NOPTS_VALUE){
1588         pos_max = (url_filesize(url_fileno(&s->pb)) - 1 - s->data_offset) / asf->packet_size; //FIXME wrong
1589         pts_max = s->duration; //FIXME wrong
1590         pos_limit= pos_max;
1591     }
1592 
1593     no_change=0;
1594     while (pos_min < pos_limit) {
1595         int64_t start_pos;
1596         assert(pos_limit <= pos_max);
1597 
1598         if(no_change==0){
1599             int64_t approximate_keyframe_distance= pos_max - pos_limit;
1600             // interpolate position (better than dichotomy)
1601             pos = (int64_t)((double)(pos_max - pos_min) *
1602                             (double)(pts - pts_min) /
1603                             (double)(pts_max - pts_min)) + pos_min - approximate_keyframe_distance;
1604         }else if(no_change==1){
1605             // bisection, if interpolation failed to change min or max pos last time
1606             pos = (pos_min + pos_limit)>>1;
1607         }else{
1608             // linear search if bisection failed, can only happen if there are very few or no keyframes between min/max
1609             pos=pos_min;
1610         }
1611         if(pos <= pos_min)
1612             pos= pos_min + 1;
1613         else if(pos > pos_limit)
1614             pos= pos_limit;
1615         start_pos= pos;
1616 
1617         // read the next timestamp
1618     	cur_pts = asf_read_pts(s, &pos, stream_index);
1619         if(pos == pos_max)
1620             no_change++;
1621         else
1622             no_change=0;
1623 
1624 #ifdef DEBUG_SEEK
1625 printf("%Ld %Ld %Ld / %Ld %Ld %Ld target:%Ld limit:%Ld start:%Ld\n", pos_min, pos, pos_max, pts_min, cur_pts, pts_max, pts, pos_limit, start_pos);
1626 #endif
1627         assert (cur_pts != AV_NOPTS_VALUE);
1628         if (pts < cur_pts) {
1629             pos_limit = start_pos - 1;
1630             pos_max = pos;
1631             pts_max = cur_pts;
1632         } else {
1633             pos_min = pos;
1634             pts_min = cur_pts;
1635             /* check if we are lucky */
1636             if (pts == cur_pts)
1637                 break;
1638         }
1639     }
1640     pos = pos_min;
1641     url_fseek(&s->pb, pos*asf->packet_size + s->data_offset, SEEK_SET);
1642     asf_reset_header(s);
1643     return 0;
1644 }
1645 
1646 static AVInputFormat asf_iformat = {
1647     "asf",
1648     "asf format",
1649     sizeof(ASFContext),
1650     asf_probe,
1651     asf_read_header,
1652     asf_read_packet,
1653     asf_read_close,
1654     asf_read_seek,
1655 };
1656 
1657 #ifdef CONFIG_ENCODERS
1658 static AVOutputFormat asf_oformat = {
1659     "asf",
1660     "asf format",
1661     "video/x-ms-asf",
1662     "asf,wmv",
1663     sizeof(ASFContext),
1664 #ifdef CONFIG_MP3LAME
1665     CODEC_ID_MP3,
1666 #else
1667     CODEC_ID_MP2,
1668 #endif
1669     CODEC_ID_MSMPEG4V3,
1670     asf_write_header,
1671     asf_write_packet,
1672     asf_write_trailer,
1673 };
1674 
1675 static AVOutputFormat asf_stream_oformat = {
1676     "asf_stream",
1677     "asf format",
1678     "video/x-ms-asf",
1679     "asf,wmv",
1680     sizeof(ASFContext),
1681 #ifdef CONFIG_MP3LAME
1682     CODEC_ID_MP3,
1683 #else
1684     CODEC_ID_MP2,
1685 #endif
1686     CODEC_ID_MSMPEG4V3,
1687     asf_write_stream_header,
1688     asf_write_packet,
1689     asf_write_trailer,
1690 };
1691 #endif //CONFIG_ENCODERS
1692 
asf_init(void)1693 int asf_init(void)
1694 {
1695     av_register_input_format(&asf_iformat);
1696 #ifdef CONFIG_ENCODERS
1697     av_register_output_format(&asf_oformat);
1698     av_register_output_format(&asf_stream_oformat);
1699 #endif //CONFIG_ENCODERS
1700     return 0;
1701 }
1702