+ return 1;
+ }else{
+ av_init_packet(out);
+ return 0;
+ }
+}
+
+/**
+ * Interleaves a AVPacket correctly so it can be muxed.
+ * @param out the interleaved packet will be output here
+ * @param in the input packet
+ * @param flush 1 if no further packets are available as input and all
+ * remaining packets should be output
+ * @return 1 if a packet was output, 0 if no packet could be output,
+ * < 0 if an error occured
+ */
+static int av_interleave_packet(AVFormatContext *s, AVPacket *out, AVPacket *in, int flush){
+ if(s->oformat->interleave_packet)
+ return s->oformat->interleave_packet(s, out, in, flush);
+ else
+ return av_interleave_packet_per_dts(s, out, in, flush);
+}
+
+/**
+ * Writes a packet to an output media file ensuring correct interleaving.
+ *
+ * The packet must contain one audio or video frame.
+ * If the packets are already correctly interleaved the application should
+ * call av_write_frame() instead as its slightly faster, its also important
+ * to keep in mind that completly non interleaved input will need huge amounts
+ * of memory to interleave with this, so its prefereable to interleave at the
+ * demuxer level
+ *
+ * @param s media file handle
+ * @param pkt the packet, which contains the stream_index, buf/buf_size, dts/pts, ...
+ * @return < 0 if error, = 0 if OK, 1 if end of stream wanted.
+ */
+int av_interleaved_write_frame(AVFormatContext *s, AVPacket *pkt){
+ AVStream *st= s->streams[ pkt->stream_index];
+
+ //FIXME/XXX/HACK drop zero sized packets
+ if(st->codec->codec_type == CODEC_TYPE_AUDIO && pkt->size==0)
+ return 0;
+
+//av_log(NULL, AV_LOG_DEBUG, "av_interleaved_write_frame %d %Ld %Ld\n", pkt->size, pkt->dts, pkt->pts);
+ if(compute_pkt_fields2(st, pkt) < 0)
+ return -1;
+
+ if(pkt->dts == AV_NOPTS_VALUE)
+ return -1;
+
+ for(;;){
+ AVPacket opkt;
+ int ret= av_interleave_packet(s, &opkt, pkt, 0);
+ if(ret<=0) //FIXME cleanup needed for ret<0 ?
+ return ret;
+
+ truncate_ts(s->streams[opkt.stream_index], &opkt);
+ ret= s->oformat->write_packet(s, &opkt);
+
+ av_free_packet(&opkt);
+ pkt= NULL;
+