-- service->pcr_packet_period =
-- pcr_st->codecpar->sample_rate / (10 * frame_size);
-- }
-- } else {
-- // max delta PCR 0.1s
-- // TODO: should be avg_frame_rate
-- service->pcr_packet_period =
-- ts_st->user_tb.den / (10 * ts_st->user_tb.num);
-- }
-- if (!service->pcr_packet_period)
-- service->pcr_packet_period = 1;
-- }
--
-- ts->last_pat_ts = AV_NOPTS_VALUE;
-- ts->last_sdt_ts = AV_NOPTS_VALUE;
-- // The user specified a period, use only it
-- if (ts->pat_period < INT_MAX/2) {
-- ts->pat_packet_period = INT_MAX;
-+ if (!pcr_st && s->nb_streams > 0)
-+ pcr_st = s->streams[0];
-+ if (!pcr_st) {
-+ av_log(s, AV_LOG_ERROR, "no streams\n");
-+ ret = AVERROR(EINVAL);
-+ goto fail;
- }
-- if (ts->sdt_period < INT_MAX/2) {
-- ts->sdt_packet_period = INT_MAX;
-+ ts_st = pcr_st->priv_data;
-+ if (service->pcr_sid == 0x1fff)
-+ service->pcr_sid = ts_st->pid;
-+ if (service->pcr_pid == 0x1fff)
-+ service->pcr_pid = ts->m2ts_mode > 1 ?
-+ 0x1000 + ts->service_id : service->pcr_sid ;
-+ if (service->pmt.pid == service->pcr_pid) {
-+ av_log(s, AV_LOG_ERROR, "Duplicate stream id %d\n", service->pcr_pid);
-+ ret = AVERROR(EINVAL);
-+ goto fail;
- }
-
-+ clk_rate = ts->mux_rate > 1 ? ts->mux_rate : PCR_TIME_BASE;
-+ ts->sdt_packet_period = ts->sdt_period < 0 ? -1 : ts->sdt_period/1000 * clk_rate;
-+ ts->pat_packet_period = ts->pat_period/1000 * clk_rate;
-+ service->pcr_packet_period = ts->pcr_period/1000 * clk_rate;
-+ if (service->pcr_packet_period < (TS_PACKET_SIZE*8*10))
-+ service->pcr_packet_period = (TS_PACKET_SIZE*8*10);
-+ av_log(s, AV_LOG_VERBOSE, "clk_rate %f: ticks/pkt %d pcr, %d sdt, %d pmt\n", clk_rate,
-+ (int)service->pcr_packet_period, (int)ts->sdt_packet_period, (int)ts->pat_packet_period);
-+
-+ if (ts->copyts < 1)
-+ ts->first_pcr = av_rescale(s->max_delay, PCR_TIME_BASE, AV_TIME_BASE);
-+
- // output a PCR as soon as possible
-- service->pcr_packet_count = service->pcr_packet_period;
-- ts->pat_packet_count = ts->pat_packet_period - 1;
-- ts->sdt_packet_count = ts->sdt_packet_period - 1;
+- ts_st->pid = ts->start_pid + i;
+ }
++ else
++ ts_st->pid = START_PID + i;
+ } else {
+ ts_st->pid = st->id;
+ }
+@@ -1267,9 +1269,14 @@
+ ts->last_pat_ts = AV_NOPTS_VALUE;
+ ts->last_sdt_ts = AV_NOPTS_VALUE;
+ ts->last_nit_ts = AV_NOPTS_VALUE;
+- ts->pat_period = av_rescale(ts->pat_period_us, PCR_TIME_BASE, AV_TIME_BASE);
+- ts->sdt_period = av_rescale(ts->sdt_period_us, PCR_TIME_BASE, AV_TIME_BASE);
+- ts->nit_period = av_rescale(ts->nit_period_us, PCR_TIME_BASE, AV_TIME_BASE);
++ ts->pat_period = ts->pat_period_us < 0 ? -1 :
++ av_rescale(ts->pat_period_us, PCR_TIME_BASE, AV_TIME_BASE);
++ ts->sdt_period = ts->sdt_period_us < 0 ? -1 :
++ av_rescale(ts->sdt_period_us, PCR_TIME_BASE, AV_TIME_BASE);
++ ts->nit_period = ts->nit_period_us < 0 ? -1 :
++ av_rescale(ts->nit_period_us, PCR_TIME_BASE, AV_TIME_BASE);