Project

General

Profile

Bug #1569 » dvr_rec.c

Mark Kirkpatrick, 2013-01-23 20:51

 
1
/*
2
 *  Digital Video Recorder
3
 *  Copyright (C) 2008 Andreas Öman
4
 *
5
 *  This program is free software: you can redistribute it and/or modify
6
 *  it under the terms of the GNU General Public License as published by
7
 *  the Free Software Foundation, either version 3 of the License, or
8
 *  (at your option) any later version.
9
 *
10
 *  This program 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
13
 *  GNU General Public License for more details.
14
 *
15
 *  You should have received a copy of the GNU General Public License
16
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
17
 */
18

    
19
#include <stdarg.h>
20
#include <pthread.h>
21
#include <assert.h>
22
#include <string.h>
23
#include <sys/stat.h>
24
#include <libgen.h> /* basename */
25

    
26
#include "htsstr.h"
27

    
28
#include "tvheadend.h"
29
#include "streaming.h"
30
#include "dvr.h"
31
#include "spawn.h"
32
#include "service.h"
33
#include "plumbing/tsfix.h"
34
#include "plumbing/globalheaders.h"
35

    
36
#include "muxer.h"
37

    
38
/**
39
 *
40
 */
41
static void *dvr_thread(void *aux);
42
static void dvr_spawn_postproc(dvr_entry_t *de, const char *dvr_postproc);
43
static void dvr_thread_epilog(dvr_entry_t *de);
44

    
45

    
46
const static int prio2weight[5] = {
47
  [DVR_PRIO_IMPORTANT]   = 500,
48
  [DVR_PRIO_HIGH]        = 400,
49
  [DVR_PRIO_NORMAL]      = 300,
50
  [DVR_PRIO_LOW]         = 200,
51
  [DVR_PRIO_UNIMPORTANT] = 100,
52
};
53

    
54
/**
55
 *
56
 */
57
void
58
dvr_rec_subscribe(dvr_entry_t *de)
59
{
60
  char buf[100];
61
  int weight;
62
  streaming_target_t *st;
63
  int flags;
64

    
65
  assert(de->de_s == NULL);
66

    
67
  if(de->de_pri < 5)
68
    weight = prio2weight[de->de_pri];
69
  else
70
    weight = 300;
71

    
72
  snprintf(buf, sizeof(buf), "DVR: %s", lang_str_get(de->de_title, NULL));
73

    
74
  if(de->de_mc == MC_PASS) {
75
    streaming_queue_init(&de->de_sq, SMT_PACKET);
76
    de->de_gh = NULL;
77
    de->de_tsfix = NULL;
78
    st = &de->de_sq.sq_st;
79
    flags = SUBSCRIPTION_RAW_MPEGTS;
80
  } else {
81
    streaming_queue_init(&de->de_sq, 0);
82
    de->de_tsfix = tsfix_create(&de->de_sq.sq_st);
83
    tsfix_set_start_time(de->de_tsfix, de->de_start - (60 * de->de_start_extra));
84
    st = de->de_gh = globalheaders_create(de->de_tsfix);
85
    flags = 0;
86
  }
87

    
88
  de->de_s = subscription_create_from_channel(de->de_channel, weight,
89
					      buf, st, flags,
90
					      NULL, NULL, NULL);
91

    
92
  pthread_create(&de->de_thread, NULL, dvr_thread, de);
93
}
94

    
95
/**
96
 *
97
 */
98
void
99
dvr_rec_unsubscribe(dvr_entry_t *de, int stopcode)
100
{
101
  assert(de->de_s != NULL);
102

    
103
  subscription_unsubscribe(de->de_s);
104

    
105
  streaming_target_deliver(&de->de_sq.sq_st, streaming_msg_create(SMT_EXIT));
106
  
107
  pthread_join(de->de_thread, NULL);
108
  de->de_s = NULL;
109

    
110
  if(de->de_tsfix)
111
    tsfix_destroy(de->de_tsfix);
112

    
113
  if(de->de_gh)
114
    globalheaders_destroy(de->de_gh);
115

    
116
  de->de_last_error = stopcode;
117
}
118

    
119

    
120
/**
121
 * Replace various chars with a dash
122
 */
123
static void
124
cleanupfilename(char *s, int dvr_flags)
125
{
126
  int i, len = strlen(s);
127
  for(i = 0; i < len; i++) { 
128
    if(s[i] == '\'' || s[i] == '/' || s[i] == ':' || s[i] == '\\' || s[i] == '<' ||
129
       s[i] == '>' || s[i] == '|' || s[i] == '*' || s[i] == '?')
130
      s[i] = '-';
131

    
132
    if((dvr_flags & DVR_WHITESPACE_IN_TITLE) && s[i] == ' ')
133
      s[i] = '-';	
134
  }
135
}
136

    
137
/**
138
 * Filename generator
139
 *
140
 * - convert from utf8
141
 * - avoid duplicate filenames
142
 *
143
 */
144
static int
145
pvr_generate_filename(dvr_entry_t *de, const streaming_start_t *ss)
146
{
147
  char fullname[1000];
148
  char path[500];
149
  int tally = 0;
150
  struct stat st;
151
  char filename[1000];
152
  struct tm tm;
153
  dvr_config_t *cfg = dvr_config_find_by_name_default(de->de_config_name);
154

    
155
  dvr_make_title(filename, sizeof(filename), de);
156
  cleanupfilename(filename,cfg->dvr_flags);
157

    
158
  snprintf(path, sizeof(path), "%s", cfg->dvr_storage);
159

    
160
  /* Remove trailing slash */
161

    
162
  if (path[strlen(path)-1] == '/')
163
    path[strlen(path)-1] = '\0';
164

    
165
  /* Append per-day directory */
166

    
167
  if(cfg->dvr_flags & DVR_DIR_PER_DAY) {
168
    localtime_r(&de->de_start, &tm);
169
    strftime(fullname, sizeof(fullname), "%F", &tm);
170
    cleanupfilename(fullname,cfg->dvr_flags);
171
    snprintf(path + strlen(path), sizeof(path) - strlen(path), 
172
	     "/%s", fullname);
173
  }
174

    
175
  /* Append per-channel directory */
176

    
177
  if(cfg->dvr_flags & DVR_DIR_PER_CHANNEL) {
178

    
179
    char *chname = strdup(de->de_channel->ch_name);
180
    cleanupfilename(chname,cfg->dvr_flags);
181
    snprintf(path + strlen(path), sizeof(path) - strlen(path), 
182
	     "/%s", chname);
183
    free(chname);
184
  }
185

    
186
  // TODO: per-brand, per-season
187

    
188
  /* Append per-title directory */
189

    
190
  if(cfg->dvr_flags & DVR_DIR_PER_TITLE) {
191

    
192
    char *title = strdup(lang_str_get(de->de_title, NULL));
193
    cleanupfilename(title,cfg->dvr_flags);
194
    snprintf(path + strlen(path), sizeof(path) - strlen(path), 
195
	     "/%s", title);
196
    free(title);
197
  }
198

    
199

    
200
  /* */
201
  if(makedirs(path, 0777) != 0) {
202
    return -1;
203
  }
204
  
205

    
206
  /* Construct final name */
207
  
208
  snprintf(fullname, sizeof(fullname), "%s/%s.%s",
209
	   path, filename, muxer_suffix(de->de_mux, ss));
210

    
211
  while(1) {
212
    if(stat(fullname, &st) == -1) {
213
      tvhlog(LOG_DEBUG, "dvr", "File \"%s\" -- %s -- Using for recording",
214
	     fullname, strerror(errno));
215
      break;
216
    }
217

    
218
    tvhlog(LOG_DEBUG, "dvr", "Overwrite protection, file \"%s\" exists", 
219
	   fullname);
220

    
221
    tally++;
222

    
223
    snprintf(fullname, sizeof(fullname), "%s/%s-%d.%s",
224
	     path, filename, tally, muxer_suffix(de->de_mux, ss));
225
  }
226

    
227
  tvh_str_set(&de->de_filename, fullname);
228

    
229
  return 0;
230
}
231

    
232
/**
233
 *
234
 */
235
static void
236
dvr_rec_fatal_error(dvr_entry_t *de, const char *fmt, ...)
237
{
238
  char msgbuf[256];
239

    
240
  va_list ap;
241
  va_start(ap, fmt);
242

    
243
  vsnprintf(msgbuf, sizeof(msgbuf), fmt, ap);
244
  va_end(ap);
245

    
246
  tvhlog(LOG_ERR, "dvr", 
247
	 "Recording error: \"%s\": %s",
248
	 de->de_filename ?: lang_str_get(de->de_title, NULL), msgbuf);
249
}
250

    
251

    
252
/**
253
 *
254
 */
255
static void
256
dvr_rec_set_state(dvr_entry_t *de, dvr_rs_state_t newstate, int error)
257
{
258
  int notify = 0;
259
  if(de->de_rec_state != newstate) {
260
    de->de_rec_state = newstate;
261
    notify = 1;
262
  }
263
  if(de->de_last_error != error) {
264
    de->de_last_error = error;
265
    notify = 1;
266
    if(error)
267
      de->de_errors++;
268
  }
269
  if (notify)
270
    dvr_entry_notify(de);
271
}
272

    
273
/**
274
 *
275
 */
276
static int
277
dvr_rec_start(dvr_entry_t *de, const streaming_start_t *ss)
278
{
279
  const source_info_t *si = &ss->ss_si;
280
  const streaming_start_component_t *ssc;
281
  int i;
282
  dvr_config_t *cfg = dvr_config_find_by_name_default(de->de_config_name);
283

    
284
  de->de_mux = muxer_create(de->de_mc);
285
  if(!de->de_mux) {
286
    dvr_rec_fatal_error(de, "Unable to create muxer");
287
    return -1;
288
  }
289

    
290
  if(pvr_generate_filename(de, ss) != 0) {
291
    dvr_rec_fatal_error(de, "Unable to create directories");
292
    return -1;
293
  }
294

    
295
  if(muxer_open_file(de->de_mux, de->de_filename)) {
296
    dvr_rec_fatal_error(de, "Unable to open file");
297
    return -1;
298
  }
299

    
300
  if(muxer_init(de->de_mux, ss, lang_str_get(de->de_title, NULL))) {
301
    dvr_rec_fatal_error(de, "Unable to init file");
302
    return -1;
303
  }
304

    
305
  if(cfg->dvr_flags & DVR_TAG_FILES && de->de_bcast) {
306
    if(muxer_write_meta(de->de_mux, de->de_bcast)) {
307
      dvr_rec_fatal_error(de, "Unable to write meta data");
308
      return -1;
309
    }
310
  }
311

    
312
  tvhlog(LOG_INFO, "dvr", "%s from "
313
	 "adapter: \"%s\", "
314
	 "network: \"%s\", mux: \"%s\", provider: \"%s\", "
315
	 "service: \"%s\"",
316
	 de->de_filename ?: lang_str_get(de->de_title, NULL),
317
	 si->si_adapter  ?: "<N/A>",
318
	 si->si_network  ?: "<N/A>",
319
	 si->si_mux      ?: "<N/A>",
320
	 si->si_provider ?: "<N/A>",
321
	 si->si_service  ?: "<N/A>");
322

    
323

    
324
  tvhlog(LOG_INFO, "dvr",
325
	 " #  %-16s  %-4s  %-10s  %-12s  %-11s  %-8s",
326
	 "type",
327
	 "lang",
328
	 "resolution",
329
	 "aspect ratio",
330
	 "sample rate",
331
	 "channels");
332

    
333
  for(i = 0; i < ss->ss_num_components; i++) {
334
    ssc = &ss->ss_components[i];
335

    
336
    char res[11];
337
    char asp[6];
338
    char sr[6];
339
    char ch[7];
340

    
341
    if(SCT_ISAUDIO(ssc->ssc_type)) {
342
      if(ssc->ssc_sri)
343
	snprintf(sr, sizeof(sr), "%d", sri_to_rate(ssc->ssc_sri));
344
      else
345
	strcpy(sr, "?");
346

    
347
      if(ssc->ssc_channels == 6)
348
	snprintf(ch, sizeof(ch), "5.1");
349
      else if(ssc->ssc_channels == 0)
350
	strcpy(ch, "?");
351
      else
352
	snprintf(ch, sizeof(ch), "%d", ssc->ssc_channels);
353
    } else {
354
      sr[0] = 0;
355
      ch[0] = 0;
356
    }
357

    
358
    if(SCT_ISVIDEO(ssc->ssc_type)) {
359
      if(ssc->ssc_width && ssc->ssc_height)
360
	snprintf(res, sizeof(res), "%dx%d",
361
		 ssc->ssc_width, ssc->ssc_height);
362
      else
363
	strcpy(res, "?");
364
    } else {
365
      res[0] = 0;
366
    }
367

    
368
    if(SCT_ISVIDEO(ssc->ssc_type)) {
369
      if(ssc->ssc_aspect_num &&  ssc->ssc_aspect_den)
370
	snprintf(asp, sizeof(asp), "%d:%d",
371
		 ssc->ssc_aspect_num, ssc->ssc_aspect_den);
372
      else
373
	strcpy(asp, "?");
374
    } else {
375
      asp[0] = 0;
376
    }
377

    
378
    tvhlog(LOG_INFO, "dvr",
379
	   "%2d  %-16s  %-4s  %-10s  %-12s  %-11s  %-8s  %s",
380
	   ssc->ssc_index,
381
	   streaming_component_type2txt(ssc->ssc_type),
382
	   ssc->ssc_lang,
383
	   res,
384
	   asp,
385
	   sr,
386
	   ch,
387
	   ssc->ssc_disabled ? "<disabled, no valid input>" : "");
388
  }
389

    
390
  return 0;
391
}
392

    
393

    
394
/**
395
 *
396
 */
397
static void *
398
dvr_thread(void *aux)
399
{
400
  dvr_entry_t *de = aux;
401
  dvr_config_t *cfg = dvr_config_find_by_name_default(de->de_config_name);
402
  streaming_queue_t *sq = &de->de_sq;
403
  streaming_message_t *sm;
404
  th_pkt_t *pkt;
405
  int run = 1;
406
  int started = 0;
407
  int comm_skip = (cfg->dvr_flags & DVR_SKIP_COMMERCIALS);
408
  int commercial = COMMERCIAL_UNKNOWN;
409

    
410
  pthread_mutex_lock(&sq->sq_mutex);
411

    
412
  while(run) {
413
    sm = TAILQ_FIRST(&sq->sq_queue);
414
    if(sm == NULL) {
415
      pthread_cond_wait(&sq->sq_cond, &sq->sq_mutex);
416
      continue;
417
    }
418
    
419
    TAILQ_REMOVE(&sq->sq_queue, sm, sm_link);
420

    
421
    pthread_mutex_unlock(&sq->sq_mutex);
422

    
423
    switch(sm->sm_type) {
424

    
425
    case SMT_PACKET:
426
      pkt = sm->sm_data;
427
      if(pkt->pkt_commercial == COMMERCIAL_YES)
428
	dvr_rec_set_state(de, DVR_RS_COMMERCIAL, 0);
429
      else
430
	dvr_rec_set_state(de, DVR_RS_RUNNING, 0);
431

    
432
      if(pkt->pkt_commercial == COMMERCIAL_YES && comm_skip)
433
	break;
434

    
435
      if(commercial != pkt->pkt_commercial)
436
	muxer_add_marker(de->de_mux);
437

    
438
      commercial = pkt->pkt_commercial;
439

    
440
      if(started) {
441
	muxer_write_pkt(de->de_mux, sm->sm_type, sm->sm_data);
442
	sm->sm_data = NULL;
443
      }
444
      break;
445

    
446
    case SMT_MPEGTS:
447
      if(started) {
448
	dvr_rec_set_state(de, DVR_RS_RUNNING, 0);
449
	muxer_write_pkt(de->de_mux, sm->sm_type, sm->sm_data);
450
	sm->sm_data = NULL;
451
      }
452
      break;
453

    
454
    case SMT_START:
455
      if(started &&
456
	 muxer_reconfigure(de->de_mux, sm->sm_data) < 0) {
457
	tvhlog(LOG_WARNING,
458
	       "dvr", "Unable to reconfigure \"%s\"",
459
	       de->de_filename ?: lang_str_get(de->de_title, NULL));
460

    
461
	// Try to restart the recording if the muxer doesn't
462
	// support reconfiguration of the streams.
463
	dvr_thread_epilog(de);
464
	started = 0;
465
      }
466

    
467
      if(!started) {
468
	pthread_mutex_lock(&global_lock);
469
	dvr_rec_set_state(de, DVR_RS_WAIT_PROGRAM_START, 0);
470
	if(dvr_rec_start(de, sm->sm_data) == 0)
471
	  started = 1;
472
	pthread_mutex_unlock(&global_lock);
473
      } 
474
      break;
475

    
476
    case SMT_STOP:
477
       if(sm->sm_code == SM_CODE_SOURCE_RECONFIGURED) {
478
	 // Subscription is restarting, wait for SMT_START
479

    
480
       } else if(sm->sm_code == 0) {
481
	 // Recording is completed
482

    
483
	de->de_last_error = 0;
484
	tvhlog(LOG_INFO, 
485
	       "dvr", "Recording completed: \"%s\"",
486
	       de->de_filename ?: lang_str_get(de->de_title, NULL));
487

    
488
	dvr_thread_epilog(de);
489
	started = 0;
490

    
491
      }else if(de->de_last_error != sm->sm_code) {
492
	 // Error during recording
493

    
494
	 dvr_rec_set_state(de, DVR_RS_ERROR, sm->sm_code);
495
	 tvhlog(LOG_ERR,
496
		"dvr", "Recording stopped: \"%s\": %s",
497
		de->de_filename ?: lang_str_get(de->de_title, NULL),
498
		streaming_code2txt(sm->sm_code));
499

    
500
	 dvr_thread_epilog(de);
501
	 started = 0;
502
      }
503
      break;
504

    
505
    case SMT_SERVICE_STATUS:
506
      if(sm->sm_code & TSS_PACKETS) {
507
	
508
      } else if(sm->sm_code & (TSS_GRACEPERIOD | TSS_ERRORS)) {
509

    
510
	int code = SM_CODE_UNDEFINED_ERROR;
511

    
512

    
513
	if(sm->sm_code & TSS_NO_DESCRAMBLER)
514
	  code = SM_CODE_NO_DESCRAMBLER;
515

    
516
	if(sm->sm_code & TSS_NO_ACCESS)
517
	  code = SM_CODE_NO_ACCESS;
518

    
519
	if(de->de_last_error != code) {
520
	  dvr_rec_set_state(de, DVR_RS_ERROR, code);
521
	  tvhlog(LOG_ERR,
522
		 "dvr", "Streaming error: \"%s\": %s",
523
		 de->de_filename ?: lang_str_get(de->de_title, NULL),
524
		 streaming_code2txt(code));
525
	}
526
      }
527
      break;
528

    
529
    case SMT_NOSTART:
530

    
531
      if(de->de_last_error != sm->sm_code) {
532
	dvr_rec_set_state(de, DVR_RS_PENDING, sm->sm_code);
533

    
534
	tvhlog(LOG_ERR,
535
	       "dvr", "Recording unable to start: \"%s\": %s",
536
	       de->de_filename ?: lang_str_get(de->de_title, NULL),
537
	       streaming_code2txt(sm->sm_code));
538
      }
539
      break;
540

    
541
    case SMT_SPEED:
542
    case SMT_SKIP:
543
    case SMT_SIGNAL_STATUS:
544
    case SMT_TIMESHIFT_STATUS:
545
      break;
546

    
547
    case SMT_EXIT:
548
      run = 0;
549
      break;
550
    }
551

    
552
    streaming_msg_free(sm);
553
    pthread_mutex_lock(&sq->sq_mutex);
554
  }
555
  pthread_mutex_unlock(&sq->sq_mutex);
556

    
557
  if(de->de_mux)
558
    dvr_thread_epilog(de);
559

    
560
  return NULL;
561
}
562

    
563

    
564
/**
565
 *
566
 */
567
static void
568
dvr_spawn_postproc(dvr_entry_t *de, const char *dvr_postproc)
569
{
570
  const char *fmap[256];
571
  char **args;
572
  char start[16];
573
  char stop[16];
574
  char *fbasename; /* filename dup for basename */
575
  int i;
576

    
577
  args = htsstr_argsplit(dvr_postproc);
578
  /* no arguments at all */
579
  if(!args[0]) {
580
    htsstr_argsplit_free(args);
581
    return;
582
  }
583

    
584
  fbasename = strdup(de->de_filename); 
585
  snprintf(start, sizeof(start), "%ld", de->de_start - de->de_start_extra);
586
  snprintf(stop, sizeof(stop),   "%ld", de->de_stop  + de->de_stop_extra);
587

    
588
  memset(fmap, 0, sizeof(fmap));
589
  fmap['f'] = de->de_filename; /* full path to recoding */
590
  fmap['b'] = basename(fbasename); /* basename of recoding */
591
  fmap['c'] = de->de_channel->ch_name; /* channel name */
592
  fmap['C'] = de->de_creator; /* user who created this recording */
593
  fmap['t'] = lang_str_get(de->de_title, NULL); /* program title */
594
  fmap['d'] = lang_str_get(de->de_desc, NULL); /* program description */
595
  /* error message, empty if no error (FIXME:?) */
596
  fmap['e'] = tvh_strdupa(streaming_code2txt(de->de_last_error));
597
  fmap['S'] = start; /* start time, unix epoch */
598
  fmap['E'] = stop; /* stop time, unix epoch */
599
  // TODO: brand, season
600

    
601
  /* format arguments */
602
  for(i = 0; args[i]; i++) {
603
    char *s;
604

    
605
    s = htsstr_format(args[i], fmap);
606
    free(args[i]);
607
    args[i] = s;
608
  }
609
  
610
  spawnv(args[0], (void *)args);
611
    
612
  free(fbasename);
613
  htsstr_argsplit_free(args);
614
}
615

    
616
/**
617
 *
618
 */
619
static void
620
dvr_thread_epilog(dvr_entry_t *de)
621
{
622
  muxer_close(de->de_mux);
623
  muxer_destroy(de->de_mux);
624
  de->de_mux = NULL;
625

    
626
  dvr_config_t *cfg = dvr_config_find_by_name_default(de->de_config_name);
627
  if(cfg->dvr_postproc)
628
    dvr_spawn_postproc(de,cfg->dvr_postproc);
629
}
    (1-1/1)