Merge branch 'matroska'
[mplayer/kovensky.git] / stream / cache2.c
blob70ba5d1c5af43e80663b501e54de118def46a993
1 #include "config.h"
3 // Initial draft of my new cache system...
4 // Note it runs in 2 processes (using fork()), but doesn't requires locking!!
5 // TODO: seeking, data consistency checking
7 #define READ_USLEEP_TIME 10000
8 #define FILL_USLEEP_TIME 50000
9 #define PREFILL_SLEEP_TIME 200
10 #define CONTROL_SLEEP_TIME 0
12 #include <stdio.h>
13 #include <stdlib.h>
14 #include <string.h>
15 #include <signal.h>
16 #include <sys/types.h>
17 #include <unistd.h>
18 #include <errno.h>
20 #include "osdep/shmem.h"
21 #include "osdep/timer.h"
22 #if defined(__MINGW32__)
23 #include <windows.h>
24 static void ThreadProc( void *s );
25 #elif defined(__OS2__)
26 #define INCL_DOS
27 #include <os2.h>
28 static void ThreadProc( void *s );
29 #elif defined(PTHREAD_CACHE)
30 #include <pthread.h>
31 static void *ThreadProc(void *s);
32 #else
33 #include <sys/wait.h>
34 #endif
36 #include "mp_msg.h"
37 #include "help_mp.h"
39 #include "stream.h"
40 #include "cache2.h"
42 typedef struct {
43 // constats:
44 unsigned char *buffer; // base pointer of the alllocated buffer memory
45 int buffer_size; // size of the alllocated buffer memory
46 int sector_size; // size of a single sector (2048/2324)
47 int back_size; // we should keep back_size amount of old bytes for backward seek
48 int fill_limit; // we should fill buffer only if space>=fill_limit
49 int seek_limit; // keep filling cache if distanse is less that seek limit
50 // filler's pointers:
51 int eof;
52 off_t min_filepos; // buffer contain only a part of the file, from min-max pos
53 off_t max_filepos;
54 off_t offset; // filepos <-> bufferpos offset value (filepos of the buffer's first byte)
55 // reader's pointers:
56 off_t read_filepos;
57 // commands/locking:
58 // int seek_lock; // 1 if we will seek/reset buffer, 2 if we are ready for cmd
59 // int fifo_flag; // 1 if we should use FIFO to notice cache about buffer reads.
60 // callback
61 stream_t* stream;
62 volatile int control;
63 volatile unsigned control_uint_arg;
64 volatile double control_double_arg;
65 volatile int control_res;
66 volatile off_t control_new_pos;
67 volatile double stream_time_length;
68 } cache_vars_t;
70 static int min_fill=0;
72 int cache_fill_status=0;
74 static void cache_stats(cache_vars_t* s){
75 int newb=s->max_filepos-s->read_filepos; // new bytes in the buffer
76 mp_msg(MSGT_CACHE,MSGL_INFO,"0x%06X [0x%06X] 0x%06X ",(int)s->min_filepos,(int)s->read_filepos,(int)s->max_filepos);
77 mp_msg(MSGT_CACHE,MSGL_INFO,"%3d %% (%3d%%)\n",100*newb/s->buffer_size,100*min_fill/s->buffer_size);
80 static int cache_read(cache_vars_t* s,unsigned char* buf,int size){
81 int total=0;
82 while(size>0){
83 int pos,newb,len;
85 //printf("CACHE2_READ: 0x%X <= 0x%X <= 0x%X \n",s->min_filepos,s->read_filepos,s->max_filepos);
87 if(s->read_filepos>=s->max_filepos || s->read_filepos<s->min_filepos){
88 // eof?
89 if(s->eof) break;
90 // waiting for buffer fill...
91 usec_sleep(READ_USLEEP_TIME); // 10ms
92 continue; // try again...
95 newb=s->max_filepos-s->read_filepos; // new bytes in the buffer
96 if(newb<min_fill) min_fill=newb; // statistics...
98 // printf("*** newb: %d bytes ***\n",newb);
100 pos=s->read_filepos - s->offset;
101 if(pos<0) pos+=s->buffer_size; else
102 if(pos>=s->buffer_size) pos-=s->buffer_size;
104 if(newb>s->buffer_size-pos) newb=s->buffer_size-pos; // handle wrap...
105 if(newb>size) newb=size;
107 // check:
108 if(s->read_filepos<s->min_filepos) mp_msg(MSGT_CACHE,MSGL_ERR,"Ehh. s->read_filepos<s->min_filepos !!! Report bug...\n");
110 // len=write(mem,newb)
111 //printf("Buffer read: %d bytes\n",newb);
112 memcpy(buf,&s->buffer[pos],newb);
113 buf+=newb;
114 len=newb;
115 // ...
117 s->read_filepos+=len;
118 size-=len;
119 total+=len;
122 cache_fill_status=(s->max_filepos-s->read_filepos)/(s->buffer_size / 100);
123 return total;
126 static int cache_fill(cache_vars_t* s){
127 int back,back2,newb,space,len,pos;
128 off_t read=s->read_filepos;
130 if(read<s->min_filepos || read>s->max_filepos){
131 // seek...
132 mp_msg(MSGT_CACHE,MSGL_DBG2,"Out of boundaries... seeking to 0x%"PRIX64" \n",(int64_t)read);
133 // streaming: drop cache contents only if seeking backward or too much fwd:
134 if(s->stream->type!=STREAMTYPE_STREAM ||
135 read<s->min_filepos || read>=s->max_filepos+s->seek_limit)
137 s->offset= // FIXME!?
138 s->min_filepos=s->max_filepos=read; // drop cache content :(
139 if(s->stream->eof) stream_reset(s->stream);
140 stream_seek(s->stream,read);
141 mp_msg(MSGT_CACHE,MSGL_DBG2,"Seek done. new pos: 0x%"PRIX64" \n",(int64_t)stream_tell(s->stream));
145 // calc number of back-bytes:
146 back=read - s->min_filepos;
147 if(back<0) back=0; // strange...
148 if(back>s->back_size) back=s->back_size;
150 // calc number of new bytes:
151 newb=s->max_filepos - read;
152 if(newb<0) newb=0; // strange...
154 // calc free buffer space:
155 space=s->buffer_size - (newb+back);
157 // calc bufferpos:
158 pos=s->max_filepos - s->offset;
159 if(pos>=s->buffer_size) pos-=s->buffer_size; // wrap-around
161 if(space<s->fill_limit){
162 // printf("Buffer is full (%d bytes free, limit: %d)\n",space,s->fill_limit);
163 return 0; // no fill...
166 // printf("### read=0x%X back=%d newb=%d space=%d pos=%d\n",read,back,newb,space,pos);
168 // reduce space if needed:
169 if(space>s->buffer_size-pos) space=s->buffer_size-pos;
171 // if(space>32768) space=32768; // limit one-time block size
172 if(space>4*s->sector_size) space=4*s->sector_size;
174 // if(s->seek_lock) return 0; // FIXME
176 #if 1
177 // back+newb+space <= buffer_size
178 back2=s->buffer_size-(space+newb); // max back size
179 if(s->min_filepos<(read-back2)) s->min_filepos=read-back2;
180 #else
181 s->min_filepos=read-back; // avoid seeking-back to temp area...
182 #endif
184 // ....
185 //printf("Buffer fill: %d bytes of %d\n",space,s->buffer_size);
186 //len=stream_fill_buffer(s->stream);
187 //memcpy(&s->buffer[pos],s->stream->buffer,len); // avoid this extra copy!
188 // ....
189 len=stream_read(s->stream,&s->buffer[pos],space);
190 if(!len) s->eof=1;
192 s->max_filepos+=len;
193 if(pos+len>=s->buffer_size){
194 // wrap...
195 s->offset+=s->buffer_size;
198 return len;
202 static int cache_execute_control(cache_vars_t *s) {
203 int res = 1;
204 static unsigned last;
205 if (!s->stream->control) {
206 s->stream_time_length = 0;
207 s->control_new_pos = 0;
208 s->control_res = STREAM_UNSUPPORTED;
209 s->control = -1;
210 return res;
212 if (GetTimerMS() - last > 99) {
213 double len;
214 if (s->stream->control(s->stream, STREAM_CTRL_GET_TIME_LENGTH, &len) == STREAM_OK)
215 s->stream_time_length = len;
216 else
217 s->stream_time_length = 0;
218 last = GetTimerMS();
220 if (s->control == -1) return res;
221 switch (s->control) {
222 case STREAM_CTRL_GET_CURRENT_TIME:
223 case STREAM_CTRL_SEEK_TO_TIME:
224 case STREAM_CTRL_GET_ASPECT_RATIO:
225 s->control_res = s->stream->control(s->stream, s->control, &s->control_double_arg);
226 break;
227 case STREAM_CTRL_SEEK_TO_CHAPTER:
228 case STREAM_CTRL_GET_NUM_CHAPTERS:
229 case STREAM_CTRL_GET_CURRENT_CHAPTER:
230 case STREAM_CTRL_GET_NUM_ANGLES:
231 case STREAM_CTRL_GET_ANGLE:
232 case STREAM_CTRL_SET_ANGLE:
233 s->control_res = s->stream->control(s->stream, s->control, &s->control_uint_arg);
234 break;
235 case -2:
236 res = 0;
237 default:
238 s->control_res = STREAM_UNSUPPORTED;
239 break;
241 s->control_new_pos = s->stream->pos;
242 s->control = -1;
243 return res;
246 static cache_vars_t* cache_init(int size,int sector){
247 int num;
248 #if !defined(__MINGW32__) && !defined(PTHREAD_CACHE) && !defined(__OS2__)
249 cache_vars_t* s=shmem_alloc(sizeof(cache_vars_t));
250 #else
251 cache_vars_t* s=malloc(sizeof(cache_vars_t));
252 #endif
253 if(s==NULL) return NULL;
255 memset(s,0,sizeof(cache_vars_t));
256 num=size/sector;
257 if(num < 16){
258 num = 16;
259 }//32kb min_size
260 s->buffer_size=num*sector;
261 s->sector_size=sector;
262 #if !defined(__MINGW32__) && !defined(PTHREAD_CACHE) && !defined(__OS2__)
263 s->buffer=shmem_alloc(s->buffer_size);
264 #else
265 s->buffer=malloc(s->buffer_size);
266 #endif
268 if(s->buffer == NULL){
269 #if !defined(__MINGW32__) && !defined(PTHREAD_CACHE) && !defined(__OS2__)
270 shmem_free(s,sizeof(cache_vars_t));
271 #else
272 free(s);
273 #endif
274 return NULL;
277 s->fill_limit=8*sector;
278 s->back_size=s->buffer_size/2;
279 return s;
282 void cache_uninit(stream_t *s) {
283 cache_vars_t* c = s->cache_data;
284 if(s->cache_pid) {
285 #if defined(__MINGW32__) || defined(PTHREAD_CACHE) || defined(__OS2__)
286 cache_do_control(s, -2, NULL);
287 #else
288 kill(s->cache_pid,SIGKILL);
289 waitpid(s->cache_pid,NULL,0);
290 #endif
291 s->cache_pid = 0;
293 if(!c) return;
294 #if defined(__MINGW32__) || defined(PTHREAD_CACHE) || defined(__OS2__)
295 free(c->stream);
296 free(c->buffer);
297 c->buffer = NULL;
298 free(s->cache_data);
299 #else
300 shmem_free(c->buffer,c->buffer_size);
301 c->buffer = NULL;
302 shmem_free(s->cache_data,sizeof(cache_vars_t));
303 #endif
304 s->cache_data = NULL;
307 static void exit_sighandler(int x){
308 // close stream
309 exit(0);
313 * \return 1 on success, 0 if the function was interrupted and -1 on error
315 int stream_enable_cache(stream_t *stream,int size,int min,int seek_limit){
316 int ss = stream->sector_size ? stream->sector_size : STREAM_BUFFER_SIZE;
317 int res = -1;
318 cache_vars_t* s;
320 if (stream->flags & STREAM_NON_CACHEABLE) {
321 mp_msg(MSGT_CACHE,MSGL_STATUS,"\rThis stream is non-cacheable\n");
322 return 1;
325 s=cache_init(size,ss);
326 if(s == NULL) return -1;
327 stream->cache_data=s;
328 s->stream=stream; // callback
329 s->seek_limit=seek_limit;
332 //make sure that we won't wait from cache_fill
333 //more data than it is alowed to fill
334 if (s->seek_limit > s->buffer_size - s->fill_limit ){
335 s->seek_limit = s->buffer_size - s->fill_limit;
337 if (min > s->buffer_size - s->fill_limit) {
338 min = s->buffer_size - s->fill_limit;
341 #if !defined(__MINGW32__) && !defined(PTHREAD_CACHE) && !defined(__OS2__)
342 if((stream->cache_pid=fork())){
343 if ((pid_t)stream->cache_pid == -1)
344 stream->cache_pid = 0;
345 #else
347 stream_t* stream2=malloc(sizeof(stream_t));
348 memcpy(stream2,s->stream,sizeof(stream_t));
349 s->stream=stream2;
350 #if defined(__MINGW32__)
351 stream->cache_pid = _beginthread( ThreadProc, 0, s );
352 #elif defined(__OS2__)
353 stream->cache_pid = _beginthread( ThreadProc, NULL, 256 * 1024, s );
354 #else
356 pthread_t tid;
357 pthread_create(&tid, NULL, ThreadProc, s);
358 stream->cache_pid = 1;
360 #endif
361 #endif
362 if (!stream->cache_pid) {
363 mp_msg(MSGT_CACHE, MSGL_ERR,
364 "Starting cache process/thread failed: %s.\n", strerror(errno));
365 goto err_out;
367 // wait until cache is filled at least prefill_init %
368 mp_msg(MSGT_CACHE,MSGL_V,"CACHE_PRE_INIT: %"PRId64" [%"PRId64"] %"PRId64" pre:%d eof:%d \n",
369 (int64_t)s->min_filepos,(int64_t)s->read_filepos,(int64_t)s->max_filepos,min,s->eof);
370 while(s->read_filepos<s->min_filepos || s->max_filepos-s->read_filepos<min){
371 mp_tmsg(MSGT_CACHE,MSGL_STATUS,"\rCache fill: %5.2f%% (%"PRId64" bytes) ",
372 100.0*(float)(s->max_filepos-s->read_filepos)/(float)(s->buffer_size),
373 (int64_t)s->max_filepos-s->read_filepos
375 if(s->eof) break; // file is smaller than prefill size
376 if(stream_check_interrupt(PREFILL_SLEEP_TIME)) {
377 res = 0;
378 goto err_out;
381 mp_msg(MSGT_CACHE,MSGL_STATUS,"\n");
382 return 1; // parent exits
384 err_out:
385 cache_uninit(stream);
386 return res;
389 #if defined(__MINGW32__) || defined(PTHREAD_CACHE) || defined(__OS2__)
391 #ifdef PTHREAD_CACHE
392 static void *ThreadProc( void *s ){
393 #else
394 static void ThreadProc( void *s ){
395 #endif
396 #endif
398 // cache thread mainloop:
399 signal(SIGTERM,exit_sighandler); // kill
400 do {
401 if(!cache_fill(s)){
402 usec_sleep(FILL_USLEEP_TIME); // idle
404 // cache_stats(s->cache_data);
405 } while (cache_execute_control(s));
406 #if defined(__MINGW32__) || defined(__OS2__)
407 _endthread();
408 #endif
409 #ifdef PTHREAD_CACHE
410 return NULL;
411 #endif
412 // make sure forked code never leaves this function
413 exit(0);
416 int cache_stream_fill_buffer(stream_t *s){
417 int len;
418 if(s->eof){ s->buf_pos=s->buf_len=0; return 0; }
419 if(!s->cache_pid) return stream_fill_buffer(s);
421 // cache_stats(s->cache_data);
423 if(s->pos!=((cache_vars_t*)s->cache_data)->read_filepos) mp_msg(MSGT_CACHE,MSGL_ERR,"!!! read_filepos differs!!! report this bug...\n");
425 len=cache_read(s->cache_data,s->buffer, ((cache_vars_t*)s->cache_data)->sector_size);
426 //printf("cache_stream_fill_buffer->read -> %d\n",len);
428 if(len<=0){ s->eof=1; s->buf_pos=s->buf_len=0; return 0; }
429 s->buf_pos=0;
430 s->buf_len=len;
431 s->pos+=len;
432 // printf("[%d]",len);fflush(stdout);
433 return len;
437 int cache_stream_seek_long(stream_t *stream,off_t pos){
438 cache_vars_t* s;
439 off_t newpos;
440 if(!stream->cache_pid) return stream_seek_long(stream,pos);
442 s=stream->cache_data;
443 // s->seek_lock=1;
445 mp_msg(MSGT_CACHE,MSGL_DBG2,"CACHE2_SEEK: 0x%"PRIX64" <= 0x%"PRIX64" (0x%"PRIX64") <= 0x%"PRIX64" \n",s->min_filepos,pos,s->read_filepos,s->max_filepos);
447 newpos=pos/s->sector_size; newpos*=s->sector_size; // align
448 stream->pos=s->read_filepos=newpos;
449 s->eof=0; // !!!!!!!
451 cache_stream_fill_buffer(stream);
453 pos-=newpos;
454 if(pos>=0 && pos<=stream->buf_len){
455 stream->buf_pos=pos; // byte position in sector
456 return 1;
459 // stream->buf_pos=stream->buf_len=0;
460 // return 1;
462 mp_msg(MSGT_CACHE,MSGL_V,"cache_stream_seek: WARNING! Can't seek to 0x%"PRIX64" !\n",(int64_t)(pos+newpos));
463 return 0;
466 int cache_do_control(stream_t *stream, int cmd, void *arg) {
467 cache_vars_t* s = stream->cache_data;
468 switch (cmd) {
469 case STREAM_CTRL_SEEK_TO_TIME:
470 s->control_double_arg = *(double *)arg;
471 s->control = cmd;
472 break;
473 case STREAM_CTRL_SEEK_TO_CHAPTER:
474 case STREAM_CTRL_SET_ANGLE:
475 s->control_uint_arg = *(unsigned *)arg;
476 s->control = cmd;
477 break;
478 // the core might call these every frame, they are too slow for this...
479 case STREAM_CTRL_GET_TIME_LENGTH:
480 // case STREAM_CTRL_GET_CURRENT_TIME:
481 *(double *)arg = s->stream_time_length;
482 return s->stream_time_length ? STREAM_OK : STREAM_UNSUPPORTED;
483 case STREAM_CTRL_GET_NUM_CHAPTERS:
484 case STREAM_CTRL_GET_CURRENT_CHAPTER:
485 case STREAM_CTRL_GET_ASPECT_RATIO:
486 case STREAM_CTRL_GET_NUM_ANGLES:
487 case STREAM_CTRL_GET_ANGLE:
488 case -2:
489 s->control = cmd;
490 break;
491 default:
492 return STREAM_UNSUPPORTED;
494 while (s->control != -1)
495 usec_sleep(CONTROL_SLEEP_TIME);
496 switch (cmd) {
497 case STREAM_CTRL_GET_TIME_LENGTH:
498 case STREAM_CTRL_GET_CURRENT_TIME:
499 case STREAM_CTRL_GET_ASPECT_RATIO:
500 *(double *)arg = s->control_double_arg;
501 break;
502 case STREAM_CTRL_GET_NUM_CHAPTERS:
503 case STREAM_CTRL_GET_CURRENT_CHAPTER:
504 case STREAM_CTRL_GET_NUM_ANGLES:
505 case STREAM_CTRL_GET_ANGLE:
506 *(unsigned *)arg = s->control_uint_arg;
507 break;
508 case STREAM_CTRL_SEEK_TO_CHAPTER:
509 case STREAM_CTRL_SEEK_TO_TIME:
510 case STREAM_CTRL_SET_ANGLE:
511 stream->pos = s->read_filepos = s->control_new_pos;
512 break;
514 return s->control_res;