int CICache::check_in(Asset *asset)
{
total_lock->lock("CICache::check_in");
+ CICacheItem *current = 0;
if( !check_outs ) {
- CICacheItem *current = first;
+ current = first;
while(current && strcmp(current->asset->path, asset->path) != 0)
current = NEXT;
if(current && current->checked_out) {
int CWindowMaskFeatherSlider::update(float v)
{
- while( max < v ) max *= 1.25;
+ float vv = fabsf(v);
+ while( max < vv ) max *= 1.25;
return update(get_w(), v, -max-5, max+5);
}
int CWindowMaskFeatherSlider::update(int r, float v, float mn, float mx)
AVPacket *pkt = ret > 0 ? (AVPacket*)ipkt : 0;
if( pkt ) {
if( pkt->stream_index != st->index ) continue;
- if( !pkt->data | !pkt->size ) continue;
+ if( !pkt->data || !pkt->size ) continue;
}
if( (ret=avcodec_send_packet(avctx, pkt)) < 0 ) {
ff_err(ret, "FFStream::decode: avcodec_send_packet failed.\nfile:%s\n",
frame->best_effort_timestamp = AV_NOPTS_VALUE;
int ret = avcodec_receive_frame(avctx, frame);
if( ret < 0 ) {
- if( first_frame || ret == AVERROR(EAGAIN) ) return 0;
+ if( first_frame ) return 0;
+ if( ret == AVERROR(EAGAIN) ) return 0;
if( ret == AVERROR_EOF ) { st_eof(1); return 0; }
ff_err(ret, "FFAudioStream::decode_frame: Could not read audio frame.\nfile:%s\n",
ffmpeg->fmt_ctx->url);
int first_frame = seeked; seeked = 0;
int ret = avcodec_receive_frame(avctx, frame);
if( ret < 0 ) {
- if( first_frame || ret == AVERROR(EAGAIN) ) return 0;
+ if( first_frame ) return 0;
if( ret == AVERROR(EAGAIN) ) return 0;
if( ret == AVERROR_EOF ) { st_eof(1); return 0; }
ff_err(ret, "FFVideoStream::decode_frame: Could not read video frame.\nfile:%s\n,",
class MaskEdge : public ArrayList<MaskCoord>
{
public:
- MaskCoord &append() { return ArrayList<MaskCoord>::append(); }
MaskCoord &append(double x, double y, double z=0) {
- MaskCoord &c = append();
+ MaskCoord &c = ArrayList<MaskCoord>::append();
c.x = x; c.y = y; c.z = z;
return c;
}
va_end(ap);
FILE *fp = !strcmp(fn,"-") ? stdout : fopen(fn,"w");
if( fp ) {
+ uint8_t **rows = (uint8_t**)vfrm->get_rows();
int w = vfrm->get_w(), h = vfrm->get_h();
int m = vfrm->get_color_model();
- fprintf(fp,"P5\n%d %d\n%d\n",w,h,m==BC_A8? 0xff : 0xffff);
int bpp = m==BC_A8? 1 : 2;
- fwrite(vfrm->get_data(),bpp*w,h,fp); fflush(fp);
+ fprintf(fp,"P5\n%d %d\n%d\n",w,h,255);
+ for( int y=0; y<h; ++y ) {
+ uint8_t *bp = rows[y];
+ for( int x=0; x<w; ++x,bp+=bpp ) {
+ int b = m==BC_A8 ? *(uint8_t*)bp : *(uint16_t*)bp>>8;
+ putc(b,fp);
+ }
+ }
+ fflush(fp);
if( fp != stdout ) fclose(fp);
}
}
: LoadClient(engine)
{
this->engine = engine;
- spot = 0;
- r = 0;
}
MaskUnit::~MaskUnit()
{
}
-void MaskUnit::draw_line(int v, int ix1, int iy1, int ix2, int iy2)
+void MaskUnit::clear_mask(VFrame *msk, int a)
+{
+ temp_t **mrows = (temp_t **)msk->get_rows();
+ int w = msk->get_w();
+ for( int y=start_y; y<end_y; ++y ) {
+ temp_t *mrow = mrows[y];
+ for( int x=0; x<w; ++x ) mrow[x] = a;
+ }
+}
+
+void MaskUnit::draw_line(int ix1, int iy1, int ix2, int iy2)
{
if( iy1 == iy2 ) return;
int x1 = iy1 < iy2 ? ix1 : ix2;
if( y2 > end_y ) y2 = end_y;
if( y2 < start_y || y1 >= end_y ) return;
- VFrame *temp = engine->temp;
- int w1 = temp->get_w()-1;
- temp_t **rows = (temp_t **)temp->get_rows();
+ VFrame *in = engine->in;
+ int w1 = in->get_w()-1;
+ temp_t **irows = (temp_t **)in->get_rows();
for( int y=y1; y<y2; ++i,++y ) {
int x = (int)(i*slope + x1);
bclamp(x, 0, w1);
- rows[y][x] = rows[y][x] == v ? 0 : v;
+ irows[y][x] = irows[y][x] == fc ? bc : fc;
}
}
-
-void MaskUnit::draw_fill(int v)
+void MaskUnit::draw_fill()
{
- VFrame *temp = engine->temp;
- int temp_w = temp->get_w();
- temp_t **rows = (temp_t**)temp->get_rows();
+ VFrame *in = engine->in;
+ temp_t **irows = (temp_t**)in->get_rows();
+ int w = in->get_w();
for( int y=start_y; y<end_y; ++y ) {
- temp_t *row = rows[y];
- int value = 0, total = 0;
- for( int x=0; x<temp_w; ++x )
- if( row[x] == v ) ++total;
+ temp_t *irow = irows[y];
+ int total = 0;
+ for( int x=0; x<w; ++x )
+ if( irow[x] == fc ) ++total;
if( total < 2 ) continue;
if( total & 0x1 ) --total;
- for( int x=0; x<temp_w; ++x ) {
- if( row[x]==v && total>0 ) {
+ int inside = 0;
+ for( int x=0; x<w; ++x ) {
+ if( irow[x]==fc && total>0 ) {
--total;
- value = value ? 0 : v;
+ inside = 1-inside;
}
- else if( value )
- row[x] = value;
+ else if( inside )
+ irow[x] = fc;
}
}
}
int y1 = iy1 < iy2 ? iy1 : iy2;
int x2 = iy1 < iy2 ? ix2 : ix1;
int y2 = iy1 < iy2 ? iy2 : iy1;
- VFrame *temp = engine->temp;
- int h = temp->get_h();
+ VFrame *in = engine->in;
+ int h = in->get_h();
if( y2 < 0 || y1 >= h ) return;
int x = x1, y = y1;
int dx = x2-x1, dy = y2-y1;
int dx2 = 2*dx, dy2 = 2*dy;
if( dx < 0 ) dx = -dx;
- int m = dx > dy ? dx : dy, n = m;
+ int m = dx > dy ? dx : dy, i = m;
if( dy >= dx ) {
if( dx2 >= 0 ) do { /* +Y, +X */
- draw_spot(x, y++);
+ draw_edge(x, y++);
if( (m -= dx2) < 0 ) { m += dy2; ++x; }
- } while( --n >= 0 );
+ } while( --i >= 0 );
else do { /* +Y, -X */
- draw_spot(x, y++);
+ draw_edge(x, y++);
if( (m += dx2) < 0 ) { m += dy2; --x; }
- } while( --n >= 0 );
+ } while( --i >= 0 );
}
else {
if( dx2 >= 0 ) do { /* +X, +Y */
- draw_spot(x++, y);
+ draw_edge(x++, y);
if( (m -= dy2) < 0 ) { m += dx2; ++y; }
- } while( --n >= 0 );
+ } while( --i >= 0 );
else do { /* -X, +Y */
- draw_spot(x--, y);
+ draw_edge(x--, y);
if( (m -= dy2) < 0 ) { m -= dx2; ++y; }
- } while( --n >= 0 );
+ } while( --i >= 0 );
}
}
-void MaskUnit::draw_spot(int ix, int iy)
+void MaskUnit::draw_edge(int ix, int iy)
{
- int rr = r * r, n = abs(r), rv = r * v;
- if( iy < start_y-n || iy >= end_y+n ) return;
- VFrame *temp = engine->temp;
- int w1 = temp->get_w()-1, h1 = temp->get_h()-1;
- int xs = ix - n; bclamp(xs, 0, w1);
- int xn = ix + n; bclamp(xn, 0, w1);
- int ys = iy - n; bclamp(ys, 0, h1);
- int yn = iy + n; bclamp(yn, 0, h1);
-
- temp_t **rows = (temp_t**)temp->get_rows();
- for( int y=ys ; y<=yn; ++y ) {
- temp_t *row = rows[y];
- for( int x=xs; x<=xn; ++x ) {
- int dx = x-ix, dy = y-iy;
- int dd = dx*dx + dy*dy;
- if( dd >= rr ) continue;
- temp_t *rp = &row[x], a = spot[dd];
- if( rv*(*rp-a) < 0 ) *rp = a;
- }
+ if( iy < start_y || iy >= end_y ) return;
+ VFrame *in = engine->in;
+ temp_t **irows = (temp_t **)in->get_rows();
+ irows[iy][ix] = fc;
+}
+void MaskUnit::draw_filled_polygon(MaskEdge &edge)
+{
+ for( int i=0; i<edge.size(); ++i ) {
+ MaskCoord a = edge[i];
+ MaskCoord b = i<edge.size()-1 ? edge[i+1] : edge[0];
+ draw_line(a.x,a.y, b.x,b.y);
}
+ draw_fill();
}
-void MaskUnit::process_package(LoadPackage *package)
+void MaskUnit::feather_x(VFrame *in, VFrame *out)
{
- MaskPackage *ptr = (MaskPackage*)package;
- start_y = ptr->start_y;
- end_y = ptr->end_y;
- if( start_y >= end_y ) return;
- mask_model = engine->mask->get_color_model();
- VFrame *temp = engine->temp;
- if( engine->recalculate && engine->step == DO_MASK ) {
-// Draw masked region of polygons on temp
- for( int k=0; k<engine->edges.size(); ++k ) {
- if( !engine->edges[k] ) continue;
- MaskEdge &edge = *engine->edges[k];
- if( edge.size() < 3 ) continue;
- int v = k + 1;
- for( int i=0; i<edge.size(); ++i ) {
- MaskCoord a = edge[i];
- MaskCoord b = i<edge.size()-1 ? edge[i+1] : edge[0];
- draw_line(v, a.x,a.y, b.x,b.y);
+ float *psf = engine->psf; int psz = engine->psz;
+ temp_t **orows = (temp_t**)out->get_rows();
+ temp_t **irows = (temp_t**)in->get_rows();
+ int w = in->get_w(), w1 = w-1;
+ for( int y=start_y; y<end_y; ++y ) {
+ temp_t *rp = irows[y];
+ for( int x=0; x<w; ++x ) {
+ temp_t c = rp[x], f = c * psf[0];
+ for( int i=1; i<psz; ++i ) {
+ int l = x-i; if( l < 0 ) l = 0;
+ int r = x+i; if( r > w1 ) r = w1;
+ temp_t g = bmax(rp[l], rp[r]) * psf[i];
+ if( f < g ) f = g;
}
- draw_fill(v);
- }
-// map temp to fader alpha
- int temp_w = temp->get_w();
- temp_t **rows = (temp_t**)temp->get_rows();
- temp_t *fade = engine->fade;
- for( int y=start_y; y<end_y; ++y ) {
- temp_t *tp = rows[y];
- for( int i=temp_w; --i>=0; ++tp ) *tp = fade[*tp];
+ orows[y][x] = c > f ? c : f;
}
}
- if( engine->recalculate && engine->step == DO_FEATHER ) {
-// draw feather
- for( int k=0; k<engine->edges.size(); ++k ) {
- if( !(v = engine->faders[k]) ) continue;
- if( !(r = engine->feathers[k]) ) continue;
- MaskEdge &edge = *engine->edges[k];
- if( !edge.size() ) continue;
- float rv = r * v, vv = fabs(v);
- int fg = 0xffff * (rv >= 0 ? vv : 0);
- int bg = 0xffff * (rv >= 0 ? 0 : vv);
- int rr = r*r; double dr = 1./rr;
- // gausian, rr is x**2, limit 1/255
- double sig2 = -log(255.0);
- temp_t psf[rr+1]; spot = psf;
- for( int i=0; i<=rr; ++i ) {
- double d = exp(i*dr * sig2);
- psf[i] = d*fg + (1-d)*bg;
- }
- int n = edge.size();
- for( int i=0; i<n; ++i ) {
- MaskCoord &a = edge[i];
- MaskCoord &b = i<edge.size()-1 ? edge[i+1] : edge[0];
- draw_feather(a.x,a.y, b.x,b.y);
+}
+void MaskUnit::feather_y(VFrame *in, VFrame *out)
+{
+ float *psf = engine->psf; int psz = engine->psz;
+ temp_t **orows = (temp_t**)out->get_rows();
+ temp_t **irows = (temp_t**)in->get_rows();
+ int h = in->get_h(), h1 = h-1;
+ for( int y=0; y<h; ++y ) {
+ temp_t *rp = irows[y];
+ for( int x=start_x; x<end_x; ++x ) {
+ temp_t c = rp[x], f = c * psf[0];
+ for( int i=1; i<psz; ++i ) {
+ int d = y-i; if( d < 0 ) d = 0;
+ int u = y+i; if( u > h1 ) u = h1;
+ temp_t *drow = irows[d], *urow = irows[u];
+ temp_t g = bmax(drow[x], urow[x]) * psf[i];
+ if( f < g ) f = g;
}
+ orows[y][x] = c > f ? c : f;
}
-
-#define REMAP(cmodel, type, expr) case cmodel: { \
-type **msk_rows = (type**)engine->mask->get_rows(); \
-for( int y=start_y; y<end_y; ++y ) { \
- temp_t *rp = rows[y]; \
- type *mp = msk_rows[y]; \
- for( int i=temp_w; --i>=0; ++rp,++mp ) *mp = expr; \
-} } break
-// map alpha to mask
- const float to_flt = 1/65535.;
- int temp_w = temp->get_w();
- temp_t **rows = (temp_t**)temp->get_rows();
- switch( mask_model ) {
- REMAP(BC_A8, uint8_t, *rp >> 8);
- REMAP(BC_A16, uint16_t, *rp);
- REMAP(BC_A_FLOAT, float, *rp * to_flt);
+ }
+}
+void MaskUnit::mask_blend(VFrame *in, VFrame *mask, float r, float v)
+{
+ temp_t **irows = (temp_t**)in->get_rows();
+ temp_t **mrows = (temp_t**)mask->get_rows();
+ const int mn = 0x0000, mx = 0xffff;
+ int iv = v>=0 ? 1 : -1;
+ float rr = r!=0 ? r : 1;
+ float rv = rr*v>=0. ? 1 : -1;;
+ int vv = (v>=0. ? 1.-v : 1.+v) * mx;
+ unsigned fg = rv>0. ? vv : mx;
+ unsigned bg = rv>0. ? mx : vv;
+ int w = in->get_w();
+ int b = r<0 ? mx : mn;
+ for( int y=start_y; y<end_y; ++y ) {
+ temp_t *irow = irows[y], *mrow = mrows[y];
+ for( int x=0; x<w; ++x ) {
+ temp_t c = irow[x];
+ if( c == b ) continue;
+ temp_t a = (c*fg + (mx-c)*bg) / mx;
+ temp_t *cp = mrow + x, color = *cp;
+ if( iv*(color-a) > 0 ) *cp = a;
}
}
-
-// Apply mask
- if( engine->step == DO_APPLY ) {
- int mask_w = engine->mask->get_w();
- uint8_t **out_rows = engine->output->get_rows();
- uint8_t **msk_rows = engine->mask->get_rows();
+}
+void MaskUnit::apply_mask_alpha(VFrame *output, VFrame *mask)
+{
+ int w = mask->get_w();
+ uint8_t **orows = output->get_rows();
+ temp_t **mrows = (temp_t **)mask->get_rows();
#define APPLY_MASK_ALPHA(cmodel, type, max, components, do_yuv) \
case cmodel: \
-for( int y=ptr->start_y; y<ptr->end_y; ++y ) { \
- type *out_row = (type*)out_rows[y]; \
- type *msk_row = (type*)msk_rows[y]; \
- type chroma_offset = (int)(max + 1) / 2; \
- for( int x=0; x<mask_w; ++x ) { \
- type a = msk_row[x], b = max-a; \
+for( int y=start_y; y<end_y; ++y ) { \
+ type *orow = (type*)orows[y]; \
+ temp_t *mrow = mrows[y]; \
+ for( int x=0; x<w; ++x ) { \
+ temp_t a = mrow[x]; \
if( components == 4 ) { \
- out_row[x*4 + 3] = out_row[x*4 + 3]*b / max; \
+ orow[x*4 + 3] = orow[x*4 + 3]*a / 0xffff; \
} \
else { \
- out_row[x*3 + 0] = out_row[x*3 + 0]*b / max; \
- out_row[x*3 + 1] = out_row[x*3 + 1]*b / max; \
- out_row[x*3 + 2] = out_row[x*3 + 2]*b / max; \
+ orow[x*3 + 0] = orow[x*3 + 0]*a / 0xffff; \
+ orow[x*3 + 1] = orow[x*3 + 1]*a / 0xffff; \
+ orow[x*3 + 2] = orow[x*3 + 2]*a / 0xffff; \
if( do_yuv ) { \
- out_row[x*3 + 1] += chroma_offset*a / max; \
- out_row[x*3 + 2] += chroma_offset*a / max; \
+ a = 0xffff-a; \
+ type chroma_offset = (int)(max + 1) / 2; \
+ orow[x*3 + 1] += chroma_offset*a / 0xffff; \
+ orow[x*3 + 2] += chroma_offset*a / 0xffff; \
} \
} \
} \
} break
- switch( engine->output->get_color_model() ) { \
- APPLY_MASK_ALPHA(BC_RGB888, uint8_t, 0xff, 3, 0); \
- APPLY_MASK_ALPHA(BC_RGB_FLOAT, float, 1.0, 3, 0); \
- APPLY_MASK_ALPHA(BC_YUV888, uint8_t, 0xff, 3, 1); \
- APPLY_MASK_ALPHA(BC_RGBA_FLOAT, float, 1.0, 4, 0); \
- APPLY_MASK_ALPHA(BC_YUVA8888, uint8_t, 0xff, 4, 1); \
- APPLY_MASK_ALPHA(BC_RGBA8888, uint8_t, 0xff, 4, 0); \
- APPLY_MASK_ALPHA(BC_RGB161616, uint16_t, 0xffff, 3, 0); \
- APPLY_MASK_ALPHA(BC_YUV161616, uint16_t, 0xffff, 3, 1); \
- APPLY_MASK_ALPHA(BC_YUVA16161616, uint16_t, 0xffff, 4, 1); \
- APPLY_MASK_ALPHA(BC_RGBA16161616, uint16_t, 0xffff, 4, 0); \
- }
+ switch( engine->output->get_color_model() ) { \
+ APPLY_MASK_ALPHA(BC_RGB888, uint8_t, 0xff, 3, 0); \
+ APPLY_MASK_ALPHA(BC_RGB_FLOAT, float, 1.0, 3, 0); \
+ APPLY_MASK_ALPHA(BC_YUV888, uint8_t, 0xff, 3, 1); \
+ APPLY_MASK_ALPHA(BC_RGBA_FLOAT, float, 1.0, 4, 0); \
+ APPLY_MASK_ALPHA(BC_YUVA8888, uint8_t, 0xff, 4, 1); \
+ APPLY_MASK_ALPHA(BC_RGBA8888, uint8_t, 0xff, 4, 0); \
+ APPLY_MASK_ALPHA(BC_RGB161616, uint16_t, 0xffff, 3, 0); \
+ APPLY_MASK_ALPHA(BC_YUV161616, uint16_t, 0xffff, 3, 1); \
+ APPLY_MASK_ALPHA(BC_YUVA16161616, uint16_t, 0xffff, 4, 1); \
+ APPLY_MASK_ALPHA(BC_RGBA16161616, uint16_t, 0xffff, 4, 0); \
+ }
+}
+
+
+void MaskUnit::process_package(LoadPackage *package)
+{
+ pkg = (MaskPackage*)package;
+ start_x = pkg->start_x; end_x = pkg->end_x;
+ start_y = pkg->start_y; end_y = pkg->end_y;
+ if( start_y >= end_y ) return;
+ MaskEdge *edge = engine->edge;
+ float r = engine->r, v = engine->v;
+ VFrame *in = engine->in;
+ VFrame *out = engine->out;
+ VFrame *mask = engine->mask;
+ switch( engine->step ) {
+ case DO_MASK: {
+// Draw masked region of polygons on in
+ if( edge->size() < 3 ) break;
+ bc = r>=0 ? 0 : 0xffff;
+ fc = r>=0 ? 0xffff : 0;
+ clear_mask(in, bc);
+ if( bc == fc ) break;
+ draw_filled_polygon(*edge);
+ break; }
+ case DO_FEATHER_X: {
+ feather_x(in, out);
+ break; }
+ case DO_FEATHER_Y: {
+ feather_y(out, in);
+ break; }
+ case DO_MASK_BLEND: {
+ mask_blend(in, mask, r, v);
+ break; }
+ case DO_APPLY: {
+ apply_mask_alpha(engine->output, mask);
+ break; }
}
}
// : LoadServer(1, 1)
{
mask = 0;
- temp = 0;
+ in = 0;
+ out = 0;
}
MaskEngine::~MaskEngine()
{
delete mask;
- delete temp;
- for( int i = 0; i < point_sets.total; i++ )
- point_sets[i]->remove_all_objects();
- point_sets.remove_all_objects();
+ delete in;
+ delete out;
}
int MaskEngine::points_equivalent(MaskPoints *new_points,
return 1;
}
+void MaskEngine::clear_mask(VFrame *msk, int a)
+{
+ temp_t **mrows = (temp_t **)msk->get_rows();
+ int w = msk->get_w(), h = msk->get_h();
+ for( int y=0; y<h; ++y ) {
+ temp_t *mrow = mrows[y];
+ for( int x=0; x<w; ++x ) mrow[x] = a;
+ }
+}
+void MaskEngine::draw_point_spot(float r)
+{
+ double sig2 = -log(255.0)/((double)r*r);
+ for( int i=0; i<psz; ++i )
+ psf[i] = exp(i*i * sig2);
+}
+
void MaskEngine::do_mask(VFrame *output,
int64_t start_position_project,
MaskAutos *keyframe_set,
}
// Determine if recalculation is needed
-SET_TRACE
-
int mask_w = output->get_w(), mask_h = output->get_h();
if( mask && ( mask->get_color_model() != mask_model ||
mask->get_w() != mask_w || mask->get_h() != mask_h ) ) {
delete mask; mask = 0;
recalculate = 1;
}
- if( temp && ( temp->get_w() != mask_w || temp->get_h() != mask_h ) ) {
- delete temp; temp = 0;
+ if( in && ( in->get_w() != mask_w || in->get_h() != mask_h ) ) {
+ delete in; in = 0;
+ delete out; out = 0;
}
total_submasks = keyframe_set->total_submasks(start_position_project, PLAY_FORWARD);
if( new_fader != faders[i] ) { recalculate = 1; break; }
float new_feather = keyframe_set->get_feather(start_position_project, i, PLAY_FORWARD);
if( new_feather != feathers[i] ) { recalculate = 1; break; }
- MaskPoints new_points;
- keyframe_set->get_points(&new_points, i,
+ MaskPoints points;
+ keyframe_set->get_points(&points, i,
start_position_project, PLAY_FORWARD);
- if( !points_equivalent(&new_points, point_sets[i]) )
+ if( !points_equivalent(&points, point_sets[i]) )
recalculate = 1;
}
if( recalculate ) {
+ if( !in ) in = new VFrame(mask_w, mask_h, BC_A16, 0);
+ if( !out ) out = new VFrame(mask_w, mask_h, BC_A16, 0);
+ if( !mask ) mask = new VFrame(mask_w, mask_h, BC_A16, 0);
for( int i = 0; i < point_sets.total; i++ ) {
MaskPoints *points = point_sets[i];
points->remove_all_objects();
edges.remove_all_objects();
faders.remove_all();
feathers.remove_all();
- fade[0] = 0;
+ float cc = 1;
int show_mask = keyframe_set->track->masks;
for( int i=0; i<total_submasks; ++i ) {
float fader = keyframe_set->get_fader(start_position_project, i, PLAY_FORWARD);
float v = fader / 100;
faders.append(v);
- temp_t t = fabs(v) * 0xffff;
- if( fader < 0 ) {
- if( fade[0] < t ) fade[0] = t;
- t = 0;
- }
- fade[i+1] = t;
float feather = keyframe_set->get_feather(start_position_project, i, PLAY_FORWARD);
feathers.append(feather);
- MaskPoints *new_points = new MaskPoints();
- keyframe_set->get_points(new_points, i, start_position_project, PLAY_FORWARD);
- point_sets.append(new_points);
- MaskEdge *edge = edges.append(new MaskEdge());
- if( !((show_mask>>i) & 1) ) continue;
- edge->load(*new_points, 0);
+ MaskPoints *points = new MaskPoints();
+ keyframe_set->get_points(points, i, start_position_project, PLAY_FORWARD);
+ point_sets.append(points);
+ MaskEdge &edge = *edges.append(new MaskEdge());
+ if( !fader || !((show_mask>>i) & 1) || !points->size() ) continue;
+ edge.load(*points, 0);
+ if( v >= 0 ) continue;
+ float vv = 1 + v;
+ if( cc > vv ) cc = vv;
}
+ clear_mask(mask, cc*0xffff);
// draw mask
- if( !mask ) mask = new VFrame(mask_w, mask_h, mask_model, 0);
- if( !temp ) temp = new VFrame(mask_w, mask_h, BC_A16, 0);
- mask->clear_frame();
- temp->clear_frame();
- step = DO_MASK;
- process_packages();
- step = DO_FEATHER;
- process_packages();
+ for( int k=0; k<edges.size(); ++k ) {
+ this->edge = edges[k];
+ this->r = feathers[k];
+ this->v = faders[k];
+ if( !this->v ) continue;
+ if( this->edge->size() < 3 ) continue;
+ float rr = fabsf(r);
+ if( rr > 1024 ) rr = 1024; // MAX
+ psf = new float[psz = rr+1];
+ draw_point_spot(r);
+//write_mask(mask, "/tmp/mask%d.pgm", k);
+ step = DO_MASK;
+ process_packages();
+//write_mask(in, "/tmp/in0%d.pgm", k);
+ step = DO_FEATHER_X;
+ process_packages();
+//write_mask(out, "/tmp/out1%d.pgm", k);
+ step = DO_FEATHER_Y;
+ process_packages();
+ step = DO_MASK_BLEND;
+ process_packages();
+ delete [] psf; psf = 0;
+//write_mask(in, "/tmp/in2%d.pgm", k);
+//printf("edge %d\n",k);
+ }
}
-// Run units
-SET_TRACE
- step = DO_APPLY;
- process_packages();
-SET_TRACE
+//write_mask(mask, "/tmp/mask.pgm");
+ step = DO_APPLY;
+ process_packages();
}
void MaskEngine::init_packages()
{
SET_TRACE
//printf("MaskEngine::init_packages 1\n");
- int x0 = 0, y0 = 0, i = 0, n = get_total_packages();
+ int x1 = 0, y1 = 0, i = 0, n = get_total_packages();
int out_w = output->get_w(), out_h = output->get_h();
SET_TRACE
while( i < n ) {
- MaskPackage *ptr = (MaskPackage*)get_package(i++);
- int x1 = (out_w * i) / n, y1 = (out_h * i) / n;
- ptr->start_x = x0; ptr->end_x = x1;
- ptr->start_y = y0; ptr->end_y = y1;
- x0 = x1; y0 = y1;
+ MaskPackage *pkg = (MaskPackage*)get_package(i++);
+ int x2 = (out_w * i) / n, y2 = (out_h * i) / n;
+ pkg->start_x = x1; pkg->end_x = x2;
+ pkg->start_y = y1; pkg->end_y = y2;
+ x1 = x2; y1 = y2;
}
SET_TRACE
//printf("MaskEngine::init_packages 2\n");
enum
{
DO_MASK,
- DO_FEATHER,
- DO_APPLY
+ DO_FEATHER_X,
+ DO_FEATHER_Y,
+ DO_MASK_BLEND,
+ DO_APPLY,
};
MaskPackage();
~MaskPackage();
- int start_x, end_x, start_y, end_y;
+ int start_x, end_x;
+ int start_y, end_y;
};
class MaskUnit : public LoadClient
MaskUnit(MaskEngine *engine);
~MaskUnit();
- void draw_line(int v, int x1, int y1, int x2, int y2);
- void draw_fill(int v);
+ void clear_mask(VFrame *msk, int a);
+ void draw_line(int x1, int y1, int x2, int y2);
+ void draw_fill();
void draw_feather(int ix1,int iy1, int ix2,int iy2);
- void draw_spot(int ix, int iy);
+ void draw_edge(int ix, int iy);
+ void draw_filled_polygon(MaskEdge &edge);
+ void feather_x(VFrame *in, VFrame *out);
+ void feather_y(VFrame *in, VFrame *out);
+ void mask_blend(VFrame *in, VFrame *mask, float r, float v);
+ void apply_mask_alpha(VFrame *output, VFrame *mask);
+
void process_package(LoadPackage *package);
MaskEngine *engine;
- int start_y, end_y;
+ MaskPackage *pkg;
int mask_model;
- float v, r;
- temp_t *spot;
+ int bc, fc;
+ int start_x, end_x;
+ int start_y, end_y;
};
class MaskEngine : public LoadServer
MaskAuto *default_auto);
int points_equivalent(MaskPoints *new_points,
MaskPoints *points);
+ void clear_mask(VFrame *msk, int a);
+ void draw_point_spot(float r);
void delete_packages();
void init_packages();
LoadPackage* new_package();
VFrame *output;
- VFrame *mask, *temp;
+ VFrame *mask, *in, *out;
MaskEdges edges;
MaskPointSets point_sets;
ArrayList<float> faders;
ArrayList<float> feathers;
int step, total_submasks;
int recalculate;
- temp_t fade[SUBMASKS+1];
+ MaskEdge *edge;
+ float r, v;
+ float *psf;
+ int psz;
};
"#version 430\n"
"layout(location=0) out vec4 color;\n"
"uniform sampler2D tex;\n"
-// apparently, only doubles index properly in shared buffers
- "buffer buf { dvec2 points[]; };\n"
+ "const int MAX = 1024;\n"
+ "uniform float psf[MAX];\n"
+ "uniform int n;\n"
+ "uniform vec2 dxy;\n"
+ "uniform vec2 twh;\n"
+ "\n"
+ "void main() {\n"
+ " vec2 tc = gl_FragCoord.xy/textureSize(tex,0);\n"
+ " color = texture(tex, tc);\n"
+ " float c = color.r, f = c*psf[0];\n"
+ " for( int i=1; i<n; ++i ) {\n"
+ " vec2 dd = float(i)*dxy;\n"
+ " vec2 a = tc+dd, ac = min(max(vec2(0.),a), twh);\n"
+ " vec2 b = tc-dd, bc = min(max(vec2(0.),b), twh);\n"
+ " float fa = texture2D(tex, ac).r * psf[i];\n"
+ " float fb = texture2D(tex, bc).r * psf[i];\n"
+ " float m = max(fa, fb);\n"
+ " if( f < m ) f = m;\n"
+ " }\n"
+ " if( c < f ) color = vec4(f);\n"
+ "}\n";
+
+static const char *max_frag =
+ "#version 430\n"
+ "layout(location=0) out vec4 color;\n"
+ "uniform sampler2D tex;\n"
+ "uniform sampler2D tex1;\n"
"uniform float r;\n"
"uniform float v;\n"
+ "\n"
"void main() {\n"
- " vec2 tex_st = gl_FragCoord.xy/textureSize(tex,0);\n"
- " color = texture(tex, tex_st);\n"
- " if( r==0. ) return;\n"
- " float rv = r*v>0. ? 1 : -1;\n"
- " float rr = r*r, dr = 1./rr;\n"
- " float vv = v>=0 ? 1.-v : 1.+v;\n"
- " float fg = rv>=0 ? vv : 1.;\n"
- " float bg = rv>=0 ? 1. : vv;\n"
- " int len = points.length();\n"
- " float sig2 = -log(255.0);\n"
- " for( int i=0; i<len; ++i ) {\n"
- " float dx = float(points[i].x) - gl_FragCoord.x;\n"
- " float dy = float(points[i].y) - gl_FragCoord.y;\n"
- " float dd = dx*dx + dy*dy;\n"
- " if( dd >= rr ) continue;\n"
- " float ss = dd / rr;\n"
- " float d = exp(ss * sig2);\n"
- " float a = d*fg + (1.-d)*bg;\n"
- " if( rv*(color.a-a) > 0 ) color = vec4(a);\n"
- " }\n"
+ " vec2 tc = gl_FragCoord.xy/textureSize(tex,0);\n"
+ " color = texture2D(tex1, tc);\n"
+ " float c = texture2D(tex, tc).r;\n"
+ " float b = r<0 ? 1. : 0.;\n"
+ " if( c == b ) return;\n"
+ " float iv = v>=0. ? 1. : -1.;\n"
+ " float rr = r!=0. ? r : 1.;\n"
+ " float rv = rr*v>=0. ? 1. : -1.;\n"
+ " float vv = v>=0. ? 1.-v : 1.+v;\n"
+ " float fg = rv>0. ? vv : 1.;\n"
+ " float bg = rv>0. ? 1. : vv;\n"
+ " float a = c*fg + (1.-c)*bg;\n"
+ " if( iv*(color.a-a) > 0. ) color = vec4(a);\n"
"}\n";
static const char *multiply_mask4_frag =
void bind(int texture_unit);
void read_screen(int x, int y, int w, int h);
void set_output_texture();
+ void unset_output_texture();
GLuint fb, rb;
};
void fb_texture::read_screen(int x, int y, int w, int h)
{
+ bind(1);
glBindFramebuffer(GL_FRAMEBUFFER, 0);
glReadBuffer(GL_BACK);
glCopyTexSubImage2D(GL_TEXTURE_2D, 0, 0,0, x,y, w,h);
void fb_texture::set_output_texture()
{
- glFramebufferTexture(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, get_texture_id(), 0);
- GLenum dbo[1] = { GL_COLOR_ATTACHMENT0, }; // bind layout(location=0) out vec4 color;
+ GLenum at = GL_COLOR_ATTACHMENT0;
+ glFramebufferTexture(GL_FRAMEBUFFER, at, get_texture_id(), 0);
+ GLenum dbo[1] = { at, }; // bind layout(location=0) out vec4 color;
glDrawBuffers(1, dbo);
int ret = glCheckFramebufferStatus(GL_FRAMEBUFFER);
if( ret != GL_FRAMEBUFFER_COMPLETE ) {
return;
}
}
+void fb_texture::unset_output_texture()
+{
+ glDrawBuffers(0, 0);
+ int at = GL_COLOR_ATTACHMENT0;
+ glFramebufferTexture(GL_FRAMEBUFFER, at, 0, 0);
+ glBindFramebuffer(GL_FRAMEBUFFER, 0);
+ glDisable(GL_TEXTURE_2D);
+}
+
+
+class zglTessData : public ArrayList<double *>
+{
+public:
+ zglTessData() { set_array_delete(); }
+ ~zglTessData() { remove_all_objects(); }
+};
static void combineData(GLdouble coords[3],
GLdouble *vertex_data[4], GLfloat weight[4],
GLdouble **outData, void *data)
{
- ArrayList<double *> *invented = (ArrayList<double *> *)data;
+ zglTessData *invented = (zglTessData *)data;
GLdouble *vertex = new double[6];
invented->append(vertex);
vertex[0] = coords[0];
// dbug
static void zglBegin(GLenum mode) { glBegin(mode); }
static void zglEnd() { glEnd(); }
-static void zglVertex3dv(const GLdouble *v) { glVertex3dv(v); }
+static void zglVertex(const GLdouble *v) { glVertex3dv(v); }
#endif
int w = command->frame->get_w();
int h = command->frame->get_h();
MaskEdges edges;
- float faders[SUBMASKS], feathers[SUBMASKS], bg = 1;
+ float faders[SUBMASKS], feathers[SUBMASKS], cc = 1;
MaskPoints point_set[SUBMASKS];
// Draw every submask as a new polygon
int total_submasks = command->keyframe_set->total_submasks(
command->start_position_project, PLAY_FORWARD);
+ int show_mask = command->keyframe_set->track->masks;
for(int k = 0; k < total_submasks; k++) {
MaskPoints &points = point_set[k];
command->start_position_project, k, PLAY_FORWARD);
float v = fader/100.;
faders[k] = v;
- if( v < 0 && (v+=1) < bg ) bg = v;
float feather = command->keyframe_set->get_feather(
command->start_position_project, k, PLAY_FORWARD);
feathers[k] = feather;
+ MaskEdge &edge = *edges.append(new MaskEdge());
+ if( !v || !((show_mask>>k) & 1) || !points.size() ) continue;
+ edge.load(point_set[k], h);
+ if( v >= 0 ) continue;
+ float vv = 1 + v;
+ if( cc > vv ) cc = vv;
}
-// clear screen
- glDisable(GL_TEXTURE_2D);
- glClearColor(bg, bg, bg, bg);
+
+ fb_texture *mask = new fb_texture(w, h, color_model);
+ mask->set_output_texture();
+ glClearColor(cc, cc, cc, cc);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
+ mask->unset_output_texture();
- int show_mask = command->keyframe_set->track->masks;
- for(int k = 0; k < total_submasks; k++) {
- MaskEdge &edge = *edges.append(new MaskEdge());
- if( !((show_mask>>k) & 1) ) continue;
- edge.load(point_set[k], h);
- if( edge.size() > 0 ) {
-// draw polygon
- float fader = faders[k];
- float v = fader < 0 ? 1 : 1-fader;
- glColor4f(v, v, v, v);
+ unsigned int feather_shader =
+ VFrame::make_shader(0, in_vertex_frag, feather_frag, 0);
+ unsigned int max_shader =
+ VFrame::make_shader(0, in_vertex_frag, max_frag, 0);
+ if( feather_shader && max_shader ) {
+ fb_texture *in = new fb_texture(w, h, color_model);
+ fb_texture *out = new fb_texture(w, h, color_model);
+ float tw = 1./out->get_texture_w(), th = 1./out->get_texture_h();
+ float tw1 = (w-1)*tw, th1 = (h-1)*th;
+ for(int k = 0; k < total_submasks; k++) {
+ MaskEdge &edge = *edges[k];
+ if( edge.size() < 3 ) continue;
+ float r = feathers[k], v = faders[k];
+ glBindFramebuffer(GL_FRAMEBUFFER, 0);
+ glActiveTexture(GL_TEXTURE0);
+ glDisable(GL_TEXTURE_2D);
+ float b = r>=0 ? 0. : 1.;
+ float f = r>=0 ? 1. : 0.;
+ glClearColor(b, b, b, b);
+ glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
+ glColor4f(f, f, f, f);
+ glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
int display_list = glGenLists(1);
- glNewList(display_list, GL_COMPILE);
#if 0
- glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
+ glNewList(display_list, GL_COMPILE);
glBegin(GL_POLYGON);
MaskCoord *c = &edge[0];
for( int i=edge.size(); --i>=0; ++c )
glVertex2f(c->x, c->y);
glEnd();
+ glEndList();
+ glCallList(display_list);
#else
+ { zglTessData invented;
GLUtesselator *tess = gluNewTess();
- gluTessCallback(tess, GLU_TESS_VERTEX,(GLvoid (*)()) &zglVertex3dv);
+ gluTessProperty(tess, GLU_TESS_TOLERANCE, 0.5);
+ gluTessCallback(tess, GLU_TESS_VERTEX,(GLvoid (*)()) &zglVertex);
gluTessCallback(tess, GLU_TESS_BEGIN,(GLvoid (*)()) &zglBegin);
gluTessCallback(tess, GLU_TESS_END,(GLvoid (*)()) &zglEnd);
gluTessCallback(tess, GLU_TESS_COMBINE_DATA,(GLvoid (*)()) &combineData);
- ArrayList<double *> invented;
- invented.set_array_delete();
-
- gluTessBeginPolygon(tess, &invented);
+ glNewList(display_list, GL_COMPILE);
+ gluTessBeginPolygon(tess, &invented);
gluTessBeginContour(tess);
MaskCoord *c = &edge[0];
for( int i=edge.size(); --i>=0; ++c )
gluTessVertex(tess, (GLdouble *)c, c);
gluTessEndContour(tess);
- gluTessEndPolygon(tess);
- gluDeleteTess(tess);
- invented.remove_all_objects();
-#endif
+ gluTessEndPolygon(tess);
glEndList();
glCallList(display_list);
+ gluDeleteTess(tess); }
+#endif
glDeleteLists(1, display_list);
- }
- }
-
-// in/out textures
- fb_texture *in = new fb_texture(w, h, color_model);
- in->bind(0);
- in->read_screen(0,0, w,h);
- fb_texture *out = new fb_texture(w, h, color_model);
-
- unsigned int frag_shader =
- VFrame::make_shader(0, in_vertex_frag, feather_frag, 0);
- if( frag_shader > 0 ) {
- GLuint points[1];
- glGenBuffers(1, points);
- for(int k = 0; k < total_submasks; k++) {
- MaskEdge &edge = *edges[k];
- if( !edge.size() ) continue;
- if( !faders[k] ) continue;
- if( !feathers[k] ) continue;
- MaskSpots spots;
- for( int i=0; i<edge.size(); ++i ) {
- MaskCoord &a = edge[i];
- MaskCoord &b = i<edge.size()-1 ? edge[i+1] : edge[0];
- draw_spots(spots, a.x,a.y+h, b.x,b.y+h);
+ in->read_screen(0,0, w,h);
+//in->write_tex("/tmp/in0.ppm");
+ if( r ) {
+ double sig2 = -log(255.0)/(r*r);
+ int n = abs((int)r) + 1;
+ if( n > 1024 ) n = 1024; // MAX
+ float psf[n]; // point spot fn
+ for( int i=0; i<n; ++i )
+ psf[i] = exp(i*i * sig2);
+ glUseProgram(feather_shader);
+ glUniform1fv(glGetUniformLocation(feather_shader, "psf"), n, psf);
+ glUniform1i(glGetUniformLocation(feather_shader, "n"), n);
+ glUniform2f(glGetUniformLocation(feather_shader, "dxy"), tw, 0.);
+ glUniform2f(glGetUniformLocation(feather_shader, "twh"), tw1, th1);
+ glUniform1i(glGetUniformLocation(feather_shader, "tex"), 0);
+ in->bind(0);
+ out->set_output_texture();
+ out->draw_texture(0,0, w,h, 0,0, w,h);
+ out->unset_output_texture();
+//out->write_tex("/tmp/out1.ppm");
+ fb_texture *t = in; in = out; out = t;
+ glUniform2f(glGetUniformLocation(feather_shader, "dxy"), 0., th);
+ in->bind(0);
+ out->set_output_texture();
+ out->draw_texture(0,0, w,h, 0,0, w,h);
+ out->unset_output_texture();
+//out->write_tex("/tmp/out2.ppm");
+ glUseProgram(0);
+ t = in; in = out; out = t;
}
- int sz = spots.size() * sizeof(MaskSpot);
- glBindBufferRange(GL_SHADER_STORAGE_BUFFER, 0, points[0], 0, sz);
- glBufferData(GL_SHADER_STORAGE_BUFFER, sz, &spots[0], GL_DYNAMIC_COPY);
- glBindBuffer(GL_SHADER_STORAGE_BUFFER, 0);
- glUseProgram(frag_shader);
- float r = feathers[k], v = faders[k];
- glUniform1f(glGetUniformLocation(frag_shader, "r"), r);
- glUniform1f(glGetUniformLocation(frag_shader, "v"), v);
+
+ glUseProgram(max_shader);
in->bind(0);
- glUniform1i(glGetUniformLocation(frag_shader, "tex"), 0);
- out->set_output_texture();
+//in->write_tex("/tmp/in1.ppm");
+//mask->write_tex("/tmp/mask1.ppm");
+ mask->bind(1);
+ glUniform1i(glGetUniformLocation(max_shader, "tex"), 0);
+ glUniform1i(glGetUniformLocation(max_shader, "tex1"), 1);
+ glUniform1f(glGetUniformLocation(max_shader, "r"), r);
+ glUniform1f(glGetUniformLocation(max_shader, "v"), v);
glViewport(0,0, w,h);
+ out->set_output_texture();
out->draw_texture(0,0, w,h, 0,0, w,h);
+ out->unset_output_texture();
glUseProgram(0);
- fb_texture *t = in; in = out; out = t;
+ fb_texture *t = mask; mask = out; out = t;
+//mask->write_tex("/tmp/mask2.ppm");
}
- glDeleteBuffers(1, points);
+ delete in;
+ delete out;
}
- glDrawBuffers(0, 0);
- glBindFramebuffer(GL_FRAMEBUFFER, 0);
-
const char *alpha_shader = BC_CModels::has_alpha(color_model) ?
multiply_mask4_frag :
!BC_CModels::is_yuv(color_model) ?
glUseProgram(shader);
if( shader > 0 ) {
command->frame->bind_texture(0);
- in->BC_Texture::bind(1);
+ mask->BC_Texture::bind(1);
glUniform1i(glGetUniformLocation(shader, "tex"), 0);
glUniform1i(glGetUniformLocation(shader, "tex1"), 1);
}
command->frame->draw_texture();
command->frame->set_opengl_state(VFrame::SCREEN);
glUseProgram(0);
- delete in;
- delete out;
-// Default drawable
- glDisable(GL_TEXTURE_2D);
+ delete mask;
glColor4f(1, 1, 1, 1);
glActiveTexture(GL_TEXTURE0);
+ glDisable(GL_TEXTURE_2D);
window->enable_opengl();
}
command->canvas->unlock_canvas();
[ . ])
PKG_3RD([ffmpeg],[yes],
- [ffmpeg-4.1.4],
+ [ffmpeg-4.2],
[ libavutil/libavutil.a \
libavcodec/libavcodec.a \
libpostproc/libpostproc.a \
#framepack ###Input/output error
framerate
framestep step=30
+#freezedetect
fspp
gblur
#geq ###Invalid argument
#showfreqs ###Input/output error
#showinfo ###not part of frame data
showpalette s=30
+#showspatial
#showspectrum s=1280x480:scale=log ###Input/output error
#showspectrumpic ###Input/output error
#showvolume r=30 ###Input/output error
testsrc2 duration=5.3:size=qcif:rate=10
#threshold ###Input/output error
#thumbnail n=50
+#thumbnail_cuda
tile layout=3x2:nb_frames=5:padding=7:margin=2
tinterlace
transpose
waveform
weave
xbr
+#xmedian
yadif
yuvtestsrc
zoompan
ciescope
crossfeed
deflicker
+#derain
despill
doubleweave
floodfill
GLuint id, GLenum severity, GLsizei length, const GLchar* message,
const void* userParam)
{
+ if( type == GL_DEBUG_TYPE_OTHER &&
+ severity == GL_DEBUG_SEVERITY_NOTIFICATION ) return;
fprintf(stderr, "GL CALLBACK: %s type = 0x%x, severity = 0x%x, message = %s\n",
( type == GL_DEBUG_TYPE_ERROR ? "** GL ERROR **" : "" ),
type, severity, message );
+++ /dev/null
-diff -urN a/fftools/cmdutils.c b/fftools/cmdutils.c
---- a/fftools/cmdutils.c 2018-10-01 10:52:48.866784675 -0600
-+++ b/fftools/cmdutils.c 2018-10-01 10:52:55.550799827 -0600
-@@ -1179,6 +1179,7 @@
-
- void show_banner(int argc, char **argv, const OptionDef *options)
- {
-+ return;
- int idx = locate_option(argc, argv, options, "version");
- if (hide_banner || idx)
- return;
+++ /dev/null
-diff -urN a/libavformat/bluray.c b/libavformat/bluray.c
---- a/libavformat/bluray.c 2018-04-13 17:34:28.000000000 -0600
-+++ b/libavformat/bluray.c 2018-04-24 11:02:19.724232178 -0600
-@@ -28,7 +28,7 @@
- #include "libavutil/opt.h"
-
- #define BLURAY_PROTO_PREFIX "bluray:"
--#define MIN_PLAYLIST_LENGTH 180 /* 3 min */
-+#define MIN_PLAYLIST_LENGTH 0
-
- typedef struct {
- const AVClass *class;
+++ /dev/null
-diff -urN a/libavformat/mpegtsenc.c b/libavformat/mpegtsenc.c
---- a/libavformat/mpegtsenc.c 2018-04-20 04:02:57.000000000 -0600
-+++ b/libavformat/mpegtsenc.c 2018-04-24 10:27:57.193689213 -0600
-@@ -56,9 +56,8 @@
- int sid; /* service ID */
- char *name;
- char *provider_name;
-- int pcr_pid;
-- int pcr_packet_count;
-- int pcr_packet_period;
-+ int64_t pcr, pcr_packet_timer, pcr_packet_period;
-+ int pcr_sid, pcr_pid;
- AVProgram *program;
- } MpegTSService;
-
-@@ -78,14 +77,12 @@
- MpegTSSection pat; /* MPEG-2 PAT table */
- MpegTSSection sdt; /* MPEG-2 SDT table context */
- MpegTSService **services;
-- int sdt_packet_count;
-- int sdt_packet_period;
-- int pat_packet_count;
-- int pat_packet_period;
-+ int64_t sdt_packet_timer, sdt_packet_period;
-+ int64_t pat_packet_timer, pat_packet_period;
- int nb_services;
- int onid;
- int tsid;
-- int64_t first_pcr;
-+ int64_t pcr, first_pcr, delay;
- int mux_rate; ///< set to 1 when VBR
- int pes_payload_size;
-
-@@ -95,12 +92,14 @@
- int service_type;
-
- int pmt_start_pid;
-+ int pcr_start_pid;
- int start_pid;
- int m2ts_mode;
-+ int64_t ts_offset;
-
- int reemit_pat_pmt; // backward compatibility
-
-- int pcr_period;
-+ double pcr_period;
- #define MPEGTS_FLAG_REEMIT_PAT_PMT 0x01
- #define MPEGTS_FLAG_AAC_LATM 0x02
- #define MPEGTS_FLAG_PAT_PMT_AT_FRAMES 0x04
-@@ -111,8 +110,6 @@
- int tables_version;
- double pat_period;
- double sdt_period;
-- int64_t last_pat_ts;
-- int64_t last_sdt_ts;
-
- int omit_video_pes_length;
- } MpegTSWrite;
-@@ -222,10 +219,10 @@
- #define DEFAULT_PROVIDER_NAME "FFmpeg"
- #define DEFAULT_SERVICE_NAME "Service01"
-
--/* we retransmit the SI info at this rate */
-+/* we retransmit the SI info at this rate (ms) */
- #define SDT_RETRANS_TIME 500
- #define PAT_RETRANS_TIME 100
--#define PCR_RETRANS_TIME 20
-+#define PCR_RETRANS_TIME 50
-
- typedef struct MpegTSWriteStream {
- struct MpegTSService *service;
-@@ -721,6 +718,7 @@
- service->pmt.pid = ts->pmt_start_pid + ts->nb_services;
- service->sid = sid;
- service->pcr_pid = 0x1fff;
-+ service->pcr_sid = 0x1fff;
- service->provider_name = av_strdup(provider_name);
- service->name = av_strdup(name);
- if (!service->provider_name || !service->name)
-@@ -736,18 +734,11 @@
- return NULL;
- }
-
--static int64_t get_pcr(const MpegTSWrite *ts, AVIOContext *pb)
--{
-- return av_rescale(avio_tell(pb) + 11, 8 * PCR_TIME_BASE, ts->mux_rate) +
-- ts->first_pcr;
--}
--
- static void mpegts_prefix_m2ts_header(AVFormatContext *s)
- {
- MpegTSWrite *ts = s->priv_data;
- if (ts->m2ts_mode) {
-- int64_t pcr = get_pcr(s->priv_data, s->pb);
-- uint32_t tp_extra_header = pcr % 0x3fffffff;
-+ uint32_t tp_extra_header = ts->pcr % 0x3fffffff;
- tp_extra_header = AV_RB32(&tp_extra_header);
- avio_write(s->pb, (unsigned char *) &tp_extra_header,
- sizeof(tp_extra_header));
-@@ -768,6 +759,7 @@
- MpegTSService *service;
- AVStream *st, *pcr_st = NULL;
- AVDictionaryEntry *title, *provider;
-+ double clk_rate;
- int i, j;
- const char *service_name;
- const char *provider_name;
-@@ -776,6 +768,15 @@
-
- if (s->max_delay < 0) /* Not set by the caller */
- s->max_delay = 0;
-+ ts->delay = av_rescale(s->max_delay, 90000, AV_TIME_BASE);
-+
-+ if (ts->m2ts_mode == -1) {
-+ if (av_match_ext(s->url, "m2ts")) {
-+ ts->m2ts_mode = 1;
-+ } else {
-+ ts->m2ts_mode = 0;
-+ }
-+ }
-
- // round up to a whole number of TS packets
- ts->pes_payload_size = (ts->pes_payload_size + 14 + 183) / 184 * 184 - 14;
-@@ -822,6 +823,8 @@
- service->program = program;
- }
- }
-+ if (ts->m2ts_mode > 1)
-+ service->pmt.pid = 0x00ff + ts->service_id;
-
- ts->pat.pid = PAT_PID;
- /* Initialize at 15 so that it wraps and is equal to 0 for the
-@@ -907,10 +910,9 @@
- ts_st->discontinuity = ts->flags & MPEGTS_FLAG_DISCONT;
- /* update PCR pid by using the first video stream */
- if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO &&
-- service->pcr_pid == 0x1fff) {
-- service->pcr_pid = ts_st->pid;
-+ service->pcr_sid == 0x1fff)
- pcr_st = st;
-- }
-+
- if (st->codecpar->codec_id == AV_CODEC_ID_AAC &&
- st->codecpar->extradata_size > 0) {
- AVStream *ast;
-@@ -946,78 +948,47 @@
- av_freep(&pids);
-
- /* if no video stream, use the first stream as PCR */
-- if (service->pcr_pid == 0x1fff && s->nb_streams > 0) {
-- pcr_st = s->streams[0];
-- ts_st = pcr_st->priv_data;
-- service->pcr_pid = ts_st->pid;
-- } else
-- ts_st = pcr_st->priv_data;
--
-- if (ts->mux_rate > 1) {
-- service->pcr_packet_period = (int64_t)ts->mux_rate * ts->pcr_period /
-- (TS_PACKET_SIZE * 8 * 1000);
-- ts->sdt_packet_period = (int64_t)ts->mux_rate * SDT_RETRANS_TIME /
-- (TS_PACKET_SIZE * 8 * 1000);
-- ts->pat_packet_period = (int64_t)ts->mux_rate * PAT_RETRANS_TIME /
-- (TS_PACKET_SIZE * 8 * 1000);
--
-- if (ts->copyts < 1)
-- ts->first_pcr = av_rescale(s->max_delay, PCR_TIME_BASE, AV_TIME_BASE);
-- } else {
-- /* Arbitrary values, PAT/PMT will also be written on video key frames */
-- ts->sdt_packet_period = 200;
-- ts->pat_packet_period = 40;
-- if (pcr_st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) {
-- int frame_size = av_get_audio_frame_duration2(pcr_st->codecpar, 0);
-- if (!frame_size) {
-- av_log(s, AV_LOG_WARNING, "frame size not set\n");
-- service->pcr_packet_period =
-- pcr_st->codecpar->sample_rate / (10 * 512);
-- } else {
-- 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->pcr = 0;
-+ service->pcr_packet_timer = 0;
-+ ts->pat_packet_timer = 0;
-+ ts->sdt_packet_timer = 0;
-
- if (ts->mux_rate == 1)
- av_log(s, AV_LOG_VERBOSE, "muxrate VBR, ");
- else
- av_log(s, AV_LOG_VERBOSE, "muxrate %d, ", ts->mux_rate);
-- av_log(s, AV_LOG_VERBOSE,
-- "pcr every %d pkts, sdt every %d, pat/pmt every %d pkts\n",
-- service->pcr_packet_period,
-- ts->sdt_packet_period, ts->pat_packet_period);
--
-- if (ts->m2ts_mode == -1) {
-- if (av_match_ext(s->url, "m2ts")) {
-- ts->m2ts_mode = 1;
-- } else {
-- ts->m2ts_mode = 0;
-- }
-- }
-
- return 0;
-
-@@ -1032,22 +1003,12 @@
- MpegTSWrite *ts = s->priv_data;
- int i;
-
-- if (++ts->sdt_packet_count == ts->sdt_packet_period ||
-- (dts != AV_NOPTS_VALUE && ts->last_sdt_ts == AV_NOPTS_VALUE) ||
-- (dts != AV_NOPTS_VALUE && dts - ts->last_sdt_ts >= ts->sdt_period*90000.0)
-- ) {
-- ts->sdt_packet_count = 0;
-- if (dts != AV_NOPTS_VALUE)
-- ts->last_sdt_ts = FFMAX(dts, ts->last_sdt_ts);
-+ if ( ts->sdt_packet_period >= 0 && ts->pcr >= ts->sdt_packet_timer ) {
-+ ts->sdt_packet_timer = ts->pcr + ts->sdt_packet_period;
- mpegts_write_sdt(s);
- }
-- if (++ts->pat_packet_count == ts->pat_packet_period ||
-- (dts != AV_NOPTS_VALUE && ts->last_pat_ts == AV_NOPTS_VALUE) ||
-- (dts != AV_NOPTS_VALUE && dts - ts->last_pat_ts >= ts->pat_period*90000.0) ||
-- force_pat) {
-- ts->pat_packet_count = 0;
-- if (dts != AV_NOPTS_VALUE)
-- ts->last_pat_ts = FFMAX(dts, ts->last_pat_ts);
-+ if (ts->pcr >= ts->pat_packet_timer || force_pat) {
-+ ts->pat_packet_timer = ts->pcr + ts->pat_packet_period;
- mpegts_write_pat(s);
- for (i = 0; i < ts->nb_services; i++)
- mpegts_write_pmt(s, ts->services[i]);
-@@ -1089,13 +1050,14 @@
- {
- MpegTSWrite *ts = s->priv_data;
- MpegTSWriteStream *ts_st = st->priv_data;
-+ uint32_t pcr_pid = ts_st->service->pcr_pid;
- uint8_t *q;
- uint8_t buf[TS_PACKET_SIZE];
-
- q = buf;
- *q++ = 0x47;
-- *q++ = ts_st->pid >> 8;
-- *q++ = ts_st->pid;
-+ *q++ = pcr_pid >> 8;
-+ *q++ = pcr_pid;
- *q++ = 0x20 | ts_st->cc; /* Adaptation only */
- /* Continuity Count field does not increment (see 13818-1 section 2.4.3.3) */
- *q++ = TS_PACKET_SIZE - 5; /* Adaptation Field Length */
-@@ -1106,7 +1068,7 @@
- }
-
- /* PCR coded into 6 bytes */
-- q += write_pcr_bits(q, get_pcr(ts, s->pb));
-+ q += write_pcr_bits(q, ts->pcr);
-
- /* stuffing bytes */
- memset(q, 0xFF, TS_PACKET_SIZE - (q - buf));
-@@ -1175,8 +1137,6 @@
- uint8_t *q;
- int val, is_start, len, header_len, write_pcr, is_dvb_subtitle, is_dvb_teletext, flags;
- int afc_len, stuffing_len;
-- int64_t pcr = -1; /* avoid warning */
-- int64_t delay = av_rescale(s->max_delay, 90000, AV_TIME_BASE);
- int force_pat = st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO && key && !ts_st->prev_payload_key;
-
- av_assert0(ts_st->payload != buf || st->codecpar->codec_type != AVMEDIA_TYPE_VIDEO);
-@@ -1186,28 +1146,33 @@
-
- is_start = 1;
- while (payload_size > 0) {
-+ ts->pcr = ts->first_pcr + (ts->mux_rate == 1 ?
-+ (dts == AV_NOPTS_VALUE ? 0 : (dts - ts->delay) * 300) :
-+ // add 11, pcr references the last byte of program clock reference base
-+ av_rescale(avio_tell(s->pb) + 11, 8 * PCR_TIME_BASE, ts->mux_rate));
-+
- retransmit_si_info(s, force_pat, dts);
- force_pat = 0;
-
- write_pcr = 0;
-- if (ts_st->pid == ts_st->service->pcr_pid) {
-- if (ts->mux_rate > 1 || is_start) // VBR pcr period is based on frames
-- ts_st->service->pcr_packet_count++;
-- if (ts_st->service->pcr_packet_count >=
-- ts_st->service->pcr_packet_period) {
-- ts_st->service->pcr_packet_count = 0;
-+ if (ts_st->pid == ts_st->service->pcr_sid) {
-+ if( ts->pcr >= ts_st->service->pcr_packet_timer ) {
-+ ts_st->service->pcr_packet_timer = ts->pcr + ts_st->service->pcr_packet_period;
- write_pcr = 1;
- }
- }
--
-+ if (write_pcr && ts_st->service->pcr_sid != ts_st->service->pcr_pid) {
-+ mpegts_insert_pcr_only(s, st);
-+ continue;
-+ }
- if (ts->mux_rate > 1 && dts != AV_NOPTS_VALUE &&
-- (dts - get_pcr(ts, s->pb) / 300) > delay) {
-- /* pcr insert gets priority over null packet insert */
-- if (write_pcr)
-- mpegts_insert_pcr_only(s, st);
-+ (dts - ts->pcr / 300) > ts->delay) {
-+ /* pcr insert gets priority over null packet insert */
-+ if (write_pcr)
-+ mpegts_insert_pcr_only(s, st);
- else
-- mpegts_insert_null_packet(s);
-- /* recalculate write_pcr and possibly retransmit si_info */
-+ mpegts_insert_null_packet(s);
-+ /* recalculate write_pcr and possibly retransimit si_info */
- continue;
- }
-
-@@ -1217,6 +1182,10 @@
- val = ts_st->pid >> 8;
- if (is_start)
- val |= 0x40;
-+ if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO &&
-+ st->codecpar->codec_id == AV_CODEC_ID_AC3 &&
-+ ts->m2ts_mode > 1)
-+ val |= 0x20;
- *q++ = val;
- *q++ = ts_st->pid;
- ts_st->cc = ts_st->cc + 1 & 0xf;
-@@ -1228,7 +1197,7 @@
- }
- if (key && is_start && pts != AV_NOPTS_VALUE) {
- // set Random Access for key frames
-- if (ts_st->pid == ts_st->service->pcr_pid)
-+ if (ts_st->pid == ts_st->service->pcr_sid)
- write_pcr = 1;
- set_af_flag(buf, 0x40);
- q = get_ts_payload_start(buf);
-@@ -1236,14 +1205,10 @@
- if (write_pcr) {
- set_af_flag(buf, 0x10);
- q = get_ts_payload_start(buf);
-- // add 11, pcr references the last byte of program clock reference base
- if (ts->mux_rate > 1)
-- pcr = get_pcr(ts, s->pb);
-- else
-- pcr = (dts - delay) * 300;
-- if (dts != AV_NOPTS_VALUE && dts < pcr / 300)
-+ if (dts != AV_NOPTS_VALUE && dts < ts->pcr / 300)
- av_log(s, AV_LOG_WARNING, "dts < pcr, TS is invalid\n");
-- extend_af(buf, write_pcr_bits(q, pcr));
-+ extend_af(buf, write_pcr_bits(q, ts->pcr));
- q = get_ts_payload_start(buf);
- }
- if (is_start) {
-@@ -1344,11 +1309,13 @@
- *q++ = flags;
- *q++ = header_len;
- if (pts != AV_NOPTS_VALUE) {
-- write_pts(q, flags >> 6, pts);
-+ int64_t ts_pts = pts + ts->ts_offset;
-+ write_pts(q, flags >> 6, ts_pts);
- q += 5;
- }
- if (dts != AV_NOPTS_VALUE && pts != AV_NOPTS_VALUE && dts != pts) {
-- write_pts(q, 1, dts);
-+ int64_t ts_dts = dts + ts->ts_offset;
-+ write_pts(q, 1, ts_dts);
- q += 5;
- }
- if (pes_extension && st->codecpar->codec_id == AV_CODEC_ID_DIRAC) {
-@@ -1519,7 +1486,6 @@
- uint8_t *data = NULL;
- MpegTSWrite *ts = s->priv_data;
- MpegTSWriteStream *ts_st = st->priv_data;
-- const int64_t delay = av_rescale(s->max_delay, 90000, AV_TIME_BASE) * 2;
- int64_t dts = pkt->dts, pts = pkt->pts;
- int opus_samples = 0;
- int side_data_size;
-@@ -1540,16 +1506,15 @@
- }
-
- if (ts->flags & MPEGTS_FLAG_REEMIT_PAT_PMT) {
-- ts->pat_packet_count = ts->pat_packet_period - 1;
-- ts->sdt_packet_count = ts->sdt_packet_period - 1;
-+ ts->pat_packet_timer = ts->sdt_packet_timer = 0;
- ts->flags &= ~MPEGTS_FLAG_REEMIT_PAT_PMT;
- }
-
- if (ts->copyts < 1) {
- if (pts != AV_NOPTS_VALUE)
-- pts += delay;
-+ pts += 2*ts->delay;
- if (dts != AV_NOPTS_VALUE)
-- dts += delay;
-+ dts += 2*ts->delay;
- }
-
- if (ts_st->first_pts_check && pts == AV_NOPTS_VALUE) {
-@@ -1737,7 +1702,7 @@
- AVStream *st2 = s->streams[i];
- MpegTSWriteStream *ts_st2 = st2->priv_data;
- if ( ts_st2->payload_size
-- && (ts_st2->payload_dts == AV_NOPTS_VALUE || dts - ts_st2->payload_dts > delay/2)) {
-+ && (ts_st2->payload_dts == AV_NOPTS_VALUE || dts - ts_st2->payload_dts > ts->delay)) {
- mpegts_write_pes(s, st2, ts_st2->payload, ts_st2->payload_size,
- ts_st2->payload_pts, ts_st2->payload_dts,
- ts_st2->payload_flags & AV_PKT_FLAG_KEY, stream_id);
-@@ -1908,12 +1873,18 @@
- { "mpegts_pmt_start_pid", "Set the first pid of the PMT.",
- offsetof(MpegTSWrite, pmt_start_pid), AV_OPT_TYPE_INT,
- { .i64 = 0x1000 }, 0x0010, 0x1f00, AV_OPT_FLAG_ENCODING_PARAM },
-+ { "mpegts_pcr_start_pid", "Set the first pid of the PCR.",
-+ offsetof(MpegTSWrite, pcr_start_pid), AV_OPT_TYPE_INT,
-+ { .i64 = 0x1000 }, 0x0010, 0x1f00, AV_OPT_FLAG_ENCODING_PARAM },
- { "mpegts_start_pid", "Set the first pid.",
- offsetof(MpegTSWrite, start_pid), AV_OPT_TYPE_INT,
- { .i64 = 0x0100 }, 0x0010, 0x0f00, AV_OPT_FLAG_ENCODING_PARAM },
- { "mpegts_m2ts_mode", "Enable m2ts mode.",
- offsetof(MpegTSWrite, m2ts_mode), AV_OPT_TYPE_BOOL,
-- { .i64 = -1 }, -1, 1, AV_OPT_FLAG_ENCODING_PARAM },
-+ { .i64 = -1 }, -1, 2, AV_OPT_FLAG_ENCODING_PARAM },
-+ { "mpegts_pcr_offset", "clock offset.",
-+ offsetof(MpegTSWrite, ts_offset), AV_OPT_TYPE_BOOL,
-+ { .i64 = 0 }, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM },
- { "muxrate", NULL,
- offsetof(MpegTSWrite, mux_rate), AV_OPT_TYPE_INT,
- { .i64 = 1 }, 0, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM },
-@@ -1951,15 +1922,15 @@
- { "omit_video_pes_length", "Omit the PES packet length for video packets",
- offsetof(MpegTSWrite, omit_video_pes_length), AV_OPT_TYPE_BOOL,
- { .i64 = 1 }, 0, 1, AV_OPT_FLAG_ENCODING_PARAM },
-- { "pcr_period", "PCR retransmission time in milliseconds",
-- offsetof(MpegTSWrite, pcr_period), AV_OPT_TYPE_INT,
-- { .i64 = PCR_RETRANS_TIME }, 0, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM },
-- { "pat_period", "PAT/PMT retransmission time limit in seconds",
-+ { "pcr_period", "PCR retransmission time limit in msecs",
-+ offsetof(MpegTSWrite, pcr_period), AV_OPT_TYPE_DOUBLE,
-+ { .dbl = PCR_RETRANS_TIME }, 0, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM },
-+ { "pat_period", "PAT/PMT retransmission time limit in msecs",
- offsetof(MpegTSWrite, pat_period), AV_OPT_TYPE_DOUBLE,
-- { .dbl = INT_MAX }, 0, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM },
-- { "sdt_period", "SDT retransmission time limit in seconds",
-+ { .dbl = PAT_RETRANS_TIME }, 0, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM },
-+ { "sdt_period", "SDT retransmission time limit in msecs",
- offsetof(MpegTSWrite, sdt_period), AV_OPT_TYPE_DOUBLE,
-- { .dbl = INT_MAX }, 0, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM },
-+ { .dbl = SDT_RETRANS_TIME }, -1, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM },
- { NULL },
- };
-
+++ /dev/null
-diff -urN a/libavformat/avformat.h b/libavformat/avformat.h
---- a/libavformat/avformat.h 2018-11-05 16:22:26.000000000 -0700
-+++ b/libavformat/avformat.h 2018-11-08 07:25:17.066799941 -0700
-@@ -487,6 +487,9 @@
- The user or muxer can override this through
- AVFormatContext.avoid_negative_ts
- */
-+#define AVFMT_SEEK_NOSTREAMS 0x80000 /**< Stream index ignored by seek,
-+ or some streams fail to seek
-+ */
-
- #define AVFMT_SEEK_TO_PTS 0x4000000 /**< Seeking is based on PTS */
-
-@@ -647,7 +650,8 @@
- /**
- * Can use flags: AVFMT_NOFILE, AVFMT_NEEDNUMBER, AVFMT_SHOW_IDS,
- * AVFMT_GENERIC_INDEX, AVFMT_TS_DISCONT, AVFMT_NOBINSEARCH,
-- * AVFMT_NOGENSEARCH, AVFMT_NO_BYTE_SEEK, AVFMT_SEEK_TO_PTS.
-+ * AVFMT_NOGENSEARCH, AVFMT_NO_BYTE_SEEK, AVFMT_SEEK_TO_PTS,
-+ * AVFMT_SEEK_NOSTREAMS
- */
- int flags;
-
-diff -urN a/libavformat/dv.c b/libavformat/dv.c
---- a/libavformat/dv.c 2018-11-01 12:34:26.000000000 -0600
-+++ b/libavformat/dv.c 2018-11-08 07:25:17.066799941 -0700
-@@ -632,6 +632,7 @@
- AVInputFormat ff_dv_demuxer = {
- .name = "dv",
- .long_name = NULL_IF_CONFIG_SMALL("DV (Digital Video)"),
-+ .flags = AVFMT_SEEK_NOSTREAMS,
- .priv_data_size = sizeof(RawDVContext),
- .read_probe = dv_probe,
- .read_header = dv_read_header,
-diff -urN a/libavformat/matroskadec.c b/libavformat/matroskadec.c
---- a/libavformat/matroskadec.c 2018-11-05 16:22:26.000000000 -0700
-+++ b/libavformat/matroskadec.c 2018-11-08 07:25:17.067799930 -0700
-@@ -4030,6 +4030,7 @@
- AVInputFormat ff_matroska_demuxer = {
- .name = "matroska,webm",
- .long_name = NULL_IF_CONFIG_SMALL("Matroska / WebM"),
-+ .flags = AVFMT_SEEK_NOSTREAMS,
- .extensions = "mkv,mk3d,mka,mks",
- .priv_data_size = sizeof(MatroskaDemuxContext),
- .read_probe = matroska_probe,
-@@ -4043,6 +4044,7 @@
- AVInputFormat ff_webm_dash_manifest_demuxer = {
- .name = "webm_dash_manifest",
- .long_name = NULL_IF_CONFIG_SMALL("WebM DASH Manifest"),
-+ .flags = AVFMT_SEEK_NOSTREAMS,
- .priv_data_size = sizeof(MatroskaDemuxContext),
- .read_header = webm_dash_manifest_read_header,
- .read_packet = webm_dash_manifest_read_packet,
-diff -urN a/libavformat/utils.c b/libavformat/utils.c
---- a/libavformat/utils.c 2018-11-05 16:22:26.000000000 -0700
-+++ b/libavformat/utils.c 2018-11-08 07:25:17.069799908 -0700
-@@ -2472,6 +2472,13 @@
- return seek_frame_byte(s, stream_index, timestamp, flags);
- }
-
-+ if (stream_index != -1 && (s->iformat->flags & AVFMT_SEEK_NOSTREAMS)) {
-+ timestamp = av_rescale_q(timestamp,
-+ s->streams[stream_index]->time_base,
-+ AV_TIME_BASE_Q);
-+ stream_index = -1;
-+ }
-+
- if (stream_index < 0) {
- stream_index = av_find_default_stream_index(s);
- if (stream_index < 0)
+++ /dev/null
---- a/libavfilter/af_aformat.c 2018-07-17 03:27:41.000000000 -0600
-+++ b/libavfilter/af_aformat.c 2019-03-16 17:55:28.449442750 -0600
-@@ -109,6 +109,16 @@
- return 0;
- }
-
-+#define DEL_FIELD(p,mem,fld) if( p->mem ) { av_freep(&p->mem->fld); av_freep(&p->mem); }
-+
-+static av_cold void uninit(AVFilterContext *ctx)
-+{
-+ AFormatContext *s = ctx->priv;
-+ DEL_FIELD(s, formats, formats);
-+ DEL_FIELD(s, sample_rates, formats);
-+ DEL_FIELD(s, channel_layouts, channel_layouts);
-+}
-+
- static int query_formats(AVFilterContext *ctx)
- {
- AFormatContext *s = ctx->priv;
-@@ -146,6 +156,7 @@
- .name = "aformat",
- .description = NULL_IF_CONFIG_SMALL("Convert the input audio to one of the specified formats."),
- .init = init,
-+ .uninit = uninit,
- .query_formats = query_formats,
- .priv_size = sizeof(AFormatContext),
- .priv_class = &aformat_class,
+++ /dev/null
-diff -u a/libavfilter/formats.c b/libavfilter/formats.c
---- a/libavfilter/formats.c 2018-11-02 18:17:29.000000000 -0600
-+++ b/libavfilter/formats.c 2019-04-09 14:12:01.659501027 -0600
-@@ -107,11 +107,13 @@
- possibly causing a lossy conversion elsewhere in the graph.
- To avoid that, pretend that there are no common formats to force the
- insertion of a conversion filter. */
-- if (type == AVMEDIA_TYPE_VIDEO)
-- for (i = 0; i < a->nb_formats; i++)
-+ if (type == AVMEDIA_TYPE_VIDEO) {
-+ for (i = 0; i < a->nb_formats; i++) {
-+ const AVPixFmtDescriptor *adesc = av_pix_fmt_desc_get(a->formats[i]);
-+ if( !adesc ) continue;
- for (j = 0; j < b->nb_formats; j++) {
-- const AVPixFmtDescriptor *adesc = av_pix_fmt_desc_get(a->formats[i]);
- const AVPixFmtDescriptor *bdesc = av_pix_fmt_desc_get(b->formats[j]);
-+ if( !bdesc ) continue;
- alpha2 |= adesc->flags & bdesc->flags & AV_PIX_FMT_FLAG_ALPHA;
- chroma2|= adesc->nb_components > 1 && bdesc->nb_components > 1;
- if (a->formats[i] == b->formats[j]) {
-@@ -119,6 +121,8 @@
- chroma1|= adesc->nb_components > 1;
- }
- }
-+ }
-+ }
-
- // If chroma or alpha can be lost through merging then do not merge
- if (alpha2 > alpha1 || chroma2 > chroma1)
+++ /dev/null
-diff -u a/libavcodec/vdpau_mpeg12.c b/libavcodec/vdpau_mpeg12.c
---- a/libavcodec/vdpau_mpeg12.c 2018-11-02 18:17:29.000000000 -0600
-+++ b/libavcodec/vdpau_mpeg12.c 2019-04-22 10:28:41.762275864 -0600
-@@ -114,6 +114,7 @@
- .frame_priv_data_size = sizeof(struct vdpau_picture_context),
- .init = vdpau_mpeg1_init,
- .uninit = ff_vdpau_common_uninit,
-+ .frame_params = ff_vdpau_common_frame_params,
- .priv_data_size = sizeof(VDPAUContext),
- .caps_internal = HWACCEL_CAP_ASYNC_SAFE,
- };
+++ /dev/null
-diff -urN a/libavcodec/h263dec.c b/libavcodec/h263dec.c
---- a/libavcodec/h263dec.c
-+++ b/libavcodec/h263dec.c
-@@ -684,7 +684,7 @@ frame_end:
- if (CONFIG_MPEG4_DECODER && avctx->codec_id == AV_CODEC_ID_MPEG4)
- ff_mpeg4_frame_end(avctx, buf, buf_size);
-
-- if (!s->divx_packed && avctx->hwaccel)
-+ if (s->divx_packed && avctx->hwaccel)
- ff_thread_finish_setup(avctx);
-
- av_assert1(s->current_picture.f->pict_type == s->current_picture_ptr->f->pict_type);
--- /dev/null
+diff -ru a/fftools/cmdutils.c b/fftools/cmdutils.c
+--- a/fftools/cmdutils.c 2019-07-08 11:45:25.000000000 -0600
++++ b/fftools/cmdutils.c 2019-08-08 17:19:36.357374727 -0600
+@@ -1179,6 +1179,7 @@
+
+ void show_banner(int argc, char **argv, const OptionDef *options)
+ {
++ return;
+ int idx = locate_option(argc, argv, options, "version");
+ if (hide_banner || idx)
+ return;
--- /dev/null
+diff -ru a/libavformat/bluray.c b/libavformat/bluray.c
+--- a/libavformat/bluray.c 2019-07-08 11:45:25.000000000 -0600
++++ b/libavformat/bluray.c 2019-08-08 17:20:07.011299703 -0600
+@@ -28,7 +28,7 @@
+ #include "libavutil/opt.h"
+
+ #define BLURAY_PROTO_PREFIX "bluray:"
+-#define MIN_PLAYLIST_LENGTH 180 /* 3 min */
++#define MIN_PLAYLIST_LENGTH 0
+
+ typedef struct {
+ const AVClass *class;
--- /dev/null
+diff -ru a/libavformat/mpegtsenc.c b/libavformat/mpegtsenc.c
+--- a/libavformat/mpegtsenc.c 2019-08-05 14:52:21.000000000 -0600
++++ b/libavformat/mpegtsenc.c 2019-08-08 17:22:07.392150886 -0600
+@@ -56,9 +56,8 @@
+ int sid; /* service ID */
+ uint8_t name[256];
+ uint8_t provider_name[256];
+- int pcr_pid;
+- int pcr_packet_count;
+- int pcr_packet_period;
++ int64_t pcr, pcr_packet_timer, pcr_packet_period;
++ int pcr_sid, pcr_pid;
+ AVProgram *program;
+ } MpegTSService;
+
+@@ -78,14 +77,12 @@
+ MpegTSSection pat; /* MPEG-2 PAT table */
+ MpegTSSection sdt; /* MPEG-2 SDT table context */
+ MpegTSService **services;
+- int sdt_packet_count;
+- int sdt_packet_period;
+- int pat_packet_count;
+- int pat_packet_period;
++ int64_t sdt_packet_timer, sdt_packet_period;
++ int64_t pat_packet_timer, pat_packet_period;
+ int nb_services;
+ int onid;
+ int tsid;
+- int64_t first_pcr;
++ int64_t pcr, first_pcr, delay;
+ int mux_rate; ///< set to 1 when VBR
+ int pes_payload_size;
+
+@@ -95,12 +92,14 @@
+ int service_type;
+
+ int pmt_start_pid;
++ int pcr_start_pid;
+ int start_pid;
+ int m2ts_mode;
++ int64_t ts_offset;
+
+ int reemit_pat_pmt; // backward compatibility
+
+- int pcr_period;
++ double pcr_period;
+ #define MPEGTS_FLAG_REEMIT_PAT_PMT 0x01
+ #define MPEGTS_FLAG_AAC_LATM 0x02
+ #define MPEGTS_FLAG_PAT_PMT_AT_FRAMES 0x04
+@@ -111,8 +110,6 @@
+ int tables_version;
+ double pat_period;
+ double sdt_period;
+- int64_t last_pat_ts;
+- int64_t last_sdt_ts;
+
+ int omit_video_pes_length;
+ } MpegTSWrite;
+@@ -222,10 +219,10 @@
+ #define DEFAULT_PROVIDER_NAME "FFmpeg"
+ #define DEFAULT_SERVICE_NAME "Service01"
+
+-/* we retransmit the SI info at this rate */
++/* we retransmit the SI info at this rate (ms) */
+ #define SDT_RETRANS_TIME 500
+ #define PAT_RETRANS_TIME 100
+-#define PCR_RETRANS_TIME 20
++#define PCR_RETRANS_TIME 50
+
+ typedef struct MpegTSWriteStream {
+ struct MpegTSService *service;
+@@ -730,6 +727,7 @@
+ service->pmt.pid = ts->pmt_start_pid + ts->nb_services;
+ service->sid = sid;
+ service->pcr_pid = 0x1fff;
++ service->pcr_sid = 0x1fff;
+ if (encode_str8(service->provider_name, provider_name) < 0 ||
+ encode_str8(service->name, name) < 0) {
+ av_log(s, AV_LOG_ERROR, "Too long service or provider name\n");
+@@ -744,18 +742,11 @@
+ return NULL;
+ }
+
+-static int64_t get_pcr(const MpegTSWrite *ts, AVIOContext *pb)
+-{
+- return av_rescale(avio_tell(pb) + 11, 8 * PCR_TIME_BASE, ts->mux_rate) +
+- ts->first_pcr;
+-}
+-
+ static void mpegts_prefix_m2ts_header(AVFormatContext *s)
+ {
+ MpegTSWrite *ts = s->priv_data;
+ if (ts->m2ts_mode) {
+- int64_t pcr = get_pcr(s->priv_data, s->pb);
+- uint32_t tp_extra_header = pcr % 0x3fffffff;
++ uint32_t tp_extra_header = ts->pcr % 0x3fffffff;
+ tp_extra_header = AV_RB32(&tp_extra_header);
+ avio_write(s->pb, (unsigned char *) &tp_extra_header,
+ sizeof(tp_extra_header));
+@@ -776,6 +767,7 @@
+ MpegTSService *service;
+ AVStream *st, *pcr_st = NULL;
+ AVDictionaryEntry *title, *provider;
++ double clk_rate;
+ int i, j;
+ const char *service_name;
+ const char *provider_name;
+@@ -784,6 +776,15 @@
+
+ if (s->max_delay < 0) /* Not set by the caller */
+ s->max_delay = 0;
++ ts->delay = av_rescale(s->max_delay, 90000, AV_TIME_BASE);
++
++ if (ts->m2ts_mode == -1) {
++ if (av_match_ext(s->url, "m2ts")) {
++ ts->m2ts_mode = 1;
++ } else {
++ ts->m2ts_mode = 0;
++ }
++ }
+
+ // round up to a whole number of TS packets
+ ts->pes_payload_size = (ts->pes_payload_size + 14 + 183) / 184 * 184 - 14;
+@@ -830,6 +831,8 @@
+ service->program = program;
+ }
+ }
++ if (ts->m2ts_mode > 1)
++ service->pmt.pid = 0x00ff + ts->service_id;
+
+ ts->pat.pid = PAT_PID;
+ /* Initialize at 15 so that it wraps and is equal to 0 for the
+@@ -915,10 +918,9 @@
+ ts_st->discontinuity = ts->flags & MPEGTS_FLAG_DISCONT;
+ /* update PCR pid by using the first video stream */
+ if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO &&
+- service->pcr_pid == 0x1fff) {
+- service->pcr_pid = ts_st->pid;
++ service->pcr_sid == 0x1fff)
+ pcr_st = st;
+- }
++
+ if (st->codecpar->codec_id == AV_CODEC_ID_AAC &&
+ st->codecpar->extradata_size > 0) {
+ AVStream *ast;
+@@ -954,78 +956,47 @@
+ av_freep(&pids);
+
+ /* if no video stream, use the first stream as PCR */
+- if (service->pcr_pid == 0x1fff && s->nb_streams > 0) {
+- pcr_st = s->streams[0];
+- ts_st = pcr_st->priv_data;
+- service->pcr_pid = ts_st->pid;
+- } else
+- ts_st = pcr_st->priv_data;
+-
+- if (ts->mux_rate > 1) {
+- service->pcr_packet_period = (int64_t)ts->mux_rate * ts->pcr_period /
+- (TS_PACKET_SIZE * 8 * 1000);
+- ts->sdt_packet_period = (int64_t)ts->mux_rate * SDT_RETRANS_TIME /
+- (TS_PACKET_SIZE * 8 * 1000);
+- ts->pat_packet_period = (int64_t)ts->mux_rate * PAT_RETRANS_TIME /
+- (TS_PACKET_SIZE * 8 * 1000);
+-
+- if (ts->copyts < 1)
+- ts->first_pcr = av_rescale(s->max_delay, PCR_TIME_BASE, AV_TIME_BASE);
+- } else {
+- /* Arbitrary values, PAT/PMT will also be written on video key frames */
+- ts->sdt_packet_period = 200;
+- ts->pat_packet_period = 40;
+- if (pcr_st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) {
+- int frame_size = av_get_audio_frame_duration2(pcr_st->codecpar, 0);
+- if (!frame_size) {
+- av_log(s, AV_LOG_WARNING, "frame size not set\n");
+- service->pcr_packet_period =
+- pcr_st->codecpar->sample_rate / (10 * 512);
+- } else {
+- 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->pcr = 0;
++ service->pcr_packet_timer = 0;
++ ts->pat_packet_timer = 0;
++ ts->sdt_packet_timer = 0;
+
+ if (ts->mux_rate == 1)
+ av_log(s, AV_LOG_VERBOSE, "muxrate VBR, ");
+ else
+ av_log(s, AV_LOG_VERBOSE, "muxrate %d, ", ts->mux_rate);
+- av_log(s, AV_LOG_VERBOSE,
+- "pcr every %d pkts, sdt every %d, pat/pmt every %d pkts\n",
+- service->pcr_packet_period,
+- ts->sdt_packet_period, ts->pat_packet_period);
+-
+- if (ts->m2ts_mode == -1) {
+- if (av_match_ext(s->url, "m2ts")) {
+- ts->m2ts_mode = 1;
+- } else {
+- ts->m2ts_mode = 0;
+- }
+- }
+
+ return 0;
+
+@@ -1040,22 +1011,12 @@
+ MpegTSWrite *ts = s->priv_data;
+ int i;
+
+- if (++ts->sdt_packet_count == ts->sdt_packet_period ||
+- (dts != AV_NOPTS_VALUE && ts->last_sdt_ts == AV_NOPTS_VALUE) ||
+- (dts != AV_NOPTS_VALUE && dts - ts->last_sdt_ts >= ts->sdt_period*90000.0)
+- ) {
+- ts->sdt_packet_count = 0;
+- if (dts != AV_NOPTS_VALUE)
+- ts->last_sdt_ts = FFMAX(dts, ts->last_sdt_ts);
++ if ( ts->sdt_packet_period >= 0 && ts->pcr >= ts->sdt_packet_timer ) {
++ ts->sdt_packet_timer = ts->pcr + ts->sdt_packet_period;
+ mpegts_write_sdt(s);
+ }
+- if (++ts->pat_packet_count == ts->pat_packet_period ||
+- (dts != AV_NOPTS_VALUE && ts->last_pat_ts == AV_NOPTS_VALUE) ||
+- (dts != AV_NOPTS_VALUE && dts - ts->last_pat_ts >= ts->pat_period*90000.0) ||
+- force_pat) {
+- ts->pat_packet_count = 0;
+- if (dts != AV_NOPTS_VALUE)
+- ts->last_pat_ts = FFMAX(dts, ts->last_pat_ts);
++ if (ts->pcr >= ts->pat_packet_timer || force_pat) {
++ ts->pat_packet_timer = ts->pcr + ts->pat_packet_period;
+ mpegts_write_pat(s);
+ for (i = 0; i < ts->nb_services; i++)
+ mpegts_write_pmt(s, ts->services[i]);
+@@ -1097,13 +1058,14 @@
+ {
+ MpegTSWrite *ts = s->priv_data;
+ MpegTSWriteStream *ts_st = st->priv_data;
++ uint32_t pcr_pid = ts_st->service->pcr_pid;
+ uint8_t *q;
+ uint8_t buf[TS_PACKET_SIZE];
+
+ q = buf;
+ *q++ = 0x47;
+- *q++ = ts_st->pid >> 8;
+- *q++ = ts_st->pid;
++ *q++ = pcr_pid >> 8;
++ *q++ = pcr_pid;
+ *q++ = 0x20 | ts_st->cc; /* Adaptation only */
+ /* Continuity Count field does not increment (see 13818-1 section 2.4.3.3) */
+ *q++ = TS_PACKET_SIZE - 5; /* Adaptation Field Length */
+@@ -1114,7 +1076,7 @@
+ }
+
+ /* PCR coded into 6 bytes */
+- q += write_pcr_bits(q, get_pcr(ts, s->pb));
++ q += write_pcr_bits(q, ts->pcr);
+
+ /* stuffing bytes */
+ memset(q, 0xFF, TS_PACKET_SIZE - (q - buf));
+@@ -1183,8 +1145,6 @@
+ uint8_t *q;
+ int val, is_start, len, header_len, write_pcr, is_dvb_subtitle, is_dvb_teletext, flags;
+ int afc_len, stuffing_len;
+- int64_t pcr = -1; /* avoid warning */
+- int64_t delay = av_rescale(s->max_delay, 90000, AV_TIME_BASE);
+ int force_pat = st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO && key && !ts_st->prev_payload_key;
+
+ av_assert0(ts_st->payload != buf || st->codecpar->codec_type != AVMEDIA_TYPE_VIDEO);
+@@ -1194,28 +1154,33 @@
+
+ is_start = 1;
+ while (payload_size > 0) {
++ ts->pcr = ts->first_pcr + (ts->mux_rate == 1 ?
++ (dts == AV_NOPTS_VALUE ? 0 : (dts - ts->delay) * 300) :
++ // add 11, pcr references the last byte of program clock reference base
++ av_rescale(avio_tell(s->pb) + 11, 8 * PCR_TIME_BASE, ts->mux_rate));
++
+ retransmit_si_info(s, force_pat, dts);
+ force_pat = 0;
+
+ write_pcr = 0;
+- if (ts_st->pid == ts_st->service->pcr_pid) {
+- if (ts->mux_rate > 1 || is_start) // VBR pcr period is based on frames
+- ts_st->service->pcr_packet_count++;
+- if (ts_st->service->pcr_packet_count >=
+- ts_st->service->pcr_packet_period) {
+- ts_st->service->pcr_packet_count = 0;
++ if (ts_st->pid == ts_st->service->pcr_sid) {
++ if( ts->pcr >= ts_st->service->pcr_packet_timer ) {
++ ts_st->service->pcr_packet_timer = ts->pcr + ts_st->service->pcr_packet_period;
+ write_pcr = 1;
+ }
+ }
+-
++ if (write_pcr && ts_st->service->pcr_sid != ts_st->service->pcr_pid) {
++ mpegts_insert_pcr_only(s, st);
++ continue;
++ }
+ if (ts->mux_rate > 1 && dts != AV_NOPTS_VALUE &&
+- (dts - get_pcr(ts, s->pb) / 300) > delay) {
+- /* pcr insert gets priority over null packet insert */
+- if (write_pcr)
+- mpegts_insert_pcr_only(s, st);
++ (dts - ts->pcr / 300) > ts->delay) {
++ /* pcr insert gets priority over null packet insert */
++ if (write_pcr)
++ mpegts_insert_pcr_only(s, st);
+ else
+- mpegts_insert_null_packet(s);
+- /* recalculate write_pcr and possibly retransmit si_info */
++ mpegts_insert_null_packet(s);
++ /* recalculate write_pcr and possibly retransimit si_info */
+ continue;
+ }
+
+@@ -1225,6 +1190,10 @@
+ val = ts_st->pid >> 8;
+ if (is_start)
+ val |= 0x40;
++ if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO &&
++ st->codecpar->codec_id == AV_CODEC_ID_AC3 &&
++ ts->m2ts_mode > 1)
++ val |= 0x20;
+ *q++ = val;
+ *q++ = ts_st->pid;
+ ts_st->cc = ts_st->cc + 1 & 0xf;
+@@ -1236,7 +1205,7 @@
+ }
+ if (key && is_start && pts != AV_NOPTS_VALUE) {
+ // set Random Access for key frames
+- if (ts_st->pid == ts_st->service->pcr_pid)
++ if (ts_st->pid == ts_st->service->pcr_sid)
+ write_pcr = 1;
+ set_af_flag(buf, 0x40);
+ q = get_ts_payload_start(buf);
+@@ -1244,14 +1213,10 @@
+ if (write_pcr) {
+ set_af_flag(buf, 0x10);
+ q = get_ts_payload_start(buf);
+- // add 11, pcr references the last byte of program clock reference base
+ if (ts->mux_rate > 1)
+- pcr = get_pcr(ts, s->pb);
+- else
+- pcr = (dts - delay) * 300;
+- if (dts != AV_NOPTS_VALUE && dts < pcr / 300)
++ if (dts != AV_NOPTS_VALUE && dts < ts->pcr / 300)
+ av_log(s, AV_LOG_WARNING, "dts < pcr, TS is invalid\n");
+- extend_af(buf, write_pcr_bits(q, pcr));
++ extend_af(buf, write_pcr_bits(q, ts->pcr));
+ q = get_ts_payload_start(buf);
+ }
+ if (is_start) {
+@@ -1352,11 +1317,13 @@
+ *q++ = flags;
+ *q++ = header_len;
+ if (pts != AV_NOPTS_VALUE) {
+- write_pts(q, flags >> 6, pts);
++ int64_t ts_pts = pts + ts->ts_offset;
++ write_pts(q, flags >> 6, ts_pts);
+ q += 5;
+ }
+ if (dts != AV_NOPTS_VALUE && pts != AV_NOPTS_VALUE && dts != pts) {
+- write_pts(q, 1, dts);
++ int64_t ts_dts = dts + ts->ts_offset;
++ write_pts(q, 1, ts_dts);
+ q += 5;
+ }
+ if (pes_extension && st->codecpar->codec_id == AV_CODEC_ID_DIRAC) {
+@@ -1527,7 +1494,6 @@
+ uint8_t *data = NULL;
+ MpegTSWrite *ts = s->priv_data;
+ MpegTSWriteStream *ts_st = st->priv_data;
+- const int64_t delay = av_rescale(s->max_delay, 90000, AV_TIME_BASE) * 2;
+ int64_t dts = pkt->dts, pts = pkt->pts;
+ int opus_samples = 0;
+ int side_data_size;
+@@ -1548,16 +1514,15 @@
+ }
+
+ if (ts->flags & MPEGTS_FLAG_REEMIT_PAT_PMT) {
+- ts->pat_packet_count = ts->pat_packet_period - 1;
+- ts->sdt_packet_count = ts->sdt_packet_period - 1;
++ ts->pat_packet_timer = ts->sdt_packet_timer = 0;
+ ts->flags &= ~MPEGTS_FLAG_REEMIT_PAT_PMT;
+ }
+
+ if (ts->copyts < 1) {
+ if (pts != AV_NOPTS_VALUE)
+- pts += delay;
++ pts += 2*ts->delay;
+ if (dts != AV_NOPTS_VALUE)
+- dts += delay;
++ dts += 2*ts->delay;
+ }
+
+ if (ts_st->first_pts_check && pts == AV_NOPTS_VALUE) {
+@@ -1745,7 +1710,7 @@
+ AVStream *st2 = s->streams[i];
+ MpegTSWriteStream *ts_st2 = st2->priv_data;
+ if ( ts_st2->payload_size
+- && (ts_st2->payload_dts == AV_NOPTS_VALUE || dts - ts_st2->payload_dts > delay/2)) {
++ && (ts_st2->payload_dts == AV_NOPTS_VALUE || dts - ts_st2->payload_dts > ts->delay)) {
+ mpegts_write_pes(s, st2, ts_st2->payload, ts_st2->payload_size,
+ ts_st2->payload_pts, ts_st2->payload_dts,
+ ts_st2->payload_flags & AV_PKT_FLAG_KEY, stream_id);
+@@ -1914,12 +1879,18 @@
+ { "mpegts_pmt_start_pid", "Set the first pid of the PMT.",
+ offsetof(MpegTSWrite, pmt_start_pid), AV_OPT_TYPE_INT,
+ { .i64 = 0x1000 }, 0x0010, 0x1f00, AV_OPT_FLAG_ENCODING_PARAM },
++ { "mpegts_pcr_start_pid", "Set the first pid of the PCR.",
++ offsetof(MpegTSWrite, pcr_start_pid), AV_OPT_TYPE_INT,
++ { .i64 = 0x1000 }, 0x0010, 0x1f00, AV_OPT_FLAG_ENCODING_PARAM },
+ { "mpegts_start_pid", "Set the first pid.",
+ offsetof(MpegTSWrite, start_pid), AV_OPT_TYPE_INT,
+ { .i64 = 0x0100 }, 0x0010, 0x0f00, AV_OPT_FLAG_ENCODING_PARAM },
+ { "mpegts_m2ts_mode", "Enable m2ts mode.",
+ offsetof(MpegTSWrite, m2ts_mode), AV_OPT_TYPE_BOOL,
+- { .i64 = -1 }, -1, 1, AV_OPT_FLAG_ENCODING_PARAM },
++ { .i64 = -1 }, -1, 2, AV_OPT_FLAG_ENCODING_PARAM },
++ { "mpegts_pcr_offset", "clock offset.",
++ offsetof(MpegTSWrite, ts_offset), AV_OPT_TYPE_BOOL,
++ { .i64 = 0 }, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM },
+ { "muxrate", NULL,
+ offsetof(MpegTSWrite, mux_rate), AV_OPT_TYPE_INT,
+ { .i64 = 1 }, 0, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM },
+@@ -1957,15 +1928,15 @@
+ { "omit_video_pes_length", "Omit the PES packet length for video packets",
+ offsetof(MpegTSWrite, omit_video_pes_length), AV_OPT_TYPE_BOOL,
+ { .i64 = 1 }, 0, 1, AV_OPT_FLAG_ENCODING_PARAM },
+- { "pcr_period", "PCR retransmission time in milliseconds",
+- offsetof(MpegTSWrite, pcr_period), AV_OPT_TYPE_INT,
+- { .i64 = PCR_RETRANS_TIME }, 0, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM },
+- { "pat_period", "PAT/PMT retransmission time limit in seconds",
++ { "pcr_period", "PCR retransmission time limit in msecs",
++ offsetof(MpegTSWrite, pcr_period), AV_OPT_TYPE_DOUBLE,
++ { .dbl = PCR_RETRANS_TIME }, 0, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM },
++ { "pat_period", "PAT/PMT retransmission time limit in msecs",
+ offsetof(MpegTSWrite, pat_period), AV_OPT_TYPE_DOUBLE,
+- { .dbl = INT_MAX }, 0, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM },
+- { "sdt_period", "SDT retransmission time limit in seconds",
++ { .dbl = PAT_RETRANS_TIME }, 0, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM },
++ { "sdt_period", "SDT retransmission time limit in msecs",
+ offsetof(MpegTSWrite, sdt_period), AV_OPT_TYPE_DOUBLE,
+- { .dbl = INT_MAX }, 0, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM },
++ { .dbl = SDT_RETRANS_TIME }, -1, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM },
+ { NULL },
+ };
+
--- /dev/null
+diff -ru a/libavformat/avformat.h b/libavformat/avformat.h
+--- a/libavformat/avformat.h 2019-08-05 14:52:21.000000000 -0600
++++ b/libavformat/avformat.h 2019-08-08 17:26:45.869297510 -0600
+@@ -485,6 +485,9 @@
+ The user or muxer can override this through
+ AVFormatContext.avoid_negative_ts
+ */
++#define AVFMT_SEEK_NOSTREAMS 0x80000 /**< Stream index ignored by seek,
++ or some streams fail to seek
++ */
+
+ #define AVFMT_SEEK_TO_PTS 0x4000000 /**< Seeking is based on PTS */
+
+@@ -654,7 +657,8 @@
+ /**
+ * Can use flags: AVFMT_NOFILE, AVFMT_NEEDNUMBER, AVFMT_SHOW_IDS,
+ * AVFMT_NOTIMESTAMPS, AVFMT_GENERIC_INDEX, AVFMT_TS_DISCONT, AVFMT_NOBINSEARCH,
+- * AVFMT_NOGENSEARCH, AVFMT_NO_BYTE_SEEK, AVFMT_SEEK_TO_PTS.
++ * AVFMT_NOGENSEARCH, AVFMT_NO_BYTE_SEEK, AVFMT_SEEK_TO_PTS,
++ * AVFMT_SEEK_NOSTREAMS
+ */
+ int flags;
+
+Only in b/libavformat: avformat.h.orig
+Only in b/libavformat: avformat.h.rej
+diff -ru a/libavformat/dv.c b/libavformat/dv.c
+--- a/libavformat/dv.c 2019-08-05 14:52:21.000000000 -0600
++++ b/libavformat/dv.c 2019-08-08 17:23:57.558692650 -0600
+@@ -632,6 +632,7 @@
+ AVInputFormat ff_dv_demuxer = {
+ .name = "dv",
+ .long_name = NULL_IF_CONFIG_SMALL("DV (Digital Video)"),
++ .flags = AVFMT_SEEK_NOSTREAMS,
+ .priv_data_size = sizeof(RawDVContext),
+ .read_probe = dv_probe,
+ .read_header = dv_read_header,
+diff -ru a/libavformat/matroskadec.c b/libavformat/matroskadec.c
+--- a/libavformat/matroskadec.c 2019-08-05 14:52:21.000000000 -0600
++++ b/libavformat/matroskadec.c 2019-08-08 17:23:57.559692582 -0600
+@@ -4229,6 +4229,7 @@
+ AVInputFormat ff_matroska_demuxer = {
+ .name = "matroska,webm",
+ .long_name = NULL_IF_CONFIG_SMALL("Matroska / WebM"),
++ .flags = AVFMT_SEEK_NOSTREAMS,
+ .extensions = "mkv,mk3d,mka,mks",
+ .priv_data_size = sizeof(MatroskaDemuxContext),
+ .read_probe = matroska_probe,
+@@ -4242,6 +4243,7 @@
+ AVInputFormat ff_webm_dash_manifest_demuxer = {
+ .name = "webm_dash_manifest",
+ .long_name = NULL_IF_CONFIG_SMALL("WebM DASH Manifest"),
++ .flags = AVFMT_SEEK_NOSTREAMS,
+ .priv_data_size = sizeof(MatroskaDemuxContext),
+ .read_header = webm_dash_manifest_read_header,
+ .read_packet = webm_dash_manifest_read_packet,
+Only in b/libavformat: matroskadec.c.orig
+diff -ru a/libavformat/utils.c b/libavformat/utils.c
+--- a/libavformat/utils.c 2019-08-05 14:52:21.000000000 -0600
++++ b/libavformat/utils.c 2019-08-08 17:23:57.560692514 -0600
+@@ -2472,6 +2472,13 @@
+ return seek_frame_byte(s, stream_index, timestamp, flags);
+ }
+
++ if (stream_index != -1 && (s->iformat->flags & AVFMT_SEEK_NOSTREAMS)) {
++ timestamp = av_rescale_q(timestamp,
++ s->streams[stream_index]->time_base,
++ AV_TIME_BASE_Q);
++ stream_index = -1;
++ }
++
+ if (stream_index < 0) {
+ stream_index = av_find_default_stream_index(s);
+ if (stream_index < 0)
--- /dev/null
+diff -ru a/libavfilter/af_aformat.c b/libavfilter/af_aformat.c
+--- a/libavfilter/af_aformat.c 2018-07-17 03:27:41.000000000 -0600
++++ b/libavfilter/af_aformat.c 2019-08-08 18:20:22.150540943 -0600
+@@ -109,6 +109,16 @@
+ return 0;
+ }
+
++#define DEL_FIELD(p,mem,fld) if( p->mem ) { av_freep(&p->mem->fld); av_freep(&p->mem); }
++
++static av_cold void uninit(AVFilterContext *ctx)
++{
++ AFormatContext *s = ctx->priv;
++ DEL_FIELD(s, formats, formats);
++ DEL_FIELD(s, sample_rates, formats);
++ DEL_FIELD(s, channel_layouts, channel_layouts);
++}
++
+ static int query_formats(AVFilterContext *ctx)
+ {
+ AFormatContext *s = ctx->priv;
+@@ -146,6 +156,7 @@
+ .name = "aformat",
+ .description = NULL_IF_CONFIG_SMALL("Convert the input audio to one of the specified formats."),
+ .init = init,
++ .uninit = uninit,
+ .query_formats = query_formats,
+ .priv_size = sizeof(AFormatContext),
+ .priv_class = &aformat_class,
--- /dev/null
+diff -ru a/libavfilter/formats.c b/libavfilter/formats.c
+--- a/libavfilter/formats.c 2019-07-08 11:45:25.000000000 -0600
++++ b/libavfilter/formats.c 2019-08-08 18:20:27.709164671 -0600
+@@ -107,11 +107,13 @@
+ possibly causing a lossy conversion elsewhere in the graph.
+ To avoid that, pretend that there are no common formats to force the
+ insertion of a conversion filter. */
+- if (type == AVMEDIA_TYPE_VIDEO)
+- for (i = 0; i < a->nb_formats; i++)
++ if (type == AVMEDIA_TYPE_VIDEO) {
++ for (i = 0; i < a->nb_formats; i++) {
++ const AVPixFmtDescriptor *adesc = av_pix_fmt_desc_get(a->formats[i]);
++ if( !adesc ) continue;
+ for (j = 0; j < b->nb_formats; j++) {
+- const AVPixFmtDescriptor *adesc = av_pix_fmt_desc_get(a->formats[i]);
+ const AVPixFmtDescriptor *bdesc = av_pix_fmt_desc_get(b->formats[j]);
++ if( !bdesc ) continue;
+ alpha2 |= adesc->flags & bdesc->flags & AV_PIX_FMT_FLAG_ALPHA;
+ chroma2|= adesc->nb_components > 1 && bdesc->nb_components > 1;
+ if (a->formats[i] == b->formats[j]) {
+@@ -119,6 +121,8 @@
+ chroma1|= adesc->nb_components > 1;
+ }
+ }
++ }
++ }
+
+ // If chroma or alpha can be lost through merging then do not merge
+ if (alpha2 > alpha1 || chroma2 > chroma1)
--- /dev/null
+diff -ru a/libavcodec/vdpau_mpeg12.c b/libavcodec/vdpau_mpeg12.c
+--- a/libavcodec/vdpau_mpeg12.c 2019-07-08 11:45:25.000000000 -0600
++++ b/libavcodec/vdpau_mpeg12.c 2019-08-08 18:20:33.488773439 -0600
+@@ -114,6 +114,7 @@
+ .frame_priv_data_size = sizeof(struct vdpau_picture_context),
+ .init = vdpau_mpeg1_init,
+ .uninit = ff_vdpau_common_uninit,
++ .frame_params = ff_vdpau_common_frame_params,
+ .priv_data_size = sizeof(VDPAUContext),
+ .caps_internal = HWACCEL_CAP_ASYNC_SAFE,
+ };
--- /dev/null
+diff -ru a/libavcodec/h263dec.c b/libavcodec/h263dec.c
+--- a/libavcodec/h263dec.c 2019-08-05 14:52:21.000000000 -0600
++++ b/libavcodec/h263dec.c 2019-08-08 18:20:39.255383087 -0600
+@@ -684,7 +684,7 @@
+ if (CONFIG_MPEG4_DECODER && avctx->codec_id == AV_CODEC_ID_MPEG4)
+ ff_mpeg4_frame_end(avctx, buf, buf_size);
+
+- if (!s->divx_packed && avctx->hwaccel)
++ if (s->divx_packed && avctx->hwaccel)
+ ff_thread_finish_setup(avctx);
+
+ av_assert1(s->current_picture.f->pict_type == s->current_picture_ptr->f->pict_type);